' + roundedButton + circleButton + thumbnailButton + borderedButton + noneButton + '
' +
+ '');
+ for (var i = 0, lenGroup = group[1].length; i < lenGroup; i++) {
+ var $button = $(tplButtonInfo[group[1][i]](lang, options));
+
+ $button.attr('data-name', group[1][i]);
+
+ $group.append($button);
+ }
+ $content.append($group);
+ }
+
+ return tplPopover('note-air-popover', $content.children());
+ };
+
+ var $notePopover = $('
');
+
+ $notePopover.append(tplLinkPopover());
+ $notePopover.append(tplImagePopover());
+
+ if (options.airMode) {
+ $notePopover.append(tplAirPopover());
+ }
+
+ return $notePopover;
+ };
+
+ var tplHandles = function () {
+ return '
' +
+ '
' +
+ '
' +
+ '
' +
+ '
' +
+ '
' +
+ '
';
+ };
+
+ /**
+ * shortcut table template
+ * @param {String} title
+ * @param {String} body
+ */
+ var tplShortcut = function (title, keys) {
+ var keyClass = 'note-shortcut-col col-xs-6 note-shortcut-';
+ var body = [];
+
+ for (var i in keys) {
+ if (keys.hasOwnProperty(i)) {
+ body.push(
+ '
' + keys[i].kbd + ' ' + keys[i].text + ' '
+ );
+ }
+ }
+
+ return '
' + title + ' ' + '(keys)' + ' ' +
+ '
' + body.join('') + ' ';
+ };
+
+ var tplShortcutText = function (lang) {
+ var keys = [
+ {kbd: '⌘ + B', text: lang.font.bold},
+ {kbd: '⌘ + I', text: lang.font.italic},
+ {kbd: '⌘ + U', text: lang.font.underline},
+ {kbd: '⌘ + \\', text: lang.font.clear}
+ ];
+
+ return tplShortcut(lang.shortcut.textFormatting, keys);
+ };
+
+ var tplShortcutAction = function (lang) {
+ var keys = [
+ {kbd: '⌘ + Z', text: lang.history.undo},
+ {kbd: '⌘ + ⇧ + Z', text: lang.history.redo},
+ {kbd: '⌘ + ]', text: lang.paragraph.indent},
+ {kbd: '⌘ + [', text: lang.paragraph.outdent},
+ {kbd: '⌘ + ENTER', text: lang.hr.insert}
+ ];
+
+ return tplShortcut(lang.shortcut.action, keys);
+ };
+
+ var tplShortcutPara = function (lang) {
+ var keys = [
+ {kbd: '⌘ + ⇧ + L', text: lang.paragraph.left},
+ {kbd: '⌘ + ⇧ + E', text: lang.paragraph.center},
+ {kbd: '⌘ + ⇧ + R', text: lang.paragraph.right},
+ {kbd: '⌘ + ⇧ + J', text: lang.paragraph.justify},
+ {kbd: '⌘ + ⇧ + NUM7', text: lang.lists.ordered},
+ {kbd: '⌘ + ⇧ + NUM8', text: lang.lists.unordered}
+ ];
+
+ return tplShortcut(lang.shortcut.paragraphFormatting, keys);
+ };
+
+ var tplShortcutStyle = function (lang) {
+ var keys = [
+ {kbd: '⌘ + NUM0', text: lang.style.normal},
+ {kbd: '⌘ + NUM1', text: lang.style.h1},
+ {kbd: '⌘ + NUM2', text: lang.style.h2},
+ {kbd: '⌘ + NUM3', text: lang.style.h3},
+ {kbd: '⌘ + NUM4', text: lang.style.h4},
+ {kbd: '⌘ + NUM5', text: lang.style.h5},
+ {kbd: '⌘ + NUM6', text: lang.style.h6}
+ ];
+
+ return tplShortcut(lang.shortcut.documentStyle, keys);
+ };
+
+ var tplExtraShortcuts = function (lang, options) {
+ var extraKeys = options.extraKeys;
+ var keys = [];
+
+ for (var key in extraKeys) {
+ if (extraKeys.hasOwnProperty(key)) {
+ keys.push({kbd: key, text: extraKeys[key]});
+ }
+ }
+
+ return tplShortcut(lang.shortcut.extraKeys, keys);
+ };
+
+ var tplShortcutTable = function (lang, options) {
+ var template = [
+ '
' + tplShortcutAction(lang, options) + '
',
+ '
' + tplShortcutStyle(lang, options) + '
',
+ '
' + tplShortcutText(lang, options) + '
',
+ '
' + tplShortcutPara(lang, options) + '
'
+ ].join('
');
+
+ if (options.extraKeys) {
+ //template.push('
' + tplExtraShortcuts(lang, options) + '
');
+ }
+ return template;
+ };
+
+ var replaceMacKeys = function (sHtml) {
+ return sHtml.replace(/⌘/g, 'Ctrl').replace(/⇧/g, 'Shift');
+ };
+
+ var tplDialogInfo = {
+ image: function (lang, options) {
+ var imageLimitation = '';
+
+ if (options.maximumImageFileSize) {
+ var unit = Math.floor(Math.log(options.maximumImageFileSize) / Math.log(1024));
+ var readableSize = (options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 + ' ' + ' KMGTP'[unit] + 'B';
+
+ imageLimitation = '
' + lang.image.maximumFileSize + ' : ' + readableSize + ' ';
+ }
+
+ var body = '
' +
+ '
' +
+ '
' +
+ ' ' +
+ '' + lang.image.url + ' ' +
+ '
' +
+ '
';
+
+ var footer = '
' + lang.image.insert + ' ' +
+ '
' + lang.shortcut.close + ' ';
+ return tplDialog('note-image-dialog', lang.image.insert, body, footer);
+ },
+
+ link: function (lang, options) {
+ var body = '
' +
+ '
' +
+ ' ' +
+ '' + lang.link.textToDisplay + ' ' +
+ '
' +
+ '
' +
+ '
' +
+ '
' +
+ ' ' +
+ '' + lang.link.url + ' ' +
+ '
' +
+ '
' +
+ (!options.disableLinkTarget ?
+ '
' +
+ '
' +
+ ' ' +
+ '' + lang.link.openInNewWindow + ' ' +
+ '
' +
+ '
'
+ : ''
+ );
+
+ var footer = '
' + lang.link.insert + ' ' +
+ '
' + lang.shortcut.close + ' ';
+ return tplDialog('note-link-dialog', lang.link.insert, body, footer);
+ },
+
+ help: function (lang, options) {
+ var body = (agent.isMac ? tplShortcutTable(lang, options) : replaceMacKeys(tplShortcutTable(lang, options)));
+ var footer = '
' + lang.shortcut.close + ' ';
+
+ return tplDialog('note-help-dialog', lang.shortcut.shortcuts, body, footer);
+ }
+ };
+
+ var tplDialogs = function (lang, options) {
+ var dialogs = '';
+
+ $.each(tplDialogInfo, function (idx, tplDialog) {
+ dialogs += tplDialog(lang, options);
+ });
+
+ return '
' + dialogs + '
';
+ };
+
+ var tplStatusbar = function () {
+ return '
' +
+ '
' +
+ '
' +
+ '
' +
+ '
';
+ };
+
+ var representShortcut = function (str) {
+ if (agent.isMac) {
+ str = str.replace('CMD', '⌘').replace('SHIFT', '⇧');
+ }
+
+ return str.replace('BACKSLASH', '\\')
+ .replace('SLASH', '/')
+ .replace('LEFTBRACKET', '[')
+ .replace('RIGHTBRACKET', ']');
+ };
+
+ /**
+ * createTooltip
+ * @param {jQuery} $container
+ * @param {Object} keyMap
+ * @param {String} [sPlacement]
+ */
+ // >>>>>>> CK
+ var createTooltip = function ($container, keyMap, sPlacement) {
+ $(document).ready(function () {
+ var invertedKeyMap = func.invertObject(keyMap);
+ var $buttons = $container.find('.btn');
+
+ console.log($container);
+
+ $buttons.each(function (i, elBtn) {
+ var $btn = $(elBtn);
+ var sShortcut = invertedKeyMap[$btn.data('event')];
+ var text = $btn.attr('title');
+
+ if (sShortcut) {
+ $btn.attr('data-tooltip', function (i, v) {
+ text = text + ' (' + representShortcut(sShortcut) + ')';
+
+ $(this).removeAttr('title');
+ return text;
+ });
+ }
+ $btn.attr('data-position', 'bottom');
+ $btn.attr('data-tooltip', text);
+ $btn.removeAttr('title');
+ }).ckTooltip({
+ container: $container,
+ position: 'top',
+ delay: 30
+ });
+ });
+ };
+
+ // >>>>>>> CK
+ // createPalette
+ var createPalette = function ($container, options) {
+ var colorInfo = options.colors;
+ var colorTitles = options.colorTitles;
+
+ $container.find('.note-color-palette').each(function () {
+ var $palette = $(this), eventName = $palette.attr('data-target-event');
+ var paletteContents = [];
+
+ for (var row = 0, lenRow = colorInfo.length; row < lenRow; row++) {
+ var colors = colorInfo[row];
+ var titles = colorTitles[row];
+ var buttons = [];
+
+ for (var col = 0, lenCol = colors.length; col < lenCol; col++) {
+ var color = colors[col];
+ var title = titles[col];
+
+ buttons.push(['
'].join(''));
+ }
+ paletteContents.push('
' + buttons.join('') + '
');
+ }
+ $palette.html(paletteContents.join(''));
+
+ $palette.find('button').mouseenter(function () {
+ $palette.siblings('.colorName').html($(this).data('description'));
+ });
+ $palette.mouseleave(function () {
+ $(this).siblings('.colorName').html('');
+ });
+ });
+ };
+
+ /**
+ * create materialnote layout (air mode)
+ *
+ * @param {jQuery} $holder
+ * @param {Object} options
+ */
+ this.createLayoutByAirMode = function ($holder, options) {
+ var langInfo = options.langInfo;
+ var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
+ var id = func.uniqueId();
+
+ $holder.addClass('note-air-editor note-editable');
+ $holder.attr({
+ 'id': 'note-editor-' + id,
+ 'contentEditable': true
+ });
+
+ var body = document.body;
+
+ // create Popover
+ var $popover = $(tplPopovers(langInfo, options));
+ $popover.addClass('note-air-layout');
+ $popover.attr('id', 'note-popover-' + id);
+ $popover.appendTo(body);
+ createTooltip($popover, keyMap);
+ createPalette($popover, options);
+
+ // create Handle
+ var $handle = $(tplHandles());
+ $handle.addClass('note-air-layout');
+ $handle.attr('id', 'note-handle-' + id);
+ $handle.appendTo(body);
+
+ // create Dialog
+ var $dialog = $(tplDialogs(langInfo, options));
+ $dialog.addClass('note-air-layout');
+ $dialog.attr('id', 'note-dialog-' + id);
+ $dialog.find('button.close, a.modal-close').click(function () {
+ $(this).closest('.modal').materialModal("close");
+ });
+ $dialog.appendTo(body);
+ };
+
+ /**
+ * create materialnote layout (normal mode)
+ *
+ * @param {jQuery} $holder
+ * @param {Object} options
+ */
+ this.createLayoutByFrame = function ($holder, options) {
+ var langInfo = options.langInfo;
+
+ //01. create Editor
+ var $editor = $('
');
+ if (options.width) {
+ $editor.width(options.width);
+ }
+
+ //02. statusbar (resizebar)
+ if (options.height > 0) {
+ $('
' + (options.disableResizeEditor ? '' : tplStatusbar()) + '
').prependTo($editor);
+ }
+
+ //03. create Editable
+ var isContentEditable = !$holder.is(':disabled');
+ var $editable = $('
')
+ .prependTo($editor);
+ if (options.height) {
+ $editable.height(options.height);
+ }
+ if (options.direction) {
+ $editable.attr('dir', options.direction);
+ }
+ var placeholder = $holder.attr('placeholder') || options.placeholder;
+ if (placeholder) {
+ $editable.attr('data-placeholder', placeholder);
+ }
+
+ $editable.html(dom.html($holder));
+
+ //031. create codable
+ $('
').prependTo($editor);
+
+ //04. create Toolbar
+ var $toolbar = $('
');
+ for (var idx = 0, len = options.toolbar.length; idx < len; idx++) {
+ var groupName = options.toolbar[idx][0];
+ var groupButtons = options.toolbar[idx][1];
+
+ var $group = $('
');
+ for (var i = 0, btnLength = groupButtons.length; i < btnLength; i++) {
+ var buttonInfo = tplButtonInfo[groupButtons[i]];
+ // continue creating toolbar even if a button doesn't exist
+ if (!$.isFunction(buttonInfo)) {
+ continue;
+ }
+
+ var $button = $(buttonInfo(langInfo, options));
+ $button.attr('data-name', groupButtons[i]); // set button's alias, becuase to get button element from $toolbar
+ $group.append($button);
+ }
+ $toolbar.append($group);
+ }
+
+ $toolbar.prependTo($editor);
+ var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
+ createPalette($toolbar, options);
+ createTooltip($toolbar, keyMap, 'bottom');
+
+
+ // >>>>>>> CK - following toolbar
+ // following toolbar
+ function followingBar() {
+ // $(window).unbind('scroll');
+ // console.log($._data( $(window)[0], "events" ));
+ $(window).scroll(function () {
+ var isFullscreen = $editor.hasClass('fullscreen');
+
+ if (isFullscreen) {
+ console.log("fullscreen");
+ return false;
+ }
+
+ var toolbar = $editor.children('.note-toolbar');
+ var toolbarHeight = toolbar.outerHeight();
+ var editable = $editor.children('.note-editable');
+ var editableHeight = editable.outerHeight();
+ var editorWidth = $editor.width;
+ var toolbarOffset, editorOffsetTop, editorOffsetBottom;
+ var activateOffset, deactivateOffsetTop, deactivateOffsetBottom;
+ var currentOffset;
+ var relativeOffset;
+ var otherBarHeight;
+
+ // check if the web app is currently using another static bar
+ otherBarHeight = $("." + options.otherStaticBarClass).outerHeight();
+ if (!otherBarHeight) otherBarHeight = 0;
+ //console.log(otherBarHeight);
+
+ currentOffset = $(document).scrollTop();
+ toolbarOffset = toolbar.offset().top;
+ editorOffsetTop = $editor.offset().top;
+ editorOffsetBottom = editorOffsetTop + editableHeight;
+ activateOffset = toolbarOffset - otherBarHeight;
+ deactivateOffsetBottom = editorOffsetBottom - otherBarHeight;
+ deactivateOffsetTop = editorOffsetTop - otherBarHeight;
+
+ if ((currentOffset > activateOffset) && (currentOffset < deactivateOffsetBottom)) {
+ relativeOffset = currentOffset - $editor.offset().top + otherBarHeight;
+ toolbar.css({'top': relativeOffset + 'px', 'z-index': 2000});
+ } else {
+ if ((currentOffset < toolbarOffset) && (currentOffset < deactivateOffsetBottom)) {
+ toolbar.css({'top': 0, 'z-index': 1052});
+
+ if (currentOffset > deactivateOffsetTop) {
+ relativeOffset = currentOffset - $editor.offset().top + otherBarHeight;
+ toolbar.css({'top': relativeOffset + 'px', 'z-index': 2000});
+ }
+ }
+ }
+ });
+ }
+
+ if (options.followingToolbar) {
+ followingBar();
+ }
+
+ //05. create Popover
+ var $popover = $(tplPopovers(langInfo, options)).prependTo($editor);
+ createPalette($popover, options);
+ createTooltip($popover, keyMap);
+
+ //06. handle(control selection, ...)
+ $(tplHandles()).prependTo($editor);
+
+ //07. create Dialog
+ var $dialog = $(tplDialogs(langInfo, options)).prependTo($editor);
+ $dialog.find('button.close, a.modal-close').click(function () {
+ $(this).closest('.modal').materialModal("close");
+ });
+
+ //08. create Dropzone
+ $('
').prependTo($editor);
+
+ //09. Editor/Holder switch
+ $editor.insertAfter($holder);
+ $holder.hide();
+ };
+
+ this.hasNoteEditor = function ($holder) {
+ return this.noteEditorFromHolder($holder).length > 0;
+ };
+
+ this.noteEditorFromHolder = function ($holder) {
+ if ($holder.hasClass('note-air-editor')) {
+ return $holder;
+ } else if ($holder.next().hasClass('note-editor')) {
+ return $holder.next();
+ } else {
+ return $();
+ }
+ };
+
+ /**
+ * create materialnote layout
+ *
+ * @param {jQuery} $holder
+ * @param {Object} options
+ */
+ this.createLayout = function ($holder, options) {
+ if (options.airMode) {
+ this.createLayoutByAirMode($holder, options);
+ } else {
+ this.createLayoutByFrame($holder, options);
+ }
+ };
+
+ /**
+ * returns layoutInfo from holder
+ *
+ * @param {jQuery} $holder - placeholder
+ * @return {Object}
+ */
+ this.layoutInfoFromHolder = function ($holder) {
+ var $editor = this.noteEditorFromHolder($holder);
+ if (!$editor.length) {
+ return;
+ }
+
+ // connect $holder to $editor
+ $editor.data('holder', $holder);
+
+ return dom.buildLayoutInfo($editor);
+ };
+
+ /**
+ * removeLayout
+ *
+ * @param {jQuery} $holder - placeholder
+ * @param {Object} layoutInfo
+ * @param {Object} options
+ *
+ */
+ this.removeLayout = function ($holder, layoutInfo, options) {
+ if (options.airMode) {
+ $holder.removeClass('note-air-editor note-editable')
+ .removeAttr('id contentEditable');
+
+ layoutInfo.popover().remove();
+ layoutInfo.handle().remove();
+ layoutInfo.dialog().remove();
+ } else {
+ $holder.html(layoutInfo.editable().html());
+
+ layoutInfo.editor().remove();
+ $holder.show();
+ }
+ };
+
+ /**
+ *
+ * @return {Object}
+ * @return {function(label, options=):string} return.button {@link #tplButton function to make text button}
+ * @return {function(iconClass, options=):string} return.iconButton {@link #tplIconButton function to make icon button}
+ * @return {function(className, title=, body=, footer=):string} return.dialog {@link #tplDialog function to make dialog}
+ */
+ this.getTemplate = function () {
+ return {
+ button: tplButton,
+ iconButton: tplIconButton,
+ dialog: tplDialog
+ };
+ };
+
+ /**
+ * add button information
+ *
+ * @param {String} name button name
+ * @param {Function} buttonInfo function to make button, reference to {@link #tplButton},{@link #tplIconButton}
+ */
+ this.addButtonInfo = function (name, buttonInfo) {
+ tplButtonInfo[name] = buttonInfo;
+ };
+
+ /**
+ *
+ * @param {String} name
+ * @param {Function} dialogInfo function to make dialog, reference to {@link #tplDialog}
+ */
+ this.addDialogInfo = function (name, dialogInfo) {
+ tplDialogInfo[name] = dialogInfo;
+ };
+ };
+
+
+ // jQuery namespace for materialnote
+ /**
+ * @class $.materialnote
+ *
+ * materialnote attribute
+ *
+ * @mixin defaults
+ * @singleton
+ *
+ */
+ $.materialnote = $.materialnote || {};
+
+ // extends default settings
+ // - $.materialnote.version
+ // - $.materialnote.options
+ // - $.materialnote.lang
+ $.extend($.materialnote, defaults);
+
+ var renderer = new Renderer();
+ var eventHandler = new EventHandler();
+
+ $.extend($.materialnote, {
+ /** @property {Renderer} */
+ renderer: renderer,
+ /** @property {EventHandler} */
+ eventHandler: eventHandler,
+ /**
+ * @property {Object} core
+ * @property {core.agent} core.agent
+ * @property {core.dom} core.dom
+ * @property {core.range} core.range
+ */
+ core: {
+ agent: agent,
+ list: list,
+ dom: dom,
+ range: range
+ },
+ /**
+ * @property {Object}
+ * pluginEvents event list for plugins
+ * event has name and callback function.
+ *
+ * ```
+ * $.materialnote.addPlugin({
+ * events : {
+ * 'hello' : function(layoutInfo, value, $target) {
+ * console.log('event name is hello, value is ' + value );
+ * }
+ * }
+ * })
+ * ```
+ *
+ * * event name is data-event property.
+ * * layoutInfo is a materialnote layout information.
+ * * value is data-value property.
+ */
+ pluginEvents: {},
+
+ plugins: []
+ });
+
+ /**
+ * @method addPlugin
+ *
+ * add Plugin in materialnote
+ *
+ * materialnote can make a own plugin.
+ *
+ * ### Define plugin
+ * ```
+ * // get template function
+ * var tmpl = $.materialnote.renderer.getTemplate();
+ *
+ * // add a button
+ * $.materialnote.addPlugin({
+ * buttons : {
+ * // "hello" is button's namespace.
+ * "hello" : function(lang, options) {
+ * // make icon button by template function
+ * return tmpl.iconButton(options.iconPrefix + 'header', {
+ * // callback function name when button clicked
+ * event : 'hello',
+ * // set data-value property
+ * value : 'hello',
+ * hide : true
+ * });
+ * }
+ *
+ * },
+ *
+ * events : {
+ * "hello" : function(layoutInfo, value) {
+ * // here is event code
+ * }
+ * }
+ * });
+ * ```
+ * ### Use a plugin in toolbar
+ *
+ * ```
+ * $("#editor").materialnote({
+ * ...
+ * toolbar : [
+ * // display hello plugin in toolbar
+ * ['group', [ 'hello' ]]
+ * ]
+ * ...
+ * });
+ * ```
+ *
+ *
+ * @param {Object} plugin
+ * @param {Object} [plugin.buttons] define plugin button. for detail, see to Renderer.addButtonInfo
+ * @param {Object} [plugin.dialogs] define plugin dialog. for detail, see to Renderer.addDialogInfo
+ * @param {Object} [plugin.events] add event in $.materialnote.pluginEvents
+ * @param {Object} [plugin.langs] update $.materialnote.lang
+ * @param {Object} [plugin.options] update $.materialnote.options
+ */
+ $.materialnote.addPlugin = function (plugin) {
+
+ // save plugin list
+ $.materialnote.plugins.push(plugin);
+
+ if (plugin.buttons) {
+ $.each(plugin.buttons, function (name, button) {
+ renderer.addButtonInfo(name, button);
+ });
+ }
+
+ if (plugin.dialogs) {
+ $.each(plugin.dialogs, function (name, dialog) {
+ renderer.addDialogInfo(name, dialog);
+ });
+ }
+
+ if (plugin.events) {
+ $.each(plugin.events, function (name, event) {
+ $.materialnote.pluginEvents[name] = event;
+ });
+ }
+
+ if (plugin.langs) {
+ $.each(plugin.langs, function (locale, lang) {
+ if ($.materialnote.lang[locale]) {
+ $.extend($.materialnote.lang[locale], lang);
+ }
+ });
+ }
+
+ if (plugin.options) {
+ $.extend($.materialnote.options, plugin.options);
+ }
+ };
+
+ /*
+ * extend $.fn
+ */
+ $.fn.extend({
+ /**
+ * @method
+ * Initialize materialnote
+ * - create editor layout and attach Mouse and keyboard events.
+ *
+ * ```
+ * $("#materialnote").materialnote( { options ..} );
+ * ```
+ *
+ * @member $.fn
+ * @param {Object|String} options reference to $.materialnote.options
+ * @return {this}
+ */
+ materialnote: function () {
+
+ // check first argument's type
+ // - {String}: External API call {{module}}.{{method}}
+ // - {Object}: init options
+ var type = $.type(list.head(arguments));
+ var isExternalAPICalled = type === 'string';
+ var hasInitOptions = type === 'object';
+
+ // extend default options with custom user options
+ var options = hasInitOptions ? list.head(arguments) : {};
+
+ options = $.extend({}, $.materialnote.options, options);
+ options.icons = $.extend({}, $.materialnote.options.icons, options.icons);
+
+ // Include langInfo in options for later use, e.g. for image drag-n-drop
+ // Setup language info with en-US as default
+ options.langInfo = $.extend(true, {}, $.materialnote.lang['en-US'], $.materialnote.lang[options.lang]);
+
+ // override plugin options
+ if (!isExternalAPICalled && hasInitOptions) {
+ for (var i = 0, len = $.materialnote.plugins.length; i < len; i++) {
+ var plugin = $.materialnote.plugins[i];
+
+ if (options.plugin[plugin.name]) {
+ $.materialnote.plugins[i] = $.extend(true, plugin, options.plugin[plugin.name]);
+ }
+ }
+ }
+
+ this.each(function (idx, holder) {
+ // >>>>>>> CK set id for this editor
+ materialUniqueId = $(holder).attr('id');
+
+ var $holder = $(holder);
+
+ // if layout isn't created yet, createLayout and attach events
+ if (!renderer.hasNoteEditor($holder)) {
+ renderer.createLayout($holder, options);
+
+ var layoutInfo = renderer.layoutInfoFromHolder($holder);
+ $holder.data('layoutInfo', layoutInfo);
+
+ eventHandler.attach(layoutInfo, options);
+ eventHandler.attachCustomEvent(layoutInfo, options);
+
+ }
+ });
+
+ var $first = this.first();
+ if ($first.length) {
+ var layoutInfo = renderer.layoutInfoFromHolder($first);
+
+ // external API
+ if (isExternalAPICalled) {
+ var moduleAndMethod = list.head(list.from(arguments));
+ var args = list.tail(list.from(arguments));
+
+ // TODO now external API only works for editor
+ var params = [moduleAndMethod, layoutInfo.editable()].concat(args);
+ return eventHandler.invoke.apply(eventHandler, params);
+ } else if (options.focus) {
+ // focus on first editable element for initialize editor
+ layoutInfo.editable().focus();
+ }
+ }
+
+
+ // >>>>>>> CK dropdowns - tabs activation
+ $(this).each(function (index, editor) {
+ var tabs;
+ var tabContainer;
+ var toolbar;
+ var isAir = false;
+
+ if ($(editor).hasClass('note-air-editor')) {
+ var id = $(this).attr('id');
+ if (id) id = id.substring(id.lastIndexOf('-') + 1, id.length);
+
+ editor = $('#note-popover-' + id).find('.note-air-popover');
+ tabContainer = editor.find('ul.tabs');
+ tabs = editor.find('li.tab a');
+ toolbar = $(editor).find('.popover-content button.dropdown');
+ isAir = true;
+ } else {
+ editor = $(editor).next('.note-editor');
+ tabContainer = editor.find('ul.tabs');
+ tabs = editor.find('li.tab a');
+ toolbar = $(editor).find('.note-toolbar button.dropdown');
+ }
+ var go = true;
+
+ function handleDropdowns(select, bar) {
+ var list = $(select).next('ul.dropdown-menu');
+ var container = $(select).parent('.btn-group');
+
+ list.slideUp(0);
+
+ $('.preventDropClose').click(function (event) {
+ event.stopPropagation();
+ });
+
+ $(select).click(function (event) {
+ // calculate dropdown open position to avoid overflow from editor
+ var btnOffset = Math.round($(select).parent('.btn-group').offset().left - toolbar.offset().left);
+ var listBorderWidth = parseInt(list.css("border-left-width"));
+ var editorWidth = editor.outerWidth();
+ var listOffset = listBorderWidth;
+
+ list.css({'max-width': editorWidth + 'px'});
+
+ var listWidth = list.outerWidth();
+ var th = listWidth + btnOffset;
+
+ if (th >= editorWidth) {
+ listOffset = th - editorWidth;
+
+ if (!isAir) {
+ listOffset = listOffset + listBorderWidth;
+ }
+ }
+
+ list.css({'left': '-' + listOffset + 'px'});
+
+ var reopen = true;
+
+ if (list.is(':visible')) reopen = false;
+
+ bar.find('ul.dropdown-menu').slideUp(200);
+
+ if (reopen) {
+ list.slideToggle(200);
+ }
+ event.stopPropagation();
+ });
+
+ tabs.unbind().click(function (event) {
+ go = false;
+ });
+ }
+
+ $(window).click(function (event) {
+ if (go) editor.find('ul.dropdown-menu').slideUp(200);
+ go = true;
+ event.stopPropagation();
+ });
+
+ // dropdowns
+ toolbar.each(function (index, select) {
+ handleDropdowns(select, editor);
+ });
+
+ // activate tabs
+ tabContainer.tabs();
+ });
+
+ return this;
+ },
+
+ /**
+ * @method
+ *
+ * get the HTML contents of note or set the HTML contents of note.
+ *
+ * * get contents
+ * ```
+ * var content = $("#materialnote").code();
+ * ```
+ * * set contents
+ *
+ * ```
+ * $("#materialnote").code(html);
+ * ```
+ *
+ * @member $.fn
+ * @param {String} [html] - HTML contents(optional, set)
+ * @return {this|String} - context(set) or HTML contents of note(get).
+ */
+ code: function (html) {
+ // get the HTML contents of note
+ if (html === undefined) {
+ var $holder = this.first();
+ if (!$holder.length) {
+ return;
+ }
+
+ var layoutInfo = renderer.layoutInfoFromHolder($holder);
+ var $editable = layoutInfo && layoutInfo.editable();
+
+ if ($editable && $editable.length) {
+ var isCodeview = eventHandler.invoke('codeview.isActivated', layoutInfo);
+ eventHandler.invoke('codeview.sync', layoutInfo);
+ return isCodeview ? layoutInfo.codable().val() :
+ layoutInfo.editable().html();
+ }
+ return dom.value($holder);
+ }
+
+ // set the HTML contents of note
+ this.each(function (i, holder) {
+ var layoutInfo = renderer.layoutInfoFromHolder($(holder));
+ var $editable = layoutInfo && layoutInfo.editable();
+ if ($editable) {
+ $editable.html(html);
+ }
+ });
+
+ return this;
+ },
+
+ /**
+ * @method
+ *
+ * destroy Editor Layout and detach Key and Mouse Event
+ *
+ * @member $.fn
+ * @return {this}
+ */
+ destroy: function () {
+ this.each(function (idx, holder) {
+ var $holder = $(holder);
+
+ if (!renderer.hasNoteEditor($holder)) {
+ return;
+ }
+
+ var info = renderer.layoutInfoFromHolder($holder);
+ var options = info.editor().data('options');
+
+ eventHandler.detach(info, options);
+ renderer.removeLayout($holder, info, options);
+ });
+
+ return this;
+ }
+ });
+}));
diff --git a/scrummer/static/src/js/lib/external/materialize.js b/scrummer/static/src/js/lib/external/materialize.js
new file mode 100644
index 0000000..d1de196
--- /dev/null
+++ b/scrummer/static/src/js/lib/external/materialize.js
@@ -0,0 +1,9787 @@
+/*!
+ * Materialize v0.97.8 (http://materializecss.com)
+ * Copyright 2014-2015 Materialize
+ * MIT License (https://raw.githubusercontent.com/Dogfalo/materialize/master/LICENSE)
+ */
+// Check for jQuery.
+
+if (typeof(jQuery) === 'undefined') {
+ var jQuery;
+ // Check if require is a defined function.
+ if (typeof(require) === 'function') {
+ jQuery = $ = require('jquery');
+ // Else use the dollar sign alias.
+ } else {
+ jQuery = $;
+ }
+}
+;/*
+ * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
+ *
+ * Uses the built in easing capabilities added In jQuery 1.1
+ * to offer multiple easing options
+ *
+ * TERMS OF USE - jQuery Easing
+ *
+ * Open source under the BSD License.
+ *
+ * Copyright © 2008 George McGinley Smith
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this list of
+ * conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice, this list
+ * of conditions and the following disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * Neither the name of the author nor the names of contributors may be used to endorse
+ * or promote products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+// t: current time, b: begInnIng value, c: change In value, d: duration
+jQuery.easing['jswing'] = jQuery.easing['swing'];
+
+jQuery.extend(jQuery.easing,
+ {
+ def: 'easeOutQuad',
+ swing: function (x, t, b, c, d) {
+ //alert(jQuery.easing.default);
+ return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
+ },
+ easeInQuad: function (x, t, b, c, d) {
+ return c * (t /= d) * t + b;
+ },
+ easeOutQuad: function (x, t, b, c, d) {
+ return -c * (t /= d) * (t - 2) + b;
+ },
+ easeInOutQuad: function (x, t, b, c, d) {
+ if ((t /= d / 2) < 1) return c / 2 * t * t + b;
+ return -c / 2 * ((--t) * (t - 2) - 1) + b;
+ },
+ easeInCubic: function (x, t, b, c, d) {
+ return c * (t /= d) * t * t + b;
+ },
+ easeOutCubic: function (x, t, b, c, d) {
+ return c * ((t = t / d - 1) * t * t + 1) + b;
+ },
+ easeInOutCubic: function (x, t, b, c, d) {
+ if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
+ return c / 2 * ((t -= 2) * t * t + 2) + b;
+ },
+ easeInQuart: function (x, t, b, c, d) {
+ return c * (t /= d) * t * t * t + b;
+ },
+ easeOutQuart: function (x, t, b, c, d) {
+ return -c * ((t = t / d - 1) * t * t * t - 1) + b;
+ },
+ easeInOutQuart: function (x, t, b, c, d) {
+ if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
+ return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
+ },
+ easeInQuint: function (x, t, b, c, d) {
+ return c * (t /= d) * t * t * t * t + b;
+ },
+ easeOutQuint: function (x, t, b, c, d) {
+ return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
+ },
+ easeInOutQuint: function (x, t, b, c, d) {
+ if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
+ return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
+ },
+ easeInSine: function (x, t, b, c, d) {
+ return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
+ },
+ easeOutSine: function (x, t, b, c, d) {
+ return c * Math.sin(t / d * (Math.PI / 2)) + b;
+ },
+ easeInOutSine: function (x, t, b, c, d) {
+ return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
+ },
+ easeInExpo: function (x, t, b, c, d) {
+ return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
+ },
+ easeOutExpo: function (x, t, b, c, d) {
+ return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
+ },
+ easeInOutExpo: function (x, t, b, c, d) {
+ if (t == 0) return b;
+ if (t == d) return b + c;
+ if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
+ return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
+ },
+ easeInCirc: function (x, t, b, c, d) {
+ return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
+ },
+ easeOutCirc: function (x, t, b, c, d) {
+ return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
+ },
+ easeInOutCirc: function (x, t, b, c, d) {
+ if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
+ return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
+ },
+ easeInElastic: function (x, t, b, c, d) {
+ var s = 1.70158;
+ var p = 0;
+ var a = c;
+ if (t == 0) return b;
+ if ((t /= d) == 1) return b + c;
+ if (!p) p = d * .3;
+ if (a < Math.abs(c)) {
+ a = c;
+ var s = p / 4;
+ }
+ else var s = p / (2 * Math.PI) * Math.asin(c / a);
+ return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
+ },
+ easeOutElastic: function (x, t, b, c, d) {
+ var s = 1.70158;
+ var p = 0;
+ var a = c;
+ if (t == 0) return b;
+ if ((t /= d) == 1) return b + c;
+ if (!p) p = d * .3;
+ if (a < Math.abs(c)) {
+ a = c;
+ var s = p / 4;
+ }
+ else var s = p / (2 * Math.PI) * Math.asin(c / a);
+ return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
+ },
+ easeInOutElastic: function (x, t, b, c, d) {
+ var s = 1.70158;
+ var p = 0;
+ var a = c;
+ if (t == 0) return b;
+ if ((t /= d / 2) == 2) return b + c;
+ if (!p) p = d * (.3 * 1.5);
+ if (a < Math.abs(c)) {
+ a = c;
+ var s = p / 4;
+ }
+ else var s = p / (2 * Math.PI) * Math.asin(c / a);
+ if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
+ return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
+ },
+ easeInBack: function (x, t, b, c, d, s) {
+ if (s == undefined) s = 1.70158;
+ return c * (t /= d) * t * ((s + 1) * t - s) + b;
+ },
+ easeOutBack: function (x, t, b, c, d, s) {
+ if (s == undefined) s = 1.70158;
+ return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
+ },
+ easeInOutBack: function (x, t, b, c, d, s) {
+ if (s == undefined) s = 1.70158;
+ if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
+ return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
+ },
+ easeInBounce: function (x, t, b, c, d) {
+ return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b;
+ },
+ easeOutBounce: function (x, t, b, c, d) {
+ if ((t /= d) < (1 / 2.75)) {
+ return c * (7.5625 * t * t) + b;
+ } else if (t < (2 / 2.75)) {
+ return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
+ } else if (t < (2.5 / 2.75)) {
+ return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
+ } else {
+ return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
+ }
+ },
+ easeInOutBounce: function (x, t, b, c, d) {
+ if (t < d / 2) return jQuery.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b;
+ return jQuery.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b;
+ }
+ });
+
+/*
+ *
+ * TERMS OF USE - EASING EQUATIONS
+ *
+ * Open source under the BSD License.
+ *
+ * Copyright © 2001 Robert Penner
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this list of
+ * conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice, this list
+ * of conditions and the following disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * Neither the name of the author nor the names of contributors may be used to endorse
+ * or promote products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+; // Custom Easing
+jQuery.extend(jQuery.easing,
+ {
+ easeInOutMaterial: function (x, t, b, c, d) {
+ if ((t /= d / 2) < 1) return c / 2 * t * t + b;
+ return c / 4 * ((t -= 2) * t * t + 2) + b;
+ }
+ });
+
+;/*! VelocityJS.org (1.2.3). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */
+/*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */
+/*! Note that this has been modified by Materialize to confirm that Velocity is not already being imported. */
+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 = "", 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) {
+ 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)
+}));
+;!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) {
+ if (typeof define === 'function' && define.amd) {
+ define(['jquery', 'hammerjs'], factory);
+ } else if (typeof exports === 'object') {
+ factory(require('jquery'), require('hammerjs'));
+ } else {
+ factory(jQuery, Hammer);
+ }
+}(function ($, Hammer) {
+ function hammerify(el, options) {
+ var $el = $(el);
+ if (!$el.data("hammer")) {
+ $el.data("hammer", new Hammer($el[0], options));
+ }
+ }
+
+ $.fn.hammer = function (options) {
+ return this.each(function () {
+ hammerify(this, options);
+ });
+ };
+
+ // extend the emit method to also trigger jQuery events
+ Hammer.Manager.prototype.emit = (function (originalEmit) {
+ return function (type, data) {
+ originalEmit.call(this, type, data);
+ $(this.element).trigger({
+ type: type,
+ gesture: data
+ });
+ };
+ })(Hammer.Manager.prototype.emit);
+}));
+;// Required for Meteor package, the use of window prevents export by Meteor
+(function (window) {
+ if (window.Package) {
+ Materialize = {};
+ } else {
+ window.Materialize = {};
+ }
+})(window);
+
+
+/*
+ * raf.js
+ * https://github.com/ngryman/raf.js
+ *
+ * original requestAnimationFrame polyfill by Erik Möller
+ * inspired from paul_irish gist and post
+ *
+ * Copyright (c) 2013 ngryman
+ * Licensed under the MIT license.
+ */
+(function (window) {
+ var lastTime = 0,
+ vendors = ['webkit', 'moz'],
+ requestAnimationFrame = window.requestAnimationFrame,
+ cancelAnimationFrame = window.cancelAnimationFrame,
+ i = vendors.length;
+
+ // try to un-prefix existing raf
+ while (--i >= 0 && !requestAnimationFrame) {
+ requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
+ cancelAnimationFrame = window[vendors[i] + 'CancelRequestAnimationFrame'];
+ }
+
+ // polyfill with setTimeout fallback
+ // heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
+ if (!requestAnimationFrame || !cancelAnimationFrame) {
+ requestAnimationFrame = function (callback) {
+ var now = +Date.now(),
+ nextTime = Math.max(lastTime + 16, now);
+ return setTimeout(function () {
+ callback(lastTime = nextTime);
+ }, nextTime - now);
+ };
+
+ cancelAnimationFrame = clearTimeout;
+ }
+
+ // export to window
+ window.requestAnimationFrame = requestAnimationFrame;
+ window.cancelAnimationFrame = cancelAnimationFrame;
+}(window));
+
+
+// Unique ID
+Materialize.guid = (function () {
+ function s4() {
+ return Math.floor((1 + Math.random()) * 0x10000)
+ .toString(16)
+ .substring(1);
+ }
+
+ return function () {
+ return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
+ s4() + '-' + s4() + s4() + s4();
+ };
+})();
+
+/**
+ * Escapes hash from special characters
+ * @param {string} hash String returned from this.hash
+ * @returns {string}
+ */
+Materialize.escapeHash = function (hash) {
+ return hash.replace(/(:|\.|\[|\]|,|=)/g, "\\$1");
+};
+
+Materialize.elementOrParentIsFixed = function (element) {
+ var $element = $(element);
+ var $checkElements = $element.add($element.parents());
+ var isFixed = false;
+ $checkElements.each(function () {
+ if ($(this).css("position") === "fixed") {
+ isFixed = true;
+ return false;
+ }
+ });
+ return isFixed;
+};
+
+// Velocity has conflicts when loaded with jQuery, this will check for it
+// First, check if in noConflict mode
+var Vel;
+if (jQuery) {
+ Vel = jQuery.Velocity;
+} else if ($) {
+ Vel = $.Velocity;
+} else {
+ Vel = Velocity;
+}
+;(function ($) {
+ $.fn.collapsible = function (options) {
+ var defaults = {
+ accordion: undefined,
+ onOpen: undefined,
+ onClose: undefined
+ };
+
+ options = $.extend(defaults, options);
+
+
+ return this.each(function () {
+
+ var $this = $(this);
+
+ var $panel_headers = $(this).find('> li > .collapsible-header');
+
+ var collapsible_type = $this.data("collapsible");
+
+ // Turn off any existing event handlers
+ $this.off('click.collapse', '> li > .collapsible-header');
+ $panel_headers.off('click.collapse');
+
+
+ /****************
+ Helper Functions
+ ****************/
+
+ // Accordion Open
+ function accordionOpen(object) {
+ $panel_headers = $this.find('> li > .collapsible-header');
+ if (object.hasClass('active')) {
+ object.parent().addClass('active');
+ }
+ else {
+ object.parent().removeClass('active');
+ }
+ if (object.parent().hasClass('active')) {
+ object.siblings('.collapsible-body').stop(true, false).slideDown({
+ duration: 350,
+ easing: "easeOutQuart",
+ queue: false,
+ complete: function () {
+ $(this).css('height', '');
+ }
+ });
+ }
+ else {
+ object.siblings('.collapsible-body').stop(true, false).slideUp({
+ duration: 350,
+ easing: "easeOutQuart",
+ queue: false,
+ complete: function () {
+ $(this).css('height', '');
+ }
+ });
+ }
+
+ $panel_headers.not(object).removeClass('active').parent().removeClass('active');
+
+ // Close previously open accordion elements.
+ $panel_headers.not(object).parent().children('.collapsible-body').stop(true, false).each(function () {
+ if ($(this).is(':visible')) {
+ $(this).slideUp({
+ duration: 350,
+ easing: "easeOutQuart",
+ queue: false,
+ complete: function () {
+ $(this).css('height', '');
+ execCallbacks($(this).siblings('.collapsible-header'));
+ }
+ });
+ }
+ });
+ }
+
+ // Expandable Open
+ function expandableOpen(object) {
+ if (object.hasClass('active')) {
+ object.parent().addClass('active');
+ }
+ else {
+ object.parent().removeClass('active');
+ }
+ if (object.parent().hasClass('active')) {
+ object.siblings('.collapsible-body').stop(true, false).slideDown({
+ duration: 350,
+ easing: "easeOutQuart",
+ queue: false,
+ complete: function () {
+ $(this).css('height', '');
+ }
+ });
+ }
+ else {
+ object.siblings('.collapsible-body').stop(true, false).slideUp({
+ duration: 350,
+ easing: "easeOutQuart",
+ queue: false,
+ complete: function () {
+ $(this).css('height', '');
+ }
+ });
+ }
+ }
+
+ // Open collapsible. object: .collapsible-header
+ function collapsibleOpen(object) {
+ if (options.accordion || collapsible_type === "accordion" || collapsible_type === undefined) { // Handle Accordion
+ accordionOpen(object);
+ } else { // Handle Expandables
+ expandableOpen(object);
+ }
+
+ execCallbacks(object);
+ }
+
+ // Handle callbacks
+ function execCallbacks(object) {
+ if (object.hasClass('active')) {
+ if (typeof(options.onOpen) === "function") {
+ options.onOpen.call(this, object.parent());
+ }
+ } else {
+ if (typeof(options.onClose) === "function") {
+ options.onClose.call(this, object.parent());
+ }
+ }
+ }
+
+ /**
+ * Check if object is children of panel header
+ * @param {Object} object Jquery object
+ * @return {Boolean} true if it is children
+ */
+ function isChildrenOfPanelHeader(object) {
+
+ var panelHeader = getPanelHeader(object);
+
+ return panelHeader.length > 0;
+ }
+
+ /**
+ * Get panel header from a children element
+ * @param {Object} object Jquery object
+ * @return {Object} panel header object
+ */
+ function getPanelHeader(object) {
+
+ return object.closest('li > .collapsible-header');
+ }
+
+ /***** End Helper Functions *****/
+
+
+
+ // Add click handler to only direct collapsible header children
+ $this.on('click.collapse', '> li > .collapsible-header', function (e) {
+ var element = $(e.target);
+
+ if (isChildrenOfPanelHeader(element)) {
+ element = getPanelHeader(element);
+ }
+
+ element.toggleClass('active');
+
+ collapsibleOpen(element);
+ });
+
+
+ // Open first active
+ if (options.accordion || collapsible_type === "accordion" || collapsible_type === undefined) { // Handle Accordion
+ collapsibleOpen($panel_headers.filter('.active').first());
+
+ } else { // Handle Expandables
+ $panel_headers.filter('.active').each(function () {
+ collapsibleOpen($(this));
+ });
+ }
+
+ });
+ };
+
+ $(document).ready(function () {
+ $('.collapsible').collapsible();
+ });
+}(jQuery));
+;(function ($) {
+
+ // Add posibility to scroll to selected option
+ // usefull for select for example
+ $.fn.scrollTo = function (elem) {
+ $(this).scrollTop($(this).scrollTop() - $(this).offset().top + $(elem).offset().top);
+ return this;
+ };
+
+ $.fn.dropdown = function (options) {
+ var defaults = {
+ inDuration: 300,
+ outDuration: 225,
+ constrain_width: true, // Constrains width of dropdown to the activator
+ hover: false,
+ gutter: 0, // Spacing from edge
+ belowOrigin: false,
+ alignment: 'left',
+ stopPropagation: false
+ };
+
+ // Open dropdown.
+ if (options === "open") {
+ this.each(function () {
+ $(this).trigger('open');
+ });
+ return false;
+ }
+
+ // Close dropdown.
+ if (options === "close") {
+ this.each(function () {
+ $(this).trigger('close');
+ });
+ return false;
+ }
+
+ this.each(function () {
+ var origin = $(this);
+ var curr_options = $.extend({}, defaults, options);
+ var isFocused = false;
+
+ // Dropdown menu
+ var activates = $("#" + origin.attr('data-activates'));
+
+ function updateOptions() {
+ if (origin.data('induration') !== undefined)
+ curr_options.inDuration = origin.data('induration');
+ if (origin.data('outduration') !== undefined)
+ curr_options.outDuration = origin.data('outduration');
+ if (origin.data('constrainwidth') !== undefined)
+ curr_options.constrain_width = origin.data('constrainwidth');
+ if (origin.data('hover') !== undefined)
+ curr_options.hover = origin.data('hover');
+ if (origin.data('gutter') !== undefined)
+ curr_options.gutter = origin.data('gutter');
+ if (origin.data('beloworigin') !== undefined)
+ curr_options.belowOrigin = origin.data('beloworigin');
+ if (origin.data('alignment') !== undefined)
+ curr_options.alignment = origin.data('alignment');
+ if (origin.data('stoppropagation') !== undefined)
+ curr_options.stopPropagation = origin.data('stoppropagation');
+ }
+
+ updateOptions();
+
+ // Attach dropdown to its activator
+ origin.after(activates);
+
+ /*
+ Helper function to position and resize dropdown.
+ Used in hover and click handler.
+ */
+ function placeDropdown(eventType) {
+ // Check for simultaneous focus and click events.
+ if (eventType === 'focus') {
+ isFocused = true;
+ }
+
+ // Check html data attributes
+ updateOptions();
+
+ // Set Dropdown state
+ activates.addClass('active');
+ origin.addClass('active');
+
+ // Constrain width
+ if (curr_options.constrain_width === true) {
+ activates.css('width', origin.outerWidth());
+
+ } else {
+ activates.css('white-space', 'nowrap');
+ }
+
+ // Offscreen detection
+ var windowHeight = window.innerHeight;
+ var originHeight = origin.innerHeight();
+ var offsetLeft = origin.offset().left;
+ var offsetTop = origin.offset().top - $(window).scrollTop();
+ var currAlignment = curr_options.alignment;
+ var gutterSpacing = 0;
+ var leftPosition = 0;
+
+ // Below Origin
+ var verticalOffset = 0;
+ if (curr_options.belowOrigin === true) {
+ verticalOffset = originHeight;
+ }
+
+ // Check for scrolling positioned container.
+ var scrollYOffset = 0;
+ var scrollXOffset = 0;
+ var wrapper = origin.parent();
+ if (!wrapper.is('body')) {
+ if (wrapper[0].scrollHeight > wrapper[0].clientHeight) {
+ scrollYOffset = wrapper[0].scrollTop;
+ }
+ if (wrapper[0].scrollWidth > wrapper[0].clientWidth) {
+ scrollXOffset = wrapper[0].scrollLeft;
+ }
+ }
+
+
+ if (offsetLeft + activates.innerWidth() > $(window).width()) {
+ // Dropdown goes past screen on right, force right alignment
+ currAlignment = 'right';
+
+ } else if (offsetLeft - activates.innerWidth() + origin.innerWidth() < 0) {
+ // Dropdown goes past screen on left, force left alignment
+ currAlignment = 'left';
+ }
+ // Vertical bottom offscreen detection
+ if (offsetTop + activates.innerHeight() > windowHeight) {
+ // If going upwards still goes offscreen, just crop height of dropdown.
+ if (offsetTop + originHeight - activates.innerHeight() < 0) {
+ var adjustedHeight = windowHeight - offsetTop - verticalOffset;
+ activates.css('max-height', adjustedHeight);
+ } else {
+ // Flow upwards.
+ if (!verticalOffset) {
+ verticalOffset += originHeight;
+ }
+ verticalOffset -= activates.innerHeight();
+ }
+ }
+
+ // Handle edge alignment
+ if (currAlignment === 'left') {
+ gutterSpacing = curr_options.gutter;
+ leftPosition = origin.position().left + gutterSpacing;
+ }
+ else if (currAlignment === 'right') {
+ var offsetRight = origin.position().left + origin.outerWidth() - activates.outerWidth();
+ gutterSpacing = -curr_options.gutter;
+ leftPosition = offsetRight + gutterSpacing;
+ }
+
+ // Position dropdown
+ activates.css({
+ position: 'absolute',
+ top: origin.position().top + verticalOffset + scrollYOffset,
+ left: leftPosition + scrollXOffset
+ });
+
+
+ // Show dropdown
+ activates.stop(true, true).css('opacity', 0)
+ .slideDown({
+ queue: false,
+ duration: curr_options.inDuration,
+ easing: 'easeOutCubic',
+ complete: function () {
+ $(this).css('height', '');
+ }
+ })
+ .animate({opacity: 1}, {queue: false, duration: curr_options.inDuration, easing: 'easeOutSine'});
+ }
+
+ function hideDropdown() {
+ // Check for simultaneous focus and click events.
+ isFocused = false;
+ activates.fadeOut(curr_options.outDuration);
+ activates.removeClass('active');
+ origin.removeClass('active');
+ setTimeout(function () {
+ activates.css('max-height', '');
+ }, curr_options.outDuration);
+ }
+
+ // Hover
+ if (curr_options.hover) {
+ var open = false;
+ origin.unbind('click.' + origin.attr('id'));
+ // Hover handler to show dropdown
+ origin.on('mouseenter', function (e) { // Mouse over
+ if (open === false) {
+ placeDropdown();
+ open = true;
+ }
+ });
+ origin.on('mouseleave', function (e) {
+ // If hover on origin then to something other than dropdown content, then close
+ var toEl = e.toElement || e.relatedTarget; // added browser compatibility for target element
+ if (!$(toEl).closest('.dropdown-content').is(activates)) {
+ activates.stop(true, true);
+ hideDropdown();
+ open = false;
+ }
+ });
+
+ activates.on('mouseleave', function (e) { // Mouse out
+ var toEl = e.toElement || e.relatedTarget;
+ if (!$(toEl).closest('.dropdown-button').is(origin)) {
+ activates.stop(true, true);
+ hideDropdown();
+ open = false;
+ }
+ });
+
+ // Click
+ } else {
+ // Click handler to show dropdown
+ origin.unbind('click.' + origin.attr('id'));
+ origin.bind('click.' + origin.attr('id'), function (e) {
+ if (!isFocused) {
+ if (origin[0] == e.currentTarget && !origin.hasClass('active') &&
+ ($(e.target).closest('.dropdown-content').length === 0)) {
+ e.preventDefault(); // Prevents button click from moving window
+ if (curr_options.stopPropagation) {
+ e.stopPropagation();
+ }
+ placeDropdown('click');
+ }
+ // If origin is clicked and menu is open, close menu
+ else if (origin.hasClass('active')) {
+ hideDropdown();
+ $(document).unbind('click.' + activates.attr('id') + ' touchstart.' + activates.attr('id'));
+ }
+ // If menu open, add click close handler to document
+ if (activates.hasClass('active')) {
+ $(document).bind('click.' + activates.attr('id') + ' touchstart.' + activates.attr('id'), function (e) {
+ if (!activates.is(e.target) && !origin.is(e.target) && (!origin.find(e.target).length)) {
+ hideDropdown();
+ $(document).unbind('click.' + activates.attr('id') + ' touchstart.' + activates.attr('id'));
+ }
+ });
+ }
+ }
+ });
+
+ } // End else
+
+ // Listen to open and close event - useful for select component
+ origin.on('open', function (e, eventType) {
+ placeDropdown(eventType);
+ });
+ origin.on('close', hideDropdown);
+
+
+ });
+ }; // End dropdown plugin
+
+ $(document).ready(function () {
+ $('.dropdown-button').dropdown();
+ });
+}(jQuery));
+;(function ($) {
+ var _stack = 0,
+ _lastID = 0,
+ _generateID = function () {
+ _lastID++;
+ return 'materialize-modal-overlay-' + _lastID;
+ };
+
+ var methods = {
+ init: function (options) {
+ var defaults = {
+ opacity: 0.5,
+ in_duration: 350,
+ out_duration: 250,
+ ready: undefined,
+ complete: undefined,
+ dismissible: true,
+ starting_top: '4%',
+ ending_top: '10%'
+ };
+
+ // Override defaults
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+ var $modal = $(this);
+ var modal_id = $(this).attr("id") || '#' + $(this).data('target');
+
+ var closeModal = function () {
+ var overlayID = $modal.data('overlay-id');
+ var $overlay = $('#' + overlayID);
+ $modal.removeClass('open');
+
+ // Enable scrolling
+ $('body').css({
+ overflow: '',
+ width: ''
+ });
+
+ $modal.find('.modal-close').off('click.close');
+ $(document).off('keyup.modal' + overlayID);
+
+ $overlay.velocity({opacity: 0}, {duration: options.out_duration, queue: false, ease: "easeOutQuart"});
+
+
+ // Define Bottom Sheet animation
+ var exitVelocityOptions = {
+ duration: options.out_duration,
+ queue: false,
+ ease: "easeOutCubic",
+ // Handle modal ready callback
+ complete: function () {
+ $(this).css({display: "none"});
+
+ // Call complete callback
+ if (typeof(options.complete) === "function") {
+ options.complete.call(this, $modal);
+ }
+ $overlay.remove();
+ _stack--;
+ }
+ };
+ if ($modal.hasClass('bottom-sheet')) {
+ $modal.velocity({bottom: "-100%", opacity: 0}, exitVelocityOptions);
+ }
+ else {
+ $modal.velocity(
+ {top: options.starting_top, opacity: 0, scaleX: 0.7},
+ exitVelocityOptions
+ );
+ }
+ };
+
+ var openModal = function ($trigger) {
+ var $body = $('body');
+ var oldWidth = $body.innerWidth();
+ $body.css('overflow', 'hidden');
+ $body.width(oldWidth);
+
+ if ($modal.hasClass('open')) {
+ return;
+ }
+
+ var overlayID = _generateID();
+ var $overlay = $('
');
+ lStack = (++_stack);
+
+ // Store a reference of the overlay
+ $overlay.attr('id', overlayID).css('z-index', 1000 + lStack * 2);
+ $modal.data('overlay-id', overlayID).css('z-index', 1000 + lStack * 2 + 1);
+ $modal.addClass('open');
+
+ $("body").append($overlay);
+
+ if (options.dismissible) {
+ $overlay.click(function () {
+ closeModal();
+ });
+ // Return on ESC
+ $(document).on('keyup.modal' + overlayID, function (e) {
+ if (e.keyCode === 27) { // ESC key
+ closeModal();
+ }
+ });
+ }
+
+ $modal.find(".modal-close").on('click.close', function (e) {
+ closeModal();
+ });
+
+ $overlay.css({display: "block", opacity: 0});
+
+ $modal.css({
+ display: "block",
+ opacity: 0
+ });
+
+ $overlay.velocity({opacity: options.opacity}, {duration: options.in_duration, queue: false, ease: "easeOutCubic"});
+ $modal.data('associated-overlay', $overlay[0]);
+
+ // Define Bottom Sheet animation
+ var enterVelocityOptions = {
+ duration: options.in_duration,
+ queue: false,
+ ease: "easeOutCubic",
+ // Handle modal ready callback
+ complete: function () {
+ if (typeof(options.ready) === "function") {
+ options.ready.call(this, $modal, $trigger);
+ }
+ }
+ };
+ if ($modal.hasClass('bottom-sheet')) {
+ $modal.velocity({bottom: "0", opacity: 1}, enterVelocityOptions);
+ }
+ else {
+ $.Velocity.hook($modal, "scaleX", 0.7);
+ $modal.css({top: options.starting_top});
+ $modal.velocity({top: options.ending_top, opacity: 1, scaleX: '1'}, enterVelocityOptions);
+ }
+
+ };
+
+ // Reset handlers
+ $(document).off('click.modalTrigger', 'a[href="#' + modal_id + '"], [data-target="' + modal_id + '"]');
+ $(this).off('openModal');
+ $(this).off('closeModal');
+
+ // Close Handlers
+ $(document).on('click.modalTrigger', 'a[href="#' + modal_id + '"], [data-target="' + modal_id + '"]', function (e) {
+ options.starting_top = ($(this).offset().top - $(window).scrollTop()) / 1.15;
+ openModal($(this));
+ e.preventDefault();
+ }); // done set on click
+
+ $(this).on('openModal', function () {
+ var modal_id = $(this).attr("href") || '#' + $(this).data('target');
+ openModal();
+ });
+
+ $(this).on('closeModal', function (e) {
+ e.stopPropagation();
+ closeModal();
+ });
+ }); // done return
+ },
+ open: function () {
+ $(this).trigger('openModal');
+ },
+ close: function () {
+ $(this).trigger('closeModal');
+ }
+ };
+
+ /**
+ *
+ * This is $.fn.modal() method from documentation,
+ * but it's changed due to conflict with Odoo's
+ * $.fn.modal method.
+ * @param methodOrOptions
+ * @returns {*}
+ */
+ $.fn.materialModal = function (methodOrOptions) {
+ if (methods[methodOrOptions]) {
+ return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
+ } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
+ // Default to "init"
+ return methods.init.apply(this, arguments);
+ } else {
+ $.error('Method ' + methodOrOptions + ' does not exist on jQuery.modal');
+ }
+ };
+})(jQuery);
+;(function ($) {
+
+ $.fn.materialbox = function () {
+
+ return this.each(function () {
+
+ if ($(this).hasClass('initialized')) {
+ return;
+ }
+
+ $(this).addClass('initialized');
+
+ var overlayActive = false;
+ var doneAnimating = true;
+ var inDuration = 275;
+ var outDuration = 200;
+ var origin = $(this);
+ var placeholder = $('
').addClass('material-placeholder');
+ var originalWidth = 0;
+ var originalHeight = 0;
+ var ancestorsChanged;
+ var ancestor;
+ origin.wrap(placeholder);
+
+
+ origin.on('click', function () {
+ var placeholder = origin.parent('.material-placeholder');
+ var windowWidth = window.innerWidth;
+ var windowHeight = window.innerHeight;
+ var originalWidth = origin.width();
+ var originalHeight = origin.height();
+
+
+ // If already modal, return to original
+ if (doneAnimating === false) {
+ returnToOriginal();
+ return false;
+ }
+ else if (overlayActive && doneAnimating === true) {
+ returnToOriginal();
+ return false;
+ }
+
+
+ // Set states
+ doneAnimating = false;
+ origin.addClass('active');
+ overlayActive = true;
+
+ // Set positioning for placeholder
+ placeholder.css({
+ width: placeholder[0].getBoundingClientRect().width,
+ height: placeholder[0].getBoundingClientRect().height,
+ position: 'relative',
+ top: 0,
+ left: 0
+ });
+
+ // Find ancestor with overflow: hidden; and remove it
+ ancestorsChanged = undefined;
+ ancestor = placeholder[0].parentNode;
+ var count = 0;
+ while (ancestor !== null && !$(ancestor).is(document)) {
+ var curr = $(ancestor);
+ if (curr.css('overflow') !== 'visible') {
+ curr.css('overflow', 'visible');
+ if (ancestorsChanged === undefined) {
+ ancestorsChanged = curr;
+ }
+ else {
+ ancestorsChanged = ancestorsChanged.add(curr);
+ }
+ }
+ ancestor = ancestor.parentNode;
+ }
+
+ // Set css on origin
+ origin.css({position: 'absolute', 'z-index': 1000})
+ .data('width', originalWidth)
+ .data('height', originalHeight);
+
+ // Add overlay
+ var overlay = $('
')
+ .css({
+ opacity: 0
+ })
+ .click(function () {
+ if (doneAnimating === true)
+ returnToOriginal();
+ });
+ // Animate Overlay
+ // Put before in origin image to preserve z-index layering.
+ origin.before(overlay);
+ overlay.velocity({opacity: 1},
+ {duration: inDuration, queue: false, easing: 'easeOutQuad'});
+
+ // Add and animate caption if it exists
+ if (origin.data('caption') !== "") {
+ var $photo_caption = $('
');
+ $photo_caption.text(origin.data('caption'));
+ $('body').append($photo_caption);
+ $photo_caption.css({"display": "inline"});
+ $photo_caption.velocity({opacity: 1}, {duration: inDuration, queue: false, easing: 'easeOutQuad'});
+ }
+
+ // Resize Image
+ var ratio = 0;
+ var widthPercent = originalWidth / windowWidth;
+ var heightPercent = originalHeight / windowHeight;
+ var newWidth = 0;
+ var newHeight = 0;
+
+ if (widthPercent > heightPercent) {
+ ratio = originalHeight / originalWidth;
+ newWidth = windowWidth * 0.9;
+ newHeight = windowWidth * 0.9 * ratio;
+ }
+ else {
+ ratio = originalWidth / originalHeight;
+ newWidth = (windowHeight * 0.9) * ratio;
+ newHeight = windowHeight * 0.9;
+ }
+
+ // Animate image + set z-index
+ if (origin.hasClass('responsive-img')) {
+ origin.velocity({'max-width': newWidth, 'width': originalWidth}, {
+ duration: 0, queue: false,
+ complete: function () {
+ origin.css({left: 0, top: 0})
+ .velocity(
+ {
+ height: newHeight,
+ width: newWidth,
+ left: $(document).scrollLeft() + windowWidth / 2 - origin.parent('.material-placeholder').offset().left - newWidth / 2,
+ top: $(document).scrollTop() + windowHeight / 2 - origin.parent('.material-placeholder').offset().top - newHeight / 2
+ },
+ {
+ duration: inDuration,
+ queue: false,
+ easing: 'easeOutQuad',
+ complete: function () {
+ doneAnimating = true;
+ }
+ }
+ );
+ } // End Complete
+ }); // End Velocity
+ }
+ else {
+ origin.css('left', 0)
+ .css('top', 0)
+ .velocity(
+ {
+ height: newHeight,
+ width: newWidth,
+ left: $(document).scrollLeft() + windowWidth / 2 - origin.parent('.material-placeholder').offset().left - newWidth / 2,
+ top: $(document).scrollTop() + windowHeight / 2 - origin.parent('.material-placeholder').offset().top - newHeight / 2
+ },
+ {
+ duration: inDuration,
+ queue: false,
+ easing: 'easeOutQuad',
+ complete: function () {
+ doneAnimating = true;
+ }
+ }
+ ); // End Velocity
+ }
+
+ }); // End origin on click
+
+
+ // Return on scroll
+ $(window).scroll(function () {
+ if (overlayActive) {
+ returnToOriginal();
+ }
+ });
+
+ // Return on ESC
+ $(document).keyup(function (e) {
+
+ if (e.keyCode === 27 && doneAnimating === true) { // ESC key
+ if (overlayActive) {
+ returnToOriginal();
+ }
+ }
+ });
+
+
+ // This function returns the modaled image to the original spot
+ function returnToOriginal() {
+
+ doneAnimating = false;
+
+ var placeholder = origin.parent('.material-placeholder');
+ var windowWidth = window.innerWidth;
+ var windowHeight = window.innerHeight;
+ var originalWidth = origin.data('width');
+ var originalHeight = origin.data('height');
+
+ origin.velocity("stop", true);
+ $('#materialbox-overlay').velocity("stop", true);
+ $('.materialbox-caption').velocity("stop", true);
+
+
+ $('#materialbox-overlay').velocity({opacity: 0}, {
+ duration: outDuration, // Delay prevents animation overlapping
+ queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ // Remove Overlay
+ overlayActive = false;
+ $(this).remove();
+ }
+ });
+
+ // Resize Image
+ origin.velocity(
+ {
+ width: originalWidth,
+ height: originalHeight,
+ left: 0,
+ top: 0
+ },
+ {
+ duration: outDuration,
+ queue: false, easing: 'easeOutQuad'
+ }
+ );
+
+ // Remove Caption + reset css settings on image
+ $('.materialbox-caption').velocity({opacity: 0}, {
+ duration: outDuration, // Delay prevents animation overlapping
+ queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ placeholder.css({
+ height: '',
+ width: '',
+ position: '',
+ top: '',
+ left: ''
+ });
+
+ origin.css({
+ height: '',
+ top: '',
+ left: '',
+ width: '',
+ 'max-width': '',
+ position: '',
+ 'z-index': ''
+ });
+
+ // Remove class
+ origin.removeClass('active');
+ doneAnimating = true;
+ $(this).remove();
+
+ // Remove overflow overrides on ancestors
+ if (ancestorsChanged) {
+ ancestorsChanged.css('overflow', '');
+ }
+ }
+ });
+
+ }
+ });
+ };
+
+ $(document).ready(function () {
+ $('.materialboxed').materialbox();
+ });
+
+}(jQuery));
+;(function ($) {
+
+ $.fn.parallax = function () {
+ var window_width = $(window).width();
+ // Parallax Scripts
+ return this.each(function (i) {
+ var $this = $(this);
+ $this.addClass('parallax');
+
+ function updateParallax(initial) {
+ var container_height;
+ if (window_width < 601) {
+ container_height = ($this.height() > 0) ? $this.height() : $this.children("img").height();
+ }
+ else {
+ container_height = ($this.height() > 0) ? $this.height() : 500;
+ }
+ var $img = $this.children("img").first();
+ var img_height = $img.height();
+ var parallax_dist = img_height - container_height;
+ var bottom = $this.offset().top + container_height;
+ var top = $this.offset().top;
+ var scrollTop = $(window).scrollTop();
+ var windowHeight = window.innerHeight;
+ var windowBottom = scrollTop + windowHeight;
+ var percentScrolled = (windowBottom - top) / (container_height + windowHeight);
+ var parallax = Math.round((parallax_dist * percentScrolled));
+
+ if (initial) {
+ $img.css('display', 'block');
+ }
+ if ((bottom > scrollTop) && (top < (scrollTop + windowHeight))) {
+ $img.css('transform', "translate3D(-50%," + parallax + "px, 0)");
+ }
+
+ }
+
+ // Wait for image load
+ $this.children("img").one("load", function () {
+ updateParallax(true);
+ }).each(function () {
+ if (this.complete) $(this).trigger("load");
+ });
+
+ $(window).scroll(function () {
+ window_width = $(window).width();
+ updateParallax(false);
+ });
+
+ $(window).resize(function () {
+ window_width = $(window).width();
+ updateParallax(false);
+ });
+
+ });
+
+ };
+}(jQuery));
+;(function ($) {
+
+ var methods = {
+ init: function (options) {
+ var defaults = {
+ onShow: null
+ };
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+
+ // For each set of tabs, we want to keep track of
+ // which tab is active and its associated content
+ var $this = $(this),
+ window_width = $(window).width();
+
+ var $active, $content, $links = $this.find('li.tab a'),
+ $tabs_width = $this.width(),
+ $tab_width = Math.max($tabs_width, $this[0].scrollWidth) / $links.length,
+ $index = 0;
+
+ // Finds right attribute for indicator based on active tab.
+ // el: jQuery Object
+ var calcRightPos = function (el) {
+ return $tabs_width - el.position().left - el.outerWidth() - $this.scrollLeft();
+ };
+
+ // Finds left attribute for indicator based on active tab.
+ // el: jQuery Object
+ var calcLeftPos = function (el) {
+ return el.position().left + $this.scrollLeft();
+ };
+
+ // If the location.hash matches one of the links, use that as the active tab.
+ $active = $($links.filter('[href="' + location.hash + '"]'));
+
+ // If no match is found, use the first link or any with class 'active' as the initial active tab.
+ if ($active.length === 0) {
+ $active = $(this).find('li.tab a.active').first();
+ }
+ if ($active.length === 0) {
+ $active = $(this).find('li.tab a').first();
+ }
+
+ $active.addClass('active');
+ $index = $links.index($active);
+ if ($index < 0) {
+ $index = 0;
+ }
+
+ if ($active[0] !== undefined) {
+ $content = $($active[0].hash);
+ }
+
+ // append indicator then set indicator width to tab width
+ $this.append('
');
+ var $indicator = $this.find('.indicator');
+ if ($this.is(":visible")) {
+ // $indicator.css({"right": $tabs_width - (($index + 1) * $tab_width)});
+ // $indicator.css({"left": $index * $tab_width});
+ setTimeout(function () {
+ $indicator.css({"right": calcRightPos($active)});
+ $indicator.css({"left": calcLeftPos($active)});
+ }, 0);
+ }
+ $(window).resize(function () {
+ $tabs_width = $this.width();
+ $tab_width = Math.max($tabs_width, $this[0].scrollWidth) / $links.length;
+ if ($index < 0) {
+ $index = 0;
+ }
+ if ($tab_width !== 0 && $tabs_width !== 0) {
+ $indicator.css({"right": calcRightPos($active)});
+ $indicator.css({"left": calcLeftPos($active)});
+ }
+ });
+
+ // Hide the remaining content
+ $links.not($active).each(function () {
+ $(Materialize.escapeHash(this.hash)).hide();
+ });
+
+
+ // Bind the click event handler
+ $this.on('click', 'a', function (e) {
+ if ($(this).parent().hasClass('disabled')) {
+ e.preventDefault();
+ return;
+ }
+
+ // Act as regular link if target attribute is specified.
+ if (!!$(this).attr("target")) {
+ return;
+ }
+
+ $tabs_width = $this.width();
+ $tab_width = Math.max($tabs_width, $this[0].scrollWidth) / $links.length;
+
+ // Make the old tab inactive.
+ $active.removeClass('active');
+ if ($content !== undefined) {
+ $content.hide();
+ }
+
+ // Update the variables with the new link and content
+ $active = $(this);
+ $content = $(Materialize.escapeHash(this.hash));
+ $links = $this.find('li.tab a');
+ var activeRect = $active.position();
+
+ // Make the tab active.
+ $active.addClass('active');
+ var $prev_index = $index;
+ $index = $links.index($(this));
+ if ($index < 0) {
+ $index = 0;
+ }
+ // Change url to current tab
+ // window.location.hash = $active.attr('href');
+
+ if ($content !== undefined) {
+ $content.show();
+ if (typeof(options.onShow) === "function") {
+ options.onShow.call(this, $content);
+ }
+ }
+
+ // Update indicator
+
+ if (($index - $prev_index) >= 0) {
+ $indicator.velocity({"right": calcRightPos($active)}, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ $indicator.velocity({"left": calcLeftPos($active)}, {duration: 300, queue: false, easing: 'easeOutQuad', delay: 90});
+
+ } else {
+ $indicator.velocity({"left": calcLeftPos($active)}, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ $indicator.velocity({"right": calcRightPos($active)}, {duration: 300, queue: false, easing: 'easeOutQuad', delay: 90});
+ }
+
+ // Prevent the anchor's default click action
+ e.preventDefault();
+ });
+ });
+
+ },
+ select_tab: function (id) {
+ this.find('a[href="#' + id + '"]').trigger('click');
+ }
+ };
+
+ $.fn.tabs = function (methodOrOptions) {
+ if (methods[methodOrOptions]) {
+ return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
+ } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
+ // Default to "init"
+ return methods.init.apply(this, arguments);
+ } else {
+ $.error('Method ' + methodOrOptions + ' does not exist on jQuery.tabs');
+ }
+ };
+
+ $(document).ready(function () {
+ $('ul.tabs').tabs();
+ });
+}(jQuery));
+;(function ($) {
+ $.fn.tooltip = function (options) {
+ var timeout = null,
+ margin = 5;
+
+ // Defaults
+ var defaults = {
+ delay: 350,
+ tooltip: '',
+ position: 'bottom',
+ html: false
+ };
+
+ // Remove tooltip from the activator
+ if (options === "remove") {
+ this.each(function () {
+ $('#' + $(this).attr('data-tooltip-id')).remove();
+ $(this).off('mouseenter.tooltip mouseleave.tooltip');
+ });
+ return false;
+ }
+
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+ var tooltipId = Materialize.guid();
+ var origin = $(this);
+
+ // Destroy old tooltip
+ if (origin.attr('data-tooltip-id')) {
+ $('#' + origin.attr('data-tooltip-id')).remove();
+ }
+
+ origin.attr('data-tooltip-id', tooltipId);
+
+ // Get attributes.
+ var allowHtml,
+ tooltipDelay,
+ tooltipPosition,
+ tooltipText,
+ tooltipEl,
+ backdrop;
+ var setAttributes = function () {
+ allowHtml = origin.attr('data-html') ? origin.attr('data-html') === 'true' : options.html;
+ tooltipDelay = origin.attr('data-delay');
+ tooltipDelay = (tooltipDelay === undefined || tooltipDelay === '') ?
+ options.delay : tooltipDelay;
+ tooltipPosition = origin.attr('data-position');
+ tooltipPosition = (tooltipPosition === undefined || tooltipPosition === '') ?
+ options.position : tooltipPosition;
+ tooltipText = origin.attr('data-tooltip');
+ tooltipText = (tooltipText === undefined || tooltipText === '') ?
+ options.tooltip : tooltipText;
+ };
+ setAttributes();
+
+ var renderTooltipEl = function () {
+ var tooltip = $('
');
+
+ // Create Text span
+ if (allowHtml) {
+ tooltipText = $('
').html(tooltipText);
+ } else {
+ tooltipText = $('
').text(tooltipText);
+ }
+
+ // Create tooltip
+ tooltip.append(tooltipText)
+ .appendTo($('body'))
+ .attr('id', tooltipId);
+
+ // Create backdrop
+ backdrop = $('
');
+ backdrop.appendTo(tooltip);
+ return tooltip;
+ };
+ tooltipEl = renderTooltipEl();
+
+ // Destroy previously binded events
+ origin.off('mouseenter.tooltip mouseleave.tooltip');
+ // Mouse In
+ var started = false, timeoutRef;
+ origin.on({
+ 'mouseenter.tooltip': function (e) {
+ var showTooltip = function () {
+ setAttributes();
+ started = true;
+ tooltipEl.velocity('stop');
+ backdrop.velocity('stop');
+ tooltipEl.css({display: 'block', left: '0px', top: '0px'});
+
+ // Tooltip positioning
+ var originWidth = origin.outerWidth();
+ var originHeight = origin.outerHeight();
+
+ var tooltipHeight = tooltipEl.outerHeight();
+ var tooltipWidth = tooltipEl.outerWidth();
+ var tooltipVerticalMovement = '0px';
+ var tooltipHorizontalMovement = '0px';
+ var scaleXFactor = 8;
+ var scaleYFactor = 8;
+ var targetTop, targetLeft, newCoordinates;
+
+ if (tooltipPosition === "top") {
+ // Top Position
+ targetTop = origin.offset().top - tooltipHeight - margin;
+ targetLeft = origin.offset().left + originWidth / 2 - tooltipWidth / 2;
+ newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
+
+ tooltipVerticalMovement = '-10px';
+ backdrop.css({
+ bottom: 0,
+ left: 0,
+ borderRadius: '14px 14px 0 0',
+ transformOrigin: '50% 100%',
+ marginTop: tooltipHeight,
+ marginLeft: (tooltipWidth / 2) - (backdrop.width() / 2)
+ });
+ }
+ // Left Position
+ else if (tooltipPosition === "left") {
+ targetTop = origin.offset().top + originHeight / 2 - tooltipHeight / 2;
+ targetLeft = origin.offset().left - tooltipWidth - margin;
+ newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
+
+ tooltipHorizontalMovement = '-10px';
+ backdrop.css({
+ top: '-7px',
+ right: 0,
+ width: '14px',
+ height: '14px',
+ borderRadius: '14px 0 0 14px',
+ transformOrigin: '95% 50%',
+ marginTop: tooltipHeight / 2,
+ marginLeft: tooltipWidth
+ });
+ }
+ // Right Position
+ else if (tooltipPosition === "right") {
+ targetTop = origin.offset().top + originHeight / 2 - tooltipHeight / 2;
+ targetLeft = origin.offset().left + originWidth + margin;
+ newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
+
+ tooltipHorizontalMovement = '+10px';
+ backdrop.css({
+ top: '-7px',
+ left: 0,
+ width: '14px',
+ height: '14px',
+ borderRadius: '0 14px 14px 0',
+ transformOrigin: '5% 50%',
+ marginTop: tooltipHeight / 2,
+ marginLeft: '0px'
+ });
+ }
+ else {
+ // Bottom Position
+ targetTop = origin.offset().top + origin.outerHeight() + margin;
+ targetLeft = origin.offset().left + originWidth / 2 - tooltipWidth / 2;
+ newCoordinates = repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
+ tooltipVerticalMovement = '+10px';
+ backdrop.css({
+ top: 0,
+ left: 0,
+ marginLeft: (tooltipWidth / 2) - (backdrop.width() / 2)
+ });
+ }
+
+ // Set tooptip css placement
+ tooltipEl.css({
+ top: newCoordinates.y,
+ left: newCoordinates.x
+ });
+
+ // Calculate Scale to fill
+ scaleXFactor = Math.SQRT2 * tooltipWidth / parseInt(backdrop.css('width'));
+ scaleYFactor = Math.SQRT2 * tooltipHeight / parseInt(backdrop.css('height'));
+
+ tooltipEl.velocity({marginTop: tooltipVerticalMovement, marginLeft: tooltipHorizontalMovement}, {duration: 350, queue: false})
+ .velocity({opacity: 1}, {duration: 300, delay: 50, queue: false});
+ backdrop.css({display: 'block'})
+ .velocity({opacity: 1}, {duration: 55, delay: 0, queue: false})
+ .velocity({scaleX: scaleXFactor, scaleY: scaleYFactor}, {duration: 300, delay: 0, queue: false, easing: 'easeInOutQuad'});
+ };
+
+ timeoutRef = setTimeout(showTooltip, tooltipDelay); // End Interval
+
+ // Mouse Out
+ },
+ 'mouseleave.tooltip': function () {
+ // Reset State
+ started = false;
+ clearTimeout(timeoutRef);
+
+ // Animate back
+ setTimeout(function () {
+ if (started !== true) {
+ tooltipEl.velocity({
+ opacity: 0, marginTop: 0, marginLeft: 0
+ }, {duration: 225, queue: false});
+ backdrop.velocity({opacity: 0, scaleX: 1, scaleY: 1}, {
+ duration: 225,
+ queue: false,
+ complete: function () {
+ backdrop.css('display', 'none');
+ tooltipEl.css('display', 'none');
+ started = false;
+ }
+ });
+ }
+ }, 225);
+ }
+ });
+ });
+ };
+
+ var repositionWithinScreen = function (x, y, width, height) {
+ var newX = x;
+ var newY = y;
+
+ if (newX < 0) {
+ newX = 4;
+ } else if (newX + width > window.innerWidth) {
+ newX -= newX + width - window.innerWidth;
+ }
+
+ if (newY < 0) {
+ newY = 4;
+ } else if (newY + height > window.innerHeight + $(window).scrollTop) {
+ newY -= newY + height - window.innerHeight;
+ }
+
+ return {x: newX, y: newY};
+ };
+
+ $(document).ready(function () {
+ $('.tooltipped').tooltip();
+ });
+}(jQuery));
+/*!
+ * Waves v0.7.5
+ * http://fian.my.id/Waves
+ *
+ * Copyright 2014-2016 Alfiana E. Sibuea and other contributors
+ * Released under the MIT license
+ * https://github.com/fians/Waves/blob/master/LICENSE
+ */
+
+;(function (window, factory) {
+ 'use strict';
+
+ // AMD. Register as an anonymous module. Wrap in function so we have access
+ // to root via `this`.
+ if (typeof define === 'function' && define.amd) {
+ define([], function () {
+ return factory.apply(window);
+ });
+ }
+
+ // Node. Does not work with strict CommonJS, but only CommonJS-like
+ // environments that support module.exports, like Node.
+ else if (typeof exports === 'object') {
+ module.exports = factory.call(window);
+ }
+
+ // Browser globals.
+ else {
+ window.Waves = factory.call(window);
+ }
+})(typeof global === 'object' ? global : this, function () {
+ 'use strict';
+
+ var Waves = Waves || {};
+ var $$ = document.querySelectorAll.bind(document);
+ var toString = Object.prototype.toString;
+ var isTouchAvailable = 'ontouchstart' in window;
+
+
+ // Find exact position of element
+ function isWindow(obj) {
+ return obj !== null && obj === obj.window;
+ }
+
+ function getWindow(elem) {
+ return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView;
+ }
+
+ function isObject(value) {
+ var type = typeof value;
+ return type === 'function' || type === 'object' && !!value;
+ }
+
+ function isDOMNode(obj) {
+ return isObject(obj) && obj.nodeType > 0;
+ }
+
+ function getWavesElements(nodes) {
+ var stringRepr = toString.call(nodes);
+
+ if (stringRepr === '[object String]') {
+ return $$(nodes);
+ } else if (isObject(nodes) && /^\[object (Array|HTMLCollection|NodeList|Object)\]$/.test(stringRepr) && nodes.hasOwnProperty('length')) {
+ return nodes;
+ } else if (isDOMNode(nodes)) {
+ return [nodes];
+ }
+
+ return [];
+ }
+
+ function offset(elem) {
+ var docElem, win,
+ box = {top: 0, left: 0},
+ doc = elem && elem.ownerDocument;
+
+ docElem = doc.documentElement;
+
+ if (typeof elem.getBoundingClientRect !== typeof undefined) {
+ box = elem.getBoundingClientRect();
+ }
+ win = getWindow(doc);
+ return {
+ top: box.top + win.pageYOffset - docElem.clientTop,
+ left: box.left + win.pageXOffset - docElem.clientLeft
+ };
+ }
+
+ function convertStyle(styleObj) {
+ var style = '';
+
+ for (var prop in styleObj) {
+ if (styleObj.hasOwnProperty(prop)) {
+ style += (prop + ':' + styleObj[prop] + ';');
+ }
+ }
+
+ return style;
+ }
+
+ var Effect = {
+
+ // Effect duration
+ duration: 750,
+
+ // Effect delay (check for scroll before showing effect)
+ delay: 200,
+
+ show: function (e, element, velocity) {
+
+ // Disable right click
+ if (e.button === 2) {
+ return false;
+ }
+
+ element = element || this;
+
+ // Create ripple
+ var ripple = document.createElement('div');
+ ripple.className = 'waves-ripple waves-rippling';
+ element.appendChild(ripple);
+
+ // Get click coordinate and element width
+ var pos = offset(element);
+ var relativeY = 0;
+ var relativeX = 0;
+ // Support for touch devices
+ if ('touches' in e && e.touches.length) {
+ relativeY = (e.touches[0].pageY - pos.top);
+ relativeX = (e.touches[0].pageX - pos.left);
+ }
+ //Normal case
+ else {
+ relativeY = (e.pageY - pos.top);
+ relativeX = (e.pageX - pos.left);
+ }
+ // Support for synthetic events
+ relativeX = relativeX >= 0 ? relativeX : 0;
+ relativeY = relativeY >= 0 ? relativeY : 0;
+
+ var scale = 'scale(' + ((element.clientWidth / 100) * 3) + ')';
+ var translate = 'translate(0,0)';
+
+ if (velocity) {
+ translate = 'translate(' + (velocity.x) + 'px, ' + (velocity.y) + 'px)';
+ }
+
+ // Attach data to element
+ ripple.setAttribute('data-hold', Date.now());
+ ripple.setAttribute('data-x', relativeX);
+ ripple.setAttribute('data-y', relativeY);
+ ripple.setAttribute('data-scale', scale);
+ ripple.setAttribute('data-translate', translate);
+
+ // Set ripple position
+ var rippleStyle = {
+ top: relativeY + 'px',
+ left: relativeX + 'px'
+ };
+
+ ripple.classList.add('waves-notransition');
+ ripple.setAttribute('style', convertStyle(rippleStyle));
+ ripple.classList.remove('waves-notransition');
+
+ // Scale the ripple
+ rippleStyle['-webkit-transform'] = scale + ' ' + translate;
+ rippleStyle['-moz-transform'] = scale + ' ' + translate;
+ rippleStyle['-ms-transform'] = scale + ' ' + translate;
+ rippleStyle['-o-transform'] = scale + ' ' + translate;
+ rippleStyle.transform = scale + ' ' + translate;
+ rippleStyle.opacity = '1';
+
+ var duration = e.type === 'mousemove' ? 2500 : Effect.duration;
+ rippleStyle['-webkit-transition-duration'] = duration + 'ms';
+ rippleStyle['-moz-transition-duration'] = duration + 'ms';
+ rippleStyle['-o-transition-duration'] = duration + 'ms';
+ rippleStyle['transition-duration'] = duration + 'ms';
+
+ ripple.setAttribute('style', convertStyle(rippleStyle));
+ },
+
+ hide: function (e, element) {
+ element = element || this;
+
+ var ripples = element.getElementsByClassName('waves-rippling');
+
+ for (var i = 0, len = ripples.length; i < len; i++) {
+ removeRipple(e, element, ripples[i]);
+ }
+ }
+ };
+
+ /**
+ * Collection of wrapper for HTML element that only have single tag
+ * like
and
+ */
+ var TagWrapper = {
+
+ // Wrap
tag so it can perform the effect
+ input: function (element) {
+
+ var parent = element.parentNode;
+
+ // If input already have parent just pass through
+ if (parent.tagName.toLowerCase() === 'i' && parent.classList.contains('waves-effect')) {
+ return;
+ }
+
+ // Put element class and style to the specified parent
+ var wrapper = document.createElement('i');
+ wrapper.className = element.className + ' waves-input-wrapper';
+ element.className = 'waves-button-input';
+
+ // Put element as child
+ parent.replaceChild(wrapper, element);
+ wrapper.appendChild(element);
+
+ // Apply element color and background color to wrapper
+ var elementStyle = window.getComputedStyle(element, null);
+ var color = elementStyle.color;
+ var backgroundColor = elementStyle.backgroundColor;
+
+ wrapper.setAttribute('style', 'color:' + color + ';background:' + backgroundColor);
+ element.setAttribute('style', 'background-color:rgba(0,0,0,0);');
+
+ },
+
+ // Wrap
tag so it can perform the effect
+ img: function (element) {
+
+ var parent = element.parentNode;
+
+ // If input already have parent just pass through
+ if (parent.tagName.toLowerCase() === 'i' && parent.classList.contains('waves-effect')) {
+ return;
+ }
+
+ // Put element as child
+ var wrapper = document.createElement('i');
+ parent.replaceChild(wrapper, element);
+ wrapper.appendChild(element);
+
+ }
+ };
+
+ /**
+ * Hide the effect and remove the ripple. Must be
+ * a separate function to pass the JSLint...
+ */
+ function removeRipple(e, el, ripple) {
+
+ // Check if the ripple still exist
+ if (!ripple) {
+ return;
+ }
+
+ ripple.classList.remove('waves-rippling');
+
+ var relativeX = ripple.getAttribute('data-x');
+ var relativeY = ripple.getAttribute('data-y');
+ var scale = ripple.getAttribute('data-scale');
+ var translate = ripple.getAttribute('data-translate');
+
+ // Get delay beetween mousedown and mouse leave
+ var diff = Date.now() - Number(ripple.getAttribute('data-hold'));
+ var delay = 350 - diff;
+
+ if (delay < 0) {
+ delay = 0;
+ }
+
+ if (e.type === 'mousemove') {
+ delay = 150;
+ }
+
+ // Fade out ripple after delay
+ var duration = e.type === 'mousemove' ? 2500 : Effect.duration;
+
+ setTimeout(function () {
+
+ var style = {
+ top: relativeY + 'px',
+ left: relativeX + 'px',
+ opacity: '0',
+
+ // Duration
+ '-webkit-transition-duration': duration + 'ms',
+ '-moz-transition-duration': duration + 'ms',
+ '-o-transition-duration': duration + 'ms',
+ 'transition-duration': duration + 'ms',
+ '-webkit-transform': scale + ' ' + translate,
+ '-moz-transform': scale + ' ' + translate,
+ '-ms-transform': scale + ' ' + translate,
+ '-o-transform': scale + ' ' + translate,
+ 'transform': scale + ' ' + translate
+ };
+
+ ripple.setAttribute('style', convertStyle(style));
+
+ setTimeout(function () {
+ try {
+ el.removeChild(ripple);
+ } catch (e) {
+ return false;
+ }
+ }, duration);
+
+ }, delay);
+ }
+
+
+ /**
+ * Disable mousedown event for 500ms during and after touch
+ */
+ var TouchHandler = {
+
+ /* uses an integer rather than bool so there's no issues with
+ * needing to clear timeouts if another touch event occurred
+ * within the 500ms. Cannot mouseup between touchstart and
+ * touchend, nor in the 500ms after touchend. */
+ touches: 0,
+
+ allowEvent: function (e) {
+
+ var allow = true;
+
+ if (/^(mousedown|mousemove)$/.test(e.type) && TouchHandler.touches) {
+ allow = false;
+ }
+
+ return allow;
+ },
+ registerEvent: function (e) {
+ var eType = e.type;
+
+ if (eType === 'touchstart') {
+
+ TouchHandler.touches += 1; // push
+
+ } else if (/^(touchend|touchcancel)$/.test(eType)) {
+
+ setTimeout(function () {
+ if (TouchHandler.touches) {
+ TouchHandler.touches -= 1; // pop after 500ms
+ }
+ }, 500);
+
+ }
+ }
+ };
+
+
+ /**
+ * Delegated click handler for .waves-effect element.
+ * returns null when .waves-effect element not in "click tree"
+ */
+ function getWavesEffectElement(e) {
+
+ if (TouchHandler.allowEvent(e) === false) {
+ return null;
+ }
+
+ var element = null;
+ var target = e.target || e.srcElement;
+
+ while (target.parentElement !== null) {
+ if (target.classList.contains('waves-effect') && (!(target instanceof SVGElement))) {
+ element = target;
+ break;
+ }
+ target = target.parentElement;
+ }
+
+ return element;
+ }
+
+ /**
+ * Bubble the click and show effect if .waves-effect elem was found
+ */
+ function showEffect(e) {
+
+ // Disable effect if element has "disabled" property on it
+ // In some cases, the event is not triggered by the current element
+ // if (e.target.getAttribute('disabled') !== null) {
+ // return;
+ // }
+
+ var element = getWavesEffectElement(e);
+
+ if (element !== null) {
+
+ // Make it sure the element has either disabled property, disabled attribute or 'disabled' class
+ if (element.disabled || element.getAttribute('disabled') || element.classList.contains('disabled')) {
+ return;
+ }
+
+ TouchHandler.registerEvent(e);
+
+ if (e.type === 'touchstart' && Effect.delay) {
+
+ var hidden = false;
+
+ var timer = setTimeout(function () {
+ timer = null;
+ Effect.show(e, element);
+ }, Effect.delay);
+
+ var hideEffect = function (hideEvent) {
+
+ // if touch hasn't moved, and effect not yet started: start effect now
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ Effect.show(e, element);
+ }
+ if (!hidden) {
+ hidden = true;
+ Effect.hide(hideEvent, element);
+ }
+ };
+
+ var touchMove = function (moveEvent) {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ hideEffect(moveEvent);
+ };
+
+ element.addEventListener('touchmove', touchMove, false);
+ element.addEventListener('touchend', hideEffect, false);
+ element.addEventListener('touchcancel', hideEffect, false);
+
+ } else {
+
+ Effect.show(e, element);
+
+ if (isTouchAvailable) {
+ element.addEventListener('touchend', Effect.hide, false);
+ element.addEventListener('touchcancel', Effect.hide, false);
+ }
+
+ element.addEventListener('mouseup', Effect.hide, false);
+ element.addEventListener('mouseleave', Effect.hide, false);
+ }
+ }
+ }
+
+ Waves.init = function (options) {
+ var body = document.body;
+
+ options = options || {};
+
+ if ('duration' in options) {
+ Effect.duration = options.duration;
+ }
+
+ if ('delay' in options) {
+ Effect.delay = options.delay;
+ }
+
+ if (isTouchAvailable) {
+ body.addEventListener('touchstart', showEffect, false);
+ body.addEventListener('touchcancel', TouchHandler.registerEvent, false);
+ body.addEventListener('touchend', TouchHandler.registerEvent, false);
+ }
+
+ body.addEventListener('mousedown', showEffect, false);
+ };
+
+
+ /**
+ * Attach Waves to dynamically loaded inputs, or add .waves-effect and other
+ * waves classes to a set of elements. Set drag to true if the ripple mouseover
+ * or skimming effect should be applied to the elements.
+ */
+ Waves.attach = function (elements, classes) {
+
+ elements = getWavesElements(elements);
+
+ if (toString.call(classes) === '[object Array]') {
+ classes = classes.join(' ');
+ }
+
+ classes = classes ? ' ' + classes : '';
+
+ var element, tagName;
+
+ for (var i = 0, len = elements.length; i < len; i++) {
+
+ element = elements[i];
+ tagName = element.tagName.toLowerCase();
+
+ if (['input', 'img'].indexOf(tagName) !== -1) {
+ TagWrapper[tagName](element);
+ element = element.parentElement;
+ }
+
+ if (element.className.indexOf('waves-effect') === -1) {
+ element.className += ' waves-effect' + classes;
+ }
+ }
+ };
+
+
+ /**
+ * Cause a ripple to appear in an element via code.
+ */
+ Waves.ripple = function (elements, options) {
+ elements = getWavesElements(elements);
+ var elementsLen = elements.length;
+
+ options = options || {};
+ options.wait = options.wait || 0;
+ options.position = options.position || null; // default = centre of element
+
+
+ if (elementsLen) {
+ var element, pos, off, centre = {}, i = 0;
+ var mousedown = {
+ type: 'mousedown',
+ button: 1
+ };
+ var hideRipple = function (mouseup, element) {
+ return function () {
+ Effect.hide(mouseup, element);
+ };
+ };
+
+ for (; i < elementsLen; i++) {
+ element = elements[i];
+ pos = options.position || {
+ x: element.clientWidth / 2,
+ y: element.clientHeight / 2
+ };
+
+ off = offset(element);
+ centre.x = off.left + pos.x;
+ centre.y = off.top + pos.y;
+
+ mousedown.pageX = centre.x;
+ mousedown.pageY = centre.y;
+
+ Effect.show(mousedown, element);
+
+ if (options.wait >= 0 && options.wait !== null) {
+ var mouseup = {
+ type: 'mouseup',
+ button: 1
+ };
+
+ setTimeout(hideRipple(mouseup, element), options.wait);
+ }
+ }
+ }
+ };
+
+ /**
+ * Remove all ripples from an element.
+ */
+ Waves.calm = function (elements) {
+ elements = getWavesElements(elements);
+ var mouseup = {
+ type: 'mouseup',
+ button: 1
+ };
+
+ for (var i = 0, len = elements.length; i < len; i++) {
+ Effect.hide(mouseup, elements[i]);
+ }
+ };
+
+ /**
+ * Deprecated API fallback
+ */
+ Waves.displayEffect = function (options) {
+ console.error('Waves.displayEffect() has been deprecated and will be removed in future version. Please use Waves.init() to initialize Waves effect');
+ Waves.init(options);
+ };
+
+ window.Waves = Waves;
+ return Waves;
+});
+;Materialize.toast = function (message, displayLength, className, completeCallback) {
+ className = className || "";
+
+ var container = document.getElementById('toast-container');
+
+ // Create toast container if it does not exist
+ if (container === null) {
+ // create notification container
+ container = document.createElement('div');
+ container.id = 'toast-container';
+ document.body.appendChild(container);
+ }
+
+ // Select and append toast
+ var newToast = createToast(message);
+
+ // only append toast if message is not undefined
+ if (message) {
+ container.appendChild(newToast);
+ }
+
+ newToast.style.top = '35px';
+ newToast.style.opacity = 0;
+
+ // Animate toast in
+ Vel(newToast, {"top": "0px", opacity: 1}, {
+ duration: 300,
+ easing: 'easeOutCubic',
+ queue: false
+ });
+
+ // Allows timer to be pause while being panned
+ var timeLeft = displayLength;
+ var counterInterval;
+ if (timeLeft != null) {
+ counterInterval = setInterval(function () {
+ if (newToast.parentNode === null)
+ window.clearInterval(counterInterval);
+
+ // If toast is not being dragged, decrease its time remaining
+ if (!newToast.classList.contains('panning')) {
+ timeLeft -= 20;
+ }
+
+ if (timeLeft <= 0) {
+ // Animate toast out
+ Vel(newToast, {"opacity": 0, marginTop: '-40px'}, {
+ duration: 375,
+ easing: 'easeOutExpo',
+ queue: false,
+ complete: function () {
+ // Call the optional callback
+ if (typeof(completeCallback) === "function")
+ completeCallback();
+ // Remove toast after it times out
+ this[0].parentNode.removeChild(this[0]);
+ }
+ });
+ window.clearInterval(counterInterval);
+ }
+ }, 20);
+ }
+
+
+ function createToast(html) {
+
+ // Create toast
+ var toast = document.createElement('div');
+ toast.classList.add('toast');
+ if (className) {
+ var classes = className.split(' ');
+
+ for (var i = 0, count = classes.length; i < count; i++) {
+ toast.classList.add(classes[i]);
+ }
+ }
+ // If type of parameter is HTML Element
+ if (typeof HTMLElement === "object" ? html instanceof HTMLElement : html && typeof html === "object" && html !== null && html.nodeType === 1 && typeof html.nodeName === "string"
+ ) {
+ toast.appendChild(html);
+ }
+ else if (html instanceof jQuery) {
+ // Check if it is jQuery object
+ toast.appendChild(html[0]);
+ }
+ else {
+ // Insert as text;
+ toast.innerHTML = html;
+ }
+ // Bind hammer
+ var hammerHandler = new Hammer(toast, {prevent_default: false});
+ hammerHandler.on('pan', function (e) {
+ var deltaX = e.deltaX;
+ var activationDistance = 80;
+
+ // Change toast state
+ if (!toast.classList.contains('panning')) {
+ toast.classList.add('panning');
+ }
+
+ var opacityPercent = 1 - Math.abs(deltaX / activationDistance);
+ if (opacityPercent < 0)
+ opacityPercent = 0;
+
+ Vel(toast, {left: deltaX, opacity: opacityPercent}, {duration: 50, queue: false, easing: 'easeOutQuad'});
+
+ });
+
+ hammerHandler.on('panend', function (e) {
+ var deltaX = e.deltaX;
+ var activationDistance = 80;
+
+ // If toast dragged past activation point
+ if (Math.abs(deltaX) > activationDistance) {
+ Vel(toast, {marginTop: '-40px'}, {
+ duration: 375,
+ easing: 'easeOutExpo',
+ queue: false,
+ complete: function () {
+ if (typeof(completeCallback) === "function") {
+ completeCallback();
+ }
+ toast.parentNode.removeChild(toast);
+ }
+ });
+
+ } else {
+ toast.classList.remove('panning');
+ // Put toast back into original position
+ Vel(toast, {left: 0, opacity: 1}, {
+ duration: 300,
+ easing: 'easeOutExpo',
+ queue: false
+ });
+
+ }
+ });
+
+ return toast;
+ }
+};
+;(function ($) {
+
+ var methods = {
+ init: function (options) {
+ var defaults = {
+ menuWidth: 300,
+ edge: 'left',
+ closeOnClick: false,
+ draggable: true
+ };
+ options = $.extend(defaults, options);
+
+ $(this).each(function () {
+ var $this = $(this);
+ var menu_id = $("#" + $this.attr('data-activates'));
+
+ // Set to width
+ if (options.menuWidth != 300) {
+ menu_id.css('width', options.menuWidth);
+ }
+
+ // Add Touch Area
+ var $dragTarget;
+ if (options.draggable) {
+ $dragTarget = $('
').attr('data-sidenav', $this.attr('data-activates'));
+ $('body').append($dragTarget);
+ } else {
+ $dragTarget = $();
+ }
+
+ if (options.edge == 'left') {
+ menu_id.css('transform', 'translateX(-100%)');
+ $dragTarget.css({'left': 0}); // Add Touch Area
+ }
+ else {
+ menu_id.addClass('right-aligned') // Change text-alignment to right
+ .css('transform', 'translateX(100%)');
+ $dragTarget.css({'right': 0}); // Add Touch Area
+ }
+
+ // If fixed sidenav, bring menu out
+ if (menu_id.hasClass('fixed')) {
+ if (window.innerWidth > 992) {
+ menu_id.css('transform', 'translateX(0)');
+ }
+ }
+
+ // Window resize to reset on large screens fixed
+ if (menu_id.hasClass('fixed')) {
+ $(window).resize(function () {
+ if (window.innerWidth > 992) {
+ // Close menu if window is resized bigger than 992 and user has fixed sidenav
+ if ($('#sidenav-overlay').length !== 0 && menuOut) {
+ removeMenu(true);
+ }
+ else {
+ // menu_id.removeAttr('style');
+ menu_id.css('transform', 'translateX(0%)');
+ // menu_id.css('width', options.menuWidth);
+ }
+ }
+ else if (menuOut === false) {
+ if (options.edge === 'left') {
+ menu_id.css('transform', 'translateX(-100%)');
+ } else {
+ menu_id.css('transform', 'translateX(100%)');
+ }
+
+ }
+
+ });
+ }
+
+ // if closeOnClick, then add close event for all a tags in side sideNav
+ if (options.closeOnClick === true) {
+ menu_id.on("click.itemclick", "a:not(.collapsible-header)", function () {
+ removeMenu();
+ });
+ }
+
+ var removeMenu = function (restoreNav) {
+ panning = false;
+ menuOut = false;
+ // Reenable scrolling
+ $('body').css({
+ overflow: '',
+ width: ''
+ });
+
+ $('#sidenav-overlay').velocity({opacity: 0}, {
+ duration: 200,
+ queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ $(this).remove();
+ }
+ });
+ if (options.edge === 'left') {
+ // Reset phantom div
+ $dragTarget.css({width: '', right: '', left: '0'});
+ menu_id.velocity(
+ {'translateX': '-100%'},
+ {
+ duration: 200,
+ queue: false,
+ easing: 'easeOutCubic',
+ complete: function () {
+ if (restoreNav === true) {
+ // Restore Fixed sidenav
+ menu_id.removeAttr('style');
+ menu_id.css('width', options.menuWidth);
+ }
+ }
+
+ });
+ }
+ else {
+ // Reset phantom div
+ $dragTarget.css({width: '', right: '0', left: ''});
+ menu_id.velocity(
+ {'translateX': '100%'},
+ {
+ duration: 200,
+ queue: false,
+ easing: 'easeOutCubic',
+ complete: function () {
+ if (restoreNav === true) {
+ // Restore Fixed sidenav
+ menu_id.removeAttr('style');
+ menu_id.css('width', options.menuWidth);
+ }
+ }
+ });
+ }
+ };
+
+
+ // Touch Event
+ var panning = false;
+ var menuOut = false;
+
+ if (options.draggable) {
+ $dragTarget.on('click', function () {
+ if (menuOut) {
+ removeMenu();
+ }
+ });
+
+ $dragTarget.hammer({
+ prevent_default: false
+ }).bind('pan', function (e) {
+
+ if (e.gesture.pointerType == "touch") {
+
+ var direction = e.gesture.direction;
+ var x = e.gesture.center.x;
+ var y = e.gesture.center.y;
+ var velocityX = e.gesture.velocityX;
+
+ // Disable Scrolling
+ var $body = $('body');
+ var $overlay = $('#sidenav-overlay');
+ var oldWidth = $body.innerWidth();
+ $body.css('overflow', 'hidden');
+ $body.width(oldWidth);
+
+ // If overlay does not exist, create one and if it is clicked, close menu
+ if ($overlay.length === 0) {
+ $overlay = $('
');
+ $overlay.css('opacity', 0).click(function () {
+ removeMenu();
+ });
+ $('body').append($overlay);
+ }
+
+ // Keep within boundaries
+ if (options.edge === 'left') {
+ if (x > options.menuWidth) {
+ x = options.menuWidth;
+ }
+ else if (x < 0) {
+ x = 0;
+ }
+ }
+
+ if (options.edge === 'left') {
+ // Left Direction
+ if (x < (options.menuWidth / 2)) {
+ menuOut = false;
+ }
+ // Right Direction
+ else if (x >= (options.menuWidth / 2)) {
+ menuOut = true;
+ }
+ menu_id.css('transform', 'translateX(' + (x - options.menuWidth) + 'px)');
+ }
+ else {
+ // Left Direction
+ if (x < (window.innerWidth - options.menuWidth / 2)) {
+ menuOut = true;
+ }
+ // Right Direction
+ else if (x >= (window.innerWidth - options.menuWidth / 2)) {
+ menuOut = false;
+ }
+ var rightPos = (x - options.menuWidth / 2);
+ if (rightPos < 0) {
+ rightPos = 0;
+ }
+
+ menu_id.css('transform', 'translateX(' + rightPos + 'px)');
+ }
+
+
+ // Percentage overlay
+ var overlayPerc;
+ if (options.edge === 'left') {
+ overlayPerc = x / options.menuWidth;
+ $overlay.velocity({opacity: overlayPerc}, {duration: 10, queue: false, easing: 'easeOutQuad'});
+ }
+ else {
+ overlayPerc = Math.abs((x - window.innerWidth) / options.menuWidth);
+ $overlay.velocity({opacity: overlayPerc}, {duration: 10, queue: false, easing: 'easeOutQuad'});
+ }
+ }
+
+ }).bind('panend', function (e) {
+
+ if (e.gesture.pointerType == "touch") {
+ var $overlay = $('
');
+ var velocityX = e.gesture.velocityX;
+ var x = e.gesture.center.x;
+ var leftPos = x - options.menuWidth;
+ var rightPos = x - options.menuWidth / 2;
+ if (leftPos > 0) {
+ leftPos = 0;
+ }
+ if (rightPos < 0) {
+ rightPos = 0;
+ }
+ panning = false;
+
+ if (options.edge === 'left') {
+ // If velocityX <= 0.3 then the user is flinging the menu closed so ignore menuOut
+ if ((menuOut && velocityX <= 0.3) || velocityX < -0.5) {
+ // Return menu to open
+ if (leftPos !== 0) {
+ menu_id.velocity({'translateX': [0, leftPos]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ }
+
+ $overlay.velocity({opacity: 1}, {duration: 50, queue: false, easing: 'easeOutQuad'});
+ $dragTarget.css({width: '50%', right: 0, left: ''});
+ menuOut = true;
+ }
+ else if (!menuOut || velocityX > 0.3) {
+ // Enable Scrolling
+ $('body').css({
+ overflow: '',
+ width: ''
+ });
+ // Slide menu closed
+ menu_id.velocity({'translateX': [-1 * options.menuWidth - 10, leftPos]}, {
+ duration: 200,
+ queue: false,
+ easing: 'easeOutQuad'
+ });
+ $overlay.velocity({opacity: 0}, {
+ duration: 200, queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ $(this).remove();
+ }
+ });
+ $dragTarget.css({width: '10px', right: '', left: 0});
+ }
+ }
+ else {
+ if ((menuOut && velocityX >= -0.3) || velocityX > 0.5) {
+ // Return menu to open
+ if (rightPos !== 0) {
+ menu_id.velocity({'translateX': [0, rightPos]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ }
+
+ $overlay.velocity({opacity: 1}, {duration: 50, queue: false, easing: 'easeOutQuad'});
+ $dragTarget.css({width: '50%', right: '', left: 0});
+ menuOut = true;
+ }
+ else if (!menuOut || velocityX < -0.3) {
+ // Enable Scrolling
+ $('body').css({
+ overflow: '',
+ width: ''
+ });
+
+ // Slide menu closed
+ menu_id.velocity({'translateX': [options.menuWidth + 10, rightPos]}, {
+ duration: 200,
+ queue: false,
+ easing: 'easeOutQuad'
+ });
+ $overlay.velocity({opacity: 0}, {
+ duration: 200, queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ $(this).remove();
+ }
+ });
+ $dragTarget.css({width: '10px', right: 0, left: ''});
+ }
+ }
+
+ }
+ });
+ }
+
+ $this.click(function () {
+ if (menuOut === true) {
+ menuOut = false;
+ panning = false;
+ removeMenu();
+ }
+ else {
+
+ // Disable Scrolling
+ var $body = $('body');
+ var $overlay = $('
');
+ var oldWidth = $body.innerWidth();
+ $body.css('overflow', 'hidden');
+ $body.width(oldWidth);
+
+ // Push current drag target on top of DOM tree
+ $('body').append($dragTarget);
+
+ if (options.edge === 'left') {
+ $dragTarget.css({width: '50%', right: 0, left: ''});
+ menu_id.velocity({'translateX': [0, -1 * options.menuWidth]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ }
+ else {
+ $dragTarget.css({width: '50%', right: '', left: 0});
+ menu_id.velocity({'translateX': [0, options.menuWidth]}, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ }
+
+ $overlay.css('opacity', 0)
+ .click(function () {
+ menuOut = false;
+ panning = false;
+ removeMenu();
+ $overlay.velocity({opacity: 0}, {
+ duration: 300, queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ $(this).remove();
+ }
+ });
+
+ });
+ $('body').append($overlay);
+ $overlay.velocity({opacity: 1}, {
+ duration: 300, queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ menuOut = true;
+ panning = false;
+ }
+ });
+ }
+
+ return false;
+ });
+ });
+
+
+ },
+ destroy: function () {
+ var $overlay = $('#sidenav-overlay');
+ var $dragTarget = $('.drag-target[data-sidenav="' + $(this).attr('data-activates') + '"]');
+ $overlay.trigger('click');
+ $dragTarget.remove();
+ $(this).off('click');
+ $overlay.remove();
+ },
+ show: function () {
+ this.trigger('click');
+ },
+ hide: function () {
+ $('#sidenav-overlay').trigger('click');
+ }
+ };
+
+
+ $.fn.sideNav = function (methodOrOptions) {
+ if (methods[methodOrOptions]) {
+ return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
+ } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
+ // Default to "init"
+ return methods.init.apply(this, arguments);
+ } else {
+ $.error('Method ' + methodOrOptions + ' does not exist on jQuery.sideNav');
+ }
+ }; // Plugin end
+}(jQuery));
+;/**
+ * Extend jquery with a scrollspy plugin.
+ * This watches the window scroll and fires events when elements are scrolled into viewport.
+ *
+ * throttle() and getTime() taken from Underscore.js
+ * https://github.com/jashkenas/underscore
+ *
+ * @author Copyright 2013 John Smart
+ * @license https://raw.github.com/thesmart/jquery-scrollspy/master/LICENSE
+ * @see https://github.com/thesmart
+ * @version 0.1.2
+ */
+(function ($) {
+
+ var jWindow = $(window);
+ var elements = [];
+ var elementsInView = [];
+ var isSpying = false;
+ var ticks = 0;
+ var unique_id = 1;
+ var offset = {
+ top: 0,
+ right: 0,
+ bottom: 0,
+ left: 0,
+ }
+
+ /**
+ * Find elements that are within the boundary
+ * @param {number} top
+ * @param {number} right
+ * @param {number} bottom
+ * @param {number} left
+ * @return {jQuery} A collection of elements
+ */
+ function findElements(top, right, bottom, left) {
+ var hits = $();
+ $.each(elements, function (i, element) {
+ if (element.height() > 0) {
+ var elTop = element.offset().top,
+ elLeft = element.offset().left,
+ elRight = elLeft + element.width(),
+ elBottom = elTop + element.height();
+
+ var isIntersect = !(elLeft > right ||
+ elRight < left ||
+ elTop > bottom ||
+ elBottom < top);
+
+ if (isIntersect) {
+ hits.push(element);
+ }
+ }
+ });
+
+ return hits;
+ }
+
+
+ /**
+ * Called when the user scrolls the window
+ */
+ function onScroll(scrollOffset) {
+ // unique tick id
+ ++ticks;
+
+ // viewport rectangle
+ var top = jWindow.scrollTop(),
+ left = jWindow.scrollLeft(),
+ right = left + jWindow.width(),
+ bottom = top + jWindow.height();
+
+ // determine which elements are in view
+ var intersections = findElements(top + offset.top + scrollOffset || 200, right + offset.right, bottom + offset.bottom, left + offset.left);
+ $.each(intersections, function (i, element) {
+
+ var lastTick = element.data('scrollSpy:ticks');
+ if (typeof lastTick != 'number') {
+ // entered into view
+ element.triggerHandler('scrollSpy:enter');
+ }
+
+ // update tick id
+ element.data('scrollSpy:ticks', ticks);
+ });
+
+ // determine which elements are no longer in view
+ $.each(elementsInView, function (i, element) {
+ var lastTick = element.data('scrollSpy:ticks');
+ if (typeof lastTick == 'number' && lastTick !== ticks) {
+ // exited from view
+ element.triggerHandler('scrollSpy:exit');
+ element.data('scrollSpy:ticks', null);
+ }
+ });
+
+ // remember elements in view for next tick
+ elementsInView = intersections;
+ }
+
+ /**
+ * Called when window is resized
+ */
+ function onWinSize() {
+ jWindow.trigger('scrollSpy:winSize');
+ }
+
+ /**
+ * Get time in ms
+ * @license https://raw.github.com/jashkenas/underscore/master/LICENSE
+ * @type {function}
+ * @return {number}
+ */
+ var getTime = (Date.now || function () {
+ return new Date().getTime();
+ });
+
+ /**
+ * Returns a function, that, when invoked, will only be triggered at most once
+ * during a given window of time. Normally, the throttled function will run
+ * as much as it can, without ever going more than once per `wait` duration;
+ * but if you'd like to disable the execution on the leading edge, pass
+ * `{leading: false}`. To disable execution on the trailing edge, ditto.
+ * @license https://raw.github.com/jashkenas/underscore/master/LICENSE
+ * @param {function} func
+ * @param {number} wait
+ * @param {Object=} options
+ * @returns {Function}
+ */
+ function throttle(func, wait, options) {
+ var context, args, result;
+ var timeout = null;
+ var previous = 0;
+ options || (options = {});
+ var later = function () {
+ previous = options.leading === false ? 0 : getTime();
+ timeout = null;
+ result = func.apply(context, args);
+ context = args = null;
+ };
+ return function () {
+ var now = getTime();
+ if (!previous && options.leading === false) previous = now;
+ var remaining = wait - (now - previous);
+ context = this;
+ args = arguments;
+ if (remaining <= 0) {
+ clearTimeout(timeout);
+ timeout = null;
+ previous = now;
+ result = func.apply(context, args);
+ context = args = null;
+ } else if (!timeout && options.trailing !== false) {
+ timeout = setTimeout(later, remaining);
+ }
+ return result;
+ };
+ };
+
+ /**
+ * Enables ScrollSpy using a selector
+ * @param {jQuery|string} selector The elements collection, or a selector
+ * @param {Object=} options Optional.
+ throttle : number -> scrollspy throttling. Default: 100 ms
+ offsetTop : number -> offset from top. Default: 0
+ offsetRight : number -> offset from right. Default: 0
+ offsetBottom : number -> offset from bottom. Default: 0
+ offsetLeft : number -> offset from left. Default: 0
+ * @returns {jQuery}
+ */
+ $.scrollSpy = function (selector, options) {
+ var defaults = {
+ throttle: 100,
+ scrollOffset: 200 // offset - 200 allows elements near bottom of page to scroll
+ };
+ options = $.extend(defaults, options);
+
+ var visible = [];
+ selector = $(selector);
+ selector.each(function (i, element) {
+ elements.push($(element));
+ $(element).data("scrollSpy:id", i);
+ // Smooth scroll to section
+ $('a[href="#' + $(element).attr('id') + '"]').click(function (e) {
+ e.preventDefault();
+ var offset = $(Materialize.escapeHash(this.hash)).offset().top + 1;
+ $('html, body').animate({scrollTop: offset - options.scrollOffset}, {duration: 400, queue: false, easing: 'easeOutCubic'});
+ });
+ });
+
+ offset.top = options.offsetTop || 0;
+ offset.right = options.offsetRight || 0;
+ offset.bottom = options.offsetBottom || 0;
+ offset.left = options.offsetLeft || 0;
+
+ var throttledScroll = throttle(function () {
+ onScroll(options.scrollOffset);
+ }, options.throttle || 100);
+ var readyScroll = function () {
+ $(document).ready(throttledScroll);
+ };
+
+ if (!isSpying) {
+ jWindow.on('scroll', readyScroll);
+ jWindow.on('resize', readyScroll);
+ isSpying = true;
+ }
+
+ // perform a scan once, after current execution context, and after dom is ready
+ setTimeout(readyScroll, 0);
+
+
+ selector.on('scrollSpy:enter', function () {
+ visible = $.grep(visible, function (value) {
+ return value.height() != 0;
+ });
+
+ var $this = $(this);
+
+ if (visible[0]) {
+ $('a[href="#' + visible[0].attr('id') + '"]').removeClass('active');
+ if ($this.data('scrollSpy:id') < visible[0].data('scrollSpy:id')) {
+ visible.unshift($(this));
+ }
+ else {
+ visible.push($(this));
+ }
+ }
+ else {
+ visible.push($(this));
+ }
+
+
+ $('a[href="#' + visible[0].attr('id') + '"]').addClass('active');
+ });
+ selector.on('scrollSpy:exit', function () {
+ visible = $.grep(visible, function (value) {
+ return value.height() != 0;
+ });
+
+ if (visible[0]) {
+ $('a[href="#' + visible[0].attr('id') + '"]').removeClass('active');
+ var $this = $(this);
+ visible = $.grep(visible, function (value) {
+ return value.attr('id') != $this.attr('id');
+ });
+ if (visible[0]) { // Check if empty
+ $('a[href="#' + visible[0].attr('id') + '"]').addClass('active');
+ }
+ }
+ });
+
+ return selector;
+ };
+
+ /**
+ * Listen for window resize events
+ * @param {Object=} options Optional. Set { throttle: number } to change throttling. Default: 100 ms
+ * @returns {jQuery} $(window)
+ */
+ $.winSizeSpy = function (options) {
+ $.winSizeSpy = function () {
+ return jWindow;
+ }; // lock from multiple calls
+ options = options || {
+ throttle: 100
+ };
+ return jWindow.on('resize', throttle(onWinSize, options.throttle || 100));
+ };
+
+ /**
+ * Enables ScrollSpy on a collection of elements
+ * e.g. $('.scrollSpy').scrollSpy()
+ * @param {Object=} options Optional.
+ throttle : number -> scrollspy throttling. Default: 100 ms
+ offsetTop : number -> offset from top. Default: 0
+ offsetRight : number -> offset from right. Default: 0
+ offsetBottom : number -> offset from bottom. Default: 0
+ offsetLeft : number -> offset from left. Default: 0
+ * @returns {jQuery}
+ */
+ $.fn.scrollSpy = function (options) {
+ return $.scrollSpy($(this), options);
+ };
+
+})(jQuery);
+;(function ($) {
+ $(document).ready(function () {
+
+ // Function to update labels of text fields
+ Materialize.updateTextFields = function () {
+ 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';
+ $(input_selector).each(function (index, element) {
+ if ($(element).val().length > 0 || element.autofocus || $(this).attr('placeholder') !== undefined || $(element)[0].validity.badInput === true) {
+ $(this).siblings('label').addClass('active');
+ }
+ else {
+ $(this).siblings('label').removeClass('active');
+ }
+ });
+ };
+
+ // Text based inputs
+ 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';
+
+ // Add active if form auto complete
+ $(document).on('change', input_selector, function () {
+ if ($(this).val().length !== 0 || $(this).attr('placeholder') !== undefined) {
+ $(this).siblings('label').addClass('active');
+ }
+ validate_field($(this));
+ });
+
+ // Add active if input element has been pre-populated on document ready
+ $(document).ready(function () {
+ Materialize.updateTextFields();
+ });
+
+ // HTML DOM FORM RESET handling
+ $(document).on('reset', function (e) {
+ var formReset = $(e.target);
+ if (formReset.is('form')) {
+ formReset.find(input_selector).removeClass('valid').removeClass('invalid');
+ formReset.find(input_selector).each(function () {
+ if ($(this).attr('value') === '') {
+ $(this).siblings('label').removeClass('active');
+ }
+ });
+
+ // Reset select
+ formReset.find('select.initialized').each(function () {
+ var reset_text = formReset.find('option[selected]').text();
+ formReset.siblings('input.select-dropdown').val(reset_text);
+ });
+ }
+ });
+
+ // Add active when element has focus
+ $(document).on('focus', input_selector, function () {
+ $(this).siblings('label, .prefix').addClass('active');
+ });
+
+ $(document).on('blur', input_selector, function () {
+ var $inputElement = $(this);
+ var selector = ".prefix";
+
+ if ($inputElement.val().length === 0 && $inputElement[0].validity.badInput !== true && $inputElement.attr('placeholder') === undefined) {
+ selector += ", label";
+ }
+
+ $inputElement.siblings(selector).removeClass('active');
+
+ validate_field($inputElement);
+ });
+
+ window.validate_field = function (object) {
+ var hasLength = object.attr('length') !== undefined;
+ var lenAttr = parseInt(object.attr('length'));
+ var len = object.val().length;
+
+ if (object.val().length === 0 && object[0].validity.badInput === false) {
+ if (object.hasClass('validate')) {
+ object.removeClass('valid');
+ object.removeClass('invalid');
+ }
+ }
+ else {
+ if (object.hasClass('validate')) {
+ // Check for character counter attributes
+ if ((object.is(':valid') && hasLength && (len <= lenAttr)) || (object.is(':valid') && !hasLength)) {
+ object.removeClass('invalid');
+ object.addClass('valid');
+ }
+ else {
+ object.removeClass('valid');
+ object.addClass('invalid');
+ }
+ }
+ }
+ };
+
+ // Radio and Checkbox focus class
+ var radio_checkbox = 'input[type=radio], input[type=checkbox]';
+ $(document).on('keyup.radio', radio_checkbox, function (e) {
+ // TAB, check if tabbing to radio or checkbox.
+ if (e.which === 9) {
+ $(this).addClass('tabbed');
+ var $this = $(this);
+ $this.one('blur', function (e) {
+
+ $(this).removeClass('tabbed');
+ });
+ return;
+ }
+ });
+
+ // Textarea Auto Resize
+ var hiddenDiv = $('.hiddendiv').first();
+ if (!hiddenDiv.length) {
+ hiddenDiv = $('
');
+ $('body').append(hiddenDiv);
+ }
+ var text_area_selector = '.materialize-textarea';
+
+ function textareaAutoResize($textarea) {
+ // Set font properties of hiddenDiv
+
+ var fontFamily = $textarea.css('font-family');
+ var fontSize = $textarea.css('font-size');
+ var lineHeight = $textarea.css('line-height');
+
+ if (fontSize) {
+ hiddenDiv.css('font-size', fontSize);
+ }
+ if (fontFamily) {
+ hiddenDiv.css('font-family', fontFamily);
+ }
+ if (lineHeight) {
+ hiddenDiv.css('line-height', lineHeight);
+ }
+
+ if ($textarea.attr('wrap') === "off") {
+ hiddenDiv.css('overflow-wrap', "normal")
+ .css('white-space', "pre");
+ }
+
+ hiddenDiv.text($textarea.val() + '\n');
+ var content = hiddenDiv.html().replace(/\n/g, '
');
+ hiddenDiv.html(content);
+
+
+ // When textarea is hidden, width goes crazy.
+ // Approximate with half of window size
+
+ if ($textarea.is(':visible')) {
+ hiddenDiv.css('width', $textarea.width());
+ }
+ else {
+ hiddenDiv.css('width', $(window).width() / 2);
+ }
+
+ $textarea.css('height', hiddenDiv.height());
+ }
+
+ $(text_area_selector).each(function () {
+ var $textarea = $(this);
+ if ($textarea.val().length) {
+ textareaAutoResize($textarea);
+ }
+ });
+
+ $('body').on('keyup keydown autoresize', text_area_selector, function () {
+ textareaAutoResize($(this));
+ });
+
+ // File Input Path
+ $(document).on('change', '.file-field input[type="file"]', function () {
+ var file_field = $(this).closest('.file-field');
+ var path_input = file_field.find('input.file-path');
+ var files = $(this)[0].files;
+ var file_names = [];
+ for (var i = 0; i < files.length; i++) {
+ file_names.push(files[i].name);
+ }
+ path_input.val(file_names.join(", "));
+ path_input.trigger('change');
+ });
+
+ /****************
+ * Range Input *
+ ****************/
+
+ var range_type = 'input[type=range]';
+ var range_mousedown = false;
+ var left;
+
+ $(range_type).each(function () {
+ var thumb = $('
');
+ $(this).after(thumb);
+ });
+
+ var range_wrapper = '.range-field';
+ $(document).on('change', range_type, function (e) {
+ var thumb = $(this).siblings('.thumb');
+ thumb.find('.value').html($(this).val());
+ });
+
+ $(document).on('input mousedown touchstart', range_type, function (e) {
+ var thumb = $(this).siblings('.thumb');
+ var width = $(this).outerWidth();
+
+ // If thumb indicator does not exist yet, create it
+ if (thumb.length <= 0) {
+ thumb = $('
');
+ $(this).after(thumb);
+ }
+
+ // Set indicator value
+ thumb.find('.value').html($(this).val());
+
+ range_mousedown = true;
+ $(this).addClass('active');
+
+ if (!thumb.hasClass('active')) {
+ thumb.velocity({height: "30px", width: "30px", top: "-20px", marginLeft: "-15px"}, {duration: 300, easing: 'easeOutExpo'});
+ }
+
+ if (e.type !== 'input') {
+ if (e.pageX === undefined || e.pageX === null) {//mobile
+ left = e.originalEvent.touches[0].pageX - $(this).offset().left;
+ }
+ else { // desktop
+ left = e.pageX - $(this).offset().left;
+ }
+ if (left < 0) {
+ left = 0;
+ }
+ else if (left > width) {
+ left = width;
+ }
+ thumb.addClass('active').css('left', left);
+ }
+
+ thumb.find('.value').html($(this).val());
+ });
+
+ $(document).on('mouseup touchend', range_wrapper, function () {
+ range_mousedown = false;
+ $(this).removeClass('active');
+ });
+
+ $(document).on('mousemove touchmove', range_wrapper, function (e) {
+ var thumb = $(this).children('.thumb');
+ var left;
+ if (range_mousedown) {
+ if (!thumb.hasClass('active')) {
+ thumb.velocity({height: '30px', width: '30px', top: '-20px', marginLeft: '-15px'}, {duration: 300, easing: 'easeOutExpo'});
+ }
+ if (e.pageX === undefined || e.pageX === null) { //mobile
+ left = e.originalEvent.touches[0].pageX - $(this).offset().left;
+ }
+ else { // desktop
+ left = e.pageX - $(this).offset().left;
+ }
+ var width = $(this).outerWidth();
+
+ if (left < 0) {
+ left = 0;
+ }
+ else if (left > width) {
+ left = width;
+ }
+ thumb.addClass('active').css('left', left);
+ thumb.find('.value').html(thumb.siblings(range_type).val());
+ }
+ });
+
+ $(document).on('mouseout touchleave', range_wrapper, function () {
+ if (!range_mousedown) {
+
+ var thumb = $(this).children('.thumb');
+
+ if (thumb.hasClass('active')) {
+ thumb.velocity({height: '0', width: '0', top: '10px', marginLeft: '-6px'}, {duration: 100});
+ }
+ thumb.removeClass('active');
+ }
+ });
+
+ /**************************
+ * Auto complete plugin *
+ *************************/
+ $.fn.autocomplete = function (options) {
+ // Defaults
+ var defaults = {
+ data: {}
+ };
+
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+ var $input = $(this);
+ var data = options.data,
+ $inputDiv = $input.closest('.input-field'); // Div to append on
+
+ // Check if data isn't empty
+ if (!$.isEmptyObject(data)) {
+ // Create autocomplete element
+ var $autocomplete = $('
');
+
+ // Append autocomplete element
+ if ($inputDiv.length) {
+ $inputDiv.append($autocomplete); // Set ul in body
+ } else {
+ $input.after($autocomplete);
+ }
+
+ var highlight = function (string, $el) {
+ var img = $el.find('img');
+ var matchStart = $el.text().toLowerCase().indexOf("" + string.toLowerCase() + ""),
+ matchEnd = matchStart + string.length - 1,
+ beforeMatch = $el.text().slice(0, matchStart),
+ matchText = $el.text().slice(matchStart, matchEnd + 1),
+ afterMatch = $el.text().slice(matchEnd + 1);
+ $el.html("
" + beforeMatch + "" + matchText + " " + afterMatch + " ");
+ if (img.length) {
+ $el.prepend(img);
+ }
+ };
+
+ // Perform search
+ $input.on('keyup', function (e) {
+ // Capture Enter
+ if (e.which === 13) {
+ $autocomplete.find('li').first().click();
+ return;
+ }
+
+ var val = $input.val().toLowerCase();
+ $autocomplete.empty();
+
+ // Check if the input isn't empty
+ if (val !== '') {
+ for (var key in data) {
+ if (data.hasOwnProperty(key) &&
+ key.toLowerCase().indexOf(val) !== -1 &&
+ key.toLowerCase() !== val) {
+ var autocompleteOption = $('
');
+ if (!!data[key]) {
+ autocompleteOption.append('
' + key + ' ');
+ } else {
+ autocompleteOption.append('
' + key + ' ');
+ }
+ $autocomplete.append(autocompleteOption);
+
+ highlight(val, autocompleteOption);
+ }
+ }
+ }
+ });
+
+ // Set input value
+ $autocomplete.on('click', 'li', function () {
+ $input.val($(this).text().trim());
+ $input.trigger('change');
+ $autocomplete.empty();
+ });
+ }
+ });
+ };
+
+ }); // End of $(document).ready
+
+ /*******************
+ * Select Plugin *
+ ******************/
+ $.fn.material_select = function (callback) {
+ $(this).each(function () {
+ var $select = $(this);
+
+ if ($select.hasClass('browser-default')) {
+ return; // Continue to next (return false breaks out of entire loop)
+ }
+
+ var multiple = $select.attr('multiple') ? true : false,
+ lastID = $select.data('select-id'); // Tear down structure if Select needs to be rebuilt
+
+ if (lastID) {
+ $select.parent().find('span.caret').remove();
+ $select.parent().find('input').remove();
+
+ $select.unwrap();
+ $('ul#select-options-' + lastID).remove();
+ }
+
+ // If destroying the select, remove the selelct-id and reset it to it's uninitialized state.
+ if (callback === 'destroy') {
+ $select.data('select-id', null).removeClass('initialized');
+ return;
+ }
+
+ var uniqueID = Materialize.guid();
+ $select.data('select-id', uniqueID);
+ var wrapper = $('
');
+ wrapper.addClass($select.attr('class'));
+ var options = $('
'),
+ selectChildren = $select.children('option, optgroup'),
+ valuesSelected = [],
+ optionsHover = false;
+
+ var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
+
+ // Function that renders and appends the option taking into
+ // account type and possible image icon.
+ var appendOptionWithIcon = function (select, option, type) {
+ // Add disabled attr if disabled
+ var disabledClass = (option.is(':disabled')) ? 'disabled ' : '';
+ var optgroupClass = (type === 'optgroup-option') ? 'optgroup-option ' : '';
+
+ // add icons
+ var icon_url = option.data('icon');
+ var classes = option.attr('class');
+ if (!!icon_url) {
+ var classString = '';
+ if (!!classes) classString = ' class="' + classes + '"';
+
+ // Check for multiple type.
+ if (type === 'multiple') {
+ options.append($('
' + option.html() + ''));
+ } else {
+ options.append($('
' + option.html() + ' '));
+ }
+ return true;
+ }
+ var mdi = option.data('mdi');
+ var iconColor = option.data('iconColor');
+ if (!!mdi) {
+ var classString = (!!classes) ? ' class="mdi mdi-' + mdi + ' ' + classes + '"' : ' class="mdi mdi-' + mdi + '"';
+ var styleString = 'style="' + (mdi.startsWith("custom-") ? 'background-color' : 'color') + ':' + iconColor + '"';
+ // Check for multiple type.
+ if (type === 'multiple') {
+ options.append($('
' + option.html() + ''));
+ } else {
+ options.append($('
' + option.html() + ''));
+ }
+ return true;
+ }
+
+ // Check for multiple type.
+ if
+ (type === 'multiple') {
+ options.append($('
' + option.html() + ''));
+ }
+ else {
+ options.append($('
' + option.html() + ' '));
+ }
+ };
+
+ /* Create dropdown structure. */
+ if (selectChildren.length) {
+ selectChildren.each(function () {
+ if ($(this).is('option')) {
+ // Direct descendant option.
+ if (multiple) {
+ appendOptionWithIcon($select, $(this), 'multiple');
+
+ } else {
+ appendOptionWithIcon($select, $(this));
+ }
+ } else if ($(this).is('optgroup')) {
+ // Optgroup.
+ var selectOptions = $(this).children('option');
+ options.append($('
' + $(this).attr('label') + ' '));
+
+ selectOptions.each(function () {
+ appendOptionWithIcon($select, $(this), 'optgroup-option');
+ });
+ }
+ });
+ }
+
+ options.find('li:not(.optgroup)').each(function (i) {
+ $(this).click(function (e) {
+ // Check if option element is disabled
+ if (!$(this).hasClass('disabled') && !$(this).hasClass('optgroup')) {
+ var selected = true;
+
+ if (multiple) {
+ $('input[type="checkbox"]', this).prop('checked', function (i, v) {
+ return !v;
+ });
+ selected = toggleEntryFromArray(valuesSelected, $(this).index(), $select);
+ $newSelect.trigger('focus');
+ } else {
+ options.find('li').removeClass('active');
+ $(this).toggleClass('active');
+ $newSelect.val($(this).text());
+ }
+
+ activateOption(options, $(this));
+ $select.find('option').eq(i).prop('selected', selected);
+ // Trigger onchange() event
+ $select.trigger('change');
+ if (typeof callback !== 'undefined') callback();
+ }
+
+ e.stopPropagation();
+ });
+ });
+
+ // Wrap Elements
+ $select.wrap(wrapper);
+ // Add Select Display Element
+ var dropdownIcon = $('
▼ ');
+ if ($select.is(':disabled'))
+ dropdownIcon.addClass('disabled');
+
+ // escape double quotes
+ var sanitizedLabelHtml = label.replace(/"/g, '"');
+
+ var $newSelect = $('
');
+ $select.before($newSelect);
+ $newSelect.before(dropdownIcon);
+
+ $newSelect.after(options);
+ // Check if section element is disabled
+ if (!$select.is(':disabled')) {
+ $newSelect.dropdown({'hover': false, 'closeOnClick': false});
+ }
+
+ // Copy tabindex
+ if ($select.attr('tabindex')) {
+ $($newSelect[0]).attr('tabindex', $select.attr('tabindex'));
+ }
+
+ $select.addClass('initialized');
+
+ $newSelect.on({
+ 'focus': function () {
+ if ($('ul.select-dropdown').not(options[0]).is(':visible')) {
+ $('input.select-dropdown').trigger('close');
+ }
+ if (!options.is(':visible')) {
+ $(this).trigger('open', ['focus']);
+ var label = $(this).val();
+ var selectedOption = options.find('li').filter(function () {
+ return $(this).text().toLowerCase() === label.toLowerCase();
+ })[0];
+ activateOption(options, selectedOption);
+ }
+ },
+ 'click': function (e) {
+ e.stopPropagation();
+ }
+ });
+
+ $newSelect.on('blur', function () {
+ if (!multiple) {
+ $(this).trigger('close');
+ }
+ options.find('li.selected').removeClass('selected');
+ });
+
+ options.hover(function () {
+ optionsHover = true;
+ }, function () {
+ optionsHover = false;
+ });
+
+ $(window).on({
+ 'click': function () {
+ multiple && (optionsHover || $newSelect.trigger('close'));
+ }
+ });
+
+ // Add initial multiple selections.
+ if (multiple) {
+ $select.find("option:selected:not(:disabled)").each(function () {
+ var index = $(this).index();
+
+ toggleEntryFromArray(valuesSelected, index, $select);
+ options.find("li").eq(index).find(":checkbox").prop("checked", true);
+ });
+ }
+
+ // Make option as selected and scroll to selected position
+ var activateOption = function (collection, newOption) {
+ if (newOption) {
+ collection.find('li.selected').removeClass('selected');
+ var option = $(newOption);
+ option.addClass('selected');
+ options.scrollTo(option);
+ }
+ };
+
+ // Allow user to search by typing
+ // this array is cleared after 1 second
+ var filterQuery = [],
+ onKeyDown = function (e) {
+ // TAB - switch to another input
+ if (e.which == 9) {
+ $newSelect.trigger('close');
+ return;
+ }
+
+ // ARROW DOWN WHEN SELECT IS CLOSED - open select options
+ if (e.which == 40 && !options.is(':visible')) {
+ $newSelect.trigger('open');
+ return;
+ }
+
+ // ENTER WHEN SELECT IS CLOSED - submit form
+ if (e.which == 13 && !options.is(':visible')) {
+ return;
+ }
+
+ e.preventDefault();
+
+ // CASE WHEN USER TYPE LETTERS
+ var letter = String.fromCharCode(e.which).toLowerCase(),
+ nonLetters = [9, 13, 27, 38, 40];
+ if (letter && (nonLetters.indexOf(e.which) === -1)) {
+ filterQuery.push(letter);
+
+ var string = filterQuery.join(''),
+ newOption = options.find('li').filter(function () {
+ return $(this).text().toLowerCase().indexOf(string) === 0;
+ })[0];
+
+ if (newOption) {
+ activateOption(options, newOption);
+ }
+ }
+
+ // ENTER - select option and close when select options are opened
+ if (e.which == 13) {
+ var activeOption = options.find('li.selected:not(.disabled)')[0];
+ if (activeOption) {
+ $(activeOption).trigger('click');
+ if (!multiple) {
+ $newSelect.trigger('close');
+ }
+ }
+ }
+
+ // ARROW DOWN - move to next not disabled option
+ if (e.which == 40) {
+ if (options.find('li.selected').length) {
+ newOption = options.find('li.selected').next('li:not(.disabled)')[0];
+ } else {
+ newOption = options.find('li:not(.disabled)')[0];
+ }
+ activateOption(options, newOption);
+ }
+
+ // ESC - close options
+ if (e.which == 27) {
+ $newSelect.trigger('close');
+ }
+
+ // ARROW UP - move to previous not disabled option
+ if (e.which == 38) {
+ newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
+ if (newOption)
+ activateOption(options, newOption);
+ }
+
+ // Automaticaly clean filter query so user can search again by starting letters
+ setTimeout(function () {
+ filterQuery = [];
+ }, 1000);
+ };
+
+ $newSelect.on('keydown', onKeyDown);
+ });
+
+ function toggleEntryFromArray(entriesArray, entryIndex, select) {
+ var index = entriesArray.indexOf(entryIndex),
+ notAdded = index === -1;
+
+ if (notAdded) {
+ entriesArray.push(entryIndex);
+ } else {
+ entriesArray.splice(index, 1);
+ }
+
+ select.siblings('ul.dropdown-content').find('li').eq(entryIndex).toggleClass('active');
+
+ // use notAdded instead of true (to detect if the option is selected or not)
+ select.find('option').eq(entryIndex).prop('selected', notAdded);
+ setValueToInput(entriesArray, select);
+
+ return notAdded;
+ }
+
+ function setValueToInput(entriesArray, select) {
+ var value = '';
+
+ for (var i = 0, count = entriesArray.length; i < count; i++) {
+ var text = select.find('option').eq(entriesArray[i]).text();
+
+ i === 0 ? value += text : value += ', ' + text;
+ }
+
+ if (value === '') {
+ value = select.find('option:disabled').eq(0).text();
+ }
+
+ select.siblings('input.select-dropdown').val(value);
+ }
+ };
+
+}(jQuery));
+;(function ($) {
+
+ var methods = {
+
+ init: function (options) {
+ var defaults = {
+ indicators: true,
+ height: 400,
+ transition: 500,
+ interval: 6000
+ };
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+
+ // For each slider, we want to keep track of
+ // which slide is active and its associated content
+ var $this = $(this);
+ var $slider = $this.find('ul.slides').first();
+ var $slides = $slider.find('> li');
+ var $active_index = $slider.find('.active').index();
+ var $active, $indicators, $interval;
+ if ($active_index != -1) {
+ $active = $slides.eq($active_index);
+ }
+
+ // Transitions the caption depending on alignment
+ function captionTransition(caption, duration) {
+ if (caption.hasClass("center-align")) {
+ caption.velocity({opacity: 0, translateY: -100}, {duration: duration, queue: false});
+ }
+ else if (caption.hasClass("right-align")) {
+ caption.velocity({opacity: 0, translateX: 100}, {duration: duration, queue: false});
+ }
+ else if (caption.hasClass("left-align")) {
+ caption.velocity({opacity: 0, translateX: -100}, {duration: duration, queue: false});
+ }
+ }
+
+ // This function will transition the slide to any index of the next slide
+ function moveToSlide(index) {
+ // Wrap around indices.
+ if (index >= $slides.length) index = 0;
+ else if (index < 0) index = $slides.length - 1;
+
+ $active_index = $slider.find('.active').index();
+
+ // Only do if index changes
+ if ($active_index != index) {
+ $active = $slides.eq($active_index);
+ $caption = $active.find('.caption');
+
+ $active.removeClass('active');
+ $active.velocity({opacity: 0}, {
+ duration: options.transition, queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ $slides.not('.active').velocity({opacity: 0, translateX: 0, translateY: 0}, {duration: 0, queue: false});
+ }
+ });
+ captionTransition($caption, options.transition);
+
+
+ // Update indicators
+ if (options.indicators) {
+ $indicators.eq($active_index).removeClass('active');
+ }
+
+ $slides.eq(index).velocity({opacity: 1}, {duration: options.transition, queue: false, easing: 'easeOutQuad'});
+ $slides.eq(index).find('.caption').velocity({opacity: 1, translateX: 0, translateY: 0}, {
+ duration: options.transition,
+ delay: options.transition,
+ queue: false,
+ easing: 'easeOutQuad'
+ });
+ $slides.eq(index).addClass('active');
+
+
+ // Update indicators
+ if (options.indicators) {
+ $indicators.eq(index).addClass('active');
+ }
+ }
+ }
+
+ // Set height of slider
+ // If fullscreen, do nothing
+ if (!$this.hasClass('fullscreen')) {
+ if (options.indicators) {
+ // Add height if indicators are present
+ $this.height(options.height + 40);
+ }
+ else {
+ $this.height(options.height);
+ }
+ $slider.height(options.height);
+ }
+
+
+ // Set initial positions of captions
+ $slides.find('.caption').each(function () {
+ captionTransition($(this), 0);
+ });
+
+ // Move img src into background-image
+ $slides.find('img').each(function () {
+ var placeholderBase64 = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
+ if ($(this).attr('src') !== placeholderBase64) {
+ $(this).css('background-image', 'url(' + $(this).attr('src') + ')');
+ $(this).attr('src', placeholderBase64);
+ }
+ });
+
+ // dynamically add indicators
+ if (options.indicators) {
+ $indicators = $('
');
+ $slides.each(function (index) {
+ var $indicator = $('
');
+
+ // Handle clicks on indicators
+ $indicator.click(function () {
+ var $parent = $slider.parent();
+ var curr_index = $parent.find($(this)).index();
+ moveToSlide(curr_index);
+
+ // reset interval
+ clearInterval($interval);
+ $interval = setInterval(
+ function () {
+ $active_index = $slider.find('.active').index();
+ if ($slides.length == $active_index + 1) $active_index = 0; // loop to start
+ else $active_index += 1;
+
+ moveToSlide($active_index);
+
+ }, options.transition + options.interval
+ );
+ });
+ $indicators.append($indicator);
+ });
+ $this.append($indicators);
+ $indicators = $this.find('ul.indicators').find('li.indicator-item');
+ }
+
+ if ($active) {
+ $active.show();
+ }
+ else {
+ $slides.first().addClass('active').velocity({opacity: 1}, {duration: options.transition, queue: false, easing: 'easeOutQuad'});
+
+ $active_index = 0;
+ $active = $slides.eq($active_index);
+
+ // Update indicators
+ if (options.indicators) {
+ $indicators.eq($active_index).addClass('active');
+ }
+ }
+
+ // Adjust height to current slide
+ $active.find('img').each(function () {
+ $active.find('.caption').velocity({opacity: 1, translateX: 0, translateY: 0}, {
+ duration: options.transition,
+ queue: false,
+ easing: 'easeOutQuad'
+ });
+ });
+
+ // auto scroll
+ $interval = setInterval(
+ function () {
+ $active_index = $slider.find('.active').index();
+ moveToSlide($active_index + 1);
+
+ }, options.transition + options.interval
+ );
+
+
+ // HammerJS, Swipe navigation
+
+ // Touch Event
+ var panning = false;
+ var swipeLeft = false;
+ var swipeRight = false;
+
+ $this.hammer({
+ prevent_default: false
+ }).bind('pan', function (e) {
+ if (e.gesture.pointerType === "touch") {
+
+ // reset interval
+ clearInterval($interval);
+
+ var direction = e.gesture.direction;
+ var x = e.gesture.deltaX;
+ var velocityX = e.gesture.velocityX;
+
+ $curr_slide = $slider.find('.active');
+ $curr_slide.velocity({
+ translateX: x
+ }, {duration: 50, queue: false, easing: 'easeOutQuad'});
+
+ // Swipe Left
+ if (direction === 4 && (x > ($this.innerWidth() / 2) || velocityX < -0.65)) {
+ swipeRight = true;
+ }
+ // Swipe Right
+ else if (direction === 2 && (x < (-1 * $this.innerWidth() / 2) || velocityX > 0.65)) {
+ swipeLeft = true;
+ }
+
+ // Make Slide Behind active slide visible
+ var next_slide;
+ if (swipeLeft) {
+ next_slide = $curr_slide.next();
+ if (next_slide.length === 0) {
+ next_slide = $slides.first();
+ }
+ next_slide.velocity({
+ opacity: 1
+ }, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ }
+ if (swipeRight) {
+ next_slide = $curr_slide.prev();
+ if (next_slide.length === 0) {
+ next_slide = $slides.last();
+ }
+ next_slide.velocity({
+ opacity: 1
+ }, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ }
+
+
+ }
+
+ }).bind('panend', function (e) {
+ if (e.gesture.pointerType === "touch") {
+
+ $curr_slide = $slider.find('.active');
+ panning = false;
+ curr_index = $slider.find('.active').index();
+
+ if (!swipeRight && !swipeLeft || $slides.length <= 1) {
+ // Return to original spot
+ $curr_slide.velocity({
+ translateX: 0
+ }, {duration: 300, queue: false, easing: 'easeOutQuad'});
+ }
+ else if (swipeLeft) {
+ moveToSlide(curr_index + 1);
+ $curr_slide.velocity({translateX: -1 * $this.innerWidth()}, {
+ duration: 300, queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ $curr_slide.velocity({opacity: 0, translateX: 0}, {duration: 0, queue: false});
+ }
+ });
+ }
+ else if (swipeRight) {
+ moveToSlide(curr_index - 1);
+ $curr_slide.velocity({translateX: $this.innerWidth()}, {
+ duration: 300, queue: false, easing: 'easeOutQuad',
+ complete: function () {
+ $curr_slide.velocity({opacity: 0, translateX: 0}, {duration: 0, queue: false});
+ }
+ });
+ }
+ swipeLeft = false;
+ swipeRight = false;
+
+ // Restart interval
+ clearInterval($interval);
+ $interval = setInterval(
+ function () {
+ $active_index = $slider.find('.active').index();
+ if ($slides.length == $active_index + 1) $active_index = 0; // loop to start
+ else $active_index += 1;
+
+ moveToSlide($active_index);
+
+ }, options.transition + options.interval
+ );
+ }
+ });
+
+ $this.on('sliderPause', function () {
+ clearInterval($interval);
+ });
+
+ $this.on('sliderStart', function () {
+ clearInterval($interval);
+ $interval = setInterval(
+ function () {
+ $active_index = $slider.find('.active').index();
+ if ($slides.length == $active_index + 1) $active_index = 0; // loop to start
+ else $active_index += 1;
+
+ moveToSlide($active_index);
+
+ }, options.transition + options.interval
+ );
+ });
+
+ $this.on('sliderNext', function () {
+ $active_index = $slider.find('.active').index();
+ moveToSlide($active_index + 1);
+ });
+
+ $this.on('sliderPrev', function () {
+ $active_index = $slider.find('.active').index();
+ moveToSlide($active_index - 1);
+ });
+
+ });
+
+
+ },
+ pause: function () {
+ $(this).trigger('sliderPause');
+ },
+ start: function () {
+ $(this).trigger('sliderStart');
+ },
+ next: function () {
+ $(this).trigger('sliderNext');
+ },
+ prev: function () {
+ $(this).trigger('sliderPrev');
+ }
+ };
+
+
+ $.fn.slider = function (methodOrOptions) {
+ if (methods[methodOrOptions]) {
+ return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
+ } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
+ // Default to "init"
+ return methods.init.apply(this, arguments);
+ } else {
+ $.error('Method ' + methodOrOptions + ' does not exist on jQuery.tooltip');
+ }
+ }; // Plugin end
+}(jQuery));
+;(function ($) {
+ $(document).ready(function () {
+
+ $(document).on('click.card', '.card', function (e) {
+ if ($(this).find('> .card-reveal').length) {
+ if ($(e.target).is($('.card-reveal .card-title')) || $(e.target).is($('.card-reveal .card-title i'))) {
+ // Make Reveal animate down and display none
+ $(this).find('.card-reveal').velocity(
+ {translateY: 0}, {
+ duration: 225,
+ queue: false,
+ easing: 'easeInOutQuad',
+ complete: function () {
+ $(this).css({display: 'none'});
+ }
+ }
+ );
+ }
+ else if ($(e.target).is($('.card .activator')) ||
+ $(e.target).is($('.card .activator i'))) {
+ $(e.target).closest('.card').css('overflow', 'hidden');
+ $(this).find('.card-reveal').css({display: 'block'}).velocity("stop", false).velocity({translateY: '-100%'}, {
+ duration: 300,
+ queue: false,
+ easing: 'easeInOutQuad'
+ });
+ }
+ }
+ });
+
+ });
+}(jQuery));
+;(function ($) {
+ var chipsHandleEvents = false;
+ var materialChipsDefaults = {
+ data: [],
+ placeholder: '',
+ secondaryPlaceholder: '',
+ };
+
+ $(document).ready(function () {
+ // Handle removal of static chips.
+ $(document).on('click', '.chip .close', function (e) {
+ var $chips = $(this).closest('.chips');
+ if ($chips.attr('data-initialized')) {
+ return;
+ }
+ $(this).closest('.chip').remove();
+ });
+ });
+
+ $.fn.material_chip = function (options) {
+ var self = this;
+ this.$el = $(this);
+ this.$document = $(document);
+ this.SELS = {
+ CHIPS: '.chips',
+ CHIP: '.chip',
+ INPUT: 'input',
+ DELETE: '.material-icons',
+ SELECTED_CHIP: '.selected',
+ };
+
+ if ('data' === options) {
+ return this.$el.data('chips');
+ }
+
+ var curr_options = $.extend({}, materialChipsDefaults, options);
+
+
+ // Initialize
+ this.init = function () {
+ var i = 0;
+ var chips;
+ self.$el.each(function () {
+ var $chips = $(this);
+ var chipId = Materialize.guid();
+
+ if (!curr_options.data || !(curr_options.data instanceof Array)) {
+ curr_options.data = [];
+ }
+ $chips.data('chips', curr_options.data);
+ $chips.attr('data-index', i);
+ $chips.attr('data-initialized', true);
+
+ if (!$chips.hasClass(self.SELS.CHIPS)) {
+ $chips.addClass('chips');
+ }
+
+ self.chips($chips, chipId);
+ i++;
+ });
+ };
+
+ this.handleEvents = function () {
+ var SELS = self.SELS;
+
+ self.$document.off('click.chips-focus', SELS.CHIPS).on('click.chips-focus', SELS.CHIPS, function (e) {
+ $(e.target).find(SELS.INPUT).focus();
+ });
+
+ self.$document.off('click.chips-select', SELS.CHIP).on('click.chips-select', SELS.CHIP, function (e) {
+ $(SELS.CHIP).removeClass('selected');
+ $(this).toggleClass('selected');
+ });
+
+ self.$document.off('keydown.chips').on('keydown.chips', function (e) {
+ if ($(e.target).is('input, textarea')) {
+ return;
+ }
+
+ // delete
+ var $chip = self.$document.find(SELS.CHIP + SELS.SELECTED_CHIP);
+ var $chips = $chip.closest(SELS.CHIPS);
+ var length = $chip.siblings(SELS.CHIP).length;
+ var index;
+
+ if (!$chip.length) {
+ return;
+ }
+
+ if (e.which === 8 || e.which === 46) {
+ e.preventDefault();
+
+ index = $chip.index();
+ self.deleteChip(index, $chips);
+
+ var selectIndex = null;
+ if ((index + 1) < length) {
+ selectIndex = index;
+ } else if (index === length || (index + 1) === length) {
+ selectIndex = length - 1;
+ }
+
+ if (selectIndex < 0) selectIndex = null;
+
+ if (null !== selectIndex) {
+ self.selectChip(selectIndex, $chips);
+ }
+ if (!length) $chips.find('input').focus();
+
+ // left
+ } else if (e.which === 37) {
+ index = $chip.index() - 1;
+ if (index < 0) {
+ return;
+ }
+ $(SELS.CHIP).removeClass('selected');
+ self.selectChip(index, $chips);
+
+ // right
+ } else if (e.which === 39) {
+ index = $chip.index() + 1;
+ $(SELS.CHIP).removeClass('selected');
+ if (index > length) {
+ $chips.find('input').focus();
+ return;
+ }
+ self.selectChip(index, $chips);
+ }
+ });
+
+ self.$document.off('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT, function (e) {
+ var $currChips = $(e.target).closest(SELS.CHIPS);
+ $currChips.addClass('focus');
+ $currChips.siblings('label, .prefix').addClass('active');
+ $(SELS.CHIP).removeClass('selected');
+ });
+
+ self.$document.off('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT, function (e) {
+ var $currChips = $(e.target).closest(SELS.CHIPS);
+ $currChips.removeClass('focus');
+
+ // Remove active if empty
+ if (!$currChips.data('chips').length) {
+ $currChips.siblings('label').removeClass('active');
+ }
+ $currChips.siblings('.prefix').removeClass('active');
+ });
+
+ self.$document.off('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT).on('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT, function (e) {
+ var $target = $(e.target);
+ var $chips = $target.closest(SELS.CHIPS);
+ var chipsLength = $chips.children(SELS.CHIP).length;
+
+ // enter
+ if (13 === e.which) {
+ e.preventDefault();
+ self.addChip({tag: $target.val()}, $chips);
+ $target.val('');
+ return;
+ }
+
+ // delete or left
+ if ((8 === e.keyCode || 37 === e.keyCode) && '' === $target.val() && chipsLength) {
+ self.selectChip(chipsLength - 1, $chips);
+ $target.blur();
+ return;
+ }
+ });
+
+ // Click on delete icon in chip.
+ self.$document.off('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE).on('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE, function (e) {
+ var $target = $(e.target);
+ var $chips = $target.closest(SELS.CHIPS);
+ var $chip = $target.closest(SELS.CHIP);
+ e.stopPropagation();
+ self.deleteChip($chip.index(), $chips);
+ $chips.find('input').focus();
+ });
+ };
+
+ this.chips = function ($chips, chipId) {
+ var html = '';
+ $chips.data('chips').forEach(function (elem) {
+ html += self.renderChip(elem);
+ });
+ html += '
';
+ $chips.html(html);
+ self.setPlaceholder($chips);
+
+ // Set for attribute for label
+ var label = $chips.next('label');
+ if (label.length) {
+ label.attr('for', chipId);
+
+ if ($chips.data('chips').length) {
+ label.addClass('active');
+ }
+ }
+ };
+
+ this.renderChip = function (elem) {
+ if (!elem.tag) return;
+
+ var html = '
' + elem.tag;
+ if (elem.image) {
+ html += '
';
+ }
+ html += '
close ';
+ html += '
';
+ return html;
+ };
+
+ this.setPlaceholder = function ($chips) {
+ if ($chips.data('chips').length && curr_options.placeholder) {
+ $chips.find('input').prop('placeholder', curr_options.placeholder);
+
+ } else if (!$chips.data('chips').length && curr_options.secondaryPlaceholder) {
+ $chips.find('input').prop('placeholder', curr_options.secondaryPlaceholder);
+ }
+ };
+
+ this.isValid = function ($chips, elem) {
+ var chips = $chips.data('chips');
+ var exists = false;
+ for (var i = 0; i < chips.length; i++) {
+ if (chips[i].tag === elem.tag) {
+ exists = true;
+ return;
+ }
+ }
+ return '' !== elem.tag && !exists;
+ };
+
+ this.addChip = function (elem, $chips) {
+ if (!self.isValid($chips, elem)) {
+ return;
+ }
+ var chipHtml = self.renderChip(elem);
+ var newData = [];
+ var oldData = $chips.data('chips');
+ for (var i = 0; i < oldData.length; i++) {
+ newData.push(oldData[i]);
+ }
+ newData.push(elem);
+
+ $chips.data('chips', newData);
+ $(chipHtml).insertBefore($chips.find('input'));
+ $chips.trigger('chip.add', elem);
+ self.setPlaceholder($chips);
+ };
+
+ this.deleteChip = function (chipIndex, $chips) {
+ var chip = $chips.data('chips')[chipIndex];
+ $chips.find('.chip').eq(chipIndex).remove();
+
+ var newData = [];
+ var oldData = $chips.data('chips');
+ for (var i = 0; i < oldData.length; i++) {
+ if (i !== chipIndex) {
+ newData.push(oldData[i]);
+ }
+ }
+
+ $chips.data('chips', newData);
+ $chips.trigger('chip.delete', chip);
+ self.setPlaceholder($chips);
+ };
+
+ this.selectChip = function (chipIndex, $chips) {
+ var $chip = $chips.find('.chip').eq(chipIndex);
+ if ($chip && false === $chip.hasClass('selected')) {
+ $chip.addClass('selected');
+ $chips.trigger('chip.select', $chips.data('chips')[chipIndex]);
+ }
+ };
+
+ this.getChipsElement = function (index, $chips) {
+ return $chips.eq(index);
+ };
+
+ // init
+ this.init();
+
+ if (!chipsHandleEvents) {
+ this.handleEvents();
+ chipsHandleEvents = true;
+ }
+ };
+}(jQuery));
+;(function ($) {
+ $.fn.pushpin = function (options) {
+ // Defaults
+ var defaults = {
+ top: 0,
+ bottom: Infinity,
+ offset: 0
+ };
+
+ // Remove pushpin event and classes
+ if (options === "remove") {
+ this.each(function () {
+ if (id = $(this).data('pushpin-id')) {
+ $(window).off('scroll.' + id);
+ $(this).removeData('pushpin-id').removeClass('pin-top pinned pin-bottom').removeAttr('style');
+ }
+ });
+ return false;
+ }
+
+ options = $.extend(defaults, options);
+
+
+ $index = 0;
+ return this.each(function () {
+ var $uniqueId = Materialize.guid(),
+ $this = $(this),
+ $original_offset = $(this).offset().top;
+
+ function removePinClasses(object) {
+ object.removeClass('pin-top');
+ object.removeClass('pinned');
+ object.removeClass('pin-bottom');
+ }
+
+ function updateElements(objects, scrolled) {
+ objects.each(function () {
+ // Add position fixed (because its between top and bottom)
+ if (options.top <= scrolled && options.bottom >= scrolled && !$(this).hasClass('pinned')) {
+ removePinClasses($(this));
+ $(this).css('top', options.offset);
+ $(this).addClass('pinned');
+ }
+
+ // Add pin-top (when scrolled position is above top)
+ if (scrolled < options.top && !$(this).hasClass('pin-top')) {
+ removePinClasses($(this));
+ $(this).css('top', 0);
+ $(this).addClass('pin-top');
+ }
+
+ // Add pin-bottom (when scrolled position is below bottom)
+ if (scrolled > options.bottom && !$(this).hasClass('pin-bottom')) {
+ removePinClasses($(this));
+ $(this).addClass('pin-bottom');
+ $(this).css('top', options.bottom - $original_offset);
+ }
+ });
+ }
+
+ $(this).data('pushpin-id', $uniqueId);
+ updateElements($this, $(window).scrollTop());
+ $(window).on('scroll.' + $uniqueId, function () {
+ var $scrolled = $(window).scrollTop() + options.offset;
+ updateElements($this, $scrolled);
+ });
+
+ });
+
+ };
+}(jQuery));
+;(function ($) {
+ $(document).ready(function () {
+
+ // jQuery reverse
+ $.fn.reverse = [].reverse;
+
+ // Hover behaviour: make sure this doesn't work on .click-to-toggle FABs!
+ $(document).on('mouseenter.fixedActionBtn', '.fixed-action-btn:not(.click-to-toggle):not(.toolbar)', function (e) {
+ var $this = $(this);
+ openFABMenu($this);
+ });
+ $(document).on('mouseleave.fixedActionBtn', '.fixed-action-btn:not(.click-to-toggle):not(.toolbar)', function (e) {
+ var $this = $(this);
+ closeFABMenu($this);
+ });
+
+ // Toggle-on-click behaviour.
+ $(document).on('click.fabClickToggle', '.fixed-action-btn.click-to-toggle > a', function (e) {
+ var $this = $(this);
+ var $menu = $this.parent();
+ if ($menu.hasClass('active')) {
+ closeFABMenu($menu);
+ } else {
+ openFABMenu($menu);
+ }
+ });
+
+ // Toolbar transition behaviour.
+ $(document).on('click.fabToolbar', '.fixed-action-btn.toolbar > a', function (e) {
+ var $this = $(this);
+ var $menu = $this.parent();
+ FABtoToolbar($menu);
+ });
+
+ });
+
+ $.fn.extend({
+ openFAB: function () {
+ openFABMenu($(this));
+ },
+ closeFAB: function () {
+ closeFABMenu($(this));
+ },
+ openToolbar: function () {
+ FABtoToolbar($(this));
+ },
+ closeToolbar: function () {
+ toolbarToFAB($(this));
+ }
+ });
+
+
+ var openFABMenu = function (btn) {
+ var $this = btn;
+ if ($this.hasClass('active') === false) {
+
+ // Get direction option
+ var horizontal = $this.hasClass('horizontal');
+ var offsetY, offsetX;
+
+ if (horizontal === true) {
+ offsetX = 40;
+ } else {
+ offsetY = 40;
+ }
+
+ $this.addClass('active');
+ $this.find('ul .btn-floating').velocity(
+ {scaleY: ".4", scaleX: ".4", translateY: offsetY + 'px', translateX: offsetX + 'px'},
+ {duration: 0});
+
+ var time = 0;
+ $this.find('ul .btn-floating').reverse().each(function () {
+ $(this).velocity(
+ {opacity: "1", scaleX: "1", scaleY: "1", translateY: "0", translateX: '0'},
+ {duration: 80, delay: time});
+ time += 40;
+ });
+ }
+ };
+
+ var closeFABMenu = function (btn) {
+ var $this = btn;
+ // Get direction option
+ var horizontal = $this.hasClass('horizontal');
+ var offsetY, offsetX;
+
+ if (horizontal === true) {
+ offsetX = 40;
+ } else {
+ offsetY = 40;
+ }
+
+ $this.removeClass('active');
+ var time = 0;
+ $this.find('ul .btn-floating').velocity("stop", true);
+ $this.find('ul .btn-floating').velocity(
+ {opacity: "0", scaleX: ".4", scaleY: ".4", translateY: offsetY + 'px', translateX: offsetX + 'px'},
+ {duration: 80}
+ );
+ };
+
+
+ /**
+ * Transform FAB into toolbar
+ * @param {Object} object jQuery object
+ */
+ var FABtoToolbar = function (btn) {
+ if (btn.attr('data-open') === "true") {
+ return;
+ }
+
+ var offsetX, offsetY, scaleFactor;
+ var windowWidth = window.innerWidth;
+ var windowHeight = window.innerHeight;
+ var btnRect = btn[0].getBoundingClientRect();
+ var anchor = btn.find('> a').first();
+ var menu = btn.find('> ul').first();
+ var backdrop = $('
');
+ var fabColor = anchor.css('background-color');
+ anchor.append(backdrop);
+
+ offsetX = btnRect.left - (windowWidth / 2) + (btnRect.width / 2);
+ offsetY = windowHeight - btnRect.bottom;
+ scaleFactor = windowWidth / backdrop.width();
+ btn.attr('data-origin-bottom', btnRect.bottom);
+ btn.attr('data-origin-left', btnRect.left);
+ btn.attr('data-origin-width', btnRect.width);
+
+ // Set initial state
+ btn.addClass('active');
+ btn.attr('data-open', true);
+ btn.css({
+ 'text-align': 'center',
+ width: '100%',
+ bottom: 0,
+ left: 0,
+ transform: 'translateX(' + offsetX + 'px)',
+ transition: 'none'
+ });
+ anchor.css({
+ transform: 'translateY(' + -offsetY + 'px)',
+ transition: 'none'
+ });
+ backdrop.css({
+ 'background-color': fabColor
+ });
+
+
+ setTimeout(function () {
+ btn.css({
+ transform: '',
+ transition: 'transform .2s cubic-bezier(0.550, 0.085, 0.680, 0.530), background-color 0s linear .2s'
+ });
+ anchor.css({
+ overflow: 'visible',
+ transform: '',
+ transition: 'transform .2s'
+ });
+
+ setTimeout(function () {
+ btn.css({
+ overflow: 'hidden',
+ 'background-color': fabColor
+ });
+ backdrop.css({
+ transform: 'scale(' + scaleFactor + ')',
+ transition: 'transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)'
+ });
+ menu.find('> li > a').css({
+ opacity: 1
+ });
+
+ // Scroll to close.
+ $(window).on('scroll.fabToolbarClose', function () {
+ toolbarToFAB(btn);
+ $(window).off('scroll.fabToolbarClose');
+ $(document).off('click.fabToolbarClose');
+ });
+
+ $(document).on('click.fabToolbarClose', function (e) {
+ if (!$(e.target).closest(menu).length) {
+ toolbarToFAB(btn);
+ $(window).off('scroll.fabToolbarClose');
+ $(document).off('click.fabToolbarClose');
+ }
+ });
+ }, 100);
+ }, 0);
+ };
+
+ /**
+ * Transform toolbar back into FAB
+ * @param {Object} object jQuery object
+ */
+ var toolbarToFAB = function (btn) {
+ if (btn.attr('data-open') !== "true") {
+ return;
+ }
+
+ var offsetX, offsetY, scaleFactor;
+ var windowWidth = window.innerWidth;
+ var windowHeight = window.innerHeight;
+ var btnWidth = btn.attr('data-origin-width');
+ var btnBottom = btn.attr('data-origin-bottom');
+ var btnLeft = btn.attr('data-origin-left');
+ var anchor = btn.find('> .btn-floating').first();
+ var menu = btn.find('> ul').first();
+ var backdrop = btn.find('.fab-backdrop');
+ var fabColor = anchor.css('background-color');
+
+ offsetX = btnLeft - (windowWidth / 2) + (btnWidth / 2);
+ offsetY = windowHeight - btnBottom;
+ scaleFactor = windowWidth / backdrop.width();
+
+
+ // Hide backdrop
+ btn.removeClass('active');
+ btn.attr('data-open', false);
+ btn.css({
+ 'background-color': 'transparent',
+ transition: 'none'
+ });
+ anchor.css({
+ transition: 'none'
+ });
+ backdrop.css({
+ transform: 'scale(0)',
+ 'background-color': fabColor
+ });
+ menu.find('> li > a').css({
+ opacity: ''
+ });
+
+ setTimeout(function () {
+ backdrop.remove();
+
+ // Set initial state.
+ btn.css({
+ 'text-align': '',
+ width: '',
+ bottom: '',
+ left: '',
+ overflow: '',
+ 'background-color': '',
+ transform: 'translate3d(' + -offsetX + 'px,0,0)'
+ });
+ anchor.css({
+ overflow: '',
+ transform: 'translate3d(0,' + offsetY + 'px,0)'
+ });
+
+ setTimeout(function () {
+ btn.css({
+ transform: 'translate3d(0,0,0)',
+ transition: 'transform .2s'
+ });
+ anchor.css({
+ transform: 'translate3d(0,0,0)',
+ transition: 'transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)'
+ });
+ }, 20);
+ }, 200);
+ };
+
+
+}(jQuery));
+;(function ($) {
+ // Image transition function
+ Materialize.fadeInImage = function (selectorOrEl) {
+ var element;
+ if (typeof(selectorOrEl) === 'string') {
+ element = $(selectorOrEl);
+ } else if (typeof(selectorOrEl) === 'object') {
+ element = selectorOrEl;
+ } else {
+ return;
+ }
+ element.css({opacity: 0});
+ $(element).velocity({opacity: 1}, {
+ duration: 650,
+ queue: false,
+ easing: 'easeOutSine'
+ });
+ $(element).velocity({opacity: 1}, {
+ duration: 1300,
+ queue: false,
+ easing: 'swing',
+ step: function (now, fx) {
+ fx.start = 100;
+ var grayscale_setting = now / 100;
+ var brightness_setting = 150 - (100 - now) / 1.75;
+
+ if (brightness_setting < 100) {
+ brightness_setting = 100;
+ }
+ if (now >= 0) {
+ $(this).css({
+ "-webkit-filter": "grayscale(" + grayscale_setting + ")" + "brightness(" + brightness_setting + "%)",
+ "filter": "grayscale(" + grayscale_setting + ")" + "brightness(" + brightness_setting + "%)"
+ });
+ }
+ }
+ });
+ };
+
+ // Horizontal staggered list
+ Materialize.showStaggeredList = function (selectorOrEl) {
+ var element;
+ if (typeof(selectorOrEl) === 'string') {
+ element = $(selectorOrEl);
+ } else if (typeof(selectorOrEl) === 'object') {
+ element = selectorOrEl;
+ } else {
+ return;
+ }
+ var time = 0;
+ element.find('li').velocity(
+ {translateX: "-100px"},
+ {duration: 0});
+
+ element.find('li').each(function () {
+ $(this).velocity(
+ {opacity: "1", translateX: "0"},
+ {duration: 800, delay: time, easing: [60, 10]});
+ time += 120;
+ });
+ };
+
+
+ $(document).ready(function () {
+ // Hardcoded .staggered-list scrollFire
+ // var staggeredListOptions = [];
+ // $('ul.staggered-list').each(function (i) {
+
+ // var label = 'scrollFire-' + i;
+ // $(this).addClass(label);
+ // staggeredListOptions.push(
+ // {selector: 'ul.staggered-list.' + label,
+ // offset: 200,
+ // callback: 'showStaggeredList("ul.staggered-list.' + label + '")'});
+ // });
+ // scrollFire(staggeredListOptions);
+
+ // HammerJS, Swipe navigation
+
+ // Touch Event
+ var swipeLeft = false;
+ var swipeRight = false;
+
+
+ // Dismissible Collections
+ $('.dismissable').each(function () {
+ $(this).hammer({
+ prevent_default: false
+ }).bind('pan', function (e) {
+ if (e.gesture.pointerType === "touch") {
+ var $this = $(this);
+ var direction = e.gesture.direction;
+ var x = e.gesture.deltaX;
+ var velocityX = e.gesture.velocityX;
+
+ $this.velocity({
+ translateX: x
+ }, {duration: 50, queue: false, easing: 'easeOutQuad'});
+
+ // Swipe Left
+ if (direction === 4 && (x > ($this.innerWidth() / 2) || velocityX < -0.75)) {
+ swipeLeft = true;
+ }
+
+ // Swipe Right
+ if (direction === 2 && (x < (-1 * $this.innerWidth() / 2) || velocityX > 0.75)) {
+ swipeRight = true;
+ }
+ }
+ }).bind('panend', function (e) {
+ // Reset if collection is moved back into original position
+ if (Math.abs(e.gesture.deltaX) < ($(this).innerWidth() / 2)) {
+ swipeRight = false;
+ swipeLeft = false;
+ }
+
+ if (e.gesture.pointerType === "touch") {
+ var $this = $(this);
+ if (swipeLeft || swipeRight) {
+ var fullWidth;
+ if (swipeLeft) {
+ fullWidth = $this.innerWidth();
+ }
+ else {
+ fullWidth = -1 * $this.innerWidth();
+ }
+
+ $this.velocity({
+ translateX: fullWidth,
+ }, {
+ duration: 100, queue: false, easing: 'easeOutQuad', complete: function () {
+ $this.css('border', 'none');
+ $this.velocity({
+ height: 0, padding: 0,
+ }, {
+ duration: 200, queue: false, easing: 'easeOutQuad', complete: function () {
+ $this.remove();
+ }
+ });
+ }
+ });
+ }
+ else {
+ $this.velocity({
+ translateX: 0,
+ }, {duration: 100, queue: false, easing: 'easeOutQuad'});
+ }
+ swipeLeft = false;
+ swipeRight = false;
+ }
+ });
+
+ });
+
+
+ // time = 0
+ // // Vertical Staggered list
+ // $('ul.staggered-list.vertical li').velocity(
+ // { translateY: "100px"},
+ // { duration: 0 });
+
+ // $('ul.staggered-list.vertical li').each(function() {
+ // $(this).velocity(
+ // { opacity: "1", translateY: "0"},
+ // { duration: 800, delay: time, easing: [60, 25] });
+ // time += 120;
+ // });
+
+ // // Fade in and Scale
+ // $('.fade-in.scale').velocity(
+ // { scaleX: .4, scaleY: .4, translateX: -600},
+ // { duration: 0});
+ // $('.fade-in').each(function() {
+ // $(this).velocity(
+ // { opacity: "1", scaleX: 1, scaleY: 1, translateX: 0},
+ // { duration: 800, easing: [60, 10] });
+ // });
+ });
+}(jQuery));
+;(function ($) {
+
+ // Input: Array of JSON objects {selector, offset, callback}
+
+ Materialize.scrollFire = function (options) {
+
+ var didScroll = false;
+
+ window.addEventListener("scroll", function () {
+ didScroll = true;
+ });
+
+ // Rate limit to 100ms
+ setInterval(function () {
+ if (didScroll) {
+ didScroll = false;
+
+ var windowScroll = window.pageYOffset + window.innerHeight;
+
+ for (var i = 0; i < options.length; i++) {
+ // Get options from each line
+ var value = options[i];
+ var selector = value.selector,
+ offset = value.offset,
+ callback = value.callback;
+
+ var currentElement = document.querySelector(selector);
+ if (currentElement !== null) {
+ var elementOffset = currentElement.getBoundingClientRect().top + window.pageYOffset;
+
+ if (windowScroll > (elementOffset + offset)) {
+ if (value.done !== true) {
+ if (typeof(callback) === 'function') {
+ callback.call(this, currentElement);
+ } else if (typeof(callback) === 'string') {
+ var callbackFunc = new Function(callback);
+ callbackFunc(currentElement);
+ }
+ value.done = true;
+ }
+ }
+ }
+ }
+ }
+ }, 100);
+ };
+
+})(jQuery);
+;/*!
+ * pickadate.js v3.5.0, 2014/04/13
+ * By Amsul, http://amsul.ca
+ * Hosted on http://amsul.github.io/pickadate.js
+ * Licensed under MIT
+ */
+
+(function (factory) {
+
+ // AMD.
+ if (typeof define == 'function' && define.amd)
+ define('picker', ['jquery'], factory)
+
+ // Node.js/browserify.
+ else if (typeof exports == 'object')
+ module.exports = factory(require('jquery'))
+
+ // Browser globals.
+ else this.Picker = factory(jQuery)
+
+}(function ($) {
+
+ var $window = $(window)
+ var $document = $(document)
+ var $html = $(document.documentElement)
+
+
+ /**
+ * The picker constructor that creates a blank picker.
+ */
+ function PickerConstructor(ELEMENT, NAME, COMPONENT, OPTIONS) {
+
+ // If there’s no element, return the picker constructor.
+ if (!ELEMENT) return PickerConstructor
+
+
+ var
+ IS_DEFAULT_THEME = false,
+
+
+ // The state of the picker.
+ STATE = {
+ id: ELEMENT.id || 'P' + Math.abs(~~(Math.random() * new Date()))
+ },
+
+
+ // Merge the defaults and options passed.
+ SETTINGS = COMPONENT ? $.extend(true, {}, COMPONENT.defaults, OPTIONS) : OPTIONS || {},
+
+
+ // Merge the default classes with the settings classes.
+ CLASSES = $.extend({}, PickerConstructor.klasses(), SETTINGS.klass),
+
+
+ // The element node wrapper into a jQuery object.
+ $ELEMENT = $(ELEMENT),
+
+
+ // Pseudo picker constructor.
+ PickerInstance = function () {
+ return this.start()
+ },
+
+
+ // The picker prototype.
+ P = PickerInstance.prototype = {
+
+ constructor: PickerInstance,
+
+ $node: $ELEMENT,
+
+
+ /**
+ * Initialize everything
+ */
+ start: function () {
+
+ // If it’s already started, do nothing.
+ if (STATE && STATE.start) return P
+
+
+ // Update the picker states.
+ STATE.methods = {}
+ STATE.start = true
+ STATE.open = false
+ STATE.type = ELEMENT.type
+
+
+ // Confirm focus state, convert into text input to remove UA stylings,
+ // and set as readonly to prevent keyboard popup.
+ ELEMENT.autofocus = ELEMENT == getActiveElement()
+ ELEMENT.readOnly = !SETTINGS.editable
+ ELEMENT.id = ELEMENT.id || STATE.id
+ if (ELEMENT.type != 'text') {
+ ELEMENT.type = 'text'
+ }
+
+
+ // Create a new picker component with the settings.
+ P.component = new COMPONENT(P, SETTINGS)
+
+
+ // Create the picker root with a holder and then prepare it.
+ P.$root = $(PickerConstructor._.node('div', createWrappedComponent(), CLASSES.picker, 'id="' + ELEMENT.id + '_root" tabindex="0"'))
+ prepareElementRoot()
+
+
+ // If there’s a format for the hidden input element, create the element.
+ if (SETTINGS.formatSubmit) {
+ prepareElementHidden()
+ }
+
+
+ // Prepare the input element.
+ prepareElement()
+
+
+ // Insert the root as specified in the settings.
+ if (SETTINGS.container) $(SETTINGS.container).append(P.$root)
+ else $ELEMENT.after(P.$root)
+
+
+ // Bind the default component and settings events.
+ P.on({
+ start: P.component.onStart,
+ render: P.component.onRender,
+ stop: P.component.onStop,
+ open: P.component.onOpen,
+ close: P.component.onClose,
+ set: P.component.onSet
+ }).on({
+ start: SETTINGS.onStart,
+ render: SETTINGS.onRender,
+ stop: SETTINGS.onStop,
+ open: SETTINGS.onOpen,
+ close: SETTINGS.onClose,
+ set: SETTINGS.onSet
+ })
+
+
+ // Once we’re all set, check the theme in use.
+ IS_DEFAULT_THEME = isUsingDefaultTheme(P.$root.children()[0])
+
+
+ // If the element has autofocus, open the picker.
+ if (ELEMENT.autofocus) {
+ P.open()
+ }
+
+
+ // Trigger queued the “start” and “render” events.
+ return P.trigger('start').trigger('render')
+ }, //start
+
+
+ /**
+ * Render a new picker
+ */
+ render: function (entireComponent) {
+
+ // Insert a new component holder in the root or box.
+ if (entireComponent) P.$root.html(createWrappedComponent())
+ else P.$root.find('.' + CLASSES.box).html(P.component.nodes(STATE.open))
+
+ // Trigger the queued “render” events.
+ return P.trigger('render')
+ }, //render
+
+
+ /**
+ * Destroy everything
+ */
+ stop: function () {
+
+ // If it’s already stopped, do nothing.
+ if (!STATE.start) return P
+
+ // Then close the picker.
+ P.close()
+
+ // Remove the hidden field.
+ if (P._hidden) {
+ P._hidden.parentNode.removeChild(P._hidden)
+ }
+
+ // Remove the root.
+ P.$root.remove()
+
+ // Remove the input class, remove the stored data, and unbind
+ // the events (after a tick for IE - see `P.close`).
+ $ELEMENT.removeClass(CLASSES.input).removeData(NAME)
+ setTimeout(function () {
+ $ELEMENT.off('.' + STATE.id)
+ }, 0)
+
+ // Restore the element state
+ ELEMENT.type = STATE.type
+ ELEMENT.readOnly = false
+
+ // Trigger the queued “stop” events.
+ P.trigger('stop')
+
+ // Reset the picker states.
+ STATE.methods = {}
+ STATE.start = false
+
+ return P
+ }, //stop
+
+
+ /**
+ * Open up the picker
+ */
+ open: function (dontGiveFocus) {
+
+ // If it’s already open, do nothing.
+ if (STATE.open) return P
+
+ // Add the “active” class.
+ $ELEMENT.addClass(CLASSES.active)
+ aria(ELEMENT, 'expanded', true)
+
+ // * A Firefox bug, when `html` has `overflow:hidden`, results in
+ // killing transitions :(. So add the “opened” state on the next tick.
+ // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
+ setTimeout(function () {
+
+ // Add the “opened” class to the picker root.
+ P.$root.addClass(CLASSES.opened)
+ aria(P.$root[0], 'hidden', false)
+
+ }, 0)
+
+ // If we have to give focus, bind the element and doc events.
+ if (dontGiveFocus !== false) {
+
+ // Set it as open.
+ STATE.open = true
+
+ // Prevent the page from scrolling.
+ if (IS_DEFAULT_THEME) {
+ $html.css('overflow', 'hidden').css('padding-right', '+=' + getScrollbarWidth())
+ }
+
+ // Pass focus to the root element’s jQuery object.
+ // * Workaround for iOS8 to bring the picker’s root into view.
+ P.$root.eq(0).focus()
+
+ // Bind the document events.
+ $document.on('click.' + STATE.id + ' focusin.' + STATE.id, function (event) {
+
+ var target = event.target
+
+ // If the target of the event is not the element, close the picker picker.
+ // * Don’t worry about clicks or focusins on the root because those don’t bubble up.
+ // Also, for Firefox, a click on an `option` element bubbles up directly
+ // to the doc. So make sure the target wasn't the doc.
+ // * In Firefox stopPropagation() doesn’t prevent right-click events from bubbling,
+ // which causes the picker to unexpectedly close when right-clicking it. So make
+ // sure the event wasn’t a right-click.
+ if (target != ELEMENT && target != document && event.which != 3) {
+
+ // If the target was the holder that covers the screen,
+ // keep the element focused to maintain tabindex.
+ P.close(target === P.$root.children()[0])
+ }
+
+ }).on('keydown.' + STATE.id, function (event) {
+
+ var
+ // Get the keycode.
+ keycode = event.keyCode,
+
+ // Translate that to a selection change.
+ keycodeToMove = P.component.key[keycode],
+
+ // Grab the target.
+ target = event.target
+
+
+ // On escape, close the picker and give focus.
+ if (keycode == 27) {
+ P.close(true)
+ }
+
+
+ // Check if there is a key movement or “enter” keypress on the element.
+ else if (target == P.$root[0] && ( keycodeToMove || keycode == 13 )) {
+
+ // Prevent the default action to stop page movement.
+ event.preventDefault()
+
+ // Trigger the key movement action.
+ if (keycodeToMove) {
+ PickerConstructor._.trigger(P.component.key.go, P, [PickerConstructor._.trigger(keycodeToMove)])
+ }
+
+ // On “enter”, if the highlighted item isn’t disabled, set the value and close.
+ else if (!P.$root.find('.' + CLASSES.highlighted).hasClass(CLASSES.disabled)) {
+ P.set('select', P.component.item.highlight).close()
+ }
+ }
+
+
+ // If the target is within the root and “enter” is pressed,
+ // prevent the default action and trigger a click on the target instead.
+ else if ($.contains(P.$root[0], target) && keycode == 13) {
+ event.preventDefault()
+ target.click()
+ }
+ })
+ }
+
+ // Trigger the queued “open” events.
+ return P.trigger('open')
+ }, //open
+
+
+ /**
+ * Close the picker
+ */
+ close: function (giveFocus) {
+
+ // If we need to give focus, do it before changing states.
+ if (giveFocus) {
+ // ....ah yes! It would’ve been incomplete without a crazy workaround for IE :|
+ // The focus is triggered *after* the close has completed - causing it
+ // to open again. So unbind and rebind the event at the next tick.
+ P.$root.off('focus.toOpen').eq(0).focus()
+ setTimeout(function () {
+ P.$root.on('focus.toOpen', handleFocusToOpenEvent)
+ }, 0)
+ }
+
+ // Remove the “active” class.
+ $ELEMENT.removeClass(CLASSES.active)
+ aria(ELEMENT, 'expanded', false)
+
+ // * A Firefox bug, when `html` has `overflow:hidden`, results in
+ // killing transitions :(. So remove the “opened” state on the next tick.
+ // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
+ setTimeout(function () {
+
+ // Remove the “opened” and “focused” class from the picker root.
+ P.$root.removeClass(CLASSES.opened + ' ' + CLASSES.focused)
+ aria(P.$root[0], 'hidden', true)
+
+ }, 0)
+
+ // If it’s already closed, do nothing more.
+ if (!STATE.open) return P
+
+ // Set it as closed.
+ STATE.open = false
+
+ // Allow the page to scroll.
+ if (IS_DEFAULT_THEME) {
+ $html.css('overflow', '').css('padding-right', '-=' + getScrollbarWidth())
+ }
+
+ // Unbind the document events.
+ $document.off('.' + STATE.id)
+
+ // Trigger the queued “close” events.
+ return P.trigger('close')
+ }, //close
+
+
+ /**
+ * Clear the values
+ */
+ clear: function (options) {
+ return P.set('clear', null, options)
+ }, //clear
+
+
+ /**
+ * Set something
+ */
+ set: function (thing, value, options) {
+
+ var thingItem, thingValue,
+ thingIsObject = $.isPlainObject(thing),
+ thingObject = thingIsObject ? thing : {}
+
+ // Make sure we have usable options.
+ options = thingIsObject && $.isPlainObject(value) ? value : options || {}
+
+ if (thing) {
+
+ // If the thing isn’t an object, make it one.
+ if (!thingIsObject) {
+ thingObject[thing] = value
+ }
+
+ // Go through the things of items to set.
+ for (thingItem in thingObject) {
+
+ // Grab the value of the thing.
+ thingValue = thingObject[thingItem]
+
+ // First, if the item exists and there’s a value, set it.
+ if (thingItem in P.component.item) {
+ if (thingValue === undefined) thingValue = null
+ P.component.set(thingItem, thingValue, options)
+ }
+
+ // Then, check to update the element value and broadcast a change.
+ if (thingItem == 'select' || thingItem == 'clear') {
+ $ELEMENT.val(thingItem == 'clear' ? '' : P.get(thingItem, SETTINGS.format)).trigger('change')
+ }
+ }
+
+ // Render a new picker.
+ P.render()
+ }
+
+ // When the method isn’t muted, trigger queued “set” events and pass the `thingObject`.
+ return options.muted ? P : P.trigger('set', thingObject)
+ }, //set
+
+
+ /**
+ * Get something
+ */
+ get: function (thing, format) {
+
+ // Make sure there’s something to get.
+ thing = thing || 'value'
+
+ // If a picker state exists, return that.
+ if (STATE[thing] != null) {
+ return STATE[thing]
+ }
+
+ // Return the submission value, if that.
+ if (thing == 'valueSubmit') {
+ if (P._hidden) {
+ return P._hidden.value
+ }
+ thing = 'value'
+ }
+
+ // Return the value, if that.
+ if (thing == 'value') {
+ return ELEMENT.value
+ }
+
+ // Check if a component item exists, return that.
+ if (thing in P.component.item) {
+ if (typeof format == 'string') {
+ var thingValue = P.component.get(thing)
+ return thingValue ?
+ PickerConstructor._.trigger(
+ P.component.formats.toString,
+ P.component,
+ [format, thingValue]
+ ) : ''
+ }
+ return P.component.get(thing)
+ }
+ }, //get
+
+
+ /**
+ * Bind events on the things.
+ */
+ on: function (thing, method, internal) {
+
+ var thingName, thingMethod,
+ thingIsObject = $.isPlainObject(thing),
+ thingObject = thingIsObject ? thing : {}
+
+ if (thing) {
+
+ // If the thing isn’t an object, make it one.
+ if (!thingIsObject) {
+ thingObject[thing] = method
+ }
+
+ // Go through the things to bind to.
+ for (thingName in thingObject) {
+
+ // Grab the method of the thing.
+ thingMethod = thingObject[thingName]
+
+ // If it was an internal binding, prefix it.
+ if (internal) {
+ thingName = '_' + thingName
+ }
+
+ // Make sure the thing methods collection exists.
+ STATE.methods[thingName] = STATE.methods[thingName] || []
+
+ // Add the method to the relative method collection.
+ STATE.methods[thingName].push(thingMethod)
+ }
+ }
+
+ return P
+ }, //on
+
+
+ /**
+ * Unbind events on the things.
+ */
+ off: function () {
+ var i, thingName,
+ names = arguments;
+ for (i = 0, namesCount = names.length; i < namesCount; i += 1) {
+ thingName = names[i]
+ if (thingName in STATE.methods) {
+ delete STATE.methods[thingName]
+ }
+ }
+ return P
+ },
+
+
+ /**
+ * Fire off method events.
+ */
+ trigger: function (name, data) {
+ var _trigger = function (name) {
+ var methodList = STATE.methods[name]
+ if (methodList) {
+ methodList.map(function (method) {
+ PickerConstructor._.trigger(method, P, [data])
+ })
+ }
+ }
+ _trigger('_' + name)
+ _trigger(name)
+ return P
+ } //trigger
+ } //PickerInstance.prototype
+
+
+ /**
+ * Wrap the picker holder components together.
+ */
+ function createWrappedComponent() {
+
+ // Create a picker wrapper holder
+ return PickerConstructor._.node('div',
+
+ // Create a picker wrapper node
+ PickerConstructor._.node('div',
+
+ // Create a picker frame
+ PickerConstructor._.node('div',
+
+ // Create a picker box node
+ PickerConstructor._.node('div',
+
+ // Create the components nodes.
+ P.component.nodes(STATE.open),
+
+ // The picker box class
+ CLASSES.box
+ ),
+
+ // Picker wrap class
+ CLASSES.wrap
+ ),
+
+ // Picker frame class
+ CLASSES.frame
+ ),
+
+ // Picker holder class
+ CLASSES.holder
+ ) //endreturn
+ } //createWrappedComponent
+
+
+ /**
+ * Prepare the input element with all bindings.
+ */
+ function prepareElement() {
+
+ $ELEMENT.// Store the picker data by component name.
+ data(NAME, P).// Add the “input” class name.
+ addClass(CLASSES.input).// Remove the tabindex.
+ attr('tabindex', -1).// If there’s a `data-value`, update the value of the element.
+ val($ELEMENT.data('value') ?
+ P.get('select', SETTINGS.format) :
+ ELEMENT.value
+ )
+
+
+ // Only bind keydown events if the element isn’t editable.
+ if (!SETTINGS.editable) {
+
+ $ELEMENT.// On focus/click, focus onto the root to open it up.
+ on('focus.' + STATE.id + ' click.' + STATE.id, function (event) {
+ event.preventDefault()
+ P.$root.eq(0).focus()
+ }).// Handle keyboard event based on the picker being opened or not.
+ on('keydown.' + STATE.id, handleKeydownEvent)
+ }
+
+
+ // Update the aria attributes.
+ aria(ELEMENT, {
+ haspopup: true,
+ expanded: false,
+ readonly: false,
+ owns: ELEMENT.id + '_root'
+ })
+ }
+
+
+ /**
+ * Prepare the root picker element with all bindings.
+ */
+ function prepareElementRoot() {
+
+ P.$root.on({
+
+ // For iOS8.
+ keydown: handleKeydownEvent,
+
+ // When something within the root is focused, stop from bubbling
+ // to the doc and remove the “focused” state from the root.
+ focusin: function (event) {
+ P.$root.removeClass(CLASSES.focused)
+ event.stopPropagation()
+ },
+
+ // When something within the root holder is clicked, stop it
+ // from bubbling to the doc.
+ 'mousedown click': function (event) {
+
+ var target = event.target
+
+ // Make sure the target isn’t the root holder so it can bubble up.
+ if (target != P.$root.children()[0]) {
+
+ event.stopPropagation()
+
+ // * For mousedown events, cancel the default action in order to
+ // prevent cases where focus is shifted onto external elements
+ // when using things like jQuery mobile or MagnificPopup (ref: #249 & #120).
+ // Also, for Firefox, don’t prevent action on the `option` element.
+ if (event.type == 'mousedown' && !$(target).is('input, select, textarea, button, option')) {
+
+ event.preventDefault()
+
+ // Re-focus onto the root so that users can click away
+ // from elements focused within the picker.
+ P.$root.eq(0).focus()
+ }
+ }
+ }
+ }).// Add/remove the “target” class on focus and blur.
+ on({
+ focus: function () {
+ $ELEMENT.addClass(CLASSES.target)
+ },
+ blur: function () {
+ $ELEMENT.removeClass(CLASSES.target)
+ }
+ }).// Open the picker and adjust the root “focused” state
+ on('focus.toOpen', handleFocusToOpenEvent).// If there’s a click on an actionable element, carry out the actions.
+ on('click', '[data-pick], [data-nav], [data-clear], [data-close]', function () {
+
+ var $target = $(this),
+ targetData = $target.data(),
+ targetDisabled = $target.hasClass(CLASSES.navDisabled) || $target.hasClass(CLASSES.disabled),
+
+ // * For IE, non-focusable elements can be active elements as well
+ // (http://stackoverflow.com/a/2684561).
+ activeElement = getActiveElement()
+ activeElement = activeElement && ( activeElement.type || activeElement.href )
+
+ // If it’s disabled or nothing inside is actively focused, re-focus the element.
+ if (targetDisabled || activeElement && !$.contains(P.$root[0], activeElement)) {
+ P.$root.eq(0).focus()
+ }
+
+ // If something is superficially changed, update the `highlight` based on the `nav`.
+ if (!targetDisabled && targetData.nav) {
+ P.set('highlight', P.component.item.highlight, {nav: targetData.nav})
+ }
+
+ // If something is picked, set `select` then close with focus.
+ else if (!targetDisabled && 'pick' in targetData) {
+ P.set('select', targetData.pick)
+ }
+
+ // If a “clear” button is pressed, empty the values and close with focus.
+ else if (targetData.clear) {
+ P.clear().close(true)
+ }
+
+ else if (targetData.close) {
+ P.close(true)
+ }
+
+ }) //P.$root
+
+ aria(P.$root[0], 'hidden', true)
+ }
+
+
+ /**
+ * Prepare the hidden input element along with all bindings.
+ */
+ function prepareElementHidden() {
+
+ var name
+
+ if (SETTINGS.hiddenName === true) {
+ name = ELEMENT.name
+ ELEMENT.name = ''
+ }
+ else {
+ name = [
+ typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '',
+ typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'
+ ]
+ name = name[0] + ELEMENT.name + name[1]
+ }
+
+ P._hidden = $(
+ '
'
+ )[0]
+
+ $ELEMENT.// If the value changes, update the hidden input with the correct format.
+ on('change.' + STATE.id, function () {
+ P._hidden.value = ELEMENT.value ?
+ P.get('select', SETTINGS.formatSubmit) :
+ ''
+ })
+
+
+ // Insert the hidden input as specified in the settings.
+ if (SETTINGS.container) $(SETTINGS.container).append(P._hidden)
+ else $ELEMENT.after(P._hidden)
+ }
+
+
+ // For iOS8.
+ function handleKeydownEvent(event) {
+
+ var keycode = event.keyCode,
+
+ // Check if one of the delete keys was pressed.
+ isKeycodeDelete = /^(8|46)$/.test(keycode)
+
+ // For some reason IE clears the input value on “escape”.
+ if (keycode == 27) {
+ P.close()
+ return false
+ }
+
+ // Check if `space` or `delete` was pressed or the picker is closed with a key movement.
+ if (keycode == 32 || isKeycodeDelete || !STATE.open && P.component.key[keycode]) {
+
+ // Prevent it from moving the page and bubbling to doc.
+ event.preventDefault()
+ event.stopPropagation()
+
+ // If `delete` was pressed, clear the values and close the picker.
+ // Otherwise open the picker.
+ if (isKeycodeDelete) {
+ P.clear().close()
+ }
+ else {
+ P.open()
+ }
+ }
+ }
+
+
+ // Separated for IE
+ function handleFocusToOpenEvent(event) {
+
+ // Stop the event from propagating to the doc.
+ event.stopPropagation()
+
+ // If it’s a focus event, add the “focused” class to the root.
+ if (event.type == 'focus') {
+ P.$root.addClass(CLASSES.focused)
+ }
+
+ // And then finally open the picker.
+ P.open()
+ }
+
+
+ // Return a new picker instance.
+ return new PickerInstance()
+ } //PickerConstructor
+
+
+ /**
+ * The default classes and prefix to use for the HTML classes.
+ */
+ PickerConstructor.klasses = function (prefix) {
+ prefix = prefix || 'picker'
+ return {
+
+ picker: prefix,
+ opened: prefix + '--opened',
+ focused: prefix + '--focused',
+
+ input: prefix + '__input',
+ active: prefix + '__input--active',
+ target: prefix + '__input--target',
+
+ holder: prefix + '__holder',
+
+ frame: prefix + '__frame',
+ wrap: prefix + '__wrap',
+
+ box: prefix + '__box'
+ }
+ } //PickerConstructor.klasses
+
+
+ /**
+ * Check if the default theme is being used.
+ */
+ function isUsingDefaultTheme(element) {
+
+ var theme,
+ prop = 'position'
+
+ // For IE.
+ if (element.currentStyle) {
+ theme = element.currentStyle[prop]
+ }
+
+ // For normal browsers.
+ else if (window.getComputedStyle) {
+ theme = getComputedStyle(element)[prop]
+ }
+
+ return theme == 'fixed'
+ }
+
+
+ /**
+ * Get the width of the browser’s scrollbar.
+ * Taken from: https://github.com/VodkaBears/Remodal/blob/master/src/jquery.remodal.js
+ */
+ function getScrollbarWidth() {
+
+ if ($html.height() <= $window.height()) {
+ return 0
+ }
+
+ var $outer = $('
').appendTo('body')
+
+ // Get the width without scrollbars.
+ var widthWithoutScroll = $outer[0].offsetWidth
+
+ // Force adding scrollbars.
+ $outer.css('overflow', 'scroll')
+
+ // Add the inner div.
+ var $inner = $('
').appendTo($outer)
+
+ // Get the width with scrollbars.
+ var widthWithScroll = $inner[0].offsetWidth
+
+ // Remove the divs.
+ $outer.remove()
+
+ // Return the difference between the widths.
+ return widthWithoutScroll - widthWithScroll
+ }
+
+
+ /**
+ * PickerConstructor helper methods.
+ */
+ PickerConstructor._ = {
+
+ /**
+ * Create a group of nodes. Expects:
+ * `
+ {
+ min: {Integer},
+ max: {Integer},
+ i: {Integer},
+ node: {String},
+ item: {Function}
+ }
+ * `
+ */
+ group: function (groupObject) {
+
+ var
+ // Scope for the looped object
+ loopObjectScope,
+
+ // Create the nodes list
+ nodesList = '',
+
+ // The counter starts from the `min`
+ counter = PickerConstructor._.trigger(groupObject.min, groupObject)
+
+
+ // Loop from the `min` to `max`, incrementing by `i`
+ for (; counter <= PickerConstructor._.trigger(groupObject.max, groupObject, [counter]); counter += groupObject.i) {
+
+ // Trigger the `item` function within scope of the object
+ loopObjectScope = PickerConstructor._.trigger(groupObject.item, groupObject, [counter])
+
+ // Splice the subgroup and create nodes out of the sub nodes
+ nodesList += PickerConstructor._.node(
+ groupObject.node,
+ loopObjectScope[0], // the node
+ loopObjectScope[1], // the classes
+ loopObjectScope[2] // the attributes
+ )
+ }
+
+ // Return the list of nodes
+ return nodesList
+ }, //group
+
+
+ /**
+ * Create a dom node string
+ */
+ node: function (wrapper, item, klass, attribute) {
+
+ // If the item is false-y, just return an empty string
+ if (!item) return ''
+
+ // If the item is an array, do a join
+ item = $.isArray(item) ? item.join('') : item
+
+ // Check for the class
+ klass = klass ? ' class="' + klass + '"' : ''
+
+ // Check for any attributes
+ attribute = attribute ? ' ' + attribute : ''
+
+ // Return the wrapped item
+ return '<' + wrapper + klass + attribute + '>' + item + '' + wrapper + '>'
+ }, //node
+
+
+ /**
+ * Lead numbers below 10 with a zero.
+ */
+ lead: function (number) {
+ return ( number < 10 ? '0' : '' ) + number
+ },
+
+
+ /**
+ * Trigger a function otherwise return the value.
+ */
+ trigger: function (callback, scope, args) {
+ return typeof callback == 'function' ? callback.apply(scope, args || []) : callback
+ },
+
+
+ /**
+ * If the second character is a digit, length is 2 otherwise 1.
+ */
+ digits: function (string) {
+ return ( /\d/ ).test(string[1]) ? 2 : 1
+ },
+
+
+ /**
+ * Tell if something is a date object.
+ */
+ isDate: function (value) {
+ return {}.toString.call(value).indexOf('Date') > -1 && this.isInteger(value.getDate())
+ },
+
+
+ /**
+ * Tell if something is an integer.
+ */
+ isInteger: function (value) {
+ return {}.toString.call(value).indexOf('Number') > -1 && value % 1 === 0
+ },
+
+
+ /**
+ * Create ARIA attribute strings.
+ */
+ ariaAttr: ariaAttr
+ } //PickerConstructor._
+
+
+ /**
+ * Extend the picker with a component and defaults.
+ */
+ PickerConstructor.extend = function (name, Component) {
+
+ // Extend jQuery.
+ $.fn[name] = function (options, action) {
+
+ // Grab the component data.
+ var componentData = this.data(name)
+
+ // If the picker is requested, return the data object.
+ if (options == 'picker') {
+ return componentData
+ }
+
+ // If the component data exists and `options` is a string, carry out the action.
+ if (componentData && typeof options == 'string') {
+ return PickerConstructor._.trigger(componentData[options], componentData, [action])
+ }
+
+ // Otherwise go through each matched element and if the component
+ // doesn’t exist, create a new picker using `this` element
+ // and merging the defaults and options with a deep copy.
+ return this.each(function () {
+ var $this = $(this)
+ if (!$this.data(name)) {
+ new PickerConstructor(this, name, Component, options)
+ }
+ })
+ }
+
+ // Set the defaults.
+ $.fn[name].defaults = Component.defaults
+ } //PickerConstructor.extend
+
+
+ function aria(element, attribute, value) {
+ if ($.isPlainObject(attribute)) {
+ for (var key in attribute) {
+ ariaSet(element, key, attribute[key])
+ }
+ }
+ else {
+ ariaSet(element, attribute, value)
+ }
+ }
+
+ function ariaSet(element, attribute, value) {
+ element.setAttribute(
+ (attribute == 'role' ? '' : 'aria-') + attribute,
+ value
+ )
+ }
+
+ function ariaAttr(attribute, data) {
+ if (!$.isPlainObject(attribute)) {
+ attribute = {attribute: data}
+ }
+ data = ''
+ for (var key in attribute) {
+ var attr = (key == 'role' ? '' : 'aria-') + key,
+ attrVal = attribute[key]
+ data += attrVal == null ? '' : attr + '="' + attribute[key] + '"'
+ }
+ return data
+ }
+
+// IE8 bug throws an error for activeElements within iframes.
+ function getActiveElement() {
+ try {
+ return document.activeElement
+ } catch (err) {
+ }
+ }
+
+
+// Expose the picker constructor.
+ return PickerConstructor
+
+
+}));
+
+
+;/*!
+ * Date picker for pickadate.js v3.5.0
+ * http://amsul.github.io/pickadate.js/date.htm
+ */
+
+(function (factory) {
+
+ // AMD.
+ if (typeof define == 'function' && define.amd)
+ define(['picker', 'jquery'], factory)
+
+ // Node.js/browserify.
+ else if (typeof exports == 'object')
+ module.exports = factory(require('./picker.js'), require('jquery'))
+
+ // Browser globals.
+ else factory(Picker, jQuery)
+
+}(function (Picker, $) {
+
+
+ /**
+ * Globals and constants
+ */
+ var DAYS_IN_WEEK = 7,
+ WEEKS_IN_CALENDAR = 6,
+ _ = Picker._
+
+
+ /**
+ * The date picker constructor
+ */
+ function DatePicker(picker, settings) {
+
+ var calendar = this,
+ element = picker.$node[0],
+ elementValue = element.value,
+ elementDataValue = picker.$node.data('value'),
+ valueString = elementDataValue || elementValue,
+ formatString = elementDataValue ? settings.formatSubmit : settings.format,
+ isRTL = function () {
+
+ return element.currentStyle ?
+
+ // For IE.
+ element.currentStyle.direction == 'rtl' :
+
+ // For normal browsers.
+ getComputedStyle(picker.$root[0]).direction == 'rtl'
+ }
+
+ calendar.settings = settings
+ calendar.$node = picker.$node
+
+ // The queue of methods that will be used to build item objects.
+ calendar.queue = {
+ min: 'measure create',
+ max: 'measure create',
+ now: 'now create',
+ select: 'parse create validate',
+ highlight: 'parse navigate create validate',
+ view: 'parse create validate viewset',
+ disable: 'deactivate',
+ enable: 'activate'
+ }
+
+ // The component's item object.
+ calendar.item = {}
+
+ calendar.item.clear = null
+ calendar.item.disable = ( settings.disable || [] ).slice(0)
+ calendar.item.enable = -(function (collectionDisabled) {
+ return collectionDisabled[0] === true ? collectionDisabled.shift() : -1
+ })(calendar.item.disable)
+
+ calendar.set('min', settings.min).set('max', settings.max).set('now')
+
+ // When there’s a value, set the `select`, which in turn
+ // also sets the `highlight` and `view`.
+ if (valueString) {
+ calendar.set('select', valueString, {format: formatString})
+ }
+
+ // If there’s no value, default to highlighting “today”.
+ else {
+ calendar.set('select', null).set('highlight', calendar.item.now)
+ }
+
+
+ // The keycode to movement mapping.
+ calendar.key = {
+ 40: 7, // Down
+ 38: -7, // Up
+ 39: function () {
+ return isRTL() ? -1 : 1
+ }, // Right
+ 37: function () {
+ return isRTL() ? 1 : -1
+ }, // Left
+ go: function (timeChange) {
+ var highlightedObject = calendar.item.highlight,
+ targetDate = new Date(highlightedObject.year, highlightedObject.month, highlightedObject.date + timeChange)
+ calendar.set(
+ 'highlight',
+ targetDate,
+ {interval: timeChange}
+ )
+ this.render()
+ }
+ }
+
+
+ // Bind some picker events.
+ picker.on('render', function () {
+ picker.$root.find('.' + settings.klass.selectMonth).on('change', function () {
+ var value = this.value
+ if (value) {
+ picker.set('highlight', [picker.get('view').year, value, picker.get('highlight').date])
+ picker.$root.find('.' + settings.klass.selectMonth).trigger('focus')
+ }
+ })
+ picker.$root.find('.' + settings.klass.selectYear).on('change', function () {
+ var value = this.value
+ if (value) {
+ picker.set('highlight', [value, picker.get('view').month, picker.get('highlight').date])
+ picker.$root.find('.' + settings.klass.selectYear).trigger('focus')
+ }
+ })
+ }, 1).on('open', function () {
+ var includeToday = ''
+ if (calendar.disabled(calendar.get('now'))) {
+ includeToday = ':not(.' + settings.klass.buttonToday + ')'
+ }
+ picker.$root.find('button' + includeToday + ', select').attr('disabled', false)
+ }, 1).on('close', function () {
+ picker.$root.find('button, select').attr('disabled', true)
+ }, 1)
+
+ } //DatePicker
+
+
+ /**
+ * Set a datepicker item object.
+ */
+ DatePicker.prototype.set = function (type, value, options) {
+
+ var calendar = this,
+ calendarItem = calendar.item
+
+ // If the value is `null` just set it immediately.
+ if (value === null) {
+ if (type == 'clear') type = 'select'
+ calendarItem[type] = value
+ return calendar
+ }
+
+ // Otherwise go through the queue of methods, and invoke the functions.
+ // Update this as the time unit, and set the final value as this item.
+ // * In the case of `enable`, keep the queue but set `disable` instead.
+ // And in the case of `flip`, keep the queue but set `enable` instead.
+ calendarItem[( type == 'enable' ? 'disable' : type == 'flip' ? 'enable' : type )] = calendar.queue[type].split(' ').map(function (method) {
+ value = calendar[method](type, value, options)
+ return value
+ }).pop()
+
+ // Check if we need to cascade through more updates.
+ if (type == 'select') {
+ calendar.set('highlight', calendarItem.select, options)
+ }
+ else if (type == 'highlight') {
+ calendar.set('view', calendarItem.highlight, options)
+ }
+ else if (type.match(/^(flip|min|max|disable|enable)$/)) {
+ if (calendarItem.select && calendar.disabled(calendarItem.select)) {
+ calendar.set('select', calendarItem.select, options)
+ }
+ if (calendarItem.highlight && calendar.disabled(calendarItem.highlight)) {
+ calendar.set('highlight', calendarItem.highlight, options)
+ }
+ }
+
+ return calendar
+ } //DatePicker.prototype.set
+
+
+ /**
+ * Get a datepicker item object.
+ */
+ DatePicker.prototype.get = function (type) {
+ return this.item[type]
+ } //DatePicker.prototype.get
+
+
+ /**
+ * Create a picker date object.
+ */
+ DatePicker.prototype.create = function (type, value, options) {
+
+ var isInfiniteValue,
+ calendar = this
+
+ // If there’s no value, use the type as the value.
+ value = value === undefined ? type : value
+
+
+ // If it’s infinity, update the value.
+ if (value == -Infinity || value == Infinity) {
+ isInfiniteValue = value
+ }
+
+ // If it’s an object, use the native date object.
+ else if ($.isPlainObject(value) && _.isInteger(value.pick)) {
+ value = value.obj
+ }
+
+ // If it’s an array, convert it into a date and make sure
+ // that it’s a valid date – otherwise default to today.
+ else if ($.isArray(value)) {
+ value = new Date(value[0], value[1], value[2])
+ value = _.isDate(value) ? value : calendar.create().obj
+ }
+
+ // If it’s a number or date object, make a normalized date.
+ else if (_.isInteger(value) || _.isDate(value)) {
+ value = calendar.normalize(new Date(value), options)
+ }
+
+ // If it’s a literal true or any other case, set it to now.
+ else /*if ( value === true )*/ {
+ value = calendar.now(type, value, options)
+ }
+
+ // Return the compiled object.
+ return {
+ year: isInfiniteValue || value.getFullYear(),
+ month: isInfiniteValue || value.getMonth(),
+ date: isInfiniteValue || value.getDate(),
+ day: isInfiniteValue || value.getDay(),
+ obj: isInfiniteValue || value,
+ pick: isInfiniteValue || value.getTime()
+ }
+ } //DatePicker.prototype.create
+
+
+ /**
+ * Create a range limit object using an array, date object,
+ * literal “true”, or integer relative to another time.
+ */
+ DatePicker.prototype.createRange = function (from, to) {
+
+ var calendar = this,
+ createDate = function (date) {
+ if (date === true || $.isArray(date) || _.isDate(date)) {
+ return calendar.create(date)
+ }
+ return date
+ }
+
+ // Create objects if possible.
+ if (!_.isInteger(from)) {
+ from = createDate(from)
+ }
+ if (!_.isInteger(to)) {
+ to = createDate(to)
+ }
+
+ // Create relative dates.
+ if (_.isInteger(from) && $.isPlainObject(to)) {
+ from = [to.year, to.month, to.date + from];
+ }
+ else if (_.isInteger(to) && $.isPlainObject(from)) {
+ to = [from.year, from.month, from.date + to];
+ }
+
+ return {
+ from: createDate(from),
+ to: createDate(to)
+ }
+ } //DatePicker.prototype.createRange
+
+
+ /**
+ * Check if a date unit falls within a date range object.
+ */
+ DatePicker.prototype.withinRange = function (range, dateUnit) {
+ range = this.createRange(range.from, range.to)
+ return dateUnit.pick >= range.from.pick && dateUnit.pick <= range.to.pick
+ }
+
+
+ /**
+ * Check if two date range objects overlap.
+ */
+ DatePicker.prototype.overlapRanges = function (one, two) {
+
+ var calendar = this
+
+ // Convert the ranges into comparable dates.
+ one = calendar.createRange(one.from, one.to)
+ two = calendar.createRange(two.from, two.to)
+
+ return calendar.withinRange(one, two.from) || calendar.withinRange(one, two.to) ||
+ calendar.withinRange(two, one.from) || calendar.withinRange(two, one.to)
+ }
+
+
+ /**
+ * Get the date today.
+ */
+ DatePicker.prototype.now = function (type, value, options) {
+ value = new Date()
+ if (options && options.rel) {
+ value.setDate(value.getDate() + options.rel)
+ }
+ return this.normalize(value, options)
+ }
+
+
+ /**
+ * Navigate to next/prev month.
+ */
+ DatePicker.prototype.navigate = function (type, value, options) {
+
+ var targetDateObject,
+ targetYear,
+ targetMonth,
+ targetDate,
+ isTargetArray = $.isArray(value),
+ isTargetObject = $.isPlainObject(value),
+ viewsetObject = this.item.view
+ /*,
+ safety = 100*/
+
+
+ if (isTargetArray || isTargetObject) {
+
+ if (isTargetObject) {
+ targetYear = value.year
+ targetMonth = value.month
+ targetDate = value.date
+ }
+ else {
+ targetYear = +value[0]
+ targetMonth = +value[1]
+ targetDate = +value[2]
+ }
+
+ // If we’re navigating months but the view is in a different
+ // month, navigate to the view’s year and month.
+ if (options && options.nav && viewsetObject && viewsetObject.month !== targetMonth) {
+ targetYear = viewsetObject.year
+ targetMonth = viewsetObject.month
+ }
+
+ // Figure out the expected target year and month.
+ targetDateObject = new Date(targetYear, targetMonth + ( options && options.nav ? options.nav : 0 ), 1)
+ targetYear = targetDateObject.getFullYear()
+ targetMonth = targetDateObject.getMonth()
+
+ // If the month we’re going to doesn’t have enough days,
+ // keep decreasing the date until we reach the month’s last date.
+ while (/*safety &&*/ new Date(targetYear, targetMonth, targetDate).getMonth() !== targetMonth) {
+ targetDate -= 1
+ /*safety -= 1
+ if ( !safety ) {
+ throw 'Fell into an infinite loop while navigating to ' + new Date( targetYear, targetMonth, targetDate ) + '.'
+ }*/
+ }
+
+ value = [targetYear, targetMonth, targetDate]
+ }
+
+ return value
+ } //DatePicker.prototype.navigate
+
+
+ /**
+ * Normalize a date by setting the hours to midnight.
+ */
+ DatePicker.prototype.normalize = function (value/*, options*/) {
+ value.setHours(0, 0, 0, 0)
+ return value
+ }
+
+
+ /**
+ * Measure the range of dates.
+ */
+ DatePicker.prototype.measure = function (type, value/*, options*/) {
+
+ var calendar = this
+
+ // If it’s anything false-y, remove the limits.
+ if (!value) {
+ value = type == 'min' ? -Infinity : Infinity
+ }
+
+ // If it’s a string, parse it.
+ else if (typeof value == 'string') {
+ value = calendar.parse(type, value)
+ }
+
+ // If it's an integer, get a date relative to today.
+ else if (_.isInteger(value)) {
+ value = calendar.now(type, value, {rel: value})
+ }
+
+ return value
+ } ///DatePicker.prototype.measure
+
+
+ /**
+ * Create a viewset object based on navigation.
+ */
+ DatePicker.prototype.viewset = function (type, dateObject/*, options*/) {
+ return this.create([dateObject.year, dateObject.month, 1])
+ }
+
+
+ /**
+ * Validate a date as enabled and shift if needed.
+ */
+ DatePicker.prototype.validate = function (type, dateObject, options) {
+
+ var calendar = this,
+
+ // Keep a reference to the original date.
+ originalDateObject = dateObject,
+
+ // Make sure we have an interval.
+ interval = options && options.interval ? options.interval : 1,
+
+ // Check if the calendar enabled dates are inverted.
+ isFlippedBase = calendar.item.enable === -1,
+
+ // Check if we have any enabled dates after/before now.
+ hasEnabledBeforeTarget, hasEnabledAfterTarget,
+
+ // The min & max limits.
+ minLimitObject = calendar.item.min,
+ maxLimitObject = calendar.item.max,
+
+ // Check if we’ve reached the limit during shifting.
+ reachedMin, reachedMax,
+
+ // Check if the calendar is inverted and at least one weekday is enabled.
+ hasEnabledWeekdays = isFlippedBase && calendar.item.disable.filter(function (value) {
+
+ // If there’s a date, check where it is relative to the target.
+ if ($.isArray(value)) {
+ var dateTime = calendar.create(value).pick
+ if (dateTime < dateObject.pick) hasEnabledBeforeTarget = true
+ else if (dateTime > dateObject.pick) hasEnabledAfterTarget = true
+ }
+
+ // Return only integers for enabled weekdays.
+ return _.isInteger(value)
+ }).length
+ /*,
+
+ safety = 100*/
+
+
+ // Cases to validate for:
+ // [1] Not inverted and date disabled.
+ // [2] Inverted and some dates enabled.
+ // [3] Not inverted and out of range.
+ //
+ // Cases to **not** validate for:
+ // • Navigating months.
+ // • Not inverted and date enabled.
+ // • Inverted and all dates disabled.
+ // • ..and anything else.
+ if (!options || !options.nav) if (
+ /* 1 */ ( !isFlippedBase && calendar.disabled(dateObject) ) ||
+ /* 2 */ ( isFlippedBase && calendar.disabled(dateObject) && ( hasEnabledWeekdays || hasEnabledBeforeTarget || hasEnabledAfterTarget ) ) ||
+ /* 3 */ ( !isFlippedBase && (dateObject.pick <= minLimitObject.pick || dateObject.pick >= maxLimitObject.pick) )
+ ) {
+
+
+ // When inverted, flip the direction if there aren’t any enabled weekdays
+ // and there are no enabled dates in the direction of the interval.
+ if (isFlippedBase && !hasEnabledWeekdays && ( ( !hasEnabledAfterTarget && interval > 0 ) || ( !hasEnabledBeforeTarget && interval < 0 ) )) {
+ interval *= -1
+ }
+
+
+ // Keep looping until we reach an enabled date.
+ while (/*safety &&*/ calendar.disabled(dateObject)) {
+
+ /*safety -= 1
+ if ( !safety ) {
+ throw 'Fell into an infinite loop while validating ' + dateObject.obj + '.'
+ }*/
+
+
+ // If we’ve looped into the next/prev month with a large interval, return to the original date and flatten the interval.
+ if (Math.abs(interval) > 1 && ( dateObject.month < originalDateObject.month || dateObject.month > originalDateObject.month )) {
+ dateObject = originalDateObject
+ interval = interval > 0 ? 1 : -1
+ }
+
+
+ // If we’ve reached the min/max limit, reverse the direction, flatten the interval and set it to the limit.
+ if (dateObject.pick <= minLimitObject.pick) {
+ reachedMin = true
+ interval = 1
+ dateObject = calendar.create([
+ minLimitObject.year,
+ minLimitObject.month,
+ minLimitObject.date + (dateObject.pick === minLimitObject.pick ? 0 : -1)
+ ])
+ }
+ else if (dateObject.pick >= maxLimitObject.pick) {
+ reachedMax = true
+ interval = -1
+ dateObject = calendar.create([
+ maxLimitObject.year,
+ maxLimitObject.month,
+ maxLimitObject.date + (dateObject.pick === maxLimitObject.pick ? 0 : 1)
+ ])
+ }
+
+
+ // If we’ve reached both limits, just break out of the loop.
+ if (reachedMin && reachedMax) {
+ break
+ }
+
+
+ // Finally, create the shifted date using the interval and keep looping.
+ dateObject = calendar.create([dateObject.year, dateObject.month, dateObject.date + interval])
+ }
+
+ } //endif
+
+
+ // Return the date object settled on.
+ return dateObject
+ } //DatePicker.prototype.validate
+
+
+ /**
+ * Check if a date is disabled.
+ */
+ DatePicker.prototype.disabled = function (dateToVerify) {
+
+ var
+ calendar = this,
+
+ // Filter through the disabled dates to check if this is one.
+ isDisabledMatch = calendar.item.disable.filter(function (dateToDisable) {
+
+ // If the date is a number, match the weekday with 0index and `firstDay` check.
+ if (_.isInteger(dateToDisable)) {
+ return dateToVerify.day === ( calendar.settings.firstDay ? dateToDisable : dateToDisable - 1 ) % 7
+ }
+
+ // If it’s an array or a native JS date, create and match the exact date.
+ if ($.isArray(dateToDisable) || _.isDate(dateToDisable)) {
+ return dateToVerify.pick === calendar.create(dateToDisable).pick
+ }
+
+ // If it’s an object, match a date within the “from” and “to” range.
+ if ($.isPlainObject(dateToDisable)) {
+ return calendar.withinRange(dateToDisable, dateToVerify)
+ }
+ })
+
+ // If this date matches a disabled date, confirm it’s not inverted.
+ isDisabledMatch = isDisabledMatch.length && !isDisabledMatch.filter(function (dateToDisable) {
+ return $.isArray(dateToDisable) && dateToDisable[3] == 'inverted' ||
+ $.isPlainObject(dateToDisable) && dateToDisable.inverted
+ }).length
+
+ // Check the calendar “enabled” flag and respectively flip the
+ // disabled state. Then also check if it’s beyond the min/max limits.
+ return calendar.item.enable === -1 ? !isDisabledMatch : isDisabledMatch ||
+ dateToVerify.pick < calendar.item.min.pick ||
+ dateToVerify.pick > calendar.item.max.pick
+
+ } //DatePicker.prototype.disabled
+
+
+ /**
+ * Parse a string into a usable type.
+ */
+ DatePicker.prototype.parse = function (type, value, options) {
+
+ var calendar = this,
+ parsingObject = {}
+
+ // If it’s already parsed, we’re good.
+ if (!value || typeof value != 'string') {
+ return value
+ }
+
+ // We need a `.format` to parse the value with.
+ if (!( options && options.format )) {
+ options = options || {}
+ options.format = calendar.settings.format
+ }
+
+ // Convert the format into an array and then map through it.
+ calendar.formats.toArray(options.format).map(function (label) {
+
+ var
+ // Grab the formatting label.
+ formattingLabel = calendar.formats[label],
+
+ // The format length is from the formatting label function or the
+ // label length without the escaping exclamation (!) mark.
+ formatLength = formattingLabel ? _.trigger(formattingLabel, calendar, [value, parsingObject]) : label.replace(/^!/, '').length
+
+ // If there's a format label, split the value up to the format length.
+ // Then add it to the parsing object with appropriate label.
+ if (formattingLabel) {
+ parsingObject[label] = value.substr(0, formatLength)
+ }
+
+ // Update the value as the substring from format length to end.
+ value = value.substr(formatLength)
+ })
+
+ // Compensate for month 0index.
+ return [
+ parsingObject.yyyy || parsingObject.yy,
+ +( parsingObject.mm || parsingObject.m ) - 1,
+ parsingObject.dd || parsingObject.d
+ ]
+ } //DatePicker.prototype.parse
+
+
+ /**
+ * Various formats to display the object in.
+ */
+ DatePicker.prototype.formats = (function () {
+
+ // Return the length of the first word in a collection.
+ function getWordLengthFromCollection(string, collection, dateObject) {
+
+ // Grab the first word from the string.
+ var word = string.match(/\w+/)[0]
+
+ // If there's no month index, add it to the date object
+ if (!dateObject.mm && !dateObject.m) {
+ dateObject.m = collection.indexOf(word) + 1
+ }
+
+ // Return the length of the word.
+ return word.length
+ }
+
+ // Get the length of the first word in a string.
+ function getFirstWordLength(string) {
+ return string.match(/\w+/)[0].length
+ }
+
+ return {
+
+ d: function (string, dateObject) {
+
+ // If there's string, then get the digits length.
+ // Otherwise return the selected date.
+ return string ? _.digits(string) : dateObject.date
+ },
+ dd: function (string, dateObject) {
+
+ // If there's a string, then the length is always 2.
+ // Otherwise return the selected date with a leading zero.
+ return string ? 2 : _.lead(dateObject.date)
+ },
+ ddd: function (string, dateObject) {
+
+ // If there's a string, then get the length of the first word.
+ // Otherwise return the short selected weekday.
+ return string ? getFirstWordLength(string) : this.settings.weekdaysShort[dateObject.day]
+ },
+ dddd: function (string, dateObject) {
+
+ // If there's a string, then get the length of the first word.
+ // Otherwise return the full selected weekday.
+ return string ? getFirstWordLength(string) : this.settings.weekdaysFull[dateObject.day]
+ },
+ m: function (string, dateObject) {
+
+ // If there's a string, then get the length of the digits
+ // Otherwise return the selected month with 0index compensation.
+ return string ? _.digits(string) : dateObject.month + 1
+ },
+ mm: function (string, dateObject) {
+
+ // If there's a string, then the length is always 2.
+ // Otherwise return the selected month with 0index and leading zero.
+ return string ? 2 : _.lead(dateObject.month + 1)
+ },
+ mmm: function (string, dateObject) {
+
+ var collection = this.settings.monthsShort
+
+ // If there's a string, get length of the relevant month from the short
+ // months collection. Otherwise return the selected month from that collection.
+ return string ? getWordLengthFromCollection(string, collection, dateObject) : collection[dateObject.month]
+ },
+ mmmm: function (string, dateObject) {
+
+ var collection = this.settings.monthsFull
+
+ // If there's a string, get length of the relevant month from the full
+ // months collection. Otherwise return the selected month from that collection.
+ return string ? getWordLengthFromCollection(string, collection, dateObject) : collection[dateObject.month]
+ },
+ yy: function (string, dateObject) {
+
+ // If there's a string, then the length is always 2.
+ // Otherwise return the selected year by slicing out the first 2 digits.
+ return string ? 2 : ( '' + dateObject.year ).slice(2)
+ },
+ yyyy: function (string, dateObject) {
+
+ // If there's a string, then the length is always 4.
+ // Otherwise return the selected year.
+ return string ? 4 : dateObject.year
+ },
+
+ // Create an array by splitting the formatting string passed.
+ toArray: function (formatString) {
+ return formatString.split(/(d{1,4}|m{1,4}|y{4}|yy|!.)/g)
+ },
+
+ // Format an object into a string using the formatting options.
+ toString: function (formatString, itemObject) {
+ var calendar = this
+ return calendar.formats.toArray(formatString).map(function (label) {
+ return _.trigger(calendar.formats[label], calendar, [0, itemObject]) || label.replace(/^!/, '')
+ }).join('')
+ }
+ }
+ })() //DatePicker.prototype.formats
+
+
+ /**
+ * Check if two date units are the exact.
+ */
+ DatePicker.prototype.isDateExact = function (one, two) {
+
+ var calendar = this
+
+ // When we’re working with weekdays, do a direct comparison.
+ if (
+ ( _.isInteger(one) && _.isInteger(two) ) ||
+ ( typeof one == 'boolean' && typeof two == 'boolean' )
+ ) {
+ return one === two
+ }
+
+ // When we’re working with date representations, compare the “pick” value.
+ if (
+ ( _.isDate(one) || $.isArray(one) ) &&
+ ( _.isDate(two) || $.isArray(two) )
+ ) {
+ return calendar.create(one).pick === calendar.create(two).pick
+ }
+
+ // When we’re working with range objects, compare the “from” and “to”.
+ if ($.isPlainObject(one) && $.isPlainObject(two)) {
+ return calendar.isDateExact(one.from, two.from) && calendar.isDateExact(one.to, two.to)
+ }
+
+ return false
+ }
+
+
+ /**
+ * Check if two date units overlap.
+ */
+ DatePicker.prototype.isDateOverlap = function (one, two) {
+
+ var calendar = this,
+ firstDay = calendar.settings.firstDay ? 1 : 0
+
+ // When we’re working with a weekday index, compare the days.
+ if (_.isInteger(one) && ( _.isDate(two) || $.isArray(two) )) {
+ one = one % 7 + firstDay
+ return one === calendar.create(two).day + 1
+ }
+ if (_.isInteger(two) && ( _.isDate(one) || $.isArray(one) )) {
+ two = two % 7 + firstDay
+ return two === calendar.create(one).day + 1
+ }
+
+ // When we’re working with range objects, check if the ranges overlap.
+ if ($.isPlainObject(one) && $.isPlainObject(two)) {
+ return calendar.overlapRanges(one, two)
+ }
+
+ return false
+ }
+
+
+ /**
+ * Flip the “enabled” state.
+ */
+ DatePicker.prototype.flipEnable = function (val) {
+ var itemObject = this.item
+ itemObject.enable = val || (itemObject.enable == -1 ? 1 : -1)
+ }
+
+
+ /**
+ * Mark a collection of dates as “disabled”.
+ */
+ DatePicker.prototype.deactivate = function (type, datesToDisable) {
+
+ var calendar = this,
+ disabledItems = calendar.item.disable.slice(0)
+
+
+ // If we’re flipping, that’s all we need to do.
+ if (datesToDisable == 'flip') {
+ calendar.flipEnable()
+ }
+
+ else if (datesToDisable === false) {
+ calendar.flipEnable(1)
+ disabledItems = []
+ }
+
+ else if (datesToDisable === true) {
+ calendar.flipEnable(-1)
+ disabledItems = []
+ }
+
+ // Otherwise go through the dates to disable.
+ else {
+
+ datesToDisable.map(function (unitToDisable) {
+
+ var matchFound
+
+ // When we have disabled items, check for matches.
+ // If something is matched, immediately break out.
+ for (var index = 0; index < disabledItems.length; index += 1) {
+ if (calendar.isDateExact(unitToDisable, disabledItems[index])) {
+ matchFound = true
+ break
+ }
+ }
+
+ // If nothing was found, add the validated unit to the collection.
+ if (!matchFound) {
+ if (
+ _.isInteger(unitToDisable) ||
+ _.isDate(unitToDisable) ||
+ $.isArray(unitToDisable) ||
+ ( $.isPlainObject(unitToDisable) && unitToDisable.from && unitToDisable.to )
+ ) {
+ disabledItems.push(unitToDisable)
+ }
+ }
+ })
+ }
+
+ // Return the updated collection.
+ return disabledItems
+ } //DatePicker.prototype.deactivate
+
+
+ /**
+ * Mark a collection of dates as “enabled”.
+ */
+ DatePicker.prototype.activate = function (type, datesToEnable) {
+
+ var calendar = this,
+ disabledItems = calendar.item.disable,
+ disabledItemsCount = disabledItems.length
+
+ // If we’re flipping, that’s all we need to do.
+ if (datesToEnable == 'flip') {
+ calendar.flipEnable()
+ }
+
+ else if (datesToEnable === true) {
+ calendar.flipEnable(1)
+ disabledItems = []
+ }
+
+ else if (datesToEnable === false) {
+ calendar.flipEnable(-1)
+ disabledItems = []
+ }
+
+ // Otherwise go through the disabled dates.
+ else {
+
+ datesToEnable.map(function (unitToEnable) {
+
+ var matchFound,
+ disabledUnit,
+ index,
+ isExactRange
+
+ // Go through the disabled items and try to find a match.
+ for (index = 0; index < disabledItemsCount; index += 1) {
+
+ disabledUnit = disabledItems[index]
+
+ // When an exact match is found, remove it from the collection.
+ if (calendar.isDateExact(disabledUnit, unitToEnable)) {
+ matchFound = disabledItems[index] = null
+ isExactRange = true
+ break
+ }
+
+ // When an overlapped match is found, add the “inverted” state to it.
+ else if (calendar.isDateOverlap(disabledUnit, unitToEnable)) {
+ if ($.isPlainObject(unitToEnable)) {
+ unitToEnable.inverted = true
+ matchFound = unitToEnable
+ }
+ else if ($.isArray(unitToEnable)) {
+ matchFound = unitToEnable
+ if (!matchFound[3]) matchFound.push('inverted')
+ }
+ else if (_.isDate(unitToEnable)) {
+ matchFound = [unitToEnable.getFullYear(), unitToEnable.getMonth(), unitToEnable.getDate(), 'inverted']
+ }
+ break
+ }
+ }
+
+ // If a match was found, remove a previous duplicate entry.
+ if (matchFound) for (index = 0; index < disabledItemsCount; index += 1) {
+ if (calendar.isDateExact(disabledItems[index], unitToEnable)) {
+ disabledItems[index] = null
+ break
+ }
+ }
+
+ // In the event that we’re dealing with an exact range of dates,
+ // make sure there are no “inverted” dates because of it.
+ if (isExactRange) for (index = 0; index < disabledItemsCount; index += 1) {
+ if (calendar.isDateOverlap(disabledItems[index], unitToEnable)) {
+ disabledItems[index] = null
+ break
+ }
+ }
+
+ // If something is still matched, add it into the collection.
+ if (matchFound) {
+ disabledItems.push(matchFound)
+ }
+ })
+ }
+
+ // Return the updated collection.
+ return disabledItems.filter(function (val) {
+ return val != null
+ })
+ } //DatePicker.prototype.activate
+
+
+ /**
+ * Create a string for the nodes in the picker.
+ */
+ DatePicker.prototype.nodes = function (isOpen) {
+
+ var
+ calendar = this,
+ settings = calendar.settings,
+ calendarItem = calendar.item,
+ nowObject = calendarItem.now,
+ selectedObject = calendarItem.select,
+ highlightedObject = calendarItem.highlight,
+ viewsetObject = calendarItem.view,
+ disabledCollection = calendarItem.disable,
+ minLimitObject = calendarItem.min,
+ maxLimitObject = calendarItem.max,
+
+
+ // Create the calendar table head using a copy of weekday labels collection.
+ // * We do a copy so we don't mutate the original array.
+ tableHead = (function (collection, fullCollection) {
+
+ // If the first day should be Monday, move Sunday to the end.
+ if (settings.firstDay) {
+ collection.push(collection.shift())
+ fullCollection.push(fullCollection.shift())
+ }
+
+ // Create and return the table head group.
+ return _.node(
+ 'thead',
+ _.node(
+ 'tr',
+ _.group({
+ min: 0,
+ max: DAYS_IN_WEEK - 1,
+ i: 1,
+ node: 'th',
+ item: function (counter) {
+ return [
+ collection[counter],
+ settings.klass.weekdays,
+ 'scope=col title="' + fullCollection[counter] + '"'
+ ]
+ }
+ })
+ )
+ ) //endreturn
+
+ // Materialize modified
+ })(( settings.showWeekdaysFull ? settings.weekdaysFull : settings.weekdaysLetter ).slice(0), settings.weekdaysFull.slice(0)), //tableHead
+
+
+ // Create the nav for next/prev month.
+ createMonthNav = function (next) {
+
+ // Otherwise, return the created month tag.
+ return _.node(
+ 'div',
+ ' ',
+ settings.klass['nav' + ( next ? 'Next' : 'Prev' )] + (
+
+ // If the focused month is outside the range, disabled the button.
+ ( next && viewsetObject.year >= maxLimitObject.year && viewsetObject.month >= maxLimitObject.month ) ||
+ ( !next && viewsetObject.year <= minLimitObject.year && viewsetObject.month <= minLimitObject.month ) ?
+ ' ' + settings.klass.navDisabled : ''
+ ),
+ 'data-nav=' + ( next || -1 ) + ' ' +
+ _.ariaAttr({
+ role: 'button',
+ controls: calendar.$node[0].id + '_table'
+ }) + ' ' +
+ 'title="' + (next ? settings.labelMonthNext : settings.labelMonthPrev ) + '"'
+ ) //endreturn
+ }, //createMonthNav
+
+
+ // Create the month label.
+ //Materialize modified
+ createMonthLabel = function (override) {
+
+ var monthsCollection = settings.showMonthsShort ? settings.monthsShort : settings.monthsFull
+
+ // Materialize modified
+ if (override == "short_months") {
+ monthsCollection = settings.monthsShort;
+ }
+
+ // If there are months to select, add a dropdown menu.
+ if (settings.selectMonths && override == undefined) {
+
+ return _.node('select',
+ _.group({
+ min: 0,
+ max: 11,
+ i: 1,
+ node: 'option',
+ item: function (loopedMonth) {
+
+ return [
+
+ // The looped month and no classes.
+ monthsCollection[loopedMonth], 0,
+
+ // Set the value and selected index.
+ 'value=' + loopedMonth +
+ ( viewsetObject.month == loopedMonth ? ' selected' : '' ) +
+ (
+ (
+ ( viewsetObject.year == minLimitObject.year && loopedMonth < minLimitObject.month ) ||
+ ( viewsetObject.year == maxLimitObject.year && loopedMonth > maxLimitObject.month )
+ ) ?
+ ' disabled' : ''
+ )
+ ]
+ }
+ }),
+ settings.klass.selectMonth + ' browser-default',
+ ( isOpen ? '' : 'disabled' ) + ' ' +
+ _.ariaAttr({controls: calendar.$node[0].id + '_table'}) + ' ' +
+ 'title="' + settings.labelMonthSelect + '"'
+ )
+ }
+
+ // Materialize modified
+ if (override == "short_months")
+ if (selectedObject != null)
+ return _.node('div', monthsCollection[selectedObject.month]);
+ else return _.node('div', monthsCollection[viewsetObject.month]);
+
+ // If there's a need for a month selector
+ return _.node('div', monthsCollection[viewsetObject.month], settings.klass.month)
+ }, //createMonthLabel
+
+
+ // Create the year label.
+ // Materialize modified
+ createYearLabel = function (override) {
+
+ var focusedYear = viewsetObject.year,
+
+ // If years selector is set to a literal "true", set it to 5. Otherwise
+ // divide in half to get half before and half after focused year.
+ numberYears = settings.selectYears === true ? 5 : ~~( settings.selectYears / 2 )
+
+ // If there are years to select, add a dropdown menu.
+ if (numberYears) {
+
+ var
+ minYear = minLimitObject.year,
+ maxYear = maxLimitObject.year,
+ lowestYear = focusedYear - numberYears,
+ highestYear = focusedYear + numberYears
+
+ // If the min year is greater than the lowest year, increase the highest year
+ // by the difference and set the lowest year to the min year.
+ if (minYear > lowestYear) {
+ highestYear += minYear - lowestYear
+ lowestYear = minYear
+ }
+
+ // If the max year is less than the highest year, decrease the lowest year
+ // by the lower of the two: available and needed years. Then set the
+ // highest year to the max year.
+ if (maxYear < highestYear) {
+
+ var availableYears = lowestYear - minYear,
+ neededYears = highestYear - maxYear
+
+ lowestYear -= availableYears > neededYears ? neededYears : availableYears
+ highestYear = maxYear
+ }
+
+ if (settings.selectYears && override == undefined) {
+ return _.node('select',
+ _.group({
+ min: lowestYear,
+ max: highestYear,
+ i: 1,
+ node: 'option',
+ item: function (loopedYear) {
+ return [
+
+ // The looped year and no classes.
+ loopedYear, 0,
+
+ // Set the value and selected index.
+ 'value=' + loopedYear + ( focusedYear == loopedYear ? ' selected' : '' )
+ ]
+ }
+ }),
+ settings.klass.selectYear + ' browser-default',
+ ( isOpen ? '' : 'disabled' ) + ' ' + _.ariaAttr({controls: calendar.$node[0].id + '_table'}) + ' ' +
+ 'title="' + settings.labelYearSelect + '"'
+ )
+ }
+ }
+
+ // Materialize modified
+ if (override == "raw")
+ return _.node('div', focusedYear)
+
+ // Otherwise just return the year focused
+ return _.node('div', focusedYear, settings.klass.year)
+ } //createYearLabel
+
+
+ // Materialize modified
+ createDayLabel = function () {
+ if (selectedObject != null)
+ return _.node('div', selectedObject.date)
+ else return _.node('div', nowObject.date)
+ }
+ createWeekdayLabel = function () {
+ var display_day;
+
+ if (selectedObject != null)
+ display_day = selectedObject.day;
+ else
+ display_day = nowObject.day;
+ var weekday = settings.weekdaysFull[display_day]
+ return weekday
+ }
+
+
+ // Create and return the entire calendar.
+ return _.node(
+ // Date presentation View
+ 'div',
+ _.node(
+ 'div',
+ createWeekdayLabel(),
+ "picker__weekday-display"
+ ) +
+ _.node(
+ // Div for short Month
+ 'div',
+ createMonthLabel("short_months"),
+ settings.klass.month_display
+ ) +
+ _.node(
+ // Div for Day
+ 'div',
+ createDayLabel(),
+ settings.klass.day_display
+ ) +
+ _.node(
+ // Div for Year
+ 'div',
+ createYearLabel("raw"),
+ settings.klass.year_display
+ ),
+ settings.klass.date_display
+ ) +
+ // Calendar container
+ _.node('div',
+ _.node('div',
+ ( settings.selectYears ? createMonthLabel() + createYearLabel() : createMonthLabel() + createYearLabel() ) +
+ createMonthNav() + createMonthNav(1),
+ settings.klass.header
+ ) + _.node(
+ 'table',
+ tableHead +
+ _.node(
+ 'tbody',
+ _.group({
+ min: 0,
+ max: WEEKS_IN_CALENDAR - 1,
+ i: 1,
+ node: 'tr',
+ item: function (rowCounter) {
+
+ // If Monday is the first day and the month starts on Sunday, shift the date back a week.
+ var shiftDateBy = settings.firstDay && calendar.create([viewsetObject.year, viewsetObject.month, 1]).day === 0 ? -7 : 0
+
+ return [
+ _.group({
+ min: DAYS_IN_WEEK * rowCounter - viewsetObject.day + shiftDateBy + 1, // Add 1 for weekday 0index
+ max: function () {
+ return this.min + DAYS_IN_WEEK - 1
+ },
+ i: 1,
+ node: 'td',
+ item: function (targetDate) {
+
+ // Convert the time date from a relative date to a target date.
+ targetDate = calendar.create([viewsetObject.year, viewsetObject.month, targetDate + ( settings.firstDay ? 1 : 0 )])
+
+ var isSelected = selectedObject && selectedObject.pick == targetDate.pick,
+ isHighlighted = highlightedObject && highlightedObject.pick == targetDate.pick,
+ isDisabled = disabledCollection && calendar.disabled(targetDate) || targetDate.pick < minLimitObject.pick || targetDate.pick > maxLimitObject.pick,
+ formattedDate = _.trigger(calendar.formats.toString, calendar, [settings.format, targetDate])
+
+ return [
+ _.node(
+ 'div',
+ targetDate.date,
+ (function (klasses) {
+
+ // Add the `infocus` or `outfocus` classes based on month in view.
+ klasses.push(viewsetObject.month == targetDate.month ? settings.klass.infocus : settings.klass.outfocus)
+
+ // Add the `today` class if needed.
+ if (nowObject.pick == targetDate.pick) {
+ klasses.push(settings.klass.now)
+ }
+
+ // Add the `selected` class if something's selected and the time matches.
+ if (isSelected) {
+ klasses.push(settings.klass.selected)
+ }
+
+ // Add the `highlighted` class if something's highlighted and the time matches.
+ if (isHighlighted) {
+ klasses.push(settings.klass.highlighted)
+ }
+
+ // Add the `disabled` class if something's disabled and the object matches.
+ if (isDisabled) {
+ klasses.push(settings.klass.disabled)
+ }
+
+ return klasses.join(' ')
+ })([settings.klass.day]),
+ 'data-pick=' + targetDate.pick + ' ' + _.ariaAttr({
+ role: 'gridcell',
+ label: formattedDate,
+ selected: isSelected && calendar.$node.val() === formattedDate ? true : null,
+ activedescendant: isHighlighted ? true : null,
+ disabled: isDisabled ? true : null
+ })
+ ),
+ '',
+ _.ariaAttr({role: 'presentation'})
+ ] //endreturn
+ }
+ })
+ ] //endreturn
+ }
+ })
+ ),
+ settings.klass.table,
+ 'id="' + calendar.$node[0].id + '_table' + '" ' + _.ariaAttr({
+ role: 'grid',
+ controls: calendar.$node[0].id,
+ readonly: true
+ })
+ )
+ , settings.klass.calendar_container) // end calendar
+
+ +
+
+ // * For Firefox forms to submit, make sure to set the buttons’ `type` attributes as “button”.
+ _.node(
+ 'div',
+ _.node('button', settings.today, "btn-flat picker__today",
+ 'type=button data-pick=' + nowObject.pick +
+ ( isOpen && !calendar.disabled(nowObject) ? '' : ' disabled' ) + ' ' +
+ _.ariaAttr({controls: calendar.$node[0].id})) +
+ _.node('button', settings.clear, "btn-flat picker__clear",
+ 'type=button data-clear=1' +
+ ( isOpen ? '' : ' disabled' ) + ' ' +
+ _.ariaAttr({controls: calendar.$node[0].id})) +
+ _.node('button', settings.close, "btn-flat picker__close",
+ 'type=button data-close=true ' +
+ ( isOpen ? '' : ' disabled' ) + ' ' +
+ _.ariaAttr({controls: calendar.$node[0].id})),
+ settings.klass.footer
+ ) //endreturn
+ } //DatePicker.prototype.nodes
+
+
+ /**
+ * The date picker defaults.
+ */
+ DatePicker.defaults = (function (prefix) {
+
+ return {
+
+ // The title label to use for the month nav buttons
+ labelMonthNext: 'Next month',
+ labelMonthPrev: 'Previous month',
+
+ // The title label to use for the dropdown selectors
+ labelMonthSelect: 'Select a month',
+ labelYearSelect: 'Select a year',
+
+ // Months and weekdays
+ monthsFull: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
+ monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
+ weekdaysFull: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
+ weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
+
+ // Materialize modified
+ weekdaysLetter: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
+
+ // Today and clear
+ today: 'Today',
+ clear: 'Clear',
+ close: 'Close',
+
+ // The format to show on the `input` element
+ format: 'd mmmm, yyyy',
+
+ // Classes
+ klass: {
+
+ table: prefix + 'table',
+
+ header: prefix + 'header',
+
+
+ // Materialize Added klasses
+ date_display: prefix + 'date-display',
+ day_display: prefix + 'day-display',
+ month_display: prefix + 'month-display',
+ year_display: prefix + 'year-display',
+ calendar_container: prefix + 'calendar-container',
+ // end
+
+
+ navPrev: prefix + 'nav--prev',
+ navNext: prefix + 'nav--next',
+ navDisabled: prefix + 'nav--disabled',
+
+ month: prefix + 'month',
+ year: prefix + 'year',
+
+ selectMonth: prefix + 'select--month',
+ selectYear: prefix + 'select--year',
+
+ weekdays: prefix + 'weekday',
+
+ day: prefix + 'day',
+ disabled: prefix + 'day--disabled',
+ selected: prefix + 'day--selected',
+ highlighted: prefix + 'day--highlighted',
+ now: prefix + 'day--today',
+ infocus: prefix + 'day--infocus',
+ outfocus: prefix + 'day--outfocus',
+
+ footer: prefix + 'footer',
+
+ buttonClear: prefix + 'button--clear',
+ buttonToday: prefix + 'button--today',
+ buttonClose: prefix + 'button--close'
+ }
+ }
+ })(Picker.klasses().picker + '__')
+
+
+ /**
+ * Extend the picker to add the date picker.
+ */
+ Picker.extend('pickadate', DatePicker)
+
+
+}));
+
+
+;(function ($) {
+
+ $.fn.characterCounter = function () {
+ return this.each(function () {
+ var $input = $(this);
+ var $counterElement = $input.parent().find('span[class="character-counter"]');
+
+ // character counter has already been added appended to the parent container
+ if ($counterElement.length) {
+ return;
+ }
+
+ var itHasLengthAttribute = $input.attr('length') !== undefined;
+
+ if (itHasLengthAttribute) {
+ $input.on('input', updateCounter);
+ $input.on('focus', updateCounter);
+ $input.on('blur', removeCounterElement);
+
+ addCounterElement($input);
+ }
+
+ });
+ };
+
+ function updateCounter() {
+ var maxLength = +$(this).attr('length'),
+ actualLength = +$(this).val().length,
+ isValidLength = actualLength <= maxLength;
+
+ $(this).parent().find('span[class="character-counter"]')
+ .html(actualLength + '/' + maxLength);
+
+ addInputStyle(isValidLength, $(this));
+ }
+
+ function addCounterElement($input) {
+ var $counterElement = $input.parent().find('span[class="character-counter"]');
+
+ if ($counterElement.length) {
+ return;
+ }
+
+ $counterElement = $('
')
+ .addClass('character-counter')
+ .css('float', 'right')
+ .css('font-size', '12px')
+ .css('height', 1);
+
+ $input.parent().append($counterElement);
+ }
+
+ function removeCounterElement() {
+ $(this).parent().find('span[class="character-counter"]').html('');
+ }
+
+ function addInputStyle(isValidLength, $input) {
+ var inputHasInvalidClass = $input.hasClass('invalid');
+ if (isValidLength && inputHasInvalidClass) {
+ $input.removeClass('invalid');
+ }
+ else if (!isValidLength && !inputHasInvalidClass) {
+ $input.removeClass('valid');
+ $input.addClass('invalid');
+ }
+ }
+
+ $(document).ready(function () {
+ $('input, textarea').characterCounter();
+ });
+
+}(jQuery));
+;(function ($) {
+
+ var methods = {
+
+ init: function (options) {
+ var defaults = {
+ time_constant: 200, // ms
+ dist: -100, // zoom scale TODO: make this more intuitive as an option
+ shift: 0, // spacing for center image
+ padding: 0, // Padding between non center items
+ full_width: false, // Change to full width styles
+ indicators: false, // Toggle indicators
+ no_wrap: false // Don't wrap around and cycle through items.
+ };
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+
+ var images, offset, center, pressed, dim, count,
+ reference, referenceY, amplitude, target, velocity,
+ xform, frame, timestamp, ticker, dragged, vertical_dragged;
+ var $indicators = $('
');
+
+
+ // Initialize
+ var view = $(this);
+ var showIndicators = view.attr('data-indicators') || options.indicators;
+
+ // Don't double initialize.
+ if (view.hasClass('initialized')) {
+ // Redraw carousel.
+ $(this).trigger('carouselNext', [0.000001]);
+ return true;
+ }
+
+
+ // Options
+ if (options.full_width) {
+ options.dist = 0;
+ var firstImage = view.find('.carousel-item img').first();
+ if (firstImage.length) {
+ imageHeight = firstImage.on('load', function () {
+ view.css('height', $(this).height());
+ });
+ } else {
+ imageHeight = view.find('.carousel-item').first().height();
+ view.css('height', imageHeight);
+ }
+
+ // Offset fixed items when indicators.
+ if (showIndicators) {
+ view.find('.carousel-fixed-item').addClass('with-indicators');
+ }
+ }
+
+
+ view.addClass('initialized');
+ pressed = false;
+ offset = target = 0;
+ images = [];
+ item_width = view.find('.carousel-item').first().innerWidth();
+ dim = item_width * 2 + options.padding;
+
+ view.find('.carousel-item').each(function (i) {
+ images.push($(this)[0]);
+ if (showIndicators) {
+ var $indicator = $('
');
+
+ // Add active to first by default.
+ if (i === 0) {
+ $indicator.addClass('active');
+ }
+
+ // Handle clicks on indicators.
+ $indicator.click(function () {
+ var index = $(this).index();
+ cycleTo(index);
+ });
+ $indicators.append($indicator);
+ }
+ });
+
+ if (showIndicators) {
+ view.append($indicators);
+ }
+ count = images.length;
+
+
+ function setupEvents() {
+ if (typeof window.ontouchstart !== 'undefined') {
+ view[0].addEventListener('touchstart', tap);
+ view[0].addEventListener('touchmove', drag);
+ view[0].addEventListener('touchend', release);
+ }
+ view[0].addEventListener('mousedown', tap);
+ view[0].addEventListener('mousemove', drag);
+ view[0].addEventListener('mouseup', release);
+ view[0].addEventListener('mouseleave', release);
+ view[0].addEventListener('click', click);
+ }
+
+ function xpos(e) {
+ // touch event
+ if (e.targetTouches && (e.targetTouches.length >= 1)) {
+ return e.targetTouches[0].clientX;
+ }
+
+ // mouse event
+ return e.clientX;
+ }
+
+ function ypos(e) {
+ // touch event
+ if (e.targetTouches && (e.targetTouches.length >= 1)) {
+ return e.targetTouches[0].clientY;
+ }
+
+ // mouse event
+ return e.clientY;
+ }
+
+ function wrap(x) {
+ return (x >= count) ? (x % count) : (x < 0) ? wrap(count + (x % count)) : x;
+ }
+
+ function scroll(x) {
+ var i, half, delta, dir, tween, el, alignment, xTranslation;
+
+ offset = (typeof x === 'number') ? x : offset;
+ center = Math.floor((offset + dim / 2) / dim);
+ delta = offset - center * dim;
+ dir = (delta < 0) ? 1 : -1;
+ tween = -dir * delta * 2 / dim;
+ half = count >> 1;
+
+ if (!options.full_width) {
+ alignment = 'translateX(' + (view[0].clientWidth - item_width) / 2 + 'px) ';
+ alignment += 'translateY(' + (view[0].clientHeight - item_width) / 2 + 'px)';
+ } else {
+ alignment = 'translateX(0)';
+ }
+
+ // Set indicator active
+ if (showIndicators) {
+ var diff = (center % count);
+ var activeIndicator = $indicators.find('.indicator-item.active');
+ if (activeIndicator.index() !== diff) {
+ activeIndicator.removeClass('active');
+ $indicators.find('.indicator-item').eq(diff).addClass('active');
+ }
+ }
+
+ // center
+ // Don't show wrapped items.
+ if (!options.no_wrap || (center >= 0 && center < count)) {
+ el = images[wrap(center)];
+ el.style[xform] = alignment +
+ ' translateX(' + (-delta / 2) + 'px)' +
+ ' translateX(' + (dir * options.shift * tween * i) + 'px)' +
+ ' translateZ(' + (options.dist * tween) + 'px)';
+ el.style.zIndex = 0;
+ if (options.full_width) {
+ tweenedOpacity = 1;
+ }
+ else {
+ tweenedOpacity = 1 - 0.2 * tween;
+ }
+ el.style.opacity = tweenedOpacity;
+ el.style.display = 'block';
+ }
+
+ for (i = 1; i <= half; ++i) {
+ // right side
+ if (options.full_width) {
+ zTranslation = options.dist;
+ tweenedOpacity = (i === half && delta < 0) ? 1 - tween : 1;
+ } else {
+ zTranslation = options.dist * (i * 2 + tween * dir);
+ tweenedOpacity = 1 - 0.2 * (i * 2 + tween * dir);
+ }
+ // Don't show wrapped items.
+ if (!options.no_wrap || center + i < count) {
+ el = images[wrap(center + i)];
+ el.style[xform] = alignment +
+ ' translateX(' + (options.shift + (dim * i - delta) / 2) + 'px)' +
+ ' translateZ(' + zTranslation + 'px)';
+ el.style.zIndex = -i;
+ el.style.opacity = tweenedOpacity;
+ el.style.display = 'block';
+ }
+
+
+ // left side
+ if (options.full_width) {
+ zTranslation = options.dist;
+ tweenedOpacity = (i === half && delta > 0) ? 1 - tween : 1;
+ } else {
+ zTranslation = options.dist * (i * 2 - tween * dir);
+ tweenedOpacity = 1 - 0.2 * (i * 2 - tween * dir);
+ }
+ // Don't show wrapped items.
+ if (!options.no_wrap || center - i >= 0) {
+ el = images[wrap(center - i)];
+ el.style[xform] = alignment +
+ ' translateX(' + (-options.shift + (-dim * i - delta) / 2) + 'px)' +
+ ' translateZ(' + zTranslation + 'px)';
+ el.style.zIndex = -i;
+ el.style.opacity = tweenedOpacity;
+ el.style.display = 'block';
+ }
+ }
+
+ // center
+ // Don't show wrapped items.
+ if (!options.no_wrap || (center >= 0 && center < count)) {
+ el = images[wrap(center)];
+ el.style[xform] = alignment +
+ ' translateX(' + (-delta / 2) + 'px)' +
+ ' translateX(' + (dir * options.shift * tween) + 'px)' +
+ ' translateZ(' + (options.dist * tween) + 'px)';
+ el.style.zIndex = 0;
+ if (options.full_width) {
+ tweenedOpacity = 1;
+ }
+ else {
+ tweenedOpacity = 1 - 0.2 * tween;
+ }
+ el.style.opacity = tweenedOpacity;
+ el.style.display = 'block';
+ }
+ }
+
+ function track() {
+ var now, elapsed, delta, v;
+
+ now = Date.now();
+ elapsed = now - timestamp;
+ timestamp = now;
+ delta = offset - frame;
+ frame = offset;
+
+ v = 1000 * delta / (1 + elapsed);
+ velocity = 0.8 * v + 0.2 * velocity;
+ }
+
+ function autoScroll() {
+ var elapsed, delta;
+
+ if (amplitude) {
+ elapsed = Date.now() - timestamp;
+ delta = amplitude * Math.exp(-elapsed / options.time_constant);
+ if (delta > 2 || delta < -2) {
+ scroll(target - delta);
+ requestAnimationFrame(autoScroll);
+ } else {
+ scroll(target);
+ }
+ }
+ }
+
+ function click(e) {
+ // Disable clicks if carousel was dragged.
+ if (dragged) {
+ e.preventDefault();
+ e.stopPropagation();
+ return false;
+
+ } else if (!options.full_width) {
+ var clickedIndex = $(e.target).closest('.carousel-item').index();
+ var diff = (center % count) - clickedIndex;
+
+ // Disable clicks if carousel was shifted by click
+ if (diff !== 0) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ cycleTo(clickedIndex);
+ }
+ }
+
+ function cycleTo(n) {
+ var diff = (center % count) - n;
+
+ // Account for wraparound.
+ if (!options.no_wrap) {
+ if (diff < 0) {
+ if (Math.abs(diff + count) < Math.abs(diff)) {
+ diff += count;
+ }
+
+ } else if (diff > 0) {
+ if (Math.abs(diff - count) < diff) {
+ diff -= count;
+ }
+ }
+ }
+
+ // Call prev or next accordingly.
+ if (diff < 0) {
+ view.trigger('carouselNext', [Math.abs(diff)]);
+
+ } else if (diff > 0) {
+ view.trigger('carouselPrev', [diff]);
+ }
+ }
+
+ function tap(e) {
+ pressed = true;
+ dragged = false;
+ vertical_dragged = false;
+ reference = xpos(e);
+ referenceY = ypos(e);
+
+ velocity = amplitude = 0;
+ frame = offset;
+ timestamp = Date.now();
+ clearInterval(ticker);
+ ticker = setInterval(track, 100);
+
+ }
+
+ function drag(e) {
+ var x, delta, deltaY;
+ if (pressed) {
+ x = xpos(e);
+ y = ypos(e);
+ delta = reference - x;
+ deltaY = Math.abs(referenceY - y);
+ if (deltaY < 30 && !vertical_dragged) {
+ // If vertical scrolling don't allow dragging.
+ if (delta > 2 || delta < -2) {
+ dragged = true;
+ reference = x;
+ scroll(offset + delta);
+ }
+
+ } else if (dragged) {
+ // If dragging don't allow vertical scroll.
+ e.preventDefault();
+ e.stopPropagation();
+ return false;
+
+ } else {
+ // Vertical scrolling.
+ vertical_dragged = true;
+ }
+ }
+
+ if (dragged) {
+ // If dragging don't allow vertical scroll.
+ e.preventDefault();
+ e.stopPropagation();
+ return false;
+ }
+ }
+
+ function release(e) {
+ if (pressed) {
+ pressed = false;
+ } else {
+ return;
+ }
+
+ clearInterval(ticker);
+ target = offset;
+ if (velocity > 10 || velocity < -10) {
+ amplitude = 0.9 * velocity;
+ target = offset + amplitude;
+ }
+ target = Math.round(target / dim) * dim;
+
+ // No wrap of items.
+ if (options.no_wrap) {
+ if (target >= dim * (count - 1)) {
+ target = dim * (count - 1);
+ } else if (target < 0) {
+ target = 0;
+ }
+ }
+ amplitude = target - offset;
+ timestamp = Date.now();
+ requestAnimationFrame(autoScroll);
+
+ if (dragged) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ return false;
+ }
+
+ xform = 'transform';
+ ['webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
+ var e = prefix + 'Transform';
+ if (typeof document.body.style[e] !== 'undefined') {
+ xform = e;
+ return false;
+ }
+ return true;
+ });
+
+
+ window.onresize = scroll;
+
+ setupEvents();
+ scroll(offset);
+
+ $(this).on('carouselNext', function (e, n) {
+ if (n === undefined) {
+ n = 1;
+ }
+ target = offset + dim * n;
+ if (offset !== target) {
+ amplitude = target - offset;
+ timestamp = Date.now();
+ requestAnimationFrame(autoScroll);
+ }
+ });
+
+ $(this).on('carouselPrev', function (e, n) {
+ if (n === undefined) {
+ n = 1;
+ }
+ target = offset - dim * n;
+ if (offset !== target) {
+ amplitude = target - offset;
+ timestamp = Date.now();
+ requestAnimationFrame(autoScroll);
+ }
+ });
+
+ $(this).on('carouselSet', function (e, n) {
+ if (n === undefined) {
+ n = 0;
+ }
+ cycleTo(n);
+ });
+
+ });
+
+
+ },
+ next: function (n) {
+ $(this).trigger('carouselNext', [n]);
+ },
+ prev: function (n) {
+ $(this).trigger('carouselPrev', [n]);
+ },
+ set: function (n) {
+ $(this).trigger('carouselSet', [n]);
+ }
+ };
+
+
+ $.fn.carousel = function (methodOrOptions) {
+ if (methods[methodOrOptions]) {
+ return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
+ } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
+ // Default to "init"
+ return methods.init.apply(this, arguments);
+ } else {
+ $.error('Method ' + methodOrOptions + ' does not exist on jQuery.carousel');
+ }
+ }; // Plugin end
+}(jQuery));
\ No newline at end of file
diff --git a/scrummer/static/src/js/lib/external/moment.js b/scrummer/static/src/js/lib/external/moment.js
new file mode 100644
index 0000000..4549e58
--- /dev/null
+++ b/scrummer/static/src/js/lib/external/moment.js
@@ -0,0 +1,4301 @@
+//! moment.js
+//! version : 2.17.1
+//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
+//! license : MIT
+//! momentjs.com
+
+;(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ global.moment = factory()
+}(this, (function () { 'use strict';
+
+var hookCallback;
+
+function hooks () {
+ return hookCallback.apply(null, arguments);
+}
+
+// This is done to register the method called with moment()
+// without creating circular dependencies.
+function setHookCallback (callback) {
+ hookCallback = callback;
+}
+
+function isArray(input) {
+ return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
+}
+
+function isObject(input) {
+ // IE8 will treat undefined and null as object if it wasn't for
+ // input != null
+ return input != null && Object.prototype.toString.call(input) === '[object Object]';
+}
+
+function isObjectEmpty(obj) {
+ var k;
+ for (k in obj) {
+ // even if its not own property I'd still call it non-empty
+ return false;
+ }
+ return true;
+}
+
+function isNumber(input) {
+ return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
+}
+
+function isDate(input) {
+ return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
+}
+
+function map(arr, fn) {
+ var res = [], i;
+ for (i = 0; i < arr.length; ++i) {
+ res.push(fn(arr[i], i));
+ }
+ return res;
+}
+
+function hasOwnProp(a, b) {
+ return Object.prototype.hasOwnProperty.call(a, b);
+}
+
+function extend(a, b) {
+ for (var i in b) {
+ if (hasOwnProp(b, i)) {
+ a[i] = b[i];
+ }
+ }
+
+ if (hasOwnProp(b, 'toString')) {
+ a.toString = b.toString;
+ }
+
+ if (hasOwnProp(b, 'valueOf')) {
+ a.valueOf = b.valueOf;
+ }
+
+ return a;
+}
+
+function createUTC (input, format, locale, strict) {
+ return createLocalOrUTC(input, format, locale, strict, true).utc();
+}
+
+function defaultParsingFlags() {
+ // We need to deep clone this object.
+ return {
+ empty : false,
+ unusedTokens : [],
+ unusedInput : [],
+ overflow : -2,
+ charsLeftOver : 0,
+ nullInput : false,
+ invalidMonth : null,
+ invalidFormat : false,
+ userInvalidated : false,
+ iso : false,
+ parsedDateParts : [],
+ meridiem : null
+ };
+}
+
+function getParsingFlags(m) {
+ if (m._pf == null) {
+ m._pf = defaultParsingFlags();
+ }
+ return m._pf;
+}
+
+var some;
+if (Array.prototype.some) {
+ some = Array.prototype.some;
+} else {
+ some = function (fun) {
+ var t = Object(this);
+ var len = t.length >>> 0;
+
+ for (var i = 0; i < len; i++) {
+ if (i in t && fun.call(this, t[i], i, t)) {
+ return true;
+ }
+ }
+
+ return false;
+ };
+}
+
+var some$1 = some;
+
+function isValid(m) {
+ if (m._isValid == null) {
+ var flags = getParsingFlags(m);
+ var parsedParts = some$1.call(flags.parsedDateParts, function (i) {
+ return i != null;
+ });
+ var isNowValid = !isNaN(m._d.getTime()) &&
+ flags.overflow < 0 &&
+ !flags.empty &&
+ !flags.invalidMonth &&
+ !flags.invalidWeekday &&
+ !flags.nullInput &&
+ !flags.invalidFormat &&
+ !flags.userInvalidated &&
+ (!flags.meridiem || (flags.meridiem && parsedParts));
+
+ if (m._strict) {
+ isNowValid = isNowValid &&
+ flags.charsLeftOver === 0 &&
+ flags.unusedTokens.length === 0 &&
+ flags.bigHour === undefined;
+ }
+
+ if (Object.isFrozen == null || !Object.isFrozen(m)) {
+ m._isValid = isNowValid;
+ }
+ else {
+ return isNowValid;
+ }
+ }
+ return m._isValid;
+}
+
+function createInvalid (flags) {
+ var m = createUTC(NaN);
+ if (flags != null) {
+ extend(getParsingFlags(m), flags);
+ }
+ else {
+ getParsingFlags(m).userInvalidated = true;
+ }
+
+ return m;
+}
+
+function isUndefined(input) {
+ return input === void 0;
+}
+
+// Plugins that add properties should also add the key here (null value),
+// so we can properly clone ourselves.
+var momentProperties = hooks.momentProperties = [];
+
+function copyConfig(to, from) {
+ var i, prop, val;
+
+ if (!isUndefined(from._isAMomentObject)) {
+ to._isAMomentObject = from._isAMomentObject;
+ }
+ if (!isUndefined(from._i)) {
+ to._i = from._i;
+ }
+ if (!isUndefined(from._f)) {
+ to._f = from._f;
+ }
+ if (!isUndefined(from._l)) {
+ to._l = from._l;
+ }
+ if (!isUndefined(from._strict)) {
+ to._strict = from._strict;
+ }
+ if (!isUndefined(from._tzm)) {
+ to._tzm = from._tzm;
+ }
+ if (!isUndefined(from._isUTC)) {
+ to._isUTC = from._isUTC;
+ }
+ if (!isUndefined(from._offset)) {
+ to._offset = from._offset;
+ }
+ if (!isUndefined(from._pf)) {
+ to._pf = getParsingFlags(from);
+ }
+ if (!isUndefined(from._locale)) {
+ to._locale = from._locale;
+ }
+
+ if (momentProperties.length > 0) {
+ for (i in momentProperties) {
+ prop = momentProperties[i];
+ val = from[prop];
+ if (!isUndefined(val)) {
+ to[prop] = val;
+ }
+ }
+ }
+
+ return to;
+}
+
+var updateInProgress = false;
+
+// Moment prototype object
+function Moment(config) {
+ copyConfig(this, config);
+ this._d = new Date(config._d != null ? config._d.getTime() : NaN);
+ if (!this.isValid()) {
+ this._d = new Date(NaN);
+ }
+ // Prevent infinite loop in case updateOffset creates new moment
+ // objects.
+ if (updateInProgress === false) {
+ updateInProgress = true;
+ hooks.updateOffset(this);
+ updateInProgress = false;
+ }
+}
+
+function isMoment (obj) {
+ return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
+}
+
+function absFloor (number) {
+ if (number < 0) {
+ // -0 -> 0
+ return Math.ceil(number) || 0;
+ } else {
+ return Math.floor(number);
+ }
+}
+
+function toInt(argumentForCoercion) {
+ var coercedNumber = +argumentForCoercion,
+ value = 0;
+
+ if (coercedNumber !== 0 && isFinite(coercedNumber)) {
+ value = absFloor(coercedNumber);
+ }
+
+ return value;
+}
+
+// compare two arrays, return the number of differences
+function compareArrays(array1, array2, dontConvert) {
+ var len = Math.min(array1.length, array2.length),
+ lengthDiff = Math.abs(array1.length - array2.length),
+ diffs = 0,
+ i;
+ for (i = 0; i < len; i++) {
+ if ((dontConvert && array1[i] !== array2[i]) ||
+ (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
+ diffs++;
+ }
+ }
+ return diffs + lengthDiff;
+}
+
+function warn(msg) {
+ if (hooks.suppressDeprecationWarnings === false &&
+ (typeof console !== 'undefined') && console.warn) {
+ console.warn('Deprecation warning: ' + msg);
+ }
+}
+
+function deprecate(msg, fn) {
+ var firstTime = true;
+
+ return extend(function () {
+ if (hooks.deprecationHandler != null) {
+ hooks.deprecationHandler(null, msg);
+ }
+ if (firstTime) {
+ var args = [];
+ var arg;
+ for (var i = 0; i < arguments.length; i++) {
+ arg = '';
+ if (typeof arguments[i] === 'object') {
+ arg += '\n[' + i + '] ';
+ for (var key in arguments[0]) {
+ arg += key + ': ' + arguments[0][key] + ', ';
+ }
+ arg = arg.slice(0, -2); // Remove trailing comma and space
+ } else {
+ arg = arguments[i];
+ }
+ args.push(arg);
+ }
+ warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
+ firstTime = false;
+ }
+ return fn.apply(this, arguments);
+ }, fn);
+}
+
+var deprecations = {};
+
+function deprecateSimple(name, msg) {
+ if (hooks.deprecationHandler != null) {
+ hooks.deprecationHandler(name, msg);
+ }
+ if (!deprecations[name]) {
+ warn(msg);
+ deprecations[name] = true;
+ }
+}
+
+hooks.suppressDeprecationWarnings = false;
+hooks.deprecationHandler = null;
+
+function isFunction(input) {
+ return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
+}
+
+function set (config) {
+ var prop, i;
+ for (i in config) {
+ prop = config[i];
+ if (isFunction(prop)) {
+ this[i] = prop;
+ } else {
+ this['_' + i] = prop;
+ }
+ }
+ this._config = config;
+ // Lenient ordinal parsing accepts just a number in addition to
+ // number + (possibly) stuff coming from _ordinalParseLenient.
+ this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
+}
+
+function mergeConfigs(parentConfig, childConfig) {
+ var res = extend({}, parentConfig), prop;
+ for (prop in childConfig) {
+ if (hasOwnProp(childConfig, prop)) {
+ if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
+ res[prop] = {};
+ extend(res[prop], parentConfig[prop]);
+ extend(res[prop], childConfig[prop]);
+ } else if (childConfig[prop] != null) {
+ res[prop] = childConfig[prop];
+ } else {
+ delete res[prop];
+ }
+ }
+ }
+ for (prop in parentConfig) {
+ if (hasOwnProp(parentConfig, prop) &&
+ !hasOwnProp(childConfig, prop) &&
+ isObject(parentConfig[prop])) {
+ // make sure changes to properties don't modify parent config
+ res[prop] = extend({}, res[prop]);
+ }
+ }
+ return res;
+}
+
+function Locale(config) {
+ if (config != null) {
+ this.set(config);
+ }
+}
+
+var keys;
+
+if (Object.keys) {
+ keys = Object.keys;
+} else {
+ keys = function (obj) {
+ var i, res = [];
+ for (i in obj) {
+ if (hasOwnProp(obj, i)) {
+ res.push(i);
+ }
+ }
+ return res;
+ };
+}
+
+var keys$1 = keys;
+
+var defaultCalendar = {
+ sameDay : '[Today at] LT',
+ nextDay : '[Tomorrow at] LT',
+ nextWeek : 'dddd [at] LT',
+ lastDay : '[Yesterday at] LT',
+ lastWeek : '[Last] dddd [at] LT',
+ sameElse : 'L'
+};
+
+function calendar (key, mom, now) {
+ var output = this._calendar[key] || this._calendar['sameElse'];
+ return isFunction(output) ? output.call(mom, now) : output;
+}
+
+var defaultLongDateFormat = {
+ LTS : 'h:mm:ss A',
+ LT : 'h:mm A',
+ L : 'MM/DD/YYYY',
+ LL : 'MMMM D, YYYY',
+ LLL : 'MMMM D, YYYY h:mm A',
+ LLLL : 'dddd, MMMM D, YYYY h:mm A'
+};
+
+function longDateFormat (key) {
+ var format = this._longDateFormat[key],
+ formatUpper = this._longDateFormat[key.toUpperCase()];
+
+ if (format || !formatUpper) {
+ return format;
+ }
+
+ this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
+ return val.slice(1);
+ });
+
+ return this._longDateFormat[key];
+}
+
+var defaultInvalidDate = 'Invalid date';
+
+function invalidDate () {
+ return this._invalidDate;
+}
+
+var defaultOrdinal = '%d';
+var defaultOrdinalParse = /\d{1,2}/;
+
+function ordinal (number) {
+ return this._ordinal.replace('%d', number);
+}
+
+var defaultRelativeTime = {
+ future : 'in %s',
+ past : '%s ago',
+ s : 'a few seconds',
+ m : 'a minute',
+ mm : '%d minutes',
+ h : 'an hour',
+ hh : '%d hours',
+ d : 'a day',
+ dd : '%d days',
+ M : 'a month',
+ MM : '%d months',
+ y : 'a year',
+ yy : '%d years'
+};
+
+function relativeTime (number, withoutSuffix, string, isFuture) {
+ var output = this._relativeTime[string];
+ return (isFunction(output)) ?
+ output(number, withoutSuffix, string, isFuture) :
+ output.replace(/%d/i, number);
+}
+
+function pastFuture (diff, output) {
+ var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
+ return isFunction(format) ? format(output) : format.replace(/%s/i, output);
+}
+
+var aliases = {};
+
+function addUnitAlias (unit, shorthand) {
+ var lowerCase = unit.toLowerCase();
+ aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
+}
+
+function normalizeUnits(units) {
+ return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
+}
+
+function normalizeObjectUnits(inputObject) {
+ var normalizedInput = {},
+ normalizedProp,
+ prop;
+
+ for (prop in inputObject) {
+ if (hasOwnProp(inputObject, prop)) {
+ normalizedProp = normalizeUnits(prop);
+ if (normalizedProp) {
+ normalizedInput[normalizedProp] = inputObject[prop];
+ }
+ }
+ }
+
+ return normalizedInput;
+}
+
+var priorities = {};
+
+function addUnitPriority(unit, priority) {
+ priorities[unit] = priority;
+}
+
+function getPrioritizedUnits(unitsObj) {
+ var units = [];
+ for (var u in unitsObj) {
+ units.push({unit: u, priority: priorities[u]});
+ }
+ units.sort(function (a, b) {
+ return a.priority - b.priority;
+ });
+ return units;
+}
+
+function makeGetSet (unit, keepTime) {
+ return function (value) {
+ if (value != null) {
+ set$1(this, unit, value);
+ hooks.updateOffset(this, keepTime);
+ return this;
+ } else {
+ return get(this, unit);
+ }
+ };
+}
+
+function get (mom, unit) {
+ return mom.isValid() ?
+ mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
+}
+
+function set$1 (mom, unit, value) {
+ if (mom.isValid()) {
+ mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
+ }
+}
+
+// MOMENTS
+
+function stringGet (units) {
+ units = normalizeUnits(units);
+ if (isFunction(this[units])) {
+ return this[units]();
+ }
+ return this;
+}
+
+
+function stringSet (units, value) {
+ if (typeof units === 'object') {
+ units = normalizeObjectUnits(units);
+ var prioritized = getPrioritizedUnits(units);
+ for (var i = 0; i < prioritized.length; i++) {
+ this[prioritized[i].unit](units[prioritized[i].unit]);
+ }
+ } else {
+ units = normalizeUnits(units);
+ if (isFunction(this[units])) {
+ return this[units](value);
+ }
+ }
+ return this;
+}
+
+function zeroFill(number, targetLength, forceSign) {
+ var absNumber = '' + Math.abs(number),
+ zerosToFill = targetLength - absNumber.length,
+ sign = number >= 0;
+ return (sign ? (forceSign ? '+' : '') : '-') +
+ Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
+}
+
+var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
+
+var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
+
+var formatFunctions = {};
+
+var formatTokenFunctions = {};
+
+// token: 'M'
+// padded: ['MM', 2]
+// ordinal: 'Mo'
+// callback: function () { this.month() + 1 }
+function addFormatToken (token, padded, ordinal, callback) {
+ var func = callback;
+ if (typeof callback === 'string') {
+ func = function () {
+ return this[callback]();
+ };
+ }
+ if (token) {
+ formatTokenFunctions[token] = func;
+ }
+ if (padded) {
+ formatTokenFunctions[padded[0]] = function () {
+ return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
+ };
+ }
+ if (ordinal) {
+ formatTokenFunctions[ordinal] = function () {
+ return this.localeData().ordinal(func.apply(this, arguments), token);
+ };
+ }
+}
+
+function removeFormattingTokens(input) {
+ if (input.match(/\[[\s\S]/)) {
+ return input.replace(/^\[|\]$/g, '');
+ }
+ return input.replace(/\\/g, '');
+}
+
+function makeFormatFunction(format) {
+ var array = format.match(formattingTokens), i, length;
+
+ for (i = 0, length = array.length; i < length; i++) {
+ if (formatTokenFunctions[array[i]]) {
+ array[i] = formatTokenFunctions[array[i]];
+ } else {
+ array[i] = removeFormattingTokens(array[i]);
+ }
+ }
+
+ return function (mom) {
+ var output = '', i;
+ for (i = 0; i < length; i++) {
+ output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
+ }
+ return output;
+ };
+}
+
+// format date using native date object
+function formatMoment(m, format) {
+ if (!m.isValid()) {
+ return m.localeData().invalidDate();
+ }
+
+ format = expandFormat(format, m.localeData());
+ formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
+
+ return formatFunctions[format](m);
+}
+
+function expandFormat(format, locale) {
+ var i = 5;
+
+ function replaceLongDateFormatTokens(input) {
+ return locale.longDateFormat(input) || input;
+ }
+
+ localFormattingTokens.lastIndex = 0;
+ while (i >= 0 && localFormattingTokens.test(format)) {
+ format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
+ localFormattingTokens.lastIndex = 0;
+ i -= 1;
+ }
+
+ return format;
+}
+
+var match1 = /\d/; // 0 - 9
+var match2 = /\d\d/; // 00 - 99
+var match3 = /\d{3}/; // 000 - 999
+var match4 = /\d{4}/; // 0000 - 9999
+var match6 = /[+-]?\d{6}/; // -999999 - 999999
+var match1to2 = /\d\d?/; // 0 - 99
+var match3to4 = /\d\d\d\d?/; // 999 - 9999
+var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
+var match1to3 = /\d{1,3}/; // 0 - 999
+var match1to4 = /\d{1,4}/; // 0 - 9999
+var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
+
+var matchUnsigned = /\d+/; // 0 - inf
+var matchSigned = /[+-]?\d+/; // -inf - inf
+
+var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
+var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
+
+var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
+
+// any word (or two) characters or numbers including two/three word month in arabic.
+// includes scottish gaelic two word and hyphenated months
+var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
+
+
+var regexes = {};
+
+function addRegexToken (token, regex, strictRegex) {
+ regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
+ return (isStrict && strictRegex) ? strictRegex : regex;
+ };
+}
+
+function getParseRegexForToken (token, config) {
+ if (!hasOwnProp(regexes, token)) {
+ return new RegExp(unescapeFormat(token));
+ }
+
+ return regexes[token](config._strict, config._locale);
+}
+
+// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
+function unescapeFormat(s) {
+ return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
+ return p1 || p2 || p3 || p4;
+ }));
+}
+
+function regexEscape(s) {
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
+}
+
+var tokens = {};
+
+function addParseToken (token, callback) {
+ var i, func = callback;
+ if (typeof token === 'string') {
+ token = [token];
+ }
+ if (isNumber(callback)) {
+ func = function (input, array) {
+ array[callback] = toInt(input);
+ };
+ }
+ for (i = 0; i < token.length; i++) {
+ tokens[token[i]] = func;
+ }
+}
+
+function addWeekParseToken (token, callback) {
+ addParseToken(token, function (input, array, config, token) {
+ config._w = config._w || {};
+ callback(input, config._w, config, token);
+ });
+}
+
+function addTimeToArrayFromToken(token, input, config) {
+ if (input != null && hasOwnProp(tokens, token)) {
+ tokens[token](input, config._a, config, token);
+ }
+}
+
+var YEAR = 0;
+var MONTH = 1;
+var DATE = 2;
+var HOUR = 3;
+var MINUTE = 4;
+var SECOND = 5;
+var MILLISECOND = 6;
+var WEEK = 7;
+var WEEKDAY = 8;
+
+var indexOf;
+
+if (Array.prototype.indexOf) {
+ indexOf = Array.prototype.indexOf;
+} else {
+ indexOf = function (o) {
+ // I know
+ var i;
+ for (i = 0; i < this.length; ++i) {
+ if (this[i] === o) {
+ return i;
+ }
+ }
+ return -1;
+ };
+}
+
+var indexOf$1 = indexOf;
+
+function daysInMonth(year, month) {
+ return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
+}
+
+// FORMATTING
+
+addFormatToken('M', ['MM', 2], 'Mo', function () {
+ return this.month() + 1;
+});
+
+addFormatToken('MMM', 0, 0, function (format) {
+ return this.localeData().monthsShort(this, format);
+});
+
+addFormatToken('MMMM', 0, 0, function (format) {
+ return this.localeData().months(this, format);
+});
+
+// ALIASES
+
+addUnitAlias('month', 'M');
+
+// PRIORITY
+
+addUnitPriority('month', 8);
+
+// PARSING
+
+addRegexToken('M', match1to2);
+addRegexToken('MM', match1to2, match2);
+addRegexToken('MMM', function (isStrict, locale) {
+ return locale.monthsShortRegex(isStrict);
+});
+addRegexToken('MMMM', function (isStrict, locale) {
+ return locale.monthsRegex(isStrict);
+});
+
+addParseToken(['M', 'MM'], function (input, array) {
+ array[MONTH] = toInt(input) - 1;
+});
+
+addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
+ var month = config._locale.monthsParse(input, token, config._strict);
+ // if we didn't find a month name, mark the date as invalid.
+ if (month != null) {
+ array[MONTH] = month;
+ } else {
+ getParsingFlags(config).invalidMonth = input;
+ }
+});
+
+// LOCALES
+
+var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
+var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
+function localeMonths (m, format) {
+ if (!m) {
+ return this._months;
+ }
+ return isArray(this._months) ? this._months[m.month()] :
+ this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
+}
+
+var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
+function localeMonthsShort (m, format) {
+ if (!m) {
+ return this._monthsShort;
+ }
+ return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
+ this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
+}
+
+function handleStrictParse(monthName, format, strict) {
+ var i, ii, mom, llc = monthName.toLocaleLowerCase();
+ if (!this._monthsParse) {
+ // this is not used
+ this._monthsParse = [];
+ this._longMonthsParse = [];
+ this._shortMonthsParse = [];
+ for (i = 0; i < 12; ++i) {
+ mom = createUTC([2000, i]);
+ this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
+ this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
+ }
+ }
+
+ if (strict) {
+ if (format === 'MMM') {
+ ii = indexOf$1.call(this._shortMonthsParse, llc);
+ return ii !== -1 ? ii : null;
+ } else {
+ ii = indexOf$1.call(this._longMonthsParse, llc);
+ return ii !== -1 ? ii : null;
+ }
+ } else {
+ if (format === 'MMM') {
+ ii = indexOf$1.call(this._shortMonthsParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._longMonthsParse, llc);
+ return ii !== -1 ? ii : null;
+ } else {
+ ii = indexOf$1.call(this._longMonthsParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._shortMonthsParse, llc);
+ return ii !== -1 ? ii : null;
+ }
+ }
+}
+
+function localeMonthsParse (monthName, format, strict) {
+ var i, mom, regex;
+
+ if (this._monthsParseExact) {
+ return handleStrictParse.call(this, monthName, format, strict);
+ }
+
+ if (!this._monthsParse) {
+ this._monthsParse = [];
+ this._longMonthsParse = [];
+ this._shortMonthsParse = [];
+ }
+
+ // TODO: add sorting
+ // Sorting makes sure if one month (or abbr) is a prefix of another
+ // see sorting in computeMonthsParse
+ for (i = 0; i < 12; i++) {
+ // make the regex if we don't have it already
+ mom = createUTC([2000, i]);
+ if (strict && !this._longMonthsParse[i]) {
+ this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
+ this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
+ }
+ if (!strict && !this._monthsParse[i]) {
+ regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
+ this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
+ }
+ // test the regex
+ if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
+ return i;
+ } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
+ return i;
+ } else if (!strict && this._monthsParse[i].test(monthName)) {
+ return i;
+ }
+ }
+}
+
+// MOMENTS
+
+function setMonth (mom, value) {
+ var dayOfMonth;
+
+ if (!mom.isValid()) {
+ // No op
+ return mom;
+ }
+
+ if (typeof value === 'string') {
+ if (/^\d+$/.test(value)) {
+ value = toInt(value);
+ } else {
+ value = mom.localeData().monthsParse(value);
+ // TODO: Another silent failure?
+ if (!isNumber(value)) {
+ return mom;
+ }
+ }
+ }
+
+ dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
+ mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
+ return mom;
+}
+
+function getSetMonth (value) {
+ if (value != null) {
+ setMonth(this, value);
+ hooks.updateOffset(this, true);
+ return this;
+ } else {
+ return get(this, 'Month');
+ }
+}
+
+function getDaysInMonth () {
+ return daysInMonth(this.year(), this.month());
+}
+
+var defaultMonthsShortRegex = matchWord;
+function monthsShortRegex (isStrict) {
+ if (this._monthsParseExact) {
+ if (!hasOwnProp(this, '_monthsRegex')) {
+ computeMonthsParse.call(this);
+ }
+ if (isStrict) {
+ return this._monthsShortStrictRegex;
+ } else {
+ return this._monthsShortRegex;
+ }
+ } else {
+ if (!hasOwnProp(this, '_monthsShortRegex')) {
+ this._monthsShortRegex = defaultMonthsShortRegex;
+ }
+ return this._monthsShortStrictRegex && isStrict ?
+ this._monthsShortStrictRegex : this._monthsShortRegex;
+ }
+}
+
+var defaultMonthsRegex = matchWord;
+function monthsRegex (isStrict) {
+ if (this._monthsParseExact) {
+ if (!hasOwnProp(this, '_monthsRegex')) {
+ computeMonthsParse.call(this);
+ }
+ if (isStrict) {
+ return this._monthsStrictRegex;
+ } else {
+ return this._monthsRegex;
+ }
+ } else {
+ if (!hasOwnProp(this, '_monthsRegex')) {
+ this._monthsRegex = defaultMonthsRegex;
+ }
+ return this._monthsStrictRegex && isStrict ?
+ this._monthsStrictRegex : this._monthsRegex;
+ }
+}
+
+function computeMonthsParse () {
+ function cmpLenRev(a, b) {
+ return b.length - a.length;
+ }
+
+ var shortPieces = [], longPieces = [], mixedPieces = [],
+ i, mom;
+ for (i = 0; i < 12; i++) {
+ // make the regex if we don't have it already
+ mom = createUTC([2000, i]);
+ shortPieces.push(this.monthsShort(mom, ''));
+ longPieces.push(this.months(mom, ''));
+ mixedPieces.push(this.months(mom, ''));
+ mixedPieces.push(this.monthsShort(mom, ''));
+ }
+ // Sorting makes sure if one month (or abbr) is a prefix of another it
+ // will match the longer piece.
+ shortPieces.sort(cmpLenRev);
+ longPieces.sort(cmpLenRev);
+ mixedPieces.sort(cmpLenRev);
+ for (i = 0; i < 12; i++) {
+ shortPieces[i] = regexEscape(shortPieces[i]);
+ longPieces[i] = regexEscape(longPieces[i]);
+ }
+ for (i = 0; i < 24; i++) {
+ mixedPieces[i] = regexEscape(mixedPieces[i]);
+ }
+
+ this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
+ this._monthsShortRegex = this._monthsRegex;
+ this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
+ this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
+}
+
+// FORMATTING
+
+addFormatToken('Y', 0, 0, function () {
+ var y = this.year();
+ return y <= 9999 ? '' + y : '+' + y;
+});
+
+addFormatToken(0, ['YY', 2], 0, function () {
+ return this.year() % 100;
+});
+
+addFormatToken(0, ['YYYY', 4], 0, 'year');
+addFormatToken(0, ['YYYYY', 5], 0, 'year');
+addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
+
+// ALIASES
+
+addUnitAlias('year', 'y');
+
+// PRIORITIES
+
+addUnitPriority('year', 1);
+
+// PARSING
+
+addRegexToken('Y', matchSigned);
+addRegexToken('YY', match1to2, match2);
+addRegexToken('YYYY', match1to4, match4);
+addRegexToken('YYYYY', match1to6, match6);
+addRegexToken('YYYYYY', match1to6, match6);
+
+addParseToken(['YYYYY', 'YYYYYY'], YEAR);
+addParseToken('YYYY', function (input, array) {
+ array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
+});
+addParseToken('YY', function (input, array) {
+ array[YEAR] = hooks.parseTwoDigitYear(input);
+});
+addParseToken('Y', function (input, array) {
+ array[YEAR] = parseInt(input, 10);
+});
+
+// HELPERS
+
+function daysInYear(year) {
+ return isLeapYear(year) ? 366 : 365;
+}
+
+function isLeapYear(year) {
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
+}
+
+// HOOKS
+
+hooks.parseTwoDigitYear = function (input) {
+ return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
+};
+
+// MOMENTS
+
+var getSetYear = makeGetSet('FullYear', true);
+
+function getIsLeapYear () {
+ return isLeapYear(this.year());
+}
+
+function createDate (y, m, d, h, M, s, ms) {
+ //can't just apply() to create a date:
+ //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
+ var date = new Date(y, m, d, h, M, s, ms);
+
+ //the date constructor remaps years 0-99 to 1900-1999
+ if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
+ date.setFullYear(y);
+ }
+ return date;
+}
+
+function createUTCDate (y) {
+ var date = new Date(Date.UTC.apply(null, arguments));
+
+ //the Date.UTC function remaps years 0-99 to 1900-1999
+ if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
+ date.setUTCFullYear(y);
+ }
+ return date;
+}
+
+// start-of-first-week - start-of-year
+function firstWeekOffset(year, dow, doy) {
+ var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
+ fwd = 7 + dow - doy,
+ // first-week day local weekday -- which local weekday is fwd
+ fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
+
+ return -fwdlw + fwd - 1;
+}
+
+//http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
+function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
+ var localWeekday = (7 + weekday - dow) % 7,
+ weekOffset = firstWeekOffset(year, dow, doy),
+ dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
+ resYear, resDayOfYear;
+
+ if (dayOfYear <= 0) {
+ resYear = year - 1;
+ resDayOfYear = daysInYear(resYear) + dayOfYear;
+ } else if (dayOfYear > daysInYear(year)) {
+ resYear = year + 1;
+ resDayOfYear = dayOfYear - daysInYear(year);
+ } else {
+ resYear = year;
+ resDayOfYear = dayOfYear;
+ }
+
+ return {
+ year: resYear,
+ dayOfYear: resDayOfYear
+ };
+}
+
+function weekOfYear(mom, dow, doy) {
+ var weekOffset = firstWeekOffset(mom.year(), dow, doy),
+ week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
+ resWeek, resYear;
+
+ if (week < 1) {
+ resYear = mom.year() - 1;
+ resWeek = week + weeksInYear(resYear, dow, doy);
+ } else if (week > weeksInYear(mom.year(), dow, doy)) {
+ resWeek = week - weeksInYear(mom.year(), dow, doy);
+ resYear = mom.year() + 1;
+ } else {
+ resYear = mom.year();
+ resWeek = week;
+ }
+
+ return {
+ week: resWeek,
+ year: resYear
+ };
+}
+
+function weeksInYear(year, dow, doy) {
+ var weekOffset = firstWeekOffset(year, dow, doy),
+ weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
+ return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
+}
+
+// FORMATTING
+
+addFormatToken('w', ['ww', 2], 'wo', 'week');
+addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
+
+// ALIASES
+
+addUnitAlias('week', 'w');
+addUnitAlias('isoWeek', 'W');
+
+// PRIORITIES
+
+addUnitPriority('week', 5);
+addUnitPriority('isoWeek', 5);
+
+// PARSING
+
+addRegexToken('w', match1to2);
+addRegexToken('ww', match1to2, match2);
+addRegexToken('W', match1to2);
+addRegexToken('WW', match1to2, match2);
+
+addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
+ week[token.substr(0, 1)] = toInt(input);
+});
+
+// HELPERS
+
+// LOCALES
+
+function localeWeek (mom) {
+ return weekOfYear(mom, this._week.dow, this._week.doy).week;
+}
+
+var defaultLocaleWeek = {
+ dow : 0, // Sunday is the first day of the week.
+ doy : 6 // The week that contains Jan 1st is the first week of the year.
+};
+
+function localeFirstDayOfWeek () {
+ return this._week.dow;
+}
+
+function localeFirstDayOfYear () {
+ return this._week.doy;
+}
+
+// MOMENTS
+
+function getSetWeek (input) {
+ var week = this.localeData().week(this);
+ return input == null ? week : this.add((input - week) * 7, 'd');
+}
+
+function getSetISOWeek (input) {
+ var week = weekOfYear(this, 1, 4).week;
+ return input == null ? week : this.add((input - week) * 7, 'd');
+}
+
+// FORMATTING
+
+addFormatToken('d', 0, 'do', 'day');
+
+addFormatToken('dd', 0, 0, function (format) {
+ return this.localeData().weekdaysMin(this, format);
+});
+
+addFormatToken('ddd', 0, 0, function (format) {
+ return this.localeData().weekdaysShort(this, format);
+});
+
+addFormatToken('dddd', 0, 0, function (format) {
+ return this.localeData().weekdays(this, format);
+});
+
+addFormatToken('e', 0, 0, 'weekday');
+addFormatToken('E', 0, 0, 'isoWeekday');
+
+// ALIASES
+
+addUnitAlias('day', 'd');
+addUnitAlias('weekday', 'e');
+addUnitAlias('isoWeekday', 'E');
+
+// PRIORITY
+addUnitPriority('day', 11);
+addUnitPriority('weekday', 11);
+addUnitPriority('isoWeekday', 11);
+
+// PARSING
+
+addRegexToken('d', match1to2);
+addRegexToken('e', match1to2);
+addRegexToken('E', match1to2);
+addRegexToken('dd', function (isStrict, locale) {
+ return locale.weekdaysMinRegex(isStrict);
+});
+addRegexToken('ddd', function (isStrict, locale) {
+ return locale.weekdaysShortRegex(isStrict);
+});
+addRegexToken('dddd', function (isStrict, locale) {
+ return locale.weekdaysRegex(isStrict);
+});
+
+addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
+ var weekday = config._locale.weekdaysParse(input, token, config._strict);
+ // if we didn't get a weekday name, mark the date as invalid
+ if (weekday != null) {
+ week.d = weekday;
+ } else {
+ getParsingFlags(config).invalidWeekday = input;
+ }
+});
+
+addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
+ week[token] = toInt(input);
+});
+
+// HELPERS
+
+function parseWeekday(input, locale) {
+ if (typeof input !== 'string') {
+ return input;
+ }
+
+ if (!isNaN(input)) {
+ return parseInt(input, 10);
+ }
+
+ input = locale.weekdaysParse(input);
+ if (typeof input === 'number') {
+ return input;
+ }
+
+ return null;
+}
+
+function parseIsoWeekday(input, locale) {
+ if (typeof input === 'string') {
+ return locale.weekdaysParse(input) % 7 || 7;
+ }
+ return isNaN(input) ? null : input;
+}
+
+// LOCALES
+
+var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
+function localeWeekdays (m, format) {
+ if (!m) {
+ return this._weekdays;
+ }
+ return isArray(this._weekdays) ? this._weekdays[m.day()] :
+ this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
+}
+
+var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
+function localeWeekdaysShort (m) {
+ return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
+}
+
+var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
+function localeWeekdaysMin (m) {
+ return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
+}
+
+function handleStrictParse$1(weekdayName, format, strict) {
+ var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
+ if (!this._weekdaysParse) {
+ this._weekdaysParse = [];
+ this._shortWeekdaysParse = [];
+ this._minWeekdaysParse = [];
+
+ for (i = 0; i < 7; ++i) {
+ mom = createUTC([2000, 1]).day(i);
+ this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
+ this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
+ this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
+ }
+ }
+
+ if (strict) {
+ if (format === 'dddd') {
+ ii = indexOf$1.call(this._weekdaysParse, llc);
+ return ii !== -1 ? ii : null;
+ } else if (format === 'ddd') {
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+ return ii !== -1 ? ii : null;
+ } else {
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
+ return ii !== -1 ? ii : null;
+ }
+ } else {
+ if (format === 'dddd') {
+ ii = indexOf$1.call(this._weekdaysParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
+ return ii !== -1 ? ii : null;
+ } else if (format === 'ddd') {
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._weekdaysParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
+ return ii !== -1 ? ii : null;
+ } else {
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._weekdaysParse, llc);
+ if (ii !== -1) {
+ return ii;
+ }
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
+ return ii !== -1 ? ii : null;
+ }
+ }
+}
+
+function localeWeekdaysParse (weekdayName, format, strict) {
+ var i, mom, regex;
+
+ if (this._weekdaysParseExact) {
+ return handleStrictParse$1.call(this, weekdayName, format, strict);
+ }
+
+ if (!this._weekdaysParse) {
+ this._weekdaysParse = [];
+ this._minWeekdaysParse = [];
+ this._shortWeekdaysParse = [];
+ this._fullWeekdaysParse = [];
+ }
+
+ for (i = 0; i < 7; i++) {
+ // make the regex if we don't have it already
+
+ mom = createUTC([2000, 1]).day(i);
+ if (strict && !this._fullWeekdaysParse[i]) {
+ this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
+ this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
+ this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
+ }
+ if (!this._weekdaysParse[i]) {
+ regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
+ this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
+ }
+ // test the regex
+ if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
+ return i;
+ } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
+ return i;
+ } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
+ return i;
+ } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
+ return i;
+ }
+ }
+}
+
+// MOMENTS
+
+function getSetDayOfWeek (input) {
+ if (!this.isValid()) {
+ return input != null ? this : NaN;
+ }
+ var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
+ if (input != null) {
+ input = parseWeekday(input, this.localeData());
+ return this.add(input - day, 'd');
+ } else {
+ return day;
+ }
+}
+
+function getSetLocaleDayOfWeek (input) {
+ if (!this.isValid()) {
+ return input != null ? this : NaN;
+ }
+ var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
+ return input == null ? weekday : this.add(input - weekday, 'd');
+}
+
+function getSetISODayOfWeek (input) {
+ if (!this.isValid()) {
+ return input != null ? this : NaN;
+ }
+
+ // behaves the same as moment#day except
+ // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
+ // as a setter, sunday should belong to the previous week.
+
+ if (input != null) {
+ var weekday = parseIsoWeekday(input, this.localeData());
+ return this.day(this.day() % 7 ? weekday : weekday - 7);
+ } else {
+ return this.day() || 7;
+ }
+}
+
+var defaultWeekdaysRegex = matchWord;
+function weekdaysRegex (isStrict) {
+ if (this._weekdaysParseExact) {
+ if (!hasOwnProp(this, '_weekdaysRegex')) {
+ computeWeekdaysParse.call(this);
+ }
+ if (isStrict) {
+ return this._weekdaysStrictRegex;
+ } else {
+ return this._weekdaysRegex;
+ }
+ } else {
+ if (!hasOwnProp(this, '_weekdaysRegex')) {
+ this._weekdaysRegex = defaultWeekdaysRegex;
+ }
+ return this._weekdaysStrictRegex && isStrict ?
+ this._weekdaysStrictRegex : this._weekdaysRegex;
+ }
+}
+
+var defaultWeekdaysShortRegex = matchWord;
+function weekdaysShortRegex (isStrict) {
+ if (this._weekdaysParseExact) {
+ if (!hasOwnProp(this, '_weekdaysRegex')) {
+ computeWeekdaysParse.call(this);
+ }
+ if (isStrict) {
+ return this._weekdaysShortStrictRegex;
+ } else {
+ return this._weekdaysShortRegex;
+ }
+ } else {
+ if (!hasOwnProp(this, '_weekdaysShortRegex')) {
+ this._weekdaysShortRegex = defaultWeekdaysShortRegex;
+ }
+ return this._weekdaysShortStrictRegex && isStrict ?
+ this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
+ }
+}
+
+var defaultWeekdaysMinRegex = matchWord;
+function weekdaysMinRegex (isStrict) {
+ if (this._weekdaysParseExact) {
+ if (!hasOwnProp(this, '_weekdaysRegex')) {
+ computeWeekdaysParse.call(this);
+ }
+ if (isStrict) {
+ return this._weekdaysMinStrictRegex;
+ } else {
+ return this._weekdaysMinRegex;
+ }
+ } else {
+ if (!hasOwnProp(this, '_weekdaysMinRegex')) {
+ this._weekdaysMinRegex = defaultWeekdaysMinRegex;
+ }
+ return this._weekdaysMinStrictRegex && isStrict ?
+ this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
+ }
+}
+
+
+function computeWeekdaysParse () {
+ function cmpLenRev(a, b) {
+ return b.length - a.length;
+ }
+
+ var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
+ i, mom, minp, shortp, longp;
+ for (i = 0; i < 7; i++) {
+ // make the regex if we don't have it already
+ mom = createUTC([2000, 1]).day(i);
+ minp = this.weekdaysMin(mom, '');
+ shortp = this.weekdaysShort(mom, '');
+ longp = this.weekdays(mom, '');
+ minPieces.push(minp);
+ shortPieces.push(shortp);
+ longPieces.push(longp);
+ mixedPieces.push(minp);
+ mixedPieces.push(shortp);
+ mixedPieces.push(longp);
+ }
+ // Sorting makes sure if one weekday (or abbr) is a prefix of another it
+ // will match the longer piece.
+ minPieces.sort(cmpLenRev);
+ shortPieces.sort(cmpLenRev);
+ longPieces.sort(cmpLenRev);
+ mixedPieces.sort(cmpLenRev);
+ for (i = 0; i < 7; i++) {
+ shortPieces[i] = regexEscape(shortPieces[i]);
+ longPieces[i] = regexEscape(longPieces[i]);
+ mixedPieces[i] = regexEscape(mixedPieces[i]);
+ }
+
+ this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
+ this._weekdaysShortRegex = this._weekdaysRegex;
+ this._weekdaysMinRegex = this._weekdaysRegex;
+
+ this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
+ this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
+ this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
+}
+
+// FORMATTING
+
+function hFormat() {
+ return this.hours() % 12 || 12;
+}
+
+function kFormat() {
+ return this.hours() || 24;
+}
+
+addFormatToken('H', ['HH', 2], 0, 'hour');
+addFormatToken('h', ['hh', 2], 0, hFormat);
+addFormatToken('k', ['kk', 2], 0, kFormat);
+
+addFormatToken('hmm', 0, 0, function () {
+ return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
+});
+
+addFormatToken('hmmss', 0, 0, function () {
+ return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
+ zeroFill(this.seconds(), 2);
+});
+
+addFormatToken('Hmm', 0, 0, function () {
+ return '' + this.hours() + zeroFill(this.minutes(), 2);
+});
+
+addFormatToken('Hmmss', 0, 0, function () {
+ return '' + this.hours() + zeroFill(this.minutes(), 2) +
+ zeroFill(this.seconds(), 2);
+});
+
+function meridiem (token, lowercase) {
+ addFormatToken(token, 0, 0, function () {
+ return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
+ });
+}
+
+meridiem('a', true);
+meridiem('A', false);
+
+// ALIASES
+
+addUnitAlias('hour', 'h');
+
+// PRIORITY
+addUnitPriority('hour', 13);
+
+// PARSING
+
+function matchMeridiem (isStrict, locale) {
+ return locale._meridiemParse;
+}
+
+addRegexToken('a', matchMeridiem);
+addRegexToken('A', matchMeridiem);
+addRegexToken('H', match1to2);
+addRegexToken('h', match1to2);
+addRegexToken('HH', match1to2, match2);
+addRegexToken('hh', match1to2, match2);
+
+addRegexToken('hmm', match3to4);
+addRegexToken('hmmss', match5to6);
+addRegexToken('Hmm', match3to4);
+addRegexToken('Hmmss', match5to6);
+
+addParseToken(['H', 'HH'], HOUR);
+addParseToken(['a', 'A'], function (input, array, config) {
+ config._isPm = config._locale.isPM(input);
+ config._meridiem = input;
+});
+addParseToken(['h', 'hh'], function (input, array, config) {
+ array[HOUR] = toInt(input);
+ getParsingFlags(config).bigHour = true;
+});
+addParseToken('hmm', function (input, array, config) {
+ var pos = input.length - 2;
+ array[HOUR] = toInt(input.substr(0, pos));
+ array[MINUTE] = toInt(input.substr(pos));
+ getParsingFlags(config).bigHour = true;
+});
+addParseToken('hmmss', function (input, array, config) {
+ var pos1 = input.length - 4;
+ var pos2 = input.length - 2;
+ array[HOUR] = toInt(input.substr(0, pos1));
+ array[MINUTE] = toInt(input.substr(pos1, 2));
+ array[SECOND] = toInt(input.substr(pos2));
+ getParsingFlags(config).bigHour = true;
+});
+addParseToken('Hmm', function (input, array, config) {
+ var pos = input.length - 2;
+ array[HOUR] = toInt(input.substr(0, pos));
+ array[MINUTE] = toInt(input.substr(pos));
+});
+addParseToken('Hmmss', function (input, array, config) {
+ var pos1 = input.length - 4;
+ var pos2 = input.length - 2;
+ array[HOUR] = toInt(input.substr(0, pos1));
+ array[MINUTE] = toInt(input.substr(pos1, 2));
+ array[SECOND] = toInt(input.substr(pos2));
+});
+
+// LOCALES
+
+function localeIsPM (input) {
+ // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
+ // Using charAt should be more compatible.
+ return ((input + '').toLowerCase().charAt(0) === 'p');
+}
+
+var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
+function localeMeridiem (hours, minutes, isLower) {
+ if (hours > 11) {
+ return isLower ? 'pm' : 'PM';
+ } else {
+ return isLower ? 'am' : 'AM';
+ }
+}
+
+
+// MOMENTS
+
+// Setting the hour should keep the time, because the user explicitly
+// specified which hour he wants. So trying to maintain the same hour (in
+// a new timezone) makes sense. Adding/subtracting hours does not follow
+// this rule.
+var getSetHour = makeGetSet('Hours', true);
+
+// months
+// week
+// weekdays
+// meridiem
+var baseConfig = {
+ calendar: defaultCalendar,
+ longDateFormat: defaultLongDateFormat,
+ invalidDate: defaultInvalidDate,
+ ordinal: defaultOrdinal,
+ ordinalParse: defaultOrdinalParse,
+ relativeTime: defaultRelativeTime,
+
+ months: defaultLocaleMonths,
+ monthsShort: defaultLocaleMonthsShort,
+
+ week: defaultLocaleWeek,
+
+ weekdays: defaultLocaleWeekdays,
+ weekdaysMin: defaultLocaleWeekdaysMin,
+ weekdaysShort: defaultLocaleWeekdaysShort,
+
+ meridiemParse: defaultLocaleMeridiemParse
+};
+
+// internal storage for locale config files
+var locales = {};
+var localeFamilies = {};
+var globalLocale;
+
+function normalizeLocale(key) {
+ return key ? key.toLowerCase().replace('_', '-') : key;
+}
+
+// pick the locale from the array
+// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
+// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
+function chooseLocale(names) {
+ var i = 0, j, next, locale, split;
+
+ while (i < names.length) {
+ split = normalizeLocale(names[i]).split('-');
+ j = split.length;
+ next = normalizeLocale(names[i + 1]);
+ next = next ? next.split('-') : null;
+ while (j > 0) {
+ locale = loadLocale(split.slice(0, j).join('-'));
+ if (locale) {
+ return locale;
+ }
+ if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
+ //the next array item is better than a shallower substring of this one
+ break;
+ }
+ j--;
+ }
+ i++;
+ }
+ return null;
+}
+
+function loadLocale(name) {
+ var oldLocale = null;
+ // TODO: Find a better way to register and load all the locales in Node
+ if (!locales[name] && (typeof module !== 'undefined') &&
+ module && module.exports) {
+ try {
+ oldLocale = globalLocale._abbr;
+ require('./locale/' + name);
+ // because defineLocale currently also sets the global locale, we
+ // want to undo that for lazy loaded locales
+ getSetGlobalLocale(oldLocale);
+ } catch (e) { }
+ }
+ return locales[name];
+}
+
+// This function will load locale and then set the global locale. If
+// no arguments are passed in, it will simply return the current global
+// locale key.
+function getSetGlobalLocale (key, values) {
+ var data;
+ if (key) {
+ if (isUndefined(values)) {
+ data = getLocale(key);
+ }
+ else {
+ data = defineLocale(key, values);
+ }
+
+ if (data) {
+ // moment.duration._locale = moment._locale = data;
+ globalLocale = data;
+ }
+ }
+
+ return globalLocale._abbr;
+}
+
+function defineLocale (name, config) {
+ if (config !== null) {
+ var parentConfig = baseConfig;
+ config.abbr = name;
+ if (locales[name] != null) {
+ deprecateSimple('defineLocaleOverride',
+ 'use moment.updateLocale(localeName, config) to change ' +
+ 'an existing locale. moment.defineLocale(localeName, ' +
+ 'config) should only be used for creating a new locale ' +
+ 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
+ parentConfig = locales[name]._config;
+ } else if (config.parentLocale != null) {
+ if (locales[config.parentLocale] != null) {
+ parentConfig = locales[config.parentLocale]._config;
+ } else {
+ if (!localeFamilies[config.parentLocale]) {
+ localeFamilies[config.parentLocale] = [];
+ }
+ localeFamilies[config.parentLocale].push({
+ name: name,
+ config: config
+ });
+ return null;
+ }
+ }
+ locales[name] = new Locale(mergeConfigs(parentConfig, config));
+
+ if (localeFamilies[name]) {
+ localeFamilies[name].forEach(function (x) {
+ defineLocale(x.name, x.config);
+ });
+ }
+
+ // backwards compat for now: also set the locale
+ // make sure we set the locale AFTER all child locales have been
+ // created, so we won't end up with the child locale set.
+ getSetGlobalLocale(name);
+
+
+ return locales[name];
+ } else {
+ // useful for testing
+ delete locales[name];
+ return null;
+ }
+}
+
+function updateLocale(name, config) {
+ if (config != null) {
+ var locale, parentConfig = baseConfig;
+ // MERGE
+ if (locales[name] != null) {
+ parentConfig = locales[name]._config;
+ }
+ config = mergeConfigs(parentConfig, config);
+ locale = new Locale(config);
+ locale.parentLocale = locales[name];
+ locales[name] = locale;
+
+ // backwards compat for now: also set the locale
+ getSetGlobalLocale(name);
+ } else {
+ // pass null for config to unupdate, useful for tests
+ if (locales[name] != null) {
+ if (locales[name].parentLocale != null) {
+ locales[name] = locales[name].parentLocale;
+ } else if (locales[name] != null) {
+ delete locales[name];
+ }
+ }
+ }
+ return locales[name];
+}
+
+// returns locale data
+function getLocale (key) {
+ var locale;
+
+ if (key && key._locale && key._locale._abbr) {
+ key = key._locale._abbr;
+ }
+
+ if (!key) {
+ return globalLocale;
+ }
+
+ if (!isArray(key)) {
+ //short-circuit everything else
+ locale = loadLocale(key);
+ if (locale) {
+ return locale;
+ }
+ key = [key];
+ }
+
+ return chooseLocale(key);
+}
+
+function listLocales() {
+ return keys$1(locales);
+}
+
+function checkOverflow (m) {
+ var overflow;
+ var a = m._a;
+
+ if (a && getParsingFlags(m).overflow === -2) {
+ overflow =
+ a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
+ a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
+ a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
+ a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
+ a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
+ a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
+ -1;
+
+ if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
+ overflow = DATE;
+ }
+ if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
+ overflow = WEEK;
+ }
+ if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
+ overflow = WEEKDAY;
+ }
+
+ getParsingFlags(m).overflow = overflow;
+ }
+
+ return m;
+}
+
+// iso 8601 regex
+// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
+var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
+var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
+
+var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
+
+var isoDates = [
+ ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
+ ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
+ ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
+ ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
+ ['YYYY-DDD', /\d{4}-\d{3}/],
+ ['YYYY-MM', /\d{4}-\d\d/, false],
+ ['YYYYYYMMDD', /[+-]\d{10}/],
+ ['YYYYMMDD', /\d{8}/],
+ // YYYYMM is NOT allowed by the standard
+ ['GGGG[W]WWE', /\d{4}W\d{3}/],
+ ['GGGG[W]WW', /\d{4}W\d{2}/, false],
+ ['YYYYDDD', /\d{7}/]
+];
+
+// iso time formats and regexes
+var isoTimes = [
+ ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
+ ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
+ ['HH:mm:ss', /\d\d:\d\d:\d\d/],
+ ['HH:mm', /\d\d:\d\d/],
+ ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
+ ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
+ ['HHmmss', /\d\d\d\d\d\d/],
+ ['HHmm', /\d\d\d\d/],
+ ['HH', /\d\d/]
+];
+
+var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
+
+// date from iso format
+function configFromISO(config) {
+ var i, l,
+ string = config._i,
+ match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
+ allowTime, dateFormat, timeFormat, tzFormat;
+
+ if (match) {
+ getParsingFlags(config).iso = true;
+
+ for (i = 0, l = isoDates.length; i < l; i++) {
+ if (isoDates[i][1].exec(match[1])) {
+ dateFormat = isoDates[i][0];
+ allowTime = isoDates[i][2] !== false;
+ break;
+ }
+ }
+ if (dateFormat == null) {
+ config._isValid = false;
+ return;
+ }
+ if (match[3]) {
+ for (i = 0, l = isoTimes.length; i < l; i++) {
+ if (isoTimes[i][1].exec(match[3])) {
+ // match[2] should be 'T' or space
+ timeFormat = (match[2] || ' ') + isoTimes[i][0];
+ break;
+ }
+ }
+ if (timeFormat == null) {
+ config._isValid = false;
+ return;
+ }
+ }
+ if (!allowTime && timeFormat != null) {
+ config._isValid = false;
+ return;
+ }
+ if (match[4]) {
+ if (tzRegex.exec(match[4])) {
+ tzFormat = 'Z';
+ } else {
+ config._isValid = false;
+ return;
+ }
+ }
+ config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
+ configFromStringAndFormat(config);
+ } else {
+ config._isValid = false;
+ }
+}
+
+// date from iso format or fallback
+function configFromString(config) {
+ var matched = aspNetJsonRegex.exec(config._i);
+
+ if (matched !== null) {
+ config._d = new Date(+matched[1]);
+ return;
+ }
+
+ configFromISO(config);
+ if (config._isValid === false) {
+ delete config._isValid;
+ hooks.createFromInputFallback(config);
+ }
+}
+
+hooks.createFromInputFallback = deprecate(
+ 'value provided is not in a recognized ISO format. moment construction falls back to js Date(), ' +
+ 'which is not reliable across all browsers and versions. Non ISO date formats are ' +
+ 'discouraged and will be removed in an upcoming major release. Please refer to ' +
+ 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
+ function (config) {
+ config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
+ }
+);
+
+// Pick the first defined of two or three arguments.
+function defaults(a, b, c) {
+ if (a != null) {
+ return a;
+ }
+ if (b != null) {
+ return b;
+ }
+ return c;
+}
+
+function currentDateArray(config) {
+ // hooks is actually the exported moment object
+ var nowValue = new Date(hooks.now());
+ if (config._useUTC) {
+ return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
+ }
+ return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
+}
+
+// convert an array to a date.
+// the array should mirror the parameters below
+// note: all values past the year are optional and will default to the lowest possible value.
+// [year, month, day , hour, minute, second, millisecond]
+function configFromArray (config) {
+ var i, date, input = [], currentDate, yearToUse;
+
+ if (config._d) {
+ return;
+ }
+
+ currentDate = currentDateArray(config);
+
+ //compute day of the year from weeks and weekdays
+ if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
+ dayOfYearFromWeekInfo(config);
+ }
+
+ //if the day of the year is set, figure out what it is
+ if (config._dayOfYear) {
+ yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
+
+ if (config._dayOfYear > daysInYear(yearToUse)) {
+ getParsingFlags(config)._overflowDayOfYear = true;
+ }
+
+ date = createUTCDate(yearToUse, 0, config._dayOfYear);
+ config._a[MONTH] = date.getUTCMonth();
+ config._a[DATE] = date.getUTCDate();
+ }
+
+ // Default to current date.
+ // * if no year, month, day of month are given, default to today
+ // * if day of month is given, default month and year
+ // * if month is given, default only year
+ // * if year is given, don't default anything
+ for (i = 0; i < 3 && config._a[i] == null; ++i) {
+ config._a[i] = input[i] = currentDate[i];
+ }
+
+ // Zero out whatever was not defaulted, including time
+ for (; i < 7; i++) {
+ config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
+ }
+
+ // Check for 24:00:00.000
+ if (config._a[HOUR] === 24 &&
+ config._a[MINUTE] === 0 &&
+ config._a[SECOND] === 0 &&
+ config._a[MILLISECOND] === 0) {
+ config._nextDay = true;
+ config._a[HOUR] = 0;
+ }
+
+ config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
+ // Apply timezone offset from input. The actual utcOffset can be changed
+ // with parseZone.
+ if (config._tzm != null) {
+ config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
+ }
+
+ if (config._nextDay) {
+ config._a[HOUR] = 24;
+ }
+}
+
+function dayOfYearFromWeekInfo(config) {
+ var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
+
+ w = config._w;
+ if (w.GG != null || w.W != null || w.E != null) {
+ dow = 1;
+ doy = 4;
+
+ // TODO: We need to take the current isoWeekYear, but that depends on
+ // how we interpret now (local, utc, fixed offset). So create
+ // a now version of current config (take local/utc/offset flags, and
+ // create now).
+ weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
+ week = defaults(w.W, 1);
+ weekday = defaults(w.E, 1);
+ if (weekday < 1 || weekday > 7) {
+ weekdayOverflow = true;
+ }
+ } else {
+ dow = config._locale._week.dow;
+ doy = config._locale._week.doy;
+
+ var curWeek = weekOfYear(createLocal(), dow, doy);
+
+ weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
+
+ // Default to current week.
+ week = defaults(w.w, curWeek.week);
+
+ if (w.d != null) {
+ // weekday -- low day numbers are considered next week
+ weekday = w.d;
+ if (weekday < 0 || weekday > 6) {
+ weekdayOverflow = true;
+ }
+ } else if (w.e != null) {
+ // local weekday -- counting starts from begining of week
+ weekday = w.e + dow;
+ if (w.e < 0 || w.e > 6) {
+ weekdayOverflow = true;
+ }
+ } else {
+ // default to begining of week
+ weekday = dow;
+ }
+ }
+ if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
+ getParsingFlags(config)._overflowWeeks = true;
+ } else if (weekdayOverflow != null) {
+ getParsingFlags(config)._overflowWeekday = true;
+ } else {
+ temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
+ config._a[YEAR] = temp.year;
+ config._dayOfYear = temp.dayOfYear;
+ }
+}
+
+// constant that refers to the ISO standard
+hooks.ISO_8601 = function () {};
+
+// date from string and format string
+function configFromStringAndFormat(config) {
+ // TODO: Move this to another part of the creation flow to prevent circular deps
+ if (config._f === hooks.ISO_8601) {
+ configFromISO(config);
+ return;
+ }
+
+ config._a = [];
+ getParsingFlags(config).empty = true;
+
+ // This array is used to make a Date, either with `new Date` or `Date.UTC`
+ var string = '' + config._i,
+ i, parsedInput, tokens, token, skipped,
+ stringLength = string.length,
+ totalParsedInputLength = 0;
+
+ tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
+
+ for (i = 0; i < tokens.length; i++) {
+ token = tokens[i];
+ parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
+ // console.log('token', token, 'parsedInput', parsedInput,
+ // 'regex', getParseRegexForToken(token, config));
+ if (parsedInput) {
+ skipped = string.substr(0, string.indexOf(parsedInput));
+ if (skipped.length > 0) {
+ getParsingFlags(config).unusedInput.push(skipped);
+ }
+ string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
+ totalParsedInputLength += parsedInput.length;
+ }
+ // don't parse if it's not a known token
+ if (formatTokenFunctions[token]) {
+ if (parsedInput) {
+ getParsingFlags(config).empty = false;
+ }
+ else {
+ getParsingFlags(config).unusedTokens.push(token);
+ }
+ addTimeToArrayFromToken(token, parsedInput, config);
+ }
+ else if (config._strict && !parsedInput) {
+ getParsingFlags(config).unusedTokens.push(token);
+ }
+ }
+
+ // add remaining unparsed input length to the string
+ getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
+ if (string.length > 0) {
+ getParsingFlags(config).unusedInput.push(string);
+ }
+
+ // clear _12h flag if hour is <= 12
+ if (config._a[HOUR] <= 12 &&
+ getParsingFlags(config).bigHour === true &&
+ config._a[HOUR] > 0) {
+ getParsingFlags(config).bigHour = undefined;
+ }
+
+ getParsingFlags(config).parsedDateParts = config._a.slice(0);
+ getParsingFlags(config).meridiem = config._meridiem;
+ // handle meridiem
+ config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
+
+ configFromArray(config);
+ checkOverflow(config);
+}
+
+
+function meridiemFixWrap (locale, hour, meridiem) {
+ var isPm;
+
+ if (meridiem == null) {
+ // nothing to do
+ return hour;
+ }
+ if (locale.meridiemHour != null) {
+ return locale.meridiemHour(hour, meridiem);
+ } else if (locale.isPM != null) {
+ // Fallback
+ isPm = locale.isPM(meridiem);
+ if (isPm && hour < 12) {
+ hour += 12;
+ }
+ if (!isPm && hour === 12) {
+ hour = 0;
+ }
+ return hour;
+ } else {
+ // this is not supposed to happen
+ return hour;
+ }
+}
+
+// date from string and array of format strings
+function configFromStringAndArray(config) {
+ var tempConfig,
+ bestMoment,
+
+ scoreToBeat,
+ i,
+ currentScore;
+
+ if (config._f.length === 0) {
+ getParsingFlags(config).invalidFormat = true;
+ config._d = new Date(NaN);
+ return;
+ }
+
+ for (i = 0; i < config._f.length; i++) {
+ currentScore = 0;
+ tempConfig = copyConfig({}, config);
+ if (config._useUTC != null) {
+ tempConfig._useUTC = config._useUTC;
+ }
+ tempConfig._f = config._f[i];
+ configFromStringAndFormat(tempConfig);
+
+ if (!isValid(tempConfig)) {
+ continue;
+ }
+
+ // if there is any input that was not parsed add a penalty for that format
+ currentScore += getParsingFlags(tempConfig).charsLeftOver;
+
+ //or tokens
+ currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
+
+ getParsingFlags(tempConfig).score = currentScore;
+
+ if (scoreToBeat == null || currentScore < scoreToBeat) {
+ scoreToBeat = currentScore;
+ bestMoment = tempConfig;
+ }
+ }
+
+ extend(config, bestMoment || tempConfig);
+}
+
+function configFromObject(config) {
+ if (config._d) {
+ return;
+ }
+
+ var i = normalizeObjectUnits(config._i);
+ config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
+ return obj && parseInt(obj, 10);
+ });
+
+ configFromArray(config);
+}
+
+function createFromConfig (config) {
+ var res = new Moment(checkOverflow(prepareConfig(config)));
+ if (res._nextDay) {
+ // Adding is smart enough around DST
+ res.add(1, 'd');
+ res._nextDay = undefined;
+ }
+
+ return res;
+}
+
+function prepareConfig (config) {
+ var input = config._i,
+ format = config._f;
+
+ config._locale = config._locale || getLocale(config._l);
+
+ if (input === null || (format === undefined && input === '')) {
+ return createInvalid({nullInput: true});
+ }
+
+ if (typeof input === 'string') {
+ config._i = input = config._locale.preparse(input);
+ }
+
+ if (isMoment(input)) {
+ return new Moment(checkOverflow(input));
+ } else if (isDate(input)) {
+ config._d = input;
+ } else if (isArray(format)) {
+ configFromStringAndArray(config);
+ } else if (format) {
+ configFromStringAndFormat(config);
+ } else {
+ configFromInput(config);
+ }
+
+ if (!isValid(config)) {
+ config._d = null;
+ }
+
+ return config;
+}
+
+function configFromInput(config) {
+ var input = config._i;
+ if (input === undefined) {
+ config._d = new Date(hooks.now());
+ } else if (isDate(input)) {
+ config._d = new Date(input.valueOf());
+ } else if (typeof input === 'string') {
+ configFromString(config);
+ } else if (isArray(input)) {
+ config._a = map(input.slice(0), function (obj) {
+ return parseInt(obj, 10);
+ });
+ configFromArray(config);
+ } else if (typeof(input) === 'object') {
+ configFromObject(config);
+ } else if (isNumber(input)) {
+ // from milliseconds
+ config._d = new Date(input);
+ } else {
+ hooks.createFromInputFallback(config);
+ }
+}
+
+function createLocalOrUTC (input, format, locale, strict, isUTC) {
+ var c = {};
+
+ if (locale === true || locale === false) {
+ strict = locale;
+ locale = undefined;
+ }
+
+ if ((isObject(input) && isObjectEmpty(input)) ||
+ (isArray(input) && input.length === 0)) {
+ input = undefined;
+ }
+ // object construction must be done this way.
+ // https://github.com/moment/moment/issues/1423
+ c._isAMomentObject = true;
+ c._useUTC = c._isUTC = isUTC;
+ c._l = locale;
+ c._i = input;
+ c._f = format;
+ c._strict = strict;
+
+ return createFromConfig(c);
+}
+
+function createLocal (input, format, locale, strict) {
+ return createLocalOrUTC(input, format, locale, strict, false);
+}
+
+var prototypeMin = deprecate(
+ 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
+ function () {
+ var other = createLocal.apply(null, arguments);
+ if (this.isValid() && other.isValid()) {
+ return other < this ? this : other;
+ } else {
+ return createInvalid();
+ }
+ }
+);
+
+var prototypeMax = deprecate(
+ 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
+ function () {
+ var other = createLocal.apply(null, arguments);
+ if (this.isValid() && other.isValid()) {
+ return other > this ? this : other;
+ } else {
+ return createInvalid();
+ }
+ }
+);
+
+// Pick a moment m from moments so that m[fn](other) is true for all
+// other. This relies on the function fn to be transitive.
+//
+// moments should either be an array of moment objects or an array, whose
+// first element is an array of moment objects.
+function pickBy(fn, moments) {
+ var res, i;
+ if (moments.length === 1 && isArray(moments[0])) {
+ moments = moments[0];
+ }
+ if (!moments.length) {
+ return createLocal();
+ }
+ res = moments[0];
+ for (i = 1; i < moments.length; ++i) {
+ if (!moments[i].isValid() || moments[i][fn](res)) {
+ res = moments[i];
+ }
+ }
+ return res;
+}
+
+// TODO: Use [].sort instead?
+function min () {
+ var args = [].slice.call(arguments, 0);
+
+ return pickBy('isBefore', args);
+}
+
+function max () {
+ var args = [].slice.call(arguments, 0);
+
+ return pickBy('isAfter', args);
+}
+
+var now = function () {
+ return Date.now ? Date.now() : +(new Date());
+};
+
+function Duration (duration) {
+ var normalizedInput = normalizeObjectUnits(duration),
+ years = normalizedInput.year || 0,
+ quarters = normalizedInput.quarter || 0,
+ months = normalizedInput.month || 0,
+ weeks = normalizedInput.week || 0,
+ days = normalizedInput.day || 0,
+ hours = normalizedInput.hour || 0,
+ minutes = normalizedInput.minute || 0,
+ seconds = normalizedInput.second || 0,
+ milliseconds = normalizedInput.millisecond || 0;
+
+ // representation for dateAddRemove
+ this._milliseconds = +milliseconds +
+ seconds * 1e3 + // 1000
+ minutes * 6e4 + // 1000 * 60
+ hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
+ // Because of dateAddRemove treats 24 hours as different from a
+ // day when working around DST, we need to store them separately
+ this._days = +days +
+ weeks * 7;
+ // It is impossible translate months into days without knowing
+ // which months you are are talking about, so we have to store
+ // it separately.
+ this._months = +months +
+ quarters * 3 +
+ years * 12;
+
+ this._data = {};
+
+ this._locale = getLocale();
+
+ this._bubble();
+}
+
+function isDuration (obj) {
+ return obj instanceof Duration;
+}
+
+function absRound (number) {
+ if (number < 0) {
+ return Math.round(-1 * number) * -1;
+ } else {
+ return Math.round(number);
+ }
+}
+
+// FORMATTING
+
+function offset (token, separator) {
+ addFormatToken(token, 0, 0, function () {
+ var offset = this.utcOffset();
+ var sign = '+';
+ if (offset < 0) {
+ offset = -offset;
+ sign = '-';
+ }
+ return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
+ });
+}
+
+offset('Z', ':');
+offset('ZZ', '');
+
+// PARSING
+
+addRegexToken('Z', matchShortOffset);
+addRegexToken('ZZ', matchShortOffset);
+addParseToken(['Z', 'ZZ'], function (input, array, config) {
+ config._useUTC = true;
+ config._tzm = offsetFromString(matchShortOffset, input);
+});
+
+// HELPERS
+
+// timezone chunker
+// '+10:00' > ['10', '00']
+// '-1530' > ['-15', '30']
+var chunkOffset = /([\+\-]|\d\d)/gi;
+
+function offsetFromString(matcher, string) {
+ var matches = (string || '').match(matcher);
+
+ if (matches === null) {
+ return null;
+ }
+
+ var chunk = matches[matches.length - 1] || [];
+ var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
+ var minutes = +(parts[1] * 60) + toInt(parts[2]);
+
+ return minutes === 0 ?
+ 0 :
+ parts[0] === '+' ? minutes : -minutes;
+}
+
+// Return a moment from input, that is local/utc/zone equivalent to model.
+function cloneWithOffset(input, model) {
+ var res, diff;
+ if (model._isUTC) {
+ res = model.clone();
+ diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
+ // Use low-level api, because this fn is low-level api.
+ res._d.setTime(res._d.valueOf() + diff);
+ hooks.updateOffset(res, false);
+ return res;
+ } else {
+ return createLocal(input).local();
+ }
+}
+
+function getDateOffset (m) {
+ // On Firefox.24 Date#getTimezoneOffset returns a floating point.
+ // https://github.com/moment/moment/pull/1871
+ return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
+}
+
+// HOOKS
+
+// This function will be called whenever a moment is mutated.
+// It is intended to keep the offset in sync with the timezone.
+hooks.updateOffset = function () {};
+
+// MOMENTS
+
+// keepLocalTime = true means only change the timezone, without
+// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
+// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
+// +0200, so we adjust the time as needed, to be valid.
+//
+// Keeping the time actually adds/subtracts (one hour)
+// from the actual represented time. That is why we call updateOffset
+// a second time. In case it wants us to change the offset again
+// _changeInProgress == true case, then we have to adjust, because
+// there is no such time in the given timezone.
+function getSetOffset (input, keepLocalTime) {
+ var offset = this._offset || 0,
+ localAdjust;
+ if (!this.isValid()) {
+ return input != null ? this : NaN;
+ }
+ if (input != null) {
+ if (typeof input === 'string') {
+ input = offsetFromString(matchShortOffset, input);
+ if (input === null) {
+ return this;
+ }
+ } else if (Math.abs(input) < 16) {
+ input = input * 60;
+ }
+ if (!this._isUTC && keepLocalTime) {
+ localAdjust = getDateOffset(this);
+ }
+ this._offset = input;
+ this._isUTC = true;
+ if (localAdjust != null) {
+ this.add(localAdjust, 'm');
+ }
+ if (offset !== input) {
+ if (!keepLocalTime || this._changeInProgress) {
+ addSubtract(this, createDuration(input - offset, 'm'), 1, false);
+ } else if (!this._changeInProgress) {
+ this._changeInProgress = true;
+ hooks.updateOffset(this, true);
+ this._changeInProgress = null;
+ }
+ }
+ return this;
+ } else {
+ return this._isUTC ? offset : getDateOffset(this);
+ }
+}
+
+function getSetZone (input, keepLocalTime) {
+ if (input != null) {
+ if (typeof input !== 'string') {
+ input = -input;
+ }
+
+ this.utcOffset(input, keepLocalTime);
+
+ return this;
+ } else {
+ return -this.utcOffset();
+ }
+}
+
+function setOffsetToUTC (keepLocalTime) {
+ return this.utcOffset(0, keepLocalTime);
+}
+
+function setOffsetToLocal (keepLocalTime) {
+ if (this._isUTC) {
+ this.utcOffset(0, keepLocalTime);
+ this._isUTC = false;
+
+ if (keepLocalTime) {
+ this.subtract(getDateOffset(this), 'm');
+ }
+ }
+ return this;
+}
+
+function setOffsetToParsedOffset () {
+ if (this._tzm != null) {
+ this.utcOffset(this._tzm);
+ } else if (typeof this._i === 'string') {
+ var tZone = offsetFromString(matchOffset, this._i);
+ if (tZone != null) {
+ this.utcOffset(tZone);
+ }
+ else {
+ this.utcOffset(0, true);
+ }
+ }
+ return this;
+}
+
+function hasAlignedHourOffset (input) {
+ if (!this.isValid()) {
+ return false;
+ }
+ input = input ? createLocal(input).utcOffset() : 0;
+
+ return (this.utcOffset() - input) % 60 === 0;
+}
+
+function isDaylightSavingTime () {
+ return (
+ this.utcOffset() > this.clone().month(0).utcOffset() ||
+ this.utcOffset() > this.clone().month(5).utcOffset()
+ );
+}
+
+function isDaylightSavingTimeShifted () {
+ if (!isUndefined(this._isDSTShifted)) {
+ return this._isDSTShifted;
+ }
+
+ var c = {};
+
+ copyConfig(c, this);
+ c = prepareConfig(c);
+
+ if (c._a) {
+ var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
+ this._isDSTShifted = this.isValid() &&
+ compareArrays(c._a, other.toArray()) > 0;
+ } else {
+ this._isDSTShifted = false;
+ }
+
+ return this._isDSTShifted;
+}
+
+function isLocal () {
+ return this.isValid() ? !this._isUTC : false;
+}
+
+function isUtcOffset () {
+ return this.isValid() ? this._isUTC : false;
+}
+
+function isUtc () {
+ return this.isValid() ? this._isUTC && this._offset === 0 : false;
+}
+
+// ASP.NET json date format regex
+var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
+
+// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
+// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
+// and further modified to allow for strings containing both week and day
+var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
+
+function createDuration (input, key) {
+ var duration = input,
+ // matching against regexp is expensive, do it on demand
+ match = null,
+ sign,
+ ret,
+ diffRes;
+
+ if (isDuration(input)) {
+ duration = {
+ ms : input._milliseconds,
+ d : input._days,
+ M : input._months
+ };
+ } else if (isNumber(input)) {
+ duration = {};
+ if (key) {
+ duration[key] = input;
+ } else {
+ duration.milliseconds = input;
+ }
+ } else if (!!(match = aspNetRegex.exec(input))) {
+ sign = (match[1] === '-') ? -1 : 1;
+ duration = {
+ y : 0,
+ d : toInt(match[DATE]) * sign,
+ h : toInt(match[HOUR]) * sign,
+ m : toInt(match[MINUTE]) * sign,
+ s : toInt(match[SECOND]) * sign,
+ ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
+ };
+ } else if (!!(match = isoRegex.exec(input))) {
+ sign = (match[1] === '-') ? -1 : 1;
+ duration = {
+ y : parseIso(match[2], sign),
+ M : parseIso(match[3], sign),
+ w : parseIso(match[4], sign),
+ d : parseIso(match[5], sign),
+ h : parseIso(match[6], sign),
+ m : parseIso(match[7], sign),
+ s : parseIso(match[8], sign)
+ };
+ } else if (duration == null) {// checks for null or undefined
+ duration = {};
+ } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
+ diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
+
+ duration = {};
+ duration.ms = diffRes.milliseconds;
+ duration.M = diffRes.months;
+ }
+
+ ret = new Duration(duration);
+
+ if (isDuration(input) && hasOwnProp(input, '_locale')) {
+ ret._locale = input._locale;
+ }
+
+ return ret;
+}
+
+createDuration.fn = Duration.prototype;
+
+function parseIso (inp, sign) {
+ // We'd normally use ~~inp for this, but unfortunately it also
+ // converts floats to ints.
+ // inp may be undefined, so careful calling replace on it.
+ var res = inp && parseFloat(inp.replace(',', '.'));
+ // apply sign while we're at it
+ return (isNaN(res) ? 0 : res) * sign;
+}
+
+function positiveMomentsDifference(base, other) {
+ var res = {milliseconds: 0, months: 0};
+
+ res.months = other.month() - base.month() +
+ (other.year() - base.year()) * 12;
+ if (base.clone().add(res.months, 'M').isAfter(other)) {
+ --res.months;
+ }
+
+ res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
+
+ return res;
+}
+
+function momentsDifference(base, other) {
+ var res;
+ if (!(base.isValid() && other.isValid())) {
+ return {milliseconds: 0, months: 0};
+ }
+
+ other = cloneWithOffset(other, base);
+ if (base.isBefore(other)) {
+ res = positiveMomentsDifference(base, other);
+ } else {
+ res = positiveMomentsDifference(other, base);
+ res.milliseconds = -res.milliseconds;
+ res.months = -res.months;
+ }
+
+ return res;
+}
+
+// TODO: remove 'name' arg after deprecation is removed
+function createAdder(direction, name) {
+ return function (val, period) {
+ var dur, tmp;
+ //invert the arguments, but complain about it
+ if (period !== null && !isNaN(+period)) {
+ deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
+ 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
+ tmp = val; val = period; period = tmp;
+ }
+
+ val = typeof val === 'string' ? +val : val;
+ dur = createDuration(val, period);
+ addSubtract(this, dur, direction);
+ return this;
+ };
+}
+
+function addSubtract (mom, duration, isAdding, updateOffset) {
+ var milliseconds = duration._milliseconds,
+ days = absRound(duration._days),
+ months = absRound(duration._months);
+
+ if (!mom.isValid()) {
+ // No op
+ return;
+ }
+
+ updateOffset = updateOffset == null ? true : updateOffset;
+
+ if (milliseconds) {
+ mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
+ }
+ if (days) {
+ set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
+ }
+ if (months) {
+ setMonth(mom, get(mom, 'Month') + months * isAdding);
+ }
+ if (updateOffset) {
+ hooks.updateOffset(mom, days || months);
+ }
+}
+
+var add = createAdder(1, 'add');
+var subtract = createAdder(-1, 'subtract');
+
+function getCalendarFormat(myMoment, now) {
+ var diff = myMoment.diff(now, 'days', true);
+ return diff < -6 ? 'sameElse' :
+ diff < -1 ? 'lastWeek' :
+ diff < 0 ? 'lastDay' :
+ diff < 1 ? 'sameDay' :
+ diff < 2 ? 'nextDay' :
+ diff < 7 ? 'nextWeek' : 'sameElse';
+}
+
+function calendar$1 (time, formats) {
+ // We want to compare the start of today, vs this.
+ // Getting start-of-today depends on whether we're local/utc/offset or not.
+ var now = time || createLocal(),
+ sod = cloneWithOffset(now, this).startOf('day'),
+ format = hooks.calendarFormat(this, sod) || 'sameElse';
+
+ var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
+
+ return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
+}
+
+function clone () {
+ return new Moment(this);
+}
+
+function isAfter (input, units) {
+ var localInput = isMoment(input) ? input : createLocal(input);
+ if (!(this.isValid() && localInput.isValid())) {
+ return false;
+ }
+ units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
+ if (units === 'millisecond') {
+ return this.valueOf() > localInput.valueOf();
+ } else {
+ return localInput.valueOf() < this.clone().startOf(units).valueOf();
+ }
+}
+
+function isBefore (input, units) {
+ var localInput = isMoment(input) ? input : createLocal(input);
+ if (!(this.isValid() && localInput.isValid())) {
+ return false;
+ }
+ units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
+ if (units === 'millisecond') {
+ return this.valueOf() < localInput.valueOf();
+ } else {
+ return this.clone().endOf(units).valueOf() < localInput.valueOf();
+ }
+}
+
+function isBetween (from, to, units, inclusivity) {
+ inclusivity = inclusivity || '()';
+ return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
+ (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
+}
+
+function isSame (input, units) {
+ var localInput = isMoment(input) ? input : createLocal(input),
+ inputMs;
+ if (!(this.isValid() && localInput.isValid())) {
+ return false;
+ }
+ units = normalizeUnits(units || 'millisecond');
+ if (units === 'millisecond') {
+ return this.valueOf() === localInput.valueOf();
+ } else {
+ inputMs = localInput.valueOf();
+ return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
+ }
+}
+
+function isSameOrAfter (input, units) {
+ return this.isSame(input, units) || this.isAfter(input,units);
+}
+
+function isSameOrBefore (input, units) {
+ return this.isSame(input, units) || this.isBefore(input,units);
+}
+
+function diff (input, units, asFloat) {
+ var that,
+ zoneDelta,
+ delta, output;
+
+ if (!this.isValid()) {
+ return NaN;
+ }
+
+ that = cloneWithOffset(input, this);
+
+ if (!that.isValid()) {
+ return NaN;
+ }
+
+ zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
+
+ units = normalizeUnits(units);
+
+ if (units === 'year' || units === 'month' || units === 'quarter') {
+ output = monthDiff(this, that);
+ if (units === 'quarter') {
+ output = output / 3;
+ } else if (units === 'year') {
+ output = output / 12;
+ }
+ } else {
+ delta = this - that;
+ output = units === 'second' ? delta / 1e3 : // 1000
+ units === 'minute' ? delta / 6e4 : // 1000 * 60
+ units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
+ units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
+ units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
+ delta;
+ }
+ return asFloat ? output : absFloor(output);
+}
+
+function monthDiff (a, b) {
+ // difference in months
+ var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
+ // b is in (anchor - 1 month, anchor + 1 month)
+ anchor = a.clone().add(wholeMonthDiff, 'months'),
+ anchor2, adjust;
+
+ if (b - anchor < 0) {
+ anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
+ // linear across the month
+ adjust = (b - anchor) / (anchor - anchor2);
+ } else {
+ anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
+ // linear across the month
+ adjust = (b - anchor) / (anchor2 - anchor);
+ }
+
+ //check for negative zero, return zero if negative zero
+ return -(wholeMonthDiff + adjust) || 0;
+}
+
+hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
+hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
+
+function toString () {
+ return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
+}
+
+function toISOString () {
+ var m = this.clone().utc();
+ if (0 < m.year() && m.year() <= 9999) {
+ if (isFunction(Date.prototype.toISOString)) {
+ // native implementation is ~50x faster, use it when we can
+ return this.toDate().toISOString();
+ } else {
+ return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
+ }
+ } else {
+ return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
+ }
+}
+
+/**
+ * Return a human readable representation of a moment that can
+ * also be evaluated to get a new moment which is the same
+ *
+ * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
+ */
+function inspect () {
+ if (!this.isValid()) {
+ return 'moment.invalid(/* ' + this._i + ' */)';
+ }
+ var func = 'moment';
+ var zone = '';
+ if (!this.isLocal()) {
+ func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
+ zone = 'Z';
+ }
+ var prefix = '[' + func + '("]';
+ var year = (0 < this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
+ var datetime = '-MM-DD[T]HH:mm:ss.SSS';
+ var suffix = zone + '[")]';
+
+ return this.format(prefix + year + datetime + suffix);
+}
+
+function format (inputString) {
+ if (!inputString) {
+ inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
+ }
+ var output = formatMoment(this, inputString);
+ return this.localeData().postformat(output);
+}
+
+function from (time, withoutSuffix) {
+ if (this.isValid() &&
+ ((isMoment(time) && time.isValid()) ||
+ createLocal(time).isValid())) {
+ return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
+ } else {
+ return this.localeData().invalidDate();
+ }
+}
+
+function fromNow (withoutSuffix) {
+ return this.from(createLocal(), withoutSuffix);
+}
+
+function to (time, withoutSuffix) {
+ if (this.isValid() &&
+ ((isMoment(time) && time.isValid()) ||
+ createLocal(time).isValid())) {
+ return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
+ } else {
+ return this.localeData().invalidDate();
+ }
+}
+
+function toNow (withoutSuffix) {
+ return this.to(createLocal(), withoutSuffix);
+}
+
+// If passed a locale key, it will set the locale for this
+// instance. Otherwise, it will return the locale configuration
+// variables for this instance.
+function locale (key) {
+ var newLocaleData;
+
+ if (key === undefined) {
+ return this._locale._abbr;
+ } else {
+ newLocaleData = getLocale(key);
+ if (newLocaleData != null) {
+ this._locale = newLocaleData;
+ }
+ return this;
+ }
+}
+
+var lang = deprecate(
+ 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
+ function (key) {
+ if (key === undefined) {
+ return this.localeData();
+ } else {
+ return this.locale(key);
+ }
+ }
+);
+
+function localeData () {
+ return this._locale;
+}
+
+function startOf (units) {
+ units = normalizeUnits(units);
+ // the following switch intentionally omits break keywords
+ // to utilize falling through the cases.
+ switch (units) {
+ case 'year':
+ this.month(0);
+ /* falls through */
+ case 'quarter':
+ case 'month':
+ this.date(1);
+ /* falls through */
+ case 'week':
+ case 'isoWeek':
+ case 'day':
+ case 'date':
+ this.hours(0);
+ /* falls through */
+ case 'hour':
+ this.minutes(0);
+ /* falls through */
+ case 'minute':
+ this.seconds(0);
+ /* falls through */
+ case 'second':
+ this.milliseconds(0);
+ }
+
+ // weeks are a special case
+ if (units === 'week') {
+ this.weekday(0);
+ }
+ if (units === 'isoWeek') {
+ this.isoWeekday(1);
+ }
+
+ // quarters are also special
+ if (units === 'quarter') {
+ this.month(Math.floor(this.month() / 3) * 3);
+ }
+
+ return this;
+}
+
+function endOf (units) {
+ units = normalizeUnits(units);
+ if (units === undefined || units === 'millisecond') {
+ return this;
+ }
+
+ // 'date' is an alias for 'day', so it should be considered as such.
+ if (units === 'date') {
+ units = 'day';
+ }
+
+ return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
+}
+
+function valueOf () {
+ return this._d.valueOf() - ((this._offset || 0) * 60000);
+}
+
+function unix () {
+ return Math.floor(this.valueOf() / 1000);
+}
+
+function toDate () {
+ return new Date(this.valueOf());
+}
+
+function toArray () {
+ var m = this;
+ return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
+}
+
+function toObject () {
+ var m = this;
+ return {
+ years: m.year(),
+ months: m.month(),
+ date: m.date(),
+ hours: m.hours(),
+ minutes: m.minutes(),
+ seconds: m.seconds(),
+ milliseconds: m.milliseconds()
+ };
+}
+
+function toJSON () {
+ // new Date(NaN).toJSON() === null
+ return this.isValid() ? this.toISOString() : null;
+}
+
+function isValid$1 () {
+ return isValid(this);
+}
+
+function parsingFlags () {
+ return extend({}, getParsingFlags(this));
+}
+
+function invalidAt () {
+ return getParsingFlags(this).overflow;
+}
+
+function creationData() {
+ return {
+ input: this._i,
+ format: this._f,
+ locale: this._locale,
+ isUTC: this._isUTC,
+ strict: this._strict
+ };
+}
+
+// FORMATTING
+
+addFormatToken(0, ['gg', 2], 0, function () {
+ return this.weekYear() % 100;
+});
+
+addFormatToken(0, ['GG', 2], 0, function () {
+ return this.isoWeekYear() % 100;
+});
+
+function addWeekYearFormatToken (token, getter) {
+ addFormatToken(0, [token, token.length], 0, getter);
+}
+
+addWeekYearFormatToken('gggg', 'weekYear');
+addWeekYearFormatToken('ggggg', 'weekYear');
+addWeekYearFormatToken('GGGG', 'isoWeekYear');
+addWeekYearFormatToken('GGGGG', 'isoWeekYear');
+
+// ALIASES
+
+addUnitAlias('weekYear', 'gg');
+addUnitAlias('isoWeekYear', 'GG');
+
+// PRIORITY
+
+addUnitPriority('weekYear', 1);
+addUnitPriority('isoWeekYear', 1);
+
+
+// PARSING
+
+addRegexToken('G', matchSigned);
+addRegexToken('g', matchSigned);
+addRegexToken('GG', match1to2, match2);
+addRegexToken('gg', match1to2, match2);
+addRegexToken('GGGG', match1to4, match4);
+addRegexToken('gggg', match1to4, match4);
+addRegexToken('GGGGG', match1to6, match6);
+addRegexToken('ggggg', match1to6, match6);
+
+addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
+ week[token.substr(0, 2)] = toInt(input);
+});
+
+addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
+ week[token] = hooks.parseTwoDigitYear(input);
+});
+
+// MOMENTS
+
+function getSetWeekYear (input) {
+ return getSetWeekYearHelper.call(this,
+ input,
+ this.week(),
+ this.weekday(),
+ this.localeData()._week.dow,
+ this.localeData()._week.doy);
+}
+
+function getSetISOWeekYear (input) {
+ return getSetWeekYearHelper.call(this,
+ input, this.isoWeek(), this.isoWeekday(), 1, 4);
+}
+
+function getISOWeeksInYear () {
+ return weeksInYear(this.year(), 1, 4);
+}
+
+function getWeeksInYear () {
+ var weekInfo = this.localeData()._week;
+ return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
+}
+
+function getSetWeekYearHelper(input, week, weekday, dow, doy) {
+ var weeksTarget;
+ if (input == null) {
+ return weekOfYear(this, dow, doy).year;
+ } else {
+ weeksTarget = weeksInYear(input, dow, doy);
+ if (week > weeksTarget) {
+ week = weeksTarget;
+ }
+ return setWeekAll.call(this, input, week, weekday, dow, doy);
+ }
+}
+
+function setWeekAll(weekYear, week, weekday, dow, doy) {
+ var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
+ date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
+
+ this.year(date.getUTCFullYear());
+ this.month(date.getUTCMonth());
+ this.date(date.getUTCDate());
+ return this;
+}
+
+// FORMATTING
+
+addFormatToken('Q', 0, 'Qo', 'quarter');
+
+// ALIASES
+
+addUnitAlias('quarter', 'Q');
+
+// PRIORITY
+
+addUnitPriority('quarter', 7);
+
+// PARSING
+
+addRegexToken('Q', match1);
+addParseToken('Q', function (input, array) {
+ array[MONTH] = (toInt(input) - 1) * 3;
+});
+
+// MOMENTS
+
+function getSetQuarter (input) {
+ return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
+}
+
+// FORMATTING
+
+addFormatToken('D', ['DD', 2], 'Do', 'date');
+
+// ALIASES
+
+addUnitAlias('date', 'D');
+
+// PRIOROITY
+addUnitPriority('date', 9);
+
+// PARSING
+
+addRegexToken('D', match1to2);
+addRegexToken('DD', match1to2, match2);
+addRegexToken('Do', function (isStrict, locale) {
+ return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
+});
+
+addParseToken(['D', 'DD'], DATE);
+addParseToken('Do', function (input, array) {
+ array[DATE] = toInt(input.match(match1to2)[0], 10);
+});
+
+// MOMENTS
+
+var getSetDayOfMonth = makeGetSet('Date', true);
+
+// FORMATTING
+
+addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
+
+// ALIASES
+
+addUnitAlias('dayOfYear', 'DDD');
+
+// PRIORITY
+addUnitPriority('dayOfYear', 4);
+
+// PARSING
+
+addRegexToken('DDD', match1to3);
+addRegexToken('DDDD', match3);
+addParseToken(['DDD', 'DDDD'], function (input, array, config) {
+ config._dayOfYear = toInt(input);
+});
+
+// HELPERS
+
+// MOMENTS
+
+function getSetDayOfYear (input) {
+ var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
+ return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
+}
+
+// FORMATTING
+
+addFormatToken('m', ['mm', 2], 0, 'minute');
+
+// ALIASES
+
+addUnitAlias('minute', 'm');
+
+// PRIORITY
+
+addUnitPriority('minute', 14);
+
+// PARSING
+
+addRegexToken('m', match1to2);
+addRegexToken('mm', match1to2, match2);
+addParseToken(['m', 'mm'], MINUTE);
+
+// MOMENTS
+
+var getSetMinute = makeGetSet('Minutes', false);
+
+// FORMATTING
+
+addFormatToken('s', ['ss', 2], 0, 'second');
+
+// ALIASES
+
+addUnitAlias('second', 's');
+
+// PRIORITY
+
+addUnitPriority('second', 15);
+
+// PARSING
+
+addRegexToken('s', match1to2);
+addRegexToken('ss', match1to2, match2);
+addParseToken(['s', 'ss'], SECOND);
+
+// MOMENTS
+
+var getSetSecond = makeGetSet('Seconds', false);
+
+// FORMATTING
+
+addFormatToken('S', 0, 0, function () {
+ return ~~(this.millisecond() / 100);
+});
+
+addFormatToken(0, ['SS', 2], 0, function () {
+ return ~~(this.millisecond() / 10);
+});
+
+addFormatToken(0, ['SSS', 3], 0, 'millisecond');
+addFormatToken(0, ['SSSS', 4], 0, function () {
+ return this.millisecond() * 10;
+});
+addFormatToken(0, ['SSSSS', 5], 0, function () {
+ return this.millisecond() * 100;
+});
+addFormatToken(0, ['SSSSSS', 6], 0, function () {
+ return this.millisecond() * 1000;
+});
+addFormatToken(0, ['SSSSSSS', 7], 0, function () {
+ return this.millisecond() * 10000;
+});
+addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
+ return this.millisecond() * 100000;
+});
+addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
+ return this.millisecond() * 1000000;
+});
+
+
+// ALIASES
+
+addUnitAlias('millisecond', 'ms');
+
+// PRIORITY
+
+addUnitPriority('millisecond', 16);
+
+// PARSING
+
+addRegexToken('S', match1to3, match1);
+addRegexToken('SS', match1to3, match2);
+addRegexToken('SSS', match1to3, match3);
+
+var token;
+for (token = 'SSSS'; token.length <= 9; token += 'S') {
+ addRegexToken(token, matchUnsigned);
+}
+
+function parseMs(input, array) {
+ array[MILLISECOND] = toInt(('0.' + input) * 1000);
+}
+
+for (token = 'S'; token.length <= 9; token += 'S') {
+ addParseToken(token, parseMs);
+}
+// MOMENTS
+
+var getSetMillisecond = makeGetSet('Milliseconds', false);
+
+// FORMATTING
+
+addFormatToken('z', 0, 0, 'zoneAbbr');
+addFormatToken('zz', 0, 0, 'zoneName');
+
+// MOMENTS
+
+function getZoneAbbr () {
+ return this._isUTC ? 'UTC' : '';
+}
+
+function getZoneName () {
+ return this._isUTC ? 'Coordinated Universal Time' : '';
+}
+
+var proto = Moment.prototype;
+
+proto.add = add;
+proto.calendar = calendar$1;
+proto.clone = clone;
+proto.diff = diff;
+proto.endOf = endOf;
+proto.format = format;
+proto.from = from;
+proto.fromNow = fromNow;
+proto.to = to;
+proto.toNow = toNow;
+proto.get = stringGet;
+proto.invalidAt = invalidAt;
+proto.isAfter = isAfter;
+proto.isBefore = isBefore;
+proto.isBetween = isBetween;
+proto.isSame = isSame;
+proto.isSameOrAfter = isSameOrAfter;
+proto.isSameOrBefore = isSameOrBefore;
+proto.isValid = isValid$1;
+proto.lang = lang;
+proto.locale = locale;
+proto.localeData = localeData;
+proto.max = prototypeMax;
+proto.min = prototypeMin;
+proto.parsingFlags = parsingFlags;
+proto.set = stringSet;
+proto.startOf = startOf;
+proto.subtract = subtract;
+proto.toArray = toArray;
+proto.toObject = toObject;
+proto.toDate = toDate;
+proto.toISOString = toISOString;
+proto.inspect = inspect;
+proto.toJSON = toJSON;
+proto.toString = toString;
+proto.unix = unix;
+proto.valueOf = valueOf;
+proto.creationData = creationData;
+
+// Year
+proto.year = getSetYear;
+proto.isLeapYear = getIsLeapYear;
+
+// Week Year
+proto.weekYear = getSetWeekYear;
+proto.isoWeekYear = getSetISOWeekYear;
+
+// Quarter
+proto.quarter = proto.quarters = getSetQuarter;
+
+// Month
+proto.month = getSetMonth;
+proto.daysInMonth = getDaysInMonth;
+
+// Week
+proto.week = proto.weeks = getSetWeek;
+proto.isoWeek = proto.isoWeeks = getSetISOWeek;
+proto.weeksInYear = getWeeksInYear;
+proto.isoWeeksInYear = getISOWeeksInYear;
+
+// Day
+proto.date = getSetDayOfMonth;
+proto.day = proto.days = getSetDayOfWeek;
+proto.weekday = getSetLocaleDayOfWeek;
+proto.isoWeekday = getSetISODayOfWeek;
+proto.dayOfYear = getSetDayOfYear;
+
+// Hour
+proto.hour = proto.hours = getSetHour;
+
+// Minute
+proto.minute = proto.minutes = getSetMinute;
+
+// Second
+proto.second = proto.seconds = getSetSecond;
+
+// Millisecond
+proto.millisecond = proto.milliseconds = getSetMillisecond;
+
+// Offset
+proto.utcOffset = getSetOffset;
+proto.utc = setOffsetToUTC;
+proto.local = setOffsetToLocal;
+proto.parseZone = setOffsetToParsedOffset;
+proto.hasAlignedHourOffset = hasAlignedHourOffset;
+proto.isDST = isDaylightSavingTime;
+proto.isLocal = isLocal;
+proto.isUtcOffset = isUtcOffset;
+proto.isUtc = isUtc;
+proto.isUTC = isUtc;
+
+// Timezone
+proto.zoneAbbr = getZoneAbbr;
+proto.zoneName = getZoneName;
+
+// Deprecations
+proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
+proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
+proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
+proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
+proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
+
+function createUnix (input) {
+ return createLocal(input * 1000);
+}
+
+function createInZone () {
+ return createLocal.apply(null, arguments).parseZone();
+}
+
+function preParsePostFormat (string) {
+ return string;
+}
+
+var proto$1 = Locale.prototype;
+
+proto$1.calendar = calendar;
+proto$1.longDateFormat = longDateFormat;
+proto$1.invalidDate = invalidDate;
+proto$1.ordinal = ordinal;
+proto$1.preparse = preParsePostFormat;
+proto$1.postformat = preParsePostFormat;
+proto$1.relativeTime = relativeTime;
+proto$1.pastFuture = pastFuture;
+proto$1.set = set;
+
+// Month
+proto$1.months = localeMonths;
+proto$1.monthsShort = localeMonthsShort;
+proto$1.monthsParse = localeMonthsParse;
+proto$1.monthsRegex = monthsRegex;
+proto$1.monthsShortRegex = monthsShortRegex;
+
+// Week
+proto$1.week = localeWeek;
+proto$1.firstDayOfYear = localeFirstDayOfYear;
+proto$1.firstDayOfWeek = localeFirstDayOfWeek;
+
+// Day of Week
+proto$1.weekdays = localeWeekdays;
+proto$1.weekdaysMin = localeWeekdaysMin;
+proto$1.weekdaysShort = localeWeekdaysShort;
+proto$1.weekdaysParse = localeWeekdaysParse;
+
+proto$1.weekdaysRegex = weekdaysRegex;
+proto$1.weekdaysShortRegex = weekdaysShortRegex;
+proto$1.weekdaysMinRegex = weekdaysMinRegex;
+
+// Hours
+proto$1.isPM = localeIsPM;
+proto$1.meridiem = localeMeridiem;
+
+function get$1 (format, index, field, setter) {
+ var locale = getLocale();
+ var utc = createUTC().set(setter, index);
+ return locale[field](utc, format);
+}
+
+function listMonthsImpl (format, index, field) {
+ if (isNumber(format)) {
+ index = format;
+ format = undefined;
+ }
+
+ format = format || '';
+
+ if (index != null) {
+ return get$1(format, index, field, 'month');
+ }
+
+ var i;
+ var out = [];
+ for (i = 0; i < 12; i++) {
+ out[i] = get$1(format, i, field, 'month');
+ }
+ return out;
+}
+
+// ()
+// (5)
+// (fmt, 5)
+// (fmt)
+// (true)
+// (true, 5)
+// (true, fmt, 5)
+// (true, fmt)
+function listWeekdaysImpl (localeSorted, format, index, field) {
+ if (typeof localeSorted === 'boolean') {
+ if (isNumber(format)) {
+ index = format;
+ format = undefined;
+ }
+
+ format = format || '';
+ } else {
+ format = localeSorted;
+ index = format;
+ localeSorted = false;
+
+ if (isNumber(format)) {
+ index = format;
+ format = undefined;
+ }
+
+ format = format || '';
+ }
+
+ var locale = getLocale(),
+ shift = localeSorted ? locale._week.dow : 0;
+
+ if (index != null) {
+ return get$1(format, (index + shift) % 7, field, 'day');
+ }
+
+ var i;
+ var out = [];
+ for (i = 0; i < 7; i++) {
+ out[i] = get$1(format, (i + shift) % 7, field, 'day');
+ }
+ return out;
+}
+
+function listMonths (format, index) {
+ return listMonthsImpl(format, index, 'months');
+}
+
+function listMonthsShort (format, index) {
+ return listMonthsImpl(format, index, 'monthsShort');
+}
+
+function listWeekdays (localeSorted, format, index) {
+ return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
+}
+
+function listWeekdaysShort (localeSorted, format, index) {
+ return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
+}
+
+function listWeekdaysMin (localeSorted, format, index) {
+ return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
+}
+
+getSetGlobalLocale('en', {
+ ordinalParse: /\d{1,2}(th|st|nd|rd)/,
+ ordinal : function (number) {
+ var b = number % 10,
+ output = (toInt(number % 100 / 10) === 1) ? 'th' :
+ (b === 1) ? 'st' :
+ (b === 2) ? 'nd' :
+ (b === 3) ? 'rd' : 'th';
+ return number + output;
+ }
+});
+
+// Side effect imports
+hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
+hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
+
+var mathAbs = Math.abs;
+
+function abs () {
+ var data = this._data;
+
+ this._milliseconds = mathAbs(this._milliseconds);
+ this._days = mathAbs(this._days);
+ this._months = mathAbs(this._months);
+
+ data.milliseconds = mathAbs(data.milliseconds);
+ data.seconds = mathAbs(data.seconds);
+ data.minutes = mathAbs(data.minutes);
+ data.hours = mathAbs(data.hours);
+ data.months = mathAbs(data.months);
+ data.years = mathAbs(data.years);
+
+ return this;
+}
+
+function addSubtract$1 (duration, input, value, direction) {
+ var other = createDuration(input, value);
+
+ duration._milliseconds += direction * other._milliseconds;
+ duration._days += direction * other._days;
+ duration._months += direction * other._months;
+
+ return duration._bubble();
+}
+
+// supports only 2.0-style add(1, 's') or add(duration)
+function add$1 (input, value) {
+ return addSubtract$1(this, input, value, 1);
+}
+
+// supports only 2.0-style subtract(1, 's') or subtract(duration)
+function subtract$1 (input, value) {
+ return addSubtract$1(this, input, value, -1);
+}
+
+function absCeil (number) {
+ if (number < 0) {
+ return Math.floor(number);
+ } else {
+ return Math.ceil(number);
+ }
+}
+
+function bubble () {
+ var milliseconds = this._milliseconds;
+ var days = this._days;
+ var months = this._months;
+ var data = this._data;
+ var seconds, minutes, hours, years, monthsFromDays;
+
+ // if we have a mix of positive and negative values, bubble down first
+ // check: https://github.com/moment/moment/issues/2166
+ if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
+ (milliseconds <= 0 && days <= 0 && months <= 0))) {
+ milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
+ days = 0;
+ months = 0;
+ }
+
+ // The following code bubbles up values, see the tests for
+ // examples of what that means.
+ data.milliseconds = milliseconds % 1000;
+
+ seconds = absFloor(milliseconds / 1000);
+ data.seconds = seconds % 60;
+
+ minutes = absFloor(seconds / 60);
+ data.minutes = minutes % 60;
+
+ hours = absFloor(minutes / 60);
+ data.hours = hours % 24;
+
+ days += absFloor(hours / 24);
+
+ // convert days to months
+ monthsFromDays = absFloor(daysToMonths(days));
+ months += monthsFromDays;
+ days -= absCeil(monthsToDays(monthsFromDays));
+
+ // 12 months -> 1 year
+ years = absFloor(months / 12);
+ months %= 12;
+
+ data.days = days;
+ data.months = months;
+ data.years = years;
+
+ return this;
+}
+
+function daysToMonths (days) {
+ // 400 years have 146097 days (taking into account leap year rules)
+ // 400 years have 12 months === 4800
+ return days * 4800 / 146097;
+}
+
+function monthsToDays (months) {
+ // the reverse of daysToMonths
+ return months * 146097 / 4800;
+}
+
+function as (units) {
+ var days;
+ var months;
+ var milliseconds = this._milliseconds;
+
+ units = normalizeUnits(units);
+
+ if (units === 'month' || units === 'year') {
+ days = this._days + milliseconds / 864e5;
+ months = this._months + daysToMonths(days);
+ return units === 'month' ? months : months / 12;
+ } else {
+ // handle milliseconds separately because of floating point math errors (issue #1867)
+ days = this._days + Math.round(monthsToDays(this._months));
+ switch (units) {
+ case 'week' : return days / 7 + milliseconds / 6048e5;
+ case 'day' : return days + milliseconds / 864e5;
+ case 'hour' : return days * 24 + milliseconds / 36e5;
+ case 'minute' : return days * 1440 + milliseconds / 6e4;
+ case 'second' : return days * 86400 + milliseconds / 1000;
+ // Math.floor prevents floating point math errors here
+ case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
+ default: throw new Error('Unknown unit ' + units);
+ }
+ }
+}
+
+// TODO: Use this.as('ms')?
+function valueOf$1 () {
+ return (
+ this._milliseconds +
+ this._days * 864e5 +
+ (this._months % 12) * 2592e6 +
+ toInt(this._months / 12) * 31536e6
+ );
+}
+
+function makeAs (alias) {
+ return function () {
+ return this.as(alias);
+ };
+}
+
+var asMilliseconds = makeAs('ms');
+var asSeconds = makeAs('s');
+var asMinutes = makeAs('m');
+var asHours = makeAs('h');
+var asDays = makeAs('d');
+var asWeeks = makeAs('w');
+var asMonths = makeAs('M');
+var asYears = makeAs('y');
+
+function get$2 (units) {
+ units = normalizeUnits(units);
+ return this[units + 's']();
+}
+
+function makeGetter(name) {
+ return function () {
+ return this._data[name];
+ };
+}
+
+var milliseconds = makeGetter('milliseconds');
+var seconds = makeGetter('seconds');
+var minutes = makeGetter('minutes');
+var hours = makeGetter('hours');
+var days = makeGetter('days');
+var months = makeGetter('months');
+var years = makeGetter('years');
+
+function weeks () {
+ return absFloor(this.days() / 7);
+}
+
+var round = Math.round;
+var thresholds = {
+ s: 45, // seconds to minute
+ m: 45, // minutes to hour
+ h: 22, // hours to day
+ d: 26, // days to month
+ M: 11 // months to year
+};
+
+// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
+function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
+ return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
+}
+
+function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
+ var duration = createDuration(posNegDuration).abs();
+ var seconds = round(duration.as('s'));
+ var minutes = round(duration.as('m'));
+ var hours = round(duration.as('h'));
+ var days = round(duration.as('d'));
+ var months = round(duration.as('M'));
+ var years = round(duration.as('y'));
+
+ var a = seconds < thresholds.s && ['s', seconds] ||
+ minutes <= 1 && ['m'] ||
+ minutes < thresholds.m && ['mm', minutes] ||
+ hours <= 1 && ['h'] ||
+ hours < thresholds.h && ['hh', hours] ||
+ days <= 1 && ['d'] ||
+ days < thresholds.d && ['dd', days] ||
+ months <= 1 && ['M'] ||
+ months < thresholds.M && ['MM', months] ||
+ years <= 1 && ['y'] || ['yy', years];
+
+ a[2] = withoutSuffix;
+ a[3] = +posNegDuration > 0;
+ a[4] = locale;
+ return substituteTimeAgo.apply(null, a);
+}
+
+// This function allows you to set the rounding function for relative time strings
+function getSetRelativeTimeRounding (roundingFunction) {
+ if (roundingFunction === undefined) {
+ return round;
+ }
+ if (typeof(roundingFunction) === 'function') {
+ round = roundingFunction;
+ return true;
+ }
+ return false;
+}
+
+// This function allows you to set a threshold for relative time strings
+function getSetRelativeTimeThreshold (threshold, limit) {
+ if (thresholds[threshold] === undefined) {
+ return false;
+ }
+ if (limit === undefined) {
+ return thresholds[threshold];
+ }
+ thresholds[threshold] = limit;
+ return true;
+}
+
+function humanize (withSuffix) {
+ var locale = this.localeData();
+ var output = relativeTime$1(this, !withSuffix, locale);
+
+ if (withSuffix) {
+ output = locale.pastFuture(+this, output);
+ }
+
+ return locale.postformat(output);
+}
+
+var abs$1 = Math.abs;
+
+function toISOString$1() {
+ // for ISO strings we do not use the normal bubbling rules:
+ // * milliseconds bubble up until they become hours
+ // * days do not bubble at all
+ // * months bubble up until they become years
+ // This is because there is no context-free conversion between hours and days
+ // (think of clock changes)
+ // and also not between days and months (28-31 days per month)
+ var seconds = abs$1(this._milliseconds) / 1000;
+ var days = abs$1(this._days);
+ var months = abs$1(this._months);
+ var minutes, hours, years;
+
+ // 3600 seconds -> 60 minutes -> 1 hour
+ minutes = absFloor(seconds / 60);
+ hours = absFloor(minutes / 60);
+ seconds %= 60;
+ minutes %= 60;
+
+ // 12 months -> 1 year
+ years = absFloor(months / 12);
+ months %= 12;
+
+
+ // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
+ var Y = years;
+ var M = months;
+ var D = days;
+ var h = hours;
+ var m = minutes;
+ var s = seconds;
+ var total = this.asSeconds();
+
+ if (!total) {
+ // this is the same as C#'s (Noda) and python (isodate)...
+ // but not other JS (goog.date)
+ return 'P0D';
+ }
+
+ return (total < 0 ? '-' : '') +
+ 'P' +
+ (Y ? Y + 'Y' : '') +
+ (M ? M + 'M' : '') +
+ (D ? D + 'D' : '') +
+ ((h || m || s) ? 'T' : '') +
+ (h ? h + 'H' : '') +
+ (m ? m + 'M' : '') +
+ (s ? s + 'S' : '');
+}
+
+var proto$2 = Duration.prototype;
+
+proto$2.abs = abs;
+proto$2.add = add$1;
+proto$2.subtract = subtract$1;
+proto$2.as = as;
+proto$2.asMilliseconds = asMilliseconds;
+proto$2.asSeconds = asSeconds;
+proto$2.asMinutes = asMinutes;
+proto$2.asHours = asHours;
+proto$2.asDays = asDays;
+proto$2.asWeeks = asWeeks;
+proto$2.asMonths = asMonths;
+proto$2.asYears = asYears;
+proto$2.valueOf = valueOf$1;
+proto$2._bubble = bubble;
+proto$2.get = get$2;
+proto$2.milliseconds = milliseconds;
+proto$2.seconds = seconds;
+proto$2.minutes = minutes;
+proto$2.hours = hours;
+proto$2.days = days;
+proto$2.weeks = weeks;
+proto$2.months = months;
+proto$2.years = years;
+proto$2.humanize = humanize;
+proto$2.toISOString = toISOString$1;
+proto$2.toString = toISOString$1;
+proto$2.toJSON = toISOString$1;
+proto$2.locale = locale;
+proto$2.localeData = localeData;
+
+// Deprecations
+proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
+proto$2.lang = lang;
+
+// Side effect imports
+
+// FORMATTING
+
+addFormatToken('X', 0, 0, 'unix');
+addFormatToken('x', 0, 0, 'valueOf');
+
+// PARSING
+
+addRegexToken('x', matchSigned);
+addRegexToken('X', matchTimestamp);
+addParseToken('X', function (input, array, config) {
+ config._d = new Date(parseFloat(input, 10) * 1000);
+});
+addParseToken('x', function (input, array, config) {
+ config._d = new Date(toInt(input));
+});
+
+// Side effect imports
+
+
+hooks.version = '2.17.1';
+
+setHookCallback(createLocal);
+
+hooks.fn = proto;
+hooks.min = min;
+hooks.max = max;
+hooks.now = now;
+hooks.utc = createUTC;
+hooks.unix = createUnix;
+hooks.months = listMonths;
+hooks.isDate = isDate;
+hooks.locale = getSetGlobalLocale;
+hooks.invalid = createInvalid;
+hooks.duration = createDuration;
+hooks.isMoment = isMoment;
+hooks.weekdays = listWeekdays;
+hooks.parseZone = createInZone;
+hooks.localeData = getLocale;
+hooks.isDuration = isDuration;
+hooks.monthsShort = listMonthsShort;
+hooks.weekdaysMin = listWeekdaysMin;
+hooks.defineLocale = defineLocale;
+hooks.updateLocale = updateLocale;
+hooks.locales = listLocales;
+hooks.weekdaysShort = listWeekdaysShort;
+hooks.normalizeUnits = normalizeUnits;
+hooks.relativeTimeRounding = getSetRelativeTimeRounding;
+hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
+hooks.calendarFormat = getCalendarFormat;
+hooks.prototype = proto;
+
+return hooks;
+
+})));
\ No newline at end of file
diff --git a/scrummer/static/src/js/lib/external/waypoint.js b/scrummer/static/src/js/lib/external/waypoint.js
new file mode 100644
index 0000000..d70b245
--- /dev/null
+++ b/scrummer/static/src/js/lib/external/waypoint.js
@@ -0,0 +1,662 @@
+/*!
+Waypoints - 4.0.1
+Copyright © 2011-2016 Caleb Troughton
+Licensed under the MIT license.
+https://github.com/imakewebthings/waypoints/blob/master/licenses.txt
+*/
+(function() {
+ 'use strict'
+
+ var keyCounter = 0
+ var allWaypoints = {}
+
+ /* http://imakewebthings.com/waypoints/api/waypoint */
+ function Waypoint(options) {
+ if (!options) {
+ throw new Error('No options passed to Waypoint constructor')
+ }
+ if (!options.element) {
+ throw new Error('No element option passed to Waypoint constructor')
+ }
+ if (!options.handler) {
+ throw new Error('No handler option passed to Waypoint constructor')
+ }
+
+ this.key = 'waypoint-' + keyCounter
+ this.options = Waypoint.Adapter.extend({}, Waypoint.defaults, options)
+ this.element = this.options.element
+ this.adapter = new Waypoint.Adapter(this.element)
+ this.callback = options.handler
+ this.axis = this.options.horizontal ? 'horizontal' : 'vertical'
+ this.enabled = this.options.enabled
+ this.triggerPoint = null
+ this.group = Waypoint.Group.findOrCreate({
+ name: this.options.group,
+ axis: this.axis
+ })
+ this.context = Waypoint.Context.findOrCreateByElement(this.options.context)
+
+ if (Waypoint.offsetAliases[this.options.offset]) {
+ this.options.offset = Waypoint.offsetAliases[this.options.offset]
+ }
+ this.group.add(this)
+ this.context.add(this)
+ allWaypoints[this.key] = this
+ keyCounter += 1
+ }
+
+ /* Private */
+ Waypoint.prototype.queueTrigger = function(direction) {
+ this.group.queueTrigger(this, direction)
+ }
+
+ /* Private */
+ Waypoint.prototype.trigger = function(args) {
+ if (!this.enabled) {
+ return
+ }
+ if (this.callback) {
+ this.callback.apply(this, args)
+ }
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/destroy */
+ Waypoint.prototype.destroy = function() {
+ this.context.remove(this)
+ this.group.remove(this)
+ delete allWaypoints[this.key]
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/disable */
+ Waypoint.prototype.disable = function() {
+ this.enabled = false
+ return this
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/enable */
+ Waypoint.prototype.enable = function() {
+ this.context.refresh()
+ this.enabled = true
+ return this
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/next */
+ Waypoint.prototype.next = function() {
+ return this.group.next(this)
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/previous */
+ Waypoint.prototype.previous = function() {
+ return this.group.previous(this)
+ }
+
+ /* Private */
+ Waypoint.invokeAll = function(method) {
+ var allWaypointsArray = []
+ for (var waypointKey in allWaypoints) {
+ allWaypointsArray.push(allWaypoints[waypointKey])
+ }
+ for (var i = 0, end = allWaypointsArray.length; i < end; i++) {
+ allWaypointsArray[i][method]()
+ }
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/destroy-all */
+ Waypoint.destroyAll = function() {
+ Waypoint.invokeAll('destroy')
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/disable-all */
+ Waypoint.disableAll = function() {
+ Waypoint.invokeAll('disable')
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/enable-all */
+ Waypoint.enableAll = function() {
+ Waypoint.Context.refreshAll()
+ for (var waypointKey in allWaypoints) {
+ allWaypoints[waypointKey].enabled = true
+ }
+ return this
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/refresh-all */
+ Waypoint.refreshAll = function() {
+ Waypoint.Context.refreshAll()
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/viewport-height */
+ Waypoint.viewportHeight = function() {
+ return window.innerHeight || document.documentElement.clientHeight
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/viewport-width */
+ Waypoint.viewportWidth = function() {
+ return document.documentElement.clientWidth
+ }
+
+ Waypoint.adapters = []
+
+ Waypoint.defaults = {
+ context: window,
+ continuous: true,
+ enabled: true,
+ group: 'default',
+ horizontal: false,
+ offset: 0
+ }
+
+ Waypoint.offsetAliases = {
+ 'bottom-in-view': function() {
+ return this.context.innerHeight() - this.adapter.outerHeight()
+ },
+ 'right-in-view': function() {
+ return this.context.innerWidth() - this.adapter.outerWidth()
+ }
+ }
+
+ window.Waypoint = Waypoint
+}())
+;(function() {
+ 'use strict'
+
+ function requestAnimationFrameShim(callback) {
+ window.setTimeout(callback, 1000 / 60)
+ }
+
+ var keyCounter = 0
+ var contexts = {}
+ var Waypoint = window.Waypoint
+ var oldWindowLoad = window.onload
+
+ /* http://imakewebthings.com/waypoints/api/context */
+ function Context(element) {
+ this.element = element
+ this.Adapter = Waypoint.Adapter
+ this.adapter = new this.Adapter(element)
+ this.key = 'waypoint-context-' + keyCounter
+ this.didScroll = false
+ this.didResize = false
+ this.oldScroll = {
+ x: this.adapter.scrollLeft(),
+ y: this.adapter.scrollTop()
+ }
+ this.waypoints = {
+ vertical: {},
+ horizontal: {}
+ }
+
+ element.waypointContextKey = this.key
+ contexts[element.waypointContextKey] = this
+ keyCounter += 1
+ if (!Waypoint.windowContext) {
+ Waypoint.windowContext = true
+ Waypoint.windowContext = new Context(window)
+ }
+
+ this.createThrottledScrollHandler()
+ this.createThrottledResizeHandler()
+ }
+
+ /* Private */
+ Context.prototype.add = function(waypoint) {
+ var axis = waypoint.options.horizontal ? 'horizontal' : 'vertical'
+ this.waypoints[axis][waypoint.key] = waypoint
+ this.refresh()
+ }
+
+ /* Private */
+ Context.prototype.checkEmpty = function() {
+ var horizontalEmpty = this.Adapter.isEmptyObject(this.waypoints.horizontal)
+ var verticalEmpty = this.Adapter.isEmptyObject(this.waypoints.vertical)
+ var isWindow = this.element == this.element.window
+ if (horizontalEmpty && verticalEmpty && !isWindow) {
+ this.adapter.off('.waypoints')
+ delete contexts[this.key]
+ }
+ }
+
+ /* Private */
+ Context.prototype.createThrottledResizeHandler = function() {
+ var self = this
+
+ function resizeHandler() {
+ self.handleResize()
+ self.didResize = false
+ }
+
+ this.adapter.on('resize.waypoints', function() {
+ if (!self.didResize) {
+ self.didResize = true
+ Waypoint.requestAnimationFrame(resizeHandler)
+ }
+ })
+ }
+
+ /* Private */
+ Context.prototype.createThrottledScrollHandler = function() {
+ var self = this
+ function scrollHandler() {
+ self.handleScroll()
+ self.didScroll = false
+ }
+
+ this.adapter.on('scroll.waypoints', function() {
+ if (!self.didScroll || Waypoint.isTouch) {
+ self.didScroll = true
+ Waypoint.requestAnimationFrame(scrollHandler)
+ }
+ })
+ }
+
+ /* Private */
+ Context.prototype.handleResize = function() {
+ Waypoint.Context.refreshAll()
+ }
+
+ /* Private */
+ Context.prototype.handleScroll = function() {
+ var triggeredGroups = {}
+ var axes = {
+ horizontal: {
+ newScroll: this.adapter.scrollLeft(),
+ oldScroll: this.oldScroll.x,
+ forward: 'right',
+ backward: 'left'
+ },
+ vertical: {
+ newScroll: this.adapter.scrollTop(),
+ oldScroll: this.oldScroll.y,
+ forward: 'down',
+ backward: 'up'
+ }
+ }
+
+ for (var axisKey in axes) {
+ var axis = axes[axisKey]
+ var isForward = axis.newScroll > axis.oldScroll
+ var direction = isForward ? axis.forward : axis.backward
+
+ for (var waypointKey in this.waypoints[axisKey]) {
+ var waypoint = this.waypoints[axisKey][waypointKey]
+ if (waypoint.triggerPoint === null) {
+ continue
+ }
+ var wasBeforeTriggerPoint = axis.oldScroll < waypoint.triggerPoint
+ var nowAfterTriggerPoint = axis.newScroll >= waypoint.triggerPoint
+ var crossedForward = wasBeforeTriggerPoint && nowAfterTriggerPoint
+ var crossedBackward = !wasBeforeTriggerPoint && !nowAfterTriggerPoint
+ if (crossedForward || crossedBackward) {
+ waypoint.queueTrigger(direction)
+ triggeredGroups[waypoint.group.id] = waypoint.group
+ }
+ }
+ }
+
+ for (var groupKey in triggeredGroups) {
+ triggeredGroups[groupKey].flushTriggers()
+ }
+
+ this.oldScroll = {
+ x: axes.horizontal.newScroll,
+ y: axes.vertical.newScroll
+ }
+ }
+
+ /* Private */
+ Context.prototype.innerHeight = function() {
+ /*eslint-disable eqeqeq */
+ if (this.element == this.element.window) {
+ return Waypoint.viewportHeight()
+ }
+ /*eslint-enable eqeqeq */
+ return this.adapter.innerHeight()
+ }
+
+ /* Private */
+ Context.prototype.remove = function(waypoint) {
+ delete this.waypoints[waypoint.axis][waypoint.key]
+ this.checkEmpty()
+ }
+
+ /* Private */
+ Context.prototype.innerWidth = function() {
+ /*eslint-disable eqeqeq */
+ if (this.element == this.element.window) {
+ return Waypoint.viewportWidth()
+ }
+ /*eslint-enable eqeqeq */
+ return this.adapter.innerWidth()
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/context-destroy */
+ Context.prototype.destroy = function() {
+ var allWaypoints = []
+ for (var axis in this.waypoints) {
+ for (var waypointKey in this.waypoints[axis]) {
+ allWaypoints.push(this.waypoints[axis][waypointKey])
+ }
+ }
+ for (var i = 0, end = allWaypoints.length; i < end; i++) {
+ allWaypoints[i].destroy()
+ }
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/context-refresh */
+ Context.prototype.refresh = function() {
+ /*eslint-disable eqeqeq */
+ var isWindow = this.element == this.element.window
+ /*eslint-enable eqeqeq */
+ var contextOffset = isWindow ? undefined : this.adapter.offset()
+ var triggeredGroups = {}
+ var axes
+
+ this.handleScroll()
+ axes = {
+ horizontal: {
+ contextOffset: isWindow ? 0 : contextOffset.left,
+ contextScroll: isWindow ? 0 : this.oldScroll.x,
+ contextDimension: this.innerWidth(),
+ oldScroll: this.oldScroll.x,
+ forward: 'right',
+ backward: 'left',
+ offsetProp: 'left'
+ },
+ vertical: {
+ contextOffset: isWindow ? 0 : contextOffset.top,
+ contextScroll: isWindow ? 0 : this.oldScroll.y,
+ contextDimension: this.innerHeight(),
+ oldScroll: this.oldScroll.y,
+ forward: 'down',
+ backward: 'up',
+ offsetProp: 'top'
+ }
+ }
+
+ for (var axisKey in axes) {
+ var axis = axes[axisKey]
+ for (var waypointKey in this.waypoints[axisKey]) {
+ var waypoint = this.waypoints[axisKey][waypointKey]
+ var adjustment = waypoint.options.offset
+ var oldTriggerPoint = waypoint.triggerPoint
+ var elementOffset = 0
+ var freshWaypoint = oldTriggerPoint == null
+ var contextModifier, wasBeforeScroll, nowAfterScroll
+ var triggeredBackward, triggeredForward
+
+ if (waypoint.element !== waypoint.element.window) {
+ elementOffset = waypoint.adapter.offset()[axis.offsetProp]
+ }
+
+ if (typeof adjustment === 'function') {
+ adjustment = adjustment.apply(waypoint)
+ }
+ else if (typeof adjustment === 'string') {
+ adjustment = parseFloat(adjustment)
+ if (waypoint.options.offset.indexOf('%') > - 1) {
+ adjustment = Math.ceil(axis.contextDimension * adjustment / 100)
+ }
+ }
+
+ contextModifier = axis.contextScroll - axis.contextOffset
+ waypoint.triggerPoint = Math.floor(elementOffset + contextModifier - adjustment)
+ wasBeforeScroll = oldTriggerPoint < axis.oldScroll
+ nowAfterScroll = waypoint.triggerPoint >= axis.oldScroll
+ triggeredBackward = wasBeforeScroll && nowAfterScroll
+ triggeredForward = !wasBeforeScroll && !nowAfterScroll
+
+ if (!freshWaypoint && triggeredBackward) {
+ waypoint.queueTrigger(axis.backward)
+ triggeredGroups[waypoint.group.id] = waypoint.group
+ }
+ else if (!freshWaypoint && triggeredForward) {
+ waypoint.queueTrigger(axis.forward)
+ triggeredGroups[waypoint.group.id] = waypoint.group
+ }
+ else if (freshWaypoint && axis.oldScroll >= waypoint.triggerPoint) {
+ waypoint.queueTrigger(axis.forward)
+ triggeredGroups[waypoint.group.id] = waypoint.group
+ }
+ }
+ }
+
+ Waypoint.requestAnimationFrame(function() {
+ for (var groupKey in triggeredGroups) {
+ triggeredGroups[groupKey].flushTriggers()
+ }
+ })
+
+ return this
+ }
+
+ /* Private */
+ Context.findOrCreateByElement = function(element) {
+ return Context.findByElement(element) || new Context(element)
+ }
+
+ /* Private */
+ Context.refreshAll = function() {
+ for (var contextId in contexts) {
+ contexts[contextId].refresh()
+ }
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/context-find-by-element */
+ Context.findByElement = function(element) {
+ return contexts[element.waypointContextKey]
+ }
+
+ window.onload = function() {
+ if (oldWindowLoad) {
+ oldWindowLoad()
+ }
+ Context.refreshAll()
+ }
+
+
+ Waypoint.requestAnimationFrame = function(callback) {
+ var requestFn = window.requestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ requestAnimationFrameShim
+ requestFn.call(window, callback)
+ }
+ Waypoint.Context = Context
+}())
+;(function() {
+ 'use strict'
+
+ function byTriggerPoint(a, b) {
+ return a.triggerPoint - b.triggerPoint
+ }
+
+ function byReverseTriggerPoint(a, b) {
+ return b.triggerPoint - a.triggerPoint
+ }
+
+ var groups = {
+ vertical: {},
+ horizontal: {}
+ }
+ var Waypoint = window.Waypoint
+
+ /* http://imakewebthings.com/waypoints/api/group */
+ function Group(options) {
+ this.name = options.name
+ this.axis = options.axis
+ this.id = this.name + '-' + this.axis
+ this.waypoints = []
+ this.clearTriggerQueues()
+ groups[this.axis][this.name] = this
+ }
+
+ /* Private */
+ Group.prototype.add = function(waypoint) {
+ this.waypoints.push(waypoint)
+ }
+
+ /* Private */
+ Group.prototype.clearTriggerQueues = function() {
+ this.triggerQueues = {
+ up: [],
+ down: [],
+ left: [],
+ right: []
+ }
+ }
+
+ /* Private */
+ Group.prototype.flushTriggers = function() {
+ for (var direction in this.triggerQueues) {
+ var waypoints = this.triggerQueues[direction]
+ var reverse = direction === 'up' || direction === 'left'
+ waypoints.sort(reverse ? byReverseTriggerPoint : byTriggerPoint)
+ for (var i = 0, end = waypoints.length; i < end; i += 1) {
+ var waypoint = waypoints[i]
+ if (waypoint.options.continuous || i === waypoints.length - 1) {
+ waypoint.trigger([direction])
+ }
+ }
+ }
+ this.clearTriggerQueues()
+ }
+
+ /* Private */
+ Group.prototype.next = function(waypoint) {
+ this.waypoints.sort(byTriggerPoint)
+ var index = Waypoint.Adapter.inArray(waypoint, this.waypoints)
+ var isLast = index === this.waypoints.length - 1
+ return isLast ? null : this.waypoints[index + 1]
+ }
+
+ /* Private */
+ Group.prototype.previous = function(waypoint) {
+ this.waypoints.sort(byTriggerPoint)
+ var index = Waypoint.Adapter.inArray(waypoint, this.waypoints)
+ return index ? this.waypoints[index - 1] : null
+ }
+
+ /* Private */
+ Group.prototype.queueTrigger = function(waypoint, direction) {
+ this.triggerQueues[direction].push(waypoint)
+ }
+
+ /* Private */
+ Group.prototype.remove = function(waypoint) {
+ var index = Waypoint.Adapter.inArray(waypoint, this.waypoints)
+ if (index > -1) {
+ this.waypoints.splice(index, 1)
+ }
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/first */
+ Group.prototype.first = function() {
+ return this.waypoints[0]
+ }
+
+ /* Public */
+ /* http://imakewebthings.com/waypoints/api/last */
+ Group.prototype.last = function() {
+ return this.waypoints[this.waypoints.length - 1]
+ }
+
+ /* Private */
+ Group.findOrCreate = function(options) {
+ return groups[options.axis][options.name] || new Group(options)
+ }
+
+ Waypoint.Group = Group
+}())
+;(function() {
+ 'use strict'
+
+ var $ = window.jQuery
+ var Waypoint = window.Waypoint
+
+ function JQueryAdapter(element) {
+ this.$element = $(element)
+ }
+
+ $.each([
+ 'innerHeight',
+ 'innerWidth',
+ 'off',
+ 'offset',
+ 'on',
+ 'outerHeight',
+ 'outerWidth',
+ 'scrollLeft',
+ 'scrollTop'
+ ], function(i, method) {
+ JQueryAdapter.prototype[method] = function() {
+ var args = Array.prototype.slice.call(arguments)
+ return this.$element[method].apply(this.$element, args)
+ }
+ })
+
+ $.each([
+ 'extend',
+ 'inArray',
+ 'isEmptyObject'
+ ], function(i, method) {
+ JQueryAdapter[method] = $[method]
+ })
+
+ Waypoint.adapters.push({
+ name: 'jquery',
+ Adapter: JQueryAdapter
+ })
+ Waypoint.Adapter = JQueryAdapter
+}())
+;(function() {
+ 'use strict'
+
+ var Waypoint = window.Waypoint
+
+ function createExtension(framework) {
+ return function() {
+ var waypoints = []
+ var overrides = arguments[0]
+
+ if (framework.isFunction(arguments[0])) {
+ overrides = framework.extend({}, arguments[1])
+ overrides.handler = arguments[0]
+ }
+
+ this.each(function() {
+ var options = framework.extend({}, overrides, {
+ element: this
+ })
+ if (typeof options.context === 'string') {
+ options.context = framework(this).closest(options.context)[0]
+ }
+ waypoints.push(new Waypoint(options))
+ })
+
+ return waypoints
+ }
+ }
+
+ if (window.jQuery) {
+ window.jQuery.fn.waypoint = createExtension(window.jQuery)
+ }
+ if (window.Zepto) {
+ window.Zepto.fn.waypoint = createExtension(window.Zepto)
+ }
+}())
+;
\ No newline at end of file
diff --git a/scrummer/static/src/js/lib/jquery-validate.js b/scrummer/static/src/js/lib/jquery-validate.js
new file mode 100644
index 0000000..3ab1381
--- /dev/null
+++ b/scrummer/static/src/js/lib/jquery-validate.js
@@ -0,0 +1,37 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+odoo.define('jquery-validator', function (require) {
+ var _t = require('web.core')._t;
+
+ jQuery.validator.setDefaults({
+ messages: {
+ required: _t("This field is required."),
+ remote: _t("Please fix this field."),
+ email: _t("Please enter a valid email address."),
+ url: _t("Please enter a valid URL."),
+ date: _t("Please enter a valid date."),
+ dateISO: _t("Please enter a valid date (ISO)."),
+ number: _t("Please enter a valid number."),
+ digits: _t("Please enter only digits."),
+ equalTo: _t("Please enter the same value again."),
+ maxlength: $.validator.format(_t("Please enter no more than {0} characters.")),
+ minlength: $.validator.format(_t("Please enter at least {0} characters.")),
+ rangelength: $.validator.format(_t("Please enter a value between {0} and {1} characters long.")),
+ range: $.validator.format(_t("Please enter a value between {0} and {1}.")),
+ max: $.validator.format(_t("Please enter a value less than or equal to {0}.")),
+ min: $.validator.format(_t("Please enter a value greater than or equal to {0}.")),
+ step: $.validator.format(_t("Please enter a multiple of {0}."))
+ },
+ ignore:"",
+ validClass:"",
+ errorElement: 'div',
+ errorPlacement: function (error, element) {
+ var placement = $(element).data('error');
+ if (placement) {
+ $(placement).append(error)
+ } else {
+ error.insertAfter(element);
+ }
+ }
+ });
+});
diff --git a/scrummer/static/src/js/lib/materialNoteOverrides.js b/scrummer/static/src/js/lib/materialNoteOverrides.js
new file mode 100644
index 0000000..301ad6f
--- /dev/null
+++ b/scrummer/static/src/js/lib/materialNoteOverrides.js
@@ -0,0 +1,197 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+(function ($) {
+ $.fn.ckTooltip = function (options) {
+ var timeout = null,
+ counter = null,
+ started = false,
+ counterInterval = null,
+ margin = 5;
+
+ // Defaults
+ var defaults = {
+ delay: 350
+ };
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+ var origin = $(this);
+
+ // Create Text span
+ var tooltip_text = $(' ').text(origin.attr('data-tooltip'));
+
+ // Create tooltip
+ var newTooltip = $('
');
+ newTooltip.addClass('material-tooltip').append(tooltip_text);
+ newTooltip.appendTo($('body'));
+
+ var backdrop = $('
').addClass('backdrop');
+ backdrop.appendTo(newTooltip);
+ backdrop.css({top: 0, left: 0});
+
+ //Destroy previously binded events
+ //$(this).off('mouseenter mouseleave');
+
+ $.event.special.destroyed = {
+ remove: function (o) {
+ if (o.handler) {
+ o.handler();
+ }
+ }
+ };
+ $(this).bind('destroyed', function () {
+ newTooltip.remove();
+ });
+
+ // Mouse In
+ $(this).on({
+ mouseenter: function (e) {
+ var tooltip_delay = origin.data("delay");
+
+ tooltip_delay = (tooltip_delay === undefined || tooltip_delay === '') ? options.delay : tooltip_delay;
+ counter = 0;
+ counterInterval = setInterval(function () {
+ counter += 10;
+
+ if (counter >= tooltip_delay && started === false) {
+ started = true;
+ newTooltip.css({display: 'block', left: '0px', top: '0px'});
+
+ // Set Tooltip text
+ newTooltip.children('span').text(origin.attr('data-tooltip'));
+
+ // Tooltip positioning
+ var originWidth = origin.outerWidth();
+ var originHeight = origin.outerHeight();
+ var tooltipPosition = origin.attr('data-position');
+ var tooltipHeight = newTooltip.outerHeight();
+ var tooltipWidth = newTooltip.outerWidth();
+ var tooltipVerticalMovement = '0px';
+ var tooltipHorizontalMovement = '0px';
+ var scale_factor = 8;
+
+ if (tooltipPosition === "top") {
+ // Top Position
+ newTooltip.css({
+ top: origin.offset().top - tooltipHeight - margin,
+ left: origin.offset().left + originWidth / 2 - tooltipWidth / 2
+ });
+ tooltipVerticalMovement = '-10px';
+ backdrop.css({
+ borderRadius: '14px 14px 0 0',
+ transformOrigin: '50% 90%',
+ marginTop: tooltipHeight,
+ marginLeft: (tooltipWidth / 2) - (backdrop.width() / 2)
+
+ });
+ }
+ // Left Position
+ else if (tooltipPosition === "left") {
+ newTooltip.css({
+ top: origin.offset().top + originHeight / 2 - tooltipHeight / 2,
+ left: origin.offset().left - tooltipWidth - margin
+ });
+ tooltipHorizontalMovement = '-10px';
+ backdrop.css({
+ width: '14px',
+ height: '14px',
+ borderRadius: '14px 0 0 14px',
+ transformOrigin: '95% 50%',
+ marginTop: tooltipHeight / 2,
+ marginLeft: tooltipWidth
+ });
+ }
+ // Right Position
+ else if (tooltipPosition === "right") {
+ newTooltip.css({
+ top: origin.offset().top + originHeight / 2 - tooltipHeight / 2,
+ left: origin.offset().left + originWidth + margin
+ });
+ tooltipHorizontalMovement = '+10px';
+ backdrop.css({
+ width: '14px',
+ height: '14px',
+ borderRadius: '0 14px 14px 0',
+ transformOrigin: '5% 50%',
+ marginTop: tooltipHeight / 2,
+ marginLeft: '0px'
+ });
+ }
+ else {
+ // Bottom Position
+ newTooltip.css({
+ top: origin.offset().top + origin.outerHeight() + margin,
+ left: origin.offset().left + originWidth / 2 - tooltipWidth / 2
+ });
+ tooltipVerticalMovement = '+10px';
+ backdrop.css({
+ marginLeft: (tooltipWidth / 2) - (backdrop.width() / 2)
+ });
+ }
+
+ // Calculate Scale to fill
+ scale_factor = tooltipWidth / 8;
+ if (scale_factor < 8) {
+ scale_factor = 8;
+ }
+ if (tooltipPosition === "right" || tooltipPosition === "left") {
+ scale_factor = tooltipWidth / 10;
+ if (scale_factor < 6)
+ scale_factor = 6;
+ }
+
+ newTooltip.velocity({
+ opacity: 1,
+ marginTop: tooltipVerticalMovement,
+ marginLeft: tooltipHorizontalMovement
+ }, {duration: 150, queue: false});
+ backdrop.css({display: 'block'})
+ .velocity({opacity: 1}, {duration: 50, delay: 0, queue: false})
+ .velocity({scale: scale_factor}, {duration: 150, delay: 0, queue: false, easing: 'easeInOutQuad'});
+ }
+ }, 10); // End Interval
+
+ // Mouse Out
+ },
+ mouseleave: function () {
+ // Reset State
+ clearInterval(counterInterval);
+ counter = 0;
+
+ // Animate back
+ newTooltip.velocity({
+ opacity: 0, marginTop: 0, marginLeft: 0
+ }, {duration: 150, queue: false, delay: 50}
+ );
+ backdrop.velocity({opacity: 0, scale: 1}, {
+ duration: 150,
+ delay: 50, queue: false,
+ complete: function () {
+ backdrop.css('display', 'none');
+ newTooltip.css('display', 'none');
+ started = false;
+ }
+ });
+ }
+ });
+ });
+ };
+ // $.materialnote.eventHandler.modules.clipboard.attach = function (layoutInfo) {
+ // var $editable = layoutInfo.editable();
+ // $editable.on('paste', function (e) {
+ // var clipboardData = ((e.originalEvent || e).clipboardData || window.clipboardData);
+ // // Change nothing if pasting html (copy from text editor / web / ...) or
+ // // if clipboardData is not available (IE / ...)
+ // if (clipboardData && clipboardData.types && clipboardData.types.length === 1 && clipboardData.types[0] === "text/plain") {
+ // e.preventDefault();
+ // $editable.data('NoteHistory').recordUndo($editable); // FIXME
+ // var pastedText = clipboardData.getData("text/plain");
+ // // Try removing linebreaks which are not really linebreaks (in a PDF,
+ // // when a sentence goes over the next line, copying it considers it
+ // // a linebreak for example).
+ // var formattedText = pastedText.replace(/([\w-])\r?\n([\w-])/g, "$1 $2").trim();
+ // document.execCommand("insertText", false, formattedText);
+ // }
+ // });
+ // };
+}(jQuery));
diff --git a/scrummer/static/src/js/lib/my-jquery-extensions.js b/scrummer/static/src/js/lib/my-jquery-extensions.js
new file mode 100644
index 0000000..6a4ab42
--- /dev/null
+++ b/scrummer/static/src/js/lib/my-jquery-extensions.js
@@ -0,0 +1,735 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+'use strict';
+jQuery.fn.getDataFromAncestor = function (dataAttr, oldest = "body") {
+ var el = $(this[0]);
+ return el.is(oldest) || el.data(dataAttr) !== undefined || el.parent().length == 0 ? el.data(dataAttr) : el.parent().getDataFromAncestor(dataAttr);
+};
+
+$.fn.insertAt = function (elements, index) {
+ if (index >= this.children().size()) {
+ this.append(elements);
+ } else {
+ var before = this.children().eq(index);
+ $(elements).insertBefore(before);
+ }
+ return this;
+};
+
+$.fn.serializeObject = function () {
+ var o = {};
+ var a = this.serializeArray();
+ $.each(a, function () {
+ // convert value to Number if possible
+ if (!isNaN(Number(this.value))) {
+ this.value = Number(this.value);
+ }
+ if (o[this.name] !== undefined) {
+ if (!o[this.name].push) {
+ o[this.name] = [o[this.name]];
+ }
+ o[this.name].push(this.value || '');
+ } else {
+ o[this.name] = this.value || '';
+ }
+ });
+ return o;
+};
+$.fn.scrollToElement = function (element, duration = 500) {
+ this.animate({
+ scrollTop: element.offset().top
+ - this.offset().top
+ + this.scrollTop()
+ - Math.round(this.height() / 2)
+ + element.outerHeight()
+ }, duration);
+};
+$.fn.highlight = function () {
+ this.css("position", "relative");
+ let overlay = $('
');
+ this.append(overlay);
+ overlay.animate({opacity: 0.1}, 1000, function () {
+ $(this).remove();
+ });
+};
+
+$.fn.responsive = function () {
+ var medias = [
+ window.matchMedia('(max-width: 600px)'),
+ window.matchMedia('(min-width: 601px) and (max-width: 992px)'),
+ window.matchMedia('(min-width: 993px)')
+ ];
+ var current_class;
+ var classes = {
+ 0: "s",
+ 1: "m",
+ 2: "l"
+ };
+
+ // Checks which media is matched and returns appropriate class (s/m/l)
+ var size_class = () => {
+ for (var i = 0; i < medias.length; i++) {
+ if (medias[i].matches) {
+ return classes[i];
+ }
+ }
+ };
+
+ // Calls rearange if screen class has changed
+ var set_size_class = () => {
+ var sc = size_class();
+ if (sc !== current_class) {
+ current_class = sc;
+ rearange(sc);
+ }
+ };
+
+ // Finds all responsive elements and places them after anchor
+ // an example of anchor
+ //
+ var rearange = (sc) => {
+ this.find(".responsive").each((i, n) => {
+ let node = $(n);
+ let id = node.data("responsiveId");
+ let anchor = this.find(`responsive[data-id=${id}].${sc}`);
+ if (anchor.length > 1) {
+ throw new Error("Found multiple anchors for responsive jQuery element");
+ }
+ node.insertAfter(anchor);
+ })
+ };
+
+ medias.forEach(m => {
+ m.addListener(set_size_class);
+ });
+ rearange(size_class())
+};
+let guid = function () {
+ function s4() {
+ return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
+ }
+
+ return function () {
+ return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
+ };
+};
+$.fn.new_autocomplete = function (options) {
+ // Defaults
+ // New format means that ID is key, and value is object that contains name (required), src
+ var defaults = {
+ data: {},
+ delay: 200,
+ limit: Infinity,
+ onAutocomplete: null,
+ onRendered: null,
+ minLength: 1
+ };
+
+ options = $.extend(defaults, options);
+
+ return this.each(function () {
+ var $input = $(this);
+ var customDataEnabled = typeof options.customData === "function";
+ var getData = function (val) {
+ if (customDataEnabled) {
+ return options.customData(val);
+ }
+ return options.data;
+ }
+ var data = options.data;
+ var count = 0,
+ activeIndex = 0,
+ oldVal,
+ searching,
+ $inputDiv = $input.closest('.input-field'); // Div to append on
+
+ // Check if data isn't empty
+ if (customDataEnabled || !$.isEmptyObject(data)) {
+ var $autocomplete = $('');
+ var $oldAutocomplete;
+
+ // Append autocomplete element.
+ // Prevent double structure init.
+ if ($inputDiv.length) {
+ $oldAutocomplete = $inputDiv.children('.autocomplete-content.dropdown-content').first();
+ if (!$oldAutocomplete.length) {
+ $inputDiv.append($autocomplete); // Set ul in body
+ $inputDiv.addClass("autocomplete");
+ }
+ } else {
+ $oldAutocomplete = $input.next('.autocomplete-content.dropdown-content');
+ if (!$oldAutocomplete.length) {
+ $input.after($autocomplete);
+ }
+ }
+ if ($oldAutocomplete.length) {
+ $autocomplete = $oldAutocomplete;
+ }
+
+ // Highlight partial match.
+ var highlight = function (string, $el) {
+ var img = $el.find('img');
+ var matchStart = $el.text().toLowerCase().indexOf("" + string.toLowerCase() + ""),
+ matchEnd = matchStart + string.length - 1,
+ beforeMatch = $el.text().slice(0, matchStart),
+ matchText = $el.text().slice(matchStart, matchEnd + 1),
+ afterMatch = $el.text().slice(matchEnd + 1);
+ $el.html("" + beforeMatch + "" + matchText + " " + afterMatch + " ");
+ if (img.length) {
+ $el.prepend(img);
+ }
+ };
+
+ // Reset current element position
+ var resetCurrentElement = function () {
+ activeIndex = 0;
+ $autocomplete.find('.active').removeClass('active');
+ };
+
+ // Remove autocomplete elements
+ var removeAutocomplete = function () {
+ $autocomplete.empty();
+ resetCurrentElement();
+ };
+ var _delay = function (handler, delay) {
+ function handlerProxy() {
+ return (typeof handler === "string" ? instance[handler] : handler)
+ .apply(instance, arguments);
+ }
+
+ var instance = this;
+ return setTimeout(handlerProxy, delay || 0);
+ };
+ var _inputTimeout = function () {
+ var timestamp = Date.now();
+ $input.data("async-stamp", timestamp);
+ var val = $input.val().toLowerCase();
+
+ clearTimeout(searching);
+ searching = _delay(function () {
+ var equalValues = oldVal === val;
+
+ if (!equalValues) {
+ removeAutocomplete();
+ if (val.length >= options.minLength) {
+ $inputDiv = $input.closest(".autocomplete");
+ $inputDiv.addClass("autocomplete-loading");
+ $.when(getData(val)).then(function (data) {
+ if ($input.data("async-stamp") != timestamp) {
+ return;
+ }
+ for (var id in data) {
+ if (customDataEnabled || data.hasOwnProperty(id) && data[id].name.toLowerCase().indexOf(val) !== -1) {
+ if (!data[id].id) {
+ console.error("Missing ID in new_autocomplete data");
+ }
+ // Break if past limit
+ if (count >= options.limit) {
+ break;
+ }
+
+ var autocompleteOption = $(' ');
+ // set first as active
+ if (count === 0) {
+ autocompleteOption.addClass("active");
+ }
+ autocompleteOption.data("id", id);
+ if (!!data[id].imgurl) {
+ autocompleteOption.append('' + data[id].name + ' ');
+ } else {
+ autocompleteOption.append('' + data[id].name + ' ');
+ }
+
+ $autocomplete.append(autocompleteOption);
+ highlight(val, autocompleteOption);
+ count++;
+ }
+ }
+ // Handle onRendered callback.
+ if (typeof options.onRendered === "function") {
+ options.onRendered.call(this, $input.val(), $autocomplete);
+ }
+ $inputDiv.removeClass("autocomplete-loading");
+ });
+ }
+ }
+ // Update oldVal
+ oldVal = val;
+ }, options.delay);
+ };
+
+ $input.off('blur.autocomplete').on('blur.autocomplete', function () {
+ removeAutocomplete();
+ oldVal = undefined;
+ });
+
+ // Perform search
+ $input.off('keyup.autocomplete focus.autocomplete').on('keyup.autocomplete focus.autocomplete', function (e) {
+ // Reset count.
+ let val = $input.val();
+ count = 0;
+ // Don't capture enter or arrow key usage.
+ if (e.which === 13 || e.which === 38 || e.which === 40 || oldVal === val) {
+ return;
+ }
+ _inputTimeout()
+ });
+
+ $input.off('keydown.autocomplete').on('keydown.autocomplete', function (e) {
+ // Arrow keys and enter key usage
+ var keyCode = e.which,
+ liElement,
+ numItems = $autocomplete.children('li').length,
+ $active = $autocomplete.children('.active').first();
+
+ // select element on Enter
+ if (keyCode === 13 && activeIndex >= 0) {
+ liElement = $autocomplete.children('li').eq(activeIndex);
+ if (liElement.length) {
+ liElement.trigger('mousedown.autocomplete');
+ e.preventDefault();
+ }
+ return;
+ }
+ // If escape is pressed, close autocomplete
+ if (e.which === 27) {
+ removeAutocomplete();
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ return;
+ }
+
+ // Capture up and down key
+ if (keyCode === 38 || keyCode === 40) {
+ e.preventDefault();
+ if (numItems === 0) {
+ oldVal = undefined;
+ _inputTimeout();
+ return;
+ }
+ if (keyCode === 38 && activeIndex > 0) {
+ activeIndex--;
+ }
+
+ if (keyCode === 40 && activeIndex < numItems - 1) {
+ activeIndex++;
+ }
+
+ $active.removeClass('active');
+ if (activeIndex >= 0) {
+ $autocomplete.children('li').eq(activeIndex).addClass('active');
+ }
+ }
+ });
+
+ // Set input value
+ $autocomplete.off('mousedown.autocomplete touchstart.autocomplete').on('mousedown.autocomplete touchstart.autocomplete', 'li', function () {
+ var text = $(this).text().trim();
+ var autocompleteOptionId = $(this).data("id");
+ $input.val(text);
+ $input.data("autocompleteOptionId", autocompleteOptionId);
+ $input.trigger('change');
+ removeAutocomplete();
+
+ // Handle onAutocomplete callback.
+ if (typeof options.onAutocomplete === "function") {
+ options.onAutocomplete.call(this, text, autocompleteOptionId);
+ }
+ });
+
+ // Empty data
+ } else {
+ $input.off('keyup.autocomplete focus.autocomplete');
+ }
+ });
+};
+var materialChipsDefaults = {
+ data: [],
+ placeholder: '',
+ secondaryPlaceholder: '',
+ autocompleteOptions: {minLength: 0},
+ beforeDeleteHook: function (elem) {
+ return $.when();
+ },
+ beforeAddHook: function (elem) {
+ return $.when();
+ },
+};
+
+$(document).ready(function () {
+ // Handle removal of static chips.
+ $(document).on('click', '.chip .close', function (e) {
+ var $chips = $(this).closest('.chips');
+ if ($chips.attr('data-initialized')) {
+ return;
+ }
+ $(this).closest('.chip').remove();
+ });
+});
+
+$.fn.new_material_chip = function (options) {
+ var self = this;
+ this.$el = $(this);
+ this.$document = $(document);
+ this.SELS = {
+ CHIPS: '.chips',
+ CHIP: '.chip',
+ INPUT: 'input',
+ DELETE: '.material-icons',
+ SELECTED_CHIP: '.selected'
+ };
+
+ if ('data' === options) {
+ return this.$el.data('chips');
+ }
+ var autocomplete_options = $.extend({}, materialChipsDefaults.autocompleteOptions, options.autocompleteOptions);
+ var curr_options = $.extend({}, materialChipsDefaults, options);
+ curr_options.autocompleteOptions = autocomplete_options;
+ self.hasCustomAutocomplete = typeof curr_options.autocompleteOptions.customData === "function";
+ self.hasAutocomplete = self.hasCustomAutocomplete || !$.isEmptyObject(curr_options.autocompleteOptions.data);
+
+ // Initialize
+ this.init = function () {
+ var i = 0;
+ var chips;
+ self.$el.each(function () {
+ var $chips = $(this);
+ var chipId = Materialize.guid();
+ self.chipId = chipId;
+
+ if (!curr_options.data) {
+ curr_options.data = {};
+ }
+ $chips.data('chips', curr_options.data);
+ $chips.attr('data-index', i);
+ $chips.attr('data-initialized', true);
+
+ if (!$chips.hasClass(self.SELS.CHIPS)) {
+ $chips.addClass('chips');
+ }
+
+ self.chips($chips, chipId);
+ i++;
+ });
+ };
+
+ this.handleEvents = function () {
+ var SELS = self.SELS;
+
+ self.$document.off('click.chips-focus', SELS.CHIPS).on('click.chips-focus', SELS.CHIPS, function (e) {
+ $(e.target).find(SELS.INPUT).focus();
+ });
+
+ self.$document.off('click.chips-select', SELS.CHIP).on('click.chips-select', SELS.CHIP, function (e) {
+ var $chip = $(e.target);
+ if ($chip.length) {
+ var wasSelected = $chip.hasClass('selected');
+ var $chips = $chip.closest(SELS.CHIPS);
+ $(SELS.CHIP).removeClass('selected');
+
+ if (!wasSelected) {
+ self.selectChip($chip.index(), $chips);
+ }
+ }
+ });
+
+ self.$document.off('keydown.chips').on('keydown.chips', function (e) {
+ if ($(e.target).is('input, textarea')) {
+ return;
+ }
+
+ var $chip = self.$document.find(SELS.CHIP + SELS.SELECTED_CHIP);
+ var $chips = $chip.closest(SELS.CHIPS);
+ var length = $chip.siblings(SELS.CHIP).length;
+ var index;
+
+ if (!$chip.length) {
+ return;
+ }
+ // delete
+ if (e.which === 8 || e.which === 46) {
+ e.preventDefault();
+
+ index = $chip.index();
+ curr_options.beforeDeleteHook($chip).then(function () {
+ self.deleteChip(index, $chips);
+
+ var selectIndex = null;
+ if (index + 1 < length) {
+ selectIndex = index;
+ } else if (index === length || index + 1 === length) {
+ selectIndex = length - 1;
+ }
+
+ if (selectIndex < 0) selectIndex = null;
+
+ if (null !== selectIndex) {
+ self.selectChip(selectIndex, $chips);
+ }
+ if (!length) $chips.find('input').focus();
+ });
+
+ // left
+ } else if (e.which === 37) {
+ index = $chip.index() - 1;
+ if (index < 0) {
+ return;
+ }
+ $(SELS.CHIP).removeClass('selected');
+ self.selectChip(index, $chips);
+
+ // right
+ } else if (e.which === 39) {
+ index = $chip.index() + 1;
+ $(SELS.CHIP).removeClass('selected');
+ if (index > length) {
+ $chips.find('input').focus();
+ return;
+ }
+ self.selectChip(index, $chips);
+ }
+ });
+
+ self.$document.off('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusin.chips', SELS.CHIPS + ' ' + SELS.INPUT, function (e) {
+ var $currChips = $(e.target).closest(SELS.CHIPS);
+ $currChips.addClass('focus');
+ $currChips.siblings('label, .prefix').addClass('active');
+ $(SELS.CHIP).removeClass('selected');
+ });
+
+ self.$document.off('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT).on('focusout.chips', SELS.CHIPS + ' ' + SELS.INPUT, function (e) {
+ var $currChips = $(e.target).closest(SELS.CHIPS);
+ $currChips.removeClass('focus');
+
+ // Remove active if empty
+ if ($currChips.data('chips') === undefined || !Object.keys($currChips.data('chips')).length) {
+ $currChips.siblings('label').removeClass('active');
+ }
+ $currChips.siblings('.prefix').removeClass('active');
+ });
+
+ self.$document.off('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT).on('keydown.chips-add', SELS.CHIPS + ' ' + SELS.INPUT, function (e) {
+ var $target = $(e.target);
+ var $chips = $target.closest(SELS.CHIPS);
+ var chipsLength = $chips.children(SELS.CHIP).length;
+
+ // enter
+ if (13 === e.which) {
+ // Override enter if autocompleting.
+ if (self.hasAutocomplete &&
+ ($chips.find('.autocomplete-content.dropdown-content').length &&
+ $chips.find('.autocomplete-content.dropdown-content').children().length ||
+ $chips.hasClass("autocomplete-loading")
+ )) {
+ return;
+ }
+
+ e.preventDefault();
+
+ self.addChip({name: $target.val(), id: $target.data("autocompleteOptionId")}, $chips);
+ $target.val('');
+ $target.data("autocompleteOptionId", false);
+ return;
+ }
+
+ // delete or left
+ if ((8 === e.keyCode || 37 === e.keyCode) && '' === $target.val() && chipsLength) {
+ e.preventDefault();
+ self.selectChip(chipsLength - 1, $chips);
+ $target.blur();
+ return;
+ }
+ });
+
+ // Click on delete icon in chip.
+ self.$document.off('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE).on('click.chips-delete', SELS.CHIPS + ' ' + SELS.DELETE, function (e) {
+ var $target = $(e.target);
+ var $chips = $target.closest(SELS.CHIPS);
+ var $chip = $target.closest(SELS.CHIP);
+ e.stopPropagation();
+ curr_options.beforeDeleteHook($chip).then(function () {
+ self.deleteChip($chip.index(), $chips);
+ $chips.find('input').focus();
+ });
+ });
+ };
+
+ this.chips = function ($chips, chipId) {
+ $chips.empty();
+ var chipsData = $chips.data('chips')
+ for (var chipId in chipsData) {
+ var chip = chipsData[chipId];
+ $chips.append(self.renderChip(chip));
+ }
+ $chips.append($(' '));
+ self.setPlaceholder($chips);
+
+ // Set for attribute for label
+ var label = $chips.next('label');
+ if (label.length) {
+ label.attr('for', chipId);
+
+ if ($chips.data('chips') !== undefined && Object.keys($chips.data('chips')).length) {
+ label.addClass('active');
+ }
+ }
+
+ // Setup autocomplete if needed.
+ var input = $('#' + chipId);
+ if (self.hasAutocomplete) {
+ curr_options.autocompleteOptions.onAutocomplete = function (val) {
+ self.addChip({name: val, id: input.data("autocompleteOptionId")}, $chips);
+ input.val('');
+ input.data("autocompleteOptionId", false);
+ input.focus();
+ };
+ curr_options.autocompleteOptions.onRendered = function (val, $autocomplete) {
+ if (val.length === 0) return;
+ var exists = false;
+ var chipsData = $chips.data('chips');
+ for (var chipId in chipsData) {
+ var chip = chipsData[chipId];
+ if (chip.name === val) {
+ exists = true;
+ }
+ }
+ if (!exists) {
+ var createTagOption = $('' + val + ' ');
+ $autocomplete.append(createTagOption);
+ }
+ };
+ input.new_autocomplete(curr_options.autocompleteOptions);
+ }
+ };
+
+ /**
+ * Render chip jQuery element.
+ * @param {Object} elem
+ * @return {jQuery}
+ */
+ this.renderChip = function (elem) {
+ if (!elem.name) {
+ console.error("Cannot add chip without name");
+ return;
+ }
+
+ var $renderedChip = $('
');
+ $renderedChip.data("id", elem.id);
+ $renderedChip.text(elem.name);
+ if (elem.image) {
+ $renderedChip.prepend($(' ').attr('src', elem.image));
+ }
+ $renderedChip.append($('close '));
+ return $renderedChip;
+ };
+
+ this.setPlaceholder = function ($chips) {
+ if ($chips.data('chips') !== undefined && !Object.keys($chips.data('chips')).length && curr_options.placeholder) {
+ $chips.find('input').prop('placeholder', curr_options.placeholder);
+ } else if (($chips.data('chips') === undefined || !!Object.keys($chips.data('chips')).length) && curr_options.secondaryPlaceholder) {
+ $chips.find('input').prop('placeholder', curr_options.secondaryPlaceholder);
+ }
+ };
+
+ this.isValid = function ($chips, elem) {
+ var chips = $chips.data('chips');
+ var exists = false;
+ for (var chipId in chips) {
+ var chip = chips[chipId];
+ if (chip.name === elem.name) {
+ exists = true;
+ return;
+ }
+ }
+ return '' !== elem.name && !exists;
+ };
+
+ this.addChip = function (elem, $chips) {
+ if (!self.isValid($chips, elem)) {
+ return;
+ }
+ curr_options.beforeAddHook(elem).then(function (elemUpdate) {
+ $.extend(elem, elemUpdate);
+ var $renderedChip = self.renderChip(elem);
+ var newData = {};
+ var oldData = $chips.data('chips');
+ for (var id in oldData) {
+ newData[id] = oldData[id];
+ }
+ if (!elem.id) {
+ console.error("Chip element does not have an ID");
+ }
+ newData[elem.id] = elem;
+
+ $chips.data('chips', newData);
+ $renderedChip.insertBefore($chips.find('input'));
+ $chips.trigger('chip.add', elem);
+ self.setPlaceholder($chips);
+ });
+ };
+
+ this.deleteChip = function (chipIndex, $chips) {
+ var $chip = $chips.find('.chip').eq(chipIndex);
+ var chipId = $chip.data("id");
+ var chip = $chips.data('chips')[chipId];
+ $chip.remove();
+
+ var newData = {};
+ var oldData = $chips.data('chips');
+ for (var id in oldData) {
+ if (id != chipId) {
+ newData[id] = oldData[id];
+ }
+ }
+
+ $chips.data('chips', newData);
+ $chips.trigger('chip.delete', chip);
+ self.setPlaceholder($chips);
+ };
+
+ this.selectChip = function (chipIndex, $chips) {
+ var $chip = $chips.find('.chip').eq(chipIndex);
+ if ($chip && false === $chip.hasClass('selected')) {
+ $chip.addClass('selected');
+ $chips.trigger('chip.select', $chips.data('chips')[chipIndex]);
+ }
+ };
+
+ this.getChipsElement = function (index, $chips) {
+ return $chips.eq(index);
+ };
+
+ // init
+ this.init();
+
+ this.handleEvents();
+};
+// Warn if overriding existing method
+if (Array.prototype.equals)
+ console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
+// attach the .equals method to Array's prototype to call it on any array
+Array.prototype.equals = function (array) {
+ // if the other array is a falsy value, return
+ if (!array)
+ return false;
+
+ // compare lengths - can save a lot of time
+ if (this.length != array.length)
+ return false;
+
+ for (var i = 0, l = this.length; i < l; i++) {
+ // Check if we have nested arrays
+ if (this[i] instanceof Array && array[i] instanceof Array) {
+ // recurse into the nested arrays
+ if (!this[i].equals(array[i]))
+ return false;
+ }
+ else if (this[i] != array[i]) {
+ // Warning - two different object instances will never be equal: {x:20} != {x:20}
+ return false;
+ }
+ }
+ return true;
+}
+// Hide method from for-in loops
+Object.defineProperty(Array.prototype, "equals", {enumerable: false});
diff --git a/scrummer/static/src/js/lib/pluralize.js b/scrummer/static/src/js/lib/pluralize.js
new file mode 100644
index 0000000..b7125b7
--- /dev/null
+++ b/scrummer/static/src/js/lib/pluralize.js
@@ -0,0 +1,448 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+odoo.define('pluralize', function (require) {
+
+ // Rule storage - pluralize and singularize need to be run sequentially,
+ // while other rules can be optimized using an object for instant lookups.
+ var pluralRules = [];
+ var singularRules = [];
+ var uncountables = {};
+ var irregularPlurals = {};
+ var irregularSingles = {};
+
+ /**
+ * Title case a string.
+ *
+ * @param {string} str
+ * @return {string}
+ */
+ function toTitleCase (str) {
+ return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
+ }
+
+ /**
+ * Sanitize a pluralization rule to a usable regular expression.
+ *
+ * @param {(RegExp|string)} rule
+ * @return {RegExp}
+ */
+ function sanitizeRule (rule) {
+ if (typeof rule === 'string') {
+ return new RegExp('^' + rule + '$', 'i');
+ }
+
+ return rule;
+ }
+
+ /**
+ * Pass in a word token to produce a function that can replicate the case on
+ * another word.
+ *
+ * @param {string} word
+ * @param {string} token
+ * @return {Function}
+ */
+ function restoreCase (word, token) {
+ // Tokens are an exact match.
+ if (word === token) {
+ return token;
+ }
+
+ // Upper cased words. E.g. "HELLO".
+ if (word === word.toUpperCase()) {
+ return token.toUpperCase();
+ }
+
+ // Title cased words. E.g. "Title".
+ if (word[0] === word[0].toUpperCase()) {
+ return toTitleCase(token);
+ }
+
+ // Lower cased words. E.g. "test".
+ return token.toLowerCase();
+ }
+
+ /**
+ * Interpolate a regexp string.
+ *
+ * @param {string} str
+ * @param {Array} args
+ * @return {string}
+ */
+ function interpolate (str, args) {
+ return str.replace(/\$(\d{1,2})/g, function (match, index) {
+ return args[index] || '';
+ });
+ }
+
+ /**
+ * Sanitize a word by passing in the word and sanitization rules.
+ *
+ * @param {string} token
+ * @param {string} word
+ * @param {Array} collection
+ * @return {string}
+ */
+ function sanitizeWord (token, word, collection) {
+ // Empty string or doesn't need fixing.
+ if (!token.length || uncountables.hasOwnProperty(token)) {
+ return word;
+ }
+
+ var len = collection.length;
+
+ // Iterate over the sanitization rules and use the first one to match.
+ while (len--) {
+ var rule = collection[len];
+
+ // If the rule passes, return the replacement.
+ if (rule[0].test(word)) {
+ return word.replace(rule[0], function (match, index, word) {
+ var result = interpolate(rule[1], arguments);
+
+ if (match === '') {
+ return restoreCase(word[index - 1], result);
+ }
+
+ return restoreCase(match, result);
+ });
+ }
+ }
+
+ return word;
+ }
+
+ /**
+ * Replace a word with the updated word.
+ *
+ * @param {Object} replaceMap
+ * @param {Object} keepMap
+ * @param {Array} rules
+ * @return {Function}
+ */
+ function replaceWord (replaceMap, keepMap, rules) {
+ return function (word) {
+ // Get the correct token and case restoration functions.
+ var token = word.toLowerCase();
+
+ // Check against the keep object map.
+ if (keepMap.hasOwnProperty(token)) {
+ return restoreCase(word, token);
+ }
+
+ // Check against the replacement map for a direct word replacement.
+ if (replaceMap.hasOwnProperty(token)) {
+ return restoreCase(word, replaceMap[token]);
+ }
+
+ // Run all the rules against the word.
+ return sanitizeWord(token, word, rules);
+ };
+ }
+
+ /**
+ * Pluralize or singularize a word based on the passed in count.
+ *
+ * @param {string} word
+ * @param {number} count
+ * @param {boolean} inclusive
+ * @return {string}
+ */
+ function pluralize (word, count, inclusive) {
+ var pluralized = count === 1
+ ? pluralize.singular(word) : pluralize.plural(word);
+
+ return (inclusive ? count + ' ' : '') + pluralized;
+ }
+
+ /**
+ * Pluralize a word.
+ *
+ * @type {Function}
+ */
+ pluralize.plural = replaceWord(
+ irregularSingles, irregularPlurals, pluralRules
+ );
+
+ /**
+ * Singularize a word.
+ *
+ * @type {Function}
+ */
+ pluralize.singular = replaceWord(
+ irregularPlurals, irregularSingles, singularRules
+ );
+
+ /**
+ * Add a pluralization rule to the collection.
+ *
+ * @param {(string|RegExp)} rule
+ * @param {string} replacement
+ */
+ pluralize.addPluralRule = function (rule, replacement) {
+ pluralRules.push([sanitizeRule(rule), replacement]);
+ };
+
+ /**
+ * Add a singularization rule to the collection.
+ *
+ * @param {(string|RegExp)} rule
+ * @param {string} replacement
+ */
+ pluralize.addSingularRule = function (rule, replacement) {
+ singularRules.push([sanitizeRule(rule), replacement]);
+ };
+
+ /**
+ * Add an uncountable word rule.
+ *
+ * @param {(string|RegExp)} word
+ */
+ pluralize.addUncountableRule = function (word) {
+ if (typeof word === 'string') {
+ uncountables[word.toLowerCase()] = true;
+ return;
+ }
+
+ // Set singular and plural references for the word.
+ pluralize.addPluralRule(word, '$0');
+ pluralize.addSingularRule(word, '$0');
+ };
+
+ /**
+ * Add an irregular word definition.
+ *
+ * @param {string} single
+ * @param {string} plural
+ */
+ pluralize.addIrregularRule = function (single, plural) {
+ plural = plural.toLowerCase();
+ single = single.toLowerCase();
+
+ irregularSingles[single] = plural;
+ irregularPlurals[plural] = single;
+ };
+
+ /**
+ * Irregular rules.
+ */
+ [
+ // Pronouns.
+ ['I', 'we'],
+ ['me', 'us'],
+ ['he', 'they'],
+ ['she', 'they'],
+ ['them', 'them'],
+ ['myself', 'ourselves'],
+ ['yourself', 'yourselves'],
+ ['itself', 'themselves'],
+ ['herself', 'themselves'],
+ ['himself', 'themselves'],
+ ['themself', 'themselves'],
+ ['is', 'are'],
+ ['was', 'were'],
+ ['has', 'have'],
+ ['this', 'these'],
+ ['that', 'those'],
+ // Words ending in with a consonant and `o`.
+ ['echo', 'echoes'],
+ ['dingo', 'dingoes'],
+ ['volcano', 'volcanoes'],
+ ['tornado', 'tornadoes'],
+ ['torpedo', 'torpedoes'],
+ // Ends with `us`.
+ ['genus', 'genera'],
+ ['viscus', 'viscera'],
+ // Ends with `ma`.
+ ['stigma', 'stigmata'],
+ ['stoma', 'stomata'],
+ ['dogma', 'dogmata'],
+ ['lemma', 'lemmata'],
+ ['schema', 'schemata'],
+ ['anathema', 'anathemata'],
+ // Other irregular rules.
+ ['ox', 'oxen'],
+ ['axe', 'axes'],
+ ['die', 'dice'],
+ ['yes', 'yeses'],
+ ['foot', 'feet'],
+ ['eave', 'eaves'],
+ ['goose', 'geese'],
+ ['tooth', 'teeth'],
+ ['quiz', 'quizzes'],
+ ['human', 'humans'],
+ ['proof', 'proofs'],
+ ['carve', 'carves'],
+ ['valve', 'valves'],
+ ['looey', 'looies'],
+ ['thief', 'thieves'],
+ ['groove', 'grooves'],
+ ['pickaxe', 'pickaxes'],
+ ['whiskey', 'whiskies']
+ ].forEach(function (rule) {
+ return pluralize.addIrregularRule(rule[0], rule[1]);
+ });
+
+ /**
+ * Pluralization rules.
+ */
+ [
+ [/s?$/i, 's'],
+ [/([^aeiou]ese)$/i, '$1'],
+ [/(ax|test)is$/i, '$1es'],
+ [/(alias|[^aou]us|tlas|gas|ris)$/i, '$1es'],
+ [/(e[mn]u)s?$/i, '$1s'],
+ [/([^l]ias|[aeiou]las|[emjzr]as|[iu]am)$/i, '$1'],
+ [/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
+ [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
+ [/(seraph|cherub)(?:im)?$/i, '$1im'],
+ [/(her|at|gr)o$/i, '$1oes'],
+ [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],
+ [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
+ [/sis$/i, 'ses'],
+ [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
+ [/([^aeiouy]|qu)y$/i, '$1ies'],
+ [/([^ch][ieo][ln])ey$/i, '$1ies'],
+ [/(x|ch|ss|sh|zz)$/i, '$1es'],
+ [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
+ [/(m|l)(?:ice|ouse)$/i, '$1ice'],
+ [/(pe)(?:rson|ople)$/i, '$1ople'],
+ [/(child)(?:ren)?$/i, '$1ren'],
+ [/eaux$/i, '$0'],
+ [/m[ae]n$/i, 'men'],
+ ['thou', 'you']
+ ].forEach(function (rule) {
+ return pluralize.addPluralRule(rule[0], rule[1]);
+ });
+
+ /**
+ * Singularization rules.
+ */
+ [
+ [/s$/i, ''],
+ [/(ss)$/i, '$1'],
+ [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(?:sis|ses)$/i, '$1sis'],
+ [/(^analy)(?:sis|ses)$/i, '$1sis'],
+ [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'],
+ [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],
+ [/ies$/i, 'y'],
+ [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'],
+ [/\b(mon|smil)ies$/i, '$1ey'],
+ [/(m|l)ice$/i, '$1ouse'],
+ [/(seraph|cherub)im$/i, '$1'],
+ [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|tlas|gas|(?:her|at|gr)o|ris)(?:es)?$/i, '$1'],
+ [/(e[mn]u)s?$/i, '$1'],
+ [/(movie|twelve)s$/i, '$1'],
+ [/(cris|test|diagnos)(?:is|es)$/i, '$1is'],
+ [/(alumn|syllab|octop|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],
+ [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],
+ [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],
+ [/(alumn|alg|vertebr)ae$/i, '$1a'],
+ [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],
+ [/(matr|append)ices$/i, '$1ix'],
+ [/(pe)(rson|ople)$/i, '$1rson'],
+ [/(child)ren$/i, '$1'],
+ [/(eau)x?$/i, '$1'],
+ [/men$/i, 'man']
+ ].forEach(function (rule) {
+ return pluralize.addSingularRule(rule[0], rule[1]);
+ });
+
+ /**
+ * Uncountable rules.
+ */
+ [
+ // Singular words with no plurals.
+ 'advice',
+ 'adulthood',
+ 'agenda',
+ 'aid',
+ 'alcohol',
+ 'ammo',
+ 'athletics',
+ 'bison',
+ 'blood',
+ 'bream',
+ 'buffalo',
+ 'butter',
+ 'carp',
+ 'cash',
+ 'chassis',
+ 'chess',
+ 'clothing',
+ 'commerce',
+ 'cod',
+ 'cooperation',
+ 'corps',
+ 'digestion',
+ 'debris',
+ 'diabetes',
+ 'energy',
+ 'equipment',
+ 'elk',
+ 'excretion',
+ 'expertise',
+ 'flounder',
+ 'fun',
+ 'gallows',
+ 'garbage',
+ 'graffiti',
+ 'headquarters',
+ 'health',
+ 'herpes',
+ 'highjinks',
+ 'homework',
+ 'housework',
+ 'information',
+ 'jeans',
+ 'justice',
+ 'kudos',
+ 'labour',
+ 'literature',
+ 'machinery',
+ 'mackerel',
+ 'mail',
+ 'media',
+ 'mews',
+ 'moose',
+ 'music',
+ 'news',
+ 'pike',
+ 'plankton',
+ 'pliers',
+ 'pollution',
+ 'premises',
+ 'rain',
+ 'research',
+ 'rice',
+ 'salmon',
+ 'scissors',
+ 'series',
+ 'sewage',
+ 'shambles',
+ 'shrimp',
+ 'species',
+ 'staff',
+ 'swine',
+ 'trout',
+ 'traffic',
+ 'transporation',
+ 'tuna',
+ 'wealth',
+ 'welfare',
+ 'whiting',
+ 'wildebeest',
+ 'wildlife',
+ 'you',
+ // Regexes.
+ /pox$/i, // "chickpox", "smallpox"
+ /ois$/i,
+ /deer$/i, // "deer", "reindeer"
+ /fish$/i, // "fish", "blowfish", "angelfish"
+ /sheep$/i,
+ /measles$/i,
+ /[^aeiou]ese$/i // "chinese", "japanese"
+ ].forEach(pluralize.addUncountableRule);
+
+ return pluralize;
+});
diff --git a/scrummer/static/src/js/main.js b/scrummer/static/src/js/main.js
new file mode 100644
index 0000000..a7a4b00
--- /dev/null
+++ b/scrummer/static/src/js/main.js
@@ -0,0 +1,11 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.main', function (require) {
+ "use strict";
+ var AgileLayout = require('scrummer.layout');
+ var core = require('web.core');
+
+ core.action_registry.add('scrummer', AgileLayout.AgileLayout);
+
+});
diff --git a/scrummer/static/src/js/views/backlog.js b/scrummer/static/src/js/views/backlog.js
new file mode 100644
index 0000000..ac57910
--- /dev/null
+++ b/scrummer/static/src/js/views/backlog.js
@@ -0,0 +1,784 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.view.backlog', function (require) {
+ "use strict";
+ const data = require('scrummer.data');
+ const DataServiceFactory = require('scrummer.data_service_factory');
+ const AgileViewWidget = require('scrummer.BaseWidgets').AgileViewWidget;
+ const AgileModals = require('scrummer.widget.modal');
+ const AbstractModelList = require('scrummer.abstract_model_list');
+ const ModelList = require('scrummer.model_list');
+ const TaskWidget = require('scrummer.widget.task').TaskWidget;
+ const hash_service = require('scrummer.hash_service');
+ const pluralize = require('pluralize');
+ const web_core = require('web.core');
+ const qweb = web_core.qweb;
+ const _t = web_core._t;
+ const core = require('scrummer.core');
+ const AgileToast = require('scrummer.toast');
+ const Sortable = require('sortable');
+ const dialog = require('scrummer.dialog');
+ const mixins = require('scrummer.mixins');
+ const TOP = _t("Top");
+ const BOTTOM = _t("Bottom");
+
+ const task_service = DataServiceFactory.get("project.task", false);
+ const project_service = DataServiceFactory.get("project.project");
+
+ const AbstractBacklogView = AgileViewWidget.extend({
+ title: _t("Backlog"),
+ template: "scrummer.view.backlog",
+ _name: "BacklogView",
+ menuItems: [
+ {
+ class: "add-new-item",
+ icon: "mdi-library-books",
+ text: _t("Add new item"),
+ callback: '_onAddNewItemClick'
+ },
+ ],
+ shouldRenderDragShortcuts: true,
+ custom_events: Object.assign(AgileViewWidget.prototype.custom_events || {}, {
+ drag_start: '_onDragStart',
+ drag_end: '_onDragEnd',
+ backlog_list_changed: '_onBacklogListChanged',
+ open_link_modal: '_onOpenLinkModal',
+ open_new_item_modal: '_onOpenNewItemModal',
+ loading_more_items_started: '_onLoadingMoreItemsStarted',
+ loading_more_items_finished: '_onLoadingMoreItemsFinished',
+ }),
+ init(parent, options) {
+ this._super(parent, options);
+
+ // Getting board_id from hash and fetch all project_ids from that board in order to create filter for fetching projects
+ this.board_id = parseInt(hash_service.get("board"));
+ this.task_id = hash_service.get("task") && parseInt(hash_service.get("task"));
+
+ this.filterQuery = "";
+ this.taskWidgetItemMap = new Map();
+ this.backlogLength = 10;
+
+ window.data = data;
+ window.blv = this;
+ },
+ removeNavSearch() {
+ core.bus.trigger("search:remove");
+ },
+ prepareUser() {
+ return data.cache.get("current_user").then(user => {
+ this.user = user;
+ });
+ },
+ prepareProjects() {
+ return project_service.dataset.id_search("", this.setupProjectIds()
+ .then(this.getProjectDomain.bind(this)))
+ .then(ids => project_service.getRecords(ids))
+ .then(projects => {
+ this.projects = projects;
+ });
+ },
+ prepareBoard() {
+ return DataServiceFactory.get("project.agile.board").getRecord(this.board_id).then(board => {
+ this.board = board;
+ })
+ },
+ // All variables that will be used in getApplyFilterDomain method must be set prior to calling this._super() when
+ loadDependencies() {
+ return this.prepareBoard()
+ .then(() => this.prepareUser())
+ .then(() => this.prepareProjects());
+ },
+ willStart() {
+ let prepared = $.when(this._super(), this.loadDependencies());
+
+ return $.when(
+ prepared.then(() => this.getFilteredTaskIds()),
+ prepared.then(() => task_service.dataset.id_search(this.filterQuery, this.getBacklogTaskDomain(), false, false, "agile_order")
+ .then(ids => {
+ this.backlogTaskIds = ids;
+ })
+ ));
+ },
+ getBacklogTaskDomain() {
+ let domain = [
+ ["project_id", "in", this.project_ids],
+ ["wkf_state_type", "!=", "done"]
+ ];
+
+ if (this.boardTaskTypeFilterExists()) {
+ domain.push([
+ "type_id", "in", this.board.backlog_task_type_ids
+ ]);
+ }
+ return $.when(domain);
+ },
+ getProjectDomain() {
+ return [
+ ["board_ids", "in", this.board_id],
+ ["id", "in", this.project_ids],
+ ["workflow_id", "!=", false]
+ ];
+ },
+ getApplyFilterDomain() {
+
+ let domain = [
+ "|",
+ "|",
+ ["key", "ilike", this.filterQuery],
+ ["description", "ilike", this.filterQuery],
+ ["name", "ilike", this.filterQuery],
+ ["project_id", "in", this.project_ids], // Task must be in one of the projects
+ ];
+
+ if (this.boardTaskTypeFilterExists()) {
+ domain.push([
+ "type_id", "in", this.board.backlog_task_type_ids
+ ]);
+ }
+
+ return $.when(domain);
+ },
+ _getTaskItemClass() {
+ throw new NotImplementedException("You should return class of non-abstract BacklogTaskItem");
+ },
+ renderElement() {
+ this._super();
+ this.backlogTaskList = new BacklogList(this, {
+ model: "project.task",
+ taskWidgetItemCache: this.taskWidgetItemMap,
+ task_ids: this.backlogTaskIds,
+ _getNewListWidget: this._getNewListWidget.bind(this),
+ ModelItem: this._getTaskItemClass(),
+ name: "backlog",
+ sortable: {group: "backlog"},
+ });
+
+ let backlogData = {
+ count: "0 issues",
+ estimates: {
+ todo: 0,
+ inProgress: 0,
+ done: 0
+ }
+ };
+ this.backlogNode = $(qweb.render("scrummer.backlog", backlogData).trim());
+ this.backlogNode.insertAfter(this.$("#backlog-view .section"));
+ this.backlogTaskList.insertBefore(this.$(".list-preloader"));
+ this.$(".list-preloader").hide();
+ },
+ _getNewListWidget(list_id) {
+ throw new NotImplementedException("This method must be implemented")
+ },
+ start() {
+ this._is_added_to_DOM.then(() => {
+ core.bus.trigger("search:show", input => {
+ this.applyFilter(input.val());
+ });
+ });
+ this.bindEventListeners();
+ },
+ bindEventListeners() {
+ this.$('.tooltipped').tooltip({delay: 50});
+ core.bus.on("project.task:write", this, this._onProjectTaskWrite);
+ core.bus.on("project.task:create", this, this._onProjectTaskCreate);
+ core.bus.on("project.task:unlink", this, this._onProjectTaskUnlink);
+ },
+ setNewTaskOrder(task) {
+ throw new NotImplementedException();
+ },
+ getFilteredTaskIds() {
+ return task_service.dataset
+ .id_search("", this.getApplyFilterDomain(), false, false, "agile_order").then(task_ids => {
+ this.allFilteredTaskIds = task_ids;
+ return task_ids;
+ });
+ },
+ applyFilter(q) {
+ if (q === this.queryFilter) {
+ return;
+ }
+ if (q !== undefined) {
+ this.filterQuery = q;
+ }
+ this.getFilteredTaskIds().then(this.handleFilter.bind(this));
+ },
+ handleFilter(task_ids) {
+ this.backlogTaskList.applyFilter(task_ids);
+ },
+ allTaskIds() {
+ return this.backlogTaskList.task_ids.slice();
+ },
+ getTaskListOfTaskWidget(taskWidget) {
+ throw new NotImplementedException();
+ },
+ isTaskInBacklog(task) {
+ throw new NotImplementedException();
+ },
+ addTaskToNonBacklogList(task) {
+ throw new NotImplementedException();
+ },
+ removeTask(id, removeFromCache = false, syncerMeta) {
+ let taskWidget = this.taskWidgetItemMap.get(id);
+ if (!taskWidget) {
+ return false;
+ }
+ this.getTaskListOfTaskWidget(taskWidget).removeItem(id);
+ if (removeFromCache) {
+ this.taskWidgetItemMap.delete(id)
+ }
+ if (syncerMeta) {
+ if (syncerMeta.user_id.id !== data.session.uid && syncerMeta.indirect === false) {
+ AgileToast.toastTask(syncerMeta.user_id, syncerMeta.data, syncerMeta.method);
+ }
+ }
+ return true;
+ },
+
+ boardTaskTypeFilterExists() {
+ return this.board.backlog_task_type_ids && this.board.backlog_task_type_ids.length > 0;
+ },
+
+ isBoardAllowedTaskType(type_id) {
+ return this.boardTaskTypeFilterExists() ? this.board.backlog_task_type_ids.includes(type_id) : true;
+ },
+
+ addTask(id, syncerMeta, highlight = true) {
+ $.when(task_service.getRecord(id)).then(task => {
+ // Skip adding tasks from other projects
+ if (!this.project_ids.includes(task.project_id[0])) {
+ return;
+ }
+
+ if (!this.isBoardAllowedTaskType(task.type_id[0])) {
+ return;
+ }
+
+ let taskWidget;
+ if (this.isTaskInBacklog(task)) {
+ taskWidget = this.backlogTaskList.addItem(task);
+
+ } else {
+ taskWidget = this.addTaskToNonBacklogList(task);
+ }
+ if (!taskWidget) {
+ return;
+ }
+ this.taskWidgetItemMap.has(task.id) || this.taskWidgetItemMap.set(task.id, taskWidget);
+ highlight && taskWidget._is_added_to_DOM.then(() => {
+ $("#backlog-view").scrollToElement(taskWidget.$el);
+ taskWidget.$el.highlight();
+ });
+ if (syncerMeta) {
+ if (syncerMeta.user_id.id !== data.session.uid && syncerMeta.indirect === false) {
+ AgileToast.toastTask(syncerMeta.user_id, task, syncerMeta.method);
+ }
+ }
+ })
+ },
+ setupProjectIds() {
+ return data.cache.get("current_user").then(user => {
+ let hashProjectId;
+ if (hash_service.get("project")) {
+ if (isNaN(parseInt(hash_service.get("project")))) {
+ throw new Error("Project id in URL must be a number");
+ }
+ hashProjectId = parseInt(hash_service.get("project"));
+ this.project_ids = [hashProjectId];
+ }
+
+ return data.cache.get("projects_in_board", {
+ 'id': this.board_id,
+ team_id: user.team_id[0]
+ }).then(projectMap => {
+ if (hashProjectId && projectMap.has(hashProjectId)) {
+ return;
+ } else if (hashProjectId) {
+ hash_service.delete("project");
+ }
+ //this.project_ids = user.team_ids[user.team_id[0]].project_ids;
+ let project_ids = [];
+ for (const project of projectMap)
+ project_ids.push(project[0])
+ this.project_ids = project_ids;
+ });
+
+ });
+ },
+ prepareShortcuts(list_id) {
+ throw new NotImplementedException("You should either implement this method or disable shortcuts by setting shouldRenderDragShortcuts to false");
+ },
+ renderDragShortcuts(shortcutPlace, shortcuts, sourceList) {
+ this.shortcutContainer = $(`
`);
+ for (let shortcut of shortcuts) {
+ if (shortcut.positioner) {
+ let positionerNode = $(`
`);
+ this.renderDragShortcutNode(shortcut, sourceList, TOP).appendTo(positionerNode);
+ let positionerNodeName = $(`${shortcut.name}
`);
+ positionerNodeName.appendTo(positionerNode);
+ this.renderDragShortcutNode(shortcut, sourceList, BOTTOM).appendTo(positionerNode);
+ positionerNode.appendTo(this.shortcutContainer);
+ } else {
+ let shortcutNode = this.renderDragShortcutNode(shortcut, sourceList);
+ shortcutNode.appendTo(this.shortcutContainer);
+ }
+ }
+ shortcutPlace.append(this.shortcutContainer);
+ },
+ renderDragShortcutNode(shortcut, sourceList, position) {
+ let name;
+ let positionData;
+ if (position) {
+ name = position;
+ positionData = `data-shortcut-position="${position}"`
+ } else {
+ name = shortcut.name;
+ positionData = "";
+ }
+ let shortcutNode = $(`${name}
`);
+ shortcutNode[0].addEventListener("dragenter", evt => {
+ $(evt.target).addClass("hover")
+ }, false);
+ shortcutNode[0].addEventListener("dragleave", evt => {
+ $(evt.target).removeClass("hover")
+ }, false);
+ Sortable.create(shortcutNode[0], {
+ group: "backlog",
+ onAdd: function (evt) {
+ if (position) {
+ if (position == TOP) {
+ sourceList.moveToTop(evt);
+ } else if (position == BOTTOM) {
+ sourceList.moveToBottom(evt);
+ }
+ } else {
+ this.dragShortcutCallback(evt.item, sourceList, shortcut);
+ }
+ }.bind(this)
+ });
+ return shortcutNode;
+ },
+ dragShortcutCallback(item, sourceList, shortcut) {
+ let taskId = parseInt(item.dataset.id);
+ let itemWidget = this.taskWidgetItemMap.get(taskId);
+ let newListWidget = sourceList._getNewListWidget(shortcut.id);
+ // sourceList._setNewItemList(itemWidget, newListWidget);
+ let newPosition = shortcut.id ? newListWidget.list.size : 0; // insert to the bottom of the non-backlog list or in the beginning of backlog list
+ itemWidget.set_list(newListWidget, sourceList.getNewOrder(0, newPosition, shortcut.id, false));
+ },
+
+ _onProjectTaskWrite(id, vals, payload, record) {
+ this.removeTask(id, true);
+ this.addTask(id, payload, data.session.uid === payload.user_id.id);
+ if (this.rightSideWidget && this.rightSideWidget.id === id) {
+ let editPromise = record && record._edit("check") ? record._edit() : $.when();
+ editPromise.then(() => {
+ // Since trigger_up wraps event arguments in data object, here I mimic that behaviour.
+ this.trigger("open_right_side", {
+ data: {
+ WidgetClass: TaskWidget,
+ options: {id, isQuickDetailView: true}
+ }
+ });
+ });
+
+ }
+ },
+ _onProjectTaskCreate(id, vals, payload) {
+ this.addTask(id, payload);
+ },
+ _onProjectTaskUnlink(id, payload) {
+ this.removeTask(id, true, payload);
+ if (this.rightSideWidget && this.rightSideWidget.id === id) {
+ this.rightSideWidget.destroy(true);
+ delete this.rightSideWidget;
+ }
+ },
+ // CUSTOM EVENT HENDLERS
+ _onDragStart(evt) {
+ if (this.shouldRenderDragShortcuts) {
+ let shortcutPlace = this.$("#backlog-view");
+ let shortcuts = this.prepareShortcuts(evt.target.id);
+ this.renderDragShortcuts(shortcutPlace, shortcuts, evt.target);
+ }
+ },
+ _onDragEnd(evt) {
+ this.shortcutContainer && this.shortcutContainer.remove();
+ if (!evt.data.sortableEvent.target || evt.data.sortableEvent.target.classList.contains("shortcut-item")) {
+ evt.data.sortableEvent.preventDefault();
+ }
+ },
+ _onBacklogListChanged(evt) {
+ this.backlogNode.find(".task-count").text((evt.data.size || 0) + " of " + evt.data.total + " " + pluralize("issue", evt.data.total));
+ Waypoint.refreshAll();
+ },
+ _onOpenLinkModal(evt) {
+ if (!evt.data.id) {
+ throw new Error("Event payload must contain id of task for wich link should be created");
+ }
+ task_service.getRecord(evt.data.id).then(record => {
+ if (!record) {
+ throw new Error("Task doens't exist");
+ }
+ let modal = new AgileModals.LinkItemModal(this, {
+ task: record,
+ task_ids: [...this.allTaskIds()],
+ });
+ modal.appendTo($("body"));
+ });
+ },
+ _onOpenNewItemModal(evt) {
+ let options = {
+ projects: this.projects
+ };
+ Object.assign(options, evt.data);
+ let newItemModal = new AgileModals.NewItemModal(this, options);
+ newItemModal.appendTo($("body"));
+ },
+ _onLoadingMoreItemsStarted() {
+ this.loadingMoreItems = true;
+ this.$(".list-preloader").show();
+ },
+ _onLoadingMoreItemsFinished() {
+ this.loadingMoreItems = false;
+ if (this.backlogTaskList.shouldLoadMore() && this.$(".master-list").height() / this.$el.height() < 1.1) {
+ this.backlogTaskList.loadMoreItems();
+ } else {
+ this.$(".list-preloader").hide();
+ }
+ },
+ _onAddNewItemClick() {
+ let defaults = {
+ project: this.projects.find(p => p.id == hash_service.get("project"))
+ };
+ this.trigger_up("open_new_item_modal", {
+ currentProjectId: parseInt(hash_service.get("project")) || undefined,
+ focus: "name",
+ defaults,
+ beforeHook: this.setNewTaskOrder.bind(this),
+ });
+ }
+ // CUSTOM EVENT HENDLERS END
+ });
+
+ const SimpleBacklogTaskItem = ModelList.SimpleTaskItem.extend(mixins.MenuItemsMixin, {
+ //order_field: "agile_order",
+ _name: "BacklogTaskItem",
+ events: {
+ 'click': function (evt) {
+ if (evt.isDefaultPrevented()) {
+ // Skip if default behaviour is prevented, eg. when clicked on menu.
+ return;
+ }
+ this._onItemClicked(evt);
+ },
+ },
+ menuItems: [
+ {
+ class: "assign-to-me",
+ icon: "mdi-account-check",
+ image: function () {
+ return this.currentUser.imageUrl
+ },
+ text: _t("Assign To Me"),
+ callback: '_onAssignToMeClick',
+ sequence: 1,
+ hidden() {
+ return this.record.user_id && this.record.user_id[0] == data.session.uid;
+ }
+ },
+ {
+ class: "unassign",
+ icon: "mdi-account-minus",
+ text: _t("Unassign"),
+ callback: '_onUnassignClick',
+ sequence: 2,
+ hidden() {
+ return !(this.record.user_id && this.record.user_id[0] == data.session.uid);
+ }
+ },
+ {
+ class: "edit-item",
+ icon: "mdi-pencil",
+ text: _t("Edit"),
+ callback: '_onEditItemClick',
+ sequence: 3,
+ },
+ {
+ class: "add-sub-item",
+ icon: "mdi-subdirectory-arrow-right",
+ text: _t("Add Sub Item"),
+ callback: '_onAddSubItemClick',
+ sequence: 4,
+ hidden() {
+ return !this.task_type.allow_sub_tasks;
+ },
+ },
+ {
+ class: "add-link",
+ icon: "mdi-link",
+ text: _t("Add Link"),
+ callback: '_onAddLinkClick',
+ sequence: 5,
+ },
+ {
+ class: "add-comment",
+ icon: "mdi-comment-account",
+ text: _t("Add Comment"),
+ callback: '_onAddCommentClick',
+ sequence: 6,
+ },
+ {
+ class: "delete",
+ icon: "mdi-delete",
+ text: _t("Delete"),
+ callback: '_onDelete',
+ sequence: 7,
+ },
+ ],
+ init() {
+ this._super.apply(this, arguments);
+ mixins.MenuItemsMixin.init.call(this);
+ },
+ start() {
+ mixins.MenuItemsMixin.start.call(this);
+ this.$(".task-menu, .dropdown-content a").click(evt => {
+ // Prevent triggering click handler for entire task item
+ evt.preventDefault();
+ });
+ return this._super();
+ },
+ addedToDOM() {
+ this._super();
+ this.$('.dropdown-button').dropdown();
+
+ },
+ rerenderWidget() {
+ this.renderElement();
+ this.start();
+ this.addedToDOM();
+ },
+ _onItemClicked(evt) {
+ this.trigger_up("open_right_side", {
+ WidgetClass: TaskWidget,
+ options: {id: this.record.id, isQuickDetailView: true}
+ });
+ },
+ _onAssignToMeClick() {
+ this.record.user_id = data.session.uid;
+ },
+ _onUnassignClick() {
+ this.record.user_id = false;
+ },
+ _onEditItemClick() {
+ this.trigger_up("open_new_item_modal", {
+ currentProjectId: this.record.project_id[0],
+ focus: "name",
+ edit: this.record,
+ });
+ },
+ _onAddSubItemClick() {
+ this.trigger_up("open_new_item_modal", {
+ parent_id: this.record.id,
+ currentProjectId: this.record.project_id[0]
+ });
+ },
+ _onAddLinkClick() {
+ this.trigger_up("open_link_modal", {id: this.record.id});
+ },
+ _onAddCommentClick() {
+ var modal = new AgileModals.CommentItemModal(this, {
+ task: this.record,
+ });
+ modal.appendTo($("body"));
+ },
+ _onDelete() {
+ dialog.confirm(_t("Delete task"), _t("Are you sure you want to delete this task?"), _t("yes")).done(() => {
+ this.record.unlink();
+ });
+ },
+ });
+
+ const BacklogList = AbstractModelList.ModelList.extend({
+ _name: "BacklogList",
+ pageSize: 10,
+ init(parent, options) {
+ this._super(parent, options);
+ this.size = this.pageSize;
+ this._require_prop("task_ids", "Field task_ids is array containing ids of all tasks in backlog");
+ this._require_prop("taskWidgetItemCache", "JavaScript Map object where key is id, and value is cached widget item.");
+ this._require_prop("_getNewListWidget", "A function that accepts list id in and returns ModelList widget instance");
+ this.allFilteredTaskIds = this.getAllTaskIds();
+ },
+ getAllTaskIds() {
+ return this.task_ids;
+ },
+ loadItems() {
+ return task_service.getRecords(this.getSlicedBacklogTaskIds(this.getFilteredTaskIds(this.allFilteredTaskIds))).then(tasks => this.data = tasks);
+ },
+ shouldLoadMore() {
+ return this.allFilteredTaskIds.length > this.list.size;
+ },
+ getFilteredTaskIds(filtered_task_ids) {
+ return filtered_task_ids !== undefined ?
+ this.getAllTaskIds().filter(id => filtered_task_ids.includes(id)) :
+ this.getAllTaskIds();
+ },
+ getSlicedBacklogTaskIds(backlog_task_ids) {
+ return backlog_task_ids.slice(0, this.size)
+ },
+ loadMoreItems() {
+ this.size += 10;
+ let sliced_task_ids = this.getSlicedBacklogTaskIds(this.getFilteredTaskIds(this.allFilteredTaskIds));
+ this.trigger_up("loading_more_items_started");
+ task_service.getRecords(sliced_task_ids).then(tasks => this.data = tasks).then(tasks => {
+ tasks.forEach(this.addItem.bind(this));
+ this.trigger_up("loading_more_items_finished");
+
+ /* Because lazy loading backlog items work when you scroll down to bottom of backlog,
+ * we need to manage the case where bottom of backlog is above bottom of window.
+ * In such case, when master list is less then 110% in height, load more items if available
+ */
+ this.trigger_up("backlog_list_changed", {
+ size: this.list.size,
+ total: this.allFilteredTaskIds.length
+ });
+ })
+ },
+ addItem(item) {
+ if (this.list.has(item.id)) {
+ return;
+ }
+ !this.getAllTaskIds().includes(item.id) && this.getAllTaskIds().push(item.id);
+ !this.allFilteredTaskIds.includes(item.id) && this.allFilteredTaskIds.push(item.id);
+
+ let cachedWidget = this.taskWidgetItemCache.get(item.id);
+ // Use cached widget if exists on backlog view, or create it and store in cache
+ let retVal = this._super(cachedWidget || item);
+ cachedWidget || this.taskWidgetItemCache.set(item.id, retVal);
+
+ this.trigger_up("backlog_list_changed", {
+ size: this.list.size,
+ total: this.allFilteredTaskIds.length
+ });
+ return retVal;
+ },
+ removeItem(id, destroy) {
+ let removed = this._super.apply(this, arguments);
+ this.allFilteredTaskIds.includes(id) && this.allFilteredTaskIds.splice(this.allFilteredTaskIds.indexOf(id), 1);
+ if (removed) {
+ this.trigger_up("backlog_list_changed", {
+ size: this.list.size,
+ total: this.allFilteredTaskIds.length
+ });
+ }
+ return removed;
+ },
+ addedToDOM() {
+ this.$el.waypoint({
+ handler: (direction) => {
+ if (direction === "down" && this.shouldLoadMore()) {
+ // console.log("Backlog bottom hit, loading more tasks");
+ this.loadMoreItems();
+ }
+ },
+ context: "#backlog-view",
+ offset: 'bottom-in-view'
+ })
+ },
+ applyFilter(filteredTaskIds) {
+ // Reset backlog length and slice tasks so that only first page gets loaded.
+ this.size = 10;
+ this.allFilteredTaskIds = this.getFilteredTaskIds(filteredTaskIds);
+ // Remove filtered tasks from list
+ for (let id of this.list.keys()) {
+ if (!this.allFilteredTaskIds.includes(id)) {
+ this.removeItem(id, false);
+ }
+ }
+ if (this.shouldLoadMore() && !this.loadingMoreItems) {
+ this.loadMoreItems();
+ }
+ }
+ });
+
+ const NonBacklogList = AbstractModelList.ModelList.extend({
+ _name: "NonBacklogList",
+ init() {
+ this._super.apply(this, arguments);
+ this._require_prop("_getNewListWidget", "A function that accepts list id in and returns ModelList widget instance");
+ this._require_prop("taskWidgetItemCache", "JavaScript Map object where key is id, and value is cached widget item.");
+ this._require_prop("allFilteredTaskIds", "This is the array of ids that will be used for general filtering of tasks in list.");
+ },
+ loadItems() {
+ return task_service.getRecords(this.getAllTaskIds()).then(tasks => this.data = tasks);
+ },
+ getAllTaskIds() {
+ if (!this.generalFilteredTaskIds) {
+ this.generalFilteredTaskIds = this.task_ids.filter(id => this.allFilteredTaskIds.includes(id));
+ }
+ return this.generalFilteredTaskIds;
+ },
+ getFilteredTaskIds(filtered_task_ids) {
+ let allTaskIds = this.getAllTaskIds();
+ return filtered_task_ids !== undefined ?
+ filtered_task_ids.filter(id => allTaskIds.includes(id)) : allTaskIds;
+ },
+ shouldTaskBeAdded(item) {
+ if (hash_service.get("project")) {
+ let project_id = parseInt(hash_service.get("project"));
+ let task_project_id = item._class === "ModelListItem" ? item.record.project_id : item.project_id;
+ return isNaN(project_id) || task_project_id && project_id === task_project_id[0];
+ }
+ return true;
+ },
+ addItem(item) {
+ // Prevent adding tasks to list that doesn't belong to it.
+ if (!this.shouldTaskBeAdded(item)) {
+ return;
+ }
+ if (this.list.has(item.id)) {
+ return this.list.get(item.id);
+ }
+ let cachedWidget = this.taskWidgetItemCache.get(item.id);
+
+ // Use cached widget if exists on backlog view, or create it and store in cache
+ let retVal = this._super(cachedWidget || item);
+ cachedWidget || this.taskWidgetItemCache.set(item.id, retVal);
+ this.trigger_up("non_backlog_list_changed", {
+ size: this.list.size,
+ total: (this.allFilteredTaskIds || this.getAllTaskIds()).length,
+ id: this.attributes['data-id']
+ });
+ return retVal;
+ },
+ removeItem() {
+ let removed = this._super.apply(this, arguments);
+ if (removed) {
+ this.trigger_up("non_backlog_list_changed", {
+ size: this.list.size,
+ total: (this.allFilteredTaskIds || this.getAllTaskIds()).length,
+ id: this.attributes['data-id']
+ });
+ }
+ },
+ applyFilter(filteredTaskIds) {
+ this.allFilteredTaskIds = this.getFilteredTaskIds(filteredTaskIds);
+ // Add tasks that passed filter to list, if they are missing
+ let taskIDsToBeAdded = this.getAllTaskIds().filter(id => this.allFilteredTaskIds.includes(id) && !this.list.has(id));
+ task_service.getRecords(taskIDsToBeAdded).then(records => records.forEach(record => this.addItem(record)));
+
+ // Remove filtered tasks from list
+ for (let id of this.list.keys()) {
+ !this.allFilteredTaskIds.includes(id) && this.removeItem(id, false);
+ }
+ }
+ });
+
+ return {
+ AbstractBacklogView,
+ BacklogList,
+ SimpleBacklogTaskItem,
+ NonBacklogList
+ };
+});
diff --git a/scrummer/static/src/js/views/kanban_table.js b/scrummer/static/src/js/views/kanban_table.js
new file mode 100644
index 0000000..7583fdf
--- /dev/null
+++ b/scrummer/static/src/js/views/kanban_table.js
@@ -0,0 +1,1251 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.view.kanban_table', function (require) {
+ "use strict";
+ const data = require('scrummer.data');
+ const core = require('scrummer.core');
+ const BaseWidgets = require('scrummer.BaseWidgets');
+ const TaskWidget = require('scrummer.widget.task').TaskWidget;
+ const AgileModals = require('scrummer.widget.modal');
+ const storage_service = require('scrummer.storage_service');
+ require('sortable');
+ const pluralize = require('pluralize');
+ const DataServiceFactory = require('scrummer.data_service_factory');
+ const task_service = DataServiceFactory.get("project.task", false);
+ const AgileToast = require('scrummer.toast');
+ const dialog = require('scrummer.dialog');
+ const mixins = require('scrummer.mixins');
+
+ const web_core = require('web.core');
+ const qweb = web_core.qweb;
+ const _t = web_core._t;
+
+ const INDEX_NOT_FOUND = -1;
+
+ function getFieldId(record, field) {
+ return Array.isArray(record[field]) ? record[field][0] : record[field];
+ }
+
+ function getFieldName(record, field) {
+ return Array.isArray(record[field]) ? record[field][1] : record[field];
+ }
+
+ class SwimlaneDefinition {
+ /**
+ *
+ * @param kanbanTable - A reference to parent kanbanTable
+ * @param field - Name of field that will be used for grouping cards
+ * @param text - Will be shown in UI select-option when changing swimlane
+ */
+ constructor(kanbanTable, field, text, undefinedHeaderName = _t("Undefined"), headerTemplate = "scrummer.kanban_table.swimlane.header.simple") {
+ this.kanbanTable = kanbanTable;
+ this.field = field;
+ this.text = text;
+ this.undefinedHeaderName = undefinedHeaderName;
+ this.headerTemplate = headerTemplate;
+ this.swimlaneNoHeaderTemplate = "scrummer.kanban_table.swimlane";
+ this.swimlaneTemplate = "scrummer.kanban_table.swimlane.collapsible";
+ this.columnTemplate = "scrummer.kanban_table.column";
+ }
+
+ /**
+ * Returns concrete value or promise which resolves string/number/undefined that will be used as a group ID for custom grouping of cards in swimlanes.
+ */
+ mapper(card) {
+ if (this.field === undefined) {
+ return undefined;
+ } else {
+ return getFieldId(card, this.field);
+ }
+ }
+
+ compare(x, y) {
+ return x === undefined || x === false ? 1 : y === undefined || y === false ? -1 : x - y;
+ }
+
+ /**
+ * Returns promise which resolves a dictionary that will be passed to qweb.render - headerTemplate
+ * If no swimlane is selected, it should return undefined
+ * @param card
+ * @returns {Object}
+ */
+ header(card) {
+ function pluralizedCount() {
+ let count = this.recordCount();
+ return count + " " + pluralize('issue', count);
+ }
+
+ if (this.field === undefined) {
+ return undefined;
+ } else if (!card[this.field]) {
+ return {
+ headerData: {name: this.undefinedHeaderName},
+ pluralizedCount,
+ afterRender() {
+ }
+ };
+ } else {
+ return {
+ headerData: {name: getFieldName(card, this.field)},
+ pluralizedCount,
+ afterRender() {
+ }
+ };
+ }
+ }
+
+ /**
+ * Returns concrete value or promise which resolves boolean wether card should be rendered on table or not.
+ * @param card
+ * @returns {boolean}
+ */
+ filter(card) {
+ return true;
+ }
+
+ /**
+ * Should be called before any other method.
+ * Initializes arrays/maps/etc. of promises used to enable bulk fetching.
+ */
+ begin() {
+ return this;
+ }
+
+ /**
+ * Should be called when mapper function has been called for all records
+ * Purpose of this method is to create a batch request for all records external dependencies.
+ * Since base SwimlaneDefinition doesn't return any promises, nothing has to be resolved.
+ * References to temporary promises, etc. should be deleted so that GC can clean them up
+ */
+ resolve() {
+ return this;
+ }
+ }
+
+ class AsyncSwimlaneDefinition extends SwimlaneDefinition {
+ mapper(card) {
+ if (this.state !== "in_transaction") {
+ throw new Error("SwimlaneDefinition mapper called without call to begin method");
+ }
+ }
+
+ filter(card) {
+ if (this.state !== "in_transaction") {
+ throw new Error("SwimlaneDefinition filter called without call to begin method");
+ }
+ return super.filter(card);
+ }
+
+ begin() {
+ this.state = "in_transaction";
+ return this;
+ }
+
+ resolve() {
+ this.state = "resolved";
+ return this;
+ }
+ }
+
+ class StorySwimlaneDefinition extends AsyncSwimlaneDefinition {
+ constructor(kanbanTable) {
+ super(kanbanTable, 'story', _t("User Story"), _t("Other issues"), "scrummer.kanban_table.swimlane.header.story");
+ }
+
+ begin() {
+ super.begin();
+ this.parent_ids = [];
+ this.parentDeferredMap = {};
+ return this;
+ }
+
+ _getParentPromise(id) {
+ if (!this.parentDeferredMap[id])
+ this.parentDeferredMap[id] = new $.Deferred();
+ this.parent_ids.includes(id) || this.parent_ids.push(id);
+ return this.parentDeferredMap[id].promise();
+ }
+
+ mapper(task) {
+ super.mapper(task);
+ if (!task.parent_id) {
+ return undefined;
+ }
+ let parentPromise = this._getParentPromise(task.parent_id[0]);
+ return parentPromise.then(parentTask => {
+ return parentTask.is_user_story ? parentTask.id : undefined;
+ });
+ }
+
+ filter(task) {
+ // Don't render user stories that are already shown as a swimlane
+ return !(task.is_user_story && task.child_ids.find(t => this.kanbanTable.data.ids.includes(t)) ? true : false);
+ }
+
+ header(task) {
+ if (!task.parent_id) {
+ let header = super.header(task);
+ header.headerData.name = this.undefinedHeaderName;
+ header._overrideTemplate = "scrummer.kanban_table.swimlane.header.simple";
+ return header;
+ }
+ return this._getParentPromise(task.parent_id[0]).then(task => {
+ return {
+
+ task,
+ count() {
+ let count = this.recordCount();
+ return count + " " + pluralize('sub-task', count);
+ },
+ afterRender: element => {
+ element.find(".task-key").click(() => {
+ this.kanbanTable.trigger_up("open_task", {id: task.id});
+ })
+
+ }
+
+ };
+ });
+ }
+
+ resolve() {
+ super.resolve();
+ this.kanbanTable.loadRecords(this.parent_ids).then(records => {
+ for (let record of records) {
+ this.parentDeferredMap[record.id].resolve(record);
+ }
+ });
+ return this;
+ }
+ }
+
+ var AbstractCard = BaseWidgets.AgileBaseWidget.extend(mixins.MenuItemsMixin, {
+ _name: "AbstractCard",
+ template: "scrummer.kanban_table.card",
+ customCardTitle: undefined,
+ customCardFooter: undefined,
+ init(parent, options) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this._require_obj("record", ["id"]);
+ mixins.MenuItemsMixin.init.call(this);
+ },
+ renderElement() {
+ this._super();
+ this.customCardTitle && this.$(".card-title").append(qweb.render(this.customCardTitle, {widget: this}));
+ this.customCardFooter && this.$(".footer-content").append(qweb.render(this.customCardFooter, {widget: this}));
+ },
+ start() {
+ mixins.MenuItemsMixin.start.call(this);
+ this._is_added_to_DOM.then(() => {
+ this.$('.dropdown-button').dropdown();
+ this.$('.tooltipped').tooltip();
+ });
+ return this._super();
+ },
+ image_url() {
+ return false;
+ },
+ image_tooltip() {
+ return false;
+ },
+ index() {
+ return this.$el.index();
+ }
+ });
+ var TaskCard = AbstractCard.extend({
+ menuItems: [
+ {
+ class: "assign-to-me",
+ icon: "mdi-account-check",
+ text: _t("Assign To Me"),
+ callback: '_onAssignToMeClick',
+ sequence: 1,
+ hidden() {
+ return this.record.user_id && this.record.user_id[0] == data.session.uid;
+ }
+ },
+ {
+ class: "unassign",
+ icon: "mdi-account-minus",
+ text: _t("Unassign"),
+ callback: '_onUnassignClick',
+ sequence: 2,
+ hidden() {
+ return !(this.record.user_id && this.record.user_id[0] == data.session.uid);
+ }
+ },
+ {
+ class: "edit-item",
+ icon: "mdi-pencil",
+ text: _t("Edit"),
+ callback: '_onEditItemClick',
+ sequence: 3,
+ },
+ {
+ class: "add-sub-item",
+ icon: "mdi-subdirectory-arrow-right",
+ text: _t("Add Sub Item"),
+ callback: '_onAddSubItemClick',
+ sequence: 4,
+ hidden() {
+ return !this.task_type.allow_sub_tasks;
+ },
+ },
+ {
+ class: "add-link",
+ icon: "mdi-link",
+ text: _t("Add Link"),
+ callback: '_onAddLinkClick',
+ sequence: 5,
+ },
+ {
+ class: "work-log",
+ icon: "mdi-worker",
+ text: _t("Log Work"),
+ callback: '_onWorkLogClick',
+ sequence: 6,
+ },
+ {
+ class: "add-comment",
+ icon: "mdi-comment-account",
+ text: _t("Add Comment"),
+ callback: '_onAddCommentClick',
+ sequence: 7,
+ },
+ {
+ class: "delete",
+ icon: "mdi-delete",
+ text: _t("Delete"),
+ callback: '_onDelete',
+ sequence: 8,
+ },
+ ],
+ customCardTitle: "scrummer.kanban_table.card.task.title",
+ customCardFooter: "scrummer.kanban_table.card.task.footer",
+ init(parent, options) {
+ this._super(parent, options);
+ this.task = this.record;
+ },
+ willStart() {
+ return this._super().then(() => {
+ return $.when(data.cache.get("current_user").then(user => data.cache.get("team_members", {teamId: user.team_id[0]})).then(members => {
+ this.user = members.find(e => this.task.user_id && e.id == this.task.user_id[0]);
+ }), DataServiceFactory.get("project.task.type2").getRecord(this.task.type_id[0]).then(task_type => {
+ this.task_type = task_type;
+ }))
+ });
+ },
+ start() {
+ this.$(".task-key").unbind("click");
+ this.$(".task-key").click(() => {
+ this.trigger_up("open_task", {id: this.task.id});
+ });
+ return this._super();
+ },
+ image_url() {
+ return this.user ? data.getImage("res.users", this.user.id, this.user.write_date) : "/scrummer/static/img/unassigned.png";
+ },
+ image_tooltip() {
+ return this.user ? this.user.name : _t("Unassigned");
+ },
+ _onWorkLogClick() {
+ var modal = new AgileModals.WorkLogModal(this.getParent(), {
+ task: this.task,
+ userId: data.session.uid
+ });
+ modal.appendTo($("body"));
+ },
+ _onAddLinkClick() {
+ var modal = new AgileModals.LinkItemModal(this.getParent(), {
+ task: this.task,
+ });
+ modal.appendTo($("body"));
+ },
+ _onAddCommentClick() {
+ var modal = new AgileModals.CommentItemModal(this.getParent(), {
+ task: this.task,
+ });
+ modal.appendTo($("body"));
+ },
+ _onAddSubItemClick() {
+ var newItemModal = new AgileModals.NewItemModal(this.getParent(), {
+ currentProjectId: this.task.project_id[0],
+ parent_id: this.task.id,
+ });
+ newItemModal.appendTo($("body"));
+ },
+ _onEditItemClick() {
+ let newItemModal = new AgileModals.NewItemModal(this.getParent(), {
+ currentProjectId: this.task.project_id[0],
+ edit: this.task,
+ });
+ newItemModal.appendTo($("body"));
+ },
+ _onAssignToMeClick() {
+ this.task.user_id = data.session.uid;
+ // data.cache.get("current_user").then(user => {
+ // this.user = user;
+ // this.renderElement();
+ // this.start();
+ // });
+ },
+ _onUnassignClick() {
+ this.task.user_id = false;
+ },
+ _onDelete() {
+ dialog.confirm(_t("Delete task"), _t("Are you sure you want to delete this task?"), _t("yes")).done(() => {
+ this.task.unlink();
+ });
+ },
+
+ });
+
+ var AbstractKanbanTable = BaseWidgets.AgileBaseWidget.extend({
+ _name: "KanbanTable",
+ template: "scrummer.kanban_table",
+ kanbanTableOptionsID: undefined,
+ init(parent, options) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this.swimlanes = this.initSwimlaneDefinitions();
+ this._require_prop("swimlanes", "This property specifies fields used to group cards in swimlanes. " +
+ "Fields are stored in ES6 Map." +
+ "Key is field name, value is instance of SwimlaneDefinition ES6 class");
+ this._require_prop("dataService", "An instance of implementation of DataService from scrummer.DataService module.");
+ this._require_prop("stageField", "This property tells table what is the field of card model that workflow is wrapped around.");
+ this._require_prop("kanbanTableOptionsID", "This property is used to identify key of options object in local storage");
+ /**
+ * This method should be overridden in concrete implementation
+ * Here we have demo structure that shows what loadData should resolve
+ {
+ board: {
+ name: "Development",
+ columns: {
+ "1": {order: 1, id: 1, name: "To Do"},
+ "2": {order: 2, id: 2, name: "In Progress"},
+ "3": {order: 3, id: 3, name: "Done"},
+ },
+ // state_id is link to project.workflow.state
+ status: {
+ "1": {state_id: 72, "column_id": 1, "id": 1, "order": 2},
+ "2": {state_id: 66, "column_id": 1, "id": 2, "order": 1},
+ "3": {state_id: 67, "column_id": 2, "id": 3, "order": 0},
+ "4": {state_id: 68, "column_id": 3, "id": 4, "order": 0}
+ },
+ },
+ workflow: {
+ workflows: {
+ 1: {id: 1, name: "Workflow 1", description: "Workflow 1 description"},
+ 2: {id: 2, name: "Workflow 2", description: "Workflow 2 description"},
+ 3: {id: 3, name: "Workflow 3", description: "Workflow 3 description"},
+ }
+ states: {
+ 66: {
+ id: 66,
+ stage_id: 4, // This will has to be defined when creating KanbanTable (stageField)
+ global_in: true,
+ global_out: false,
+ name: "To Do",
+ type: "todo",
+ workflow_id: 1,
+ in_transitions: [],
+ out_transitions: [91],
+ },
+ 67: {
+ id: 67,
+ stage_id: 14,
+ global_in: false,
+ global_out: false,
+ name: "In Progress",
+ type: "in_progress",
+ workflow_id: 1,
+ in_transitions: [91, 97],
+ out_transitions: [92, 95]
+ },
+ ...
+ }
+ transitions: {
+ 1: {
+ id: 1,
+ name: "Start progress",
+ description: "Begin working on task",
+ src: 66,
+ dst: 67,
+ workflow_id: 1,
+ user_confirmation: true,
+ },
+ ...
+ }
+ }
+ ids: [1,2,3,4,5]
+ }
+ */
+ this._require_obj("data", ['board', 'workflow', 'ids'], "Check code comments for propper format of data");
+ this._require_obj("Card", ["Card"], "Card object with Card property must point to concrete implementation of AbstractCard class.");
+
+ this.records = [];
+
+ //Keeping track of card widgets
+ this.cardWidgetsMap = new Map();
+
+ // Load current board options from storage service
+ this.kanbanOptions = storage_service.get("kto" + this.kanbanTableOptionsID) || {};
+ this.swimlane = this.swimlane || this.kanbanOptions.swimlane;
+
+ },
+ /**
+ * Override this method in order to append more swimlane options
+ * @returns {Map}
+ */
+ initSwimlaneDefinitions() {
+ return new Map([
+ [undefined, new SwimlaneDefinition(this, undefined, _t("No swimlanes"))],
+ ])
+ },
+ willStart() {
+ // Only user result is needed to be assigned to widget.
+ return $.when(data.cache.get("current_user"), this._super.apply(arguments), this.loadRecords(this.data.ids)).then(user => {
+ this.current_user = user;
+ this.prepareData();
+ return this.prepareSwimlaneData();
+ }
+ )
+ },
+ /**
+ * Wraps dataService.getRecords and saves records in cache for later synchronous use.
+ * @param ids
+ */
+ loadRecords(ids) {
+ return this.dataService.getRecords(ids).then(records => {
+ this.records.push.apply(this.records, records);
+ return records;
+ });
+ },
+ /**
+ * Wraps dataService.getRecord and saves record in cache for later synchronous use.
+ * @param id
+ */
+ loadRecord(id) {
+ return this.dataService.getRecord(id).then(record => {
+ this.records.push(record);
+ return record;
+ });
+ },
+ prepareData() {
+ // Create columns array and sort it by column order
+ let columns_map = this.data.board.columns;
+ this.data.sorted_columns = Object.keys(columns_map).map(key => columns_map[key]).sort((a, b) => a.order - b.order);
+ this.states = {};
+ this.data.board.stateToStatus = {};
+ this.data.workflow.global_states = {
+ in: [],
+ out: []
+ };
+ // Assign every state to a column in sorted_columns, map state to status and save global states
+ for (let status_id in this.data.board.status) {
+ let status = this.data.board.status[status_id];
+ let state = this.data.workflow.states[status.state_id];
+ let column = this.data.sorted_columns.find(col => {
+ return status.column_id == col.id;
+ });
+
+ state.global_in && this.data.workflow.global_states.in.push(state);
+ state.global_out && this.data.workflow.global_states.out.push(state);
+
+ this.data.board.stateToStatus[state.id] = status;
+
+ // Push state to column.states and create array if it didn't exist before.
+ (column.status = column.status || []).push(status);
+ this.states[state.id] = state;
+ }
+ },
+ renderElement() {
+ this._super();
+ this.$(".column-headers").append(this.renderHeaders());
+ this.renderSwimlanes(this.$(".swimlanes"));
+ },
+ prepareSwimlaneData() {
+ let swimlaneDefinition = this.swimlanes.get(this.swimlane).begin();
+ this.data.swimlanes = new Map();
+
+ let promises = [];
+
+ function recordCount() {
+ return this.records.length;
+ };
+ for (let record_id of this.data.ids) {
+ let record = this.records.find(r => r.id === record_id);
+ promises.push($.when(swimlaneDefinition.mapper(record), swimlaneDefinition.filter(record)).then((group, passIt) => {
+ if (passIt) {
+ if (this.data.swimlanes.has(group)) {
+ this.data.swimlanes.get(group).records.push(record);
+ }
+ else {
+ let swimlaneData = {records: [record]};
+ this.data.swimlanes.set(group, swimlaneData);
+ return $.when(swimlaneDefinition.header(record)).then(header => {
+ if (header) {
+ header.recordCount = recordCount.bind(swimlaneData);
+ }
+ swimlaneData.header = header;
+ })
+ }
+ }
+ }));
+ }
+ swimlaneDefinition.resolve();
+ return $.when(...promises);
+ },
+ getActiveSwimlane() {
+ return this.swimlanes.get(this.swimlane);
+ },
+ renderHeaders() {
+ let result = [];
+ for (let column of this.data.sorted_columns) {
+ result.push((`${column.name} `))
+ }
+ return result;
+ },
+ renderSwimlanes(placeholder) {
+ let result = [];
+ if (this.data.swimlanes.size < 1) {
+ return;
+ } else if (this.data.swimlanes.size === 1 && [...this.data.swimlanes.keys()][0] === undefined) {
+ this.data.swimlanes.forEach((data, id) => {
+ result.push(this.renderSwimlane(data, id, false, placeholder));
+ });
+ } else {
+ let swimlaneDefinition = this.swimlanes.get(this.swimlane)
+
+ // let sortedSwimlanes = [...this.data.swimlanes.keys()].sort((a, b) => !a ? 1 : -1);
+ let sortedSwimlanes = [...this.data.swimlanes.keys()].sort(swimlaneDefinition.compare);
+ sortedSwimlanes.forEach(id => {
+ let data = this.data.swimlanes.get(id);
+ result.push(this.renderSwimlane(data, id, true, placeholder));
+ });
+ }
+ return result;
+ },
+ renderSwimlane(data, id, renderHeader = true, placeholder) {
+ let node;
+ let swimlaneDefinition = this.swimlanes.get(this.swimlane);
+
+ if (!renderHeader) { // No swimlane
+ node = $(qweb.render(swimlaneDefinition.swimlaneNoHeaderTemplate).trim());
+ } else { // If swimlane has header, render collapsibles
+
+ node = $(qweb.render(swimlaneDefinition.swimlaneTemplate).trim());
+ let headerTemplate = data.header._overrideTemplate || swimlaneDefinition.headerTemplate;
+ let header = $(qweb.render(headerTemplate, data.header).trim());
+ node.find(".collapsible-header").append(header);
+ data.header.afterRender(header);
+ }
+
+ node.attr("data-swimlane-id", id);
+
+ placeholder.append(node);
+
+ // prepare records for columns and render them
+ let recordsByStageFieldId = new Map();
+ data.records.forEach(record => {
+ let recordStageFieldId = this.getStageFieldId(record);
+ recordsByStageFieldId.has(recordStageFieldId) ?
+ recordsByStageFieldId.get(recordStageFieldId).push(record) :
+ recordsByStageFieldId.set(recordStageFieldId, [record]);
+ });
+
+
+ for (let column of this.data.sorted_columns) {
+ let column_cards = [];
+ recordsByStageFieldId.forEach((records, stageFieldId) => {
+ // Check if card belongs to column by checking if some status has workflow.state that wraps around records stageFieldId
+ if (column.status && column.status.some(e => this.data.workflow.states[e.state_id].stage_id == stageFieldId)) {
+ column_cards.push(...records);
+ }
+ });
+ this.renderColumn(column, column_cards, node.find(".columns"));
+ }
+ return node;
+ },
+ renderColumn(column, records, placeholder) {
+ let swimlaneDefinition = this.swimlanes.get(this.swimlane);
+ let node = $(qweb.render(swimlaneDefinition.columnTemplate, column));
+ placeholder.append(node);
+ let sorted_records = records.sort((a, b) => a.agile_order - b.agile_order);
+ for (let record of sorted_records) {
+ let cardWidget = this.renderCard(record);
+ cardWidget.appendTo(node).then(() => {
+ cardWidget.start();
+ });
+ }
+
+ var tableThis = this;
+ node.sortable({
+ start: function (event, ui) {
+ var cardNode = $(ui.helper);
+ let swimlaneId = cardNode.getDataFromAncestor("swimlane-id", ".swimlane");
+ let columnId = cardNode.getDataFromAncestor("column-id");
+ let cardId = cardNode.getDataFromAncestor("card-id");
+
+ this.swimlaneNode = swimlaneId === undefined ?
+ tableThis.$(`.swimlane:not([data-swimlane-id])`) :
+ tableThis.$(`.swimlane[data-swimlane-id=${swimlaneId}]`);
+
+ let preventStopEvent = this.preventStopEvent;
+ // Generate overlays over all other columns except the source column
+ for (let columnNode of $.makeArray(this.swimlaneNode.find(`.column:not([data-column-id=${columnId}])`))) {
+ columnNode = $(columnNode);
+ let columnNodeId = columnNode.data("column-id");
+ let columnOverlay = tableThis.generateOverlay(columnNodeId, cardId);
+
+ // Attach event on drop on each of overlay states
+ columnOverlay.find(".state").on("drop", (event, ui) => {
+ let cardNode = $(ui.helper);
+ let cardId = cardNode.data("card-id");
+ let targetDataset = event.target.dataset;
+ let newState = tableThis.data.workflow.states[targetDataset["stateId"]];
+ let newStatus = tableThis.data.board.stateToStatus[newState.id];
+ let isTransitionGlobal = targetDataset["transitionId"] === "global";
+ let transition = tableThis.data.workflow.transitions[targetDataset["transitionId"]];
+
+ // get cardWidget from table
+ let cardWidget = tableThis.cardWidgetsMap.get(cardId);
+ let stage_id = parseInt(newState.stage_id);
+
+ if (!isTransitionGlobal && transition.user_confirmation) {
+ tableThis.openStageChangeModal(newState.stage_id, cardWidget, message => {
+ cardWidget.record[tableThis.stageField] = stage_id;
+ });
+ } else {
+ cardWidget.record[tableThis.stageField] = stage_id;
+ }
+
+ // Set property of sortable so that sorting within column is not mixed with changing column.
+ preventStopEvent = true;
+ });
+ columnOverlay.appendTo(columnNode);
+ }
+ console.log(swimlaneId, columnId, cardId);
+ },
+ stop: function (event, ui) {
+ console.log("removing overlays");
+ this.swimlaneNode.find(".column-overlay").remove();
+
+ if (this.preventStopEvent) {
+ delete this.preventStopEvent;
+ return;
+ }
+ console.log(event);
+ }
+ });
+ return node;
+ },
+ renderCard(record) {
+ if (this.cardWidgetsMap.has(record.id)) {
+ return this.cardWidgetsMap.get(record.id);
+ }
+ let cardWidget = new this.Card.Card(this, {record});
+ this.cardWidgetsMap.set(record.id, cardWidget);
+ return cardWidget;
+
+ },
+ getStageFieldId(record) {
+ return getFieldId(record, this.stageField);
+ },
+ getStageFieldName(record) {
+ return getFieldName(record, this.stageField);
+ },
+ getWorkflowState(stageFieldId, workflow_id) {
+ for (let state_id in this.data.workflow.states) {
+ let state = this.data.workflow.states[state_id];
+ if (state.workflow_id === workflow_id && state[this.stageField] === stageFieldId) {
+ return state;
+ }
+ }
+ },
+ getColumnFromStageField(stageFieldId) {
+ for (let column of this.data.sorted_columns) {
+ for (let status of column.status) {
+ if (this.data.workflow.states[status.state_id].stage_id === stageFieldId) {
+ return column;
+ }
+ }
+ }
+ },
+ generateOverlay: function (columnId, recordId) {
+ let record = this.records.find(r => r.id === recordId);
+ let stageFieldId = this.getStageFieldId(record);
+
+ let currentState = this.getWorkflowState(stageFieldId, record.workflow_id[0]);
+ let availableTransitions = this.getAvailableTransitions(currentState, this.data.workflow, record);
+
+ var overlay = $(`
`);
+
+ if (this.data.board.columns[columnId].status) {
+ for (let status of this.data.board.columns[columnId].status) {
+ let state = this.data.workflow.states[status.state_id];
+ let transition = availableTransitions.find(t => t.dst == state.id);
+ if (transition) {
+ let stateNode = $(`${state.name}
`);
+ stateNode.droppable({
+ classes: {"ui-droppable-hover": "hover"},
+ });
+ stateNode.appendTo(overlay);
+ }
+ }
+ }
+ return overlay;
+ },
+ getAvailableTransitions(currentState, workflow) {
+ // Duplicate transitions won't be rendered multiple times, so don't worry
+ // This case can happen, if there is in/out transition and state is global in/our
+ let transitions = currentState.out_transitions.map(t_id => workflow.transitions[t_id]);
+ if (currentState.global_out) {
+ for (let state_id in workflow.states) {
+ let state = workflow.states[state_id];
+ if (state.id !== currentState.id) {
+ transitions.push(this.generateFakeTransition(workflow, currentState, state));
+ }
+ }
+ } else {
+ workflow.global_states.in.filter(e => e.id != currentState.id).forEach(state => {
+ transitions.push(this.generateFakeTransition(workflow, currentState, state));
+ });
+ }
+ console.log(transitions);
+ return transitions;
+ },
+ generateFakeTransition(workflow, src, dst) {
+ return {
+ description: "",
+ dst: dst.id,
+ id: "global",
+ name: dst.name,
+ src: src.id,
+ user_confirmation: false,
+ workflow_id: workflow.id
+ }
+ },
+ openStageChangeModal(newStageId, cardWidget, confirmedCallback) {
+ let state = this.getWorkflowState(newStageId, cardWidget.record.workflow_id[0]);
+ var modal = new AgileModals.TaskStageConfirmationModal(this, {
+ taskId: cardWidget.record.id,
+ stageId: newStageId,
+ stageName: state.name,
+ userName: cardWidget.record.user_id ? cardWidget.record.user_id[1] : _t("Unassigned"),
+ afterHook: (confirmation, form, result) => {
+ confirmedCallback(result);
+ }
+ });
+ modal.appendTo($("body"));
+ },
+ getCard(id) {
+ return this.cardWidgetsMap.get(id);
+ },
+ addCard(id, syncerMeta, highlight = true) {
+ return this._doAddCard(id, syncerMeta, highlight, INDEX_NOT_FOUND);
+ },
+
+ insertCardAt(id, index, syncerMeta, highlight = true) {
+ return this._doAddCard(id, syncerMeta, highlight, index);
+ },
+ shouldCardBeAdded(record) {
+ return true;
+ },
+ _doAddCard(id, syncerMeta, highlight, index) {
+ return this.dataService.getRecord(id).then(record => {
+ if (record && this.shouldCardBeAdded(record)) {
+ let swimlaneDefinition = this.swimlanes.get(this.swimlane).begin();
+ let def = $.when(swimlaneDefinition.mapper(record), swimlaneDefinition.filter(record)).then((group, passIt) => {
+ if (passIt) {
+ if (this.data.swimlanes.has(group)) {
+ this.data.swimlanes.get(group).records.push(record);
+ let column = this.getColumnFromStageField(this.getStageFieldId(record));
+ if (!column) {
+ return;
+ }
+ var node = group === undefined ?
+ this.$(`.swimlane:not([data-swimlane-id]) ${" "} div[data-column-id="${column.id}"]`) :
+ this.$(`.swimlane[data-swimlane-id=${group}] ${" "} div[data-column-id="${column.id}"]`);
+ let cardWidget = this.renderCard(record);
+
+ if (index > INDEX_NOT_FOUND) {
+ cardWidget.insertAt(node, index).then(() => {
+ cardWidget.start();
+ });
+ ;
+ } else {
+ cardWidget.appendTo(node).then(() => {
+ cardWidget.start();
+ });
+ ;
+ }
+ let swimlaneNode = group === undefined ?
+ this.$('.swimlane:not([data-swimlane-id])') :
+ this.$(`.swimlane[data-swimlane-id=${group}]`);
+ let count = this.data.swimlanes.get(group).records.length;
+ swimlaneNode.find(".swimlane-header .count").text(count + " " + pluralize('issue', count));
+
+ if (syncerMeta.indirect === false) {
+ cardWidget._is_added_to_DOM.then(() => {
+ node.scrollToElement(cardWidget.$el);
+ highlight && cardWidget.$el.highlight();
+ });
+ }
+ }
+ else { // If destination swimlane doesn't exist then render it with new card and append in view
+ let swimlaneData = {records: [record]};
+ this.data.swimlanes.set(group, swimlaneData);
+
+ let recordCount = function () {
+ return this.records.length;
+ };
+ return $.when(swimlaneDefinition.header(record)).then(header => {
+ if (header) {
+ header.recordCount = recordCount.bind(swimlaneData);
+ }
+ swimlaneData.header = header;
+ // If last swimlane is undefined, then insert new swimlane before it, otherwize insert swimlane after it.
+ let lastSwimlane = this.$(".swimlane").last();
+ let newSwimlaneNode = this.renderSwimlane(swimlaneData, group, !!header, lastSwimlane);
+ if (this.$(".swimlane").length === 0) {
+ this.$(".swimlanes").append(newSwimlaneNode)
+ } else if (lastSwimlane.data("swimlane-id") !== undefined) {
+
+ let sortedSwimlanes = [...this.data.swimlanes.keys()].sort(swimlaneDefinition.compare);
+ let index = sortedSwimlanes.indexOf(group);
+
+ this.$(".swimlanes").insertAt(newSwimlaneNode, index);
+ //newSwimlaneNode.insertAfter(lastSwimlane);
+ } else {
+ newSwimlaneNode.insertBefore(lastSwimlane)
+ }
+ // Enable collapsing in new swimlane
+ newSwimlaneNode.find('.collapsible').collapsible();
+ })
+ }
+ if (syncerMeta) {
+ if (syncerMeta.user_id.id !== data.session.uid && syncerMeta.indirect === false) {
+ AgileToast.toastTask(syncerMeta.user_id, record, syncerMeta.method);
+ }
+ }
+ }
+ });
+ swimlaneDefinition.resolve();
+ return def;
+ }
+ });
+
+ },
+ removeCard(id, removeFromCache = false, syncerMeta) {
+ let cardWidget = this.cardWidgetsMap.get(id);
+ if (!cardWidget) {
+ return false;
+ }
+ if (removeFromCache) {
+ let swimlaneDefinition = this.swimlanes.get(this.swimlane).begin();
+ let previousMapped = cardWidget.record._previous ? swimlaneDefinition.mapper(cardWidget.record._previous) : null;
+ $.when(previousMapped, swimlaneDefinition.mapper(cardWidget.record), swimlaneDefinition.filter(cardWidget.record)).then((previousGroup, group, passIt) => {
+ if (previousGroup !== null) {
+ let swimlaneData = this.data.swimlanes.get(previousGroup);
+ swimlaneData.records = swimlaneData.records.filter(e => e.id !== cardWidget.record.id);
+ let swimlaneNode = previousGroup === undefined ?
+ this.$('.swimlane:not([data-swimlane-id])') :
+ this.$(`.swimlane[data-swimlane-id=${previousGroup}]`);
+ if (swimlaneData.records.length === 0) {
+ this.data.swimlanes.delete(previousGroup);
+ swimlaneNode.remove();
+ } else {
+ let count = swimlaneData.records.length;
+ swimlaneNode.find(".swimlane-header .count").text(count + " " + pluralize('issue', count));
+ }
+ }
+ });
+
+ cardWidget.destroy();
+ this.cardWidgetsMap.delete(id)
+ } else {
+ cardWidget.$el.detach();
+ }
+ if (syncerMeta) {
+ if (syncerMeta.user_id.id !== data.session.uid && syncerMeta.indirect === false) {
+ AgileToast.toastTask(syncerMeta.user_id, syncerMeta.data, syncerMeta.method);
+ }
+ }
+ },
+ /**
+ * This method should return [project.workflow.state].id.
+ * Usually from [this.stageField] and workflow,
+ * but if there is related field on model, it can be returned also.
+ *
+ * @param {number} id - ID of record under the card.
+ */
+ getCardState(id) {
+ throw new Error("Not implemented");
+ },
+ resolveCardIndex(card, delta) {
+ return INDEX_NOT_FOUND;
+ },
+ setSwimlane(name, store = true) {
+ this.kanbanOptions.swimlane = name;
+ store && storage_service.set("kto" + this.kanbanTableOptionsID, this.kanbanOptions);
+ this.prepareSwimlaneData().then(() => {
+ this.$(".swimlanes").empty();
+ this.renderSwimlanes(this.$(".swimlanes"));
+ this.$('.collapsible').collapsible();
+ });
+ },
+ addedToDOM() {
+ this.$('.collapsible').collapsible();
+ }
+ });
+ var TaskTable = AbstractKanbanTable.extend({
+ Card: {Card: TaskCard},
+ dataService: task_service,
+ stageField: "stage_id",
+ init(parent, options) {
+ this._super(parent, options);
+ if (!Array.isArray(this.data.board.task_types)) {
+ throw new Error("TaskTable requires board to define task_type as Array");
+ }
+ },
+ initSwimlaneDefinitions() {
+ let defs = this._super();
+ defs.set('user_id', new SwimlaneDefinition(this, 'user_id', _t("Assignee"), _t("Unassigned")));
+ defs.set('priority_id', new SwimlaneDefinition(this, 'priority_id', _t("Priority"), _t("Without priority")));
+ defs.set('project_id', new SwimlaneDefinition(this, 'project_id', _t("Project"), _t("Without project")));
+ defs.set('epic_id', new SwimlaneDefinition(this, 'epic_id', _t("Epic"), _t("Without epic")));
+ defs.set('story', new StorySwimlaneDefinition(this));
+ return defs;
+ },
+ prepareData() {
+ this._super();
+ this.board_project_ids = Object.keys(this.data.board.projects).map(k => parseInt(k));
+ },
+ getCardState(id) {
+ return this.cardWidgetsMap.get(id).task.wkf_state_id;
+ },
+ shouldCardBeAdded(task) {
+
+ // Filter tasks by project filters
+ let team_project_ids = this.current_user.team_ids[this.current_user.team_id[0]].project_ids;
+ let hash_project_id = parseInt(hash_service.get("project"));
+ let task_project_id = task.project_id[0];
+
+ if (hash_project_id && task_project_id !== hash_project_id) return false;
+ if (!team_project_ids.includes(task_project_id)) return false;
+ if (!this.board_project_ids.includes(task_project_id)) return false;
+
+ // Filter task by task_types filter
+ if (this.data.board.task_types.length && !this.data.board.task_types.includes(task.type_id[0])) return false;
+
+ // todo Map task (stage_id, workflow_id) to Wkf State and then check if the state is mapped to any of the columns in the board
+ // todo Check if stage_id is in this.data.workflow.states (but create stageToState map when loading)
+
+ return true;
+ },
+ resolveCardIndex(id, delta) {
+ let card = this.cardWidgetsMap.get(id);
+ if (!card) return INDEX_NOT_FOUND;
+
+ let swimlane = this.getActiveSwimlane();
+ let swimlane_field = swimlane.field === undefined ? false :
+ swimlane.field === 'story' ? 'parent_id' : swimlane.field;
+
+ let isUpdated = function (fieldName) {
+ if (!(fieldName in delta)) return false;
+ let left = getFieldId(delta[fieldName]);
+ let right = fieldName in card.record._previous ? getFieldId(card.record._previous[fieldName]) : false;
+ return left != right;
+ }.bind(this);
+
+ let isUpdatedStageField = function () {
+ return isUpdated(this.stageField);
+ }.bind(this);
+
+
+ // When there is no swimlane we need to see if the stage is updated
+ if (swimlane_field === undefined)
+ return isUpdatedStageField();
+
+ // Check if the current swimlane field is updated
+ if (isUpdated(swimlane.field))
+ return INDEX_NOT_FOUND;
+
+ if (isUpdatedStageField())
+ return INDEX_NOT_FOUND;
+
+ return card.index();
+ },
+ });
+
+ var AbstractKanbanTableView = BaseWidgets.AgileViewWidget.extend({
+ _name: "KanbanTableView",
+ template: "scrummer.view.kanban_table",
+ emptyTitle: _t("No data in kanban table"),
+ emptyTemplate: "scrummer.view.kanban_table.empty",
+ init(parent, options) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ // Because of core.Class implementation wraps functions, we will have to wrap KanbanTable class in an object.
+ this._require_obj("KanbanTable", ["KanbanTable"], "KanbanTable object with KanbanTable property must point to concrete implementation of AbstractKanbanTable class.");
+ },
+ openSettings() {
+ // Set form fields.
+ if (this.kanbanTable.swimlane) {
+ this.$("#modal-settings select").val(this.kanbanTable.swimlane).material_select();
+ }
+ let modalNode = this.$("#modal-settings");
+ modalNode.materialModal("open");
+ },
+ destroy() {
+ this._super();
+ // Not sure if this is needed anymore
+ // TODO: Check why is this here...
+ if ($(".lean-overlay").size()) {
+ $(".lean-overlay").remove();
+ }
+ },
+ isEmpty() {
+ throw new Error("Not implemented");
+ },
+ getTitle() {
+ console.warn("This should be overridden in concrete implementation");
+ return _t("Kanban table");
+ },
+ willStart() {
+ return this._super().then(data.cache.get("current_user").then(user => {
+ this.user = user;
+ }));
+ },
+ renderElement() {
+ // Handling case when there is no data, and empty template should be rendered
+ if (this.isEmpty()) {
+ this.setTitle(this.emptyTitle);
+ }
+ this._super();
+ if (!this.isEmpty()) {
+ this.kanbanTable = new this.KanbanTable.KanbanTable(this, this.generateKanbanTableOptions());
+
+ // Render settings modal
+ this.$("#kanban-table-view").append(this.renderSettingsModal());
+ this.kanbanTable.appendTo(this.$("#kanban-table-view"));
+ this.setTitle(this.getTitle());
+
+ // Set action menu
+ this.trigger_up("init_action_menu", this.getActionMenu());
+ }
+ //this.$el.append(JSON.stringify(this.data));
+ },
+ generateKanbanTableOptions() {
+ return {data: this.data};
+ },
+ renderSettingsModal() {
+ let swimlanes = [];
+ for (let [key, obj] of this.kanbanTable.swimlanes.entries()) {
+ swimlanes.push({value: key, text: obj.text});
+ }
+ return qweb.render("scrummer.view.kanban_table.settings_modal", {swimlanes});
+ },
+ _getSwimlaneOptions() {
+ return this.kanbanTable.swimlanes
+ },
+ getActionMenu() {
+ return {
+ items: [
+ {icon: "settings", action: this.openSettings.bind(this)}
+ ]
+ }
+ },
+ start() {
+ this._is_added_to_DOM.then(() => {
+ this.$('select').material_select();
+ //this.$('.section').perfectScrollbar({suppressScrollY: true});
+ });
+
+ let modalNode = this.$("#modal-settings");
+ // On save button click check if form has been modified, and if so update options, and store them to storage_service
+ this.$("#modal-settings .modal-save").click(evt => {
+ if (this.kanbanTable.swimlane !== this.$("#modal-settings select :selected").attr("value")) {
+ this.kanbanTable.swimlane = this.$("#modal-settings select :selected").attr("value");
+ this.kanbanTable.setSwimlane(this.kanbanTable.swimlane);
+ }
+ modalNode.materialModal("close");
+ });
+ modalNode.materialModal();
+ return this._super();
+ }
+ });
+ var TaskKanbanTableView = AbstractKanbanTableView.extend({
+ custom_events: Object.assign(AbstractKanbanTableView.prototype.custom_events, {
+ open_task: "_onOpenTask",
+ }),
+ _onOpenTask: function (evt) {
+ this.trigger_up("open_right_side", {
+ WidgetClass: TaskWidget,
+ options: {id: evt.data.id, isQuickDetailView: true}
+ });
+ },
+ addedToDOM() {
+ core.bus.on("project.task:write", this, this._onProjectTaskWrite);
+ core.bus.on("project.task:create", this, this._onProjectTaskCreate);
+ core.bus.on("project.task:unlink", this, this._onProjectTaskUnlink);
+ return this._super();
+ },
+ _onProjectTaskWrite(id, delta, payload, record) {
+ if (!this.kanbanTable) {
+ return
+ }
+
+ let editPromise = record && record._edit("check") ? record._edit() : $.when();
+ editPromise.then(() => {
+ let cardIndex = this.kanbanTable.resolveCardIndex(id, delta);
+ this.kanbanTable.removeCard(id, true);
+ return this.kanbanTable.insertCardAt(id, cardIndex, payload).then(() => {
+ if (this.rightSideWidget && this.rightSideWidget.id === id) {
+ // Since trigger_up wraps event arguments in data object, here I mimic that behaviour.
+ this.trigger("open_right_side", {
+ data: {
+ WidgetClass: TaskWidget,
+ options: {id, isQuickDetailView: true}
+ }
+ });
+ }
+ });
+ });
+ },
+ _onProjectTaskCreate(id, vals, payload) {
+ if (!this.kanbanTable) {
+ return
+ }
+
+ this.kanbanTable.addCard(id, payload);
+ },
+ _onProjectTaskUnlink(id, payload) {
+ if (!this.kanbanTable) {
+ return
+ }
+
+ this.kanbanTable.removeCard(id, true, payload);
+ if (this.rightSideWidget && this.rightSideWidget.id === id) {
+ this.rightSideWidget.destroy(true);
+ delete this.rightSideWidget;
+ }
+ },
+ });
+
+
+ return {
+ AbstractKanbanTableView,
+ AbstractKanbanTable,
+ AbstractCard,
+ TaskCard,
+ TaskKanbanTableView,
+ TaskTable,
+ SwimlaneDefinition,
+ AsyncSwimlaneDefinition,
+ StorySwimlaneDefinition,
+ }
+});
diff --git a/scrummer/static/src/js/views/page_manager.js b/scrummer/static/src/js/views/page_manager.js
new file mode 100644
index 0000000..0df33de
--- /dev/null
+++ b/scrummer/static/src/js/views/page_manager.js
@@ -0,0 +1,99 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.page_manager', function (require) {
+ "use strict";
+
+ const web_core = require('web.core');
+ const _t = web_core._t;
+ const core = require('scrummer.core');
+ const bus = core.bus;
+ const hash_service = require('scrummer.hash_service');
+ const AgileBaseWidget = require('scrummer.BaseWidgets').AgileBaseWidget;
+ const DashboardPage = require('scrummer.page.dashboard').DashboardPage;
+ const BoardPage = require('scrummer.page.board');
+
+ const qweb = core.qweb;
+
+ // Key is used to define what string should be used in hash_service for ViewManager
+ const PageManager = AgileBaseWidget.extend({
+ key: "page",
+ id: "middle",
+ _name: "Page Manager",
+ init(parent, options = {}){
+ this._super(parent, options);
+ Object.assign(this, options);
+ this._require_prop("key");
+ this._require_prop("defaultView");
+
+ this.build_view_registry();
+ this.instantiate_views();
+ bus.on('team:changed', null, (team_id, team_changing) => {
+ data.cache.get("current_user").then(user => {
+ if (user.team_ids[user.team_id[0]].project_ids.length) {
+ this.rerender_view({team_changing});
+ }
+ else {
+ this.set_view("dashboard", {team_changing});
+ }
+ });
+ });
+ },
+
+ instantiate_views(){
+ //Subscribe to view change event on hash service
+ hash_service.on("change:" + this.key, this, (hash_service, options) => this.set_view(options.newValue));
+ },
+
+ renderElement(){
+ this._super();
+ this.$el.prepend($("
"));
+ // set default view if none is set
+ if (!hash_service.get(this.key)) {
+ hash_service.setHash(this.key, this.defaultView, false);
+ } else {
+ this.set_view(hash_service.get(this.key));
+ }
+ },
+ set_view(view_name, options = {}){
+ if (this.view_registry.get(view_name)) {
+ this.current_view = view_name;
+ let ViewWidget = this.view_registry.get(view_name);
+
+ // Checking if ViewWidget is AgileBaseWidget subclass,
+ // I've been able to identify that it is subclass of root OdooClass
+ // TODO: Test if ViewWidget is extension of AgileBaseWidget
+ if (!ViewWidget.toString().includes("OdooClass")) {
+ throw new Error(_t("Widget does not exist"));
+ }
+
+ // if current widget property is set, and has destroy method, call it to destroy widget.
+ if (this.widget && typeof this.widget.destroy === "function") {
+ this.widget.destroy();
+ }
+
+ // Instantiate ViewWidget with this as parent and add it to DOM.
+ this.widget = new ViewWidget(this, options);
+ this.widget.appendTo(this.$el);
+ console.log(this.message = "View " + view_name + " loaded...");
+ } else {
+ hash_service.setHash(this.key, this.defaultView, false);
+ console.error(_t("View ") + view_name + _t(" does not exist!"));
+ }
+ },
+ rerender_view(options){
+ this.set_view(this.current_view, options);
+ },
+ // Overwrite this method and call this._super() in order to add additional views to registry
+ // view_registry is map with view name as key and widget class as value
+ // All view widgets should extend AgileViewWidget, and set appropriate title property
+ build_view_registry(){
+ this.view_registry = new Map();
+ this.view_registry.set("dashboard", DashboardPage);
+ this.view_registry.set("board", BoardPage);
+ }
+ });
+
+ return PageManager
+
+});
diff --git a/scrummer/static/src/js/views/pages/board.js b/scrummer/static/src/js/views/pages/board.js
new file mode 100644
index 0000000..b8964f7
--- /dev/null
+++ b/scrummer/static/src/js/views/pages/board.js
@@ -0,0 +1,156 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+odoo.define('scrummer.page.board', function (require) {
+ "use strict";
+
+ const AgileContainerWidget = require('scrummer.BaseWidgets').AgileContainerWidget;
+ const hash_service = require('scrummer.hash_service');
+ const storage_service = require('scrummer.storage_service');
+ const AgileMenu = require('scrummer.menu');
+ const data = require('scrummer.data');
+ const ViewManager = require('scrummer.view_manager');
+ const BoardChooser = require('scrummer.board_chooser').BoardChooser;
+ const crash_manager = require('web.crash_manager');
+ const web_core = require('web.core');
+ const _t = web_core._t;
+
+ const BoardPage = AgileContainerWidget.extend({
+ template: "scrummer.page.board",
+ _name: "BoardPage",
+ custom_events: {
+ board_type_changed: function () {
+ this.rerender_widget(['boardDeferred']);
+ }
+ },
+ init(parent, options) {
+ this._super(parent, options);
+ this.trigger_up('menu.added');
+ window.bp = this;
+ },
+ willStart() {
+ return this._super().then(() => {
+ this.boardDeferred = $.Deferred();
+ this.getBoard(this.boardDeferred);
+ return this.boardDeferred.promise();
+ });
+ },
+ handleNoBoard() {
+ crash_manager.show_error({
+ type: _t("Configuration error"),
+ message: _t("You don't have access to any board."),
+ data: {debug: ""}
+ });
+ hash_service.setHash("page", "dashboard");
+ },
+ getBoard(deferred) {
+ data.cache.get("current_user").then(user => {
+ // Checking if board id is set in URL
+ // Note: it can be invalid if user lost rights to see it
+ let board = hash_service.get("board") || storage_service.get("board");
+ if (user.board_ids.includes(board)) {
+ this.board = board;
+ if(hash_service.get("board") !== board){
+ hash_service.set("board", board)
+ }
+ if(storage_service.get("board") !== board){
+ storage_service.set("board", board)
+ }
+ }
+ if (!this.board) {
+ let project_id = hash_service.get("project");
+ if (project_id) {
+ data.cache.get("board_for_project", {id: project_id}).then(board_id => {
+ if (!board_id) {
+ this.handleNoBoard();
+ return;
+ }
+ this.board = board_id;
+ this.fetchBoard(board_id).done(deferred.resolve);
+ hash_service.set("board", this.board);
+ });
+ }
+ else {
+ data.getDataSet("project.agile.board").read_slice([], {
+ domain: [["is_default", "=", true]]
+ }).then(boards => {
+ if (boards.length === 0) {
+ this.handleNoBoard();
+ deferred.reject();
+ return;
+ }
+ this.board_data = boards[0];
+ hash_service.set("board", this.board_data.id);
+ storage_service.set("board", this.board_data.id);
+ deferred.resolve();
+ })
+ }
+ }
+ if (this.board) {
+ this.fetchBoard(this.board).done(deferred.resolve)
+ }
+ });
+ },
+ fetchBoard(board_id) {
+ let getBoardDef = $.Deferred();
+ data.getDataSet("project.agile.board").read_ids([parseInt(board_id)]).then(boards => {
+ if (boards.length === 0) {
+ hash_service.delete("board");
+ storage_service.delete("board");
+ this.getBoard(this.boardDeferred);
+ getBoardDef.reject();
+ return;
+ }
+ this.board_data = boards[0];
+ getBoardDef.resolve();
+ });
+ return getBoardDef.promise();
+ },
+ start() {
+ this._is_added_to_DOM.then(() => {
+ //Main Left Sidebar Menu
+ $('.button-collapse').sideNav({
+ menuWidth: 300,
+ edge: 'left', // Choose the horizontal origin
+ });
+ });
+ this.trigger_up('menu.added');
+ return this._super();
+ },
+ destroy() {
+ hash_service.delete("task");
+ hash_service.delete("view");
+ hash_service.delete("board");
+ $('.button-collapse').sideNav('hide');
+ return this._super();
+ },
+ build_widget_list() {
+
+ this.add_widget({
+ 'id': 'menu_widget',
+ 'widget': AgileMenu.AgileViewMenu,
+ 'replace': 'widget.aside-left',
+ 'args': {
+ viewKey: "view",
+ template: "scrummer.menu",
+ boardType: this.board_data.type,
+ }
+ });
+ this.add_widget({
+ 'id': 'board_chooser',
+ 'widget': BoardChooser,
+ 'replace': 'widget.board-chooser',
+ });
+ this.add_widget({
+ 'id': 'view_manager_widget',
+ 'widget': ViewManager,
+ 'replace': 'widget.view_manager',
+ 'args': {
+ defaultView: this.board_data.type,
+ _name: "view_manager_widget",
+ }
+ });
+ }
+ });
+
+ return BoardPage;
+});
diff --git a/scrummer/static/src/js/views/pages/dashboard.js b/scrummer/static/src/js/views/pages/dashboard.js
new file mode 100644
index 0000000..ff0a1ba
--- /dev/null
+++ b/scrummer/static/src/js/views/pages/dashboard.js
@@ -0,0 +1,167 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+odoo.define('scrummer.page.dashboard', function (require) {
+ "use strict";
+
+ var ModelList = require('scrummer.model_list');
+ var AbstractModelList = require('scrummer.abstract_model_list');
+ var core = require('scrummer.core');
+ var qweb = require('web.core').qweb;
+ var bus = core.bus;
+ var _t = require('web.core')._t;
+ var AgileBaseWidgets = require('scrummer.BaseWidgets');
+ var hash_service = require('scrummer.hash_service');
+ var SubheaderWidget = require('scrummer.subheader').SubheaderWidget;
+ var data = require('scrummer.data');
+ var pluralize = require('pluralize');
+ var ActivityStream = require('scrummer.activity_stream').ActivityStream;
+
+ var DashboardPage = AgileBaseWidgets.AgileViewWidget.extend({
+ title: _t("Dashboard"),
+ _name: "Dashboard",
+ template: "scrummer.page.dashboard",
+ init(parent, options) {
+ this._super(parent, options);
+ this.projectList = new AbstractModelList.ModelList(this, {
+ model: "project.project",
+ emptyPlaceholder: $(qweb.render("scrummer.dashboard.project-list.empty", {})),
+ fields: [
+ "name",
+ "image_key",
+ "user_id",
+ "key",
+ "state",
+ "partner_id",
+ "todo_estimation",
+ "in_progress_estimation",
+ "done_estimation",
+ "__last_update"
+ ],
+ domain: $.when(data.cache.get("current_user"))
+ .then(user => [["id", "in", user.team_ids[user.team_id[0]].project_ids], ["workflow_id", "!=", false]]),
+ ModelItem: ProjectItem
+ });
+ this.assignedToMeList = new AssignedToMe(this);
+ this.activityStream = new ActivityStream(this, {team_changing: this.options.team_changing});
+ this.subheader = new SubheaderWidget(this);
+
+ this.trigger_up('menu.removed');
+ },
+ start() {
+ let allTasks = $("");
+ this.$("#project-list").parent().find("div.list-title").append(allTasks);
+ allTasks.click(() => {
+ hash_service.delete("project");
+ hash_service.setHash("page", "board");
+ });
+ this.trigger_up('menu.removed');
+ },
+ renderElement() {
+ this._super();
+ this.projectList.appendTo(this.$("#project-list"));
+ this.assignedToMeList.appendTo(this.$("#assigned-to-me"));
+ this.activityStream.appendTo(this.$("#activity-stream"));
+ this.subheader.appendTo(this.$("#subheader-wrapper"));
+ this.projectList._is_added_to_DOM.then(() => {
+ this.$('.list-preloader.projects').remove();
+ });
+ }
+ });
+ const AssignedToMeMenuItem = ModelList.SimpleTaskItem.extend({
+ start() {
+ this.$(".task-menu").hide();
+ this.$(".task-key").click(e => {
+ hash_service.setHash("project", this.record.project_id[0]);
+ });
+ return this._super();
+ }
+ });
+ AssignedToMeMenuItem.sort_by = "agile_order";
+ var AssignedToMe = AgileBaseWidgets.AgileBaseWidget.extend({
+ _name: "AssignedToMe",
+ template: 'scrummer.dashboard.assigned_to_me',
+ init(parent, options) {
+ this._super(parent, options);
+ this.estimates = {
+ todo: 0,
+ in_progress: 0,
+ done: 0,
+ };
+ this.assignedToMeList = new AbstractModelList.ModelList(this, {
+ template: "scrummer.backlog.task_list",
+ model: "project.task",
+ ModelItem: AssignedToMeMenuItem,
+ emptyPlaceholder: $("" + _t("You havent commited to any task in this team.") + "
"),
+ fields: ["name",
+ "agile_order",
+ "story_points",
+ "project_id",
+ "key",
+ "color",
+ "priority_id",
+ "parent_id",
+ "parent_key",
+ "type_id",
+ "user_id",
+ "priority_scrummer_icon_color",
+ "priority_scrummer_icon",
+ "type_scrummer_icon_color",
+ "type_scrummer_icon",
+ "wkf_state_type"],
+ domain: $.when(data.xmlidToResId("scrummer.project_task_type_epic"), data.cache.get("current_user"))
+ .then((type_epic, user) => [["user_id", "=", data.session.uid],
+ ["type_id", "!=", type_epic],
+ ["project_id", "in", user.team_ids[user.team_id[0]].project_ids]]),
+ _name: "Assigned to me",
+ attributes: {"data-id": this.id}
+ });
+ },
+ renderElement() {
+ this._super();
+ this.assignedToMeList.appendTo(this.$el);
+ this.assignedToMeList._is_rendered.then(() => {
+ let items = this.assignedToMeList.data;
+ this.$(".list-preloader").remove();
+ this.$(".list-count").text(items.length + " " + pluralize('issue', items.length));
+ for (let task of items) {
+ this.estimates[task.wkf_state_type] += task.story_points;
+ }
+ this.$(".estimates .estimate.todo").html(this.estimates.todo);
+ this.$(".estimates .estimate.in_progress").html(this.estimates.in_progress);
+ this.$(".estimates .estimate.done").html(this.estimates.done);
+ this.$(".estimates").show();
+ });
+ this.assignedToMeList._is_added_to_DOM.then(() => {
+ this.assignedToMeList.$('.tooltipped').tooltip({delay: 50});
+ });
+ }
+ });
+
+ var ProjectItem = AbstractModelList.AbstractModelListItem.extend({
+ _name: "ProjectItem",
+ template: "scrummer.list.project_item",
+ //order_field: "agile_order",
+ init(parent, options) {
+ this._super(parent, options);
+ },
+ start() {
+ // When clicked on project in dashboard, fetch all boards and open last board.
+ this.$("a.project-key").click(() => {
+ hash_service.setHash("project", this.record.id, false);
+ hash_service.setHash("page", "board", false);
+ });
+ return this._super();
+ },
+ image_url() {
+ return data.getImage("project.project", this.record.id, this.record.__last_update);
+ }
+ });
+ ProjectItem.sort_by = "agile_order";
+
+ return {
+ DashboardPage,
+ AssignedToMe,
+ AssignedToMeMenuItem,
+ ProjectItem
+ };
+});
diff --git a/scrummer/static/src/js/views/task.js b/scrummer/static/src/js/views/task.js
new file mode 100644
index 0000000..4940faf
--- /dev/null
+++ b/scrummer/static/src/js/views/task.js
@@ -0,0 +1,371 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.view.task', function (require) {
+ "use strict";
+ const data = require('scrummer.data');
+ const DataServiceFactory = require('scrummer.data_service_factory');
+ const BaseWidgets = require('scrummer.BaseWidgets');
+ const hash_service = require('scrummer.hash_service');
+ const TaskWidget = require('scrummer.widget.task').TaskWidget;
+ const AgileModals = require('scrummer.widget.modal');
+ const AgileToast = require('scrummer.toast');
+ const core = require('scrummer.core');
+ const web_core = require('web.core');
+ const qweb = web_core.qweb;
+ const _t = web_core._t;
+ const dialog = require('scrummer.dialog');
+
+ var TaskView = BaseWidgets.AgileViewWidget.extend({
+ title: "Task View",
+ _name: "TaskView",
+ template: "scrummer.view.task",
+ menuItems: [
+ {
+ class: "assign-to-me",
+ icon: "mdi-account-check",
+ text: _t("Assign To Me"),
+ callback: '_onAssignToMeClick',
+ sequence: 1,
+ hidden() {
+ let taskWidget = this.taskWidget;
+ return taskWidget.data_service.getRecord(taskWidget.id)
+ .then(task => task.user_id && task.user_id[0] == data.session.uid)
+ }
+ },
+
+ {
+ class: "unassign",
+ icon: "mdi-account-minus",
+ text: _t("Unassign"),
+ callback: '_onUnassignClick',
+ sequence: 2,
+ hidden() {
+ let taskWidget = this.taskWidget;
+ return taskWidget.data_service.getRecord(taskWidget.id)
+ .then(task => !(task.user_id && task.user_id[0] == data.session.uid))
+ },
+ },
+ {
+ class: "edit-item",
+ icon: "mdi-pencil",
+ text: _t("Edit"),
+ callback: '_onEditItemClick',
+ sequence: 3,
+ },
+ {
+ class: "add-sub-item",
+ icon: "mdi-subdirectory-arrow-right",
+ text: _t("Add Sub Item"),
+ callback: '_onAddSubItemClick',
+ sequence: 4,
+ hidden() {
+ let taskWidget = this.taskWidget;
+ return taskWidget.data_service.getRecord(taskWidget.id)
+ .then(task => {
+ return DataServiceFactory.get("project.task.type2")
+ .getRecord(task.type_id[0])
+ .then(task_type => !task_type.allow_sub_tasks)
+ })
+ },
+ },
+ {
+ class: "add-link",
+ icon: "mdi-link",
+ text: _t("Add Link"),
+ callback: '_onAddLinkClick',
+ sequence: 5,
+ },
+ {
+ class: "work-log",
+ icon: "mdi-worker",
+ text: _t("Log Work"),
+ callback: '_onWorkLogClick',
+ sequence: 6,
+ },
+ {
+ class: "add-comment",
+ icon: "mdi-comment-account",
+ text: _t("Add Comment"),
+ callback: '_onAddCommentClick',
+ sequence: 7,
+ },
+ {
+ class: "delete",
+ icon: "mdi-delete",
+ text: _t("Delete task"),
+ callback: '_onDelete',
+ sequence: 8,
+ },
+ ],
+
+ init(parent, options) {
+ this._super(parent, options);
+ this.taskId = parseInt(hash_service.get("task"));
+ if (!this.taskId) {
+ throw new Error(_t("Task id must be set in Task view"));
+ }
+ this.renderTask();
+ hash_service.on("change:task", this, (hash_service, options) => this.loadTask(parseInt(hash_service.get("task"))));
+ },
+ renderTask(id, data) {
+ if (id) {
+ this.taskId = id;
+ }
+ if (this.taskWidget && typeof this.taskWidget.destroy === "function") {
+ //this.$el.empty();
+ this.taskWidget.destroy();
+ }
+ this.taskWidget = new TaskWidget(this, {
+ id: this.taskId,
+ template: "scrummer.view.task_widget",
+ data,
+ highlightNewWidget: this.scrollAndHighlight
+ });
+ this.taskWidget._is_rendered.then(this.afterTaskRender.bind(this));
+ },
+ loadTask(id, data) {
+ this.renderTask(id, data);
+ this.taskWidget.appendTo(this.$el);
+ },
+ afterTaskRender() {
+ let title = $(qweb.render("scrummer.view.task.title", {widget: this.taskWidget}));
+ title.find(".task-key").click(e => {
+ let taskId = $(e.currentTarget).attr("task-id");
+ hash_service.setHash("task", taskId);
+ hash_service.setHash("view", "task");
+ hash_service.setHash("page", "board");
+ });
+ this.setTitle(title, this.taskWidget.name);
+ this.taskWidget.$el.responsive();
+
+ if (this.workflowTaskWidget) {
+ this.workflowTaskWidget.destroy();
+ }
+
+ window.wtw = this.workflowTaskWidget = new WorkflowTransitionsWidget(this, {
+ taskWidget: this.taskWidget
+ });
+ this.updateMenuVisibility();
+ this.trigger_up("init_action_menu", {
+ items: [
+ {widget: this.workflowTaskWidget}
+ ]
+ });
+ },
+ renderElement() {
+ this._super();
+ this.taskWidget.appendTo(this.$el);
+ },
+ scrollAndHighlight(widget) {
+ widget._is_added_to_DOM.then(() => {
+ $("#middle-content").scrollToElement(widget.$el);
+ widget.$el.highlight();
+ })
+ },
+ start() {
+ core.bus.on("project.task:write", this, (id, vals, payload, record) => {
+ if (id === this.taskId) {
+ let editPromise = record._edit("check") ? record._edit() : $.when();
+ editPromise.then(() => {
+ this.loadTask(record.id, record);
+ });
+
+ if (payload) {
+ if (payload.user_id.id !== data.session.uid && payload.indirect === false) {
+ AgileToast.toastTask(payload.user_id, record, payload.method);
+ }
+ }
+ }
+ });
+ core.bus.on("project.task:unlink", this, (id, payload) => {
+ // TODO: Remove actions, floating buttons, generate overlay with message box telling that task has been deleted
+ });
+ return this._super();
+ },
+ addedToDOM() {
+ this.$('.tooltipped').tooltip();
+ this.$('.collapsible').collapsible();
+ this.$(".message-body").expander({
+ slicePoint: 140,
+ expandEffect: "fadeIn",
+ collapseEffect: "fadeOut"
+ });
+ },
+
+ _onAssignToMeClick() {
+ this.taskWidget._model.user_id = data.session.uid;
+ },
+ _onUnassignClick() {
+ this.taskWidget._model.user_id = false;
+ },
+ _onEditItemClick() {
+ let newItemModal = new AgileModals.NewItemModal(this, {
+ currentProjectId: this.taskWidget._model.project_id[0],
+ focus: "name",
+ edit: this.taskWidget._model,
+ });
+ newItemModal.appendTo($("body"));
+ },
+ _onAddSubItemClick() {
+ let newItemModal = new AgileModals.NewItemModal(this, {
+ currentProjectId: this.taskWidget._model.project_id[0],
+ parent_id: this.taskWidget._model.id,
+ });
+ newItemModal.appendTo($("body"));
+ },
+ _onAddLinkClick() {
+ let modal = new AgileModals.LinkItemModal(this, {
+ task: this.taskWidget._model,
+ });
+ modal.appendTo($("body"));
+ },
+ _onWorkLogClick() {
+ let modal = new AgileModals.WorkLogModal(this, {
+ task: this.taskWidget._model,
+ userId: data.session.uid,
+ });
+ modal.appendTo($("body"));
+ },
+ _onAddCommentClick() {
+ let modal = new AgileModals.CommentItemModal(this, {
+ task: this.taskWidget._model,
+ });
+ modal.appendTo($("body"));
+ },
+ _onDelete() {
+ dialog.confirm(_t("Delete task"), _t("Are you sure you want to delete this task?"), _t("yes")).done(() => {
+ this.taskWidget._model.unlink();
+ });
+ },
+ });
+
+ const WorkflowTransitionsWidget = BaseWidgets.AgileBaseWidget.extend({
+ id: "workflow-transition-widget",
+ init(parent, options) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this._require_obj("taskWidget");
+ this.workflowId = this.taskWidget._model.workflow_id[0];
+ this.taskStageId = this.taskWidget._model.stage_id[0];
+ this.size = this.size || 2;
+ },
+ willStart() {
+ return $.when(this._super(),
+ data.cache.get("project.workflow", {id: this.workflowId}).then(workflow => {
+ this.workflow = workflow;
+ }),
+ data.cache.get("current_user").then(user => {
+ this.current_user = user;
+ }));
+ },
+ renderElement() {
+ this._super();
+ this.setCurrentStage();
+ },
+ setSize(size) {
+ this.size = size;
+ this.setCurrentStage();
+ },
+ setCurrentStage(stageId) {
+ if (stageId) {
+ this.taskStageId = stageId;
+ }
+ this.outTransitions = this.getAllowedTransitions();
+ this.renderButtons();
+ },
+ getAllowedTransitions() {
+ return this.workflow.states[this.workflow.stageToState[this.taskStageId]].out_transitions
+ .map(transitionId => this.workflow.transitions[transitionId]);
+ },
+ renderButtons() {
+ this.$el.empty();
+ if (this.outTransitions.length > this.size + 1) { // This won't fit
+ for (let i = 0; i < this.size; i++) {
+ this.$el.append(this.generateButton(this.outTransitions[i]));
+ }
+ // TODO: Generate dropdown!
+ let overflow = this.outTransitions.slice(this.size);
+ this.$el.append(this.generateOverflow(overflow));
+ this.$('.dropdown-button').dropdown();
+ }
+ else { // This will fit
+ this.outTransitions.forEach(trId => {
+ this.$el.append(this.generateButton(trId));
+ })
+ }
+ },
+ generateButton(transition, overflow) {
+ let newState = this.workflow.states[transition.dst];
+ let button = overflow ? this.renderOverflowElement(transition.name) : this.renderButton(transition.name);
+ button.click(() => {
+ if (transition.user_confirmation) {
+ this.openStageChangeModal(newState.stage_id, newState.name, this.taskWidget, () => {
+ this.updateStage(newState);
+ });
+ return;
+ } else {
+
+ this.taskWidget._model.stage_id = newState.stage_id;
+ this.updateStage(newState);
+ }
+ });
+ return button;
+ },
+ generateOverflow(overflow) {
+ let wrapper = $("
");
+ wrapper.append($("... "));
+ let list = $("");
+ wrapper.append(list);
+ overflow.forEach(trId => {
+ let elem = $(" ");
+ elem.append(this.generateButton(trId, true));
+ list.append(elem);
+ });
+ return wrapper;
+ },
+ renderButton(text) {
+ return $("" + text + " ");
+ },
+ renderOverflowElement(text) {
+ return $("" + text + " ");
+ },
+ updateStage(state) {
+ this.setCurrentStage(state.stage_id);
+ },
+ openStageChangeModal(newStageId, newStateName, taskWidget, confirmedCallback) {
+ let userName = false;
+
+ if (taskWidget._model.user_id) {
+ if (taskWidget._model.user_id instanceof Array) {
+ userName = taskWidget._model.user_id[1];
+ } else {
+ userName = taskWidget._model.user_id.name;
+ }
+ }
+
+ let modal = new AgileModals.TaskStageConfirmationModal(this, {
+ taskId: taskWidget.id,
+ stageId: newStageId,
+ stageName: newStateName,
+ // userId: taskWidget._model.user_id ? taskWidget._model.user_id.id : false,
+ userName: userName,
+ afterHook: (comment, confirmation, form) => {
+
+ // confirmedCallback();
+ }
+ });
+ modal.appendTo($("body"));
+ },
+ addedToDOM() {
+ this._super();
+ this.$('.dropdown-button').dropdown();
+ },
+ });
+
+ return {
+ TaskView,
+ WorkflowTransitionsWidget
+ };
+
+});
diff --git a/scrummer/static/src/js/views/view_manager.js b/scrummer/static/src/js/views/view_manager.js
new file mode 100644
index 0000000..5998f27
--- /dev/null
+++ b/scrummer/static/src/js/views/view_manager.js
@@ -0,0 +1,173 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.view_manager', function (require) {
+ "use strict";
+
+ const hash_service = require('scrummer.hash_service');
+ const SubheaderWidget = require('scrummer.subheader').SubheaderWidget;
+ const AgileBaseWidget = require('scrummer.BaseWidgets').AgileBaseWidget;
+ const TaskView = require('scrummer.view.task').TaskView;
+ const web_core = require('web.core');
+ const _t = web_core._t;
+
+
+ // Key is used to define what string should be used in hash_service for ViewManager
+ const ViewManager = AgileBaseWidget.extend({
+ key: "view",
+ template: "scrummer.view_manager",
+ custom_events: {
+ set_title: '_onSetTitle',
+ init_action_menu: function (evt) {
+ this.initActionMenu(evt.data.items);
+ },
+ rerender_view: function (evt) {
+ this.rerender_view();
+ }
+ },
+ init(parent, options = {}) {
+ this._super(parent, options);
+ Object.assign(this, options);
+ this._require_prop("key");
+ this._require_prop("defaultView");
+
+ this.build_view_registry();
+ this.instantiate_views();
+ this.register_events();
+ },
+
+ instantiate_views() {
+ //Subscribe to view change event on hash service
+ hash_service.on("change:" + this.key, this, (hash_service, options) => options.newValue && this.set_view(options.newValue));
+ // Setting view will render it again, so when board is changed, load same view for that board.
+ hash_service.on("change:board", this, (hash_service, options) => options.newValue && this.set_view(hash_service.get("view")));
+ },
+ register_events() {
+ this.on("loading:start", this, () => {
+ this.$(".progress").addClass("active");
+ this.$(".view-content").removeClass("loaded");
+ });
+ this.on("loading:stop", this, () => {
+ this.$(".progress").removeClass("active");
+ this.$(".view-content").addClass("loaded");
+ });
+ },
+ renderElement() {
+ this._super();
+ // set default view if none is set
+ if (!hash_service.get(this.key)) {
+ hash_service.setHash(this.key, this.defaultView, false);
+ } else {
+ this.set_view(hash_service.get(this.key));
+ }
+ this.subheader = new SubheaderWidget(this);
+ this.subheader.appendTo(this.$("#subheader-wrapper"));
+ },
+ set_view(view_name) {
+ if (this.view_registry.get(view_name)) {
+ this.current_view = view_name;
+ let ViewWidget = this.view_registry.get(view_name);
+
+ // Checking if ViewWidget is AgileBaseWidget subclass,
+ // I've been able to identify that it is subclass of root OdooClass
+ // TODO: Test if ViewWidget is extension of AgileBaseWidget
+ if (!ViewWidget.toString().includes("OdooClass")) {
+ throw new Error("Widget does not exist");
+ }
+
+ // if current widget property is set, and has destroy method, call it to destroy widget.
+ if (this.widget && typeof this.widget.destroy === "function") {
+ var old = this.widget;
+ this.removeActionMenu();
+ // TODO: Remove this hack
+ if (typeof this.widget.removeNavSearch === "function") {
+ this.widget.removeNavSearch();
+ }
+ }
+
+ this.trigger("loading:start");
+ // Instantiate ViewWidget with this as parent and add it to DOM.
+ this.widget = new ViewWidget(this);
+ this.widget.appendTo(this.$("widget.view-content").empty());
+ this.widget._is_added_to_DOM.then(() => {
+ if (old) {
+ old.destroy();
+ }
+ this.trigger("loading:stop");
+ });
+
+
+ console.log(this.message = "View " + view_name + " loaded...");
+ } else {
+ hash_service.setHash(this.key, this.defaultView, false);
+ console.error(_t("View ") + view_name + _t(" does not exist!"));
+ }
+ },
+ rerender_view() {
+ this.set_view(this.current_view);
+ },
+ // Overwrite this method and call this._super() in order to add additional views to registry
+ // view_registry is map with view name as key and widget class as value
+ // All view widgets should extend AgileViewWidget, and set appropriate title property
+ build_view_registry() {
+ this.view_registry = new Map();
+ this.view_registry.set("task", TaskView);
+ },
+ /**
+ *
+ * @callback actionCallback
+ *
+ * @param {Object[]} menuItems Array of menu items
+ * @param {string} menuItems[].icon - Class of Material Design Icon (without dot)
+ * @param {string} menuItems[].title - Text to be displayed in button
+ * @param {actionCallback} menuItems[].action - Callback to run when button is clicked.
+ */
+ initActionMenu(menuItems) {
+ if (jQuery.isFunction(menuItems)) {
+ let callback = menuItems;
+ var el = $("
");
+ el.appendTo(this.$(".actions-menu"));
+
+ let actionMenuPromise = callback(el);
+ if (jQuery.isFunction(actionMenuPromise.promise)) {
+ actionMenuPromise.always((widget) => {
+ if (widget == this.widget) {
+ this.$(".actions-menu").empty();
+ }
+ })
+ } else {
+ throw new Error("openRightSide callback should return promise");
+ }
+ return;
+ }
+ if (!Array.isArray(menuItems)) {
+ throw new Error("menuItems must be an array");
+ }
+ for (let item of menuItems) {
+ if (item.widget && item.widget.__AGILE_BASE_WIDGET) {
+ item.widget.appendTo(this.$(".actions-menu"));
+ } else {
+ let node = $(' ');
+ let html = "";
+ if (item.icon) {
+ html += " ";
+ } else {
+ html += item.title;
+ }
+ node[0].innerHTML = html;
+ node.click(item.action);
+ node.appendTo(this.$(".actions-menu"));
+ }
+ }
+ },
+ removeActionMenu() {
+ this.$(".actions-menu").empty();
+ },
+ _onSetTitle(evt) {
+ this._is_rendered.then(()=>{
+ this.subheader.setTitle(evt.data.title);
+ });
+ }
+ });
+ return ViewManager;
+});
diff --git a/scrummer/static/src/js/widgets/abstract_model_list.js b/scrummer/static/src/js/widgets/abstract_model_list.js
new file mode 100644
index 0000000..38437a9
--- /dev/null
+++ b/scrummer/static/src/js/widgets/abstract_model_list.js
@@ -0,0 +1,403 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.abstract_model_list', function (require) {
+ "use strict";
+ const data = require('scrummer.data');
+ const AgileContainerWidget = require('scrummer.BaseWidgets').AgileContainerWidget;
+ const AgileBaseWidget = require('scrummer.BaseWidgets').AgileBaseWidget;
+ const Sortable = require('sortable');
+ const dialog = require('scrummer.dialog');
+ const crash_manager = require('web.crash_manager');
+ const core = require('web.core');
+ const _t = core._t;
+
+ // TODO: This widget took a lot of hits in favour of rest of code and became very bad.
+ // TODO: We decided to write it from scratch. Please be warned that its API might change in near future.
+ const ModelList = AgileContainerWidget.extend({
+ _name: "ModelList",
+ emptyPlaceholder: undefined,
+ className: "model-list",
+ useDataService: false,
+ custom_events: {
+ /**
+ This event will be triggered after list item has changed parent list.
+ change parent will occur on destination list.
+ */
+ change_parent: '_onChangeParent',
+ change_order: '_onChangeOrder',
+ remove_item: '_onRemoveItem'
+ },
+ init(parent, options = {}) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this._require_prop("model");
+ this._require_prop("ModelItem");
+ this.getDatasetDefaults(options);
+ },
+ getDatasetDefaults(options) {
+ this.fields = options.fields || this.ModelItem.default_fields || ["name", "agile_order"];
+ this.domain = options.domain || [];
+ this.context = options.context || [];
+ this.offset = options.offset || 0;
+ this.limit = options.limit || false;
+ this.queryString = options.queryString || "";
+ this.dataset = data.getDataSet(this.model);
+
+ if (this.useDataService) {
+ this.data_service = DataServiceFactory.get(this.model);
+ this.hasCustomFilter = options.domain || options.context || options.offset || options.limit || options.queryString ? true : false;
+ }
+
+ },
+ loadItems() {
+ let def = $.Deferred();
+ // If options.data is set, modelList will be created with that data, and it will not fetch data from server.
+ if (Array.isArray(this.data)) {
+ def.resolve();
+ } else if (this.useDataService) {
+ if (this.hasCustomFilter) {
+ // TODO: Make this generic. We should be also able to pass contextand offset
+ // TODO: Cache parameters in order to avoid calling id_search every time if criteria didn't change
+ return this.data_service.dataset.id_search(this.queryString, this.domain, 'ilike', this.limit).then(ids => {
+ return this.data_service.getRecords(ids).then(records => {
+ this.data = records;
+ def.resolve();
+ });
+ })
+ } else {
+ return this.data_service.getAllRecords().then(records => {
+ this.data = records;
+ def.resolve();
+ });
+ }
+ } else {
+ $.when(this.fields, this.domain, this.offset, this.limit, this.context).then((fields, domain, offset, limit, context) => {
+ this.dataset.read_slice(fields, {
+ domain,
+ offset,
+ limit,
+ context
+ })
+ .then(r => {
+ this.data = r;
+ def.resolve(r);
+ })
+ .fail(e => def.reject(e));
+ });
+ }
+ return def;
+ },
+ willStart() {
+ return $.when(this._super(), this.loadItems());
+ },
+ addItem(item, attributes) {
+ if (typeof item[this.ModelItem.sort_by] === "function") {
+ throw new Error("ModelItem doesn't have set sort_by property.")
+ }
+ if (item._class === "ModelListItem") {
+ if (item.id) {
+ this.list.set(item.id, item);
+ }
+ if (!this.__parentedChildren.find(e => e.id == item.id)) {
+ item.setParent(this);
+ this._appendInOrder(item, item[this.ModelItem.sort_by]);
+ }
+ this.trigger_up("add_item", {
+ widget: item,
+ itemData: item.record
+ });
+
+ return item;
+ }
+ let widgetOptions = {
+ id: item.id,
+ record: item,
+ attributes: {"data-id": item.id},
+ dataset: this.dataset,
+ order_field: this.ModelItem.sort_by,
+ };
+ Object.assign(widgetOptions, this.itemExtensions);
+ attributes && Object.assign(widgetOptions.attributes, attributes);
+ let modelItem = new this.ModelItem(this, widgetOptions);
+ this.list.set(item.id, modelItem);
+ this._appendInOrder(modelItem, item[this.ModelItem.sort_by]);
+ this.$el.removeClass("empty");
+ this.trigger_up("add_item", {widget: modelItem, itemData: item});
+ return modelItem;
+ },
+ removeItem(id, destroy = true, silently = false) {
+ let itemWidget = this.list.get(id);
+ if (!itemWidget) {
+ return false;
+ }
+ itemWidget.setParent(undefined);
+ let itemData = itemWidget.record;
+ destroy ? itemWidget.destroy() : itemWidget.$el.detach();
+ this.list.delete(id);
+ if (!silently) {
+ this.trigger_up("remove_item", {itemData});
+ }
+ if (!this.list.size) {
+ this.$el.addClass("empty");
+ }
+ return true;
+ },
+ moveToTop(evt) {
+ console.log("moving to top", evt);
+ let widget_id = $(evt.item).data("id");
+ let itemWidget = this.list.get(widget_id);
+ // This can happen if task gets deleted/moved to other teams sprint
+ if (!itemWidget) {
+ return;
+ }
+ if (evt.oldIndex !== 0) {
+ itemWidget.set_order(this.getNewOrder(evt.oldIndex, 0, this.id, true), true);
+ }
+ },
+ moveToBottom(evt) {
+ console.log("moving to bottom", evt);
+ let widget_id = $(evt.item).data("id");
+ let itemWidget = this.list.get(widget_id);
+ // This can happen if task gets deleted/moved to other teams sprint
+ if (!itemWidget) {
+ return;
+ }
+ if (evt.oldIndex !== this.__parentedChildren.length - 1) {
+ itemWidget.set_order(this.getNewOrder(evt.oldIndex, this.__parentedChildren.length - 1, this.id, true), true);
+ }
+ },
+ onDragStart(/**Event*/ evt) {
+ try {
+ this.trigger_up("drag_start");
+ } catch (e) {
+ this._handleError(e);
+ }
+ },
+ onDragEnd(/**Event*/ evt) {
+ try {
+ this.trigger_up("drag_end", {sortableEvent: evt});
+ if (evt.defaultPrevented) {
+ return;
+ }
+ let widget_id = $(evt.item).data("id");
+ let itemWidget = this.list.get(widget_id);
+ // This can happen if task gets deleted/moved to other teams sprint
+ if (!itemWidget) {
+ return;
+ }
+ let from_list_id = $(evt.from).data("id"); // List from which task is dragged
+ let to_list_id = $(evt.to).data("id"); // Destination list on task dragging
+ if (from_list_id === to_list_id) {
+ // if list is same, and order is changed, just update order
+ if (evt.oldIndex !== evt.newIndex) {
+ itemWidget.set_order(this.getNewOrder(evt.oldIndex, evt.newIndex, to_list_id, true), true);
+ }
+ } else {
+ // If list is changed update both list and order.
+ // Order should be calculated by surrounding items on target list based by ModelItem.sort_by
+ let newListWidget = this._getNewListWidget(to_list_id);
+
+ itemWidget.set_list(newListWidget, this.getNewOrder(evt.oldIndex, evt.newIndex, to_list_id));
+ }
+ } catch (e) {
+ this._handleError(e);
+ }
+ },
+ renderElement() {
+ this._super();
+ if (this.emptyPlaceholder) {
+ this.emptyPlaceholder.addClass("empty-placeholder");
+ this.$el.append(this.emptyPlaceholder);
+ this.$el.addClass("empty");
+ }
+ this.list = new Map();
+ for (let item of this.data) {
+ this.addItem(item);
+ }
+
+ // sortable setup
+ if ("sortable" in this && this.sortable) {
+ this._is_added_to_DOM.then(() => {
+ // Convert jquery object to HTMLElement and create sortable
+ this.$el.attr("data-sortable", this.sortable.group);
+ Sortable.create(this.$el.get(0), {
+ group: this.sortable.group,
+ onStart: this.onDragStart.bind(this),
+ onEnd: this.onDragEnd.bind(this)
+ });
+ });
+
+ }
+ },
+ _setNewItemList(itemWidget, newListWidget) {
+ // TODO: Prevent destroying widget! PS look diff in order to catch up with work
+ this.removeItem(itemWidget.id, false);
+ newListWidget.addItem(itemWidget);
+ },
+ getNewOrder(oldIndex, newIndex, new_list_id, sameList = false) {
+ // first parent is list, and grandparent is backlog view;
+ let itemsInNewList = this._getNewListWidget(new_list_id).__parentedChildren;
+
+ // if list is empty, return one
+ if (!itemsInNewList.length) {
+ return 1;
+ }
+ // if moved to first element in list
+ if (newIndex == 0) {
+ let currentFirstOrder = itemsInNewList[0][this.ModelItem.sort_by];
+ return currentFirstOrder > 0 ? currentFirstOrder / 2 : currentFirstOrder - 1;
+ }
+ //if moved to the end of the same list return agile_order of last element incremented by one.
+ if (sameList && newIndex == itemsInNewList.length - 1) {
+ return itemsInNewList[newIndex][this.ModelItem.sort_by] + 1;
+ }
+ // if moved to the end of new list return agile_order of last element incremented by one.
+ if (newIndex == itemsInNewList.length) {
+ return itemsInNewList[newIndex - 1][this.ModelItem.sort_by] + 1;
+ }
+ // if item is sorted within the same list, and moved toward the beginning of list, look one element farther
+ if (sameList && oldIndex < newIndex) {
+ return (itemsInNewList[newIndex][this.ModelItem.sort_by] + itemsInNewList[newIndex + 1][this.ModelItem.sort_by]) / 2;
+ }
+ return (itemsInNewList[newIndex - 1][this.ModelItem.sort_by] + itemsInNewList[newIndex][this.ModelItem.sort_by]) / 2;
+
+ },
+ _getNewListWidget() {
+ throw new Error("You must implement this method");
+ },
+ // Sorts widgets by agile_order on parent widget
+ _sortWidgets() {
+ if (!this.ModelItem.sort_by && !this.ModelItem.reverse) {
+ return;
+ }
+ let widgets = this.__parentedChildren.sort((a, b) => {
+ // If compare value is of type string compare strings, else compare as integer
+ return (typeof a[this.ModelItem.sort_by] === "string") ?
+ a[this.ModelItem.sort_by].localeCompare(b[this.ModelItem.sort_by]) :
+ a[this.ModelItem.sort_by] - b[this.ModelItem.sort_by]
+ });
+ this.__parentedChildren = this.ModelItem.reverse ? widgets.reverse() : widgets;
+ },
+ // Appends widget acording to agile order. If agile_order is set, widgets will be sorted again
+ _appendInOrder(itemWidget, order) {
+ if (order !== undefined) {
+ itemWidget[this.ModelItem.sort_by] = order;
+ this._sortWidgets();
+ }
+ // if widget is already in dom, then new insertion is not
+ let existingDOMnode = this.$("*[data-id='" + itemWidget.id + "']");
+ if (existingDOMnode.size()) {
+ existingDOMnode.remove();
+ }
+ let index = this.__parentedChildren.findIndex(e => e.id == itemWidget.id);
+ // if first prepend to parent widget
+ if (index == 0) {
+ itemWidget.prependTo(this.$el);
+ }
+ // if last append to parent widget
+ else if (index == (this.__parentedChildren.length - 1)) {
+ itemWidget.appendTo(this.$el)
+ }
+ // if somewhere in middle insert after prior widget
+ else {
+ let priorWidget = this.__parentedChildren[index - 1];
+ // Make sure that both prior widget and list widget is rendered before inserting after prior widget,
+ // It wouldn't work without this if priorWidget's willStart() take some time to resolve.
+ $.when(priorWidget._is_rendered, this._is_rendered).then(() => {
+ itemWidget.insertAfter(priorWidget.$el);
+ });
+
+ }
+ },
+ _onChangeParent(evt) {
+ evt.stopped = true;
+ this.list.set(evt.data.id, evt.data.item);
+ this._sortWidgets();
+ },
+ _onChangeOrder(evt) {
+ evt.stopped = true;
+ if (evt.data.itemWidget.$el) {
+ evt.data.itemWidget.$el.remove();
+ }
+ this._appendInOrder(evt.data.itemWidget, evt.data.order);
+ },
+ _onRemoveItem(evt) {
+ this.removeItem(evt.data.id);
+ // Since item is getting destroyed, and it is better to set evt.target to this list
+ evt.target = this;
+ },
+ _handleError(error) {
+ let traceback = error ? error.stack : '';
+ crash_manager.show_error({
+ type: _t("Odoo Client Error"),
+ message: error.message,
+ data: {debug: _t('Traceback:') + "\n" + traceback},
+ });
+ }
+ });
+
+ // <<<<==========================++++++ LIST ITEMS +++++==============================>>>>
+
+ const AbstractModelListItem = AgileBaseWidget.extend({
+ _name: "AbstractModelListItem",
+ // _class is used to determine type of object in some methods like addItem of ModelList
+ _class: "ModelListItem",
+ init(parent, options) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this._require_prop("order_field", "Make sure that ModelListItem implementation sets order_field");
+ this.removeConfirmation && this._require_obj("removeConfirmation", ['title', 'message']);
+ },
+ changeParent(parent) {
+ this._super(parent);
+ this.trigger_up("change_parent", {id: this.id, item: this});
+ },
+ /**
+ * This method is used to set list item id asynchronously, e.g. after rendering list item prior to record creation
+ * @param id
+ */
+ setId(id) {
+ this.id = id;
+ this.$el.attr("data-id", id);
+ this.trigger_up("change_parent", {id: this.id, item: this});
+ },
+ // Use this in order to change ListItems order in ModelList widget
+ set_order(order, write = false) {
+ this.trigger_up("change_order", {itemWidget: this, order});
+ if (write) {
+ this.dataset.write(this.id, {[this.order_field]: order})
+ .done(r => console.info(`Agile order saved: ${this.id}, ${order}`))
+ .fail(r => console.error("Error while saving agile order: ", r));
+ }
+ },
+ set_list(listWidget, order) {
+ this.changeParent(listWidget);
+ this.set_order(order);
+ },
+
+ remove() {
+ if (this.removeConfirmation) {
+ dialog.confirm(this.removeConfirmation.title, this.removeConfirmation.message, this.removeConfirmation.okText, this.removeConfirmation.cancelText).done(() => {
+ this._unlink();
+ });
+ }
+ else {
+ this._unlink();
+ }
+ },
+ _unlink() {
+ this.dataset.unlink([this.id]).then(() => {
+ this.trigger_up("remove_item", {
+ id: this.id,
+ itemData: this.record
+ });
+ });
+ }
+ });
+
+ return {
+ ModelList,
+ AbstractModelListItem,
+ };
+});
diff --git a/scrummer/static/src/js/widgets/activity_stream.js b/scrummer/static/src/js/widgets/activity_stream.js
new file mode 100644
index 0000000..9a76069
--- /dev/null
+++ b/scrummer/static/src/js/widgets/activity_stream.js
@@ -0,0 +1,182 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.activity_stream', function (require) {
+ "use strict";
+
+ var data = require('scrummer.data');
+ var AgileBaseWidget = require('scrummer.BaseWidgets').AgileBaseWidget;
+ var core = require("web.core");
+
+ var _t = core._t;
+ var qweb = core.qweb;
+
+ var ActivityStream = AgileBaseWidget.extend({
+ _name: "ActivityStream",
+ template: "scrummer.activity.stream",
+ limit: 8,
+ loadMoreStep: 8,
+ emptyPlaceholder: $("" + _t("There are no activities.") + "
"),
+ init(parent, options) {
+ this._super(parent, options);
+ Object.assign(this, options);
+ this.prepareData();
+ window.as = this;
+ },
+ prepareData() {
+ this.activitiesDeferred = $.Deferred();
+ data.getMessageSubtypes("project.task").then(subtypes => {
+ this.subtypes = subtypes;
+ console.log("Subtypes", subtypes);
+ this.subtype_ids = subtypes.map(e => e.id);
+
+ let team_changing = (this.team_changing && this.team_changing.state() === "pending") ? this.team_changing : $.Deferred().resolve();
+ team_changing.then(() => {
+ data.session.rpc("/scrummer/activity-stream", {subtype_ids: this.subtype_ids, limit: this.limit})
+ .then(messages => {
+ this.messagesCount = messages.length;
+ window.msgs = messages;
+ this.messages = [];
+ this.groupWeekDays = new Map();
+ if (!this.lastMessage) {
+ this.lastMessage = {};
+ }
+
+ this.prepareMessages(messages);
+ this.activitiesDeferred.resolve();
+ });
+ });
+ });
+ return this.activitiesDeferred;
+ },
+ prepareMessages(messages) {
+ this.messages.push(messages);
+ messages.forEach(m => {
+ let weekday = this.formatGroupWeekDay(m.date);
+ this.groupWeekDays.has(weekday) ?
+ this.isSameAuthor(m, this.lastMessage) ? this.lastGroup.push(m) : this.groupWeekDays.get(weekday).push(this.lastGroup = [m]) :
+ this.groupWeekDays.set(weekday, [this.lastGroup = [m]]);
+ this.lastMessage = m;
+ });
+ },
+ loadMore() {
+ this.$(".list-preloader").show();
+ this.limit += this.loadMoreStep;
+ this.prepareData();
+ this.activitiesDeferred.then(() => {
+ this.renderElement();
+ this.start();
+ });
+ },
+ start() {
+ this.$(".message-body").expander({
+ slicePoint: 140,
+ expandEffect: "fadeIn",
+ collapseEffect: "fadeOut"
+ });
+
+ this.$(".load-more-btn").click(this.loadMore.bind(this));
+ },
+
+ renderElement() {
+ this._super();
+ this.$(".load-more-btn").hide();
+ // Adding backlog task list
+ this.activitiesDeferred.then(() => {
+ this.$(".list-preloader").hide();
+ if (this.messagesCount > 0 && this.limit <= this.messagesCount) {
+ this.$(".load-more-btn").show();
+ }
+ for (let [weekdayGroup, activityGroups] of this.groupWeekDays) {
+ // Append week-day (Yesterday, Monday, Sunday, etc.)
+ this.$(".activity").append($(`${weekdayGroup}
`));
+ for (let activityGroup of activityGroups) {
+ // Render and append activity Group (Activities by he same author will be grouped)
+ let author = this.getAuthor(activityGroup[0]);
+ let groupNode = $(qweb.render("scrummer.activity.group", {author}));
+ this.$(".activity").append(groupNode);
+ let activityGroupContent = groupNode.find(".activity-group-content");
+ console.log("Group:", this.getAuthor(activityGroup[0]));
+ for (let message of activityGroup) {
+ // Render activities in group
+ let messageNode = $(qweb.render("scrummer.activity.item", {widget: this, message}));
+ messageNode.find(".activity-object").click(e => {
+ e.preventDefault();
+ e.stopPropagation();
+ var objectModel = $(e.currentTarget).attr("object-model");
+ var objectId = $(e.currentTarget).attr("object-id");
+ switch (objectModel) {
+ case "project.task":
+ hash_service.setHash("task", objectId, false);
+ hash_service.setHash("view", "task", false);
+ hash_service.setHash("page", "board");
+ break;
+ }
+ });
+ activityGroupContent.append(messageNode);
+ // console.log("Message:", message);
+ }
+ }
+ }
+ if (this.groupWeekDays.size) {
+ this.$el.removeClass("empty");
+ }
+ console.log(this.groupWeekDays);
+ });
+ if (this.emptyPlaceholder) {
+ this.emptyPlaceholder.addClass("empty-placeholder");
+ this.$el.append(this.emptyPlaceholder);
+ this.$el.addClass("empty");
+ }
+ },
+ isSameAuthor(m1, m2) {
+ if (m1.author_id[0] == 0 && m2.author_id[0] == 0)
+ return m1.author_id[1] === m2.author_id[1];
+ return m1.author_id[0] == m2.author_id[0];
+ },
+ getAuthor(message) {
+ return {
+ name: message.author_id[1],
+ image: data.getImage("res.partner", message.author_id[0])
+ }
+ },
+ timeFormat: {
+ sameDay: '[Today at] HH:MM',
+ lastDay: '[Yesterday at] HH:MM',
+ lastWeek: 'dddd [at] HH:MM',
+ sameElse: 'DD/MM/YYYY [at] HH:MM'
+ },
+ formatTime(time) {
+ return moment(time).calendar(null, this.timeFormat);
+ },
+ groupWeekDayFormat: {
+ sameDay: '[Today]',
+ lastDay: '[Yesterday]',
+ lastWeek: 'dddd',
+ sameElse: '[Older]'
+ },
+ formatGroupWeekDay(time) {
+ return moment(time).calendar(null, this.groupWeekDayFormat);
+ },
+ getActivityType(message) {
+
+ //TODO: Rewrite and add support for multilanguage.
+ let isCommit = message.subtype_id && message.subtype_id[1] === "Code committed";
+ let isComment = message.message_type === "comment";
+ return {
+ subtype: message.subtype_id && {id: message.subtype_id[0], name: message.subtype_id[1]},
+ isCommit,
+ message: isCommit ? "Code pushed" :
+ isComment ? "commented" :
+ message.subtype_id ? message.subtype_id[1] : "commented"
+ }
+ },
+ readSubscriptions() {
+
+ }
+ });
+
+ return {
+ ActivityStream
+ };
+});
diff --git a/scrummer/static/src/js/widgets/attachments.js b/scrummer/static/src/js/widgets/attachments.js
new file mode 100644
index 0000000..5b69c07
--- /dev/null
+++ b/scrummer/static/src/js/widgets/attachments.js
@@ -0,0 +1,267 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.attachments', require => {
+ "use strict";
+ var BaseWidgets = require('scrummer.BaseWidgets');
+ var AbstractModelList = require('scrummer.abstract_model_list');
+ var dialog = require('scrummer.dialog');
+ var _t = require('web.core')._t;
+
+ const AttachmentsWidget = BaseWidgets.AgileBaseWidget.extend({
+ template: "scrummer.attachments",
+ multiple: true,
+ convertTimeout: 3000,
+ custom_events: {
+ 'remove_attachment': function (evt) {
+ this.attachmentsList.removeItem(evt.data.id);
+ }
+ },
+ init(parent, options) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this._require_prop("res_id");
+ this._require_prop("res_model");
+ this._require_prop("attachments");
+ // All those attachments are already stored, so set downloadable to true
+ this.attachments.forEach(e=>e.downloadable = true);
+ },
+ renderElement() {
+ this._super();
+ this.$(".attachments-input").attr("multiple", this.multiple);
+ this.attachmentsList = new AbstractModelList.ModelList(this, {
+ model: "ir.attachment",
+ data: this.attachments,
+ ModelItem: AttachmentsItem,
+ });
+ this.attachmentsList.appendTo(this.$el);
+ },
+ start() {
+ this.initDragAndDrop();
+ this.$(".upload-files").click(e => this.$(".attachments-input").trigger("click"));
+ this.$(".attachments-input").change(e => this.uploadFiles(e.target.files));
+ return this._super();
+ },
+ initDragAndDrop() {
+ let dragCounter = 0;
+ let removeTimeout;
+ let captureDragover = false;
+ let finalizeWave = () => {
+ Waves.calm(this.$el[0]);
+ removeTimeout = setTimeout(() => this.$el.removeClass('waves-effect'), 700);
+ this.$el.removeClass('is-dragover');
+ };
+ this.$el.on('drag dragstart dragend dragover dragenter dragleave drop', e => {
+ e.preventDefault();
+ e.stopPropagation();
+ })
+ .on('dragover dragenter dragstart', e => {
+ this.$el.addClass('is-dragover');
+ if ((e.type === "dragenter" || e.type === "dragstart") && dragCounter++ == 0) {
+ captureDragover = true;
+ }
+ if (e.type === "dragover" && captureDragover) {
+ captureDragover = false;
+ clearTimeout(removeTimeout);
+ this.$el.addClass('waves-effect');
+ Waves.ripple(this.$el[0], {
+ wait: 999999,
+ position: { // This position relative to HTML element.
+ x: e.originalEvent.layerX, //px
+ y: e.originalEvent.layerY //px
+ }
+ });
+ }
+ })
+ .on('dragleave dragend drop', e => {
+ if (e.type === "dragleave" && --dragCounter == 0) {
+ finalizeWave();
+ }
+ })
+ .on('drop', e => {
+ finalizeWave();
+ let droppedFiles = e.originalEvent.dataTransfer.files;
+ this.uploadFiles(droppedFiles);
+ dragCounter = 0;
+ });
+ },
+ uploadFiles(fileList) {
+ if (fileList.length > 0) {
+ for (let file of fileList) {
+ // let newAttachmentItem = new AttachmentsItem(this, {
+ // // attributes: {"data-id": item.id},
+ // file: file,
+ // dataset: data.getDataSet("ir.attachment"),
+ // order_field: AttachmentsItem.sort_by
+ // });
+ this.attachmentsList.addItem({
+ // attributes: {"data-id": item.id},
+ file: file,
+ res_id: this.res_id,
+ res_model: this.res_model,
+ convertTimeout: this.convertTimeout,
+ dataset: data.getDataSet("ir.attachment"),
+ order_field: AttachmentsItem.sort_by
+ });
+ }
+ }
+ },
+ getIds(){
+ return [...this.attachmentsList.list.keys()].filter(x=>x);
+ }
+ });
+ /**
+ * This widgets looks and reacts differently according to its state.
+ * It can be downloadable, which means that attachment is already stored, and download can be initiated.
+ * When widget has downloadable set to true, it enables user to delete the attachment.
+ * When user selects a file, or drag&drop file to AttachmentsWidget, an non downloadable AttachmentsItem widget
+ * gets created and rendered. Until file gets uploaded and prepared for download, this widget provides user
+ * with visual feedback that file upload is in progress, and gives user an ability to abort file upload.
+ */
+ const AttachmentsItem = AbstractModelList.AbstractModelListItem.extend({
+ template: "scrummer.attachments.item",
+ max_upload_size: 25 * 1024 * 1024, // 25Mo
+ init(parent, options) {
+ this._super(parent, options);
+ this.record = this.record || {};
+ if (!this.record.downloadable) {
+ this._require_obj("record", ['file', 'res_model', 'res_id', 'convertTimeout']);
+ this.record.name = this.record.file.name;
+ }
+ },
+ willStart() {
+ let superPromise = this._super();
+ if(this.record.downloadable){
+ return $.when(superPromise, this.prepareUserImage());
+ }
+ return superPromise;
+ },
+ prepareUserImage() {
+ return data.cache.get("get_user", {id: this.record.create_uid[0]}).then(user => {
+ this.user_image_url = data.getImage("res.users", user.id, user.write_date);
+ });
+ },
+ renderElement() {
+ this._super();
+ if (this.record.downloadable) {
+ this.$el.addClass("downloadable");
+ this.$el.addClass("complete");
+ }
+ },
+ start() {
+ if (this.record.downloadable) {
+ this.$(".delete").click(this.remove.bind(this));
+ } else { // This is a case of uploading/creating new attachment
+ this.loadFile(this.record.file);
+ this.$(".abort").click(this.destroy.bind(this));
+ this.$(".retry").click(() => {
+ this.$el.removeClass("with-error");
+ this.loadFile(this.record.file)
+ });
+
+ }
+ this.$(".tooltipped").tooltip();
+ return this._super();
+ },
+ loadFile(file) {
+ console.log(file.name);
+ if (file.size > this.max_upload_size) {
+ this.$el.addClass("with-error");
+ this.setError(_t("File exceed the maximum file size of ") + this.max_upload_size / 1024 / 1024 + "MB");
+ this.setProgress(0);
+ this.$(".retry").hide();
+ return false;
+ }
+ this.setStatus(_t("Preparing file..."));
+ this.setProgress(false);
+ let fileReader = new FileReader();
+ let self = this;
+ fileReader.onloadend = upload => {
+ let data = upload.target.result;
+ data = data.split(',')[1];
+ self.uploadFile(data);
+ };
+ fileReader.readAsDataURL(file);
+ },
+ setError(error) {
+ this.$(".error").text(error);
+ },
+ setStatus(status) {
+ this.$(".status").text(status);
+ },
+ setProgress(progress) {
+ if (progress === false) { //show indeterminate progress bar
+ this.$(".progress").empty().append($('
'));
+ } else if (Number(progress) === progress && progress >= 0 && progress <= 1) {
+ this.$(".progress").empty().append($('
'));
+ } else {
+ throw new Error("Illegal argument");
+ }
+ },
+ uploadFile(file_base64) {
+ if (this.record.file.size === false) {
+ this.setError(_t("Browser couldn't load file"));
+ } else {
+ this.setStatus(_t("Uploading file..."));
+ data.getDataSet("ir.attachment").create({
+ res_id: this.record.res_id,
+ res_model: this.record.res_model,
+ name: this.record.file.name,
+ datas: file_base64,
+ datas_fname: this.record.file.name
+ }).then(this.onFileUploaded.bind(this), this.onFileUploadError.bind(this));
+ }
+ },
+ onFileUploaded(id) {
+ this.setId(id);
+ this.setProgress(1);
+ this.$(".delete").click(this.remove.bind(this));
+ this.$el.addClass("complete");
+ this.attachmentLoaded = data.getDataSet("ir.attachment").read_ids([id], ["name", "datas_fname", "local_url", "create_uid", "create_date",]);
+ setTimeout(this.convertToLink.bind(this), this.record.convertTimeout);
+ },
+ onFileUploadError() {
+ this.setProgress(0);
+ this.$el.addClass("with-error");
+ this.setError(_t("Error while uploading file"));
+ },
+ convertToLink() {
+ this.attachmentLoaded.then(result => {
+ let attachment = result[0];
+ Object.assign(this.record, attachment);
+ this.record.downloadable = true;
+ this.$el.addClass("downloadable");
+ this.$(".name").html(`${this.record.name} `);
+ this.prepareUserImage().then(() => {
+ let image = $(` `);
+ image.insertBefore(this.$(".meta"));
+ image.tooltip();
+ });
+
+ });
+ },
+ remove() {
+ dialog.confirm(_t("Delete attachment"), _t("Are you sure you want to delete this attachment?"), _t("yes")).done(() => {
+ this.dataset.unlink([this.record.id]).then(() => {
+ this.trigger_up("remove_attachment", {id: this.record.id});
+ });
+ });
+ },
+ destroy() {
+ if (!this.__destroying) {
+ this.__destroying = true;
+ this.$el.addClass("fade-out");
+ let self = this;
+ this.$el.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', e => self.destroy());
+ } else {
+ this._super();
+ }
+ }
+ });
+ AttachmentsItem.sort_by = "create_date";
+ return {
+ AttachmentsWidget,
+ AttachmentsItem
+ }
+});
diff --git a/scrummer/static/src/js/widgets/base_widget.js b/scrummer/static/src/js/widgets/base_widget.js
new file mode 100644
index 0000000..36a9369
--- /dev/null
+++ b/scrummer/static/src/js/widgets/base_widget.js
@@ -0,0 +1,414 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.BaseWidgets', function (require) {
+ "use strict";
+ const Widget = require('web.Widget');
+ const mixins = require('scrummer.mixins');
+ var core = require('web.core');
+ var _t = core._t;
+
+ var AgileBaseWidget = Widget.extend(mixins.RequireMixin, {
+ __AGILE_BASE_WIDGET: true,
+ init(parent, options = {}) {
+ this._super(parent);
+ this.__is_rendered = $.Deferred();
+ this._is_rendered = this.__is_rendered.promise();
+ this.__is_added_to_DOM = $.Deferred();
+ this._is_added_to_DOM = this.__is_added_to_DOM.promise();
+ this._destroyed = $.Deferred();
+ },
+ show() {
+ this.$el.removeClass('oe_hidden');
+ },
+ hide() {
+ this.$el.addClass('oe_hidden');
+ },
+ changeParent(parent) {
+ if (this.getParent() === parent) {
+ return;
+ }
+ if (this.$el) {
+ this.$el.remove();
+ }
+ this.setParent(parent);
+ },
+ renderElement() {
+ this._super();
+ this.$el.attr(this.attributes);
+ },
+ /**
+ * Attach the current widget to a dom element
+ *
+ * @param target A jQuery object or a Widget instance.
+ */
+ attachTo: function (target) {
+ var self = this;
+ this.setElement(target.$el || target);
+ return this.willStart().then(function () {
+ self.resolveRenderAndDOM();
+ return self.start();
+ });
+ },
+
+ insertAt: function(target, index) {
+ var self = this;
+ return this.__widgetRenderAndInsert(function(t) {
+ t.insertAt(self.$el, index);
+ }, target);
+ },
+
+ willStart() {
+ if (this.__willStartCalled) {
+ throw new Error("You should not call willStart by yourself. Use _is_rendered promise to know when data is loaded.");
+ }
+ this.__willStartCalled = true;
+ return this._super();
+ },
+ /**
+ * Renders the current widget and replaces the given jQuery object.
+ *
+ * @param target A jQuery object or a Widget instance.
+ */
+ __widgetRenderAndInsert(insertion, target) {
+ if (this.__willStartCalled) {
+ this._is_rendered.then(() => {
+ insertion(target);
+ });
+ return $.when();
+ }
+ return this.willStart().then(() => {
+ this.renderElement();
+ insertion(target);
+ this.resolveRenderAndDOM();
+ return this.start();
+ });
+ },
+ resolveRenderAndDOM() {
+ this.__is_rendered.resolve();
+ // If parent is agile widget attach to chain
+ if (!this.__parentedDestroyed && this.getParent().__AGILE_BASE_WIDGET) {
+ this.getParent()._is_added_to_DOM.then(() => {
+ this.__is_added_to_DOM.resolve();
+ });
+ }
+ },
+ addedToDOM() {
+ },
+ destroy() {
+ this._super();
+ this._destroyed.resolve(arguments);
+ },
+ start() {
+ let ret = this._super();
+ this._is_added_to_DOM.then(() => {
+ this.addedToDOM();
+ });
+ return ret;
+ },
+ /**
+ * This method destroys all children widgets, calls again willStart to prepare data and then renders widget again
+ * @param {string[]} deferredsToClear array of field names that are used for resolving willStart. Those fields are getting set to undefined
+ */
+ rerender_widget(deferredsToClear = []) {
+ this.emptyWidget();
+ for (let field of deferredsToClear) {
+ delete this[field];
+ }
+ this.__willStartCalled = false;
+ this.willStart().then(() => {
+ this.renderElement();
+ return this.start();
+ })
+ },
+ emptyWidget() {
+ for (let children of this.getChildren()) {
+ children.destroy();
+ }
+ }
+
+ });
+ var AgileViewWidget = AgileBaseWidget.extend(mixins.MenuItemsMixin, {
+ custom_events: {
+ set_title: '_onSetTitle',
+ open_right_side: '_onOpenRightSide'
+ },
+ init(parent, options) {
+ this._super(parent, options);
+ this.options = options;
+ mixins.MenuItemsMixin.init.call(this);
+ },
+ renderElement() {
+ this._super();
+ if (!this.title) {
+ console.error("Title not set");
+ this.title = _t("Project Agile");
+ }
+ let floatingButton = $(core.qweb.render("scrummer.view.floating-action-button", {widget: this}).trim());
+ this.$el.append(floatingButton);
+ this.setTitle(this.title);
+ },
+ setTitle(title, stringTitle) {
+ if (title !== undefined) {
+ this.title = title;
+ $("title").html(stringTitle || this.title);
+ this.trigger_up("set_title", {title: this.title});
+ }
+ },
+ _onSetTitle(evt) {
+ if (this.subheader) {
+ this.subheader.setTitle(evt.data.title);
+ }
+ },
+ _onOpenRightSide(evt) {
+ let WidgetClass = evt.data.WidgetClass;
+ let widgetOptions = evt.data.options;
+
+ this.$el.addClass("with-right");
+ // If right side is open, then destroy current widget and send preventClosing signal.
+ if (this.rightSideWidget) {
+ this.rightSideWidget.destroy({preventClosing: true});
+ }
+ this.rightSideWidget = new WidgetClass(this, widgetOptions);
+ this.rightSideWidget.appendTo(this.$("#right-detail-view").empty());
+
+ this.rightSideWidget._destroyed.then(args => {
+ // Check if preventClosing signal is sent to widgets destroy method.
+ if (typeof args[0] !== "object" || !args[0].preventClosing) {
+ this.$el.removeClass("with-right");
+ delete this.rightSideWidget;
+ }
+ });
+ },
+ start(){
+ mixins.MenuItemsMixin.start.call(this);
+ return this._super();
+ },
+ updateMenuVisibility(){
+ mixins.MenuItemsMixin.updateMenuVisibility.call(this);
+ },
+ });
+ var AgileContainerWidget = AgileBaseWidget.extend({
+ init(parent, options) {
+ this._super(parent, options);
+ this.widgetDefinitions = [];
+ this.widget = {};
+ },
+ renderElement() {
+ this._super();
+ this.build_widget_list();
+ this.build_widgets();
+ },
+ build_widgets() {
+ for (let def of this.widgetDefinitions) {
+ this.render_widget(def)
+ }
+ },
+ render_widget(def) {
+ if (typeof def.condition === "undefined" || typeof def.condition === "function" && def.condition.call(this) || def.condition) {
+ let args = typeof def.args === 'function' ? def.args(this) : def.args;
+ let w = new def.widget(this, args || {});
+ if (def.replace) {
+ w.replace(this.$(def.replace));
+ } else if (def.append) {
+ w.appendTo(this.$(def.append));
+ } else if (def.prepend) {
+ w.prependTo(this.$(def.prepend));
+ } else {
+ w.appendTo(this.$el);
+ }
+ this.widget[def.id] = w;
+ }
+ },
+ build_widget_list() {
+ },
+ /* This method should recieve widget in form like this:
+ {
+ 'name': 'proxy_status',
+ 'widget': NameOfWidgetClass,
+ 'append': '.css-selector', // or replace or prepend
+ 'condition': function(){ return true}, // Expression or function that returns boolean specifying if widget should be added or not
+ 'args': {} // object sent to widget as options
+ }
+ */
+ add_widget(widgetDefinition) {
+ console.log(this.template + " adding widget: " + widgetDefinition.name);
+ this.widgetDefinitions.push(widgetDefinition);
+ },
+ rerender_widget(widgetDefinitions) {
+ this.widgetDefinitions = [];
+ this._super(widgetDefinitions);
+ }
+
+ });
+ var DataWidget = AgileBaseWidget.extend({
+ /**
+ * @param {Widget} parent Parent widget
+ * @param {Object} options DataWidget parameters.
+ *
+ * @param {string} options.id - The id of the record.
+ * @param {string} options.data_service - Instance of DataService, if this is set, then DataWidget won't send requests to server directly.
+ * @param {string} options.dataset - The dataset object of the record.
+ * @param {string[]} [options.fields] - Fields that dataset should fetch of the record. Mandatory if data is not specified.
+ * @param {string} [options.data] - The initial data used to set model.
+ * If data is not specified, internal _model will be populated with data from server
+ * @param {string} [options.name] Name of the model, used for easy identiication when debugging.
+ * @param {string} [options.domID] This is used to set custom id of DOM node.
+ */
+ init(parent, options = {}) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this._model = this.data;
+ delete this.data;
+ this._require_prop("id");
+ this.useDataService = this.data_service && this.data_service.__dataService;
+ if (!this.useDataService) {
+ this._require_prop("dataset");
+ this.wrapModel();
+ } else {
+ // store reference to dataset from data_service for consistency
+ this.dataset = this.data_service.dataset;
+ }
+ },
+ willStart() {
+ return this._super().then(() => {
+ if (this.useDataService) {
+ return this.data_service.getRecord(this.id).then(record => {
+ // Assigning proxy to this.__model is for backward compatibility. DataService will not trigger RPC if value doesn't change
+ this._model = record;
+ this.__model = record._source;
+ this.name = record.name;
+ })
+ } else if (typeof this._model === "object") {
+ return $.when();
+ }
+ return this.dataset.read_ids([this.id], this.fields)
+ .then((result) => {
+ this._model = result[0];
+ this.name = this._model.name; // For easier debugging
+ });
+
+ });
+ },
+ /**
+ * This method wraps this._model with proxy which forbids creating new property and automatically stores value on server
+ * If you want to save value to model without triggering write call to server, use "this.__model"
+ *
+ * You can call methods on server model by calling function on _model. Context is sent to server by default, and
+ * return value from that function is native JavaScript Promise object
+ */
+ wrapModel() {
+ this._is_rendered.then(() => {
+ let model = this._model;
+ model.__widget = this;
+ let keys = Object.keys(model);
+ // this._model will trigger write
+ this._model = new Proxy(model, {
+ set(trapTarget, key, value, receiver) {
+
+ if (!keys.includes(key) || key === "__widget" || key === "id") {
+ throw new TypeError("Trying to write non-existing property", arguments);
+ }
+ let widget = trapTarget.__widget;
+ // TODO: Find more elegant way to deal with many2one fields
+ let writeValue = Array.isArray(value) ? value[0] : value;
+ let displayValue = Array.isArray(value) ? value[1] : value;
+ widget.dataset.write(trapTarget.id, {[key]: writeValue})
+ .done(r => console.info(`Saved ${trapTarget.__widget.dataset.model} [${trapTarget.id}]: ${key} - ${value}`))
+ .fail(r => console.error(`Error ${trapTarget.__widget.dataset.model} [${trapTarget.id}]: ${key} - ${value}`, r));
+ widget.$(`[data-field="${key}"] .field_value`).text(displayValue);
+
+ return Reflect.set(trapTarget, key, value, receiver);
+ },
+ get(trapTarget, key, receiver) {
+ let widget = trapTarget.__widget;
+ let model = trapTarget;
+ // if target doesn't contain key, assume it is function.
+ if (!(key in receiver)) {
+ // Wrap function in a Proxy that will catch arguments
+ return new Proxy(() => {
+ }, {
+ apply: function (trapTarget, thisArg, argumentList) {
+ return widget.dataset._model.call(key, [[model.id], ...argumentList], {context: widget.dataset.get_context().eval()})
+ }
+ });
+ }
+
+ return Reflect.get(trapTarget, key, receiver);
+ }
+ });
+ // this.__model will not trigger save rpc call
+ this.__model = new Proxy(model, {
+ set(trapTarget, key, value, receiver) {
+ if (!keys.includes(key) || key === "__widget" || key === "id") {
+ throw new TypeError("Trying to write non-existing property");
+ }
+ let widget = trapTarget.__widget;
+ let displayValue = Array.isArray(value) ? value[1] : value;
+ widget.$(`[data-field="${key}"] .field_value`).text(displayValue);
+ return Reflect.set(trapTarget, key, value, receiver);
+ }
+ });
+ });
+ },
+
+ start() {
+ this.$("[data-widget-editable=true]")
+ .attr('contenteditable', 'true')
+ .on('keypress', (e) => {
+ if (e.which == 13) {
+ e.preventDefault();
+ $(e.target).blur();
+ }
+ })
+ .blur((e) => {
+ let target = $(e.target);
+ let field = target.data("field");
+ if (field === undefined) {
+ throw new Error("DataWidget data-field attribute must be set when using data-widget-editable!");
+ }
+ let oldVal = this._model[field];
+ let newValue = target.text().trim();
+ if (oldVal !== newValue) {
+ this.dataset.write(this.id, {[field]: newValue}).done(() => {
+ console.info(`Changed ${field} from: ${oldVal} to: ${newValue}`);
+ }).fail((e) => {
+ console.error("Error while saving data: ", e);
+ });
+ }
+ });
+ return this._super();
+ },
+ /**
+ * Overrides native Widget method by using domID instead of id for DOM node ID.
+ * id is reserved for record id
+ *
+ * @return {jQuery}
+ * @override
+ * @private
+ */
+ _make_descriptive() {
+ var attrs = _.extend({}, this.attributes || {});
+ if (this.domID) {
+ attrs.domID = this.domID;
+ }
+ if (this.className) {
+ attrs['class'] = this.className;
+ }
+ return $(this.make(this.tagName, attrs));
+ },
+ unlink() {
+ return this.dataset.unlink([this.id])
+ .done(r => console.info(`Record deleted: ${this.dataset.model}, ${this.id}`))
+ .fail(r => console.error(`Error while deleting record: ${this.dataset.model}, ${this.id}`, r));
+ }
+ });
+
+ return {
+ AgileBaseWidget,
+ AgileViewWidget,
+ AgileContainerWidget,
+ DataWidget
+ };
+
+});
diff --git a/scrummer/static/src/js/widgets/board_chooser.js b/scrummer/static/src/js/widgets/board_chooser.js
new file mode 100644
index 0000000..72494b0
--- /dev/null
+++ b/scrummer/static/src/js/widgets/board_chooser.js
@@ -0,0 +1,170 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.board_chooser', function (require) {
+ "use strict";
+
+ const data = require('scrummer.data');
+ const AbstractModelList = require('scrummer.abstract_model_list');
+ const AgileBaseWidget = require('scrummer.BaseWidgets').AgileBaseWidget;
+ const storage_service = require('scrummer.storage_service');
+ const DataServiceFactory = require('scrummer.data_service_factory');
+ const hash_service = require('scrummer.hash_service');
+ const _t = require('web.core')._t;
+ const crash_manager = require('web.crash_manager');
+
+ const BoardChooser = AgileBaseWidget.extend({
+ _name: "BoardChooser",
+ template: "scrummer.board_chooser",
+ custom_events: {
+ 'set_board': '_onSetBoard',
+ },
+ _onSetBoard(evt) {
+ this.setBoard(evt.data.id);
+ },
+ init(parent, options) {
+ Object.assign(this, options);
+ this._super(parent, options);
+ this.current_board = parseInt(hash_service.get("board"));
+ this.current_project = parseInt(hash_service.get("project"));
+ },
+ willStart() {
+ return $.when(
+ this._super(),
+ // Store reference to current_user, so that we can use it in synchronous methods
+ data.cache.get("current_user").then(user => {
+ this.user = user;
+ }),
+ // If current_project is set, fetch it and store so that it can be used in synchronous project_image_url method
+ this.current_project && DataServiceFactory.get("project.project").getRecord(this.current_project).then(project => {
+ this.project = project;
+ })
+ ).then(() => {
+ let board_service = DataServiceFactory.get("project.agile.board");
+ let project_ids = this.current_project ? [this.current_project] : this.user.team_ids[this.user.team_id[0]].project_ids;
+ let board_filter = [
+ "|",
+ "&",
+ ["visibility", "=", "global"],
+ ["project_ids", "in", project_ids],
+
+ "|",
+ "&",
+ "&",
+ ["visibility", "=", "team"],
+ ["team_id", "=", this.user.team_id[0]],
+ ["project_ids", "in", project_ids],
+
+ "&",
+ "&",
+ ["visibility", "=", "user"],
+ ["user_id", "=", this.user.id],
+ ["project_ids", "in", project_ids],
+
+ ];
+ return board_service.dataset.id_search("", board_filter).then(board_ids => {
+ return board_service.getRecords(board_ids, true).then(records => {
+ this.boards = records;
+ if (this.boards.size == 0) {
+ // delete this.template;
+ crash_manager.show_error({
+ type: _t("Configuration error"),
+ message: _t("Project ") + this.project.name + _t(" does not have any board associated with it."),
+ data: {debug: ""}
+ });
+ hash_service.setHash("page", "dashboard");
+ return $.Deferred().reject();
+ }
+ if (!this.boards.has(this.current_board) && this.boards.size > 0) {
+ this.setBoard([...this.boards.keys()][0])
+ } else {
+ // save current board;
+ this.board = this.boards.get(this.current_board);
+ }
+ })
+ })
+ });
+ },
+ setBoard(id) {
+ storage_service.set("board", id);
+
+ let boardTypeChanged = this.board === undefined || this.board.type !== this.boards.get(id).type;
+ hash_service.setHash("board", id, true, boardTypeChanged);
+
+ if (this.board !== undefined) {
+ this.boardList.addItem(this.board);
+ }
+ this.board = this.boards.get(id);
+ if (boardTypeChanged) {
+ hash_service.delete("view");
+ this.trigger_up("board_type_changed");
+ }
+ this.$("a.available-boards").html(this.board.name + ' ')
+ },
+ start() {
+ // Materialize Dropdown
+ this.boardList._is_added_to_DOM.then(() => {
+ $('.dropdown-button').dropdown({
+ inDuration: 300,
+ outDuration: 125,
+ constrain_width: true, // Does not change width of dropdown to that of the activator
+ hover: false, // Activate on click
+ alignment: 'left', // Aligns dropdown to left or right edge (works with constrain_width)
+ gutter: 0, // Spacing from edge
+ belowOrigin: true // Displays dropdown below the button
+ });
+ });
+ },
+
+ renderElement() {
+ this._super();
+ let data = [...this.boards.values()];
+ this.boardList = new AbstractModelList.ModelList(this, {
+ model: "project.agile.board",
+ // useDataService: true,
+ // domain: [["project_ids", "in", this.current_project ? [this.current_project] : user.team_ids[user.team_id[0]].project_ids]],
+ data,
+ tagName: "ul",
+ id: "board-chooser-dropdown",
+ className: "dropdown-content",
+ ModelItem: BoardListItem
+ });
+ // Adding backlog task list
+ this.boardList.insertAfter(this.$(".available-boards"));
+ },
+
+ project_image_url() {
+ return this.current_project ?
+ data.getImage("project.project", this.current_project, this.project.write_date) :
+ data.getImage("project.agile.team", this.user.team_id[0]);
+ }
+ });
+ const BoardListItem = AgileBaseWidget.extend({
+ _name: "BoardListItem",
+ template: "scrummer.list.board_chooser_item",
+ init(parent, options) {
+ this._super(parent, options);
+ Object.assign(this, options);
+ },
+ start() {
+ if (this.id == hash_service.get("board")) {
+ this.destroy();
+ } else {
+ // When clicked on project in dashboard, fetch all boards and open last board.
+ this.$("a").click(() => {
+ this.selectBoard();
+ });
+ }
+ return this._super();
+ },
+ selectBoard() {
+ this.trigger_up("set_board", {id: this.record.id});
+ this.destroy();
+ }
+ });
+ BoardListItem.sort_by = "id";
+ return {
+ BoardChooser,
+ BoardListItem
+ };
+});
diff --git a/scrummer/static/src/js/widgets/header.js b/scrummer/static/src/js/widgets/header.js
new file mode 100644
index 0000000..3b45345
--- /dev/null
+++ b/scrummer/static/src/js/widgets/header.js
@@ -0,0 +1,132 @@
+// Copyright 2017 - 2018 Modoolar
+// License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
+
+odoo.define('scrummer.header', function (require) {
+ "use strict";
+ var AgileBaseWidgets = require('scrummer.BaseWidgets');
+ var AgileMenu = require('scrummer.menu');
+ var data = require('scrummer.data');
+ var bus = require('scrummer.core').bus;
+ const HeaderWidget = AgileBaseWidgets.AgileBaseWidget.extend({
+ template: "scrummer.layout.header",
+ _name: "HeaderWidget",
+ init(parent, options) {
+ this._super(parent, options);
+ this.menuTopWidget = new AgileMenu.AgileTopMenu(this, {viewKey: "page"});
+ },
+ renderElement() {
+ this._super();
+ data.cache.get("current_user").then(user => {
+ this.user = user;
+ this.$(".user-name").html(user.name);
+ let team = user.team_id[1];
+ this.$(".team-name").html(team);
+ if (Object.keys(user.team_ids).length > 1) {
+ let teamList = this.$("#team-dropdown");
+ for (let team_id in user.team_ids) {
+ let team = user.team_ids[team_id];
+ let teamLi = $(" " + team.name + " ");
+ teamList.append(teamLi);
+ teamLi.click(() => {
+ if (user.team_id[0] !== team.id) {
+ user.team_id[0] = team.id;
+ this.$(".team-name").html(team.name);
+ let newProject = user.team_ids[team.id].project_ids.length ? user.team_ids[team.id].project_ids[0] : false;
+ let teamChangeDef = $.Deferred();
+ hash_service.delete("view");
+ hash_service.setHash("page", "dashboard");
+ hash_service.delete("project");
+ bus.trigger("team:changed", team.id, teamChangeDef);
+
+ data.getDataSet("res.users").call('change_team', [[data.session.uid], team.id]).then(() => {
+ console.log("changed team context:", team.id);
+ teamChangeDef.resolve();
+ })
+ }
+ })
+ }
+ } else {
+ this.$(".team-dropdown-button").hide();
+ }
+ this.$(".user-button").show();
+ });
+ this.menuTopWidget.appendTo(this.$(".nav-middle"));
+ },
+ addedToDOM() {
+ this._super();
+ this.$('.notification-button').dropdown({
+ inDuration: 300,
+ outDuration: 225,
+ constrain_width: false, // Does not change width of dropdown to that of the activator
+ hover: true, // Activate on hover
+ gutter: 0, // Spacing from edge
+ belowOrigin: true, // Displays dropdown below the button
+ alignment: 'left' // Displays dropdown with edge aligned to the left of button
+ });
+ this.$('.user-button').dropdown({
+ inDuration: 300,
+ outDuration: 225,
+ constrain_width: false,
+ hover: true,
+ gutter: 0,
+ belowOrigin: true,
+ alignment: 'right'
+ });
+ this.$('.team-dropdown-button').closest(".dropdown-content").css("display", "block");
+ let buttonWidth = this.$('.team-dropdown-button').outerWidth();
+ // Fix for case when icon is not loaded at the moment of calculating width
+ if ($('.team-dropdown-button').find("i.mdi").outerWidth() === 0) {
+ buttonWidth += 20;
+ }
+ this.$('.team-dropdown-button').closest(".dropdown-content").css("display", "");
+ this.$('.team-dropdown-button').dropdown({
+ inDuration: 300,
+ outDuration: 225,
+ constrain_width: false,
+ hover: true,
+ gutter: buttonWidth,
+ belowOrigin: false,
+ alignment: 'right'
+ });
+
+ },
+ start() {
+ bus.on("search:show", this, (keydownEvent, callback) => {
+ this.$(".nav-wrapper").addClass("with-search");
+ $(".nav-search > div").show();
+ let searchInput = $(".nav-search input");
+ searchInput.keydown(function (evt) {
+ clearTimeout(this.searchDelayTimeout);
+ if (evt.keyCode == 13) {
+ keydownEvent($(this));
+ } else {
+ this.searchDelayTimeout = setTimeout(() => {
+ keydownEvent($(this));
+ }, 1000);
+ }
+ });
+ if (typeof callback == "function") {
+ callback(searchInput);
+ }
+ });
+ bus.on("search:remove", this, () => {
+ this.$(".nav-wrapper").removeClass("with-search");
+ this.$(".nav-search > div").hide();
+ this.$(".nav-search input").off();
+ });
+ this.$(".search-button").click(() => {
+ this.$(".nav-wrapper").toggleClass("search-open");
+ });
+ this.$(".back-to-odoo").click(e => {
+ e.preventDefault();
+ let href = "/web";
+ href += data.session.debug ? "?debug=" + data.session.debug : "";
+ window.location.href = href;
+ });
+ return this._super();
+ }
+ });
+ return {
+ HeaderWidget
+ }
+});
diff --git a/scrummer/static/src/js/widgets/layout.js b/scrummer/static/src/js/widgets/layout.js
new file mode 100644
index 0000000..a9e5e94
--- /dev/null
+++ b/scrummer/static/src/js/widgets/layout.js
@@ -0,0 +1,118 @@
+// Copyright 2017 - 2018 Modoolar