2 * Materialize v0.98.0 (http://materializecss.com)
3 * Copyright 2014-2015 Materialize
4 * MIT License (https://raw.githubusercontent.com/Dogfalo/materialize/master/LICENSE)
7 if (typeof(jQuery) === 'undefined') {
9 // Check if require is a defined function.
10 if (typeof(require) === 'function') {
11 jQuery = $ = require('jquery');
12 // Else use the dollar sign alias.
18 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
20 * Uses the built in easing capabilities added In jQuery 1.1
21 * to offer multiple easing options
23 * TERMS OF USE - jQuery Easing
25 * Open source under the BSD License.
27 * Copyright © 2008 George McGinley Smith
28 * All rights reserved.
30 * Redistribution and use in source and binary forms, with or without modification,
31 * are permitted provided that the following conditions are met:
33 * Redistributions of source code must retain the above copyright notice, this list of
34 * conditions and the following disclaimer.
35 * Redistributions in binary form must reproduce the above copyright notice, this list
36 * of conditions and the following disclaimer in the documentation and/or other materials
37 * provided with the distribution.
39 * Neither the name of the author nor the names of contributors may be used to endorse
40 * or promote products derived from this software without specific prior written permission.
42 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
43 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
44 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
45 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
46 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
47 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
48 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
49 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
54 // t: current time, b: begInnIng value, c: change In value, d: duration
55 jQuery.easing['jswing'] = jQuery.easing['swing'];
57 jQuery.extend( jQuery.easing,
60 swing: function (x, t, b, c, d) {
61 //alert(jQuery.easing.default);
62 return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
64 easeInQuad: function (x, t, b, c, d) {
65 return c*(t/=d)*t + b;
67 easeOutQuad: function (x, t, b, c, d) {
68 return -c *(t/=d)*(t-2) + b;
70 easeInOutQuad: function (x, t, b, c, d) {
71 if ((t/=d/2) < 1) return c/2*t*t + b;
72 return -c/2 * ((--t)*(t-2) - 1) + b;
74 easeInCubic: function (x, t, b, c, d) {
75 return c*(t/=d)*t*t + b;
77 easeOutCubic: function (x, t, b, c, d) {
78 return c*((t=t/d-1)*t*t + 1) + b;
80 easeInOutCubic: function (x, t, b, c, d) {
81 if ((t/=d/2) < 1) return c/2*t*t*t + b;
82 return c/2*((t-=2)*t*t + 2) + b;
84 easeInQuart: function (x, t, b, c, d) {
85 return c*(t/=d)*t*t*t + b;
87 easeOutQuart: function (x, t, b, c, d) {
88 return -c * ((t=t/d-1)*t*t*t - 1) + b;
90 easeInOutQuart: function (x, t, b, c, d) {
91 if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
92 return -c/2 * ((t-=2)*t*t*t - 2) + b;
94 easeInQuint: function (x, t, b, c, d) {
95 return c*(t/=d)*t*t*t*t + b;
97 easeOutQuint: function (x, t, b, c, d) {
98 return c*((t=t/d-1)*t*t*t*t + 1) + b;
100 easeInOutQuint: function (x, t, b, c, d) {
101 if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
102 return c/2*((t-=2)*t*t*t*t + 2) + b;
104 easeInSine: function (x, t, b, c, d) {
105 return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
107 easeOutSine: function (x, t, b, c, d) {
108 return c * Math.sin(t/d * (Math.PI/2)) + b;
110 easeInOutSine: function (x, t, b, c, d) {
111 return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
113 easeInExpo: function (x, t, b, c, d) {
114 return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
116 easeOutExpo: function (x, t, b, c, d) {
117 return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
119 easeInOutExpo: function (x, t, b, c, d) {
121 if (t==d) return b+c;
122 if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
123 return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
125 easeInCirc: function (x, t, b, c, d) {
126 return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
128 easeOutCirc: function (x, t, b, c, d) {
129 return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
131 easeInOutCirc: function (x, t, b, c, d) {
132 if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
133 return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
135 easeInElastic: function (x, t, b, c, d) {
136 var s=1.70158;var p=0;var a=c;
137 if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
138 if (a < Math.abs(c)) { a=c; var s=p/4; }
139 else var s = p/(2*Math.PI) * Math.asin (c/a);
140 return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
142 easeOutElastic: function (x, t, b, c, d) {
143 var s=1.70158;var p=0;var a=c;
144 if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
145 if (a < Math.abs(c)) { a=c; var s=p/4; }
146 else var s = p/(2*Math.PI) * Math.asin (c/a);
147 return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
149 easeInOutElastic: function (x, t, b, c, d) {
150 var s=1.70158;var p=0;var a=c;
151 if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
152 if (a < Math.abs(c)) { a=c; var s=p/4; }
153 else var s = p/(2*Math.PI) * Math.asin (c/a);
154 if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
155 return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
157 easeInBack: function (x, t, b, c, d, s) {
158 if (s == undefined) s = 1.70158;
159 return c*(t/=d)*t*((s+1)*t - s) + b;
161 easeOutBack: function (x, t, b, c, d, s) {
162 if (s == undefined) s = 1.70158;
163 return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
165 easeInOutBack: function (x, t, b, c, d, s) {
166 if (s == undefined) s = 1.70158;
167 if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
168 return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
170 easeInBounce: function (x, t, b, c, d) {
171 return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
173 easeOutBounce: function (x, t, b, c, d) {
174 if ((t/=d) < (1/2.75)) {
175 return c*(7.5625*t*t) + b;
176 } else if (t < (2/2.75)) {
177 return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
178 } else if (t < (2.5/2.75)) {
179 return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
181 return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
184 easeInOutBounce: function (x, t, b, c, d) {
185 if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
186 return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
192 * TERMS OF USE - EASING EQUATIONS
194 * Open source under the BSD License.
196 * Copyright © 2001 Robert Penner
197 * All rights reserved.
199 * Redistribution and use in source and binary forms, with or without modification,
200 * are permitted provided that the following conditions are met:
202 * Redistributions of source code must retain the above copyright notice, this list of
203 * conditions and the following disclaimer.
204 * Redistributions in binary form must reproduce the above copyright notice, this list
205 * of conditions and the following disclaimer in the documentation and/or other materials
206 * provided with the distribution.
208 * Neither the name of the author nor the names of contributors may be used to endorse
209 * or promote products derived from this software without specific prior written permission.
211 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
212 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
213 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
214 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
215 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
216 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
217 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
218 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
219 * OF THE POSSIBILITY OF SUCH DAMAGE.
222 jQuery.extend( jQuery.easing,
224 easeInOutMaterial: function (x, t, b, c, d) {
225 if ((t/=d/2) < 1) return c/2*t*t + b;
226 return c/4*((t-=2)*t*t + 2) + b;
228 });;/*! VelocityJS.org (1.2.3). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */
229 /*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */
230 /*! Note that this has been modified by Materialize to confirm that Velocity is not already being imported. */
231 jQuery.Velocity?console.log("Velocity is already loaded. You may be needlessly importing Velocity again; note that Materialize includes Velocity."):(!function(e){function t(e){var t=e.length,a=r.type(e);return"function"===a||r.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===a||0===t||"number"==typeof t&&t>0&&t-1 in e}if(!e.jQuery){var r=function(e,t){return new r.fn.init(e,t)};r.isWindow=function(e){return null!=e&&e==e.window},r.type=function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[i.call(e)]||"object":typeof e},r.isArray=Array.isArray||function(e){return"array"===r.type(e)},r.isPlainObject=function(e){var t;if(!e||"object"!==r.type(e)||e.nodeType||r.isWindow(e))return!1;try{if(e.constructor&&!o.call(e,"constructor")&&!o.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(a){return!1}for(t in e);return void 0===t||o.call(e,t)},r.each=function(e,r,a){var n,o=0,i=e.length,s=t(e);if(a){if(s)for(;i>o&&(n=r.apply(e[o],a),n!==!1);o++);else for(o in e)if(n=r.apply(e[o],a),n===!1)break}else if(s)for(;i>o&&(n=r.call(e[o],o,e[o]),n!==!1);o++);else for(o in e)if(n=r.call(e[o],o,e[o]),n===!1)break;return e},r.data=function(e,t,n){if(void 0===n){var o=e[r.expando],i=o&&a[o];if(void 0===t)return i;if(i&&t in i)return i[t]}else if(void 0!==t){var o=e[r.expando]||(e[r.expando]=++r.uuid);return a[o]=a[o]||{},a[o][t]=n,n}},r.removeData=function(e,t){var n=e[r.expando],o=n&&a[n];o&&r.each(t,function(e,t){delete o[t]})},r.extend=function(){var e,t,a,n,o,i,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[l]||{},l++),"object"!=typeof s&&"function"!==r.type(s)&&(s={}),l===u&&(s=this,l--);u>l;l++)if(null!=(o=arguments[l]))for(n in o)e=s[n],a=o[n],s!==a&&(c&&a&&(r.isPlainObject(a)||(t=r.isArray(a)))?(t?(t=!1,i=e&&r.isArray(e)?e:[]):i=e&&r.isPlainObject(e)?e:{},s[n]=r.extend(c,i,a)):void 0!==a&&(s[n]=a));return s},r.queue=function(e,a,n){function o(e,r){var a=r||[];return null!=e&&(t(Object(e))?!function(e,t){for(var r=+t.length,a=0,n=e.length;r>a;)e[n++]=t[a++];if(r!==r)for(;void 0!==t[a];)e[n++]=t[a++];return e.length=n,e}(a,"string"==typeof e?[e]:e):[].push.call(a,e)),a}if(e){a=(a||"fx")+"queue";var i=r.data(e,a);return n?(!i||r.isArray(n)?i=r.data(e,a,o(n)):i.push(n),i):i||[]}},r.dequeue=function(e,t){r.each(e.nodeType?[e]:e,function(e,a){t=t||"fx";var n=r.queue(a,t),o=n.shift();"inprogress"===o&&(o=n.shift()),o&&("fx"===t&&n.unshift("inprogress"),o.call(a,function(){r.dequeue(a,t)}))})},r.fn=r.prototype={init:function(e){if(e.nodeType)return this[0]=e,this;throw new Error("Not a DOM node.")},offset:function(){var t=this[0].getBoundingClientRect?this[0].getBoundingClientRect():{top:0,left:0};return{top:t.top+(e.pageYOffset||document.scrollTop||0)-(document.clientTop||0),left:t.left+(e.pageXOffset||document.scrollLeft||0)-(document.clientLeft||0)}},position:function(){function e(){for(var e=this.offsetParent||document;e&&"html"===!e.nodeType.toLowerCase&&"static"===e.style.position;)e=e.offsetParent;return e||document}var t=this[0],e=e.apply(t),a=this.offset(),n=/^(?:body|html)$/i.test(e.nodeName)?{top:0,left:0}:r(e).offset();return a.top-=parseFloat(t.style.marginTop)||0,a.left-=parseFloat(t.style.marginLeft)||0,e.style&&(n.top+=parseFloat(e.style.borderTopWidth)||0,n.left+=parseFloat(e.style.borderLeftWidth)||0),{top:a.top-n.top,left:a.left-n.left}}};var a={};r.expando="velocity"+(new Date).getTime(),r.uuid=0;for(var n={},o=n.hasOwnProperty,i=n.toString,s="Boolean Number String Function Array Date RegExp Object Error".split(" "),l=0;l<s.length;l++)n["[object "+s[l]+"]"]=s[l].toLowerCase();r.fn.init.prototype=r.fn,e.Velocity={Utilities:r}}}(window),function(e){"object"==typeof module&&"object"==typeof module.exports?module.exports=e():"function"==typeof define&&define.amd?define(e):e()}(function(){return function(e,t,r,a){function n(e){for(var t=-1,r=e?e.length:0,a=[];++t<r;){var n=e[t];n&&a.push(n)}return a}function o(e){return m.isWrapped(e)?e=[].slice.call(e):m.isNode(e)&&(e=[e]),e}function i(e){var t=f.data(e,"velocity");return null===t?a:t}function s(e){return function(t){return Math.round(t*e)*(1/e)}}function l(e,r,a,n){function o(e,t){return 1-3*t+3*e}function i(e,t){return 3*t-6*e}function s(e){return 3*e}function l(e,t,r){return((o(t,r)*e+i(t,r))*e+s(t))*e}function u(e,t,r){return 3*o(t,r)*e*e+2*i(t,r)*e+s(t)}function c(t,r){for(var n=0;m>n;++n){var o=u(r,e,a);if(0===o)return r;var i=l(r,e,a)-t;r-=i/o}return r}function p(){for(var t=0;b>t;++t)w[t]=l(t*x,e,a)}function f(t,r,n){var o,i,s=0;do i=r+(n-r)/2,o=l(i,e,a)-t,o>0?n=i:r=i;while(Math.abs(o)>h&&++s<v);return i}function d(t){for(var r=0,n=1,o=b-1;n!=o&&w[n]<=t;++n)r+=x;--n;var i=(t-w[n])/(w[n+1]-w[n]),s=r+i*x,l=u(s,e,a);return l>=y?c(t,s):0==l?s:f(t,r,r+x)}function g(){V=!0,(e!=r||a!=n)&&p()}var m=4,y=.001,h=1e-7,v=10,b=11,x=1/(b-1),S="Float32Array"in t;if(4!==arguments.length)return!1;for(var P=0;4>P;++P)if("number"!=typeof arguments[P]||isNaN(arguments[P])||!isFinite(arguments[P]))return!1;e=Math.min(e,1),a=Math.min(a,1),e=Math.max(e,0),a=Math.max(a,0);var w=S?new Float32Array(b):new Array(b),V=!1,C=function(t){return V||g(),e===r&&a===n?t:0===t?0:1===t?1:l(d(t),r,n)};C.getControlPoints=function(){return[{x:e,y:r},{x:a,y:n}]};var T="generateBezier("+[e,r,a,n]+")";return C.toString=function(){return T},C}function u(e,t){var r=e;return m.isString(e)?b.Easings[e]||(r=!1):r=m.isArray(e)&&1===e.length?s.apply(null,e):m.isArray(e)&&2===e.length?x.apply(null,e.concat([t])):m.isArray(e)&&4===e.length?l.apply(null,e):!1,r===!1&&(r=b.Easings[b.defaults.easing]?b.defaults.easing:v),r}function c(e){if(e){var t=(new Date).getTime(),r=b.State.calls.length;r>1e4&&(b.State.calls=n(b.State.calls));for(var o=0;r>o;o++)if(b.State.calls[o]){var s=b.State.calls[o],l=s[0],u=s[2],d=s[3],g=!!d,y=null;d||(d=b.State.calls[o][3]=t-16);for(var h=Math.min((t-d)/u.duration,1),v=0,x=l.length;x>v;v++){var P=l[v],V=P.element;if(i(V)){var C=!1;if(u.display!==a&&null!==u.display&&"none"!==u.display){if("flex"===u.display){var T=["-webkit-box","-moz-box","-ms-flexbox","-webkit-flex"];f.each(T,function(e,t){S.setPropertyValue(V,"display",t)})}S.setPropertyValue(V,"display",u.display)}u.visibility!==a&&"hidden"!==u.visibility&&S.setPropertyValue(V,"visibility",u.visibility);for(var k in P)if("element"!==k){var A,F=P[k],j=m.isString(F.easing)?b.Easings[F.easing]:F.easing;if(1===h)A=F.endValue;else{var E=F.endValue-F.startValue;if(A=F.startValue+E*j(h,u,E),!g&&A===F.currentValue)continue}if(F.currentValue=A,"tween"===k)y=A;else{if(S.Hooks.registered[k]){var H=S.Hooks.getRoot(k),N=i(V).rootPropertyValueCache[H];N&&(F.rootPropertyValue=N)}var L=S.setPropertyValue(V,k,F.currentValue+(0===parseFloat(A)?"":F.unitType),F.rootPropertyValue,F.scrollData);S.Hooks.registered[k]&&(i(V).rootPropertyValueCache[H]=S.Normalizations.registered[H]?S.Normalizations.registered[H]("extract",null,L[1]):L[1]),"transform"===L[0]&&(C=!0)}}u.mobileHA&&i(V).transformCache.translate3d===a&&(i(V).transformCache.translate3d="(0px, 0px, 0px)",C=!0),C&&S.flushTransformCache(V)}}u.display!==a&&"none"!==u.display&&(b.State.calls[o][2].display=!1),u.visibility!==a&&"hidden"!==u.visibility&&(b.State.calls[o][2].visibility=!1),u.progress&&u.progress.call(s[1],s[1],h,Math.max(0,d+u.duration-t),d,y),1===h&&p(o)}}b.State.isTicking&&w(c)}function p(e,t){if(!b.State.calls[e])return!1;for(var r=b.State.calls[e][0],n=b.State.calls[e][1],o=b.State.calls[e][2],s=b.State.calls[e][4],l=!1,u=0,c=r.length;c>u;u++){var p=r[u].element;if(t||o.loop||("none"===o.display&&S.setPropertyValue(p,"display",o.display),"hidden"===o.visibility&&S.setPropertyValue(p,"visibility",o.visibility)),o.loop!==!0&&(f.queue(p)[1]===a||!/\.velocityQueueEntryFlag/i.test(f.queue(p)[1]))&&i(p)){i(p).isAnimating=!1,i(p).rootPropertyValueCache={};var d=!1;f.each(S.Lists.transforms3D,function(e,t){var r=/^scale/.test(t)?1:0,n=i(p).transformCache[t];i(p).transformCache[t]!==a&&new RegExp("^\\("+r+"[^.]").test(n)&&(d=!0,delete i(p).transformCache[t])}),o.mobileHA&&(d=!0,delete i(p).transformCache.translate3d),d&&S.flushTransformCache(p),S.Values.removeClass(p,"velocity-animating")}if(!t&&o.complete&&!o.loop&&u===c-1)try{o.complete.call(n,n)}catch(g){setTimeout(function(){throw g},1)}s&&o.loop!==!0&&s(n),i(p)&&o.loop===!0&&!t&&(f.each(i(p).tweensContainer,function(e,t){/^rotate/.test(e)&&360===parseFloat(t.endValue)&&(t.endValue=0,t.startValue=360),/^backgroundPosition/.test(e)&&100===parseFloat(t.endValue)&&"%"===t.unitType&&(t.endValue=0,t.startValue=100)}),b(p,"reverse",{loop:!0,delay:o.delay})),o.queue!==!1&&f.dequeue(p,o.queue)}b.State.calls[e]=!1;for(var m=0,y=b.State.calls.length;y>m;m++)if(b.State.calls[m]!==!1){l=!0;break}l===!1&&(b.State.isTicking=!1,delete b.State.calls,b.State.calls=[])}var f,d=function(){if(r.documentMode)return r.documentMode;for(var e=7;e>4;e--){var t=r.createElement("div");if(t.innerHTML="<!--[if IE "+e+"]><span></span><![endif]-->",t.getElementsByTagName("span").length)return t=null,e}return a}(),g=function(){var e=0;return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||function(t){var r,a=(new Date).getTime();return r=Math.max(0,16-(a-e)),e=a+r,setTimeout(function(){t(a+r)},r)}}(),m={isString:function(e){return"string"==typeof e},isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},isFunction:function(e){return"[object Function]"===Object.prototype.toString.call(e)},isNode:function(e){return e&&e.nodeType},isNodeList:function(e){return"object"==typeof e&&/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(e))&&e.length!==a&&(0===e.length||"object"==typeof e[0]&&e[0].nodeType>0)},isWrapped:function(e){return e&&(e.jquery||t.Zepto&&t.Zepto.zepto.isZ(e))},isSVG:function(e){return t.SVGElement&&e instanceof t.SVGElement},isEmptyObject:function(e){for(var t in e)return!1;return!0}},y=!1;if(e.fn&&e.fn.jquery?(f=e,y=!0):f=t.Velocity.Utilities,8>=d&&!y)throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");if(7>=d)return void(jQuery.fn.velocity=jQuery.fn.animate);var h=400,v="swing",b={State:{isMobile:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),isAndroid:/Android/i.test(navigator.userAgent),isGingerbread:/Android 2\.3\.[3-7]/i.test(navigator.userAgent),isChrome:t.chrome,isFirefox:/Firefox/i.test(navigator.userAgent),prefixElement:r.createElement("div"),prefixMatches:{},scrollAnchor:null,scrollPropertyLeft:null,scrollPropertyTop:null,isTicking:!1,calls:[]},CSS:{},Utilities:f,Redirects:{},Easings:{},Promise:t.Promise,defaults:{queue:"",duration:h,easing:v,begin:a,complete:a,progress:a,display:a,visibility:a,loop:!1,delay:!1,mobileHA:!0,_cacheValues:!0},init:function(e){f.data(e,"velocity",{isSVG:m.isSVG(e),isAnimating:!1,computedStyle:null,tweensContainer:null,rootPropertyValueCache:{},transformCache:{}})},hook:null,mock:!1,version:{major:1,minor:2,patch:2},debug:!1};t.pageYOffset!==a?(b.State.scrollAnchor=t,b.State.scrollPropertyLeft="pageXOffset",b.State.scrollPropertyTop="pageYOffset"):(b.State.scrollAnchor=r.documentElement||r.body.parentNode||r.body,b.State.scrollPropertyLeft="scrollLeft",b.State.scrollPropertyTop="scrollTop");var x=function(){function e(e){return-e.tension*e.x-e.friction*e.v}function t(t,r,a){var n={x:t.x+a.dx*r,v:t.v+a.dv*r,tension:t.tension,friction:t.friction};return{dx:n.v,dv:e(n)}}function r(r,a){var n={dx:r.v,dv:e(r)},o=t(r,.5*a,n),i=t(r,.5*a,o),s=t(r,a,i),l=1/6*(n.dx+2*(o.dx+i.dx)+s.dx),u=1/6*(n.dv+2*(o.dv+i.dv)+s.dv);return r.x=r.x+l*a,r.v=r.v+u*a,r}return function a(e,t,n){var o,i,s,l={x:-1,v:0,tension:null,friction:null},u=[0],c=0,p=1e-4,f=.016;for(e=parseFloat(e)||500,t=parseFloat(t)||20,n=n||null,l.tension=e,l.friction=t,o=null!==n,o?(c=a(e,t),i=c/n*f):i=f;s=r(s||l,i),u.push(1+s.x),c+=16,Math.abs(s.x)>p&&Math.abs(s.v)>p;);return o?function(e){return u[e*(u.length-1)|0]}:c}}();b.Easings={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},spring:function(e){return 1-Math.cos(4.5*e*Math.PI)*Math.exp(6*-e)}},f.each([["ease",[.25,.1,.25,1]],["ease-in",[.42,0,1,1]],["ease-out",[0,0,.58,1]],["ease-in-out",[.42,0,.58,1]],["easeInSine",[.47,0,.745,.715]],["easeOutSine",[.39,.575,.565,1]],["easeInOutSine",[.445,.05,.55,.95]],["easeInQuad",[.55,.085,.68,.53]],["easeOutQuad",[.25,.46,.45,.94]],["easeInOutQuad",[.455,.03,.515,.955]],["easeInCubic",[.55,.055,.675,.19]],["easeOutCubic",[.215,.61,.355,1]],["easeInOutCubic",[.645,.045,.355,1]],["easeInQuart",[.895,.03,.685,.22]],["easeOutQuart",[.165,.84,.44,1]],["easeInOutQuart",[.77,0,.175,1]],["easeInQuint",[.755,.05,.855,.06]],["easeOutQuint",[.23,1,.32,1]],["easeInOutQuint",[.86,0,.07,1]],["easeInExpo",[.95,.05,.795,.035]],["easeOutExpo",[.19,1,.22,1]],["easeInOutExpo",[1,0,0,1]],["easeInCirc",[.6,.04,.98,.335]],["easeOutCirc",[.075,.82,.165,1]],["easeInOutCirc",[.785,.135,.15,.86]]],function(e,t){b.Easings[t[0]]=l.apply(null,t[1])});var S=b.CSS={RegEx:{isHex:/^#([A-f\d]{3}){1,2}$/i,valueUnwrap:/^[A-z]+\((.*)\)$/i,wrappedValueAlreadyExtracted:/[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,valueSplit:/([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi},Lists:{colors:["fill","stroke","stopColor","color","backgroundColor","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","outlineColor"],transformsBase:["translateX","translateY","scale","scaleX","scaleY","skewX","skewY","rotateZ"],transforms3D:["transformPerspective","translateZ","scaleZ","rotateX","rotateY"]},Hooks:{templates:{textShadow:["Color X Y Blur","black 0px 0px 0px"],boxShadow:["Color X Y Blur Spread","black 0px 0px 0px 0px"],clip:["Top Right Bottom Left","0px 0px 0px 0px"],backgroundPosition:["X Y","0% 0%"],transformOrigin:["X Y Z","50% 50% 0px"],perspectiveOrigin:["X Y","50% 50%"]},registered:{},register:function(){for(var e=0;e<S.Lists.colors.length;e++){var t="color"===S.Lists.colors[e]?"0 0 0 1":"255 255 255 1";S.Hooks.templates[S.Lists.colors[e]]=["Red Green Blue Alpha",t]}var r,a,n;if(d)for(r in S.Hooks.templates){a=S.Hooks.templates[r],n=a[0].split(" ");var o=a[1].match(S.RegEx.valueSplit);"Color"===n[0]&&(n.push(n.shift()),o.push(o.shift()),S.Hooks.templates[r]=[n.join(" "),o.join(" ")])}for(r in S.Hooks.templates){a=S.Hooks.templates[r],n=a[0].split(" ");for(var e in n){var i=r+n[e],s=e;S.Hooks.registered[i]=[r,s]}}},getRoot:function(e){var t=S.Hooks.registered[e];return t?t[0]:e},cleanRootPropertyValue:function(e,t){return S.RegEx.valueUnwrap.test(t)&&(t=t.match(S.RegEx.valueUnwrap)[1]),S.Values.isCSSNullValue(t)&&(t=S.Hooks.templates[e][1]),t},extractValue:function(e,t){var r=S.Hooks.registered[e];if(r){var a=r[0],n=r[1];return t=S.Hooks.cleanRootPropertyValue(a,t),t.toString().match(S.RegEx.valueSplit)[n]}return t},injectValue:function(e,t,r){var a=S.Hooks.registered[e];if(a){var n,o,i=a[0],s=a[1];return r=S.Hooks.cleanRootPropertyValue(i,r),n=r.toString().match(S.RegEx.valueSplit),n[s]=t,o=n.join(" ")}return r}},Normalizations:{registered:{clip:function(e,t,r){switch(e){case"name":return"clip";case"extract":var a;return S.RegEx.wrappedValueAlreadyExtracted.test(r)?a=r:(a=r.toString().match(S.RegEx.valueUnwrap),a=a?a[1].replace(/,(\s+)?/g," "):r),a;case"inject":return"rect("+r+")"}},blur:function(e,t,r){switch(e){case"name":return b.State.isFirefox?"filter":"-webkit-filter";case"extract":var a=parseFloat(r);if(!a&&0!==a){var n=r.toString().match(/blur\(([0-9]+[A-z]+)\)/i);a=n?n[1]:0}return a;case"inject":return parseFloat(r)?"blur("+r+")":"none"}},opacity:function(e,t,r){if(8>=d)switch(e){case"name":return"filter";case"extract":var a=r.toString().match(/alpha\(opacity=(.*)\)/i);return r=a?a[1]/100:1;case"inject":return t.style.zoom=1,parseFloat(r)>=1?"":"alpha(opacity="+parseInt(100*parseFloat(r),10)+")"}else switch(e){case"name":return"opacity";case"extract":return r;case"inject":return r}}},register:function(){9>=d||b.State.isGingerbread||(S.Lists.transformsBase=S.Lists.transformsBase.concat(S.Lists.transforms3D));for(var e=0;e<S.Lists.transformsBase.length;e++)!function(){var t=S.Lists.transformsBase[e];S.Normalizations.registered[t]=function(e,r,n){switch(e){case"name":return"transform";case"extract":return i(r)===a||i(r).transformCache[t]===a?/^scale/i.test(t)?1:0:i(r).transformCache[t].replace(/[()]/g,"");case"inject":var o=!1;switch(t.substr(0,t.length-1)){case"translate":o=!/(%|px|em|rem|vw|vh|\d)$/i.test(n);break;case"scal":case"scale":b.State.isAndroid&&i(r).transformCache[t]===a&&1>n&&(n=1),o=!/(\d)$/i.test(n);break;case"skew":o=!/(deg|\d)$/i.test(n);break;case"rotate":o=!/(deg|\d)$/i.test(n)}return o||(i(r).transformCache[t]="("+n+")"),i(r).transformCache[t]}}}();for(var e=0;e<S.Lists.colors.length;e++)!function(){var t=S.Lists.colors[e];S.Normalizations.registered[t]=function(e,r,n){switch(e){case"name":return t;case"extract":var o;if(S.RegEx.wrappedValueAlreadyExtracted.test(n))o=n;else{var i,s={black:"rgb(0, 0, 0)",blue:"rgb(0, 0, 255)",gray:"rgb(128, 128, 128)",green:"rgb(0, 128, 0)",red:"rgb(255, 0, 0)",white:"rgb(255, 255, 255)"};/^[A-z]+$/i.test(n)?i=s[n]!==a?s[n]:s.black:S.RegEx.isHex.test(n)?i="rgb("+S.Values.hexToRgb(n).join(" ")+")":/^rgba?\(/i.test(n)||(i=s.black),o=(i||n).toString().match(S.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g," ")}return 8>=d||3!==o.split(" ").length||(o+=" 1"),o;case"inject":return 8>=d?4===n.split(" ").length&&(n=n.split(/\s+/).slice(0,3).join(" ")):3===n.split(" ").length&&(n+=" 1"),(8>=d?"rgb":"rgba")+"("+n.replace(/\s+/g,",").replace(/\.(\d)+(?=,)/g,"")+")"}}}()}},Names:{camelCase:function(e){return e.replace(/-(\w)/g,function(e,t){return t.toUpperCase()})},SVGAttribute:function(e){var t="width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";return(d||b.State.isAndroid&&!b.State.isChrome)&&(t+="|transform"),new RegExp("^("+t+")$","i").test(e)},prefixCheck:function(e){if(b.State.prefixMatches[e])return[b.State.prefixMatches[e],!0];for(var t=["","Webkit","Moz","ms","O"],r=0,a=t.length;a>r;r++){var n;if(n=0===r?e:t[r]+e.replace(/^\w/,function(e){return e.toUpperCase()}),m.isString(b.State.prefixElement.style[n]))return b.State.prefixMatches[e]=n,[n,!0]}return[e,!1]}},Values:{hexToRgb:function(e){var t,r=/^#?([a-f\d])([a-f\d])([a-f\d])$/i,a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;return e=e.replace(r,function(e,t,r,a){return t+t+r+r+a+a}),t=a.exec(e),t?[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]:[0,0,0]},isCSSNullValue:function(e){return 0==e||/^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(e)},getUnitType:function(e){return/^(rotate|skew)/i.test(e)?"deg":/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(e)?"":"px"},getDisplayType:function(e){var t=e&&e.tagName.toString().toLowerCase();return/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(t)?"inline":/^(li)$/i.test(t)?"list-item":/^(tr)$/i.test(t)?"table-row":/^(table)$/i.test(t)?"table":/^(tbody)$/i.test(t)?"table-row-group":"block"},addClass:function(e,t){e.classList?e.classList.add(t):e.className+=(e.className.length?" ":"")+t},removeClass:function(e,t){e.classList?e.classList.remove(t):e.className=e.className.toString().replace(new RegExp("(^|\\s)"+t.split(" ").join("|")+"(\\s|$)","gi")," ")}},getPropertyValue:function(e,r,n,o){function s(e,r){function n(){u&&S.setPropertyValue(e,"display","none")}var l=0;if(8>=d)l=f.css(e,r);else{var u=!1;if(/^(width|height)$/.test(r)&&0===S.getPropertyValue(e,"display")&&(u=!0,S.setPropertyValue(e,"display",S.Values.getDisplayType(e))),!o){if("height"===r&&"border-box"!==S.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var c=e.offsetHeight-(parseFloat(S.getPropertyValue(e,"borderTopWidth"))||0)-(parseFloat(S.getPropertyValue(e,"borderBottomWidth"))||0)-(parseFloat(S.getPropertyValue(e,"paddingTop"))||0)-(parseFloat(S.getPropertyValue(e,"paddingBottom"))||0);return n(),c}if("width"===r&&"border-box"!==S.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var p=e.offsetWidth-(parseFloat(S.getPropertyValue(e,"borderLeftWidth"))||0)-(parseFloat(S.getPropertyValue(e,"borderRightWidth"))||0)-(parseFloat(S.getPropertyValue(e,"paddingLeft"))||0)-(parseFloat(S.getPropertyValue(e,"paddingRight"))||0);return n(),p}}var g;g=i(e)===a?t.getComputedStyle(e,null):i(e).computedStyle?i(e).computedStyle:i(e).computedStyle=t.getComputedStyle(e,null),"borderColor"===r&&(r="borderTopColor"),l=9===d&&"filter"===r?g.getPropertyValue(r):g[r],(""===l||null===l)&&(l=e.style[r]),n()}if("auto"===l&&/^(top|right|bottom|left)$/i.test(r)){var m=s(e,"position");("fixed"===m||"absolute"===m&&/top|left/i.test(r))&&(l=f(e).position()[r]+"px")}return l}var l;if(S.Hooks.registered[r]){var u=r,c=S.Hooks.getRoot(u);n===a&&(n=S.getPropertyValue(e,S.Names.prefixCheck(c)[0])),S.Normalizations.registered[c]&&(n=S.Normalizations.registered[c]("extract",e,n)),l=S.Hooks.extractValue(u,n)}else if(S.Normalizations.registered[r]){var p,g;p=S.Normalizations.registered[r]("name",e),"transform"!==p&&(g=s(e,S.Names.prefixCheck(p)[0]),S.Values.isCSSNullValue(g)&&S.Hooks.templates[r]&&(g=S.Hooks.templates[r][1])),l=S.Normalizations.registered[r]("extract",e,g)}if(!/^[\d-]/.test(l))if(i(e)&&i(e).isSVG&&S.Names.SVGAttribute(r))if(/^(height|width)$/i.test(r))try{l=e.getBBox()[r]}catch(m){l=0}else l=e.getAttribute(r);else l=s(e,S.Names.prefixCheck(r)[0]);return S.Values.isCSSNullValue(l)&&(l=0),b.debug>=2&&console.log("Get "+r+": "+l),l},setPropertyValue:function(e,r,a,n,o){var s=r;if("scroll"===r)o.container?o.container["scroll"+o.direction]=a:"Left"===o.direction?t.scrollTo(a,o.alternateValue):t.scrollTo(o.alternateValue,a);else if(S.Normalizations.registered[r]&&"transform"===S.Normalizations.registered[r]("name",e))S.Normalizations.registered[r]("inject",e,a),s="transform",a=i(e).transformCache[r];else{if(S.Hooks.registered[r]){var l=r,u=S.Hooks.getRoot(r);n=n||S.getPropertyValue(e,u),a=S.Hooks.injectValue(l,a,n),r=u}if(S.Normalizations.registered[r]&&(a=S.Normalizations.registered[r]("inject",e,a),r=S.Normalizations.registered[r]("name",e)),s=S.Names.prefixCheck(r)[0],8>=d)try{e.style[s]=a}catch(c){b.debug&&console.log("Browser does not support ["+a+"] for ["+s+"]")}else i(e)&&i(e).isSVG&&S.Names.SVGAttribute(r)?e.setAttribute(r,a):e.style[s]=a;b.debug>=2&&console.log("Set "+r+" ("+s+"): "+a)}return[s,a]},flushTransformCache:function(e){function t(t){return parseFloat(S.getPropertyValue(e,t))}var r="";if((d||b.State.isAndroid&&!b.State.isChrome)&&i(e).isSVG){var a={translate:[t("translateX"),t("translateY")],skewX:[t("skewX")],skewY:[t("skewY")],scale:1!==t("scale")?[t("scale"),t("scale")]:[t("scaleX"),t("scaleY")],rotate:[t("rotateZ"),0,0]};f.each(i(e).transformCache,function(e){/^translate/i.test(e)?e="translate":/^scale/i.test(e)?e="scale":/^rotate/i.test(e)&&(e="rotate"),a[e]&&(r+=e+"("+a[e].join(" ")+") ",delete a[e])})}else{var n,o;f.each(i(e).transformCache,function(t){return n=i(e).transformCache[t],"transformPerspective"===t?(o=n,!0):(9===d&&"rotateZ"===t&&(t="rotate"),void(r+=t+n+" "))}),o&&(r="perspective"+o+" "+r)}S.setPropertyValue(e,"transform",r)}};S.Hooks.register(),S.Normalizations.register(),b.hook=function(e,t,r){var n=a;return e=o(e),f.each(e,function(e,o){if(i(o)===a&&b.init(o),r===a)n===a&&(n=b.CSS.getPropertyValue(o,t));else{var s=b.CSS.setPropertyValue(o,t,r);"transform"===s[0]&&b.CSS.flushTransformCache(o),n=s}}),n};var P=function(){function e(){return s?k.promise||null:l}function n(){function e(e){function p(e,t){var r=a,n=a,i=a;return m.isArray(e)?(r=e[0],!m.isArray(e[1])&&/^[\d-]/.test(e[1])||m.isFunction(e[1])||S.RegEx.isHex.test(e[1])?i=e[1]:(m.isString(e[1])&&!S.RegEx.isHex.test(e[1])||m.isArray(e[1]))&&(n=t?e[1]:u(e[1],s.duration),e[2]!==a&&(i=e[2]))):r=e,t||(n=n||s.easing),m.isFunction(r)&&(r=r.call(o,V,w)),m.isFunction(i)&&(i=i.call(o,V,w)),[r||0,n,i]}function d(e,t){var r,a;return a=(t||"0").toString().toLowerCase().replace(/[%A-z]+$/,function(e){return r=e,""}),r||(r=S.Values.getUnitType(e)),[a,r]}function h(){var e={myParent:o.parentNode||r.body,position:S.getPropertyValue(o,"position"),fontSize:S.getPropertyValue(o,"fontSize")},a=e.position===L.lastPosition&&e.myParent===L.lastParent,n=e.fontSize===L.lastFontSize;L.lastParent=e.myParent,L.lastPosition=e.position,L.lastFontSize=e.fontSize;var s=100,l={};if(n&&a)l.emToPx=L.lastEmToPx,l.percentToPxWidth=L.lastPercentToPxWidth,l.percentToPxHeight=L.lastPercentToPxHeight;else{var u=i(o).isSVG?r.createElementNS("http://www.w3.org/2000/svg","rect"):r.createElement("div");b.init(u),e.myParent.appendChild(u),f.each(["overflow","overflowX","overflowY"],function(e,t){b.CSS.setPropertyValue(u,t,"hidden")}),b.CSS.setPropertyValue(u,"position",e.position),b.CSS.setPropertyValue(u,"fontSize",e.fontSize),b.CSS.setPropertyValue(u,"boxSizing","content-box"),f.each(["minWidth","maxWidth","width","minHeight","maxHeight","height"],function(e,t){b.CSS.setPropertyValue(u,t,s+"%")}),b.CSS.setPropertyValue(u,"paddingLeft",s+"em"),l.percentToPxWidth=L.lastPercentToPxWidth=(parseFloat(S.getPropertyValue(u,"width",null,!0))||1)/s,l.percentToPxHeight=L.lastPercentToPxHeight=(parseFloat(S.getPropertyValue(u,"height",null,!0))||1)/s,l.emToPx=L.lastEmToPx=(parseFloat(S.getPropertyValue(u,"paddingLeft"))||1)/s,e.myParent.removeChild(u)}return null===L.remToPx&&(L.remToPx=parseFloat(S.getPropertyValue(r.body,"fontSize"))||16),null===L.vwToPx&&(L.vwToPx=parseFloat(t.innerWidth)/100,L.vhToPx=parseFloat(t.innerHeight)/100),l.remToPx=L.remToPx,l.vwToPx=L.vwToPx,l.vhToPx=L.vhToPx,b.debug>=1&&console.log("Unit ratios: "+JSON.stringify(l),o),l}if(s.begin&&0===V)try{s.begin.call(g,g)}catch(x){setTimeout(function(){throw x},1)}if("scroll"===A){var P,C,T,F=/^x$/i.test(s.axis)?"Left":"Top",j=parseFloat(s.offset)||0;s.container?m.isWrapped(s.container)||m.isNode(s.container)?(s.container=s.container[0]||s.container,P=s.container["scroll"+F],T=P+f(o).position()[F.toLowerCase()]+j):s.container=null:(P=b.State.scrollAnchor[b.State["scrollProperty"+F]],C=b.State.scrollAnchor[b.State["scrollProperty"+("Left"===F?"Top":"Left")]],T=f(o).offset()[F.toLowerCase()]+j),l={scroll:{rootPropertyValue:!1,startValue:P,currentValue:P,endValue:T,unitType:"",easing:s.easing,scrollData:{container:s.container,direction:F,alternateValue:C}},element:o},b.debug&&console.log("tweensContainer (scroll): ",l.scroll,o)}else if("reverse"===A){if(!i(o).tweensContainer)return void f.dequeue(o,s.queue);"none"===i(o).opts.display&&(i(o).opts.display="auto"),"hidden"===i(o).opts.visibility&&(i(o).opts.visibility="visible"),i(o).opts.loop=!1,i(o).opts.begin=null,i(o).opts.complete=null,v.easing||delete s.easing,v.duration||delete s.duration,s=f.extend({},i(o).opts,s);var E=f.extend(!0,{},i(o).tweensContainer);for(var H in E)if("element"!==H){var N=E[H].startValue;E[H].startValue=E[H].currentValue=E[H].endValue,E[H].endValue=N,m.isEmptyObject(v)||(E[H].easing=s.easing),b.debug&&console.log("reverse tweensContainer ("+H+"): "+JSON.stringify(E[H]),o)}l=E}else if("start"===A){var E;i(o).tweensContainer&&i(o).isAnimating===!0&&(E=i(o).tweensContainer),f.each(y,function(e,t){if(RegExp("^"+S.Lists.colors.join("$|^")+"$").test(e)){var r=p(t,!0),n=r[0],o=r[1],i=r[2];if(S.RegEx.isHex.test(n)){for(var s=["Red","Green","Blue"],l=S.Values.hexToRgb(n),u=i?S.Values.hexToRgb(i):a,c=0;c<s.length;c++){var f=[l[c]];o&&f.push(o),u!==a&&f.push(u[c]),y[e+s[c]]=f}delete y[e]}}});for(var z in y){var O=p(y[z]),q=O[0],$=O[1],M=O[2];z=S.Names.camelCase(z);var I=S.Hooks.getRoot(z),B=!1;if(i(o).isSVG||"tween"===I||S.Names.prefixCheck(I)[1]!==!1||S.Normalizations.registered[I]!==a){(s.display!==a&&null!==s.display&&"none"!==s.display||s.visibility!==a&&"hidden"!==s.visibility)&&/opacity|filter/.test(z)&&!M&&0!==q&&(M=0),s._cacheValues&&E&&E[z]?(M===a&&(M=E[z].endValue+E[z].unitType),B=i(o).rootPropertyValueCache[I]):S.Hooks.registered[z]?M===a?(B=S.getPropertyValue(o,I),M=S.getPropertyValue(o,z,B)):B=S.Hooks.templates[I][1]:M===a&&(M=S.getPropertyValue(o,z));var W,G,Y,D=!1;if(W=d(z,M),M=W[0],Y=W[1],W=d(z,q),q=W[0].replace(/^([+-\/*])=/,function(e,t){return D=t,""}),G=W[1],M=parseFloat(M)||0,q=parseFloat(q)||0,"%"===G&&(/^(fontSize|lineHeight)$/.test(z)?(q/=100,G="em"):/^scale/.test(z)?(q/=100,G=""):/(Red|Green|Blue)$/i.test(z)&&(q=q/100*255,G="")),/[\/*]/.test(D))G=Y;else if(Y!==G&&0!==M)if(0===q)G=Y;else{n=n||h();var Q=/margin|padding|left|right|width|text|word|letter/i.test(z)||/X$/.test(z)||"x"===z?"x":"y";switch(Y){case"%":M*="x"===Q?n.percentToPxWidth:n.percentToPxHeight;break;case"px":break;default:M*=n[Y+"ToPx"]}switch(G){case"%":M*=1/("x"===Q?n.percentToPxWidth:n.percentToPxHeight);break;case"px":break;default:M*=1/n[G+"ToPx"]}}switch(D){case"+":q=M+q;break;case"-":q=M-q;break;case"*":q=M*q;break;case"/":q=M/q}l[z]={rootPropertyValue:B,startValue:M,currentValue:M,endValue:q,unitType:G,easing:$},b.debug&&console.log("tweensContainer ("+z+"): "+JSON.stringify(l[z]),o)}else b.debug&&console.log("Skipping ["+I+"] due to a lack of browser support.")}l.element=o}l.element&&(S.Values.addClass(o,"velocity-animating"),R.push(l),""===s.queue&&(i(o).tweensContainer=l,i(o).opts=s),i(o).isAnimating=!0,V===w-1?(b.State.calls.push([R,g,s,null,k.resolver]),b.State.isTicking===!1&&(b.State.isTicking=!0,c())):V++)}var n,o=this,s=f.extend({},b.defaults,v),l={};switch(i(o)===a&&b.init(o),parseFloat(s.delay)&&s.queue!==!1&&f.queue(o,s.queue,function(e){b.velocityQueueEntryFlag=!0,i(o).delayTimer={setTimeout:setTimeout(e,parseFloat(s.delay)),next:e}}),s.duration.toString().toLowerCase()){case"fast":s.duration=200;break;case"normal":s.duration=h;break;case"slow":s.duration=600;break;default:s.duration=parseFloat(s.duration)||1}b.mock!==!1&&(b.mock===!0?s.duration=s.delay=1:(s.duration*=parseFloat(b.mock)||1,s.delay*=parseFloat(b.mock)||1)),s.easing=u(s.easing,s.duration),s.begin&&!m.isFunction(s.begin)&&(s.begin=null),s.progress&&!m.isFunction(s.progress)&&(s.progress=null),s.complete&&!m.isFunction(s.complete)&&(s.complete=null),s.display!==a&&null!==s.display&&(s.display=s.display.toString().toLowerCase(),"auto"===s.display&&(s.display=b.CSS.Values.getDisplayType(o))),s.visibility!==a&&null!==s.visibility&&(s.visibility=s.visibility.toString().toLowerCase()),s.mobileHA=s.mobileHA&&b.State.isMobile&&!b.State.isGingerbread,s.queue===!1?s.delay?setTimeout(e,s.delay):e():f.queue(o,s.queue,function(t,r){return r===!0?(k.promise&&k.resolver(g),!0):(b.velocityQueueEntryFlag=!0,void e(t))}),""!==s.queue&&"fx"!==s.queue||"inprogress"===f.queue(o)[0]||f.dequeue(o)}var s,l,d,g,y,v,x=arguments[0]&&(arguments[0].p||f.isPlainObject(arguments[0].properties)&&!arguments[0].properties.names||m.isString(arguments[0].properties));if(m.isWrapped(this)?(s=!1,d=0,g=this,l=this):(s=!0,d=1,g=x?arguments[0].elements||arguments[0].e:arguments[0]),g=o(g)){x?(y=arguments[0].properties||arguments[0].p,v=arguments[0].options||arguments[0].o):(y=arguments[d],v=arguments[d+1]);var w=g.length,V=0;if(!/^(stop|finish)$/i.test(y)&&!f.isPlainObject(v)){var C=d+1;v={};for(var T=C;T<arguments.length;T++)m.isArray(arguments[T])||!/^(fast|normal|slow)$/i.test(arguments[T])&&!/^\d/.test(arguments[T])?m.isString(arguments[T])||m.isArray(arguments[T])?v.easing=arguments[T]:m.isFunction(arguments[T])&&(v.complete=arguments[T]):v.duration=arguments[T]}var k={promise:null,resolver:null,rejecter:null};s&&b.Promise&&(k.promise=new b.Promise(function(e,t){k.resolver=e,k.rejecter=t}));var A;switch(y){case"scroll":A="scroll";break;case"reverse":A="reverse";break;case"finish":case"stop":f.each(g,function(e,t){i(t)&&i(t).delayTimer&&(clearTimeout(i(t).delayTimer.setTimeout),i(t).delayTimer.next&&i(t).delayTimer.next(),delete i(t).delayTimer)});var F=[];return f.each(b.State.calls,function(e,t){t&&f.each(t[1],function(r,n){var o=v===a?"":v;return o===!0||t[2].queue===o||v===a&&t[2].queue===!1?void f.each(g,function(r,a){a===n&&((v===!0||m.isString(v))&&(f.each(f.queue(a,m.isString(v)?v:""),function(e,t){
232 m.isFunction(t)&&t(null,!0)}),f.queue(a,m.isString(v)?v:"",[])),"stop"===y?(i(a)&&i(a).tweensContainer&&o!==!1&&f.each(i(a).tweensContainer,function(e,t){t.endValue=t.currentValue}),F.push(e)):"finish"===y&&(t[2].duration=1))}):!0})}),"stop"===y&&(f.each(F,function(e,t){p(t,!0)}),k.promise&&k.resolver(g)),e();default:if(!f.isPlainObject(y)||m.isEmptyObject(y)){if(m.isString(y)&&b.Redirects[y]){var j=f.extend({},v),E=j.duration,H=j.delay||0;return j.backwards===!0&&(g=f.extend(!0,[],g).reverse()),f.each(g,function(e,t){parseFloat(j.stagger)?j.delay=H+parseFloat(j.stagger)*e:m.isFunction(j.stagger)&&(j.delay=H+j.stagger.call(t,e,w)),j.drag&&(j.duration=parseFloat(E)||(/^(callout|transition)/.test(y)?1e3:h),j.duration=Math.max(j.duration*(j.backwards?1-e/w:(e+1)/w),.75*j.duration,200)),b.Redirects[y].call(t,t,j||{},e,w,g,k.promise?k:a)}),e()}var N="Velocity: First argument ("+y+") was not a property map, a known action, or a registered redirect. Aborting.";return k.promise?k.rejecter(new Error(N)):console.log(N),e()}A="start"}var L={lastParent:null,lastPosition:null,lastFontSize:null,lastPercentToPxWidth:null,lastPercentToPxHeight:null,lastEmToPx:null,remToPx:null,vwToPx:null,vhToPx:null},R=[];f.each(g,function(e,t){m.isNode(t)&&n.call(t)});var z,j=f.extend({},b.defaults,v);if(j.loop=parseInt(j.loop),z=2*j.loop-1,j.loop)for(var O=0;z>O;O++){var q={delay:j.delay,progress:j.progress};O===z-1&&(q.display=j.display,q.visibility=j.visibility,q.complete=j.complete),P(g,"reverse",q)}return e()}};b=f.extend(P,b),b.animate=P;var w=t.requestAnimationFrame||g;return b.State.isMobile||r.hidden===a||r.addEventListener("visibilitychange",function(){r.hidden?(w=function(e){return setTimeout(function(){e(!0)},16)},c()):w=t.requestAnimationFrame||g}),e.Velocity=b,e!==t&&(e.fn.velocity=P,e.fn.velocity.defaults=b.defaults),f.each(["Down","Up"],function(e,t){b.Redirects["slide"+t]=function(e,r,n,o,i,s){var l=f.extend({},r),u=l.begin,c=l.complete,p={height:"",marginTop:"",marginBottom:"",paddingTop:"",paddingBottom:""},d={};l.display===a&&(l.display="Down"===t?"inline"===b.CSS.Values.getDisplayType(e)?"inline-block":"block":"none"),l.begin=function(){u&&u.call(i,i);for(var r in p){d[r]=e.style[r];var a=b.CSS.getPropertyValue(e,r);p[r]="Down"===t?[a,0]:[0,a]}d.overflow=e.style.overflow,e.style.overflow="hidden"},l.complete=function(){for(var t in d)e.style[t]=d[t];c&&c.call(i,i),s&&s.resolver(i)},b(e,p,l)}}),f.each(["In","Out"],function(e,t){b.Redirects["fade"+t]=function(e,r,n,o,i,s){var l=f.extend({},r),u={opacity:"In"===t?1:0},c=l.complete;l.complete=n!==o-1?l.begin=null:function(){c&&c.call(i,i),s&&s.resolver(i)},l.display===a&&(l.display="In"===t?"auto":"none"),b(this,u,l)}}),b}(window.jQuery||window.Zepto||window,window,document)}));
233 ;!function(a,b,c,d){"use strict";function k(a,b,c){return setTimeout(q(a,c),b)}function l(a,b,c){return Array.isArray(a)?(m(a,c[b],c),!0):!1}function m(a,b,c){var e;if(a)if(a.forEach)a.forEach(b,c);else if(a.length!==d)for(e=0;e<a.length;)b.call(c,a[e],e,a),e++;else for(e in a)a.hasOwnProperty(e)&&b.call(c,a[e],e,a)}function n(a,b,c){for(var e=Object.keys(b),f=0;f<e.length;)(!c||c&&a[e[f]]===d)&&(a[e[f]]=b[e[f]]),f++;return a}function o(a,b){return n(a,b,!0)}function p(a,b,c){var e,d=b.prototype;e=a.prototype=Object.create(d),e.constructor=a,e._super=d,c&&n(e,c)}function q(a,b){return function(){return a.apply(b,arguments)}}function r(a,b){return typeof a==g?a.apply(b?b[0]||d:d,b):a}function s(a,b){return a===d?b:a}function t(a,b,c){m(x(b),function(b){a.addEventListener(b,c,!1)})}function u(a,b,c){m(x(b),function(b){a.removeEventListener(b,c,!1)})}function v(a,b){for(;a;){if(a==b)return!0;a=a.parentNode}return!1}function w(a,b){return a.indexOf(b)>-1}function x(a){return a.trim().split(/\s+/g)}function y(a,b,c){if(a.indexOf&&!c)return a.indexOf(b);for(var d=0;d<a.length;){if(c&&a[d][c]==b||!c&&a[d]===b)return d;d++}return-1}function z(a){return Array.prototype.slice.call(a,0)}function A(a,b,c){for(var d=[],e=[],f=0;f<a.length;){var g=b?a[f][b]:a[f];y(e,g)<0&&d.push(a[f]),e[f]=g,f++}return c&&(d=b?d.sort(function(a,c){return a[b]>c[b]}):d.sort()),d}function B(a,b){for(var c,f,g=b[0].toUpperCase()+b.slice(1),h=0;h<e.length;){if(c=e[h],f=c?c+g:b,f in a)return f;h++}return d}function D(){return C++}function E(a){var b=a.ownerDocument;return b.defaultView||b.parentWindow}function ab(a,b){var c=this;this.manager=a,this.callback=b,this.element=a.element,this.target=a.options.inputTarget,this.domHandler=function(b){r(a.options.enable,[a])&&c.handler(b)},this.init()}function bb(a){var b,c=a.options.inputClass;return b=c?c:H?wb:I?Eb:G?Gb:rb,new b(a,cb)}function cb(a,b,c){var d=c.pointers.length,e=c.changedPointers.length,f=b&O&&0===d-e,g=b&(Q|R)&&0===d-e;c.isFirst=!!f,c.isFinal=!!g,f&&(a.session={}),c.eventType=b,db(a,c),a.emit("hammer.input",c),a.recognize(c),a.session.prevInput=c}function db(a,b){var c=a.session,d=b.pointers,e=d.length;c.firstInput||(c.firstInput=gb(b)),e>1&&!c.firstMultiple?c.firstMultiple=gb(b):1===e&&(c.firstMultiple=!1);var f=c.firstInput,g=c.firstMultiple,h=g?g.center:f.center,i=b.center=hb(d);b.timeStamp=j(),b.deltaTime=b.timeStamp-f.timeStamp,b.angle=lb(h,i),b.distance=kb(h,i),eb(c,b),b.offsetDirection=jb(b.deltaX,b.deltaY),b.scale=g?nb(g.pointers,d):1,b.rotation=g?mb(g.pointers,d):0,fb(c,b);var k=a.element;v(b.srcEvent.target,k)&&(k=b.srcEvent.target),b.target=k}function eb(a,b){var c=b.center,d=a.offsetDelta||{},e=a.prevDelta||{},f=a.prevInput||{};(b.eventType===O||f.eventType===Q)&&(e=a.prevDelta={x:f.deltaX||0,y:f.deltaY||0},d=a.offsetDelta={x:c.x,y:c.y}),b.deltaX=e.x+(c.x-d.x),b.deltaY=e.y+(c.y-d.y)}function fb(a,b){var f,g,h,j,c=a.lastInterval||b,e=b.timeStamp-c.timeStamp;if(b.eventType!=R&&(e>N||c.velocity===d)){var k=c.deltaX-b.deltaX,l=c.deltaY-b.deltaY,m=ib(e,k,l);g=m.x,h=m.y,f=i(m.x)>i(m.y)?m.x:m.y,j=jb(k,l),a.lastInterval=b}else f=c.velocity,g=c.velocityX,h=c.velocityY,j=c.direction;b.velocity=f,b.velocityX=g,b.velocityY=h,b.direction=j}function gb(a){for(var b=[],c=0;c<a.pointers.length;)b[c]={clientX:h(a.pointers[c].clientX),clientY:h(a.pointers[c].clientY)},c++;return{timeStamp:j(),pointers:b,center:hb(b),deltaX:a.deltaX,deltaY:a.deltaY}}function hb(a){var b=a.length;if(1===b)return{x:h(a[0].clientX),y:h(a[0].clientY)};for(var c=0,d=0,e=0;b>e;)c+=a[e].clientX,d+=a[e].clientY,e++;return{x:h(c/b),y:h(d/b)}}function ib(a,b,c){return{x:b/a||0,y:c/a||0}}function jb(a,b){return a===b?S:i(a)>=i(b)?a>0?T:U:b>0?V:W}function kb(a,b,c){c||(c=$);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return Math.sqrt(d*d+e*e)}function lb(a,b,c){c||(c=$);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return 180*Math.atan2(e,d)/Math.PI}function mb(a,b){return lb(b[1],b[0],_)-lb(a[1],a[0],_)}function nb(a,b){return kb(b[0],b[1],_)/kb(a[0],a[1],_)}function rb(){this.evEl=pb,this.evWin=qb,this.allow=!0,this.pressed=!1,ab.apply(this,arguments)}function wb(){this.evEl=ub,this.evWin=vb,ab.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function Ab(){this.evTarget=yb,this.evWin=zb,this.started=!1,ab.apply(this,arguments)}function Bb(a,b){var c=z(a.touches),d=z(a.changedTouches);return b&(Q|R)&&(c=A(c.concat(d),"identifier",!0)),[c,d]}function Eb(){this.evTarget=Db,this.targetIds={},ab.apply(this,arguments)}function Fb(a,b){var c=z(a.touches),d=this.targetIds;if(b&(O|P)&&1===c.length)return d[c[0].identifier]=!0,[c,c];var e,f,g=z(a.changedTouches),h=[],i=this.target;if(f=c.filter(function(a){return v(a.target,i)}),b===O)for(e=0;e<f.length;)d[f[e].identifier]=!0,e++;for(e=0;e<g.length;)d[g[e].identifier]&&h.push(g[e]),b&(Q|R)&&delete d[g[e].identifier],e++;return h.length?[A(f.concat(h),"identifier",!0),h]:void 0}function Gb(){ab.apply(this,arguments);var a=q(this.handler,this);this.touch=new Eb(this.manager,a),this.mouse=new rb(this.manager,a)}function Pb(a,b){this.manager=a,this.set(b)}function Qb(a){if(w(a,Mb))return Mb;var b=w(a,Nb),c=w(a,Ob);return b&&c?Nb+" "+Ob:b||c?b?Nb:Ob:w(a,Lb)?Lb:Kb}function Yb(a){this.id=D(),this.manager=null,this.options=o(a||{},this.defaults),this.options.enable=s(this.options.enable,!0),this.state=Rb,this.simultaneous={},this.requireFail=[]}function Zb(a){return a&Wb?"cancel":a&Ub?"end":a&Tb?"move":a&Sb?"start":""}function $b(a){return a==W?"down":a==V?"up":a==T?"left":a==U?"right":""}function _b(a,b){var c=b.manager;return c?c.get(a):a}function ac(){Yb.apply(this,arguments)}function bc(){ac.apply(this,arguments),this.pX=null,this.pY=null}function cc(){ac.apply(this,arguments)}function dc(){Yb.apply(this,arguments),this._timer=null,this._input=null}function ec(){ac.apply(this,arguments)}function fc(){ac.apply(this,arguments)}function gc(){Yb.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function hc(a,b){return b=b||{},b.recognizers=s(b.recognizers,hc.defaults.preset),new kc(a,b)}function kc(a,b){b=b||{},this.options=o(b,hc.defaults),this.options.inputTarget=this.options.inputTarget||a,this.handlers={},this.session={},this.recognizers=[],this.element=a,this.input=bb(this),this.touchAction=new Pb(this,this.options.touchAction),lc(this,!0),m(b.recognizers,function(a){var b=this.add(new a[0](a[1]));a[2]&&b.recognizeWith(a[2]),a[3]&&b.requireFailure(a[3])},this)}function lc(a,b){var c=a.element;m(a.options.cssProps,function(a,d){c.style[B(c.style,d)]=b?a:""})}function mc(a,c){var d=b.createEvent("Event");d.initEvent(a,!0,!0),d.gesture=c,c.target.dispatchEvent(d)}var e=["","webkit","moz","MS","ms","o"],f=b.createElement("div"),g="function",h=Math.round,i=Math.abs,j=Date.now,C=1,F=/mobile|tablet|ip(ad|hone|od)|android/i,G="ontouchstart"in a,H=B(a,"PointerEvent")!==d,I=G&&F.test(navigator.userAgent),J="touch",K="pen",L="mouse",M="kinect",N=25,O=1,P=2,Q=4,R=8,S=1,T=2,U=4,V=8,W=16,X=T|U,Y=V|W,Z=X|Y,$=["x","y"],_=["clientX","clientY"];ab.prototype={handler:function(){},init:function(){this.evEl&&t(this.element,this.evEl,this.domHandler),this.evTarget&&t(this.target,this.evTarget,this.domHandler),this.evWin&&t(E(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&u(this.element,this.evEl,this.domHandler),this.evTarget&&u(this.target,this.evTarget,this.domHandler),this.evWin&&u(E(this.element),this.evWin,this.domHandler)}};var ob={mousedown:O,mousemove:P,mouseup:Q},pb="mousedown",qb="mousemove mouseup";p(rb,ab,{handler:function(a){var b=ob[a.type];b&O&&0===a.button&&(this.pressed=!0),b&P&&1!==a.which&&(b=Q),this.pressed&&this.allow&&(b&Q&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:L,srcEvent:a}))}});var sb={pointerdown:O,pointermove:P,pointerup:Q,pointercancel:R,pointerout:R},tb={2:J,3:K,4:L,5:M},ub="pointerdown",vb="pointermove pointerup pointercancel";a.MSPointerEvent&&(ub="MSPointerDown",vb="MSPointerMove MSPointerUp MSPointerCancel"),p(wb,ab,{handler:function(a){var b=this.store,c=!1,d=a.type.toLowerCase().replace("ms",""),e=sb[d],f=tb[a.pointerType]||a.pointerType,g=f==J,h=y(b,a.pointerId,"pointerId");e&O&&(0===a.button||g)?0>h&&(b.push(a),h=b.length-1):e&(Q|R)&&(c=!0),0>h||(b[h]=a,this.callback(this.manager,e,{pointers:b,changedPointers:[a],pointerType:f,srcEvent:a}),c&&b.splice(h,1))}});var xb={touchstart:O,touchmove:P,touchend:Q,touchcancel:R},yb="touchstart",zb="touchstart touchmove touchend touchcancel";p(Ab,ab,{handler:function(a){var b=xb[a.type];if(b===O&&(this.started=!0),this.started){var c=Bb.call(this,a,b);b&(Q|R)&&0===c[0].length-c[1].length&&(this.started=!1),this.callback(this.manager,b,{pointers:c[0],changedPointers:c[1],pointerType:J,srcEvent:a})}}});var Cb={touchstart:O,touchmove:P,touchend:Q,touchcancel:R},Db="touchstart touchmove touchend touchcancel";p(Eb,ab,{handler:function(a){var b=Cb[a.type],c=Fb.call(this,a,b);c&&this.callback(this.manager,b,{pointers:c[0],changedPointers:c[1],pointerType:J,srcEvent:a})}}),p(Gb,ab,{handler:function(a,b,c){var d=c.pointerType==J,e=c.pointerType==L;if(d)this.mouse.allow=!1;else if(e&&!this.mouse.allow)return;b&(Q|R)&&(this.mouse.allow=!0),this.callback(a,b,c)},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var Hb=B(f.style,"touchAction"),Ib=Hb!==d,Jb="compute",Kb="auto",Lb="manipulation",Mb="none",Nb="pan-x",Ob="pan-y";Pb.prototype={set:function(a){a==Jb&&(a=this.compute()),Ib&&(this.manager.element.style[Hb]=a),this.actions=a.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var a=[];return m(this.manager.recognizers,function(b){r(b.options.enable,[b])&&(a=a.concat(b.getTouchAction()))}),Qb(a.join(" "))},preventDefaults:function(a){if(!Ib){var b=a.srcEvent,c=a.offsetDirection;if(this.manager.session.prevented)return b.preventDefault(),void 0;var d=this.actions,e=w(d,Mb),f=w(d,Ob),g=w(d,Nb);return e||f&&c&X||g&&c&Y?this.preventSrc(b):void 0}},preventSrc:function(a){this.manager.session.prevented=!0,a.preventDefault()}};var Rb=1,Sb=2,Tb=4,Ub=8,Vb=Ub,Wb=16,Xb=32;Yb.prototype={defaults:{},set:function(a){return n(this.options,a),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(a){if(l(a,"recognizeWith",this))return this;var b=this.simultaneous;return a=_b(a,this),b[a.id]||(b[a.id]=a,a.recognizeWith(this)),this},dropRecognizeWith:function(a){return l(a,"dropRecognizeWith",this)?this:(a=_b(a,this),delete this.simultaneous[a.id],this)},requireFailure:function(a){if(l(a,"requireFailure",this))return this;var b=this.requireFail;return a=_b(a,this),-1===y(b,a)&&(b.push(a),a.requireFailure(this)),this},dropRequireFailure:function(a){if(l(a,"dropRequireFailure",this))return this;a=_b(a,this);var b=y(this.requireFail,a);return b>-1&&this.requireFail.splice(b,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(a){return!!this.simultaneous[a.id]},emit:function(a){function d(d){b.manager.emit(b.options.event+(d?Zb(c):""),a)}var b=this,c=this.state;Ub>c&&d(!0),d(),c>=Ub&&d(!0)},tryEmit:function(a){return this.canEmit()?this.emit(a):(this.state=Xb,void 0)},canEmit:function(){for(var a=0;a<this.requireFail.length;){if(!(this.requireFail[a].state&(Xb|Rb)))return!1;a++}return!0},recognize:function(a){var b=n({},a);return r(this.options.enable,[this,b])?(this.state&(Vb|Wb|Xb)&&(this.state=Rb),this.state=this.process(b),this.state&(Sb|Tb|Ub|Wb)&&this.tryEmit(b),void 0):(this.reset(),this.state=Xb,void 0)},process:function(){},getTouchAction:function(){},reset:function(){}},p(ac,Yb,{defaults:{pointers:1},attrTest:function(a){var b=this.options.pointers;return 0===b||a.pointers.length===b},process:function(a){var b=this.state,c=a.eventType,d=b&(Sb|Tb),e=this.attrTest(a);return d&&(c&R||!e)?b|Wb:d||e?c&Q?b|Ub:b&Sb?b|Tb:Sb:Xb}}),p(bc,ac,{defaults:{event:"pan",threshold:10,pointers:1,direction:Z},getTouchAction:function(){var a=this.options.direction,b=[];return a&X&&b.push(Ob),a&Y&&b.push(Nb),b},directionTest:function(a){var b=this.options,c=!0,d=a.distance,e=a.direction,f=a.deltaX,g=a.deltaY;return e&b.direction||(b.direction&X?(e=0===f?S:0>f?T:U,c=f!=this.pX,d=Math.abs(a.deltaX)):(e=0===g?S:0>g?V:W,c=g!=this.pY,d=Math.abs(a.deltaY))),a.direction=e,c&&d>b.threshold&&e&b.direction},attrTest:function(a){return ac.prototype.attrTest.call(this,a)&&(this.state&Sb||!(this.state&Sb)&&this.directionTest(a))},emit:function(a){this.pX=a.deltaX,this.pY=a.deltaY;var b=$b(a.direction);b&&this.manager.emit(this.options.event+b,a),this._super.emit.call(this,a)}}),p(cc,ac,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[Mb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.scale-1)>this.options.threshold||this.state&Sb)},emit:function(a){if(this._super.emit.call(this,a),1!==a.scale){var b=a.scale<1?"in":"out";this.manager.emit(this.options.event+b,a)}}}),p(dc,Yb,{defaults:{event:"press",pointers:1,time:500,threshold:5},getTouchAction:function(){return[Kb]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,e=a.deltaTime>b.time;if(this._input=a,!d||!c||a.eventType&(Q|R)&&!e)this.reset();else if(a.eventType&O)this.reset(),this._timer=k(function(){this.state=Vb,this.tryEmit()},b.time,this);else if(a.eventType&Q)return Vb;return Xb},reset:function(){clearTimeout(this._timer)},emit:function(a){this.state===Vb&&(a&&a.eventType&Q?this.manager.emit(this.options.event+"up",a):(this._input.timeStamp=j(),this.manager.emit(this.options.event,this._input)))}}),p(ec,ac,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[Mb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.rotation)>this.options.threshold||this.state&Sb)}}),p(fc,ac,{defaults:{event:"swipe",threshold:10,velocity:.65,direction:X|Y,pointers:1},getTouchAction:function(){return bc.prototype.getTouchAction.call(this)},attrTest:function(a){var c,b=this.options.direction;return b&(X|Y)?c=a.velocity:b&X?c=a.velocityX:b&Y&&(c=a.velocityY),this._super.attrTest.call(this,a)&&b&a.direction&&a.distance>this.options.threshold&&i(c)>this.options.velocity&&a.eventType&Q},emit:function(a){var b=$b(a.direction);b&&this.manager.emit(this.options.event+b,a),this.manager.emit(this.options.event,a)}}),p(gc,Yb,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:2,posThreshold:10},getTouchAction:function(){return[Lb]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,e=a.deltaTime<b.time;if(this.reset(),a.eventType&O&&0===this.count)return this.failTimeout();if(d&&e&&c){if(a.eventType!=Q)return this.failTimeout();var f=this.pTime?a.timeStamp-this.pTime<b.interval:!0,g=!this.pCenter||kb(this.pCenter,a.center)<b.posThreshold;this.pTime=a.timeStamp,this.pCenter=a.center,g&&f?this.count+=1:this.count=1,this._input=a;var h=this.count%b.taps;if(0===h)return this.hasRequireFailures()?(this._timer=k(function(){this.state=Vb,this.tryEmit()},b.interval,this),Sb):Vb}return Xb},failTimeout:function(){return this._timer=k(function(){this.state=Xb},this.options.interval,this),Xb},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==Vb&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),hc.VERSION="2.0.4",hc.defaults={domEvents:!1,touchAction:Jb,enable:!0,inputTarget:null,inputClass:null,preset:[[ec,{enable:!1}],[cc,{enable:!1},["rotate"]],[fc,{direction:X}],[bc,{direction:X},["swipe"]],[gc],[gc,{event:"doubletap",taps:2},["tap"]],[dc]],cssProps:{userSelect:"default",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};var ic=1,jc=2;kc.prototype={set:function(a){return n(this.options,a),a.touchAction&&this.touchAction.update(),a.inputTarget&&(this.input.destroy(),this.input.target=a.inputTarget,this.input.init()),this},stop:function(a){this.session.stopped=a?jc:ic},recognize:function(a){var b=this.session;if(!b.stopped){this.touchAction.preventDefaults(a);var c,d=this.recognizers,e=b.curRecognizer;(!e||e&&e.state&Vb)&&(e=b.curRecognizer=null);for(var f=0;f<d.length;)c=d[f],b.stopped===jc||e&&c!=e&&!c.canRecognizeWith(e)?c.reset():c.recognize(a),!e&&c.state&(Sb|Tb|Ub)&&(e=b.curRecognizer=c),f++}},get:function(a){if(a instanceof Yb)return a;for(var b=this.recognizers,c=0;c<b.length;c++)if(b[c].options.event==a)return b[c];return null},add:function(a){if(l(a,"add",this))return this;var b=this.get(a.options.event);return b&&this.remove(b),this.recognizers.push(a),a.manager=this,this.touchAction.update(),a},remove:function(a){if(l(a,"remove",this))return this;var b=this.recognizers;return a=this.get(a),b.splice(y(b,a),1),this.touchAction.update(),this},on:function(a,b){var c=this.handlers;return m(x(a),function(a){c[a]=c[a]||[],c[a].push(b)}),this},off:function(a,b){var c=this.handlers;return m(x(a),function(a){b?c[a].splice(y(c[a],b),1):delete c[a]}),this},emit:function(a,b){this.options.domEvents&&mc(a,b);var c=this.handlers[a]&&this.handlers[a].slice();if(c&&c.length){b.type=a,b.preventDefault=function(){b.srcEvent.preventDefault()};for(var d=0;d<c.length;)c[d](b),d++}},destroy:function(){this.element&&lc(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},n(hc,{INPUT_START:O,INPUT_MOVE:P,INPUT_END:Q,INPUT_CANCEL:R,STATE_POSSIBLE:Rb,STATE_BEGAN:Sb,STATE_CHANGED:Tb,STATE_ENDED:Ub,STATE_RECOGNIZED:Vb,STATE_CANCELLED:Wb,STATE_FAILED:Xb,DIRECTION_NONE:S,DIRECTION_LEFT:T,DIRECTION_RIGHT:U,DIRECTION_UP:V,DIRECTION_DOWN:W,DIRECTION_HORIZONTAL:X,DIRECTION_VERTICAL:Y,DIRECTION_ALL:Z,Manager:kc,Input:ab,TouchAction:Pb,TouchInput:Eb,MouseInput:rb,PointerEventInput:wb,TouchMouseInput:Gb,SingleTouchInput:Ab,Recognizer:Yb,AttrRecognizer:ac,Tap:gc,Pan:bc,Swipe:fc,Pinch:cc,Rotate:ec,Press:dc,on:t,off:u,each:m,merge:o,extend:n,inherit:p,bindFn:q,prefixed:B}),typeof define==g&&define.amd?define(function(){return hc}):"undefined"!=typeof module&&module.exports?module.exports=hc:a[c]=hc}(window,document,"Hammer");;(function(factory) {
234 if (typeof define === 'function' && define.amd) {
235 define(['jquery', 'hammerjs'], factory);
236 } else if (typeof exports === 'object') {
237 factory(require('jquery'), require('hammerjs'));
239 factory(jQuery, Hammer);
241 }(function($, Hammer) {
242 function hammerify(el, options) {
244 if(!$el.data("hammer")) {
245 $el.data("hammer", new Hammer($el[0], options));
249 $.fn.hammer = function(options) {
250 return this.each(function() {
251 hammerify(this, options);
255 // extend the emit method to also trigger jQuery events
256 Hammer.Manager.prototype.emit = (function(originalEmit) {
257 return function(type, data) {
258 originalEmit.call(this, type, data);
259 $(this.element).trigger({
264 })(Hammer.Manager.prototype.emit);
266 ;// Required for Meteor package, the use of window prevents export by Meteor
271 window.Materialize = {};
278 * https://github.com/ngryman/raf.js
280 * original requestAnimationFrame polyfill by Erik Möller
281 * inspired from paul_irish gist and post
283 * Copyright (c) 2013 ngryman
284 * Licensed under the MIT license.
288 vendors = ['webkit', 'moz'],
289 requestAnimationFrame = window.requestAnimationFrame,
290 cancelAnimationFrame = window.cancelAnimationFrame,
293 // try to un-prefix existing raf
294 while (--i >= 0 && !requestAnimationFrame) {
295 requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
296 cancelAnimationFrame = window[vendors[i] + 'CancelRequestAnimationFrame'];
299 // polyfill with setTimeout fallback
300 // heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
301 if (!requestAnimationFrame || !cancelAnimationFrame) {
302 requestAnimationFrame = function(callback) {
303 var now = +Date.now(),
304 nextTime = Math.max(lastTime + 16, now);
305 return setTimeout(function() {
306 callback(lastTime = nextTime);
310 cancelAnimationFrame = clearTimeout;
314 window.requestAnimationFrame = requestAnimationFrame;
315 window.cancelAnimationFrame = cancelAnimationFrame;
320 Materialize.guid = (function() {
322 return Math.floor((1 + Math.random()) * 0x10000)
327 return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
328 s4() + '-' + s4() + s4() + s4();
333 * Escapes hash from special characters
334 * @param {string} hash String returned from this.hash
337 Materialize.escapeHash = function(hash) {
338 return hash.replace( /(:|\.|\[|\]|,|=)/g, "\\$1" );
341 Materialize.elementOrParentIsFixed = function(element) {
342 var $element = $(element);
343 var $checkElements = $element.add($element.parents());
345 $checkElements.each(function(){
346 if ($(this).css("position") === "fixed") {
357 * @license https://raw.github.com/jashkenas/underscore/master/LICENSE
361 var getTime = (Date.now || function () {
362 return new Date().getTime();
367 * Returns a function, that, when invoked, will only be triggered at most once
368 * during a given window of time. Normally, the throttled function will run
369 * as much as it can, without ever going more than once per `wait` duration;
370 * but if you'd like to disable the execution on the leading edge, pass
371 * `{leading: false}`. To disable execution on the trailing edge, ditto.
372 * @license https://raw.github.com/jashkenas/underscore/master/LICENSE
373 * @param {function} func
374 * @param {number} wait
375 * @param {Object=} options
376 * @returns {Function}
378 Materialize.throttle = function(func, wait, options) {
379 var context, args, result;
382 options || (options = {});
383 var later = function () {
384 previous = options.leading === false ? 0 : getTime();
386 result = func.apply(context, args);
387 context = args = null;
391 if (!previous && options.leading === false) previous = now;
392 var remaining = wait - (now - previous);
395 if (remaining <= 0) {
396 clearTimeout(timeout);
399 result = func.apply(context, args);
400 context = args = null;
401 } else if (!timeout && options.trailing !== false) {
402 timeout = setTimeout(later, remaining);
409 // Velocity has conflicts when loaded with jQuery, this will check for it
410 // First, check if in noConflict mode
413 Vel = jQuery.Velocity;
420 $.fn.collapsible = function(options) {
422 accordion: undefined,
427 options = $.extend(defaults, options);
430 return this.each(function() {
434 var $panel_headers = $(this).find('> li > .collapsible-header');
436 var collapsible_type = $this.data("collapsible");
438 // Turn off any existing event handlers
439 $this.off('click.collapse', '> li > .collapsible-header');
440 $panel_headers.off('click.collapse');
448 function accordionOpen(object) {
449 $panel_headers = $this.find('> li > .collapsible-header');
450 if (object.hasClass('active')) {
451 object.parent().addClass('active');
454 object.parent().removeClass('active');
456 if (object.parent().hasClass('active')){
457 object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
460 object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
463 $panel_headers.not(object).removeClass('active').parent().removeClass('active');
465 // Close previously open accordion elements.
466 $panel_headers.not(object).parent().children('.collapsible-body').stop(true,false).each(function() {
467 if ($(this).is(':visible')) {
470 easing: "easeOutQuart",
474 $(this).css('height', '');
475 execCallbacks($(this).siblings('.collapsible-header'));
483 function expandableOpen(object) {
484 if (object.hasClass('active')) {
485 object.parent().addClass('active');
488 object.parent().removeClass('active');
490 if (object.parent().hasClass('active')){
491 object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
494 object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
498 // Open collapsible. object: .collapsible-header
499 function collapsibleOpen(object) {
500 if (options.accordion || collapsible_type === "accordion" || collapsible_type === undefined) { // Handle Accordion
501 accordionOpen(object);
502 } else { // Handle Expandables
503 expandableOpen(object);
506 execCallbacks(object);
510 function execCallbacks(object) {
511 if (object.hasClass('active')) {
512 if (typeof(options.onOpen) === "function") {
513 options.onOpen.call(this, object.parent());
516 if (typeof(options.onClose) === "function") {
517 options.onClose.call(this, object.parent());
523 * Check if object is children of panel header
524 * @param {Object} object Jquery object
525 * @return {Boolean} true if it is children
527 function isChildrenOfPanelHeader(object) {
529 var panelHeader = getPanelHeader(object);
531 return panelHeader.length > 0;
535 * Get panel header from a children element
536 * @param {Object} object Jquery object
537 * @return {Object} panel header object
539 function getPanelHeader(object) {
541 return object.closest('li > .collapsible-header');
544 /***** End Helper Functions *****/
548 // Add click handler to only direct collapsible header children
549 $this.on('click.collapse', '> li > .collapsible-header', function(e) {
550 var element = $(e.target);
552 if (isChildrenOfPanelHeader(element)) {
553 element = getPanelHeader(element);
556 element.toggleClass('active');
558 collapsibleOpen(element);
563 if (options.accordion || collapsible_type === "accordion" || collapsible_type === undefined) { // Handle Accordion
564 collapsibleOpen($panel_headers.filter('.active').first());
566 } else { // Handle Expandables
567 $panel_headers.filter('.active').each(function() {
568 collapsibleOpen($(this));
575 $(document).ready(function(){
576 $('.collapsible').collapsible();
578 }( jQuery ));;(function ($) {
580 // Add posibility to scroll to selected option
581 // usefull for select for example
582 $.fn.scrollTo = function(elem) {
583 $(this).scrollTop($(this).scrollTop() - $(this).offset().top + $(elem).offset().top);
587 $.fn.dropdown = function (options) {
591 constrainWidth: true, // Constrains width of dropdown to the activator
593 gutter: 0, // Spacing from edge
596 stopPropagation: false
600 if (options === "open") {
601 this.each(function() {
602 $(this).trigger('open');
608 if (options === "close") {
609 this.each(function() {
610 $(this).trigger('close');
615 this.each(function(){
616 var origin = $(this);
617 var curr_options = $.extend({}, defaults, options);
618 var isFocused = false;
621 var activates = $("#"+ origin.attr('data-activates'));
623 function updateOptions() {
624 if (origin.data('induration') !== undefined)
625 curr_options.inDuration = origin.data('induration');
626 if (origin.data('outduration') !== undefined)
627 curr_options.outDuration = origin.data('outduration');
628 if (origin.data('constrainwidth') !== undefined)
629 curr_options.constrainWidth = origin.data('constrainwidth');
630 if (origin.data('hover') !== undefined)
631 curr_options.hover = origin.data('hover');
632 if (origin.data('gutter') !== undefined)
633 curr_options.gutter = origin.data('gutter');
634 if (origin.data('beloworigin') !== undefined)
635 curr_options.belowOrigin = origin.data('beloworigin');
636 if (origin.data('alignment') !== undefined)
637 curr_options.alignment = origin.data('alignment');
638 if (origin.data('stoppropagation') !== undefined)
639 curr_options.stopPropagation = origin.data('stoppropagation');
644 // Attach dropdown to its activator
645 origin.after(activates);
648 Helper function to position and resize dropdown.
649 Used in hover and click handler.
651 function placeDropdown(eventType) {
652 // Check for simultaneous focus and click events.
653 if (eventType === 'focus') {
657 // Check html data attributes
660 // Set Dropdown state
661 activates.addClass('active');
662 origin.addClass('active');
665 if (curr_options.constrainWidth === true) {
666 activates.css('width', origin.outerWidth());
669 activates.css('white-space', 'nowrap');
672 // Offscreen detection
673 var windowHeight = window.innerHeight;
674 var originHeight = origin.innerHeight();
675 var offsetLeft = origin.offset().left;
676 var offsetTop = origin.offset().top - $(window).scrollTop();
677 var currAlignment = curr_options.alignment;
678 var gutterSpacing = 0;
679 var leftPosition = 0;
682 var verticalOffset = 0;
683 if (curr_options.belowOrigin === true) {
684 verticalOffset = originHeight;
687 // Check for scrolling positioned container.
688 var scrollYOffset = 0;
689 var scrollXOffset = 0;
690 var wrapper = origin.parent();
691 if (!wrapper.is('body')) {
692 if (wrapper[0].scrollHeight > wrapper[0].clientHeight) {
693 scrollYOffset = wrapper[0].scrollTop;
695 if (wrapper[0].scrollWidth > wrapper[0].clientWidth) {
696 scrollXOffset = wrapper[0].scrollLeft;
701 if (offsetLeft + activates.innerWidth() > $(window).width()) {
702 // Dropdown goes past screen on right, force right alignment
703 currAlignment = 'right';
705 } else if (offsetLeft - activates.innerWidth() + origin.innerWidth() < 0) {
706 // Dropdown goes past screen on left, force left alignment
707 currAlignment = 'left';
709 // Vertical bottom offscreen detection
710 if (offsetTop + activates.innerHeight() > windowHeight) {
711 // If going upwards still goes offscreen, just crop height of dropdown.
712 if (offsetTop + originHeight - activates.innerHeight() < 0) {
713 var adjustedHeight = windowHeight - offsetTop - verticalOffset;
714 activates.css('max-height', adjustedHeight);
717 if (!verticalOffset) {
718 verticalOffset += originHeight;
720 verticalOffset -= activates.innerHeight();
724 // Handle edge alignment
725 if (currAlignment === 'left') {
726 gutterSpacing = curr_options.gutter;
727 leftPosition = origin.position().left + gutterSpacing;
729 else if (currAlignment === 'right') {
730 var offsetRight = origin.position().left + origin.outerWidth() - activates.outerWidth();
731 gutterSpacing = -curr_options.gutter;
732 leftPosition = offsetRight + gutterSpacing;
737 position: 'absolute',
738 top: origin.position().top + verticalOffset + scrollYOffset,
739 left: leftPosition + scrollXOffset
744 activates.stop(true, true).css('opacity', 0)
747 duration: curr_options.inDuration,
748 easing: 'easeOutCubic',
749 complete: function() {
750 $(this).css('height', '');
753 .animate( {opacity: 1}, {queue: false, duration: curr_options.inDuration, easing: 'easeOutSine'});
755 // Add click close handler to document
756 $(document).bind('click.'+ activates.attr('id') + ' touchstart.' + activates.attr('id'), function (e) {
757 if (!activates.is(e.target) && !origin.is(e.target) && (!origin.find(e.target).length) ) {
759 $(document).unbind('click.'+ activates.attr('id') + ' touchstart.' + activates.attr('id'));
764 function hideDropdown() {
765 // Check for simultaneous focus and click events.
767 activates.fadeOut(curr_options.outDuration);
768 activates.removeClass('active');
769 origin.removeClass('active');
770 $(document).unbind('click.'+ activates.attr('id') + ' touchstart.' + activates.attr('id'));
771 setTimeout(function() { activates.css('max-height', ''); }, curr_options.outDuration);
775 if (curr_options.hover) {
777 origin.unbind('click.' + origin.attr('id'));
778 // Hover handler to show dropdown
779 origin.on('mouseenter', function(e){ // Mouse over
780 if (open === false) {
785 origin.on('mouseleave', function(e){
786 // If hover on origin then to something other than dropdown content, then close
787 var toEl = e.toElement || e.relatedTarget; // added browser compatibility for target element
788 if(!$(toEl).closest('.dropdown-content').is(activates)) {
789 activates.stop(true, true);
795 activates.on('mouseleave', function(e){ // Mouse out
796 var toEl = e.toElement || e.relatedTarget;
797 if(!$(toEl).closest('.dropdown-button').is(origin)) {
798 activates.stop(true, true);
806 // Click handler to show dropdown
807 origin.unbind('click.' + origin.attr('id'));
808 origin.bind('click.'+origin.attr('id'), function(e){
810 if ( origin[0] == e.currentTarget &&
811 !origin.hasClass('active') &&
812 ($(e.target).closest('.dropdown-content').length === 0)) {
813 e.preventDefault(); // Prevents button click from moving window
814 if (curr_options.stopPropagation) {
817 placeDropdown('click');
819 // If origin is clicked and menu is open, close menu
820 else if (origin.hasClass('active')) {
822 $(document).unbind('click.'+ activates.attr('id') + ' touchstart.' + activates.attr('id'));
829 // Listen to open and close event - useful for select component
830 origin.on('open', function(e, eventType) {
831 placeDropdown(eventType);
833 origin.on('close', hideDropdown);
837 }; // End dropdown plugin
839 $(document).ready(function(){
840 $('.dropdown-button').dropdown();
846 _generateID = function() {
848 return 'materialize-modal-overlay-' + _lastID;
852 init : function(options) {
865 options = $.extend(defaults, options);
867 return this.each(function() {
868 var $modal = $(this);
869 var modal_id = $(this).attr("id") || '#' + $(this).data('target');
871 var closeModal = function() {
872 var overlayID = $modal.data('overlay-id');
873 var $overlay = $('#' + overlayID);
874 $modal.removeClass('open');
882 $modal.find('.modal-close').off('click.close');
883 $(document).off('keyup.modal' + overlayID);
885 $overlay.velocity( { opacity: 0}, {duration: options.outDuration, queue: false, ease: "easeOutQuart"});
888 // Define Bottom Sheet animation
889 var exitVelocityOptions = {
890 duration: options.outDuration,
892 ease: "easeOutCubic",
893 // Handle modal ready callback
894 complete: function() {
895 $(this).css({display:"none"});
897 // Call complete callback
898 if (typeof(options.complete) === "function") {
899 options.complete.call(this, $modal);
905 if ($modal.hasClass('bottom-sheet')) {
906 $modal.velocity({bottom: "-100%", opacity: 0}, exitVelocityOptions);
910 { top: options.startingTop, opacity: 0, scaleX: 0.7},
916 var openModal = function($trigger) {
917 var $body = $('body');
918 var oldWidth = $body.innerWidth();
919 $body.css('overflow', 'hidden');
920 $body.width(oldWidth);
922 if ($modal.hasClass('open')) {
926 var overlayID = _generateID();
927 var $overlay = $('<div class="modal-overlay"></div>');
930 // Store a reference of the overlay
931 $overlay.attr('id', overlayID).css('z-index', 1000 + lStack * 2);
932 $modal.data('overlay-id', overlayID).css('z-index', 1000 + lStack * 2 + 1);
933 $modal.addClass('open');
935 $("body").append($overlay);
937 if (options.dismissible) {
938 $overlay.click(function() {
942 $(document).on('keyup.modal' + overlayID, function(e) {
943 if (e.keyCode === 27) { // ESC key
949 $modal.find(".modal-close").on('click.close', function(e) {
953 $overlay.css({ display : "block", opacity : 0 });
960 $overlay.velocity({opacity: options.opacity}, {duration: options.inDuration, queue: false, ease: "easeOutCubic"});
961 $modal.data('associated-overlay', $overlay[0]);
963 // Define Bottom Sheet animation
964 var enterVelocityOptions = {
965 duration: options.inDuration,
967 ease: "easeOutCubic",
968 // Handle modal ready callback
969 complete: function() {
970 if (typeof(options.ready) === "function") {
971 options.ready.call(this, $modal, $trigger);
975 if ($modal.hasClass('bottom-sheet')) {
976 $modal.velocity({bottom: "0", opacity: 1}, enterVelocityOptions);
979 $.Velocity.hook($modal, "scaleX", 0.7);
980 $modal.css({ top: options.startingTop });
981 $modal.velocity({top: options.endingTop, opacity: 1, scaleX: '1'}, enterVelocityOptions);
987 $(document).off('click.modalTrigger', 'a[href="#' + modal_id + '"], [data-target="' + modal_id + '"]');
988 $(this).off('openModal');
989 $(this).off('closeModal');
992 $(document).on('click.modalTrigger', 'a[href="#' + modal_id + '"], [data-target="' + modal_id + '"]', function(e) {
993 options.startingTop = ($(this).offset().top - $(window).scrollTop()) /1.15;
996 }); // done set on click
998 $(this).on('openModal', function() {
999 var modal_id = $(this).attr("href") || '#' + $(this).data('target');
1003 $(this).on('closeModal', function() {
1009 $(this).trigger('openModal');
1011 close : function() {
1012 $(this).trigger('closeModal');
1016 $.fn.modal = function(methodOrOptions) {
1017 if ( methods[methodOrOptions] ) {
1018 return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
1019 } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
1020 // Default to "init"
1021 return methods.init.apply( this, arguments );
1023 $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.modal' );
1029 $.fn.materialbox = function () {
1031 return this.each(function() {
1033 if ($(this).hasClass('initialized')) {
1037 $(this).addClass('initialized');
1039 var overlayActive = false;
1040 var doneAnimating = true;
1041 var inDuration = 275;
1042 var outDuration = 200;
1043 var origin = $(this);
1044 var placeholder = $('<div></div>').addClass('material-placeholder');
1045 var originalWidth = 0;
1046 var originalHeight = 0;
1047 var ancestorsChanged;
1049 origin.wrap(placeholder);
1052 origin.on('click', function(){
1053 var placeholder = origin.parent('.material-placeholder');
1054 var windowWidth = window.innerWidth;
1055 var windowHeight = window.innerHeight;
1056 var originalWidth = origin.width();
1057 var originalHeight = origin.height();
1060 // If already modal, return to original
1061 if (doneAnimating === false) {
1065 else if (overlayActive && doneAnimating===true) {
1072 doneAnimating = false;
1073 origin.addClass('active');
1074 overlayActive = true;
1076 // Set positioning for placeholder
1078 width: placeholder[0].getBoundingClientRect().width,
1079 height: placeholder[0].getBoundingClientRect().height,
1080 position: 'relative',
1085 // Find ancestor with overflow: hidden; and remove it
1086 ancestorsChanged = undefined;
1087 ancestor = placeholder[0].parentNode;
1089 while (ancestor !== null && !$(ancestor).is(document)) {
1090 var curr = $(ancestor);
1091 if (curr.css('overflow') !== 'visible') {
1092 curr.css('overflow', 'visible');
1093 if (ancestorsChanged === undefined) {
1094 ancestorsChanged = curr;
1097 ancestorsChanged = ancestorsChanged.add(curr);
1100 ancestor = ancestor.parentNode;
1103 // Set css on origin
1105 position: 'absolute',
1107 'will-change': 'left, top, width, height'
1109 .data('width', originalWidth)
1110 .data('height', originalHeight);
1113 var overlay = $('<div id="materialbox-overlay"></div>')
1118 if (doneAnimating === true)
1122 // Put before in origin image to preserve z-index layering.
1123 origin.before(overlay);
1125 // Set dimensions if needed
1126 var overlayOffset = overlay[0].getBoundingClientRect();
1129 height: windowHeight,
1130 left: -1 * overlayOffset.left,
1131 top: -1 * overlayOffset.top
1135 overlay.velocity({opacity: 1},
1136 {duration: inDuration, queue: false, easing: 'easeOutQuad'} );
1138 // Add and animate caption if it exists
1139 if (origin.data('caption') !== "") {
1140 var $photo_caption = $('<div class="materialbox-caption"></div>');
1141 $photo_caption.text(origin.data('caption'));
1142 $('body').append($photo_caption);
1143 $photo_caption.css({ "display": "inline" });
1144 $photo_caption.velocity({opacity: 1}, {duration: inDuration, queue: false, easing: 'easeOutQuad'});
1149 var widthPercent = originalWidth / windowWidth;
1150 var heightPercent = originalHeight / windowHeight;
1154 if (widthPercent > heightPercent) {
1155 ratio = originalHeight / originalWidth;
1156 newWidth = windowWidth * 0.9;
1157 newHeight = windowWidth * 0.9 * ratio;
1160 ratio = originalWidth / originalHeight;
1161 newWidth = (windowHeight * 0.9) * ratio;
1162 newHeight = windowHeight * 0.9;
1165 // Animate image + set z-index
1166 if(origin.hasClass('responsive-img')) {
1167 origin.velocity({'max-width': newWidth, 'width': originalWidth}, {duration: 0, queue: false,
1168 complete: function(){
1169 origin.css({left: 0, top: 0})
1174 left: $(document).scrollLeft() + windowWidth/2 - origin.parent('.material-placeholder').offset().left - newWidth/2,
1175 top: $(document).scrollTop() + windowHeight/2 - origin.parent('.material-placeholder').offset().top - newHeight/ 2
1178 duration: inDuration,
1180 easing: 'easeOutQuad',
1181 complete: function(){doneAnimating = true;}
1188 origin.css('left', 0)
1194 left: $(document).scrollLeft() + windowWidth/2 - origin.parent('.material-placeholder').offset().left - newWidth/2,
1195 top: $(document).scrollTop() + windowHeight/2 - origin.parent('.material-placeholder').offset().top - newHeight/ 2
1198 duration: inDuration,
1200 easing: 'easeOutQuad',
1201 complete: function(){doneAnimating = true;}
1206 }); // End origin on click
1210 $(window).scroll(function() {
1211 if (overlayActive) {
1217 $(document).keyup(function(e) {
1219 if (e.keyCode === 27 && doneAnimating === true) { // ESC key
1220 if (overlayActive) {
1227 // This function returns the modaled image to the original spot
1228 function returnToOriginal() {
1230 doneAnimating = false;
1232 var placeholder = origin.parent('.material-placeholder');
1233 var windowWidth = window.innerWidth;
1234 var windowHeight = window.innerHeight;
1235 var originalWidth = origin.data('width');
1236 var originalHeight = origin.data('height');
1238 origin.velocity("stop", true);
1239 $('#materialbox-overlay').velocity("stop", true);
1240 $('.materialbox-caption').velocity("stop", true);
1243 $('#materialbox-overlay').velocity({opacity: 0}, {
1244 duration: outDuration, // Delay prevents animation overlapping
1245 queue: false, easing: 'easeOutQuad',
1246 complete: function(){
1248 overlayActive = false;
1256 width: originalWidth,
1257 height: originalHeight,
1262 duration: outDuration,
1263 queue: false, easing: 'easeOutQuad'
1267 // Remove Caption + reset css settings on image
1268 $('.materialbox-caption').velocity({opacity: 0}, {
1269 duration: outDuration, // Delay prevents animation overlapping
1270 queue: false, easing: 'easeOutQuad',
1271 complete: function(){
1292 origin.removeClass('active');
1293 doneAnimating = true;
1296 // Remove overflow overrides on ancestors
1297 if (ancestorsChanged) {
1298 ancestorsChanged.css('overflow', '');
1307 $(document).ready(function(){
1308 $('.materialboxed').materialbox();
1314 $.fn.parallax = function () {
1315 var window_width = $(window).width();
1317 return this.each(function(i) {
1318 var $this = $(this);
1319 $this.addClass('parallax');
1321 function updateParallax(initial) {
1322 var container_height;
1323 if (window_width < 601) {
1324 container_height = ($this.height() > 0) ? $this.height() : $this.children("img").height();
1327 container_height = ($this.height() > 0) ? $this.height() : 500;
1329 var $img = $this.children("img").first();
1330 var img_height = $img.height();
1331 var parallax_dist = img_height - container_height;
1332 var bottom = $this.offset().top + container_height;
1333 var top = $this.offset().top;
1334 var scrollTop = $(window).scrollTop();
1335 var windowHeight = window.innerHeight;
1336 var windowBottom = scrollTop + windowHeight;
1337 var percentScrolled = (windowBottom - top) / (container_height + windowHeight);
1338 var parallax = Math.round((parallax_dist * percentScrolled));
1341 $img.css('display', 'block');
1343 if ((bottom > scrollTop) && (top < (scrollTop + windowHeight))) {
1344 $img.css('transform', "translate3D(-50%," + parallax + "px, 0)");
1349 // Wait for image load
1350 $this.children("img").one("load", function() {
1351 updateParallax(true);
1352 }).each(function() {
1353 if (this.complete) $(this).trigger("load");
1356 $(window).scroll(function() {
1357 window_width = $(window).width();
1358 updateParallax(false);
1361 $(window).resize(function() {
1362 window_width = $(window).width();
1363 updateParallax(false);
1373 init : function(options) {
1377 responsiveThreshold: Infinity, // breakpoint for swipeable
1379 options = $.extend(defaults, options);
1381 return this.each(function() {
1383 // For each set of tabs, we want to keep track of
1384 // which tab is active and its associated content
1385 var $this = $(this),
1386 window_width = $(window).width();
1388 var $active, $content, $links = $this.find('li.tab a'),
1389 $tabs_width = $this.width(),
1390 $tabs_content = $(),
1392 $tab_width = Math.max($tabs_width, $this[0].scrollWidth) / $links.length,
1394 index = prev_index = 0,
1400 // Finds right attribute for indicator based on active tab.
1401 // el: jQuery Object
1402 var calcRightPos = function(el) {
1403 return $tabs_width - el.position().left - el.outerWidth() - $this.scrollLeft();
1406 // Finds left attribute for indicator based on active tab.
1407 // el: jQuery Object
1408 var calcLeftPos = function(el) {
1409 return el.position().left + $this.scrollLeft();
1412 // Animates Indicator to active tab.
1413 // prev_index: Number
1414 var animateIndicator = function(prev_index) {
1415 if ((index - prev_index) >= 0) {
1416 $indicator.velocity({"right": calcRightPos($active) }, { duration: transition, queue: false, easing: 'easeOutQuad'});
1417 $indicator.velocity({"left": calcLeftPos($active) }, {duration: transition, queue: false, easing: 'easeOutQuad', delay: 90});
1420 $indicator.velocity({"left": calcLeftPos($active) }, { duration: transition, queue: false, easing: 'easeOutQuad'});
1421 $indicator.velocity({"right": calcRightPos($active) }, {duration: transition, queue: false, easing: 'easeOutQuad', delay: 90});
1425 // Change swipeable according to responsive threshold
1426 if (options.swipeable) {
1427 if (window_width > options.responsiveThreshold) {
1428 options.swipeable = false;
1433 // If the location.hash matches one of the links, use that as the active tab.
1434 $active = $($links.filter('[href="'+location.hash+'"]'));
1436 // If no match is found, use the first link or any with class 'active' as the initial active tab.
1437 if ($active.length === 0) {
1438 $active = $(this).find('li.tab a.active').first();
1440 if ($active.length === 0) {
1441 $active = $(this).find('li.tab a').first();
1444 $active.addClass('active');
1445 index = $links.index($active);
1450 if ($active[0] !== undefined) {
1451 $content = $($active[0].hash);
1452 $content.addClass('active');
1455 // append indicator then set indicator width to tab width
1456 if (!$this.find('.indicator').length) {
1457 $this.append('<div class="indicator"></div>');
1459 $indicator = $this.find('.indicator');
1461 // we make sure that the indicator is at the end of the tabs
1462 $this.append($indicator);
1464 if ($this.is(":visible")) {
1465 // $indicator.css({"right": $tabs_width - ((index + 1) * $tab_width)});
1466 // $indicator.css({"left": index * $tab_width});
1467 setTimeout(function() {
1468 $indicator.css({"right": calcRightPos($active) });
1469 $indicator.css({"left": calcLeftPos($active) });
1472 $(window).resize(function () {
1473 $tabs_width = $this.width();
1474 $tab_width = Math.max($tabs_width, $this[0].scrollWidth) / $links.length;
1478 if ($tab_width !== 0 && $tabs_width !== 0) {
1479 $indicator.css({"right": calcRightPos($active) });
1480 $indicator.css({"left": calcLeftPos($active) });
1484 // Initialize Tabs Content.
1485 if (options.swipeable) {
1486 // TODO: Duplicate calls with swipeable? handle multiple div wrapping.
1487 $links.each(function () {
1488 var $curr_content = $(Materialize.escapeHash(this.hash));
1489 $curr_content.addClass('carousel-item');
1490 $tabs_content = $tabs_content.add($curr_content);
1492 $tabs_wrapper = $tabs_content.wrapAll('<div class="tabs-content carousel"></div>');
1493 $tabs_content.css('display', '');
1494 $('.tabs-content.carousel').carousel({
1497 onCycleTo: function(item) {
1499 var prev_index = index;
1500 index = $tabs_wrapper.index(item);
1501 $active = $links.eq(index);
1502 animateIndicator(prev_index);
1507 // Hide the remaining content
1508 $links.not($active).each(function () {
1509 $(Materialize.escapeHash(this.hash)).hide();
1514 // Bind the click event handler
1515 $this.on('click', 'a', function(e) {
1516 if ($(this).parent().hasClass('disabled')) {
1521 // Act as regular link if target attribute is specified.
1522 if (!!$(this).attr("target")) {
1527 $tabs_width = $this.width();
1528 $tab_width = Math.max($tabs_width, $this[0].scrollWidth) / $links.length;
1530 // Make the old tab inactive.
1531 $active.removeClass('active');
1532 var $oldContent = $content
1534 // Update the variables with the new link and content
1536 $content = $(Materialize.escapeHash(this.hash));
1537 $links = $this.find('li.tab a');
1538 var activeRect = $active.position();
1540 // Make the tab active.
1541 $active.addClass('active');
1543 index = $links.index($(this));
1547 // Change url to current tab
1548 // window.location.hash = $active.attr('href');
1551 if (options.swipeable) {
1552 if ($tabs_content.length) {
1553 $tabs_content.carousel('set', index);
1556 if ($content !== undefined) {
1558 $content.addClass('active');
1559 if (typeof(options.onShow) === "function") {
1560 options.onShow.call(this, $content);
1564 if ($oldContent !== undefined &&
1565 !$oldContent.is($content)) {
1567 $oldContent.removeClass('active');
1571 // Reset clicked state
1572 clickedTimeout = setTimeout(function(){ clicked = false; }, transition);
1575 animateIndicator(prev_index);
1577 // Prevent the anchor's default click action
1583 select_tab : function( id ) {
1584 this.find('a[href="#' + id + '"]').trigger('click');
1588 $.fn.tabs = function(methodOrOptions) {
1589 if ( methods[methodOrOptions] ) {
1590 return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
1591 } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
1592 // Default to "init"
1593 return methods.init.apply( this, arguments );
1595 $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tabs' );
1599 $(document).ready(function(){
1600 $('ul.tabs').tabs();
1604 $.fn.tooltip = function (options) {
1616 // Remove tooltip from the activator
1617 if (options === "remove") {
1618 this.each(function() {
1619 $('#' + $(this).attr('data-tooltip-id')).remove();
1620 $(this).off('mouseenter.tooltip mouseleave.tooltip');
1625 options = $.extend(defaults, options);
1627 return this.each(function() {
1628 var tooltipId = Materialize.guid();
1629 var origin = $(this);
1631 // Destroy old tooltip
1632 if (origin.attr('data-tooltip-id')) {
1633 $('#' + origin.attr('data-tooltip-id')).remove();
1636 origin.attr('data-tooltip-id', tooltipId);
1645 var setAttributes = function() {
1646 allowHtml = origin.attr('data-html') ? origin.attr('data-html') === 'true' : options.html;
1647 tooltipDelay = origin.attr('data-delay');
1648 tooltipDelay = (tooltipDelay === undefined || tooltipDelay === '') ?
1649 options.delay : tooltipDelay;
1650 tooltipPosition = origin.attr('data-position');
1651 tooltipPosition = (tooltipPosition === undefined || tooltipPosition === '') ?
1652 options.position : tooltipPosition;
1653 tooltipText = origin.attr('data-tooltip');
1654 tooltipText = (tooltipText === undefined || tooltipText === '') ?
1655 options.tooltip : tooltipText;
1659 var renderTooltipEl = function() {
1660 var tooltip = $('<div class="material-tooltip"></div>');
1664 tooltipText = $('<span></span>').html(tooltipText);
1666 tooltipText = $('<span></span>').text(tooltipText);
1670 tooltip.append(tooltipText)
1671 .appendTo($('body'))
1672 .attr('id', tooltipId);
1675 backdrop = $('<div class="backdrop"></div>');
1676 backdrop.appendTo(tooltip);
1679 tooltipEl = renderTooltipEl();
1681 // Destroy previously binded events
1682 origin.off('mouseenter.tooltip mouseleave.tooltip');
1684 var started = false, timeoutRef;
1685 origin.on({'mouseenter.tooltip': function(e) {
1686 var showTooltip = function() {
1689 tooltipEl.velocity('stop');
1690 backdrop.velocity('stop');
1691 tooltipEl.css({ visibility: 'visible', left: '0px', top: '0px' });
1693 // Tooltip positioning
1694 var originWidth = origin.outerWidth();
1695 var originHeight = origin.outerHeight();
1696 var tooltipHeight = tooltipEl.outerHeight();
1697 var tooltipWidth = tooltipEl.outerWidth();
1698 var tooltipVerticalMovement = '0px';
1699 var tooltipHorizontalMovement = '0px';
1700 var backdropOffsetWidth = backdrop[0].offsetWidth;
1701 var backdropOffsetHeight = backdrop[0].offsetHeight;
1702 var scaleXFactor = 8;
1703 var scaleYFactor = 8;
1704 var scaleFactor = 0;
1705 var targetTop, targetLeft, newCoordinates;
1707 if (tooltipPosition === "top") {
1709 targetTop = origin.offset().top - tooltipHeight - margin;
1710 targetLeft = origin.offset().left + originWidth/2 - tooltipWidth/2;
1711 newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
1712 tooltipVerticalMovement = '-10px';
1716 borderRadius: '14px 14px 0 0',
1717 transformOrigin: '50% 100%',
1718 marginTop: tooltipHeight,
1719 marginLeft: (tooltipWidth/2) - (backdropOffsetWidth/2)
1723 else if (tooltipPosition === "left") {
1724 targetTop = origin.offset().top + originHeight/2 - tooltipHeight/2;
1725 targetLeft = origin.offset().left - tooltipWidth - margin;
1726 newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
1728 tooltipHorizontalMovement = '-10px';
1734 borderRadius: '14px 0 0 14px',
1735 transformOrigin: '95% 50%',
1736 marginTop: tooltipHeight/2,
1737 marginLeft: tooltipWidth
1741 else if (tooltipPosition === "right") {
1742 targetTop = origin.offset().top + originHeight/2 - tooltipHeight/2;
1743 targetLeft = origin.offset().left + originWidth + margin;
1744 newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
1746 tooltipHorizontalMovement = '+10px';
1752 borderRadius: '0 14px 14px 0',
1753 transformOrigin: '5% 50%',
1754 marginTop: tooltipHeight/2,
1760 targetTop = origin.offset().top + origin.outerHeight() + margin;
1761 targetLeft = origin.offset().left + originWidth/2 - tooltipWidth/2;
1762 newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
1763 tooltipVerticalMovement = '+10px';
1767 marginLeft: (tooltipWidth/2) - (backdropOffsetWidth/2)
1771 // Set tooptip css placement
1773 top: newCoordinates.y,
1774 left: newCoordinates.x
1777 // Calculate Scale to fill
1778 scaleXFactor = Math.SQRT2 * tooltipWidth / parseInt(backdropOffsetWidth);
1779 scaleYFactor = Math.SQRT2 * tooltipHeight / parseInt(backdropOffsetHeight);
1780 scaleFactor = Math.max(scaleXFactor, scaleYFactor);
1782 tooltipEl.velocity({ translateY: tooltipVerticalMovement, translateX: tooltipHorizontalMovement}, { duration: 350, queue: false })
1783 .velocity({opacity: 1}, {duration: 300, delay: 50, queue: false});
1784 backdrop.css({ visibility: 'visible' })
1785 .velocity({opacity:1},{duration: 55, delay: 0, queue: false})
1786 .velocity({scaleX: scaleFactor, scaleY: scaleFactor}, {duration: 300, delay: 0, queue: false, easing: 'easeInOutQuad'});
1789 timeoutRef = setTimeout(showTooltip, tooltipDelay); // End Interval
1793 'mouseleave.tooltip': function(){
1796 clearTimeout(timeoutRef);
1799 setTimeout(function() {
1800 if (started !== true) {
1801 tooltipEl.velocity({
1802 opacity: 0, translateY: 0, translateX: 0}, { duration: 225, queue: false});
1803 backdrop.velocity({opacity: 0, scaleX: 1, scaleY: 1}, {
1806 complete: function(){
1807 backdrop.css({ visibility: 'hidden' });
1808 tooltipEl.css({ visibility: 'hidden' });
1818 var repositionWithinScreen = function(x, y, width, height) {
1824 } else if (newX + width > window.innerWidth) {
1825 newX -= newX + width - window.innerWidth;
1830 } else if (newY + height > window.innerHeight + $(window).scrollTop) {
1831 newY -= newY + height - window.innerHeight;
1834 return {x: newX, y: newY};
1837 $(document).ready(function(){
1838 $('.tooltipped').tooltip();
1843 * http://fian.my.id/Waves
1845 * Copyright 2014 Alfiana E. Sibuea and other contributors
1846 * Released under the MIT license
1847 * https://github.com/fians/Waves/blob/master/LICENSE
1850 ;(function(window) {
1853 var Waves = Waves || {};
1854 var $$ = document.querySelectorAll.bind(document);
1856 // Find exact position of element
1857 function isWindow(obj) {
1858 return obj !== null && obj === obj.window;
1861 function getWindow(elem) {
1862 return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView;
1865 function offset(elem) {
1867 box = {top: 0, left: 0},
1868 doc = elem && elem.ownerDocument;
1870 docElem = doc.documentElement;
1872 if (typeof elem.getBoundingClientRect !== typeof undefined) {
1873 box = elem.getBoundingClientRect();
1875 win = getWindow(doc);
1877 top: box.top + win.pageYOffset - docElem.clientTop,
1878 left: box.left + win.pageXOffset - docElem.clientLeft
1882 function convertStyle(obj) {
1885 for (var a in obj) {
1886 if (obj.hasOwnProperty(a)) {
1887 style += (a + ':' + obj[a] + ';');
1899 show: function(e, element) {
1901 // Disable right click
1902 if (e.button === 2) {
1906 var el = element || this;
1909 var ripple = document.createElement('div');
1910 ripple.className = 'waves-ripple';
1911 el.appendChild(ripple);
1913 // Get click coordinate and element witdh
1914 var pos = offset(el);
1915 var relativeY = (e.pageY - pos.top);
1916 var relativeX = (e.pageX - pos.left);
1917 var scale = 'scale('+((el.clientWidth / 100) * 10)+')';
1919 // Support for touch devices
1920 if ('touches' in e) {
1921 relativeY = (e.touches[0].pageY - pos.top);
1922 relativeX = (e.touches[0].pageX - pos.left);
1925 // Attach data to element
1926 ripple.setAttribute('data-hold', Date.now());
1927 ripple.setAttribute('data-scale', scale);
1928 ripple.setAttribute('data-x', relativeX);
1929 ripple.setAttribute('data-y', relativeY);
1931 // Set ripple position
1933 'top': relativeY+'px',
1934 'left': relativeX+'px'
1937 ripple.className = ripple.className + ' waves-notransition';
1938 ripple.setAttribute('style', convertStyle(rippleStyle));
1939 ripple.className = ripple.className.replace('waves-notransition', '');
1942 rippleStyle['-webkit-transform'] = scale;
1943 rippleStyle['-moz-transform'] = scale;
1944 rippleStyle['-ms-transform'] = scale;
1945 rippleStyle['-o-transform'] = scale;
1946 rippleStyle.transform = scale;
1947 rippleStyle.opacity = '1';
1949 rippleStyle['-webkit-transition-duration'] = Effect.duration + 'ms';
1950 rippleStyle['-moz-transition-duration'] = Effect.duration + 'ms';
1951 rippleStyle['-o-transition-duration'] = Effect.duration + 'ms';
1952 rippleStyle['transition-duration'] = Effect.duration + 'ms';
1954 rippleStyle['-webkit-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)';
1955 rippleStyle['-moz-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)';
1956 rippleStyle['-o-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)';
1957 rippleStyle['transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)';
1959 ripple.setAttribute('style', convertStyle(rippleStyle));
1963 TouchHandler.touchup(e);
1966 var width = el.clientWidth * 1.4;
1970 var ripples = el.getElementsByClassName('waves-ripple');
1971 if (ripples.length > 0) {
1972 ripple = ripples[ripples.length - 1];
1977 var relativeX = ripple.getAttribute('data-x');
1978 var relativeY = ripple.getAttribute('data-y');
1979 var scale = ripple.getAttribute('data-scale');
1981 // Get delay beetween mousedown and mouse leave
1982 var diff = Date.now() - Number(ripple.getAttribute('data-hold'));
1983 var delay = 350 - diff;
1989 // Fade out ripple after delay
1990 setTimeout(function() {
1992 'top': relativeY+'px',
1993 'left': relativeX+'px',
1997 '-webkit-transition-duration': Effect.duration + 'ms',
1998 '-moz-transition-duration': Effect.duration + 'ms',
1999 '-o-transition-duration': Effect.duration + 'ms',
2000 'transition-duration': Effect.duration + 'ms',
2001 '-webkit-transform': scale,
2002 '-moz-transform': scale,
2003 '-ms-transform': scale,
2004 '-o-transform': scale,
2008 ripple.setAttribute('style', convertStyle(style));
2010 setTimeout(function() {
2012 el.removeChild(ripple);
2016 }, Effect.duration);
2020 // Little hack to make <input> can perform waves effect
2021 wrapInput: function(elements) {
2022 for (var a = 0; a < elements.length; a++) {
2023 var el = elements[a];
2025 if (el.tagName.toLowerCase() === 'input') {
2026 var parent = el.parentNode;
2028 // If input already have parent just pass through
2029 if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) {
2033 // Put element class and style to the specified parent
2034 var wrapper = document.createElement('i');
2035 wrapper.className = el.className + ' waves-input-wrapper';
2037 var elementStyle = el.getAttribute('style');
2039 if (!elementStyle) {
2043 wrapper.setAttribute('style', elementStyle);
2045 el.className = 'waves-button-input';
2046 el.removeAttribute('style');
2048 // Put element as child
2049 parent.replaceChild(wrapper, el);
2050 wrapper.appendChild(el);
2058 * Disable mousedown event for 500ms during and after touch
2060 var TouchHandler = {
2061 /* uses an integer rather than bool so there's no issues with
2062 * needing to clear timeouts if another touch event occurred
2063 * within the 500ms. Cannot mouseup between touchstart and
2064 * touchend, nor in the 500ms after touchend. */
2066 allowEvent: function(e) {
2069 if (e.type === 'touchstart') {
2070 TouchHandler.touches += 1; //push
2071 } else if (e.type === 'touchend' || e.type === 'touchcancel') {
2072 setTimeout(function() {
2073 if (TouchHandler.touches > 0) {
2074 TouchHandler.touches -= 1; //pop after 500ms
2077 } else if (e.type === 'mousedown' && TouchHandler.touches > 0) {
2083 touchup: function(e) {
2084 TouchHandler.allowEvent(e);
2090 * Delegated click handler for .waves-effect element.
2091 * returns null when .waves-effect element not in "click tree"
2093 function getWavesEffectElement(e) {
2094 if (TouchHandler.allowEvent(e) === false) {
2099 var target = e.target || e.srcElement;
2101 while (target.parentElement !== null) {
2102 if (!(target instanceof SVGElement) && target.className.indexOf('waves-effect') !== -1) {
2105 } else if (target.classList.contains('waves-effect')) {
2109 target = target.parentElement;
2116 * Bubble the click and show effect if .waves-effect elem was found
2118 function showEffect(e) {
2119 var element = getWavesEffectElement(e);
2121 if (element !== null) {
2122 Effect.show(e, element);
2124 if ('ontouchstart' in window) {
2125 element.addEventListener('touchend', Effect.hide, false);
2126 element.addEventListener('touchcancel', Effect.hide, false);
2129 element.addEventListener('mouseup', Effect.hide, false);
2130 element.addEventListener('mouseleave', Effect.hide, false);
2134 Waves.displayEffect = function(options) {
2135 options = options || {};
2137 if ('duration' in options) {
2138 Effect.duration = options.duration;
2141 //Wrap input inside <i> tag
2142 Effect.wrapInput($$('.waves-effect'));
2144 if ('ontouchstart' in window) {
2145 document.body.addEventListener('touchstart', showEffect, false);
2148 document.body.addEventListener('mousedown', showEffect, false);
2152 * Attach Waves to an input element (or any element which doesn't
2153 * bubble mouseup/mousedown events).
2154 * Intended to be used with dynamically loaded forms/inputs, or
2155 * where the user doesn't want a delegated click handler.
2157 Waves.attach = function(element) {
2158 //FUTURE: automatically add waves classes and allow users
2159 // to specify them with an options param? Eg. light/classic/button
2160 if (element.tagName.toLowerCase() === 'input') {
2161 Effect.wrapInput([element]);
2162 element = element.parentElement;
2165 if ('ontouchstart' in window) {
2166 element.addEventListener('touchstart', showEffect, false);
2169 element.addEventListener('mousedown', showEffect, false);
2172 window.Waves = Waves;
2174 document.addEventListener('DOMContentLoaded', function() {
2175 Waves.displayEffect();
2179 ;Materialize.toast = function (message, displayLength, className, completeCallback) {
2180 className = className || "";
2182 var container = document.getElementById('toast-container');
2184 // Create toast container if it does not exist
2185 if (container === null) {
2186 // create notification container
2187 container = document.createElement('div');
2188 container.id = 'toast-container';
2189 document.body.appendChild(container);
2192 // Select and append toast
2193 var newToast = createToast(message);
2195 // only append toast if message is not undefined
2197 container.appendChild(newToast);
2200 newToast.style.opacity = 0;
2203 Vel(newToast, {translateY: '-35px', opacity: 1 }, {duration: 300,
2204 easing: 'easeOutCubic',
2207 // Allows timer to be pause while being panned
2208 var timeLeft = displayLength;
2209 var counterInterval;
2210 if (timeLeft != null) {
2211 counterInterval = setInterval (function(){
2212 if (newToast.parentNode === null)
2213 window.clearInterval(counterInterval);
2215 // If toast is not being dragged, decrease its time remaining
2216 if (!newToast.classList.contains('panning')) {
2220 if (timeLeft <= 0) {
2221 // Animate toast out
2222 Vel(newToast, {"opacity": 0, marginTop: '-40px'}, { duration: 375,
2223 easing: 'easeOutExpo',
2225 complete: function(){
2226 // Call the optional callback
2227 if(typeof(completeCallback) === "function")
2229 // Remove toast after it times out
2230 this[0].parentNode.removeChild(this[0]);
2233 window.clearInterval(counterInterval);
2240 function createToast(html) {
2243 var toast = document.createElement('div');
2244 toast.classList.add('toast');
2246 var classes = className.split(' ');
2248 for (var i = 0, count = classes.length; i < count; i++) {
2249 toast.classList.add(classes[i]);
2252 // If type of parameter is HTML Element
2253 if ( typeof HTMLElement === "object" ? html instanceof HTMLElement : html && typeof html === "object" && html !== null && html.nodeType === 1 && typeof html.nodeName==="string"
2255 toast.appendChild(html);
2257 else if (html instanceof jQuery) {
2258 // Check if it is jQuery object
2259 toast.appendChild(html[0]);
2263 toast.innerHTML = html;
2266 var hammerHandler = new Hammer(toast, {prevent_default: false});
2267 hammerHandler.on('pan', function(e) {
2268 var deltaX = e.deltaX;
2269 var activationDistance = 80;
2271 // Change toast state
2272 if (!toast.classList.contains('panning')){
2273 toast.classList.add('panning');
2276 var opacityPercent = 1-Math.abs(deltaX / activationDistance);
2277 if (opacityPercent < 0)
2280 Vel(toast, {left: deltaX, opacity: opacityPercent }, {duration: 50, queue: false, easing: 'easeOutQuad'});
2284 hammerHandler.on('panend', function(e) {
2285 var deltaX = e.deltaX;
2286 var activationDistance = 80;
2288 // If toast dragged past activation point
2289 if (Math.abs(deltaX) > activationDistance) {
2290 Vel(toast, {marginTop: '-40px'}, { duration: 375,
2291 easing: 'easeOutExpo',
2293 complete: function(){
2294 if(typeof(completeCallback) === "function") {
2297 toast.parentNode.removeChild(toast);
2302 toast.classList.remove('panning');
2303 // Put toast back into original position
2304 Vel(toast, { left: 0, opacity: 1 }, { duration: 300,
2305 easing: 'easeOutExpo',
2318 init : function(options) {
2322 closeOnClick: false,
2325 options = $.extend(defaults, options);
2327 $(this).each(function(){
2328 var $this = $(this);
2329 var menuId = $this.attr('data-activates');
2330 var menu = $("#"+ menuId);
2333 if (options.menuWidth != 300) {
2334 menu.css('width', options.menuWidth);
2338 var $dragTarget = $('.drag-target[data-sidenav="' + menuId + '"]');
2339 if (options.draggable) {
2340 // Regenerate dragTarget
2341 if ($dragTarget.length) {
2342 $dragTarget.remove();
2345 $dragTarget = $('<div class="drag-target"></div>').attr('data-sidenav', menuId);
2346 $('body').append($dragTarget);
2351 if (options.edge == 'left') {
2352 menu.css('transform', 'translateX(-100%)');
2353 $dragTarget.css({'left': 0}); // Add Touch Area
2356 menu.addClass('right-aligned') // Change text-alignment to right
2357 .css('transform', 'translateX(100%)');
2358 $dragTarget.css({'right': 0}); // Add Touch Area
2361 // If fixed sidenav, bring menu out
2362 if (menu.hasClass('fixed')) {
2363 if (window.innerWidth > 992) {
2364 menu.css('transform', 'translateX(0)');
2368 // Window resize to reset on large screens fixed
2369 if (menu.hasClass('fixed')) {
2370 $(window).resize( function() {
2371 if (window.innerWidth > 992) {
2372 // Close menu if window is resized bigger than 992 and user has fixed sidenav
2373 if ($('#sidenav-overlay').length !== 0 && menuOut) {
2377 // menu.removeAttr('style');
2378 menu.css('transform', 'translateX(0%)');
2379 // menu.css('width', options.menuWidth);
2382 else if (menuOut === false){
2383 if (options.edge === 'left') {
2384 menu.css('transform', 'translateX(-100%)');
2386 menu.css('transform', 'translateX(100%)');
2394 // if closeOnClick, then add close event for all a tags in side sideNav
2395 if (options.closeOnClick === true) {
2396 menu.on("click.itemclick", "a:not(.collapsible-header)", function(){
2401 var removeMenu = function(restoreNav) {
2404 // Reenable scrolling
2410 $('#sidenav-overlay').velocity({opacity: 0}, {duration: 200,
2411 queue: false, easing: 'easeOutQuad',
2412 complete: function() {
2415 if (options.edge === 'left') {
2416 // Reset phantom div
2417 $dragTarget.css({width: '', right: '', left: '0'});
2419 {'translateX': '-100%'},
2422 easing: 'easeOutCubic',
2423 complete: function() {
2424 if (restoreNav === true) {
2425 // Restore Fixed sidenav
2426 menu.removeAttr('style');
2427 menu.css('width', options.menuWidth);
2434 // Reset phantom div
2435 $dragTarget.css({width: '', right: '0', left: ''});
2437 {'translateX': '100%'},
2440 easing: 'easeOutCubic',
2441 complete: function() {
2442 if (restoreNav === true) {
2443 // Restore Fixed sidenav
2444 menu.removeAttr('style');
2445 menu.css('width', options.menuWidth);
2455 var panning = false;
2456 var menuOut = false;
2458 if (options.draggable) {
2459 $dragTarget.on('click', function(){
2465 $dragTarget.hammer({
2466 prevent_default: false
2467 }).bind('pan', function(e) {
2469 if (e.gesture.pointerType == "touch") {
2471 var direction = e.gesture.direction;
2472 var x = e.gesture.center.x;
2473 var y = e.gesture.center.y;
2474 var velocityX = e.gesture.velocityX;
2476 // Disable Scrolling
2477 var $body = $('body');
2478 var $overlay = $('#sidenav-overlay');
2479 var oldWidth = $body.innerWidth();
2480 $body.css('overflow', 'hidden');
2481 $body.width(oldWidth);
2483 // If overlay does not exist, create one and if it is clicked, close menu
2484 if ($overlay.length === 0) {
2485 $overlay = $('<div id="sidenav-overlay"></div>');
2486 $overlay.css('opacity', 0).click( function(){
2489 $('body').append($overlay);
2492 // Keep within boundaries
2493 if (options.edge === 'left') {
2494 if (x > options.menuWidth) { x = options.menuWidth; }
2495 else if (x < 0) { x = 0; }
2498 if (options.edge === 'left') {
2500 if (x < (options.menuWidth / 2)) { menuOut = false; }
2502 else if (x >= (options.menuWidth / 2)) { menuOut = true; }
2503 menu.css('transform', 'translateX(' + (x - options.menuWidth) + 'px)');
2507 if (x < (window.innerWidth - options.menuWidth / 2)) {
2511 else if (x >= (window.innerWidth - options.menuWidth / 2)) {
2514 var rightPos = (x - options.menuWidth / 2);
2519 menu.css('transform', 'translateX(' + rightPos + 'px)');
2523 // Percentage overlay
2525 if (options.edge === 'left') {
2526 overlayPerc = x / options.menuWidth;
2527 $overlay.velocity({opacity: overlayPerc }, {duration: 10, queue: false, easing: 'easeOutQuad'});
2530 overlayPerc = Math.abs((x - window.innerWidth) / options.menuWidth);
2531 $overlay.velocity({opacity: overlayPerc }, {duration: 10, queue: false, easing: 'easeOutQuad'});
2535 }).bind('panend', function(e) {
2537 if (e.gesture.pointerType == "touch") {
2538 var $overlay = $('<div id="sidenav-overlay"></div>');
2539 var velocityX = e.gesture.velocityX;
2540 var x = e.gesture.center.x;
2541 var leftPos = x - options.menuWidth;
2542 var rightPos = x - options.menuWidth / 2;
2551 if (options.edge === 'left') {
2552 // If velocityX <= 0.3 then the user is flinging the menu closed so ignore menuOut
2553 if ((menuOut && velocityX <= 0.3) || velocityX < -0.5) {
2554 // Return menu to open
2555 if (leftPos !== 0) {
2556 menu.velocity({'translateX': [0, leftPos]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
2559 $overlay.velocity({opacity: 1 }, {duration: 50, queue: false, easing: 'easeOutQuad'});
2560 $dragTarget.css({width: '50%', right: 0, left: ''});
2563 else if (!menuOut || velocityX > 0.3) {
2569 // Slide menu closed
2570 menu.velocity({'translateX': [-1 * options.menuWidth - 10, leftPos]}, {duration: 200, queue: false, easing: 'easeOutQuad'});
2571 $overlay.velocity({opacity: 0 }, {duration: 200, queue: false, easing: 'easeOutQuad',
2572 complete: function () {
2575 $dragTarget.css({width: '10px', right: '', left: 0});
2579 if ((menuOut && velocityX >= -0.3) || velocityX > 0.5) {
2580 // Return menu to open
2581 if (rightPos !== 0) {
2582 menu.velocity({'translateX': [0, rightPos]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
2585 $overlay.velocity({opacity: 1 }, {duration: 50, queue: false, easing: 'easeOutQuad'});
2586 $dragTarget.css({width: '50%', right: '', left: 0});
2589 else if (!menuOut || velocityX < -0.3) {
2596 // Slide menu closed
2597 menu.velocity({'translateX': [options.menuWidth + 10, rightPos]}, {duration: 200, queue: false, easing: 'easeOutQuad'});
2598 $overlay.velocity({opacity: 0 }, {duration: 200, queue: false, easing: 'easeOutQuad',
2599 complete: function () {
2602 $dragTarget.css({width: '10px', right: 0, left: ''});
2610 $this.off('click.sidenav').on('click.sidenav', function() {
2611 if (menuOut === true) {
2618 // Disable Scrolling
2619 var $body = $('body');
2620 var $overlay = $('<div id="sidenav-overlay"></div>');
2621 var oldWidth = $body.innerWidth();
2622 $body.css('overflow', 'hidden');
2623 $body.width(oldWidth);
2625 // Push current drag target on top of DOM tree
2626 $('body').append($dragTarget);
2628 if (options.edge === 'left') {
2629 $dragTarget.css({width: '50%', right: 0, left: ''});
2630 menu.velocity({'translateX': [0, -1 * options.menuWidth]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
2633 $dragTarget.css({width: '50%', right: '', left: 0});
2634 menu.velocity({'translateX': [0, options.menuWidth]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
2637 $overlay.css('opacity', 0)
2642 $overlay.velocity({opacity: 0}, {duration: 300, queue: false, easing: 'easeOutQuad',
2643 complete: function() {
2648 $('body').append($overlay);
2649 $overlay.velocity({opacity: 1}, {duration: 300, queue: false, easing: 'easeOutQuad',
2650 complete: function () {
2663 destroy: function () {
2664 var $overlay = $('#sidenav-overlay');
2665 var $dragTarget = $('.drag-target[data-sidenav="' + $(this).attr('data-activates') + '"]');
2666 $overlay.trigger('click');
2667 $dragTarget.remove();
2668 $(this).off('click');
2672 this.trigger('click');
2675 $('#sidenav-overlay').trigger('click');
2680 $.fn.sideNav = function(methodOrOptions) {
2681 if ( methods[methodOrOptions] ) {
2682 return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
2683 } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
2684 // Default to "init"
2685 return methods.init.apply( this, arguments );
2687 $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.sideNav' );
2692 * Extend jquery with a scrollspy plugin.
2693 * This watches the window scroll and fires events when elements are scrolled into viewport.
2695 * throttle() and getTime() taken from Underscore.js
2696 * https://github.com/jashkenas/underscore
2698 * @author Copyright 2013 John Smart
2699 * @license https://raw.github.com/thesmart/jquery-scrollspy/master/LICENSE
2700 * @see https://github.com/thesmart
2705 var jWindow = $(window);
2707 var elementsInView = [];
2708 var isSpying = false;
2719 * Find elements that are within the boundary
2720 * @param {number} top
2721 * @param {number} right
2722 * @param {number} bottom
2723 * @param {number} left
2724 * @return {jQuery} A collection of elements
2726 function findElements(top, right, bottom, left) {
2728 $.each(elements, function(i, element) {
2729 if (element.height() > 0) {
2730 var elTop = element.offset().top,
2731 elLeft = element.offset().left,
2732 elRight = elLeft + element.width(),
2733 elBottom = elTop + element.height();
2735 var isIntersect = !(elLeft > right ||
2751 * Called when the user scrolls the window
2753 function onScroll(scrollOffset) {
2757 // viewport rectangle
2758 var top = jWindow.scrollTop(),
2759 left = jWindow.scrollLeft(),
2760 right = left + jWindow.width(),
2761 bottom = top + jWindow.height();
2763 // determine which elements are in view
2764 var intersections = findElements(top+offset.top + scrollOffset || 200, right+offset.right, bottom+offset.bottom, left+offset.left);
2765 $.each(intersections, function(i, element) {
2767 var lastTick = element.data('scrollSpy:ticks');
2768 if (typeof lastTick != 'number') {
2769 // entered into view
2770 element.triggerHandler('scrollSpy:enter');
2774 element.data('scrollSpy:ticks', ticks);
2777 // determine which elements are no longer in view
2778 $.each(elementsInView, function(i, element) {
2779 var lastTick = element.data('scrollSpy:ticks');
2780 if (typeof lastTick == 'number' && lastTick !== ticks) {
2782 element.triggerHandler('scrollSpy:exit');
2783 element.data('scrollSpy:ticks', null);
2787 // remember elements in view for next tick
2788 elementsInView = intersections;
2792 * Called when window is resized
2794 function onWinSize() {
2795 jWindow.trigger('scrollSpy:winSize');
2800 * Enables ScrollSpy using a selector
2801 * @param {jQuery|string} selector The elements collection, or a selector
2802 * @param {Object=} options Optional.
2803 throttle : number -> scrollspy throttling. Default: 100 ms
2804 offsetTop : number -> offset from top. Default: 0
2805 offsetRight : number -> offset from right. Default: 0
2806 offsetBottom : number -> offset from bottom. Default: 0
2807 offsetLeft : number -> offset from left. Default: 0
2810 $.scrollSpy = function(selector, options) {
2813 scrollOffset: 200 // offset - 200 allows elements near bottom of page to scroll
2815 options = $.extend(defaults, options);
2818 selector = $(selector);
2819 selector.each(function(i, element) {
2820 elements.push($(element));
2821 $(element).data("scrollSpy:id", i);
2822 // Smooth scroll to section
2823 $('a[href="#' + $(element).attr('id') + '"]').click(function(e) {
2825 var offset = $(Materialize.escapeHash(this.hash)).offset().top + 1;
2826 $('html, body').animate({ scrollTop: offset - options.scrollOffset }, {duration: 400, queue: false, easing: 'easeOutCubic'});
2830 offset.top = options.offsetTop || 0;
2831 offset.right = options.offsetRight || 0;
2832 offset.bottom = options.offsetBottom || 0;
2833 offset.left = options.offsetLeft || 0;
2835 var throttledScroll = Materialize.throttle(function() {
2836 onScroll(options.scrollOffset);
2837 }, options.throttle || 100);
2838 var readyScroll = function(){
2839 $(document).ready(throttledScroll);
2843 jWindow.on('scroll', readyScroll);
2844 jWindow.on('resize', readyScroll);
2848 // perform a scan once, after current execution context, and after dom is ready
2849 setTimeout(readyScroll, 0);
2852 selector.on('scrollSpy:enter', function() {
2853 visible = $.grep(visible, function(value) {
2854 return value.height() != 0;
2857 var $this = $(this);
2860 $('a[href="#' + visible[0].attr('id') + '"]').removeClass('active');
2861 if ($this.data('scrollSpy:id') < visible[0].data('scrollSpy:id')) {
2862 visible.unshift($(this));
2865 visible.push($(this));
2869 visible.push($(this));
2873 $('a[href="#' + visible[0].attr('id') + '"]').addClass('active');
2875 selector.on('scrollSpy:exit', function() {
2876 visible = $.grep(visible, function(value) {
2877 return value.height() != 0;
2881 $('a[href="#' + visible[0].attr('id') + '"]').removeClass('active');
2882 var $this = $(this);
2883 visible = $.grep(visible, function(value) {
2884 return value.attr('id') != $this.attr('id');
2886 if (visible[0]) { // Check if empty
2887 $('a[href="#' + visible[0].attr('id') + '"]').addClass('active');
2896 * Listen for window resize events
2897 * @param {Object=} options Optional. Set { throttle: number } to change throttling. Default: 100 ms
2898 * @returns {jQuery} $(window)
2900 $.winSizeSpy = function(options) {
2901 $.winSizeSpy = function() { return jWindow; }; // lock from multiple calls
2902 options = options || {
2905 return jWindow.on('resize', Materialize.throttle(onWinSize, options.throttle || 100));
2909 * Enables ScrollSpy on a collection of elements
2910 * e.g. $('.scrollSpy').scrollSpy()
2911 * @param {Object=} options Optional.
2912 throttle : number -> scrollspy throttling. Default: 100 ms
2913 offsetTop : number -> offset from top. Default: 0
2914 offsetRight : number -> offset from right. Default: 0
2915 offsetBottom : number -> offset from bottom. Default: 0
2916 offsetLeft : number -> offset from left. Default: 0
2919 $.fn.scrollSpy = function(options) {
2920 return $.scrollSpy($(this), options);
2925 $(document).ready(function() {
2927 // Function to update labels of text fields
2928 Materialize.updateTextFields = function() {
2929 var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';
2930 $(input_selector).each(function(index, element) {
2931 var $this = $(this);
2932 if ($(element).val().length > 0 || element.autofocus || $this.attr('placeholder') !== undefined) {
2933 $this.siblings('label').addClass('active');
2934 } else if ($(element)[0].validity) {
2935 $this.siblings('label').toggleClass('active', $(element)[0].validity.badInput === true);
2937 $this.siblings('label').removeClass('active');
2942 // Text based inputs
2943 var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';
2945 // Add active if form auto complete
2946 $(document).on('change', input_selector, function () {
2947 if($(this).val().length !== 0 || $(this).attr('placeholder') !== undefined) {
2948 $(this).siblings('label').addClass('active');
2950 validate_field($(this));
2953 // Add active if input element has been pre-populated on document ready
2954 $(document).ready(function() {
2955 Materialize.updateTextFields();
2958 // HTML DOM FORM RESET handling
2959 $(document).on('reset', function(e) {
2960 var formReset = $(e.target);
2961 if (formReset.is('form')) {
2962 formReset.find(input_selector).removeClass('valid').removeClass('invalid');
2963 formReset.find(input_selector).each(function () {
2964 if ($(this).attr('value') === '') {
2965 $(this).siblings('label').removeClass('active');
2970 formReset.find('select.initialized').each(function () {
2971 var reset_text = formReset.find('option[selected]').text();
2972 formReset.siblings('input.select-dropdown').val(reset_text);
2977 // Add active when element has focus
2978 $(document).on('focus', input_selector, function () {
2979 $(this).siblings('label, .prefix').addClass('active');
2982 $(document).on('blur', input_selector, function () {
2983 var $inputElement = $(this);
2984 var selector = ".prefix";
2986 if ($inputElement.val().length === 0 && $inputElement[0].validity.badInput !== true && $inputElement.attr('placeholder') === undefined) {
2987 selector += ", label";
2990 $inputElement.siblings(selector).removeClass('active');
2992 validate_field($inputElement);
2995 window.validate_field = function(object) {
2996 var hasLength = object.attr('data-length') !== undefined;
2997 var lenAttr = parseInt(object.attr('data-length'));
2998 var len = object.val().length;
3000 if (object.val().length === 0 && object[0].validity.badInput === false) {
3001 if (object.hasClass('validate')) {
3002 object.removeClass('valid');
3003 object.removeClass('invalid');
3007 if (object.hasClass('validate')) {
3008 // Check for character counter attributes
3009 if ((object.is(':valid') && hasLength && (len <= lenAttr)) || (object.is(':valid') && !hasLength)) {
3010 object.removeClass('invalid');
3011 object.addClass('valid');
3014 object.removeClass('valid');
3015 object.addClass('invalid');
3021 // Radio and Checkbox focus class
3022 var radio_checkbox = 'input[type=radio], input[type=checkbox]';
3023 $(document).on('keyup.radio', radio_checkbox, function(e) {
3024 // TAB, check if tabbing to radio or checkbox.
3025 if (e.which === 9) {
3026 $(this).addClass('tabbed');
3027 var $this = $(this);
3028 $this.one('blur', function(e) {
3030 $(this).removeClass('tabbed');
3036 // Textarea Auto Resize
3037 var hiddenDiv = $('.hiddendiv').first();
3038 if (!hiddenDiv.length) {
3039 hiddenDiv = $('<div class="hiddendiv common"></div>');
3040 $('body').append(hiddenDiv);
3042 var text_area_selector = '.materialize-textarea';
3044 function textareaAutoResize($textarea) {
3045 // Set font properties of hiddenDiv
3047 var fontFamily = $textarea.css('font-family');
3048 var fontSize = $textarea.css('font-size');
3049 var lineHeight = $textarea.css('line-height');
3051 if (fontSize) { hiddenDiv.css('font-size', fontSize); }
3052 if (fontFamily) { hiddenDiv.css('font-family', fontFamily); }
3053 if (lineHeight) { hiddenDiv.css('line-height', lineHeight); }
3055 if ($textarea.attr('wrap') === "off") {
3056 hiddenDiv.css('overflow-wrap', "normal")
3057 .css('white-space', "pre");
3060 hiddenDiv.text($textarea.val() + '\n');
3061 var content = hiddenDiv.html().replace(/\n/g, '<br>');
3062 hiddenDiv.html(content);
3065 // When textarea is hidden, width goes crazy.
3066 // Approximate with half of window size
3068 if ($textarea.is(':visible')) {
3069 hiddenDiv.css('width', $textarea.width());
3072 hiddenDiv.css('width', $(window).width()/2);
3075 $textarea.css('height', hiddenDiv.height());
3078 $(text_area_selector).each(function () {
3079 var $textarea = $(this);
3080 if ($textarea.val().length) {
3081 textareaAutoResize($textarea);
3085 $('body').on('keyup keydown autoresize', text_area_selector, function () {
3086 textareaAutoResize($(this));
3090 $(document).on('change', '.file-field input[type="file"]', function () {
3091 var file_field = $(this).closest('.file-field');
3092 var path_input = file_field.find('input.file-path');
3093 var files = $(this)[0].files;
3094 var file_names = [];
3095 for (var i = 0; i < files.length; i++) {
3096 file_names.push(files[i].name);
3098 path_input.val(file_names.join(", "));
3099 path_input.trigger('change');
3106 var range_type = 'input[type=range]';
3107 var range_mousedown = false;
3110 $(range_type).each(function () {
3111 var thumb = $('<span class="thumb"><span class="value"></span></span>');
3112 $(this).after(thumb);
3115 var range_wrapper = '.range-field';
3116 $(document).on('change', range_type, function(e) {
3117 var thumb = $(this).siblings('.thumb');
3118 thumb.find('.value').html($(this).val());
3121 $(document).on('input mousedown touchstart', range_type, function(e) {
3122 var thumb = $(this).siblings('.thumb');
3123 var width = $(this).outerWidth();
3125 // If thumb indicator does not exist yet, create it
3126 if (thumb.length <= 0) {
3127 thumb = $('<span class="thumb"><span class="value"></span></span>');
3128 $(this).after(thumb);
3131 // Set indicator value
3132 thumb.find('.value').html($(this).val());
3134 range_mousedown = true;
3135 $(this).addClass('active');
3137 if (!thumb.hasClass('active')) {
3138 thumb.velocity({ height: "30px", width: "30px", top: "-20px", marginLeft: "-15px"}, { duration: 300, easing: 'easeOutExpo' });
3141 if (e.type !== 'input') {
3142 if(e.pageX === undefined || e.pageX === null){//mobile
3143 left = e.originalEvent.touches[0].pageX - $(this).offset().left;
3146 left = e.pageX - $(this).offset().left;
3151 else if (left > width) {
3154 thumb.addClass('active').css('left', left);
3157 thumb.find('.value').html($(this).val());
3160 $(document).on('mouseup touchend', range_wrapper, function() {
3161 range_mousedown = false;
3162 $(this).removeClass('active');
3165 $(document).on('mousemove touchmove', range_wrapper, function(e) {
3166 var thumb = $(this).children('.thumb');
3168 if (range_mousedown) {
3169 if (!thumb.hasClass('active')) {
3170 thumb.velocity({ height: '30px', width: '30px', top: '-20px', marginLeft: '-15px'}, { duration: 300, easing: 'easeOutExpo' });
3172 if (e.pageX === undefined || e.pageX === null) { //mobile
3173 left = e.originalEvent.touches[0].pageX - $(this).offset().left;
3176 left = e.pageX - $(this).offset().left;
3178 var width = $(this).outerWidth();
3183 else if (left > width) {
3186 thumb.addClass('active').css('left', left);
3187 thumb.find('.value').html(thumb.siblings(range_type).val());
3191 $(document).on('mouseout touchleave', range_wrapper, function() {
3192 if (!range_mousedown) {
3194 var thumb = $(this).children('.thumb');
3196 if (thumb.hasClass('active')) {
3197 thumb.velocity({ height: '0', width: '0', top: '10px', marginLeft: '-6px'}, { duration: 100 });
3199 thumb.removeClass('active');
3203 /**************************
3204 * Auto complete plugin *
3205 *************************/
3206 $.fn.autocomplete = function (options) {
3211 onAutocomplete: null
3214 options = $.extend(defaults, options);
3216 return this.each(function() {
3217 var $input = $(this);
3218 var data = options.data,
3222 $inputDiv = $input.closest('.input-field'); // Div to append on
3224 // Check if data isn't empty
3225 if (!$.isEmptyObject(data)) {
3226 var $autocomplete = $('<ul class="autocomplete-content dropdown-content"></ul>');
3227 var $oldAutocomplete;
3229 // Append autocomplete element.
3230 // Prevent double structure init.
3231 if ($inputDiv.length) {
3232 $oldAutocomplete = $inputDiv.children('.autocomplete-content.dropdown-content').first();
3233 if (!$oldAutocomplete.length) {
3234 $inputDiv.append($autocomplete); // Set ul in body
3237 $oldAutocomplete = $input.next('.autocomplete-content.dropdown-content');
3238 if (!$oldAutocomplete.length) {
3239 $input.after($autocomplete);
3242 if ($oldAutocomplete.length) {
3243 $autocomplete = $oldAutocomplete;
3246 // Highlight partial match.
3247 var highlight = function(string, $el) {
3248 var img = $el.find('img');
3249 var matchStart = $el.text().toLowerCase().indexOf("" + string.toLowerCase() + ""),
3250 matchEnd = matchStart + string.length - 1,
3251 beforeMatch = $el.text().slice(0, matchStart),
3252 matchText = $el.text().slice(matchStart, matchEnd + 1),
3253 afterMatch = $el.text().slice(matchEnd + 1);
3254 $el.html("<span>" + beforeMatch + "<span class='highlight'>" + matchText + "</span>" + afterMatch + "</span>");
3260 // Reset current element position
3261 var resetCurrentElement = function() {
3263 $autocomplete.find('.active').removeClass('active');
3267 $input.off('keyup.autocomplete').on('keyup.autocomplete', function (e) {
3271 // Don't capture enter or arrow key usage.
3272 if (e.which === 13 ||
3278 var val = $input.val().toLowerCase();
3280 // Check if the input isn't empty
3281 if (oldVal !== val) {
3282 $autocomplete.empty();
3283 resetCurrentElement();
3286 for(var key in data) {
3287 if (data.hasOwnProperty(key) &&
3288 key.toLowerCase().indexOf(val) !== -1 &&
3289 key.toLowerCase() !== val) {
3290 // Break if past limit
3291 if (count >= options.limit) {
3295 var autocompleteOption = $('<li></li>');
3297 autocompleteOption.append('<img src="'+ data[key] +'" class="right circle"><span>'+ key +'</span>');
3299 autocompleteOption.append('<span>'+ key +'</span>');
3302 $autocomplete.append(autocompleteOption);
3303 highlight(val, autocompleteOption);
3314 $input.off('keydown.autocomplete').on('keydown.autocomplete', function (e) {
3315 // Arrow keys and enter key usage
3316 var keyCode = e.which,
3318 numItems = $autocomplete.children('li').length,
3319 $active = $autocomplete.children('.active').first();
3321 // select element on Enter
3322 if (keyCode === 13) {
3323 liElement = $autocomplete.children('li').eq(activeIndex);
3324 if (liElement.length) {
3331 // Capture up and down key
3332 if ( keyCode === 38 || keyCode === 40 ) {
3335 if (keyCode === 38 &&
3340 if (keyCode === 40 &&
3341 activeIndex < (numItems - 1) &&
3346 $active.removeClass('active');
3347 $autocomplete.children('li').eq(activeIndex).addClass('active');
3352 $autocomplete.on('click', 'li', function () {
3353 var text = $(this).text().trim();
3355 $input.trigger('change');
3356 $autocomplete.empty();
3357 resetCurrentElement();
3359 // Handle onAutocomplete callback.
3360 if (typeof(options.onAutocomplete) === "function") {
3361 options.onAutocomplete.call(this, text);
3368 }); // End of $(document).ready
3370 /*******************
3373 $.fn.material_select = function (callback) {
3374 $(this).each(function(){
3375 var $select = $(this);
3377 if ($select.hasClass('browser-default')) {
3378 return; // Continue to next (return false breaks out of entire loop)
3381 var multiple = $select.attr('multiple') ? true : false,
3382 lastID = $select.data('select-id'); // Tear down structure if Select needs to be rebuilt
3385 $select.parent().find('span.caret').remove();
3386 $select.parent().find('input').remove();
3389 $('ul#select-options-'+lastID).remove();
3392 // If destroying the select, remove the selelct-id and reset it to it's uninitialized state.
3393 if(callback === 'destroy') {
3394 $select.data('select-id', null).removeClass('initialized');
3398 var uniqueID = Materialize.guid();
3399 $select.data('select-id', uniqueID);
3400 var wrapper = $('<div class="select-wrapper"></div>');
3401 wrapper.addClass($select.attr('class'));
3402 var options = $('<ul id="select-options-' + uniqueID +'" class="dropdown-content select-dropdown ' + (multiple ? 'multiple-select-dropdown' : '') + '"></ul>'),
3403 selectChildren = $select.children('option, optgroup'),
3404 valuesSelected = [],
3405 optionsHover = false;
3407 var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
3409 // Function that renders and appends the option taking into
3410 // account type and possible image icon.
3411 var appendOptionWithIcon = function(select, option, type) {
3412 // Add disabled attr if disabled
3413 var disabledClass = (option.is(':disabled')) ? 'disabled ' : '';
3414 var optgroupClass = (type === 'optgroup-option') ? 'optgroup-option ' : '';
3417 var icon_url = option.data('icon');
3418 var classes = option.attr('class');
3420 var classString = '';
3421 if (!!classes) classString = ' class="' + classes + '"';
3423 // Check for multiple type.
3424 if (type === 'multiple') {
3425 options.append($('<li class="' + disabledClass + '"><img alt="" src="' + icon_url + '"' + classString + '><span><input type="checkbox"' + disabledClass + '/><label></label>' + option.html() + '</span></li>'));
3427 options.append($('<li class="' + disabledClass + optgroupClass + '"><img alt="" src="' + icon_url + '"' + classString + '><span>' + option.html() + '</span></li>'));
3432 // Check for multiple type.
3433 if (type === 'multiple') {
3434 options.append($('<li class="' + disabledClass + '"><span><input type="checkbox"' + disabledClass + '/><label></label>' + option.html() + '</span></li>'));
3436 options.append($('<li class="' + disabledClass + optgroupClass + '"><span>' + option.html() + '</span></li>'));
3440 /* Create dropdown structure. */
3441 if (selectChildren.length) {
3442 selectChildren.each(function() {
3443 if ($(this).is('option')) {
3444 // Direct descendant option.
3446 appendOptionWithIcon($select, $(this), 'multiple');
3449 appendOptionWithIcon($select, $(this));
3451 } else if ($(this).is('optgroup')) {
3453 var selectOptions = $(this).children('option');
3454 options.append($('<li class="optgroup"><span>' + $(this).attr('label') + '</span></li>'));
3456 selectOptions.each(function() {
3457 appendOptionWithIcon($select, $(this), 'optgroup-option');
3463 options.find('li:not(.optgroup)').each(function (i) {
3464 $(this).click(function (e) {
3465 // Check if option element is disabled
3466 if (!$(this).hasClass('disabled') && !$(this).hasClass('optgroup')) {
3467 var selected = true;
3470 $('input[type="checkbox"]', this).prop('checked', function(i, v) { return !v; });
3471 selected = toggleEntryFromArray(valuesSelected, $(this).index(), $select);
3472 $newSelect.trigger('focus');
3474 options.find('li').removeClass('active');
3475 $(this).toggleClass('active');
3476 $newSelect.val($(this).text());
3479 activateOption(options, $(this));
3480 $select.find('option').eq(i).prop('selected', selected);
3481 // Trigger onchange() event
3482 $select.trigger('change');
3483 if (typeof callback !== 'undefined') callback();
3486 e.stopPropagation();
3491 $select.wrap(wrapper);
3492 // Add Select Display Element
3493 var dropdownIcon = $('<span class="caret">▼</span>');
3494 if ($select.is(':disabled'))
3495 dropdownIcon.addClass('disabled');
3497 // escape double quotes
3498 var sanitizedLabelHtml = label.replace(/"/g, '"');
3500 var $newSelect = $('<input type="text" class="select-dropdown" readonly="true" ' + (($select.is(':disabled')) ? 'disabled' : '') + ' data-activates="select-options-' + uniqueID +'" value="'+ sanitizedLabelHtml +'"/>');
3501 $select.before($newSelect);
3502 $newSelect.before(dropdownIcon);
3504 $newSelect.after(options);
3505 // Check if section element is disabled
3506 if (!$select.is(':disabled')) {
3507 $newSelect.dropdown({'hover': false, 'closeOnClick': false});
3511 if ($select.attr('tabindex')) {
3512 $($newSelect[0]).attr('tabindex', $select.attr('tabindex'));
3515 $select.addClass('initialized');
3518 'focus': function (){
3519 if ($('ul.select-dropdown').not(options[0]).is(':visible')) {
3520 $('input.select-dropdown').trigger('close');
3522 if (!options.is(':visible')) {
3523 $(this).trigger('open', ['focus']);
3524 var label = $(this).val();
3525 if (multiple && label.indexOf(',') >= 0) {
3526 label = label.split(',')[0];
3529 var selectedOption = options.find('li').filter(function() {
3530 return $(this).text().toLowerCase() === label.toLowerCase();
3532 activateOption(options, selectedOption, true);
3535 'click': function (e){
3536 e.stopPropagation();
3540 $newSelect.on('blur', function() {
3542 $(this).trigger('close');
3544 options.find('li.selected').removeClass('selected');
3547 options.hover(function() {
3548 optionsHover = true;
3550 optionsHover = false;
3554 'click': function () {
3555 multiple && (optionsHover || $newSelect.trigger('close'));
3559 // Add initial multiple selections.
3561 $select.find("option:selected:not(:disabled)").each(function () {
3562 var index = $(this).index();
3564 toggleEntryFromArray(valuesSelected, index, $select);
3565 options.find("li").eq(index).find(":checkbox").prop("checked", true);
3570 * Make option as selected and scroll to selected position
3571 * @param {jQuery} collection Select options jQuery element
3572 * @param {Element} newOption element of the new option
3573 * @param {Boolean} firstActivation If on first activation of select
3575 var activateOption = function(collection, newOption, firstActivation) {
3577 collection.find('li.selected').removeClass('selected');
3578 var option = $(newOption);
3579 option.addClass('selected');
3580 if (!multiple || !!firstActivation) {
3581 options.scrollTo(option);
3586 // Allow user to search by typing
3587 // this array is cleared after 1 second
3588 var filterQuery = [],
3589 onKeyDown = function(e){
3590 // TAB - switch to another input
3592 $newSelect.trigger('close');
3596 // ARROW DOWN WHEN SELECT IS CLOSED - open select options
3597 if(e.which == 40 && !options.is(':visible')){
3598 $newSelect.trigger('open');
3602 // ENTER WHEN SELECT IS CLOSED - submit form
3603 if(e.which == 13 && !options.is(':visible')){
3609 // CASE WHEN USER TYPE LETTERS
3610 var letter = String.fromCharCode(e.which).toLowerCase(),
3611 nonLetters = [9,13,27,38,40];
3612 if (letter && (nonLetters.indexOf(e.which) === -1)) {
3613 filterQuery.push(letter);
3615 var string = filterQuery.join(''),
3616 newOption = options.find('li').filter(function() {
3617 return $(this).text().toLowerCase().indexOf(string) === 0;
3621 activateOption(options, newOption);
3625 // ENTER - select option and close when select options are opened
3626 if (e.which == 13) {
3627 var activeOption = options.find('li.selected:not(.disabled)')[0];
3629 $(activeOption).trigger('click');
3631 $newSelect.trigger('close');
3636 // ARROW DOWN - move to next not disabled option
3637 if (e.which == 40) {
3638 if (options.find('li.selected').length) {
3639 newOption = options.find('li.selected').next('li:not(.disabled)')[0];
3641 newOption = options.find('li:not(.disabled)')[0];
3643 activateOption(options, newOption);
3646 // ESC - close options
3647 if (e.which == 27) {
3648 $newSelect.trigger('close');
3651 // ARROW UP - move to previous not disabled option
3652 if (e.which == 38) {
3653 newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
3655 activateOption(options, newOption);
3658 // Automaticaly clean filter query so user can search again by starting letters
3659 setTimeout(function(){ filterQuery = []; }, 1000);
3662 $newSelect.on('keydown', onKeyDown);
3665 function toggleEntryFromArray(entriesArray, entryIndex, select) {
3666 var index = entriesArray.indexOf(entryIndex),
3667 notAdded = index === -1;
3670 entriesArray.push(entryIndex);
3672 entriesArray.splice(index, 1);
3675 select.siblings('ul.dropdown-content').find('li').eq(entryIndex).toggleClass('active');
3677 // use notAdded instead of true (to detect if the option is selected or not)
3678 select.find('option').eq(entryIndex).prop('selected', notAdded);
3679 setValueToInput(entriesArray, select);
3684 function setValueToInput(entriesArray, select) {
3687 for (var i = 0, count = entriesArray.length; i < count; i++) {
3688 var text = select.find('option').eq(entriesArray[i]).text();
3690 i === 0 ? value += text : value += ', ' + text;
3694 value = select.find('option:disabled').eq(0).text();
3697 select.siblings('input.select-dropdown').val(value);
3706 init : function(options) {
3713 options = $.extend(defaults, options);
3715 return this.each(function() {
3717 // For each slider, we want to keep track of
3718 // which slide is active and its associated content
3719 var $this = $(this);
3720 var $slider = $this.find('ul.slides').first();
3721 var $slides = $slider.find('> li');
3722 var $active_index = $slider.find('.active').index();
3723 var $active, $indicators, $interval;
3724 if ($active_index != -1) { $active = $slides.eq($active_index); }
3726 // Transitions the caption depending on alignment
3727 function captionTransition(caption, duration) {
3728 if (caption.hasClass("center-align")) {
3729 caption.velocity({opacity: 0, translateY: -100}, {duration: duration, queue: false});
3731 else if (caption.hasClass("right-align")) {
3732 caption.velocity({opacity: 0, translateX: 100}, {duration: duration, queue: false});
3734 else if (caption.hasClass("left-align")) {
3735 caption.velocity({opacity: 0, translateX: -100}, {duration: duration, queue: false});
3739 // This function will transition the slide to any index of the next slide
3740 function moveToSlide(index) {
3741 // Wrap around indices.
3742 if (index >= $slides.length) index = 0;
3743 else if (index < 0) index = $slides.length -1;
3745 $active_index = $slider.find('.active').index();
3747 // Only do if index changes
3748 if ($active_index != index) {
3749 $active = $slides.eq($active_index);
3750 $caption = $active.find('.caption');
3752 $active.removeClass('active');
3753 $active.velocity({opacity: 0}, {duration: options.transition, queue: false, easing: 'easeOutQuad',
3754 complete: function() {
3755 $slides.not('.active').velocity({opacity: 0, translateX: 0, translateY: 0}, {duration: 0, queue: false});
3757 captionTransition($caption, options.transition);
3760 // Update indicators
3761 if (options.indicators) {
3762 $indicators.eq($active_index).removeClass('active');
3765 $slides.eq(index).velocity({opacity: 1}, {duration: options.transition, queue: false, easing: 'easeOutQuad'});
3766 $slides.eq(index).find('.caption').velocity({opacity: 1, translateX: 0, translateY: 0}, {duration: options.transition, delay: options.transition, queue: false, easing: 'easeOutQuad'});
3767 $slides.eq(index).addClass('active');
3770 // Update indicators
3771 if (options.indicators) {
3772 $indicators.eq(index).addClass('active');
3777 // Set height of slider
3778 // If fullscreen, do nothing
3779 if (!$this.hasClass('fullscreen')) {
3780 if (options.indicators) {
3781 // Add height if indicators are present
3782 $this.height(options.height + 40);
3785 $this.height(options.height);
3787 $slider.height(options.height);
3791 // Set initial positions of captions
3792 $slides.find('.caption').each(function () {
3793 captionTransition($(this), 0);
3796 // Move img src into background-image
3797 $slides.find('img').each(function () {
3798 var placeholderBase64 = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
3799 if ($(this).attr('src') !== placeholderBase64) {
3800 $(this).css('background-image', 'url(' + $(this).attr('src') + ')' );
3801 $(this).attr('src', placeholderBase64);
3805 // dynamically add indicators
3806 if (options.indicators) {
3807 $indicators = $('<ul class="indicators"></ul>');
3808 $slides.each(function( index ) {
3809 var $indicator = $('<li class="indicator-item"></li>');
3811 // Handle clicks on indicators
3812 $indicator.click(function () {
3813 var $parent = $slider.parent();
3814 var curr_index = $parent.find($(this)).index();
3815 moveToSlide(curr_index);
3818 clearInterval($interval);
3819 $interval = setInterval(
3821 $active_index = $slider.find('.active').index();
3822 if ($slides.length == $active_index + 1) $active_index = 0; // loop to start
3823 else $active_index += 1;
3825 moveToSlide($active_index);
3827 }, options.transition + options.interval
3830 $indicators.append($indicator);
3832 $this.append($indicators);
3833 $indicators = $this.find('ul.indicators').find('li.indicator-item');
3840 $slides.first().addClass('active').velocity({opacity: 1}, {duration: options.transition, queue: false, easing: 'easeOutQuad'});
3843 $active = $slides.eq($active_index);
3845 // Update indicators
3846 if (options.indicators) {
3847 $indicators.eq($active_index).addClass('active');
3851 // Adjust height to current slide
3852 $active.find('img').each(function() {
3853 $active.find('.caption').velocity({opacity: 1, translateX: 0, translateY: 0}, {duration: options.transition, queue: false, easing: 'easeOutQuad'});
3857 $interval = setInterval(
3859 $active_index = $slider.find('.active').index();
3860 moveToSlide($active_index + 1);
3862 }, options.transition + options.interval
3866 // HammerJS, Swipe navigation
3869 var panning = false;
3870 var swipeLeft = false;
3871 var swipeRight = false;
3874 prevent_default: false
3875 }).bind('pan', function(e) {
3876 if (e.gesture.pointerType === "touch") {
3879 clearInterval($interval);
3881 var direction = e.gesture.direction;
3882 var x = e.gesture.deltaX;
3883 var velocityX = e.gesture.velocityX;
3884 var velocityY = e.gesture.velocityY;
3886 $curr_slide = $slider.find('.active');
3887 if (Math.abs(velocityX) > Math.abs(velocityY)) {
3888 $curr_slide.velocity({ translateX: x
3889 }, {duration: 50, queue: false, easing: 'easeOutQuad'});
3893 if (direction === 4 && (x > ($this.innerWidth() / 2) || velocityX < -0.65)) {
3897 else if (direction === 2 && (x < (-1 * $this.innerWidth() / 2) || velocityX > 0.65)) {
3901 // Make Slide Behind active slide visible
3904 next_slide = $curr_slide.next();
3905 if (next_slide.length === 0) {
3906 next_slide = $slides.first();
3908 next_slide.velocity({ opacity: 1
3909 }, {duration: 300, queue: false, easing: 'easeOutQuad'});
3912 next_slide = $curr_slide.prev();
3913 if (next_slide.length === 0) {
3914 next_slide = $slides.last();
3916 next_slide.velocity({ opacity: 1
3917 }, {duration: 300, queue: false, easing: 'easeOutQuad'});
3923 }).bind('panend', function(e) {
3924 if (e.gesture.pointerType === "touch") {
3926 $curr_slide = $slider.find('.active');
3928 curr_index = $slider.find('.active').index();
3930 if (!swipeRight && !swipeLeft || $slides.length <=1) {
3931 // Return to original spot
3932 $curr_slide.velocity({ translateX: 0
3933 }, {duration: 300, queue: false, easing: 'easeOutQuad'});
3935 else if (swipeLeft) {
3936 moveToSlide(curr_index + 1);
3937 $curr_slide.velocity({translateX: -1 * $this.innerWidth() }, {duration: 300, queue: false, easing: 'easeOutQuad',
3938 complete: function() {
3939 $curr_slide.velocity({opacity: 0, translateX: 0}, {duration: 0, queue: false});
3942 else if (swipeRight) {
3943 moveToSlide(curr_index - 1);
3944 $curr_slide.velocity({translateX: $this.innerWidth() }, {duration: 300, queue: false, easing: 'easeOutQuad',
3945 complete: function() {
3946 $curr_slide.velocity({opacity: 0, translateX: 0}, {duration: 0, queue: false});
3953 clearInterval($interval);
3954 $interval = setInterval(
3956 $active_index = $slider.find('.active').index();
3957 if ($slides.length == $active_index + 1) $active_index = 0; // loop to start
3958 else $active_index += 1;
3960 moveToSlide($active_index);
3962 }, options.transition + options.interval
3967 $this.on('sliderPause', function() {
3968 clearInterval($interval);
3971 $this.on('sliderStart', function() {
3972 clearInterval($interval);
3973 $interval = setInterval(
3975 $active_index = $slider.find('.active').index();
3976 if ($slides.length == $active_index + 1) $active_index = 0; // loop to start
3977 else $active_index += 1;
3979 moveToSlide($active_index);
3981 }, options.transition + options.interval
3985 $this.on('sliderNext', function() {
3986 $active_index = $slider.find('.active').index();
3987 moveToSlide($active_index + 1);
3990 $this.on('sliderPrev', function() {
3991 $active_index = $slider.find('.active').index();
3992 moveToSlide($active_index - 1);
4000 pause : function() {
4001 $(this).trigger('sliderPause');
4003 start : function() {
4004 $(this).trigger('sliderStart');
4007 $(this).trigger('sliderNext');
4010 $(this).trigger('sliderPrev');
4015 $.fn.slider = function(methodOrOptions) {
4016 if ( methods[methodOrOptions] ) {
4017 return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
4018 } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
4019 // Default to "init"
4020 return methods.init.apply( this, arguments );
4022 $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
4027 $(document).ready(function() {
4029 $(document).on('click.card', '.card', function (e) {
4030 if ($(this).find('> .card-reveal').length) {
4031 if ($(e.target).is($('.card-reveal .card-title')) || $(e.target).is($('.card-reveal .card-title i'))) {
4032 // Make Reveal animate down and display none
4033 $(this).find('.card-reveal').velocity(
4037 easing: 'easeInOutQuad',
4038 complete: function() { $(this).css({ display: 'none'}); }
4042 else if ($(e.target).is($('.card .activator')) ||
4043 $(e.target).is($('.card .activator i')) ) {
4044 $(e.target).closest('.card').css('overflow', 'hidden');
4045 $(this).find('.card-reveal').css({ display: 'block'}).velocity("stop", false).velocity({translateY: '-100%'}, {duration: 300, queue: false, easing: 'easeInOutQuad'});
4051 }( jQuery ));;(function ($) {
4052 var materialChipsDefaults = {
4055 secondaryPlaceholder: '',
4056 autocompleteData: {},
4057 autocompleteLimit: Infinity,
4060 $(document).ready(function() {
4061 // Handle removal of static chips.
4062 $(document).on('click', '.chip .close', function(e){
4063 var $chips = $(this).closest('.chips');
4064 if ($chips.attr('data-initialized')) {
4067 $(this).closest('.chip').remove();
4071 $.fn.material_chip = function (options) {
4074 this.$document = $(document);
4079 DELETE: '.material-icons',
4080 SELECTED_CHIP: '.selected',
4083 if ('data' === options) {
4084 return this.$el.data('chips');
4087 var curr_options = $.extend({}, materialChipsDefaults, options);
4088 self.hasAutocomplete = !$.isEmptyObject(curr_options.autocompleteData);
4091 this.init = function() {
4094 self.$el.each(function(){
4095 var $chips = $(this);
4096 var chipId = Materialize.guid();
4097 self.chipId = chipId;
4099 if (!curr_options.data || !(curr_options.data instanceof Array)) {
4100 curr_options.data = [];
4102 $chips.data('chips', curr_options.data);
4103 $chips.attr('data-index', i);
4104 $chips.attr('data-initialized', true);
4106 if (!$chips.hasClass(self.SELS.CHIPS)) {
4107 $chips.addClass('chips');
4110 self.chips($chips, chipId);
4115 this.handleEvents = function() {
4116 var SELS = self.SELS;
4118 self.$document.off('click.chips-focus', SELS.CHIPS).on('click.chips-focus', SELS.CHIPS, function(e){
4119 $(e.target).find(SELS.INPUT).focus();
4122 self.$document.off('click.chips-select', SELS.CHIP).on('click.chips-select', SELS.CHIP, function(e){
4123 var $chip = $(e.target);
4125 var wasSelected = $chip.hasClass('selected');
4126 var $chips = $chip.closest(SELS.CHIPS);
4127 $(SELS.CHIP).removeClass('selected');
4130 self.selectChip($chip.index(), $chips);
4135 self.$document.off('keydown.chips').on('keydown.chips', function(e){
4136 if ($(e.target).is('input, textarea')) {
4141 var $chip = self.$document.find(SELS.CHIP + SELS.SELECTED_CHIP);
4142 var $chips = $chip.closest(SELS.CHIPS);
4143 var length = $chip.siblings(SELS.CHIP).length;
4146 if (!$chip.length) {
4150 if (e.which === 8 || e.which === 46) {
4153 index = $chip.index();
4154 self.deleteChip(index, $chips);
4156 var selectIndex = null;
4157 if ((index + 1) < length) {
4158 selectIndex = index;
4159 } else if (index === length || (index + 1) === length) {
4160 selectIndex = length - 1;
4163 if (selectIndex < 0) selectIndex = null;
4165 if (null !== selectIndex) {
4166 self.selectChip(selectIndex, $chips);
4168 if (!length) $chips.find('input').focus();
4171 } else if (e.which === 37) {
4172 index = $chip.index() - 1;
4176 $(SELS.CHIP).removeClass('selected');
4177 self.selectChip(index, $chips);
4180 } else if (e.which === 39) {
4181 index = $chip.index() + 1;
4182 $(SELS.CHIP).removeClass('selected');
4183 if (index > length) {
4184 $chips.find('input').focus();
4187 self.selectChip(index, $chips);
4191 self.$document.off('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT, function(e){
4192 var $currChips = $(e.target).closest(SELS.CHIPS);
4193 $currChips.addClass('focus');
4194 $currChips.siblings('label, .prefix').addClass('active');
4195 $(SELS.CHIP).removeClass('selected');
4198 self.$document.off('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT, function(e){
4199 var $currChips = $(e.target).closest(SELS.CHIPS);
4200 $currChips.removeClass('focus');
4202 // Remove active if empty
4203 if (!$currChips.data('chips').length) {
4204 $currChips.siblings('label').removeClass('active');
4206 $currChips.siblings('.prefix').removeClass('active');
4209 self.$document.off('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT).on('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT, function(e){
4210 var $target = $(e.target);
4211 var $chips = $target.closest(SELS.CHIPS);
4212 var chipsLength = $chips.children(SELS.CHIP).length;
4215 if (13 === e.which) {
4216 // Override enter if autocompleting.
4217 if (self.hasAutocomplete &&
4218 $chips.find('.autocomplete-content.dropdown-content').length &&
4219 $chips.find('.autocomplete-content.dropdown-content').children().length) {
4224 self.addChip({tag: $target.val()}, $chips);
4230 if ((8 === e.keyCode || 37 === e.keyCode) && '' === $target.val() && chipsLength) {
4232 self.selectChip(chipsLength - 1, $chips);
4238 // Click on delete icon in chip.
4239 self.$document.off('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE).on('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE, function(e) {
4240 var $target = $(e.target);
4241 var $chips = $target.closest(SELS.CHIPS);
4242 var $chip = $target.closest(SELS.CHIP);
4243 e.stopPropagation();
4244 self.deleteChip($chip.index(), $chips);
4245 $chips.find('input').focus();
4249 this.chips = function($chips, chipId) {
4251 $chips.data('chips').forEach(function(elem){
4252 html += self.renderChip(elem);
4254 html += '<input id="' + chipId +'" class="input" placeholder="">';
4256 self.setPlaceholder($chips);
4258 // Set for attribute for label
4259 var label = $chips.next('label');
4261 label.attr('for', chipId);
4263 if ($chips.data('chips').length) {
4264 label.addClass('active');
4268 // Setup autocomplete if needed.
4269 var input = $('#' + chipId);
4270 if (self.hasAutocomplete) {
4271 input.autocomplete({
4272 data: curr_options.autocompleteData,
4273 limit: curr_options.autocompleteLimit,
4274 onAutocomplete: function(val) {
4275 self.addChip({tag: val}, $chips);
4283 this.renderChip = function(elem) {
4284 if (!elem.tag) return;
4286 var html = '<div class="chip">' + elem.tag;
4288 html += ' <img src="' + elem.image + '"> ';
4290 html += '<i class="material-icons close">close</i>';
4295 this.setPlaceholder = function($chips) {
4296 if ($chips.data('chips').length && curr_options.placeholder) {
4297 $chips.find('input').prop('placeholder', curr_options.placeholder);
4299 } else if (!$chips.data('chips').length && curr_options.secondaryPlaceholder) {
4300 $chips.find('input').prop('placeholder', curr_options.secondaryPlaceholder);
4304 this.isValid = function($chips, elem) {
4305 var chips = $chips.data('chips');
4307 for (var i=0; i < chips.length; i++) {
4308 if (chips[i].tag === elem.tag) {
4313 return '' !== elem.tag && !exists;
4316 this.addChip = function(elem, $chips) {
4317 if (!self.isValid($chips, elem)) {
4320 var chipHtml = self.renderChip(elem);
4322 var oldData = $chips.data('chips');
4323 for (var i = 0; i < oldData.length; i++) {
4324 newData.push(oldData[i]);
4328 $chips.data('chips', newData);
4329 $(chipHtml).insertBefore($chips.find('input'));
4330 $chips.trigger('chip.add', elem);
4331 self.setPlaceholder($chips);
4334 this.deleteChip = function(chipIndex, $chips) {
4335 var chip = $chips.data('chips')[chipIndex];
4336 $chips.find('.chip').eq(chipIndex).remove();
4339 var oldData = $chips.data('chips');
4340 for (var i = 0; i < oldData.length; i++) {
4341 if (i !== chipIndex) {
4342 newData.push(oldData[i]);
4346 $chips.data('chips', newData);
4347 $chips.trigger('chip.delete', chip);
4348 self.setPlaceholder($chips);
4351 this.selectChip = function(chipIndex, $chips) {
4352 var $chip = $chips.find('.chip').eq(chipIndex);
4353 if ($chip && false === $chip.hasClass('selected')) {
4354 $chip.addClass('selected');
4355 $chips.trigger('chip.select', $chips.data('chips')[chipIndex]);
4359 this.getChipsElement = function(index, $chips) {
4360 return $chips.eq(index);
4366 this.handleEvents();
4370 $.fn.pushpin = function (options) {
4378 // Remove pushpin event and classes
4379 if (options === "remove") {
4380 this.each(function () {
4381 if (id = $(this).data('pushpin-id')) {
4382 $(window).off('scroll.' + id);
4383 $(this).removeData('pushpin-id').removeClass('pin-top pinned pin-bottom').removeAttr('style');
4389 options = $.extend(defaults, options);
4393 return this.each(function() {
4394 var $uniqueId = Materialize.guid(),
4396 $original_offset = $(this).offset().top;
4398 function removePinClasses(object) {
4399 object.removeClass('pin-top');
4400 object.removeClass('pinned');
4401 object.removeClass('pin-bottom');
4404 function updateElements(objects, scrolled) {
4405 objects.each(function () {
4406 // Add position fixed (because its between top and bottom)
4407 if (options.top <= scrolled && options.bottom >= scrolled && !$(this).hasClass('pinned')) {
4408 removePinClasses($(this));
4409 $(this).css('top', options.offset);
4410 $(this).addClass('pinned');
4413 // Add pin-top (when scrolled position is above top)
4414 if (scrolled < options.top && !$(this).hasClass('pin-top')) {
4415 removePinClasses($(this));
4416 $(this).css('top', 0);
4417 $(this).addClass('pin-top');
4420 // Add pin-bottom (when scrolled position is below bottom)
4421 if (scrolled > options.bottom && !$(this).hasClass('pin-bottom')) {
4422 removePinClasses($(this));
4423 $(this).addClass('pin-bottom');
4424 $(this).css('top', options.bottom - $original_offset);
4429 $(this).data('pushpin-id', $uniqueId);
4430 updateElements($this, $(window).scrollTop());
4431 $(window).on('scroll.' + $uniqueId, function () {
4432 var $scrolled = $(window).scrollTop() + options.offset;
4433 updateElements($this, $scrolled);
4439 }( jQuery ));;(function ($) {
4440 $(document).ready(function() {
4443 $.fn.reverse = [].reverse;
4445 // Hover behaviour: make sure this doesn't work on .click-to-toggle FABs!
4446 $(document).on('mouseenter.fixedActionBtn', '.fixed-action-btn:not(.click-to-toggle):not(.toolbar)', function(e) {
4447 var $this = $(this);
4450 $(document).on('mouseleave.fixedActionBtn', '.fixed-action-btn:not(.click-to-toggle):not(.toolbar)', function(e) {
4451 var $this = $(this);
4452 closeFABMenu($this);
4455 // Toggle-on-click behaviour.
4456 $(document).on('click.fabClickToggle', '.fixed-action-btn.click-to-toggle > a', function(e) {
4457 var $this = $(this);
4458 var $menu = $this.parent();
4459 if ($menu.hasClass('active')) {
4460 closeFABMenu($menu);
4466 // Toolbar transition behaviour.
4467 $(document).on('click.fabToolbar', '.fixed-action-btn.toolbar > a', function(e) {
4468 var $this = $(this);
4469 var $menu = $this.parent();
4470 FABtoToolbar($menu);
4476 openFAB: function() {
4477 openFABMenu($(this));
4479 closeFAB: function() {
4480 closeFABMenu($(this));
4482 openToolbar: function() {
4483 FABtoToolbar($(this));
4485 closeToolbar: function() {
4486 toolbarToFAB($(this));
4491 var openFABMenu = function (btn) {
4493 if ($this.hasClass('active') === false) {
4495 // Get direction option
4496 var horizontal = $this.hasClass('horizontal');
4497 var offsetY, offsetX;
4499 if (horizontal === true) {
4505 $this.addClass('active');
4506 $this.find('ul .btn-floating').velocity(
4507 { scaleY: ".4", scaleX: ".4", translateY: offsetY + 'px', translateX: offsetX + 'px'},
4511 $this.find('ul .btn-floating').reverse().each( function () {
4513 { opacity: "1", scaleX: "1", scaleY: "1", translateY: "0", translateX: '0'},
4514 { duration: 80, delay: time });
4520 var closeFABMenu = function (btn) {
4522 // Get direction option
4523 var horizontal = $this.hasClass('horizontal');
4524 var offsetY, offsetX;
4526 if (horizontal === true) {
4532 $this.removeClass('active');
4534 $this.find('ul .btn-floating').velocity("stop", true);
4535 $this.find('ul .btn-floating').velocity(
4536 { opacity: "0", scaleX: ".4", scaleY: ".4", translateY: offsetY + 'px', translateX: offsetX + 'px'},
4543 * Transform FAB into toolbar
4544 * @param {Object} object jQuery object
4546 var FABtoToolbar = function(btn) {
4547 if (btn.attr('data-open') === "true") {
4551 var offsetX, offsetY, scaleFactor;
4552 var windowWidth = window.innerWidth;
4553 var windowHeight = window.innerHeight;
4554 var btnRect = btn[0].getBoundingClientRect();
4555 var anchor = btn.find('> a').first();
4556 var menu = btn.find('> ul').first();
4557 var backdrop = $('<div class="fab-backdrop"></div>');
4558 var fabColor = anchor.css('background-color');
4559 anchor.append(backdrop);
4561 offsetX = btnRect.left - (windowWidth / 2) + (btnRect.width / 2);
4562 offsetY = windowHeight - btnRect.bottom;
4563 scaleFactor = windowWidth / backdrop.width();
4564 btn.attr('data-origin-bottom', btnRect.bottom);
4565 btn.attr('data-origin-left', btnRect.left);
4566 btn.attr('data-origin-width', btnRect.width);
4568 // Set initial state
4569 btn.addClass('active');
4570 btn.attr('data-open', true);
4572 'text-align': 'center',
4576 transform: 'translateX(' + offsetX + 'px)',
4580 transform: 'translateY(' + -offsetY + 'px)',
4584 'background-color': fabColor
4588 setTimeout(function() {
4591 transition: 'transform .2s cubic-bezier(0.550, 0.085, 0.680, 0.530), background-color 0s linear .2s'
4594 overflow: 'visible',
4596 transition: 'transform .2s'
4599 setTimeout(function() {
4602 'background-color': fabColor
4605 transform: 'scale(' + scaleFactor + ')',
4606 transition: 'transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)'
4608 menu.find('> li > a').css({
4613 $(window).on('scroll.fabToolbarClose', function() {
4615 $(window).off('scroll.fabToolbarClose');
4616 $(document).off('click.fabToolbarClose');
4619 $(document).on('click.fabToolbarClose', function(e) {
4620 if (!$(e.target).closest(menu).length) {
4622 $(window).off('scroll.fabToolbarClose');
4623 $(document).off('click.fabToolbarClose');
4631 * Transform toolbar back into FAB
4632 * @param {Object} object jQuery object
4634 var toolbarToFAB = function(btn) {
4635 if (btn.attr('data-open') !== "true") {
4639 var offsetX, offsetY, scaleFactor;
4640 var windowWidth = window.innerWidth;
4641 var windowHeight = window.innerHeight;
4642 var btnWidth = btn.attr('data-origin-width');
4643 var btnBottom = btn.attr('data-origin-bottom');
4644 var btnLeft = btn.attr('data-origin-left');
4645 var anchor = btn.find('> .btn-floating').first();
4646 var menu = btn.find('> ul').first();
4647 var backdrop = btn.find('.fab-backdrop');
4648 var fabColor = anchor.css('background-color');
4650 offsetX = btnLeft - (windowWidth / 2) + (btnWidth / 2);
4651 offsetY = windowHeight - btnBottom;
4652 scaleFactor = windowWidth / backdrop.width();
4656 btn.removeClass('active');
4657 btn.attr('data-open', false);
4659 'background-color': 'transparent',
4666 transform: 'scale(0)',
4667 'background-color': fabColor
4669 menu.find('> li > a').css({
4673 setTimeout(function() {
4676 // Set initial state.
4683 'background-color': '',
4684 transform: 'translate3d(' + -offsetX + 'px,0,0)'
4688 transform: 'translate3d(0,' + offsetY + 'px,0)'
4691 setTimeout(function() {
4693 transform: 'translate3d(0,0,0)',
4694 transition: 'transform .2s'
4697 transform: 'translate3d(0,0,0)',
4698 transition: 'transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)'
4707 // Image transition function
4708 Materialize.fadeInImage = function(selectorOrEl) {
4710 if (typeof(selectorOrEl) === 'string') {
4711 element = $(selectorOrEl);
4712 } else if (typeof(selectorOrEl) === 'object') {
4713 element = selectorOrEl;
4717 element.css({opacity: 0});
4718 $(element).velocity({opacity: 1}, {
4721 easing: 'easeOutSine'
4723 $(element).velocity({opacity: 1}, {
4727 step: function(now, fx) {
4729 var grayscale_setting = now/100;
4730 var brightness_setting = 150 - (100 - now)/1.75;
4732 if (brightness_setting < 100) {
4733 brightness_setting = 100;
4737 "-webkit-filter": "grayscale("+grayscale_setting+")" + "brightness("+brightness_setting+"%)",
4738 "filter": "grayscale("+grayscale_setting+")" + "brightness("+brightness_setting+"%)"
4745 // Horizontal staggered list
4746 Materialize.showStaggeredList = function(selectorOrEl) {
4748 if (typeof(selectorOrEl) === 'string') {
4749 element = $(selectorOrEl);
4750 } else if (typeof(selectorOrEl) === 'object') {
4751 element = selectorOrEl;
4756 element.find('li').velocity(
4757 { translateX: "-100px"},
4760 element.find('li').each(function() {
4762 { opacity: "1", translateX: "0"},
4763 { duration: 800, delay: time, easing: [60, 10] });
4769 $(document).ready(function() {
4770 // Hardcoded .staggered-list scrollFire
4771 // var staggeredListOptions = [];
4772 // $('ul.staggered-list').each(function (i) {
4774 // var label = 'scrollFire-' + i;
4775 // $(this).addClass(label);
4776 // staggeredListOptions.push(
4777 // {selector: 'ul.staggered-list.' + label,
4779 // callback: 'showStaggeredList("ul.staggered-list.' + label + '")'});
4781 // scrollFire(staggeredListOptions);
4783 // HammerJS, Swipe navigation
4786 var swipeLeft = false;
4787 var swipeRight = false;
4790 // Dismissible Collections
4791 $('.dismissable').each(function() {
4793 prevent_default: false
4794 }).bind('pan', function(e) {
4795 if (e.gesture.pointerType === "touch") {
4796 var $this = $(this);
4797 var direction = e.gesture.direction;
4798 var x = e.gesture.deltaX;
4799 var velocityX = e.gesture.velocityX;
4801 $this.velocity({ translateX: x
4802 }, {duration: 50, queue: false, easing: 'easeOutQuad'});
4805 if (direction === 4 && (x > ($this.innerWidth() / 2) || velocityX < -0.75)) {
4810 if (direction === 2 && (x < (-1 * $this.innerWidth() / 2) || velocityX > 0.75)) {
4814 }).bind('panend', function(e) {
4815 // Reset if collection is moved back into original position
4816 if (Math.abs(e.gesture.deltaX) < ($(this).innerWidth() / 2)) {
4821 if (e.gesture.pointerType === "touch") {
4822 var $this = $(this);
4823 if (swipeLeft || swipeRight) {
4825 if (swipeLeft) { fullWidth = $this.innerWidth(); }
4826 else { fullWidth = -1 * $this.innerWidth(); }
4828 $this.velocity({ translateX: fullWidth,
4829 }, {duration: 100, queue: false, easing: 'easeOutQuad', complete:
4831 $this.css('border', 'none');
4832 $this.velocity({ height: 0, padding: 0,
4833 }, {duration: 200, queue: false, easing: 'easeOutQuad', complete:
4834 function() { $this.remove(); }
4840 $this.velocity({ translateX: 0,
4841 }, {duration: 100, queue: false, easing: 'easeOutQuad'});
4852 // // Vertical Staggered list
4853 // $('ul.staggered-list.vertical li').velocity(
4854 // { translateY: "100px"},
4855 // { duration: 0 });
4857 // $('ul.staggered-list.vertical li').each(function() {
4858 // $(this).velocity(
4859 // { opacity: "1", translateY: "0"},
4860 // { duration: 800, delay: time, easing: [60, 25] });
4864 // // Fade in and Scale
4865 // $('.fade-in.scale').velocity(
4866 // { scaleX: .4, scaleY: .4, translateX: -600},
4868 // $('.fade-in').each(function() {
4869 // $(this).velocity(
4870 // { opacity: "1", scaleX: 1, scaleY: 1, translateX: 0},
4871 // { duration: 800, easing: [60, 10] });
4877 var scrollFireEventsHandled = false;
4879 // Input: Array of JSON objects {selector, offset, callback}
4880 Materialize.scrollFire = function(options) {
4881 var onScroll = function() {
4882 var windowScroll = window.pageYOffset + window.innerHeight;
4884 for (var i = 0 ; i < options.length; i++) {
4885 // Get options from each line
4886 var value = options[i];
4887 var selector = value.selector,
4888 offset = value.offset,
4889 callback = value.callback;
4891 var currentElement = document.querySelector(selector);
4892 if ( currentElement !== null) {
4893 var elementOffset = currentElement.getBoundingClientRect().top + window.pageYOffset;
4895 if (windowScroll > (elementOffset + offset)) {
4896 if (value.done !== true) {
4897 if (typeof(callback) === 'function') {
4898 callback.call(this, currentElement);
4899 } else if (typeof(callback) === 'string') {
4900 var callbackFunc = new Function(callback);
4901 callbackFunc(currentElement);
4911 var throttledScroll = Materialize.throttle(function() {
4913 }, options.throttle || 100);
4915 if (!scrollFireEventsHandled) {
4916 window.addEventListener("scroll", throttledScroll);
4917 window.addEventListener("resize", throttledScroll);
4918 scrollFireEventsHandled = true;
4921 // perform a scan once, after current execution context, and after dom is ready
4922 setTimeout(throttledScroll, 0);
4927 * pickadate.js v3.5.0, 2014/04/13
4928 * By Amsul, http://amsul.ca
4929 * Hosted on http://amsul.github.io/pickadate.js
4930 * Licensed under MIT
4933 (function ( factory ) {
4936 if ( typeof define == 'function' && define.amd )
4937 define( 'picker', ['jquery'], factory )
4939 // Node.js/browserify.
4940 else if ( typeof exports == 'object' )
4941 module.exports = factory( require('jquery') )
4944 else this.Picker = factory( jQuery )
4948 var $window = $( window )
4949 var $document = $( document )
4950 var $html = $( document.documentElement )
4954 * The picker constructor that creates a blank picker.
4956 function PickerConstructor( ELEMENT, NAME, COMPONENT, OPTIONS ) {
4958 // If there’s no element, return the picker constructor.
4959 if ( !ELEMENT ) return PickerConstructor
4963 IS_DEFAULT_THEME = false,
4966 // The state of the picker.
4968 id: ELEMENT.id || 'P' + Math.abs( ~~(Math.random() * new Date()) )
4972 // Merge the defaults and options passed.
4973 SETTINGS = COMPONENT ? $.extend( true, {}, COMPONENT.defaults, OPTIONS ) : OPTIONS || {},
4976 // Merge the default classes with the settings classes.
4977 CLASSES = $.extend( {}, PickerConstructor.klasses(), SETTINGS.klass ),
4980 // The element node wrapper into a jQuery object.
4981 $ELEMENT = $( ELEMENT ),
4984 // Pseudo picker constructor.
4985 PickerInstance = function() {
4990 // The picker prototype.
4991 P = PickerInstance.prototype = {
4993 constructor: PickerInstance,
4999 * Initialize everything
5003 // If it’s already started, do nothing.
5004 if ( STATE && STATE.start ) return P
5007 // Update the picker states.
5011 STATE.type = ELEMENT.type
5014 // Confirm focus state, convert into text input to remove UA stylings,
5015 // and set as readonly to prevent keyboard popup.
5016 ELEMENT.autofocus = ELEMENT == getActiveElement()
5017 ELEMENT.readOnly = !SETTINGS.editable
5018 ELEMENT.id = ELEMENT.id || STATE.id
5019 if ( ELEMENT.type != 'text' ) {
5020 ELEMENT.type = 'text'
5024 // Create a new picker component with the settings.
5025 P.component = new COMPONENT(P, SETTINGS)
5028 // Create the picker root with a holder and then prepare it.
5029 P.$root = $( PickerConstructor._.node('div', createWrappedComponent(), CLASSES.picker, 'id="' + ELEMENT.id + '_root" tabindex="0"') )
5030 prepareElementRoot()
5033 // If there’s a format for the hidden input element, create the element.
5034 if ( SETTINGS.formatSubmit ) {
5035 prepareElementHidden()
5039 // Prepare the input element.
5043 // Insert the root as specified in the settings.
5044 if ( SETTINGS.container ) $( SETTINGS.container ).append( P.$root )
5045 else $ELEMENT.after( P.$root )
5048 // Bind the default component and settings events.
5050 start: P.component.onStart,
5051 render: P.component.onRender,
5052 stop: P.component.onStop,
5053 open: P.component.onOpen,
5054 close: P.component.onClose,
5055 set: P.component.onSet
5057 start: SETTINGS.onStart,
5058 render: SETTINGS.onRender,
5059 stop: SETTINGS.onStop,
5060 open: SETTINGS.onOpen,
5061 close: SETTINGS.onClose,
5066 // Once we’re all set, check the theme in use.
5067 IS_DEFAULT_THEME = isUsingDefaultTheme( P.$root.children()[ 0 ] )
5070 // If the element has autofocus, open the picker.
5071 if ( ELEMENT.autofocus ) {
5076 // Trigger queued the “start” and “render” events.
5077 return P.trigger( 'start' ).trigger( 'render' )
5082 * Render a new picker
5084 render: function( entireComponent ) {
5086 // Insert a new component holder in the root or box.
5087 if ( entireComponent ) P.$root.html( createWrappedComponent() )
5088 else P.$root.find( '.' + CLASSES.box ).html( P.component.nodes( STATE.open ) )
5090 // Trigger the queued “render” events.
5091 return P.trigger( 'render' )
5096 * Destroy everything
5100 // If it’s already stopped, do nothing.
5101 if ( !STATE.start ) return P
5103 // Then close the picker.
5106 // Remove the hidden field.
5108 P._hidden.parentNode.removeChild( P._hidden )
5114 // Remove the input class, remove the stored data, and unbind
5115 // the events (after a tick for IE - see `P.close`).
5116 $ELEMENT.removeClass( CLASSES.input ).removeData( NAME )
5117 setTimeout( function() {
5118 $ELEMENT.off( '.' + STATE.id )
5121 // Restore the element state
5122 ELEMENT.type = STATE.type
5123 ELEMENT.readOnly = false
5125 // Trigger the queued “stop” events.
5128 // Reset the picker states.
5137 * Open up the picker
5139 open: function( dontGiveFocus ) {
5141 // If it’s already open, do nothing.
5142 if ( STATE.open ) return P
5144 // Add the “active” class.
5145 $ELEMENT.addClass( CLASSES.active )
5146 aria( ELEMENT, 'expanded', true )
5148 // * A Firefox bug, when `html` has `overflow:hidden`, results in
5149 // killing transitions :(. So add the “opened” state on the next tick.
5150 // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
5151 setTimeout( function() {
5153 // Add the “opened” class to the picker root.
5154 P.$root.addClass( CLASSES.opened )
5155 aria( P.$root[0], 'hidden', false )
5159 // If we have to give focus, bind the element and doc events.
5160 if ( dontGiveFocus !== false ) {
5165 // Prevent the page from scrolling.
5166 if ( IS_DEFAULT_THEME ) {
5168 css( 'overflow', 'hidden' ).
5169 css( 'padding-right', '+=' + getScrollbarWidth() )
5172 // Pass focus to the root element’s jQuery object.
5173 // * Workaround for iOS8 to bring the picker’s root into view.
5174 P.$root.eq(0).focus()
5176 // Bind the document events.
5177 $document.on( 'click.' + STATE.id + ' focusin.' + STATE.id, function( event ) {
5179 var target = event.target
5181 // If the target of the event is not the element, close the picker picker.
5182 // * Don’t worry about clicks or focusins on the root because those don’t bubble up.
5183 // Also, for Firefox, a click on an `option` element bubbles up directly
5184 // to the doc. So make sure the target wasn't the doc.
5185 // * In Firefox stopPropagation() doesn’t prevent right-click events from bubbling,
5186 // which causes the picker to unexpectedly close when right-clicking it. So make
5187 // sure the event wasn’t a right-click.
5188 if ( target != ELEMENT && target != document && event.which != 3 ) {
5190 // If the target was the holder that covers the screen,
5191 // keep the element focused to maintain tabindex.
5192 P.close( target === P.$root.children()[0] )
5195 }).on( 'keydown.' + STATE.id, function( event ) {
5199 keycode = event.keyCode,
5201 // Translate that to a selection change.
5202 keycodeToMove = P.component.key[ keycode ],
5205 target = event.target
5208 // On escape, close the picker and give focus.
5209 if ( keycode == 27 ) {
5214 // Check if there is a key movement or “enter” keypress on the element.
5215 else if ( target == P.$root[0] && ( keycodeToMove || keycode == 13 ) ) {
5217 // Prevent the default action to stop page movement.
5218 event.preventDefault()
5220 // Trigger the key movement action.
5221 if ( keycodeToMove ) {
5222 PickerConstructor._.trigger( P.component.key.go, P, [ PickerConstructor._.trigger( keycodeToMove ) ] )
5225 // On “enter”, if the highlighted item isn’t disabled, set the value and close.
5226 else if ( !P.$root.find( '.' + CLASSES.highlighted ).hasClass( CLASSES.disabled ) ) {
5227 P.set( 'select', P.component.item.highlight ).close()
5232 // If the target is within the root and “enter” is pressed,
5233 // prevent the default action and trigger a click on the target instead.
5234 else if ( $.contains( P.$root[0], target ) && keycode == 13 ) {
5235 event.preventDefault()
5241 // Trigger the queued “open” events.
5242 return P.trigger( 'open' )
5249 close: function( giveFocus ) {
5251 // If we need to give focus, do it before changing states.
5253 // ....ah yes! It would’ve been incomplete without a crazy workaround for IE :|
5254 // The focus is triggered *after* the close has completed - causing it
5255 // to open again. So unbind and rebind the event at the next tick.
5256 P.$root.off( 'focus.toOpen' ).eq(0).focus()
5257 setTimeout( function() {
5258 P.$root.on( 'focus.toOpen', handleFocusToOpenEvent )
5262 // Remove the “active” class.
5263 $ELEMENT.removeClass( CLASSES.active )
5264 aria( ELEMENT, 'expanded', false )
5266 // * A Firefox bug, when `html` has `overflow:hidden`, results in
5267 // killing transitions :(. So remove the “opened” state on the next tick.
5268 // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
5269 setTimeout( function() {
5271 // Remove the “opened” and “focused” class from the picker root.
5272 P.$root.removeClass( CLASSES.opened + ' ' + CLASSES.focused )
5273 aria( P.$root[0], 'hidden', true )
5277 // If it’s already closed, do nothing more.
5278 if ( !STATE.open ) return P
5280 // Set it as closed.
5283 // Allow the page to scroll.
5284 if ( IS_DEFAULT_THEME ) {
5286 css( 'overflow', '' ).
5287 css( 'padding-right', '-=' + getScrollbarWidth() )
5290 // Unbind the document events.
5291 $document.off( '.' + STATE.id )
5293 // Trigger the queued “close” events.
5294 return P.trigger( 'close' )
5301 clear: function( options ) {
5302 return P.set( 'clear', null, options )
5309 set: function( thing, value, options ) {
5311 var thingItem, thingValue,
5312 thingIsObject = $.isPlainObject( thing ),
5313 thingObject = thingIsObject ? thing : {}
5315 // Make sure we have usable options.
5316 options = thingIsObject && $.isPlainObject( value ) ? value : options || {}
5320 // If the thing isn’t an object, make it one.
5321 if ( !thingIsObject ) {
5322 thingObject[ thing ] = value
5325 // Go through the things of items to set.
5326 for ( thingItem in thingObject ) {
5328 // Grab the value of the thing.
5329 thingValue = thingObject[ thingItem ]
5331 // First, if the item exists and there’s a value, set it.
5332 if ( thingItem in P.component.item ) {
5333 if ( thingValue === undefined ) thingValue = null
5334 P.component.set( thingItem, thingValue, options )
5337 // Then, check to update the element value and broadcast a change.
5338 if ( thingItem == 'select' || thingItem == 'clear' ) {
5340 val( thingItem == 'clear' ? '' : P.get( thingItem, SETTINGS.format ) ).
5345 // Render a new picker.
5349 // When the method isn’t muted, trigger queued “set” events and pass the `thingObject`.
5350 return options.muted ? P : P.trigger( 'set', thingObject )
5357 get: function( thing, format ) {
5359 // Make sure there’s something to get.
5360 thing = thing || 'value'
5362 // If a picker state exists, return that.
5363 if ( STATE[ thing ] != null ) {
5364 return STATE[ thing ]
5367 // Return the submission value, if that.
5368 if ( thing == 'valueSubmit' ) {
5370 return P._hidden.value
5375 // Return the value, if that.
5376 if ( thing == 'value' ) {
5377 return ELEMENT.value
5380 // Check if a component item exists, return that.
5381 if ( thing in P.component.item ) {
5382 if ( typeof format == 'string' ) {
5383 var thingValue = P.component.get( thing )
5385 PickerConstructor._.trigger(
5386 P.component.formats.toString,
5388 [ format, thingValue ]
5391 return P.component.get( thing )
5398 * Bind events on the things.
5400 on: function( thing, method, internal ) {
5402 var thingName, thingMethod,
5403 thingIsObject = $.isPlainObject( thing ),
5404 thingObject = thingIsObject ? thing : {}
5408 // If the thing isn’t an object, make it one.
5409 if ( !thingIsObject ) {
5410 thingObject[ thing ] = method
5413 // Go through the things to bind to.
5414 for ( thingName in thingObject ) {
5416 // Grab the method of the thing.
5417 thingMethod = thingObject[ thingName ]
5419 // If it was an internal binding, prefix it.
5421 thingName = '_' + thingName
5424 // Make sure the thing methods collection exists.
5425 STATE.methods[ thingName ] = STATE.methods[ thingName ] || []
5427 // Add the method to the relative method collection.
5428 STATE.methods[ thingName ].push( thingMethod )
5438 * Unbind events on the things.
5443 for ( i = 0, namesCount = names.length; i < namesCount; i += 1 ) {
5444 thingName = names[i]
5445 if ( thingName in STATE.methods ) {
5446 delete STATE.methods[thingName]
5454 * Fire off method events.
5456 trigger: function( name, data ) {
5457 var _trigger = function( name ) {
5458 var methodList = STATE.methods[ name ]
5460 methodList.map( function( method ) {
5461 PickerConstructor._.trigger( method, P, [ data ] )
5465 _trigger( '_' + name )
5469 } //PickerInstance.prototype
5473 * Wrap the picker holder components together.
5475 function createWrappedComponent() {
5477 // Create a picker wrapper holder
5478 return PickerConstructor._.node( 'div',
5480 // Create a picker wrapper node
5481 PickerConstructor._.node( 'div',
5483 // Create a picker frame
5484 PickerConstructor._.node( 'div',
5486 // Create a picker box node
5487 PickerConstructor._.node( 'div',
5489 // Create the components nodes.
5490 P.component.nodes( STATE.open ),
5492 // The picker box class
5496 // Picker wrap class
5500 // Picker frame class
5504 // Picker holder class
5507 } //createWrappedComponent
5512 * Prepare the input element with all bindings.
5514 function prepareElement() {
5518 // Store the picker data by component name.
5521 // Add the “input” class name.
5522 addClass(CLASSES.input).
5524 // Remove the tabindex.
5525 attr('tabindex', -1).
5527 // If there’s a `data-value`, update the value of the element.
5528 val( $ELEMENT.data('value') ?
5529 P.get('select', SETTINGS.format) :
5534 // Only bind keydown events if the element isn’t editable.
5535 if ( !SETTINGS.editable ) {
5539 // On focus/click, focus onto the root to open it up.
5540 on( 'focus.' + STATE.id + ' click.' + STATE.id, function( event ) {
5541 event.preventDefault()
5542 P.$root.eq(0).focus()
5545 // Handle keyboard event based on the picker being opened or not.
5546 on( 'keydown.' + STATE.id, handleKeydownEvent )
5550 // Update the aria attributes.
5555 owns: ELEMENT.id + '_root'
5561 * Prepare the root picker element with all bindings.
5563 function prepareElementRoot() {
5570 keydown: handleKeydownEvent,
5572 // When something within the root is focused, stop from bubbling
5573 // to the doc and remove the “focused” state from the root.
5574 focusin: function( event ) {
5575 P.$root.removeClass( CLASSES.focused )
5576 event.stopPropagation()
5579 // When something within the root holder is clicked, stop it
5580 // from bubbling to the doc.
5581 'mousedown click': function( event ) {
5583 var target = event.target
5585 // Make sure the target isn’t the root holder so it can bubble up.
5586 if ( target != P.$root.children()[ 0 ] ) {
5588 event.stopPropagation()
5590 // * For mousedown events, cancel the default action in order to
5591 // prevent cases where focus is shifted onto external elements
5592 // when using things like jQuery mobile or MagnificPopup (ref: #249 & #120).
5593 // Also, for Firefox, don’t prevent action on the `option` element.
5594 if ( event.type == 'mousedown' && !$( target ).is( 'input, select, textarea, button, option' )) {
5596 event.preventDefault()
5598 // Re-focus onto the root so that users can click away
5599 // from elements focused within the picker.
5600 P.$root.eq(0).focus()
5606 // Add/remove the “target” class on focus and blur.
5609 $ELEMENT.addClass( CLASSES.target )
5612 $ELEMENT.removeClass( CLASSES.target )
5616 // Open the picker and adjust the root “focused” state
5617 on( 'focus.toOpen', handleFocusToOpenEvent ).
5619 // If there’s a click on an actionable element, carry out the actions.
5620 on( 'click', '[data-pick], [data-nav], [data-clear], [data-close]', function() {
5622 var $target = $( this ),
5623 targetData = $target.data(),
5624 targetDisabled = $target.hasClass( CLASSES.navDisabled ) || $target.hasClass( CLASSES.disabled ),
5626 // * For IE, non-focusable elements can be active elements as well
5627 // (http://stackoverflow.com/a/2684561).
5628 activeElement = getActiveElement()
5629 activeElement = activeElement && ( activeElement.type || activeElement.href )
5631 // If it’s disabled or nothing inside is actively focused, re-focus the element.
5632 if ( targetDisabled || activeElement && !$.contains( P.$root[0], activeElement ) ) {
5633 P.$root.eq(0).focus()
5636 // If something is superficially changed, update the `highlight` based on the `nav`.
5637 if ( !targetDisabled && targetData.nav ) {
5638 P.set( 'highlight', P.component.item.highlight, { nav: targetData.nav } )
5641 // If something is picked, set `select` then close with focus.
5642 else if ( !targetDisabled && 'pick' in targetData ) {
5643 P.set( 'select', targetData.pick )
5646 // If a “clear” button is pressed, empty the values and close with focus.
5647 else if ( targetData.clear ) {
5648 P.clear().close( true )
5651 else if ( targetData.close ) {
5657 aria( P.$root[0], 'hidden', true )
5662 * Prepare the hidden input element along with all bindings.
5664 function prepareElementHidden() {
5668 if ( SETTINGS.hiddenName === true ) {
5674 typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '',
5675 typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'
5677 name = name[0] + ELEMENT.name + name[1]
5684 // Create the name using the original input’s with a prefix and suffix.
5685 'name="' + name + '"' +
5687 // If the element has a value, set the hidden value as well.
5689 $ELEMENT.data('value') || ELEMENT.value ?
5690 ' value="' + P.get('select', SETTINGS.formatSubmit) + '"' :
5698 // If the value changes, update the hidden input with the correct format.
5699 on('change.' + STATE.id, function() {
5700 P._hidden.value = ELEMENT.value ?
5701 P.get('select', SETTINGS.formatSubmit) :
5706 // Insert the hidden input as specified in the settings.
5707 if ( SETTINGS.container ) $( SETTINGS.container ).append( P._hidden )
5708 else $ELEMENT.after( P._hidden )
5713 function handleKeydownEvent( event ) {
5715 var keycode = event.keyCode,
5717 // Check if one of the delete keys was pressed.
5718 isKeycodeDelete = /^(8|46)$/.test(keycode)
5720 // For some reason IE clears the input value on “escape”.
5721 if ( keycode == 27 ) {
5726 // Check if `space` or `delete` was pressed or the picker is closed with a key movement.
5727 if ( keycode == 32 || isKeycodeDelete || !STATE.open && P.component.key[keycode] ) {
5729 // Prevent it from moving the page and bubbling to doc.
5730 event.preventDefault()
5731 event.stopPropagation()
5733 // If `delete` was pressed, clear the values and close the picker.
5734 // Otherwise open the picker.
5735 if ( isKeycodeDelete ) { P.clear().close() }
5742 function handleFocusToOpenEvent( event ) {
5744 // Stop the event from propagating to the doc.
5745 event.stopPropagation()
5747 // If it’s a focus event, add the “focused” class to the root.
5748 if ( event.type == 'focus' ) {
5749 P.$root.addClass( CLASSES.focused )
5752 // And then finally open the picker.
5757 // Return a new picker instance.
5758 return new PickerInstance()
5759 } //PickerConstructor
5764 * The default classes and prefix to use for the HTML classes.
5766 PickerConstructor.klasses = function( prefix ) {
5767 prefix = prefix || 'picker'
5771 opened: prefix + '--opened',
5772 focused: prefix + '--focused',
5774 input: prefix + '__input',
5775 active: prefix + '__input--active',
5776 target: prefix + '__input--target',
5778 holder: prefix + '__holder',
5780 frame: prefix + '__frame',
5781 wrap: prefix + '__wrap',
5783 box: prefix + '__box'
5785 } //PickerConstructor.klasses
5790 * Check if the default theme is being used.
5792 function isUsingDefaultTheme( element ) {
5798 if ( element.currentStyle ) {
5799 theme = element.currentStyle[prop]
5802 // For normal browsers.
5803 else if ( window.getComputedStyle ) {
5804 theme = getComputedStyle( element )[prop]
5807 return theme == 'fixed'
5813 * Get the width of the browser’s scrollbar.
5814 * Taken from: https://github.com/VodkaBears/Remodal/blob/master/src/jquery.remodal.js
5816 function getScrollbarWidth() {
5818 if ( $html.height() <= $window.height() ) {
5822 var $outer = $( '<div style="visibility:hidden;width:100px" />' ).
5825 // Get the width without scrollbars.
5826 var widthWithoutScroll = $outer[0].offsetWidth
5828 // Force adding scrollbars.
5829 $outer.css( 'overflow', 'scroll' )
5831 // Add the inner div.
5832 var $inner = $( '<div style="width:100%" />' ).appendTo( $outer )
5834 // Get the width with scrollbars.
5835 var widthWithScroll = $inner[0].offsetWidth
5840 // Return the difference between the widths.
5841 return widthWithoutScroll - widthWithScroll
5847 * PickerConstructor helper methods.
5849 PickerConstructor._ = {
5852 * Create a group of nodes. Expects:
5863 group: function( groupObject ) {
5866 // Scope for the looped object
5869 // Create the nodes list
5872 // The counter starts from the `min`
5873 counter = PickerConstructor._.trigger( groupObject.min, groupObject )
5876 // Loop from the `min` to `max`, incrementing by `i`
5877 for ( ; counter <= PickerConstructor._.trigger( groupObject.max, groupObject, [ counter ] ); counter += groupObject.i ) {
5879 // Trigger the `item` function within scope of the object
5880 loopObjectScope = PickerConstructor._.trigger( groupObject.item, groupObject, [ counter ] )
5882 // Splice the subgroup and create nodes out of the sub nodes
5883 nodesList += PickerConstructor._.node(
5885 loopObjectScope[ 0 ], // the node
5886 loopObjectScope[ 1 ], // the classes
5887 loopObjectScope[ 2 ] // the attributes
5891 // Return the list of nodes
5897 * Create a dom node string
5899 node: function( wrapper, item, klass, attribute ) {
5901 // If the item is false-y, just return an empty string
5902 if ( !item ) return ''
5904 // If the item is an array, do a join
5905 item = $.isArray( item ) ? item.join( '' ) : item
5907 // Check for the class
5908 klass = klass ? ' class="' + klass + '"' : ''
5910 // Check for any attributes
5911 attribute = attribute ? ' ' + attribute : ''
5913 // Return the wrapped item
5914 return '<' + wrapper + klass + attribute + '>' + item + '</' + wrapper + '>'
5919 * Lead numbers below 10 with a zero.
5921 lead: function( number ) {
5922 return ( number < 10 ? '0': '' ) + number
5927 * Trigger a function otherwise return the value.
5929 trigger: function( callback, scope, args ) {
5930 return typeof callback == 'function' ? callback.apply( scope, args || [] ) : callback
5935 * If the second character is a digit, length is 2 otherwise 1.
5937 digits: function( string ) {
5938 return ( /\d/ ).test( string[ 1 ] ) ? 2 : 1
5943 * Tell if something is a date object.
5945 isDate: function( value ) {
5946 return {}.toString.call( value ).indexOf( 'Date' ) > -1 && this.isInteger( value.getDate() )
5951 * Tell if something is an integer.
5953 isInteger: function( value ) {
5954 return {}.toString.call( value ).indexOf( 'Number' ) > -1 && value % 1 === 0
5959 * Create ARIA attribute strings.
5962 } //PickerConstructor._
5967 * Extend the picker with a component and defaults.
5969 PickerConstructor.extend = function( name, Component ) {
5972 $.fn[ name ] = function( options, action ) {
5974 // Grab the component data.
5975 var componentData = this.data( name )
5977 // If the picker is requested, return the data object.
5978 if ( options == 'picker' ) {
5979 return componentData
5982 // If the component data exists and `options` is a string, carry out the action.
5983 if ( componentData && typeof options == 'string' ) {
5984 return PickerConstructor._.trigger( componentData[ options ], componentData, [ action ] )
5987 // Otherwise go through each matched element and if the component
5988 // doesn’t exist, create a new picker using `this` element
5989 // and merging the defaults and options with a deep copy.
5990 return this.each( function() {
5991 var $this = $( this )
5992 if ( !$this.data( name ) ) {
5993 new PickerConstructor( this, name, Component, options )
5998 // Set the defaults.
5999 $.fn[ name ].defaults = Component.defaults
6000 } //PickerConstructor.extend
6004 function aria(element, attribute, value) {
6005 if ( $.isPlainObject(attribute) ) {
6006 for ( var key in attribute ) {
6007 ariaSet(element, key, attribute[key])
6011 ariaSet(element, attribute, value)
6014 function ariaSet(element, attribute, value) {
6015 element.setAttribute(
6016 (attribute == 'role' ? '' : 'aria-') + attribute,
6020 function ariaAttr(attribute, data) {
6021 if ( !$.isPlainObject(attribute) ) {
6022 attribute = { attribute: data }
6025 for ( var key in attribute ) {
6026 var attr = (key == 'role' ? '' : 'aria-') + key,
6027 attrVal = attribute[key]
6028 data += attrVal == null ? '' : attr + '="' + attribute[key] + '"'
6033 // IE8 bug throws an error for activeElements within iframes.
6034 function getActiveElement() {
6036 return document.activeElement
6042 // Expose the picker constructor.
6043 return PickerConstructor
6050 * Date picker for pickadate.js v3.5.0
6051 * http://amsul.github.io/pickadate.js/date.htm
6054 (function ( factory ) {
6057 if ( typeof define == 'function' && define.amd )
6058 define( ['picker', 'jquery'], factory )
6060 // Node.js/browserify.
6061 else if ( typeof exports == 'object' )
6062 module.exports = factory( require('./picker.js'), require('jquery') )
6065 else factory( Picker, jQuery )
6067 }(function( Picker, $ ) {
6071 * Globals and constants
6073 var DAYS_IN_WEEK = 7,
6074 WEEKS_IN_CALENDAR = 6,
6080 * The date picker constructor
6082 function DatePicker( picker, settings ) {
6084 var calendar = this,
6085 element = picker.$node[ 0 ],
6086 elementValue = element.value,
6087 elementDataValue = picker.$node.data( 'value' ),
6088 valueString = elementDataValue || elementValue,
6089 formatString = elementDataValue ? settings.formatSubmit : settings.format,
6090 isRTL = function() {
6092 return element.currentStyle ?
6095 element.currentStyle.direction == 'rtl' :
6097 // For normal browsers.
6098 getComputedStyle( picker.$root[0] ).direction == 'rtl'
6101 calendar.settings = settings
6102 calendar.$node = picker.$node
6104 // The queue of methods that will be used to build item objects.
6106 min: 'measure create',
6107 max: 'measure create',
6109 select: 'parse create validate',
6110 highlight: 'parse navigate create validate',
6111 view: 'parse create validate viewset',
6112 disable: 'deactivate',
6116 // The component's item object.
6119 calendar.item.clear = null
6120 calendar.item.disable = ( settings.disable || [] ).slice( 0 )
6121 calendar.item.enable = -(function( collectionDisabled ) {
6122 return collectionDisabled[ 0 ] === true ? collectionDisabled.shift() : -1
6123 })( calendar.item.disable )
6126 set( 'min', settings.min ).
6127 set( 'max', settings.max ).
6130 // When there’s a value, set the `select`, which in turn
6131 // also sets the `highlight` and `view`.
6132 if ( valueString ) {
6133 calendar.set( 'select', valueString, { format: formatString })
6136 // If there’s no value, default to highlighting “today”.
6139 set( 'select', null ).
6140 set( 'highlight', calendar.item.now )
6144 // The keycode to movement mapping.
6148 39: function() { return isRTL() ? -1 : 1 }, // Right
6149 37: function() { return isRTL() ? 1 : -1 }, // Left
6150 go: function( timeChange ) {
6151 var highlightedObject = calendar.item.highlight,
6152 targetDate = new Date( highlightedObject.year, highlightedObject.month, highlightedObject.date + timeChange )
6156 { interval: timeChange }
6163 // Bind some picker events.
6165 on( 'render', function() {
6166 picker.$root.find( '.' + settings.klass.selectMonth ).on( 'change', function() {
6167 var value = this.value
6169 picker.set( 'highlight', [ picker.get( 'view' ).year, value, picker.get( 'highlight' ).date ] )
6170 picker.$root.find( '.' + settings.klass.selectMonth ).trigger( 'focus' )
6173 picker.$root.find( '.' + settings.klass.selectYear ).on( 'change', function() {
6174 var value = this.value
6176 picker.set( 'highlight', [ value, picker.get( 'view' ).month, picker.get( 'highlight' ).date ] )
6177 picker.$root.find( '.' + settings.klass.selectYear ).trigger( 'focus' )
6181 on( 'open', function() {
6182 var includeToday = ''
6183 if ( calendar.disabled( calendar.get('now') ) ) {
6184 includeToday = ':not(.' + settings.klass.buttonToday + ')'
6186 picker.$root.find( 'button' + includeToday + ', select' ).attr( 'disabled', false )
6188 on( 'close', function() {
6189 picker.$root.find( 'button, select' ).attr( 'disabled', true )
6196 * Set a datepicker item object.
6198 DatePicker.prototype.set = function( type, value, options ) {
6200 var calendar = this,
6201 calendarItem = calendar.item
6203 // If the value is `null` just set it immediately.
6204 if ( value === null ) {
6205 if ( type == 'clear' ) type = 'select'
6206 calendarItem[ type ] = value
6210 // Otherwise go through the queue of methods, and invoke the functions.
6211 // Update this as the time unit, and set the final value as this item.
6212 // * In the case of `enable`, keep the queue but set `disable` instead.
6213 // And in the case of `flip`, keep the queue but set `enable` instead.
6214 calendarItem[ ( type == 'enable' ? 'disable' : type == 'flip' ? 'enable' : type ) ] = calendar.queue[ type ].split( ' ' ).map( function( method ) {
6215 value = calendar[ method ]( type, value, options )
6219 // Check if we need to cascade through more updates.
6220 if ( type == 'select' ) {
6221 calendar.set( 'highlight', calendarItem.select, options )
6223 else if ( type == 'highlight' ) {
6224 calendar.set( 'view', calendarItem.highlight, options )
6226 else if ( type.match( /^(flip|min|max|disable|enable)$/ ) ) {
6227 if ( calendarItem.select && calendar.disabled( calendarItem.select ) ) {
6228 calendar.set( 'select', calendarItem.select, options )
6230 if ( calendarItem.highlight && calendar.disabled( calendarItem.highlight ) ) {
6231 calendar.set( 'highlight', calendarItem.highlight, options )
6236 } //DatePicker.prototype.set
6240 * Get a datepicker item object.
6242 DatePicker.prototype.get = function( type ) {
6243 return this.item[ type ]
6244 } //DatePicker.prototype.get
6248 * Create a picker date object.
6250 DatePicker.prototype.create = function( type, value, options ) {
6252 var isInfiniteValue,
6255 // If there’s no value, use the type as the value.
6256 value = value === undefined ? type : value
6259 // If it’s infinity, update the value.
6260 if ( value == -Infinity || value == Infinity ) {
6261 isInfiniteValue = value
6264 // If it’s an object, use the native date object.
6265 else if ( $.isPlainObject( value ) && _.isInteger( value.pick ) ) {
6269 // If it’s an array, convert it into a date and make sure
6270 // that it’s a valid date – otherwise default to today.
6271 else if ( $.isArray( value ) ) {
6272 value = new Date( value[ 0 ], value[ 1 ], value[ 2 ] )
6273 value = _.isDate( value ) ? value : calendar.create().obj
6276 // If it’s a number or date object, make a normalized date.
6277 else if ( _.isInteger( value ) || _.isDate( value ) ) {
6278 value = calendar.normalize( new Date( value ), options )
6281 // If it’s a literal true or any other case, set it to now.
6282 else /*if ( value === true )*/ {
6283 value = calendar.now( type, value, options )
6286 // Return the compiled object.
6288 year: isInfiniteValue || value.getFullYear(),
6289 month: isInfiniteValue || value.getMonth(),
6290 date: isInfiniteValue || value.getDate(),
6291 day: isInfiniteValue || value.getDay(),
6292 obj: isInfiniteValue || value,
6293 pick: isInfiniteValue || value.getTime()
6295 } //DatePicker.prototype.create
6299 * Create a range limit object using an array, date object,
6300 * literal “true”, or integer relative to another time.
6302 DatePicker.prototype.createRange = function( from, to ) {
6304 var calendar = this,
6305 createDate = function( date ) {
6306 if ( date === true || $.isArray( date ) || _.isDate( date ) ) {
6307 return calendar.create( date )
6312 // Create objects if possible.
6313 if ( !_.isInteger( from ) ) {
6314 from = createDate( from )
6316 if ( !_.isInteger( to ) ) {
6317 to = createDate( to )
6320 // Create relative dates.
6321 if ( _.isInteger( from ) && $.isPlainObject( to ) ) {
6322 from = [ to.year, to.month, to.date + from ];
6324 else if ( _.isInteger( to ) && $.isPlainObject( from ) ) {
6325 to = [ from.year, from.month, from.date + to ];
6329 from: createDate( from ),
6330 to: createDate( to )
6332 } //DatePicker.prototype.createRange
6336 * Check if a date unit falls within a date range object.
6338 DatePicker.prototype.withinRange = function( range, dateUnit ) {
6339 range = this.createRange(range.from, range.to)
6340 return dateUnit.pick >= range.from.pick && dateUnit.pick <= range.to.pick
6345 * Check if two date range objects overlap.
6347 DatePicker.prototype.overlapRanges = function( one, two ) {
6351 // Convert the ranges into comparable dates.
6352 one = calendar.createRange( one.from, one.to )
6353 two = calendar.createRange( two.from, two.to )
6355 return calendar.withinRange( one, two.from ) || calendar.withinRange( one, two.to ) ||
6356 calendar.withinRange( two, one.from ) || calendar.withinRange( two, one.to )
6361 * Get the date today.
6363 DatePicker.prototype.now = function( type, value, options ) {
6365 if ( options && options.rel ) {
6366 value.setDate( value.getDate() + options.rel )
6368 return this.normalize( value, options )
6373 * Navigate to next/prev month.
6375 DatePicker.prototype.navigate = function( type, value, options ) {
6377 var targetDateObject,
6381 isTargetArray = $.isArray( value ),
6382 isTargetObject = $.isPlainObject( value ),
6383 viewsetObject = this.item.view/*,
6387 if ( isTargetArray || isTargetObject ) {
6389 if ( isTargetObject ) {
6390 targetYear = value.year
6391 targetMonth = value.month
6392 targetDate = value.date
6395 targetYear = +value[0]
6396 targetMonth = +value[1]
6397 targetDate = +value[2]
6400 // If we’re navigating months but the view is in a different
6401 // month, navigate to the view’s year and month.
6402 if ( options && options.nav && viewsetObject && viewsetObject.month !== targetMonth ) {
6403 targetYear = viewsetObject.year
6404 targetMonth = viewsetObject.month
6407 // Figure out the expected target year and month.
6408 targetDateObject = new Date( targetYear, targetMonth + ( options && options.nav ? options.nav : 0 ), 1 )
6409 targetYear = targetDateObject.getFullYear()
6410 targetMonth = targetDateObject.getMonth()
6412 // If the month we’re going to doesn’t have enough days,
6413 // keep decreasing the date until we reach the month’s last date.
6414 while ( /*safety &&*/ new Date( targetYear, targetMonth, targetDate ).getMonth() !== targetMonth ) {
6418 throw 'Fell into an infinite loop while navigating to ' + new Date( targetYear, targetMonth, targetDate ) + '.'
6422 value = [ targetYear, targetMonth, targetDate ]
6426 } //DatePicker.prototype.navigate
6430 * Normalize a date by setting the hours to midnight.
6432 DatePicker.prototype.normalize = function( value/*, options*/ ) {
6433 value.setHours( 0, 0, 0, 0 )
6439 * Measure the range of dates.
6441 DatePicker.prototype.measure = function( type, value/*, options*/ ) {
6445 // If it’s anything false-y, remove the limits.
6447 value = type == 'min' ? -Infinity : Infinity
6450 // If it’s a string, parse it.
6451 else if ( typeof value == 'string' ) {
6452 value = calendar.parse( type, value )
6455 // If it's an integer, get a date relative to today.
6456 else if ( _.isInteger( value ) ) {
6457 value = calendar.now( type, value, { rel: value } )
6461 } ///DatePicker.prototype.measure
6465 * Create a viewset object based on navigation.
6467 DatePicker.prototype.viewset = function( type, dateObject/*, options*/ ) {
6468 return this.create([ dateObject.year, dateObject.month, 1 ])
6473 * Validate a date as enabled and shift if needed.
6475 DatePicker.prototype.validate = function( type, dateObject, options ) {
6477 var calendar = this,
6479 // Keep a reference to the original date.
6480 originalDateObject = dateObject,
6482 // Make sure we have an interval.
6483 interval = options && options.interval ? options.interval : 1,
6485 // Check if the calendar enabled dates are inverted.
6486 isFlippedBase = calendar.item.enable === -1,
6488 // Check if we have any enabled dates after/before now.
6489 hasEnabledBeforeTarget, hasEnabledAfterTarget,
6491 // The min & max limits.
6492 minLimitObject = calendar.item.min,
6493 maxLimitObject = calendar.item.max,
6495 // Check if we’ve reached the limit during shifting.
6496 reachedMin, reachedMax,
6498 // Check if the calendar is inverted and at least one weekday is enabled.
6499 hasEnabledWeekdays = isFlippedBase && calendar.item.disable.filter( function( value ) {
6501 // If there’s a date, check where it is relative to the target.
6502 if ( $.isArray( value ) ) {
6503 var dateTime = calendar.create( value ).pick
6504 if ( dateTime < dateObject.pick ) hasEnabledBeforeTarget = true
6505 else if ( dateTime > dateObject.pick ) hasEnabledAfterTarget = true
6508 // Return only integers for enabled weekdays.
6509 return _.isInteger( value )
6516 // Cases to validate for:
6517 // [1] Not inverted and date disabled.
6518 // [2] Inverted and some dates enabled.
6519 // [3] Not inverted and out of range.
6521 // Cases to **not** validate for:
6522 // • Navigating months.
6523 // • Not inverted and date enabled.
6524 // • Inverted and all dates disabled.
6525 // • ..and anything else.
6526 if ( !options || !options.nav ) if (
6527 /* 1 */ ( !isFlippedBase && calendar.disabled( dateObject ) ) ||
6528 /* 2 */ ( isFlippedBase && calendar.disabled( dateObject ) && ( hasEnabledWeekdays || hasEnabledBeforeTarget || hasEnabledAfterTarget ) ) ||
6529 /* 3 */ ( !isFlippedBase && (dateObject.pick <= minLimitObject.pick || dateObject.pick >= maxLimitObject.pick) )
6533 // When inverted, flip the direction if there aren’t any enabled weekdays
6534 // and there are no enabled dates in the direction of the interval.
6535 if ( isFlippedBase && !hasEnabledWeekdays && ( ( !hasEnabledAfterTarget && interval > 0 ) || ( !hasEnabledBeforeTarget && interval < 0 ) ) ) {
6540 // Keep looping until we reach an enabled date.
6541 while ( /*safety &&*/ calendar.disabled( dateObject ) ) {
6545 throw 'Fell into an infinite loop while validating ' + dateObject.obj + '.'
6549 // If we’ve looped into the next/prev month with a large interval, return to the original date and flatten the interval.
6550 if ( Math.abs( interval ) > 1 && ( dateObject.month < originalDateObject.month || dateObject.month > originalDateObject.month ) ) {
6551 dateObject = originalDateObject
6552 interval = interval > 0 ? 1 : -1
6556 // If we’ve reached the min/max limit, reverse the direction, flatten the interval and set it to the limit.
6557 if ( dateObject.pick <= minLimitObject.pick ) {
6560 dateObject = calendar.create([
6561 minLimitObject.year,
6562 minLimitObject.month,
6563 minLimitObject.date + (dateObject.pick === minLimitObject.pick ? 0 : -1)
6566 else if ( dateObject.pick >= maxLimitObject.pick ) {
6569 dateObject = calendar.create([
6570 maxLimitObject.year,
6571 maxLimitObject.month,
6572 maxLimitObject.date + (dateObject.pick === maxLimitObject.pick ? 0 : 1)
6577 // If we’ve reached both limits, just break out of the loop.
6578 if ( reachedMin && reachedMax ) {
6583 // Finally, create the shifted date using the interval and keep looping.
6584 dateObject = calendar.create([ dateObject.year, dateObject.month, dateObject.date + interval ])
6590 // Return the date object settled on.
6592 } //DatePicker.prototype.validate
6596 * Check if a date is disabled.
6598 DatePicker.prototype.disabled = function( dateToVerify ) {
6603 // Filter through the disabled dates to check if this is one.
6604 isDisabledMatch = calendar.item.disable.filter( function( dateToDisable ) {
6606 // If the date is a number, match the weekday with 0index and `firstDay` check.
6607 if ( _.isInteger( dateToDisable ) ) {
6608 return dateToVerify.day === ( calendar.settings.firstDay ? dateToDisable : dateToDisable - 1 ) % 7
6611 // If it’s an array or a native JS date, create and match the exact date.
6612 if ( $.isArray( dateToDisable ) || _.isDate( dateToDisable ) ) {
6613 return dateToVerify.pick === calendar.create( dateToDisable ).pick
6616 // If it’s an object, match a date within the “from” and “to” range.
6617 if ( $.isPlainObject( dateToDisable ) ) {
6618 return calendar.withinRange( dateToDisable, dateToVerify )
6622 // If this date matches a disabled date, confirm it’s not inverted.
6623 isDisabledMatch = isDisabledMatch.length && !isDisabledMatch.filter(function( dateToDisable ) {
6624 return $.isArray( dateToDisable ) && dateToDisable[3] == 'inverted' ||
6625 $.isPlainObject( dateToDisable ) && dateToDisable.inverted
6628 // Check the calendar “enabled” flag and respectively flip the
6629 // disabled state. Then also check if it’s beyond the min/max limits.
6630 return calendar.item.enable === -1 ? !isDisabledMatch : isDisabledMatch ||
6631 dateToVerify.pick < calendar.item.min.pick ||
6632 dateToVerify.pick > calendar.item.max.pick
6634 } //DatePicker.prototype.disabled
6638 * Parse a string into a usable type.
6640 DatePicker.prototype.parse = function( type, value, options ) {
6642 var calendar = this,
6645 // If it’s already parsed, we’re good.
6646 if ( !value || typeof value != 'string' ) {
6650 // We need a `.format` to parse the value with.
6651 if ( !( options && options.format ) ) {
6652 options = options || {}
6653 options.format = calendar.settings.format
6656 // Convert the format into an array and then map through it.
6657 calendar.formats.toArray( options.format ).map( function( label ) {
6660 // Grab the formatting label.
6661 formattingLabel = calendar.formats[ label ],
6663 // The format length is from the formatting label function or the
6664 // label length without the escaping exclamation (!) mark.
6665 formatLength = formattingLabel ? _.trigger( formattingLabel, calendar, [ value, parsingObject ] ) : label.replace( /^!/, '' ).length
6667 // If there's a format label, split the value up to the format length.
6668 // Then add it to the parsing object with appropriate label.
6669 if ( formattingLabel ) {
6670 parsingObject[ label ] = value.substr( 0, formatLength )
6673 // Update the value as the substring from format length to end.
6674 value = value.substr( formatLength )
6677 // Compensate for month 0index.
6679 parsingObject.yyyy || parsingObject.yy,
6680 +( parsingObject.mm || parsingObject.m ) - 1,
6681 parsingObject.dd || parsingObject.d
6683 } //DatePicker.prototype.parse
6687 * Various formats to display the object in.
6689 DatePicker.prototype.formats = (function() {
6691 // Return the length of the first word in a collection.
6692 function getWordLengthFromCollection( string, collection, dateObject ) {
6694 // Grab the first word from the string.
6695 var word = string.match( /\w+/ )[ 0 ]
6697 // If there's no month index, add it to the date object
6698 if ( !dateObject.mm && !dateObject.m ) {
6699 dateObject.m = collection.indexOf( word ) + 1
6702 // Return the length of the word.
6706 // Get the length of the first word in a string.
6707 function getFirstWordLength( string ) {
6708 return string.match( /\w+/ )[ 0 ].length
6713 d: function( string, dateObject ) {
6715 // If there's string, then get the digits length.
6716 // Otherwise return the selected date.
6717 return string ? _.digits( string ) : dateObject.date
6719 dd: function( string, dateObject ) {
6721 // If there's a string, then the length is always 2.
6722 // Otherwise return the selected date with a leading zero.
6723 return string ? 2 : _.lead( dateObject.date )
6725 ddd: function( string, dateObject ) {
6727 // If there's a string, then get the length of the first word.
6728 // Otherwise return the short selected weekday.
6729 return string ? getFirstWordLength( string ) : this.settings.weekdaysShort[ dateObject.day ]
6731 dddd: function( string, dateObject ) {
6733 // If there's a string, then get the length of the first word.
6734 // Otherwise return the full selected weekday.
6735 return string ? getFirstWordLength( string ) : this.settings.weekdaysFull[ dateObject.day ]
6737 m: function( string, dateObject ) {
6739 // If there's a string, then get the length of the digits
6740 // Otherwise return the selected month with 0index compensation.
6741 return string ? _.digits( string ) : dateObject.month + 1
6743 mm: function( string, dateObject ) {
6745 // If there's a string, then the length is always 2.
6746 // Otherwise return the selected month with 0index and leading zero.
6747 return string ? 2 : _.lead( dateObject.month + 1 )
6749 mmm: function( string, dateObject ) {
6751 var collection = this.settings.monthsShort
6753 // If there's a string, get length of the relevant month from the short
6754 // months collection. Otherwise return the selected month from that collection.
6755 return string ? getWordLengthFromCollection( string, collection, dateObject ) : collection[ dateObject.month ]
6757 mmmm: function( string, dateObject ) {
6759 var collection = this.settings.monthsFull
6761 // If there's a string, get length of the relevant month from the full
6762 // months collection. Otherwise return the selected month from that collection.
6763 return string ? getWordLengthFromCollection( string, collection, dateObject ) : collection[ dateObject.month ]
6765 yy: function( string, dateObject ) {
6767 // If there's a string, then the length is always 2.
6768 // Otherwise return the selected year by slicing out the first 2 digits.
6769 return string ? 2 : ( '' + dateObject.year ).slice( 2 )
6771 yyyy: function( string, dateObject ) {
6773 // If there's a string, then the length is always 4.
6774 // Otherwise return the selected year.
6775 return string ? 4 : dateObject.year
6778 // Create an array by splitting the formatting string passed.
6779 toArray: function( formatString ) { return formatString.split( /(d{1,4}|m{1,4}|y{4}|yy|!.)/g ) },
6781 // Format an object into a string using the formatting options.
6782 toString: function ( formatString, itemObject ) {
6784 return calendar.formats.toArray( formatString ).map( function( label ) {
6785 return _.trigger( calendar.formats[ label ], calendar, [ 0, itemObject ] ) || label.replace( /^!/, '' )
6789 })() //DatePicker.prototype.formats
6795 * Check if two date units are the exact.
6797 DatePicker.prototype.isDateExact = function( one, two ) {
6801 // When we’re working with weekdays, do a direct comparison.
6803 ( _.isInteger( one ) && _.isInteger( two ) ) ||
6804 ( typeof one == 'boolean' && typeof two == 'boolean' )
6809 // When we’re working with date representations, compare the “pick” value.
6811 ( _.isDate( one ) || $.isArray( one ) ) &&
6812 ( _.isDate( two ) || $.isArray( two ) )
6814 return calendar.create( one ).pick === calendar.create( two ).pick
6817 // When we’re working with range objects, compare the “from” and “to”.
6818 if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {
6819 return calendar.isDateExact( one.from, two.from ) && calendar.isDateExact( one.to, two.to )
6827 * Check if two date units overlap.
6829 DatePicker.prototype.isDateOverlap = function( one, two ) {
6831 var calendar = this,
6832 firstDay = calendar.settings.firstDay ? 1 : 0
6834 // When we’re working with a weekday index, compare the days.
6835 if ( _.isInteger( one ) && ( _.isDate( two ) || $.isArray( two ) ) ) {
6836 one = one % 7 + firstDay
6837 return one === calendar.create( two ).day + 1
6839 if ( _.isInteger( two ) && ( _.isDate( one ) || $.isArray( one ) ) ) {
6840 two = two % 7 + firstDay
6841 return two === calendar.create( one ).day + 1
6844 // When we’re working with range objects, check if the ranges overlap.
6845 if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {
6846 return calendar.overlapRanges( one, two )
6854 * Flip the “enabled” state.
6856 DatePicker.prototype.flipEnable = function(val) {
6857 var itemObject = this.item
6858 itemObject.enable = val || (itemObject.enable == -1 ? 1 : -1)
6863 * Mark a collection of dates as “disabled”.
6865 DatePicker.prototype.deactivate = function( type, datesToDisable ) {
6867 var calendar = this,
6868 disabledItems = calendar.item.disable.slice(0)
6871 // If we’re flipping, that’s all we need to do.
6872 if ( datesToDisable == 'flip' ) {
6873 calendar.flipEnable()
6876 else if ( datesToDisable === false ) {
6877 calendar.flipEnable(1)
6881 else if ( datesToDisable === true ) {
6882 calendar.flipEnable(-1)
6886 // Otherwise go through the dates to disable.
6889 datesToDisable.map(function( unitToDisable ) {
6893 // When we have disabled items, check for matches.
6894 // If something is matched, immediately break out.
6895 for ( var index = 0; index < disabledItems.length; index += 1 ) {
6896 if ( calendar.isDateExact( unitToDisable, disabledItems[index] ) ) {
6902 // If nothing was found, add the validated unit to the collection.
6903 if ( !matchFound ) {
6905 _.isInteger( unitToDisable ) ||
6906 _.isDate( unitToDisable ) ||
6907 $.isArray( unitToDisable ) ||
6908 ( $.isPlainObject( unitToDisable ) && unitToDisable.from && unitToDisable.to )
6910 disabledItems.push( unitToDisable )
6916 // Return the updated collection.
6917 return disabledItems
6918 } //DatePicker.prototype.deactivate
6922 * Mark a collection of dates as “enabled”.
6924 DatePicker.prototype.activate = function( type, datesToEnable ) {
6926 var calendar = this,
6927 disabledItems = calendar.item.disable,
6928 disabledItemsCount = disabledItems.length
6930 // If we’re flipping, that’s all we need to do.
6931 if ( datesToEnable == 'flip' ) {
6932 calendar.flipEnable()
6935 else if ( datesToEnable === true ) {
6936 calendar.flipEnable(1)
6940 else if ( datesToEnable === false ) {
6941 calendar.flipEnable(-1)
6945 // Otherwise go through the disabled dates.
6948 datesToEnable.map(function( unitToEnable ) {
6955 // Go through the disabled items and try to find a match.
6956 for ( index = 0; index < disabledItemsCount; index += 1 ) {
6958 disabledUnit = disabledItems[index]
6960 // When an exact match is found, remove it from the collection.
6961 if ( calendar.isDateExact( disabledUnit, unitToEnable ) ) {
6962 matchFound = disabledItems[index] = null
6967 // When an overlapped match is found, add the “inverted” state to it.
6968 else if ( calendar.isDateOverlap( disabledUnit, unitToEnable ) ) {
6969 if ( $.isPlainObject( unitToEnable ) ) {
6970 unitToEnable.inverted = true
6971 matchFound = unitToEnable
6973 else if ( $.isArray( unitToEnable ) ) {
6974 matchFound = unitToEnable
6975 if ( !matchFound[3] ) matchFound.push( 'inverted' )
6977 else if ( _.isDate( unitToEnable ) ) {
6978 matchFound = [ unitToEnable.getFullYear(), unitToEnable.getMonth(), unitToEnable.getDate(), 'inverted' ]
6984 // If a match was found, remove a previous duplicate entry.
6985 if ( matchFound ) for ( index = 0; index < disabledItemsCount; index += 1 ) {
6986 if ( calendar.isDateExact( disabledItems[index], unitToEnable ) ) {
6987 disabledItems[index] = null
6992 // In the event that we’re dealing with an exact range of dates,
6993 // make sure there are no “inverted” dates because of it.
6994 if ( isExactRange ) for ( index = 0; index < disabledItemsCount; index += 1 ) {
6995 if ( calendar.isDateOverlap( disabledItems[index], unitToEnable ) ) {
6996 disabledItems[index] = null
7001 // If something is still matched, add it into the collection.
7003 disabledItems.push( matchFound )
7008 // Return the updated collection.
7009 return disabledItems.filter(function( val ) { return val != null })
7010 } //DatePicker.prototype.activate
7014 * Create a string for the nodes in the picker.
7016 DatePicker.prototype.nodes = function( isOpen ) {
7020 settings = calendar.settings,
7021 calendarItem = calendar.item,
7022 nowObject = calendarItem.now,
7023 selectedObject = calendarItem.select,
7024 highlightedObject = calendarItem.highlight,
7025 viewsetObject = calendarItem.view,
7026 disabledCollection = calendarItem.disable,
7027 minLimitObject = calendarItem.min,
7028 maxLimitObject = calendarItem.max,
7031 // Create the calendar table head using a copy of weekday labels collection.
7032 // * We do a copy so we don't mutate the original array.
7033 tableHead = (function( collection, fullCollection ) {
7035 // If the first day should be Monday, move Sunday to the end.
7036 if ( settings.firstDay ) {
7037 collection.push( collection.shift() )
7038 fullCollection.push( fullCollection.shift() )
7041 // Create and return the table head group.
7048 max: DAYS_IN_WEEK - 1,
7051 item: function( counter ) {
7053 collection[ counter ],
7054 settings.klass.weekdays,
7055 'scope=col title="' + fullCollection[ counter ] + '"'
7062 // Materialize modified
7063 })( ( settings.showWeekdaysFull ? settings.weekdaysFull : settings.weekdaysLetter ).slice( 0 ), settings.weekdaysFull.slice( 0 ) ), //tableHead
7066 // Create the nav for next/prev month.
7067 createMonthNav = function( next ) {
7069 // Otherwise, return the created month tag.
7073 settings.klass[ 'nav' + ( next ? 'Next' : 'Prev' ) ] + (
7075 // If the focused month is outside the range, disabled the button.
7076 ( next && viewsetObject.year >= maxLimitObject.year && viewsetObject.month >= maxLimitObject.month ) ||
7077 ( !next && viewsetObject.year <= minLimitObject.year && viewsetObject.month <= minLimitObject.month ) ?
7078 ' ' + settings.klass.navDisabled : ''
7080 'data-nav=' + ( next || -1 ) + ' ' +
7083 controls: calendar.$node[0].id + '_table'
7085 'title="' + (next ? settings.labelMonthNext : settings.labelMonthPrev ) + '"'
7090 // Create the month label.
7091 //Materialize modified
7092 createMonthLabel = function(override) {
7094 var monthsCollection = settings.showMonthsShort ? settings.monthsShort : settings.monthsFull
7096 // Materialize modified
7097 if (override == "short_months") {
7098 monthsCollection = settings.monthsShort;
7101 // If there are months to select, add a dropdown menu.
7102 if ( settings.selectMonths && override == undefined) {
7104 return _.node( 'select',
7110 item: function( loopedMonth ) {
7114 // The looped month and no classes.
7115 monthsCollection[ loopedMonth ], 0,
7117 // Set the value and selected index.
7118 'value=' + loopedMonth +
7119 ( viewsetObject.month == loopedMonth ? ' selected' : '' ) +
7122 ( viewsetObject.year == minLimitObject.year && loopedMonth < minLimitObject.month ) ||
7123 ( viewsetObject.year == maxLimitObject.year && loopedMonth > maxLimitObject.month )
7130 settings.klass.selectMonth + ' browser-default',
7131 ( isOpen ? '' : 'disabled' ) + ' ' +
7132 _.ariaAttr({ controls: calendar.$node[0].id + '_table' }) + ' ' +
7133 'title="' + settings.labelMonthSelect + '"'
7137 // Materialize modified
7138 if (override == "short_months")
7139 if (selectedObject != null)
7140 return _.node( 'div', monthsCollection[ selectedObject.month ] );
7141 else return _.node( 'div', monthsCollection[ viewsetObject.month ] );
7143 // If there's a need for a month selector
7144 return _.node( 'div', monthsCollection[ viewsetObject.month ], settings.klass.month )
7145 }, //createMonthLabel
7148 // Create the year label.
7149 // Materialize modified
7150 createYearLabel = function(override) {
7152 var focusedYear = viewsetObject.year,
7154 // If years selector is set to a literal "true", set it to 5. Otherwise
7155 // divide in half to get half before and half after focused year.
7156 numberYears = settings.selectYears === true ? 5 : ~~( settings.selectYears / 2 )
7158 // If there are years to select, add a dropdown menu.
7159 if ( numberYears ) {
7162 minYear = minLimitObject.year,
7163 maxYear = maxLimitObject.year,
7164 lowestYear = focusedYear - numberYears,
7165 highestYear = focusedYear + numberYears
7167 // If the min year is greater than the lowest year, increase the highest year
7168 // by the difference and set the lowest year to the min year.
7169 if ( minYear > lowestYear ) {
7170 highestYear += minYear - lowestYear
7171 lowestYear = minYear
7174 // If the max year is less than the highest year, decrease the lowest year
7175 // by the lower of the two: available and needed years. Then set the
7176 // highest year to the max year.
7177 if ( maxYear < highestYear ) {
7179 var availableYears = lowestYear - minYear,
7180 neededYears = highestYear - maxYear
7182 lowestYear -= availableYears > neededYears ? neededYears : availableYears
7183 highestYear = maxYear
7186 if ( settings.selectYears && override == undefined ) {
7187 return _.node( 'select',
7193 item: function( loopedYear ) {
7196 // The looped year and no classes.
7199 // Set the value and selected index.
7200 'value=' + loopedYear + ( focusedYear == loopedYear ? ' selected' : '' )
7204 settings.klass.selectYear + ' browser-default',
7205 ( isOpen ? '' : 'disabled' ) + ' ' + _.ariaAttr({ controls: calendar.$node[0].id + '_table' }) + ' ' +
7206 'title="' + settings.labelYearSelect + '"'
7211 // Materialize modified
7212 if (override == "raw")
7213 return _.node( 'div', focusedYear )
7215 // Otherwise just return the year focused
7216 return _.node( 'div', focusedYear, settings.klass.year )
7220 // Materialize modified
7221 createDayLabel = function() {
7222 if (selectedObject != null)
7223 return _.node( 'div', selectedObject.date)
7224 else return _.node( 'div', nowObject.date)
7226 createWeekdayLabel = function() {
7229 if (selectedObject != null)
7230 display_day = selectedObject.day;
7232 display_day = nowObject.day;
7233 var weekday = settings.weekdaysFull[ display_day ]
7238 // Create and return the entire calendar.
7240 // Date presentation View
7244 createWeekdayLabel(),
7245 "picker__weekday-display"
7248 // Div for short Month
7250 createMonthLabel("short_months"),
7251 settings.klass.month_display
7257 settings.klass.day_display
7262 createYearLabel("raw") ,
7263 settings.klass.year_display
7265 settings.klass.date_display
7267 // Calendar container
7270 ( settings.selectYears ? createMonthLabel() + createYearLabel() : createMonthLabel() + createYearLabel() ) +
7271 createMonthNav() + createMonthNav( 1 ),
7272 settings.klass.header
7280 max: WEEKS_IN_CALENDAR - 1,
7283 item: function( rowCounter ) {
7285 // If Monday is the first day and the month starts on Sunday, shift the date back a week.
7286 var shiftDateBy = settings.firstDay && calendar.create([ viewsetObject.year, viewsetObject.month, 1 ]).day === 0 ? -7 : 0
7290 min: DAYS_IN_WEEK * rowCounter - viewsetObject.day + shiftDateBy + 1, // Add 1 for weekday 0index
7292 return this.min + DAYS_IN_WEEK - 1
7296 item: function( targetDate ) {
7298 // Convert the time date from a relative date to a target date.
7299 targetDate = calendar.create([ viewsetObject.year, viewsetObject.month, targetDate + ( settings.firstDay ? 1 : 0 ) ])
7301 var isSelected = selectedObject && selectedObject.pick == targetDate.pick,
7302 isHighlighted = highlightedObject && highlightedObject.pick == targetDate.pick,
7303 isDisabled = disabledCollection && calendar.disabled( targetDate ) || targetDate.pick < minLimitObject.pick || targetDate.pick > maxLimitObject.pick,
7304 formattedDate = _.trigger( calendar.formats.toString, calendar, [ settings.format, targetDate ] )
7310 (function( klasses ) {
7312 // Add the `infocus` or `outfocus` classes based on month in view.
7313 klasses.push( viewsetObject.month == targetDate.month ? settings.klass.infocus : settings.klass.outfocus )
7315 // Add the `today` class if needed.
7316 if ( nowObject.pick == targetDate.pick ) {
7317 klasses.push( settings.klass.now )
7320 // Add the `selected` class if something's selected and the time matches.
7322 klasses.push( settings.klass.selected )
7325 // Add the `highlighted` class if something's highlighted and the time matches.
7326 if ( isHighlighted ) {
7327 klasses.push( settings.klass.highlighted )
7330 // Add the `disabled` class if something's disabled and the object matches.
7332 klasses.push( settings.klass.disabled )
7335 return klasses.join( ' ' )
7336 })([ settings.klass.day ]),
7337 'data-pick=' + targetDate.pick + ' ' + _.ariaAttr({
7339 label: formattedDate,
7340 selected: isSelected && calendar.$node.val() === formattedDate ? true : null,
7341 activedescendant: isHighlighted ? true : null,
7342 disabled: isDisabled ? true : null
7346 _.ariaAttr({ role: 'presentation' })
7354 settings.klass.table,
7355 'id="' + calendar.$node[0].id + '_table' + '" ' + _.ariaAttr({
7357 controls: calendar.$node[0].id,
7361 , settings.klass.calendar_container) // end calendar
7365 // * For Firefox forms to submit, make sure to set the buttons’ `type` attributes as “button”.
7368 _.node( 'button', settings.today, "btn-flat picker__today",
7369 'type=button data-pick=' + nowObject.pick +
7370 ( isOpen && !calendar.disabled(nowObject) ? '' : ' disabled' ) + ' ' +
7371 _.ariaAttr({ controls: calendar.$node[0].id }) ) +
7372 _.node( 'button', settings.clear, "btn-flat picker__clear",
7373 'type=button data-clear=1' +
7374 ( isOpen ? '' : ' disabled' ) + ' ' +
7375 _.ariaAttr({ controls: calendar.$node[0].id }) ) +
7376 _.node('button', settings.close, "btn-flat picker__close",
7377 'type=button data-close=true ' +
7378 ( isOpen ? '' : ' disabled' ) + ' ' +
7379 _.ariaAttr({ controls: calendar.$node[0].id }) ),
7380 settings.klass.footer
7382 } //DatePicker.prototype.nodes
7388 * The date picker defaults.
7390 DatePicker.defaults = (function( prefix ) {
7394 // The title label to use for the month nav buttons
7395 labelMonthNext: 'Next month',
7396 labelMonthPrev: 'Previous month',
7398 // The title label to use for the dropdown selectors
7399 labelMonthSelect: 'Select a month',
7400 labelYearSelect: 'Select a year',
7402 // Months and weekdays
7403 monthsFull: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
7404 monthsShort: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
7405 weekdaysFull: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
7406 weekdaysShort: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
7408 // Materialize modified
7409 weekdaysLetter: [ 'S', 'M', 'T', 'W', 'T', 'F', 'S' ],
7416 // The format to show on the `input` element
7417 format: 'd mmmm, yyyy',
7422 table: prefix + 'table',
7424 header: prefix + 'header',
7427 // Materialize Added klasses
7428 date_display: prefix + 'date-display',
7429 day_display: prefix + 'day-display',
7430 month_display: prefix + 'month-display',
7431 year_display: prefix + 'year-display',
7432 calendar_container: prefix + 'calendar-container',
7437 navPrev: prefix + 'nav--prev',
7438 navNext: prefix + 'nav--next',
7439 navDisabled: prefix + 'nav--disabled',
7441 month: prefix + 'month',
7442 year: prefix + 'year',
7444 selectMonth: prefix + 'select--month',
7445 selectYear: prefix + 'select--year',
7447 weekdays: prefix + 'weekday',
7449 day: prefix + 'day',
7450 disabled: prefix + 'day--disabled',
7451 selected: prefix + 'day--selected',
7452 highlighted: prefix + 'day--highlighted',
7453 now: prefix + 'day--today',
7454 infocus: prefix + 'day--infocus',
7455 outfocus: prefix + 'day--outfocus',
7457 footer: prefix + 'footer',
7459 buttonClear: prefix + 'button--clear',
7460 buttonToday: prefix + 'button--today',
7461 buttonClose: prefix + 'button--close'
7464 })( Picker.klasses().picker + '__' )
7471 * Extend the picker to add the date picker.
7473 Picker.extend( 'pickadate', DatePicker )
7481 $.fn.characterCounter = function(){
7482 return this.each(function(){
7483 var $input = $(this);
7484 var $counterElement = $input.parent().find('span[class="character-counter"]');
7486 // character counter has already been added appended to the parent container
7487 if ($counterElement.length) {
7491 var itHasLengthAttribute = $input.attr('data-length') !== undefined;
7493 if(itHasLengthAttribute){
7494 $input.on('input', updateCounter);
7495 $input.on('focus', updateCounter);
7496 $input.on('blur', removeCounterElement);
7498 addCounterElement($input);
7504 function updateCounter(){
7505 var maxLength = +$(this).attr('data-length'),
7506 actualLength = +$(this).val().length,
7507 isValidLength = actualLength <= maxLength;
7509 $(this).parent().find('span[class="character-counter"]')
7510 .html( actualLength + '/' + maxLength);
7512 addInputStyle(isValidLength, $(this));
7515 function addCounterElement($input) {
7516 var $counterElement = $input.parent().find('span[class="character-counter"]');
7518 if ($counterElement.length) {
7522 $counterElement = $('<span/>')
7523 .addClass('character-counter')
7524 .css('float','right')
7525 .css('font-size','12px')
7528 $input.parent().append($counterElement);
7531 function removeCounterElement(){
7532 $(this).parent().find('span[class="character-counter"]').html('');
7535 function addInputStyle(isValidLength, $input){
7536 var inputHasInvalidClass = $input.hasClass('invalid');
7537 if (isValidLength && inputHasInvalidClass) {
7538 $input.removeClass('invalid');
7540 else if(!isValidLength && !inputHasInvalidClass){
7541 $input.removeClass('valid');
7542 $input.addClass('invalid');
7546 $(document).ready(function(){
7547 $('input, textarea').characterCounter();
7555 init : function(options) {
7557 duration: 200, // ms
7558 dist: -100, // zoom scale TODO: make this more intuitive as an option
7559 shift: 0, // spacing for center image
7560 padding: 0, // Padding between non center items
7561 fullWidth: false, // Change to full width styles
7562 indicators: false, // Toggle indicators
7563 noWrap: false, // Don't wrap around and cycle through items.
7564 onCycleTo: null // Callback for when a new slide is cycled to.
7566 options = $.extend(defaults, options);
7568 return this.each(function() {
7570 var images, item_width, item_height, offset, center, pressed, dim, count,
7571 reference, referenceY, amplitude, target, velocity,
7572 xform, frame, timestamp, ticker, dragged, vertical_dragged;
7573 var $indicators = $('<ul class="indicators"></ul>');
7578 var showIndicators = view.attr('data-indicators') || options.indicators;
7580 // Don't double initialize.
7581 if (view.hasClass('initialized')) {
7583 $(this).trigger('carouselNext', [0.000001]);
7589 if (options.fullWidth) {
7591 var firstImage = view.find('.carousel-item img').first();
7592 if (firstImage.length) {
7593 imageHeight = firstImage.on('load', function(){
7594 view.css('height', $(this).height());
7597 imageHeight = view.find('.carousel-item').first().height();
7598 view.css('height', imageHeight);
7601 // Offset fixed items when indicators.
7602 if (showIndicators) {
7603 view.find('.carousel-fixed-item').addClass('with-indicators');
7608 view.addClass('initialized');
7610 offset = target = 0;
7612 item_width = view.find('.carousel-item').first().innerWidth();
7613 item_height = view.find('.carousel-item').first().innerHeight();
7614 dim = item_width * 2 + options.padding;
7616 view.find('.carousel-item').each(function (i) {
7617 images.push($(this)[0]);
7618 if (showIndicators) {
7619 var $indicator = $('<li class="indicator-item"></li>');
7621 // Add active to first by default.
7623 $indicator.addClass('active');
7626 // Handle clicks on indicators.
7627 $indicator.click(function (e) {
7628 e.stopPropagation();
7630 var index = $(this).index();
7633 $indicators.append($indicator);
7637 if (showIndicators) {
7638 view.append($indicators);
7640 count = images.length;
7643 function setupEvents() {
7644 if (typeof window.ontouchstart !== 'undefined') {
7645 view[0].addEventListener('touchstart', tap);
7646 view[0].addEventListener('touchmove', drag);
7647 view[0].addEventListener('touchend', release);
7649 view[0].addEventListener('mousedown', tap);
7650 view[0].addEventListener('mousemove', drag);
7651 view[0].addEventListener('mouseup', release);
7652 view[0].addEventListener('mouseleave', release);
7653 view[0].addEventListener('click', click);
7658 if (e.targetTouches && (e.targetTouches.length >= 1)) {
7659 return e.targetTouches[0].clientX;
7668 if (e.targetTouches && (e.targetTouches.length >= 1)) {
7669 return e.targetTouches[0].clientY;
7677 return (x >= count) ? (x % count) : (x < 0) ? wrap(count + (x % count)) : x;
7680 function scroll(x) {
7681 var i, half, delta, dir, tween, el, alignment, xTranslation;
7682 var lastCenter = center;
7684 offset = (typeof x === 'number') ? x : offset;
7685 center = Math.floor((offset + dim / 2) / dim);
7686 delta = offset - center * dim;
7687 dir = (delta < 0) ? 1 : -1;
7688 tween = -dir * delta * 2 / dim;
7691 if (!options.fullWidth) {
7692 alignment = 'translateX(' + (view[0].clientWidth - item_width) / 2 + 'px) ';
7693 alignment += 'translateY(' + (view[0].clientHeight - item_height) / 2 + 'px)';
7695 alignment = 'translateX(0)';
7698 // Set indicator active
7699 if (showIndicators) {
7700 var diff = (center % count);
7701 var activeIndicator = $indicators.find('.indicator-item.active');
7702 if (activeIndicator.index() !== diff) {
7703 activeIndicator.removeClass('active');
7704 $indicators.find('.indicator-item').eq(diff).addClass('active');
7709 // Don't show wrapped items.
7710 if (!options.noWrap || (center >= 0 && center < count)) {
7711 el = images[wrap(center)];
7713 // Add active class to center item.
7714 if (!$(el).hasClass('active')) {
7715 view.find('.carousel-item').removeClass('active');
7716 $(el).addClass('active');
7718 el.style[xform] = alignment +
7719 ' translateX(' + (-delta / 2) + 'px)' +
7720 ' translateX(' + (dir * options.shift * tween * i) + 'px)' +
7721 ' translateZ(' + (options.dist * tween) + 'px)';
7722 el.style.zIndex = 0;
7723 if (options.fullWidth) { tweenedOpacity = 1; }
7724 else { tweenedOpacity = 1 - 0.2 * tween; }
7725 el.style.opacity = tweenedOpacity;
7726 el.style.display = 'block';
7729 for (i = 1; i <= half; ++i) {
7731 if (options.fullWidth) {
7732 zTranslation = options.dist;
7733 tweenedOpacity = (i === half && delta < 0) ? 1 - tween : 1;
7735 zTranslation = options.dist * (i * 2 + tween * dir);
7736 tweenedOpacity = 1 - 0.2 * (i * 2 + tween * dir);
7738 // Don't show wrapped items.
7739 if (!options.noWrap || center + i < count) {
7740 el = images[wrap(center + i)];
7741 el.style[xform] = alignment +
7742 ' translateX(' + (options.shift + (dim * i - delta) / 2) + 'px)' +
7743 ' translateZ(' + zTranslation + 'px)';
7744 el.style.zIndex = -i;
7745 el.style.opacity = tweenedOpacity;
7746 el.style.display = 'block';
7751 if (options.fullWidth) {
7752 zTranslation = options.dist;
7753 tweenedOpacity = (i === half && delta > 0) ? 1 - tween : 1;
7755 zTranslation = options.dist * (i * 2 - tween * dir);
7756 tweenedOpacity = 1 - 0.2 * (i * 2 - tween * dir);
7758 // Don't show wrapped items.
7759 if (!options.noWrap || center - i >= 0) {
7760 el = images[wrap(center - i)];
7761 el.style[xform] = alignment +
7762 ' translateX(' + (-options.shift + (-dim * i - delta) / 2) + 'px)' +
7763 ' translateZ(' + zTranslation + 'px)';
7764 el.style.zIndex = -i;
7765 el.style.opacity = tweenedOpacity;
7766 el.style.display = 'block';
7771 // Don't show wrapped items.
7772 if (!options.noWrap || (center >= 0 && center < count)) {
7773 el = images[wrap(center)];
7774 el.style[xform] = alignment +
7775 ' translateX(' + (-delta / 2) + 'px)' +
7776 ' translateX(' + (dir * options.shift * tween) + 'px)' +
7777 ' translateZ(' + (options.dist * tween) + 'px)';
7778 el.style.zIndex = 0;
7779 if (options.fullWidth) { tweenedOpacity = 1; }
7780 else { tweenedOpacity = 1 - 0.2 * tween; }
7781 el.style.opacity = tweenedOpacity;
7782 el.style.display = 'block';
7785 // onCycleTo callback
7786 if (lastCenter !== center &&
7787 typeof(options.onCycleTo) === "function") {
7788 var $curr_item = view.find('.carousel-item').eq(wrap(center));
7789 options.onCycleTo.call(this, $curr_item, dragged);
7794 var now, elapsed, delta, v;
7797 elapsed = now - timestamp;
7799 delta = offset - frame;
7802 v = 1000 * delta / (1 + elapsed);
7803 velocity = 0.8 * v + 0.2 * velocity;
7806 function autoScroll() {
7810 elapsed = Date.now() - timestamp;
7811 delta = amplitude * Math.exp(-elapsed / options.duration);
7812 if (delta > 2 || delta < -2) {
7813 scroll(target - delta);
7814 requestAnimationFrame(autoScroll);
7822 // Disable clicks if carousel was dragged.
7825 e.stopPropagation();
7828 } else if (!options.fullWidth) {
7829 var clickedIndex = $(e.target).closest('.carousel-item').index();
7830 var diff = (center % count) - clickedIndex;
7832 // Disable clicks if carousel was shifted by click
7835 e.stopPropagation();
7837 cycleTo(clickedIndex);
7841 function cycleTo(n) {
7842 var diff = (center % count) - n;
7844 // Account for wraparound.
7845 if (!options.noWrap) {
7847 if (Math.abs(diff + count) < Math.abs(diff)) { diff += count; }
7849 } else if (diff > 0) {
7850 if (Math.abs(diff - count) < diff) { diff -= count; }
7854 // Call prev or next accordingly.
7856 view.trigger('carouselNext', [Math.abs(diff)]);
7858 } else if (diff > 0) {
7859 view.trigger('carouselPrev', [diff]);
7866 vertical_dragged = false;
7867 reference = xpos(e);
7868 referenceY = ypos(e);
7870 velocity = amplitude = 0;
7872 timestamp = Date.now();
7873 clearInterval(ticker);
7874 ticker = setInterval(track, 100);
7879 var x, delta, deltaY;
7883 delta = reference - x;
7884 deltaY = Math.abs(referenceY - y);
7885 if (deltaY < 30 && !vertical_dragged) {
7886 // If vertical scrolling don't allow dragging.
7887 if (delta > 2 || delta < -2) {
7890 scroll(offset + delta);
7893 } else if (dragged) {
7894 // If dragging don't allow vertical scroll.
7896 e.stopPropagation();
7900 // Vertical scrolling.
7901 vertical_dragged = true;
7906 // If dragging don't allow vertical scroll.
7908 e.stopPropagation();
7913 function release(e) {
7920 clearInterval(ticker);
7922 if (velocity > 10 || velocity < -10) {
7923 amplitude = 0.9 * velocity;
7924 target = offset + amplitude;
7926 target = Math.round(target / dim) * dim;
7928 // No wrap of items.
7929 if (options.noWrap) {
7930 if (target >= dim * (count - 1)) {
7931 target = dim * (count - 1);
7932 } else if (target < 0) {
7936 amplitude = target - offset;
7937 timestamp = Date.now();
7938 requestAnimationFrame(autoScroll);
7942 e.stopPropagation();
7947 xform = 'transform';
7948 ['webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
7949 var e = prefix + 'Transform';
7950 if (typeof document.body.style[e] !== 'undefined') {
7958 $(window).on('resize.carousel', function() {
7959 if (options.fullWidth) {
7960 item_width = view.find('.carousel-item').first().innerWidth();
7961 item_height = view.find('.carousel-item').first().innerHeight();
7962 dim = item_width * 2 + options.padding;
7963 offset = center * 2 * item_width;
7973 $(this).on('carouselNext', function(e, n) {
7974 if (n === undefined) {
7977 target = (dim * Math.round(offset / dim)) + (dim * n);
7978 if (offset !== target) {
7979 amplitude = target - offset;
7980 timestamp = Date.now();
7981 requestAnimationFrame(autoScroll);
7985 $(this).on('carouselPrev', function(e, n) {
7986 if (n === undefined) {
7989 target = (dim * Math.round(offset / dim)) - (dim * n);
7990 if (offset !== target) {
7991 amplitude = target - offset;
7992 timestamp = Date.now();
7993 requestAnimationFrame(autoScroll);
7997 $(this).on('carouselSet', function(e, n) {
7998 if (n === undefined) {
8009 next : function(n) {
8010 $(this).trigger('carouselNext', [n]);
8012 prev : function(n) {
8013 $(this).trigger('carouselPrev', [n]);
8016 $(this).trigger('carouselSet', [n]);
8021 $.fn.carousel = function(methodOrOptions) {
8022 if ( methods[methodOrOptions] ) {
8023 return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
8024 } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
8025 // Default to "init"
8026 return methods.init.apply( this, arguments );
8028 $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.carousel' );