" ).appendTo( tooltip ),
id = tooltip.uniqueId().attr( "id" );
this._addClass( content, "ui-tooltip-content" );
this._addClass( tooltip, "ui-tooltip", "ui-widget ui-widget-content" );
tooltip.appendTo( this._appendTo( element ) );
return this.tooltips[ id ] = {
element: element,
tooltip: tooltip
};
},
_find: function( target ) {
var id = target.data( "ui-tooltip-id" );
return id ? this.tooltips[ id ] : null;
},
_removeTooltip: function( tooltip ) {
tooltip.remove();
delete this.tooltips[ tooltip.attr( "id" ) ];
},
_appendTo: function( target ) {
var element = target.closest( ".ui-front, dialog" );
if ( !element.length ) {
element = this.document[ 0 ].body;
}
return element;
},
_destroy: function() {
var that = this;
// Close open tooltips
$.each( this.tooltips, function( id, tooltipData ) {
// Delegate to close method to handle common cleanup
var event = $.Event( "blur" ),
element = tooltipData.element;
event.target = event.currentTarget = element[ 0 ];
that.close( event, true );
// Remove immediately; destroying an open tooltip doesn't use the
// hide animation
$( "#" + id ).remove();
// Restore the title
if ( element.data( "ui-tooltip-title" ) ) {
// If the title attribute has changed since open(), don't restore
if ( !element.attr( "title" ) ) {
element.attr( "title", element.data( "ui-tooltip-title" ) );
}
element.removeData( "ui-tooltip-title" );
}
} );
this.liveRegion.remove();
}
} );
// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {
// Backcompat for tooltipClass option
$.widget( "ui.tooltip", $.ui.tooltip, {
options: {
tooltipClass: null
},
_tooltip: function() {
var tooltipData = this._superApply( arguments );
if ( this.options.tooltipClass ) {
tooltipData.tooltip.addClass( this.options.tooltipClass );
}
return tooltipData;
}
} );
}
var widgetsTooltip = $.ui.tooltip;
}));
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 2011–2014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery);
/* Portuguese initialisation for the jQuery UI date picker plugin. */
(function (factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["../widgets/datepicker"], factory);
} else {
// Browser globals
factory(jQuery.datepicker);
}
}(function (datepicker) {
datepicker.regional.pt = {
closeText: "Fechar",
prevText: "Anterior",
nextText: "Seguinte",
currentText: "Hoje",
monthNames: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho",
"Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthNamesShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun",
"Jul", "Ago", "Set", "Out", "Nov", "Dez"],
dayNames: [
"Domingo",
"Segunda-feira",
"Terça-feira",
"Quarta-feira",
"Quinta-feira",
"Sexta-feira",
"Sábado"
],
dayNamesShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"],
dayNamesMin: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"],
weekHeader: "Sem",
dateFormat: "dd/mm/yy",
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ""
};
datepicker.setDefaults(datepicker.regional.pt);
return datepicker.regional.pt;
}));
/*
* This combined file was created by the DataTables downloader builder:
* https://datatables.net/download
*
* To rebuild or modify this file with the latest versions of the included
* software please visit:
* https://datatables.net/download/#dt/dt-1.10.18
*
* Included libraries:
* DataTables 1.10.18
*/
/*!
DataTables 1.10.18
©2008-2018 SpryMedia Ltd - datatables.net/license
*/
(function (h) { "function" === typeof define && define.amd ? define(["jquery"], function (E) { return h(E, window, document) }) : "object" === typeof exports ? module.exports = function (E, H) { E || (E = window); H || (H = "undefined" !== typeof window ? require("jquery") : require("jquery")(E)); return h(H, E, E.document) } : h(jQuery, window, document) })(function (h, E, H, k) {
function Z(a) {
var b, c, d = {}; h.each(a, function (e) {
if ((b = e.match(/^([^A-Z]+?)([A-Z])/)) && -1 !== "a aa ai ao as b fn i m o s ".indexOf(b[1] + " ")) c = e.replace(b[0], b[2].toLowerCase()),
d[c] = e, "o" === b[1] && Z(a[e])
}); a._hungarianMap = d
} function J(a, b, c) { a._hungarianMap || Z(a); var d; h.each(b, function (e) { d = a._hungarianMap[e]; if (d !== k && (c || b[d] === k)) "o" === d.charAt(0) ? (b[d] || (b[d] = {}), h.extend(!0, b[d], b[e]), J(a[d], b[d], c)) : b[d] = b[e] }) } function Ca(a) {
var b = n.defaults.oLanguage, c = b.sDecimal; c && Da(c); if (a) {
var d = a.sZeroRecords; !a.sEmptyTable && (d && "No data available in table" === b.sEmptyTable) && F(a, a, "sZeroRecords", "sEmptyTable"); !a.sLoadingRecords && (d && "Loading..." === b.sLoadingRecords) && F(a,
a, "sZeroRecords", "sLoadingRecords"); a.sInfoThousands && (a.sThousands = a.sInfoThousands); (a = a.sDecimal) && c !== a && Da(a)
}
} function eb(a) {
A(a, "ordering", "bSort"); A(a, "orderMulti", "bSortMulti"); A(a, "orderClasses", "bSortClasses"); A(a, "orderCellsTop", "bSortCellsTop"); A(a, "order", "aaSorting"); A(a, "orderFixed", "aaSortingFixed"); A(a, "paging", "bPaginate"); A(a, "pagingType", "sPaginationType"); A(a, "pageLength", "iDisplayLength"); A(a, "searching", "bFilter"); "boolean" === typeof a.sScrollX && (a.sScrollX = a.sScrollX ? "100%" :
""); "boolean" === typeof a.scrollX && (a.scrollX = a.scrollX ? "100%" : ""); if (a = a.aoSearchCols) for (var b = 0, c = a.length; b < c; b++)a[b] && J(n.models.oSearch, a[b])
} function fb(a) { A(a, "orderable", "bSortable"); A(a, "orderData", "aDataSort"); A(a, "orderSequence", "asSorting"); A(a, "orderDataType", "sortDataType"); var b = a.aDataSort; "number" === typeof b && !h.isArray(b) && (a.aDataSort = [b]) } function gb(a) {
if (!n.__browser) {
var b = {}; n.__browser = b; var c = h("
").css({
position: "fixed", top: 0, left: -1 * h(E).scrollLeft(), height: 1, width: 1,
overflow: "hidden"
}).append(h("
").css({ position: "absolute", top: 1, left: 1, width: 100, overflow: "scroll" }).append(h("
").css({ width: "100%", height: 10 }))).appendTo("body"), d = c.children(), e = d.children(); b.barWidth = d[0].offsetWidth - d[0].clientWidth; b.bScrollOversize = 100 === e[0].offsetWidth && 100 !== d[0].clientWidth; b.bScrollbarLeft = 1 !== Math.round(e.offset().left); b.bBounding = c[0].getBoundingClientRect().width ? !0 : !1; c.remove()
} h.extend(a.oBrowser, n.__browser); a.oScroll.iBarWidth = n.__browser.barWidth
}
function hb(a, b, c, d, e, f) { var g, j = !1; c !== k && (g = c, j = !0); for (; d !== e;)a.hasOwnProperty(d) && (g = j ? b(g, a[d], d, a) : a[d], j = !0, d += f); return g } function Ea(a, b) { var c = n.defaults.column, d = a.aoColumns.length, c = h.extend({}, n.models.oColumn, c, { nTh: b ? b : H.createElement("th"), sTitle: c.sTitle ? c.sTitle : b ? b.innerHTML : "", aDataSort: c.aDataSort ? c.aDataSort : [d], mData: c.mData ? c.mData : d, idx: d }); a.aoColumns.push(c); c = a.aoPreSearchCols; c[d] = h.extend({}, n.models.oSearch, c[d]); ka(a, d, h(b).data()) } function ka(a, b, c) {
var b = a.aoColumns[b],
d = a.oClasses, e = h(b.nTh); if (!b.sWidthOrig) { b.sWidthOrig = e.attr("width") || null; var f = (e.attr("style") || "").match(/width:\s*(\d+[pxem%]+)/); f && (b.sWidthOrig = f[1]) } c !== k && null !== c && (fb(c), J(n.defaults.column, c), c.mDataProp !== k && !c.mData && (c.mData = c.mDataProp), c.sType && (b._sManualType = c.sType), c.className && !c.sClass && (c.sClass = c.className), c.sClass && e.addClass(c.sClass), h.extend(b, c), F(b, c, "sWidth", "sWidthOrig"), c.iDataSort !== k && (b.aDataSort = [c.iDataSort]), F(b, c, "aDataSort")); var g = b.mData, j = S(g), i = b.mRender ?
S(b.mRender) : null, c = function (a) { return "string" === typeof a && -1 !== a.indexOf("@") }; b._bAttrSrc = h.isPlainObject(g) && (c(g.sort) || c(g.type) || c(g.filter)); b._setter = null; b.fnGetData = function (a, b, c) { var d = j(a, b, k, c); return i && b ? i(d, b, a, c) : d }; b.fnSetData = function (a, b, c) { return N(g)(a, b, c) }; "number" !== typeof g && (a._rowReadObject = !0); a.oFeatures.bSort || (b.bSortable = !1, e.addClass(d.sSortableNone)); a = -1 !== h.inArray("asc", b.asSorting); c = -1 !== h.inArray("desc", b.asSorting); !b.bSortable || !a && !c ? (b.sSortingClass = d.sSortableNone,
b.sSortingClassJUI = "") : a && !c ? (b.sSortingClass = d.sSortableAsc, b.sSortingClassJUI = d.sSortJUIAscAllowed) : !a && c ? (b.sSortingClass = d.sSortableDesc, b.sSortingClassJUI = d.sSortJUIDescAllowed) : (b.sSortingClass = d.sSortable, b.sSortingClassJUI = d.sSortJUI)
} function $(a) { if (!1 !== a.oFeatures.bAutoWidth) { var b = a.aoColumns; Fa(a); for (var c = 0, d = b.length; c < d; c++)b[c].nTh.style.width = b[c].sWidth } b = a.oScroll; ("" !== b.sY || "" !== b.sX) && la(a); r(a, null, "column-sizing", [a]) } function aa(a, b) {
var c = ma(a, "bVisible"); return "number" ===
typeof c[b] ? c[b] : null
} function ba(a, b) { var c = ma(a, "bVisible"), c = h.inArray(b, c); return -1 !== c ? c : null } function V(a) { var b = 0; h.each(a.aoColumns, function (a, d) { d.bVisible && "none" !== h(d.nTh).css("display") && b++ }); return b } function ma(a, b) { var c = []; h.map(a.aoColumns, function (a, e) { a[b] && c.push(e) }); return c } function Ga(a) {
var b = a.aoColumns, c = a.aoData, d = n.ext.type.detect, e, f, g, j, i, h, l, q, t; e = 0; for (f = b.length; e < f; e++)if (l = b[e], t = [], !l.sType && l._sManualType) l.sType = l._sManualType; else if (!l.sType) {
g = 0; for (j = d.length; g <
j; g++) { i = 0; for (h = c.length; i < h; i++) { t[i] === k && (t[i] = B(a, i, e, "type")); q = d[g](t[i], a); if (!q && g !== d.length - 1) break; if ("html" === q) break } if (q) { l.sType = q; break } } l.sType || (l.sType = "string")
}
} function ib(a, b, c, d) {
var e, f, g, j, i, m, l = a.aoColumns; if (b) for (e = b.length - 1; 0 <= e; e--) {
m = b[e]; var q = m.targets !== k ? m.targets : m.aTargets; h.isArray(q) || (q = [q]); f = 0; for (g = q.length; f < g; f++)if ("number" === typeof q[f] && 0 <= q[f]) { for (; l.length <= q[f];)Ea(a); d(q[f], m) } else if ("number" === typeof q[f] && 0 > q[f]) d(l.length + q[f], m); else if ("string" ===
typeof q[f]) { j = 0; for (i = l.length; j < i; j++)("_all" == q[f] || h(l[j].nTh).hasClass(q[f])) && d(j, m) }
} if (c) { e = 0; for (a = c.length; e < a; e++)d(e, c[e]) }
} function O(a, b, c, d) { var e = a.aoData.length, f = h.extend(!0, {}, n.models.oRow, { src: c ? "dom" : "data", idx: e }); f._aData = b; a.aoData.push(f); for (var g = a.aoColumns, j = 0, i = g.length; j < i; j++)g[j].sType = null; a.aiDisplayMaster.push(e); b = a.rowIdFn(b); b !== k && (a.aIds[b] = f); (c || !a.oFeatures.bDeferRender) && Ha(a, e, c, d); return e } function na(a, b) {
var c; b instanceof h || (b = h(b)); return b.map(function (b,
e) { c = Ia(a, e); return O(a, c.data, e, c.cells) })
} function B(a, b, c, d) { var e = a.iDraw, f = a.aoColumns[c], g = a.aoData[b]._aData, j = f.sDefaultContent, i = f.fnGetData(g, d, { settings: a, row: b, col: c }); if (i === k) return a.iDrawError != e && null === j && (K(a, 0, "Requested unknown parameter " + ("function" == typeof f.mData ? "{function}" : "'" + f.mData + "'") + " for row " + b + ", column " + c, 4), a.iDrawError = e), j; if ((i === g || null === i) && null !== j && d !== k) i = j; else if ("function" === typeof i) return i.call(g); return null === i && "display" == d ? "" : i } function jb(a,
b, c, d) { a.aoColumns[c].fnSetData(a.aoData[b]._aData, d, { settings: a, row: b, col: c }) } function Ja(a) { return h.map(a.match(/(\\.|[^\.])+/g) || [""], function (a) { return a.replace(/\\\./g, ".") }) } function S(a) {
if (h.isPlainObject(a)) { var b = {}; h.each(a, function (a, c) { c && (b[a] = S(c)) }); return function (a, c, f, g) { var j = b[c] || b._; return j !== k ? j(a, c, f, g) : a } } if (null === a) return function (a) { return a }; if ("function" === typeof a) return function (b, c, f, g) { return a(b, c, f, g) }; if ("string" === typeof a && (-1 !== a.indexOf(".") || -1 !== a.indexOf("[") ||
-1 !== a.indexOf("("))) { var c = function (a, b, f) { var g, j; if ("" !== f) { j = Ja(f); for (var i = 0, m = j.length; i < m; i++) { f = j[i].match(ca); g = j[i].match(W); if (f) { j[i] = j[i].replace(ca, ""); "" !== j[i] && (a = a[j[i]]); g = []; j.splice(0, i + 1); j = j.join("."); if (h.isArray(a)) { i = 0; for (m = a.length; i < m; i++)g.push(c(a[i], b, j)) } a = f[0].substring(1, f[0].length - 1); a = "" === a ? g : g.join(a); break } else if (g) { j[i] = j[i].replace(W, ""); a = a[j[i]](); continue } if (null === a || a[j[i]] === k) return k; a = a[j[i]] } } return a }; return function (b, e) { return c(b, e, a) } } return function (b) { return b[a] }
}
function N(a) {
if (h.isPlainObject(a)) return N(a._); if (null === a) return function () { }; if ("function" === typeof a) return function (b, d, e) { a(b, "set", d, e) }; if ("string" === typeof a && (-1 !== a.indexOf(".") || -1 !== a.indexOf("[") || -1 !== a.indexOf("("))) {
var b = function (a, d, e) {
var e = Ja(e), f; f = e[e.length - 1]; for (var g, j, i = 0, m = e.length - 1; i < m; i++) {
g = e[i].match(ca); j = e[i].match(W); if (g) {
e[i] = e[i].replace(ca, ""); a[e[i]] = []; f = e.slice(); f.splice(0, i + 1); g = f.join("."); if (h.isArray(d)) {
j = 0; for (m = d.length; j < m; j++)f = {}, b(f, d[j], g),
a[e[i]].push(f)
} else a[e[i]] = d; return
} j && (e[i] = e[i].replace(W, ""), a = a[e[i]](d)); if (null === a[e[i]] || a[e[i]] === k) a[e[i]] = {}; a = a[e[i]]
} if (f.match(W)) a[f.replace(W, "")](d); else a[f.replace(ca, "")] = d
}; return function (c, d) { return b(c, d, a) }
} return function (b, d) { b[a] = d }
} function Ka(a) { return D(a.aoData, "_aData") } function oa(a) { a.aoData.length = 0; a.aiDisplayMaster.length = 0; a.aiDisplay.length = 0; a.aIds = {} } function pa(a, b, c) {
for (var d = -1, e = 0, f = a.length; e < f; e++)a[e] == b ? d = e : a[e] > b && a[e]--; -1 != d && c === k && a.splice(d,
1)
} function da(a, b, c, d) { var e = a.aoData[b], f, g = function (c, d) { for (; c.childNodes.length;)c.removeChild(c.firstChild); c.innerHTML = B(a, b, d, "display") }; if ("dom" === c || (!c || "auto" === c) && "dom" === e.src) e._aData = Ia(a, e, d, d === k ? k : e._aData).data; else { var j = e.anCells; if (j) if (d !== k) g(j[d], d); else { c = 0; for (f = j.length; c < f; c++)g(j[c], c) } } e._aSortData = null; e._aFilterData = null; g = a.aoColumns; if (d !== k) g[d].sType = null; else { c = 0; for (f = g.length; c < f; c++)g[c].sType = null; La(a, e) } } function Ia(a, b, c, d) {
var e = [], f = b.firstChild, g,
j, i = 0, m, l = a.aoColumns, q = a._rowReadObject, d = d !== k ? d : q ? {} : [], t = function (a, b) { if ("string" === typeof a) { var c = a.indexOf("@"); -1 !== c && (c = a.substring(c + 1), N(a)(d, b.getAttribute(c))) } }, G = function (a) { if (c === k || c === i) j = l[i], m = h.trim(a.innerHTML), j && j._bAttrSrc ? (N(j.mData._)(d, m), t(j.mData.sort, a), t(j.mData.type, a), t(j.mData.filter, a)) : q ? (j._setter || (j._setter = N(j.mData)), j._setter(d, m)) : d[i] = m; i++ }; if (f) for (; f;) { g = f.nodeName.toUpperCase(); if ("TD" == g || "TH" == g) G(f), e.push(f); f = f.nextSibling } else {
e = b.anCells;
f = 0; for (g = e.length; f < g; f++)G(e[f])
} if (b = b.firstChild ? b : b.nTr) (b = b.getAttribute("id")) && N(a.rowId)(d, b); return { data: d, cells: e }
} function Ha(a, b, c, d) {
var e = a.aoData[b], f = e._aData, g = [], j, i, m, l, q; if (null === e.nTr) {
j = c || H.createElement("tr"); e.nTr = j; e.anCells = g; j._DT_RowIndex = b; La(a, e); l = 0; for (q = a.aoColumns.length; l < q; l++) {
m = a.aoColumns[l]; i = c ? d[l] : H.createElement(m.sCellType); i._DT_CellIndex = { row: b, column: l }; g.push(i); if ((!c || m.mRender || m.mData !== l) && (!h.isPlainObject(m.mData) || m.mData._ !== l + ".display")) i.innerHTML =
B(a, b, l, "display"); m.sClass && (i.className += " " + m.sClass); m.bVisible && !c ? j.appendChild(i) : !m.bVisible && c && i.parentNode.removeChild(i); m.fnCreatedCell && m.fnCreatedCell.call(a.oInstance, i, B(a, b, l), f, b, l)
} r(a, "aoRowCreatedCallback", null, [j, f, b, g])
} e.nTr.setAttribute("role", "row")
} function La(a, b) {
var c = b.nTr, d = b._aData; if (c) {
var e = a.rowIdFn(d); e && (c.id = e); d.DT_RowClass && (e = d.DT_RowClass.split(" "), b.__rowc = b.__rowc ? qa(b.__rowc.concat(e)) : e, h(c).removeClass(b.__rowc.join(" ")).addClass(d.DT_RowClass));
d.DT_RowAttr && h(c).attr(d.DT_RowAttr); d.DT_RowData && h(c).data(d.DT_RowData)
}
} function kb(a) {
var b, c, d, e, f, g = a.nTHead, j = a.nTFoot, i = 0 === h("th, td", g).length, m = a.oClasses, l = a.aoColumns; i && (e = h("
").appendTo(g)); b = 0; for (c = l.length; b < c; b++)f = l[b], d = h(f.nTh).addClass(f.sClass), i && d.appendTo(e), a.oFeatures.bSort && (d.addClass(f.sSortingClass), !1 !== f.bSortable && (d.attr("tabindex", a.iTabIndex).attr("aria-controls", a.sTableId), Ma(a, f.nTh, b))), f.sTitle != d[0].innerHTML && d.html(f.sTitle), Na(a, "header")(a, d,
f, m); i && ea(a.aoHeader, g); h(g).find(">tr").attr("role", "row"); h(g).find(">tr>th, >tr>td").addClass(m.sHeaderTH); h(j).find(">tr>th, >tr>td").addClass(m.sFooterTH); if (null !== j) { a = a.aoFooter[0]; b = 0; for (c = a.length; b < c; b++)f = l[b], f.nTf = a[b].cell, f.sClass && h(f.nTf).addClass(f.sClass) }
} function fa(a, b, c) {
var d, e, f, g = [], j = [], i = a.aoColumns.length, m; if (b) {
c === k && (c = !1); d = 0; for (e = b.length; d < e; d++) { g[d] = b[d].slice(); g[d].nTr = b[d].nTr; for (f = i - 1; 0 <= f; f--)!a.aoColumns[f].bVisible && !c && g[d].splice(f, 1); j.push([]) } d =
0; for (e = g.length; d < e; d++) { if (a = g[d].nTr) for (; f = a.firstChild;)a.removeChild(f); f = 0; for (b = g[d].length; f < b; f++)if (m = i = 1, j[d][f] === k) { a.appendChild(g[d][f].cell); for (j[d][f] = 1; g[d + i] !== k && g[d][f].cell == g[d + i][f].cell;)j[d + i][f] = 1, i++; for (; g[d][f + m] !== k && g[d][f].cell == g[d][f + m].cell;) { for (c = 0; c < i; c++)j[d + c][f + m] = 1; m++ } h(g[d][f].cell).attr("rowspan", i).attr("colspan", m) } }
}
} function P(a) {
var b = r(a, "aoPreDrawCallback", "preDraw", [a]); if (-1 !== h.inArray(!1, b)) C(a, !1); else {
var b = [], c = 0, d = a.asStripeClasses, e =
d.length, f = a.oLanguage, g = a.iInitDisplayStart, j = "ssp" == y(a), i = a.aiDisplay; a.bDrawing = !0; g !== k && -1 !== g && (a._iDisplayStart = j ? g : g >= a.fnRecordsDisplay() ? 0 : g, a.iInitDisplayStart = -1); var g = a._iDisplayStart, m = a.fnDisplayEnd(); if (a.bDeferLoading) a.bDeferLoading = !1, a.iDraw++ , C(a, !1); else if (j) { if (!a.bDestroying && !lb(a)) return } else a.iDraw++; if (0 !== i.length) {
f = j ? a.aoData.length : m; for (j = j ? 0 : g; j < f; j++) {
var l = i[j], q = a.aoData[l]; null === q.nTr && Ha(a, l); var t = q.nTr; if (0 !== e) {
var G = d[c % e]; q._sRowStripe != G && (h(t).removeClass(q._sRowStripe).addClass(G),
q._sRowStripe = G)
} r(a, "aoRowCallback", null, [t, q._aData, c, j, l]); b.push(t); c++
}
} else c = f.sZeroRecords, 1 == a.iDraw && "ajax" == y(a) ? c = f.sLoadingRecords : f.sEmptyTable && 0 === a.fnRecordsTotal() && (c = f.sEmptyTable), b[0] = h("
", { "class": e ? d[0] : "" }).append(h("
", { valign: "top", colSpan: V(a), "class": a.oClasses.sRowEmpty }).html(c))[0]; r(a, "aoHeaderCallback", "header", [h(a.nTHead).children("tr")[0], Ka(a), g, m, i]); r(a, "aoFooterCallback", "footer", [h(a.nTFoot).children("tr")[0], Ka(a), g, m, i]); d = h(a.nTBody); d.children().detach();
d.append(h(b)); r(a, "aoDrawCallback", "draw", [a]); a.bSorted = !1; a.bFiltered = !1; a.bDrawing = !1
}
} function T(a, b) { var c = a.oFeatures, d = c.bFilter; c.bSort && mb(a); d ? ga(a, a.oPreviousSearch) : a.aiDisplay = a.aiDisplayMaster.slice(); !0 !== b && (a._iDisplayStart = 0); a._drawHold = b; P(a); a._drawHold = !1 } function nb(a) {
var b = a.oClasses, c = h(a.nTable), c = h("
").insertBefore(c), d = a.oFeatures, e = h("
", { id: a.sTableId + "_wrapper", "class": b.sWrapper + (a.nTFoot ? "" : " " + b.sNoFooter) }); a.nHolding = c[0]; a.nTableWrapper = e[0]; a.nTableReinsertBefore =
a.nTable.nextSibling; for (var f = a.sDom.split(""), g, j, i, m, l, q, k = 0; k < f.length; k++) {
g = null; j = f[k]; if ("<" == j) { i = h("
")[0]; m = f[k + 1]; if ("'" == m || '"' == m) { l = ""; for (q = 2; f[k + q] != m;)l += f[k + q], q++; "H" == l ? l = b.sJUIHeader : "F" == l && (l = b.sJUIFooter); -1 != l.indexOf(".") ? (m = l.split("."), i.id = m[0].substr(1, m[0].length - 1), i.className = m[1]) : "#" == l.charAt(0) ? i.id = l.substr(1, l.length - 1) : i.className = l; k += q } e.append(i); e = h(i) } else if (">" == j) e = e.parent(); else if ("l" == j && d.bPaginate && d.bLengthChange) g = ob(a); else if ("f" == j &&
d.bFilter) g = pb(a); else if ("r" == j && d.bProcessing) g = qb(a); else if ("t" == j) g = rb(a); else if ("i" == j && d.bInfo) g = sb(a); else if ("p" == j && d.bPaginate) g = tb(a); else if (0 !== n.ext.feature.length) { i = n.ext.feature; q = 0; for (m = i.length; q < m; q++)if (j == i[q].cFeature) { g = i[q].fnInit(a); break } } g && (i = a.aanFeatures, i[j] || (i[j] = []), i[j].push(g), e.append(g))
} c.replaceWith(e); a.nHolding = null
} function ea(a, b) {
var c = h(b).children("tr"), d, e, f, g, j, i, m, l, q, k; a.splice(0, a.length); f = 0; for (i = c.length; f < i; f++)a.push([]); f = 0; for (i = c.length; f <
i; f++) { d = c[f]; for (e = d.firstChild; e;) { if ("TD" == e.nodeName.toUpperCase() || "TH" == e.nodeName.toUpperCase()) { l = 1 * e.getAttribute("colspan"); q = 1 * e.getAttribute("rowspan"); l = !l || 0 === l || 1 === l ? 1 : l; q = !q || 0 === q || 1 === q ? 1 : q; g = 0; for (j = a[f]; j[g];)g++; m = g; k = 1 === l ? !0 : !1; for (j = 0; j < l; j++)for (g = 0; g < q; g++)a[f + g][m + j] = { cell: e, unique: k }, a[f + g].nTr = d } e = e.nextSibling } }
} function ra(a, b, c) {
var d = []; c || (c = a.aoHeader, b && (c = [], ea(c, b))); for (var b = 0, e = c.length; b < e; b++)for (var f = 0, g = c[b].length; f < g; f++)if (c[b][f].unique && (!d[f] ||
!a.bSortCellsTop)) d[f] = c[b][f].cell; return d
} function sa(a, b, c) {
r(a, "aoServerParams", "serverParams", [b]); if (b && h.isArray(b)) { var d = {}, e = /(.*?)\[\]$/; h.each(b, function (a, b) { var c = b.name.match(e); c ? (c = c[0], d[c] || (d[c] = []), d[c].push(b.value)) : d[b.name] = b.value }); b = d } var f, g = a.ajax, j = a.oInstance, i = function (b) { r(a, null, "xhr", [a, b, a.jqXHR]); c(b) }; if (h.isPlainObject(g) && g.data) { f = g.data; var m = "function" === typeof f ? f(b, a) : f, b = "function" === typeof f && m ? m : h.extend(!0, b, m); delete g.data } m = {
data: b, success: function (b) {
var c =
b.error || b.sError; c && K(a, 0, c); a.json = b; i(b)
}, dataType: "json", cache: !1, type: a.sServerMethod, error: function (b, c) { var d = r(a, null, "xhr", [a, null, a.jqXHR]); -1 === h.inArray(!0, d) && ("parsererror" == c ? K(a, 0, "Invalid JSON response", 1) : 4 === b.readyState && K(a, 0, "Ajax error", 7)); C(a, !1) }
}; a.oAjaxData = b; r(a, null, "preXhr", [a, b]); a.fnServerData ? a.fnServerData.call(j, a.sAjaxSource, h.map(b, function (a, b) { return { name: b, value: a } }), i, a) : a.sAjaxSource || "string" === typeof g ? a.jqXHR = h.ajax(h.extend(m, { url: g || a.sAjaxSource })) :
"function" === typeof g ? a.jqXHR = g.call(j, b, i, a) : (a.jqXHR = h.ajax(h.extend(m, g)), g.data = f)
} function lb(a) { return a.bAjaxDataGet ? (a.iDraw++ , C(a, !0), sa(a, ub(a), function (b) { vb(a, b) }), !1) : !0 } function ub(a) {
var b = a.aoColumns, c = b.length, d = a.oFeatures, e = a.oPreviousSearch, f = a.aoPreSearchCols, g, j = [], i, m, l, k = X(a); g = a._iDisplayStart; i = !1 !== d.bPaginate ? a._iDisplayLength : -1; var t = function (a, b) { j.push({ name: a, value: b }) }; t("sEcho", a.iDraw); t("iColumns", c); t("sColumns", D(b, "sName").join(",")); t("iDisplayStart", g); t("iDisplayLength",
i); var G = { draw: a.iDraw, columns: [], order: [], start: g, length: i, search: { value: e.sSearch, regex: e.bRegex } }; for (g = 0; g < c; g++)m = b[g], l = f[g], i = "function" == typeof m.mData ? "function" : m.mData, G.columns.push({ data: i, name: m.sName, searchable: m.bSearchable, orderable: m.bSortable, search: { value: l.sSearch, regex: l.bRegex } }), t("mDataProp_" + g, i), d.bFilter && (t("sSearch_" + g, l.sSearch), t("bRegex_" + g, l.bRegex), t("bSearchable_" + g, m.bSearchable)), d.bSort && t("bSortable_" + g, m.bSortable); d.bFilter && (t("sSearch", e.sSearch), t("bRegex",
e.bRegex)); d.bSort && (h.each(k, function (a, b) { G.order.push({ column: b.col, dir: b.dir }); t("iSortCol_" + a, b.col); t("sSortDir_" + a, b.dir) }), t("iSortingCols", k.length)); b = n.ext.legacy.ajax; return null === b ? a.sAjaxSource ? j : G : b ? j : G
} function vb(a, b) {
var c = ta(a, b), d = b.sEcho !== k ? b.sEcho : b.draw, e = b.iTotalRecords !== k ? b.iTotalRecords : b.recordsTotal, f = b.iTotalDisplayRecords !== k ? b.iTotalDisplayRecords : b.recordsFiltered; if (d) { if (1 * d < a.iDraw) return; a.iDraw = 1 * d } oa(a); a._iRecordsTotal = parseInt(e, 10); a._iRecordsDisplay = parseInt(f,
10); d = 0; for (e = c.length; d < e; d++)O(a, c[d]); a.aiDisplay = a.aiDisplayMaster.slice(); a.bAjaxDataGet = !1; P(a); a._bInitComplete || ua(a, b); a.bAjaxDataGet = !0; C(a, !1)
} function ta(a, b) { var c = h.isPlainObject(a.ajax) && a.ajax.dataSrc !== k ? a.ajax.dataSrc : a.sAjaxDataProp; return "data" === c ? b.aaData || b[c] : "" !== c ? S(c)(b) : b } function pb(a) {
var b = a.oClasses, c = a.sTableId, d = a.oLanguage, e = a.oPreviousSearch, f = a.aanFeatures, g = '
', j = d.sSearch, j = j.match(/_INPUT_/) ? j.replace("_INPUT_",
g) : j + g, b = h("
", { id: !f.f ? c + "_filter" : null, "class": b.sFilter }).append(h("
").append(j)), f = function () { var b = !this.value ? "" : this.value; b != e.sSearch && (ga(a, { sSearch: b, bRegex: e.bRegex, bSmart: e.bSmart, bCaseInsensitive: e.bCaseInsensitive }), a._iDisplayStart = 0, P(a)) }, g = null !== a.searchDelay ? a.searchDelay : "ssp" === y(a) ? 400 : 0, i = h("input", b).val(e.sSearch).attr("placeholder", d.sSearchPlaceholder).on("keyup.DT search.DT input.DT paste.DT cut.DT", g ? Oa(f, g) : f).on("keypress.DT", function (a) { if (13 == a.keyCode) return !1 }).attr("aria-controls",
c); h(a.nTable).on("search.dt.DT", function (b, c) { if (a === c) try { i[0] !== H.activeElement && i.val(e.sSearch) } catch (d) { } }); return b[0]
} function ga(a, b, c) {
var d = a.oPreviousSearch, e = a.aoPreSearchCols, f = function (a) { d.sSearch = a.sSearch; d.bRegex = a.bRegex; d.bSmart = a.bSmart; d.bCaseInsensitive = a.bCaseInsensitive }; Ga(a); if ("ssp" != y(a)) {
wb(a, b.sSearch, c, b.bEscapeRegex !== k ? !b.bEscapeRegex : b.bRegex, b.bSmart, b.bCaseInsensitive); f(b); for (b = 0; b < e.length; b++)xb(a, e[b].sSearch, b, e[b].bEscapeRegex !== k ? !e[b].bEscapeRegex : e[b].bRegex,
e[b].bSmart, e[b].bCaseInsensitive); yb(a)
} else f(b); a.bFiltered = !0; r(a, null, "search", [a])
} function yb(a) { for (var b = n.ext.search, c = a.aiDisplay, d, e, f = 0, g = b.length; f < g; f++) { for (var j = [], i = 0, m = c.length; i < m; i++)e = c[i], d = a.aoData[e], b[f](a, d._aFilterData, e, d._aData, i) && j.push(e); c.length = 0; h.merge(c, j) } } function xb(a, b, c, d, e, f) { if ("" !== b) { for (var g = [], j = a.aiDisplay, d = Pa(b, d, e, f), e = 0; e < j.length; e++)b = a.aoData[j[e]]._aFilterData[c], d.test(b) && g.push(j[e]); a.aiDisplay = g } } function wb(a, b, c, d, e, f) {
var d = Pa(b,
d, e, f), f = a.oPreviousSearch.sSearch, g = a.aiDisplayMaster, j, e = []; 0 !== n.ext.search.length && (c = !0); j = zb(a); if (0 >= b.length) a.aiDisplay = g.slice(); else { if (j || c || f.length > b.length || 0 !== b.indexOf(f) || a.bSorted) a.aiDisplay = g.slice(); b = a.aiDisplay; for (c = 0; c < b.length; c++)d.test(a.aoData[b[c]]._sFilterRow) && e.push(b[c]); a.aiDisplay = e }
} function Pa(a, b, c, d) {
a = b ? a : Qa(a); c && (a = "^(?=.*?" + h.map(a.match(/"[^"]+"|[^ ]+/g) || [""], function (a) {
if ('"' === a.charAt(0)) var b = a.match(/^"(.*)"$/), a = b ? b[1] : a; return a.replace('"',
"")
}).join(")(?=.*?") + ").*$"); return RegExp(a, d ? "i" : "")
} function zb(a) {
var b = a.aoColumns, c, d, e, f, g, j, i, h, l = n.ext.type.search; c = !1; d = 0; for (f = a.aoData.length; d < f; d++)if (h = a.aoData[d], !h._aFilterData) {
j = []; e = 0; for (g = b.length; e < g; e++)c = b[e], c.bSearchable ? (i = B(a, d, e, "filter"), l[c.sType] && (i = l[c.sType](i)), null === i && (i = ""), "string" !== typeof i && i.toString && (i = i.toString())) : i = "", i.indexOf && -1 !== i.indexOf("&") && (va.innerHTML = i, i = Wb ? va.textContent : va.innerText), i.replace && (i = i.replace(/[\r\n]/g, "")), j.push(i);
h._aFilterData = j; h._sFilterRow = j.join(" "); c = !0
} return c
} function Ab(a) { return { search: a.sSearch, smart: a.bSmart, regex: a.bRegex, caseInsensitive: a.bCaseInsensitive } } function Bb(a) { return { sSearch: a.search, bSmart: a.smart, bRegex: a.regex, bCaseInsensitive: a.caseInsensitive } } function sb(a) {
var b = a.sTableId, c = a.aanFeatures.i, d = h("
", { "class": a.oClasses.sInfo, id: !c ? b + "_info" : null }); c || (a.aoDrawCallback.push({ fn: Cb, sName: "information" }), d.attr("role", "status").attr("aria-live", "polite"), h(a.nTable).attr("aria-describedby",
b + "_info")); return d[0]
} function Cb(a) { var b = a.aanFeatures.i; if (0 !== b.length) { var c = a.oLanguage, d = a._iDisplayStart + 1, e = a.fnDisplayEnd(), f = a.fnRecordsTotal(), g = a.fnRecordsDisplay(), j = g ? c.sInfo : c.sInfoEmpty; g !== f && (j += " " + c.sInfoFiltered); j += c.sInfoPostFix; j = Db(a, j); c = c.fnInfoCallback; null !== c && (j = c.call(a.oInstance, a, d, e, f, g, j)); h(b).html(j) } } function Db(a, b) {
var c = a.fnFormatNumber, d = a._iDisplayStart + 1, e = a._iDisplayLength, f = a.fnRecordsDisplay(), g = -1 === e; return b.replace(/_START_/g, c.call(a, d)).replace(/_END_/g,
c.call(a, a.fnDisplayEnd())).replace(/_MAX_/g, c.call(a, a.fnRecordsTotal())).replace(/_TOTAL_/g, c.call(a, f)).replace(/_PAGE_/g, c.call(a, g ? 1 : Math.ceil(d / e))).replace(/_PAGES_/g, c.call(a, g ? 1 : Math.ceil(f / e)))
} function ha(a) {
var b, c, d = a.iInitDisplayStart, e = a.aoColumns, f; c = a.oFeatures; var g = a.bDeferLoading; if (a.bInitialised) {
nb(a); kb(a); fa(a, a.aoHeader); fa(a, a.aoFooter); C(a, !0); c.bAutoWidth && Fa(a); b = 0; for (c = e.length; b < c; b++)f = e[b], f.sWidth && (f.nTh.style.width = v(f.sWidth)); r(a, null, "preInit", [a]); T(a); e =
y(a); if ("ssp" != e || g) "ajax" == e ? sa(a, [], function (c) { var f = ta(a, c); for (b = 0; b < f.length; b++)O(a, f[b]); a.iInitDisplayStart = d; T(a); C(a, !1); ua(a, c) }, a) : (C(a, !1), ua(a))
} else setTimeout(function () { ha(a) }, 200)
} function ua(a, b) { a._bInitComplete = !0; (b || a.oInit.aaData) && $(a); r(a, null, "plugin-init", [a, b]); r(a, "aoInitComplete", "init", [a, b]) } function Ra(a, b) { var c = parseInt(b, 10); a._iDisplayLength = c; Sa(a); r(a, null, "length", [a, c]) } function ob(a) {
for (var b = a.oClasses, c = a.sTableId, d = a.aLengthMenu, e = h.isArray(d[0]), f =
e ? d[0] : d, d = e ? d[1] : d, e = h("
", { name: c + "_length", "aria-controls": c, "class": b.sLengthSelect }), g = 0, j = f.length; g < j; g++)e[0][g] = new Option("number" === typeof d[g] ? a.fnFormatNumber(d[g]) : d[g], f[g]); var i = h("
").addClass(b.sLength); a.aanFeatures.l || (i[0].id = c + "_length"); i.children().append(a.oLanguage.sLengthMenu.replace("_MENU_", e[0].outerHTML)); h("select", i).val(a._iDisplayLength).on("change.DT", function () { Ra(a, h(this).val()); P(a) }); h(a.nTable).on("length.dt.DT", function (b, c, d) {
a ===
c && h("select", i).val(d)
}); return i[0]
} function tb(a) {
var b = a.sPaginationType, c = n.ext.pager[b], d = "function" === typeof c, e = function (a) { P(a) }, b = h("
").addClass(a.oClasses.sPaging + b)[0], f = a.aanFeatures; d || c.fnInit(a, b, e); f.p || (b.id = a.sTableId + "_paginate", a.aoDrawCallback.push({
fn: function (a) {
if (d) { var b = a._iDisplayStart, i = a._iDisplayLength, h = a.fnRecordsDisplay(), l = -1 === i, b = l ? 0 : Math.ceil(b / i), i = l ? 1 : Math.ceil(h / i), h = c(b, i), k, l = 0; for (k = f.p.length; l < k; l++)Na(a, "pageButton")(a, f.p[l], l, h, b, i) } else c.fnUpdate(a,
e)
}, sName: "pagination"
})); return b
} function Ta(a, b, c) { var d = a._iDisplayStart, e = a._iDisplayLength, f = a.fnRecordsDisplay(); 0 === f || -1 === e ? d = 0 : "number" === typeof b ? (d = b * e, d > f && (d = 0)) : "first" == b ? d = 0 : "previous" == b ? (d = 0 <= e ? d - e : 0, 0 > d && (d = 0)) : "next" == b ? d + e < f && (d += e) : "last" == b ? d = Math.floor((f - 1) / e) * e : K(a, 0, "Unknown paging action: " + b, 5); b = a._iDisplayStart !== d; a._iDisplayStart = d; b && (r(a, null, "page", [a]), c && P(a)); return b } function qb(a) { return h("
", { id: !a.aanFeatures.r ? a.sTableId + "_processing" : null, "class": a.oClasses.sProcessing }).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0] }
function C(a, b) { a.oFeatures.bProcessing && h(a.aanFeatures.r).css("display", b ? "block" : "none"); r(a, null, "processing", [a, b]) } function rb(a) {
var b = h(a.nTable); b.attr("role", "grid"); var c = a.oScroll; if ("" === c.sX && "" === c.sY) return a.nTable; var d = c.sX, e = c.sY, f = a.oClasses, g = b.children("caption"), j = g.length ? g[0]._captionSide : null, i = h(b[0].cloneNode(!1)), m = h(b[0].cloneNode(!1)), l = b.children("tfoot"); l.length || (l = null); i = h("
", { "class": f.sScrollWrapper }).append(h("
", { "class": f.sScrollHead }).css({
overflow: "hidden",
position: "relative", border: 0, width: d ? !d ? null : v(d) : "100%"
}).append(h("
", { "class": f.sScrollHeadInner }).css({ "box-sizing": "content-box", width: c.sXInner || "100%" }).append(i.removeAttr("id").css("margin-left", 0).append("top" === j ? g : null).append(b.children("thead"))))).append(h("
", { "class": f.sScrollBody }).css({ position: "relative", overflow: "auto", width: !d ? null : v(d) }).append(b)); l && i.append(h("
", { "class": f.sScrollFoot }).css({ overflow: "hidden", border: 0, width: d ? !d ? null : v(d) : "100%" }).append(h("
",
{ "class": f.sScrollFootInner }).append(m.removeAttr("id").css("margin-left", 0).append("bottom" === j ? g : null).append(b.children("tfoot"))))); var b = i.children(), k = b[0], f = b[1], t = l ? b[2] : null; if (d) h(f).on("scroll.DT", function () { var a = this.scrollLeft; k.scrollLeft = a; l && (t.scrollLeft = a) }); h(f).css(e && c.bCollapse ? "max-height" : "height", e); a.nScrollHead = k; a.nScrollBody = f; a.nScrollFoot = t; a.aoDrawCallback.push({ fn: la, sName: "scrolling" }); return i[0]
} function la(a) {
var b = a.oScroll, c = b.sX, d = b.sXInner, e = b.sY, b = b.iBarWidth,
f = h(a.nScrollHead), g = f[0].style, j = f.children("div"), i = j[0].style, m = j.children("table"), j = a.nScrollBody, l = h(j), q = j.style, t = h(a.nScrollFoot).children("div"), n = t.children("table"), o = h(a.nTHead), p = h(a.nTable), s = p[0], r = s.style, u = a.nTFoot ? h(a.nTFoot) : null, x = a.oBrowser, U = x.bScrollOversize, Xb = D(a.aoColumns, "nTh"), Q, L, R, w, Ua = [], y = [], z = [], A = [], B, C = function (a) { a = a.style; a.paddingTop = "0"; a.paddingBottom = "0"; a.borderTopWidth = "0"; a.borderBottomWidth = "0"; a.height = 0 }; L = j.scrollHeight > j.clientHeight; if (a.scrollBarVis !==
L && a.scrollBarVis !== k) a.scrollBarVis = L, $(a); else {
a.scrollBarVis = L; p.children("thead, tfoot").remove(); u && (R = u.clone().prependTo(p), Q = u.find("tr"), R = R.find("tr")); w = o.clone().prependTo(p); o = o.find("tr"); L = w.find("tr"); w.find("th, td").removeAttr("tabindex"); c || (q.width = "100%", f[0].style.width = "100%"); h.each(ra(a, w), function (b, c) { B = aa(a, b); c.style.width = a.aoColumns[B].sWidth }); u && I(function (a) { a.style.width = "" }, R); f = p.outerWidth(); if ("" === c) {
r.width = "100%"; if (U && (p.find("tbody").height() > j.offsetHeight ||
"scroll" == l.css("overflow-y"))) r.width = v(p.outerWidth() - b); f = p.outerWidth()
} else "" !== d && (r.width = v(d), f = p.outerWidth()); I(C, L); I(function (a) { z.push(a.innerHTML); Ua.push(v(h(a).css("width"))) }, L); I(function (a, b) { if (h.inArray(a, Xb) !== -1) a.style.width = Ua[b] }, o); h(L).height(0); u && (I(C, R), I(function (a) { A.push(a.innerHTML); y.push(v(h(a).css("width"))) }, R), I(function (a, b) { a.style.width = y[b] }, Q), h(R).height(0)); I(function (a, b) {
a.innerHTML = '
' + z[b] + "
"; a.childNodes[0].style.height =
"0"; a.childNodes[0].style.overflow = "hidden"; a.style.width = Ua[b]
}, L); u && I(function (a, b) { a.innerHTML = '
' + A[b] + "
"; a.childNodes[0].style.height = "0"; a.childNodes[0].style.overflow = "hidden"; a.style.width = y[b] }, R); if (p.outerWidth() < f) { Q = j.scrollHeight > j.offsetHeight || "scroll" == l.css("overflow-y") ? f + b : f; if (U && (j.scrollHeight > j.offsetHeight || "scroll" == l.css("overflow-y"))) r.width = v(Q - b); ("" === c || "" !== d) && K(a, 1, "Possible column misalignment", 6) } else Q = "100%"; q.width = v(Q);
g.width = v(Q); u && (a.nScrollFoot.style.width = v(Q)); !e && U && (q.height = v(s.offsetHeight + b)); c = p.outerWidth(); m[0].style.width = v(c); i.width = v(c); d = p.height() > j.clientHeight || "scroll" == l.css("overflow-y"); e = "padding" + (x.bScrollbarLeft ? "Left" : "Right"); i[e] = d ? b + "px" : "0px"; u && (n[0].style.width = v(c), t[0].style.width = v(c), t[0].style[e] = d ? b + "px" : "0px"); p.children("colgroup").insertBefore(p.children("thead")); l.scroll(); if ((a.bSorted || a.bFiltered) && !a._drawHold) j.scrollTop = 0
}
} function I(a, b, c) {
for (var d = 0, e = 0,
f = b.length, g, j; e < f;) { g = b[e].firstChild; for (j = c ? c[e].firstChild : null; g;)1 === g.nodeType && (c ? a(g, j, d) : a(g, d), d++), g = g.nextSibling, j = c ? j.nextSibling : null; e++ }
} function Fa(a) {
var b = a.nTable, c = a.aoColumns, d = a.oScroll, e = d.sY, f = d.sX, g = d.sXInner, j = c.length, i = ma(a, "bVisible"), m = h("th", a.nTHead), l = b.getAttribute("width"), k = b.parentNode, t = !1, n, o, p = a.oBrowser, d = p.bScrollOversize; (n = b.style.width) && -1 !== n.indexOf("%") && (l = n); for (n = 0; n < i.length; n++)o = c[i[n]], null !== o.sWidth && (o.sWidth = Eb(o.sWidthOrig, k), t = !0); if (d ||
!t && !f && !e && j == V(a) && j == m.length) for (n = 0; n < j; n++)i = aa(a, n), null !== i && (c[i].sWidth = v(m.eq(n).width())); else {
j = h(b).clone().css("visibility", "hidden").removeAttr("id"); j.find("tbody tr").remove(); var s = h("
").appendTo(j.find("tbody")); j.find("thead, tfoot").remove(); j.append(h(a.nTHead).clone()).append(h(a.nTFoot).clone()); j.find("tfoot th, tfoot td").css("width", ""); m = ra(a, j.find("thead")[0]); for (n = 0; n < i.length; n++)o = c[i[n]], m[n].style.width = null !== o.sWidthOrig && "" !== o.sWidthOrig ? v(o.sWidthOrig) :
"", o.sWidthOrig && f && h(m[n]).append(h("
").css({ width: o.sWidthOrig, margin: 0, padding: 0, border: 0, height: 1 })); if (a.aoData.length) for (n = 0; n < i.length; n++)t = i[n], o = c[t], h(Fb(a, t)).clone(!1).append(o.sContentPadding).appendTo(s); h("[name]", j).removeAttr("name"); o = h("
").css(f || e ? { position: "absolute", top: 0, left: 0, height: 1, right: 0, overflow: "hidden" } : {}).append(j).appendTo(k); f && g ? j.width(g) : f ? (j.css("width", "auto"), j.removeAttr("width"), j.width() < k.clientWidth && l && j.width(k.clientWidth)) : e ? j.width(k.clientWidth) :
l && j.width(l); for (n = e = 0; n < i.length; n++)k = h(m[n]), g = k.outerWidth() - k.width(), k = p.bBounding ? Math.ceil(m[n].getBoundingClientRect().width) : k.outerWidth(), e += k, c[i[n]].sWidth = v(k - g); b.style.width = v(e); o.remove()
} l && (b.style.width = v(l)); if ((l || f) && !a._reszEvt) b = function () { h(E).on("resize.DT-" + a.sInstance, Oa(function () { $(a) })) }, d ? setTimeout(b, 1E3) : b(), a._reszEvt = !0
} function Eb(a, b) { if (!a) return 0; var c = h("
").css("width", v(a)).appendTo(b || H.body), d = c[0].offsetWidth; c.remove(); return d } function Fb(a,
b) { var c = Gb(a, b); if (0 > c) return null; var d = a.aoData[c]; return !d.nTr ? h("
").html(B(a, c, b, "display"))[0] : d.anCells[b] } function Gb(a, b) { for (var c, d = -1, e = -1, f = 0, g = a.aoData.length; f < g; f++)c = B(a, f, b, "display") + "", c = c.replace(Yb, ""), c = c.replace(/ /g, " "), c.length > d && (d = c.length, e = f); return e } function v(a) { return null === a ? "0px" : "number" == typeof a ? 0 > a ? "0px" : a + "px" : a.match(/\d$/) ? a + "px" : a } function X(a) {
var b, c, d = [], e = a.aoColumns, f, g, j, i; b = a.aaSortingFixed; c = h.isPlainObject(b); var m = []; f = function (a) {
a.length &&
!h.isArray(a[0]) ? m.push(a) : h.merge(m, a)
}; h.isArray(b) && f(b); c && b.pre && f(b.pre); f(a.aaSorting); c && b.post && f(b.post); for (a = 0; a < m.length; a++) { i = m[a][0]; f = e[i].aDataSort; b = 0; for (c = f.length; b < c; b++)g = f[b], j = e[g].sType || "string", m[a]._idx === k && (m[a]._idx = h.inArray(m[a][1], e[g].asSorting)), d.push({ src: i, col: g, dir: m[a][1], index: m[a]._idx, type: j, formatter: n.ext.type.order[j + "-pre"] }) } return d
} function mb(a) {
var b, c, d = [], e = n.ext.type.order, f = a.aoData, g = 0, j, i = a.aiDisplayMaster, h; Ga(a); h = X(a); b = 0; for (c = h.length; b <
c; b++)j = h[b], j.formatter && g++ , Hb(a, j.col); if ("ssp" != y(a) && 0 !== h.length) {
b = 0; for (c = i.length; b < c; b++)d[i[b]] = b; g === h.length ? i.sort(function (a, b) { var c, e, g, j, i = h.length, k = f[a]._aSortData, n = f[b]._aSortData; for (g = 0; g < i; g++)if (j = h[g], c = k[j.col], e = n[j.col], c = c < e ? -1 : c > e ? 1 : 0, 0 !== c) return "asc" === j.dir ? c : -c; c = d[a]; e = d[b]; return c < e ? -1 : c > e ? 1 : 0 }) : i.sort(function (a, b) {
var c, g, j, i, k = h.length, n = f[a]._aSortData, o = f[b]._aSortData; for (j = 0; j < k; j++)if (i = h[j], c = n[i.col], g = o[i.col], i = e[i.type + "-" + i.dir] || e["string-" + i.dir],
c = i(c, g), 0 !== c) return c; c = d[a]; g = d[b]; return c < g ? -1 : c > g ? 1 : 0
})
} a.bSorted = !0
} function Ib(a) { for (var b, c, d = a.aoColumns, e = X(a), a = a.oLanguage.oAria, f = 0, g = d.length; f < g; f++) { c = d[f]; var j = c.asSorting; b = c.sTitle.replace(/<.*?>/g, ""); var i = c.nTh; i.removeAttribute("aria-sort"); c.bSortable && (0 < e.length && e[0].col == f ? (i.setAttribute("aria-sort", "asc" == e[0].dir ? "ascending" : "descending"), c = j[e[0].index + 1] || j[0]) : c = j[0], b += "asc" === c ? a.sSortAscending : a.sSortDescending); i.setAttribute("aria-label", b) } } function Va(a,
b, c, d) {
var e = a.aaSorting, f = a.aoColumns[b].asSorting, g = function (a, b) { var c = a._idx; c === k && (c = h.inArray(a[1], f)); return c + 1 < f.length ? c + 1 : b ? null : 0 }; "number" === typeof e[0] && (e = a.aaSorting = [e]); c && a.oFeatures.bSortMulti ? (c = h.inArray(b, D(e, "0")), -1 !== c ? (b = g(e[c], !0), null === b && 1 === e.length && (b = 0), null === b ? e.splice(c, 1) : (e[c][1] = f[b], e[c]._idx = b)) : (e.push([b, f[0], 0]), e[e.length - 1]._idx = 0)) : e.length && e[0][0] == b ? (b = g(e[0]), e.length = 1, e[0][1] = f[b], e[0]._idx = b) : (e.length = 0, e.push([b, f[0]]), e[0]._idx = 0); T(a); "function" ==
typeof d && d(a)
} function Ma(a, b, c, d) { var e = a.aoColumns[c]; Wa(b, {}, function (b) { !1 !== e.bSortable && (a.oFeatures.bProcessing ? (C(a, !0), setTimeout(function () { Va(a, c, b.shiftKey, d); "ssp" !== y(a) && C(a, !1) }, 0)) : Va(a, c, b.shiftKey, d)) }) } function wa(a) {
var b = a.aLastSort, c = a.oClasses.sSortColumn, d = X(a), e = a.oFeatures, f, g; if (e.bSort && e.bSortClasses) {
e = 0; for (f = b.length; e < f; e++)g = b[e].src, h(D(a.aoData, "anCells", g)).removeClass(c + (2 > e ? e + 1 : 3)); e = 0; for (f = d.length; e < f; e++)g = d[e].src, h(D(a.aoData, "anCells", g)).addClass(c +
(2 > e ? e + 1 : 3))
} a.aLastSort = d
} function Hb(a, b) { var c = a.aoColumns[b], d = n.ext.order[c.sSortDataType], e; d && (e = d.call(a.oInstance, a, b, ba(a, b))); for (var f, g = n.ext.type.order[c.sType + "-pre"], j = 0, i = a.aoData.length; j < i; j++)if (c = a.aoData[j], c._aSortData || (c._aSortData = []), !c._aSortData[b] || d) f = d ? e[j] : B(a, j, b, "sort"), c._aSortData[b] = g ? g(f) : f } function xa(a) {
if (a.oFeatures.bStateSave && !a.bDestroying) {
var b = {
time: +new Date, start: a._iDisplayStart, length: a._iDisplayLength, order: h.extend(!0, [], a.aaSorting), search: Ab(a.oPreviousSearch),
columns: h.map(a.aoColumns, function (b, d) { return { visible: b.bVisible, search: Ab(a.aoPreSearchCols[d]) } })
}; r(a, "aoStateSaveParams", "stateSaveParams", [a, b]); a.oSavedState = b; a.fnStateSaveCallback.call(a.oInstance, a, b)
}
} function Jb(a, b, c) {
var d, e, f = a.aoColumns, b = function (b) {
if (b && b.time) {
var g = r(a, "aoStateLoadParams", "stateLoadParams", [a, b]); if (-1 === h.inArray(!1, g) && (g = a.iStateDuration, !(0 < g && b.time < +new Date - 1E3 * g) && !(b.columns && f.length !== b.columns.length))) {
a.oLoadedState = h.extend(!0, {}, b); b.start !== k &&
(a._iDisplayStart = b.start, a.iInitDisplayStart = b.start); b.length !== k && (a._iDisplayLength = b.length); b.order !== k && (a.aaSorting = [], h.each(b.order, function (b, c) { a.aaSorting.push(c[0] >= f.length ? [0, c[1]] : c) })); b.search !== k && h.extend(a.oPreviousSearch, Bb(b.search)); if (b.columns) { d = 0; for (e = b.columns.length; d < e; d++)g = b.columns[d], g.visible !== k && (f[d].bVisible = g.visible), g.search !== k && h.extend(a.aoPreSearchCols[d], Bb(g.search)) } r(a, "aoStateLoaded", "stateLoaded", [a, b])
}
} c()
}; if (a.oFeatures.bStateSave) {
var g =
a.fnStateLoadCallback.call(a.oInstance, a, b); g !== k && b(g)
} else c()
} function ya(a) { var b = n.settings, a = h.inArray(a, D(b, "nTable")); return -1 !== a ? b[a] : null } function K(a, b, c, d) {
c = "DataTables warning: " + (a ? "table id=" + a.sTableId + " - " : "") + c; d && (c += ". For more information about this error, please see http://datatables.net/tn/" + d); if (b) E.console && console.log && console.log(c); else if (b = n.ext, b = b.sErrMode || b.errMode, a && r(a, null, "error", [a, d, c]), "alert" == b) alert(c); else {
if ("throw" == b) throw Error(c); "function" ==
typeof b && b(a, d, c)
}
} function F(a, b, c, d) { h.isArray(c) ? h.each(c, function (c, d) { h.isArray(d) ? F(a, b, d[0], d[1]) : F(a, b, d) }) : (d === k && (d = c), b[c] !== k && (a[d] = b[c])) } function Xa(a, b, c) { var d, e; for (e in b) b.hasOwnProperty(e) && (d = b[e], h.isPlainObject(d) ? (h.isPlainObject(a[e]) || (a[e] = {}), h.extend(!0, a[e], d)) : a[e] = c && "data" !== e && "aaData" !== e && h.isArray(d) ? d.slice() : d); return a } function Wa(a, b, c) {
h(a).on("click.DT", b, function (b) { h(a).blur(); c(b) }).on("keypress.DT", b, function (a) { 13 === a.which && (a.preventDefault(), c(a)) }).on("selectstart.DT",
function () { return !1 })
} function z(a, b, c, d) { c && a[b].push({ fn: c, sName: d }) } function r(a, b, c, d) { var e = []; b && (e = h.map(a[b].slice().reverse(), function (b) { return b.fn.apply(a.oInstance, d) })); null !== c && (b = h.Event(c + ".dt"), h(a.nTable).trigger(b, d), e.push(b.result)); return e } function Sa(a) { var b = a._iDisplayStart, c = a.fnDisplayEnd(), d = a._iDisplayLength; b >= c && (b = c - d); b -= b % d; if (-1 === d || 0 > b) b = 0; a._iDisplayStart = b } function Na(a, b) {
var c = a.renderer, d = n.ext.renderer[b]; return h.isPlainObject(c) && c[b] ? d[c[b]] || d._ : "string" ===
typeof c ? d[c] || d._ : d._
} function y(a) { return a.oFeatures.bServerSide ? "ssp" : a.ajax || a.sAjaxSource ? "ajax" : "dom" } function ia(a, b) { var c = [], c = Kb.numbers_length, d = Math.floor(c / 2); b <= c ? c = Y(0, b) : a <= d ? (c = Y(0, c - 2), c.push("ellipsis"), c.push(b - 1)) : (a >= b - 1 - d ? c = Y(b - (c - 2), b) : (c = Y(a - d + 2, a + d - 1), c.push("ellipsis"), c.push(b - 1)), c.splice(0, 0, "ellipsis"), c.splice(0, 0, 0)); c.DT_el = "span"; return c } function Da(a) {
h.each({
num: function (b) { return za(b, a) }, "num-fmt": function (b) { return za(b, a, Ya) }, "html-num": function (b) {
return za(b,
a, Aa)
}, "html-num-fmt": function (b) { return za(b, a, Aa, Ya) }
}, function (b, c) { x.type.order[b + a + "-pre"] = c; b.match(/^html\-/) && (x.type.search[b + a] = x.type.search.html) })
} function Lb(a) { return function () { var b = [ya(this[n.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments)); return n.ext.internal[a].apply(this, b) } } var n = function (a) {
this.$ = function (a, b) { return this.api(!0).$(a, b) }; this._ = function (a, b) { return this.api(!0).rows(a, b).data() }; this.api = function (a) { return a ? new s(ya(this[x.iApiIndex])) : new s(this) };
this.fnAddData = function (a, b) { var c = this.api(!0), d = h.isArray(a) && (h.isArray(a[0]) || h.isPlainObject(a[0])) ? c.rows.add(a) : c.row.add(a); (b === k || b) && c.draw(); return d.flatten().toArray() }; this.fnAdjustColumnSizing = function (a) { var b = this.api(!0).columns.adjust(), c = b.settings()[0], d = c.oScroll; a === k || a ? b.draw(!1) : ("" !== d.sX || "" !== d.sY) && la(c) }; this.fnClearTable = function (a) { var b = this.api(!0).clear(); (a === k || a) && b.draw() }; this.fnClose = function (a) { this.api(!0).row(a).child.hide() }; this.fnDeleteRow = function (a,
b, c) { var d = this.api(!0), a = d.rows(a), e = a.settings()[0], h = e.aoData[a[0][0]]; a.remove(); b && b.call(this, e, h); (c === k || c) && d.draw(); return h }; this.fnDestroy = function (a) { this.api(!0).destroy(a) }; this.fnDraw = function (a) { this.api(!0).draw(a) }; this.fnFilter = function (a, b, c, d, e, h) { e = this.api(!0); null === b || b === k ? e.search(a, c, d, h) : e.column(b).search(a, c, d, h); e.draw() }; this.fnGetData = function (a, b) {
var c = this.api(!0); if (a !== k) {
var d = a.nodeName ? a.nodeName.toLowerCase() : ""; return b !== k || "td" == d || "th" == d ? c.cell(a, b).data() :
c.row(a).data() || null
} return c.data().toArray()
}; this.fnGetNodes = function (a) { var b = this.api(!0); return a !== k ? b.row(a).node() : b.rows().nodes().flatten().toArray() }; this.fnGetPosition = function (a) { var b = this.api(!0), c = a.nodeName.toUpperCase(); return "TR" == c ? b.row(a).index() : "TD" == c || "TH" == c ? (a = b.cell(a).index(), [a.row, a.columnVisible, a.column]) : null }; this.fnIsOpen = function (a) { return this.api(!0).row(a).child.isShown() }; this.fnOpen = function (a, b, c) { return this.api(!0).row(a).child(b, c).show().child()[0] };
this.fnPageChange = function (a, b) { var c = this.api(!0).page(a); (b === k || b) && c.draw(!1) }; this.fnSetColumnVis = function (a, b, c) { a = this.api(!0).column(a).visible(b); (c === k || c) && a.columns.adjust().draw() }; this.fnSettings = function () { return ya(this[x.iApiIndex]) }; this.fnSort = function (a) { this.api(!0).order(a).draw() }; this.fnSortListener = function (a, b, c) { this.api(!0).order.listener(a, b, c) }; this.fnUpdate = function (a, b, c, d, e) {
var h = this.api(!0); c === k || null === c ? h.row(b).data(a) : h.cell(b, c).data(a); (e === k || e) && h.columns.adjust();
(d === k || d) && h.draw(); return 0
}; this.fnVersionCheck = x.fnVersionCheck; var b = this, c = a === k, d = this.length; c && (a = {}); this.oApi = this.internal = x.internal; for (var e in n.ext.internal) e && (this[e] = Lb(e)); this.each(function () {
var e = {}, g = 1 < d ? Xa(e, a, !0) : a, j = 0, i, e = this.getAttribute("id"), m = !1, l = n.defaults, q = h(this); if ("table" != this.nodeName.toLowerCase()) K(null, 0, "Non-table node initialisation (" + this.nodeName + ")", 2); else {
eb(l); fb(l.column); J(l, l, !0); J(l.column, l.column, !0); J(l, h.extend(g, q.data())); var t = n.settings,
j = 0; for (i = t.length; j < i; j++) { var o = t[j]; if (o.nTable == this || o.nTHead && o.nTHead.parentNode == this || o.nTFoot && o.nTFoot.parentNode == this) { var s = g.bRetrieve !== k ? g.bRetrieve : l.bRetrieve; if (c || s) return o.oInstance; if (g.bDestroy !== k ? g.bDestroy : l.bDestroy) { o.oInstance.fnDestroy(); break } else { K(o, 0, "Cannot reinitialise DataTable", 3); return } } if (o.sTableId == this.id) { t.splice(j, 1); break } } if (null === e || "" === e) this.id = e = "DataTables_Table_" + n.ext._unique++; var p = h.extend(!0, {}, n.models.oSettings, {
sDestroyWidth: q[0].style.width,
sInstance: e, sTableId: e
}); p.nTable = this; p.oApi = b.internal; p.oInit = g; t.push(p); p.oInstance = 1 === b.length ? b : q.dataTable(); eb(g); Ca(g.oLanguage); g.aLengthMenu && !g.iDisplayLength && (g.iDisplayLength = h.isArray(g.aLengthMenu[0]) ? g.aLengthMenu[0][0] : g.aLengthMenu[0]); g = Xa(h.extend(!0, {}, l), g); F(p.oFeatures, g, "bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" ")); F(p, g, ["asStripeClasses", "ajax", "fnServerData", "fnFormatNumber", "sServerMethod",
"aaSorting", "aaSortingFixed", "aLengthMenu", "sPaginationType", "sAjaxSource", "sAjaxDataProp", "iStateDuration", "sDom", "bSortCellsTop", "iTabIndex", "fnStateLoadCallback", "fnStateSaveCallback", "renderer", "searchDelay", "rowId", ["iCookieDuration", "iStateDuration"], ["oSearch", "oPreviousSearch"], ["aoSearchCols", "aoPreSearchCols"], ["iDisplayLength", "_iDisplayLength"]]); F(p.oScroll, g, [["sScrollX", "sX"], ["sScrollXInner", "sXInner"], ["sScrollY", "sY"], ["bScrollCollapse", "bCollapse"]]); F(p.oLanguage, g, "fnInfoCallback");
z(p, "aoDrawCallback", g.fnDrawCallback, "user"); z(p, "aoServerParams", g.fnServerParams, "user"); z(p, "aoStateSaveParams", g.fnStateSaveParams, "user"); z(p, "aoStateLoadParams", g.fnStateLoadParams, "user"); z(p, "aoStateLoaded", g.fnStateLoaded, "user"); z(p, "aoRowCallback", g.fnRowCallback, "user"); z(p, "aoRowCreatedCallback", g.fnCreatedRow, "user"); z(p, "aoHeaderCallback", g.fnHeaderCallback, "user"); z(p, "aoFooterCallback", g.fnFooterCallback, "user"); z(p, "aoInitComplete", g.fnInitComplete, "user"); z(p, "aoPreDrawCallback",
g.fnPreDrawCallback, "user"); p.rowIdFn = S(g.rowId); gb(p); var u = p.oClasses; h.extend(u, n.ext.classes, g.oClasses); q.addClass(u.sTable); p.iInitDisplayStart === k && (p.iInitDisplayStart = g.iDisplayStart, p._iDisplayStart = g.iDisplayStart); null !== g.iDeferLoading && (p.bDeferLoading = !0, e = h.isArray(g.iDeferLoading), p._iRecordsDisplay = e ? g.iDeferLoading[0] : g.iDeferLoading, p._iRecordsTotal = e ? g.iDeferLoading[1] : g.iDeferLoading); var v = p.oLanguage; h.extend(!0, v, g.oLanguage); v.sUrl && (h.ajax({
dataType: "json", url: v.sUrl, success: function (a) {
Ca(a);
J(l.oLanguage, a); h.extend(true, v, a); ha(p)
}, error: function () { ha(p) }
}), m = !0); null === g.asStripeClasses && (p.asStripeClasses = [u.sStripeOdd, u.sStripeEven]); var e = p.asStripeClasses, x = q.children("tbody").find("tr").eq(0); -1 !== h.inArray(!0, h.map(e, function (a) { return x.hasClass(a) })) && (h("tbody tr", this).removeClass(e.join(" ")), p.asDestroyStripes = e.slice()); e = []; t = this.getElementsByTagName("thead"); 0 !== t.length && (ea(p.aoHeader, t[0]), e = ra(p)); if (null === g.aoColumns) { t = []; j = 0; for (i = e.length; j < i; j++)t.push(null) } else t =
g.aoColumns; j = 0; for (i = t.length; j < i; j++)Ea(p, e ? e[j] : null); ib(p, g.aoColumnDefs, t, function (a, b) { ka(p, a, b) }); if (x.length) { var w = function (a, b) { return a.getAttribute("data-" + b) !== null ? b : null }; h(x[0]).children("th, td").each(function (a, b) { var c = p.aoColumns[a]; if (c.mData === a) { var d = w(b, "sort") || w(b, "order"), e = w(b, "filter") || w(b, "search"); if (d !== null || e !== null) { c.mData = { _: a + ".display", sort: d !== null ? a + ".@data-" + d : k, type: d !== null ? a + ".@data-" + d : k, filter: e !== null ? a + ".@data-" + e : k }; ka(p, a) } } }) } var U = p.oFeatures,
e = function () {
if (g.aaSorting === k) { var a = p.aaSorting; j = 0; for (i = a.length; j < i; j++)a[j][1] = p.aoColumns[j].asSorting[0] } wa(p); U.bSort && z(p, "aoDrawCallback", function () { if (p.bSorted) { var a = X(p), b = {}; h.each(a, function (a, c) { b[c.src] = c.dir }); r(p, null, "order", [p, a, b]); Ib(p) } }); z(p, "aoDrawCallback", function () { (p.bSorted || y(p) === "ssp" || U.bDeferRender) && wa(p) }, "sc"); var a = q.children("caption").each(function () { this._captionSide = h(this).css("caption-side") }), b = q.children("thead"); b.length === 0 && (b = h("
").appendTo(q));
p.nTHead = b[0]; b = q.children("tbody"); b.length === 0 && (b = h("
").appendTo(q)); p.nTBody = b[0]; b = q.children("tfoot"); if (b.length === 0 && a.length > 0 && (p.oScroll.sX !== "" || p.oScroll.sY !== "")) b = h("
").appendTo(q); if (b.length === 0 || b.children().length === 0) q.addClass(u.sNoFooter); else if (b.length > 0) { p.nTFoot = b[0]; ea(p.aoFooter, p.nTFoot) } if (g.aaData) for (j = 0; j < g.aaData.length; j++)O(p, g.aaData[j]); else (p.bDeferLoading || y(p) == "dom") && na(p, h(p.nTBody).children("tr")); p.aiDisplay = p.aiDisplayMaster.slice();
p.bInitialised = true; m === false && ha(p)
}; g.bStateSave ? (U.bStateSave = !0, z(p, "aoDrawCallback", xa, "state_save"), Jb(p, g, e)) : e()
}
}); b = null; return this
}, x, s, o, u, Za = {}, Mb = /[\r\n]/g, Aa = /<.*?>/g, Zb = /^\d{2,4}[\.\/\-]\d{1,2}[\.\/\-]\d{1,2}([T ]{1}\d{1,2}[:\.]\d{2}([\.:]\d{2})?)?$/, $b = RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)", "g"), Ya = /[',$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfkɃΞ]/gi, M = function (a) { return !a || !0 === a || "-" === a ? !0 : !1 }, Nb = function (a) {
var b = parseInt(a, 10); return !isNaN(b) &&
isFinite(a) ? b : null
}, Ob = function (a, b) { Za[b] || (Za[b] = RegExp(Qa(b), "g")); return "string" === typeof a && "." !== b ? a.replace(/\./g, "").replace(Za[b], ".") : a }, $a = function (a, b, c) { var d = "string" === typeof a; if (M(a)) return !0; b && d && (a = Ob(a, b)); c && d && (a = a.replace(Ya, "")); return !isNaN(parseFloat(a)) && isFinite(a) }, Pb = function (a, b, c) { return M(a) ? !0 : !(M(a) || "string" === typeof a) ? null : $a(a.replace(Aa, ""), b, c) ? !0 : null }, D = function (a, b, c) {
var d = [], e = 0, f = a.length; if (c !== k) for (; e < f; e++)a[e] && a[e][b] && d.push(a[e][b][c]); else for (; e <
f; e++)a[e] && d.push(a[e][b]); return d
}, ja = function (a, b, c, d) { var e = [], f = 0, g = b.length; if (d !== k) for (; f < g; f++)a[b[f]][c] && e.push(a[b[f]][c][d]); else for (; f < g; f++)e.push(a[b[f]][c]); return e }, Y = function (a, b) { var c = [], d; b === k ? (b = 0, d = a) : (d = b, b = a); for (var e = b; e < d; e++)c.push(e); return c }, Qb = function (a) { for (var b = [], c = 0, d = a.length; c < d; c++)a[c] && b.push(a[c]); return b }, qa = function (a) {
var b; a: { if (!(2 > a.length)) { b = a.slice().sort(); for (var c = b[0], d = 1, e = b.length; d < e; d++) { if (b[d] === c) { b = !1; break a } c = b[d] } } b = !0 } if (b) return a.slice();
b = []; var e = a.length, f, g = 0, d = 0; a: for (; d < e; d++) { c = a[d]; for (f = 0; f < g; f++)if (b[f] === c) continue a; b.push(c); g++ } return b
}; n.util = { throttle: function (a, b) { var c = b !== k ? b : 200, d, e; return function () { var b = this, g = +new Date, j = arguments; d && g < d + c ? (clearTimeout(e), e = setTimeout(function () { d = k; a.apply(b, j) }, c)) : (d = g, a.apply(b, j)) } }, escapeRegex: function (a) { return a.replace($b, "\\$1") } }; var A = function (a, b, c) { a[b] !== k && (a[c] = a[b]) }, ca = /\[.*?\]$/, W = /\(\)$/, Qa = n.util.escapeRegex, va = h("
")[0], Wb = va.textContent !== k, Yb =
/<.*?>/g, Oa = n.util.throttle, Rb = [], w = Array.prototype, ac = function (a) { var b, c, d = n.settings, e = h.map(d, function (a) { return a.nTable }); if (a) { if (a.nTable && a.oApi) return [a]; if (a.nodeName && "table" === a.nodeName.toLowerCase()) return b = h.inArray(a, e), -1 !== b ? [d[b]] : null; if (a && "function" === typeof a.settings) return a.settings().toArray(); "string" === typeof a ? c = h(a) : a instanceof h && (c = a) } else return []; if (c) return c.map(function () { b = h.inArray(this, e); return -1 !== b ? d[b] : null }).toArray() }; s = function (a, b) {
if (!(this instanceof
s)) return new s(a, b); var c = [], d = function (a) { (a = ac(a)) && (c = c.concat(a)) }; if (h.isArray(a)) for (var e = 0, f = a.length; e < f; e++)d(a[e]); else d(a); this.context = qa(c); b && h.merge(this, b); this.selector = { rows: null, cols: null, opts: null }; s.extend(this, this, Rb)
}; n.Api = s; h.extend(s.prototype, {
any: function () { return 0 !== this.count() }, concat: w.concat, context: [], count: function () { return this.flatten().length }, each: function (a) { for (var b = 0, c = this.length; b < c; b++)a.call(this, this[b], b, this); return this }, eq: function (a) {
var b =
this.context; return b.length > a ? new s(b[a], this[a]) : null
}, filter: function (a) { var b = []; if (w.filter) b = w.filter.call(this, a, this); else for (var c = 0, d = this.length; c < d; c++)a.call(this, this[c], c, this) && b.push(this[c]); return new s(this.context, b) }, flatten: function () { var a = []; return new s(this.context, a.concat.apply(a, this.toArray())) }, join: w.join, indexOf: w.indexOf || function (a, b) { for (var c = b || 0, d = this.length; c < d; c++)if (this[c] === a) return c; return -1 }, iterator: function (a, b, c, d) {
var e = [], f, g, j, h, m, l = this.context,
n, o, u = this.selector; "string" === typeof a && (d = c, c = b, b = a, a = !1); g = 0; for (j = l.length; g < j; g++) { var r = new s(l[g]); if ("table" === b) f = c.call(r, l[g], g), f !== k && e.push(f); else if ("columns" === b || "rows" === b) f = c.call(r, l[g], this[g], g), f !== k && e.push(f); else if ("column" === b || "column-rows" === b || "row" === b || "cell" === b) { o = this[g]; "column-rows" === b && (n = Ba(l[g], u.opts)); h = 0; for (m = o.length; h < m; h++)f = o[h], f = "cell" === b ? c.call(r, l[g], f.row, f.column, g, h) : c.call(r, l[g], f, g, h, n), f !== k && e.push(f) } } return e.length || d ? (a = new s(l, a ?
e.concat.apply([], e) : e), b = a.selector, b.rows = u.rows, b.cols = u.cols, b.opts = u.opts, a) : this
}, lastIndexOf: w.lastIndexOf || function (a, b) { return this.indexOf.apply(this.toArray.reverse(), arguments) }, length: 0, map: function (a) { var b = []; if (w.map) b = w.map.call(this, a, this); else for (var c = 0, d = this.length; c < d; c++)b.push(a.call(this, this[c], c)); return new s(this.context, b) }, pluck: function (a) { return this.map(function (b) { return b[a] }) }, pop: w.pop, push: w.push, reduce: w.reduce || function (a, b) {
return hb(this, a, b, 0, this.length,
1)
}, reduceRight: w.reduceRight || function (a, b) { return hb(this, a, b, this.length - 1, -1, -1) }, reverse: w.reverse, selector: null, shift: w.shift, slice: function () { return new s(this.context, this) }, sort: w.sort, splice: w.splice, toArray: function () { return w.slice.call(this) }, to$: function () { return h(this) }, toJQuery: function () { return h(this) }, unique: function () { return new s(this.context, qa(this)) }, unshift: w.unshift
}); s.extend = function (a, b, c) {
if (c.length && b && (b instanceof s || b.__dt_wrapper)) {
var d, e, f, g = function (a, b, c) {
return function () {
var d =
b.apply(a, arguments); s.extend(d, d, c.methodExt); return d
}
}; d = 0; for (e = c.length; d < e; d++)f = c[d], b[f.name] = "function" === typeof f.val ? g(a, f.val, f) : h.isPlainObject(f.val) ? {} : f.val, b[f.name].__dt_wrapper = !0, s.extend(a, b[f.name], f.propExt)
}
}; s.register = o = function (a, b) {
if (h.isArray(a)) for (var c = 0, d = a.length; c < d; c++)s.register(a[c], b); else for (var e = a.split("."), f = Rb, g, j, c = 0, d = e.length; c < d; c++) {
g = (j = -1 !== e[c].indexOf("()")) ? e[c].replace("()", "") : e[c]; var i; a: {
i = 0; for (var m = f.length; i < m; i++)if (f[i].name === g) {
i =
f[i]; break a
} i = null
} i || (i = { name: g, val: {}, methodExt: [], propExt: [] }, f.push(i)); c === d - 1 ? i.val = b : f = j ? i.methodExt : i.propExt
}
}; s.registerPlural = u = function (a, b, c) { s.register(a, c); s.register(b, function () { var a = c.apply(this, arguments); return a === this ? this : a instanceof s ? a.length ? h.isArray(a[0]) ? new s(a.context, a[0]) : a[0] : k : a }) }; o("tables()", function (a) {
var b; if (a) {
b = s; var c = this.context; if ("number" === typeof a) a = [c[a]]; else var d = h.map(c, function (a) { return a.nTable }), a = h(d).filter(a).map(function () {
var a = h.inArray(this,
d); return c[a]
}).toArray(); b = new b(a)
} else b = this; return b
}); o("table()", function (a) { var a = this.tables(a), b = a.context; return b.length ? new s(b[0]) : a }); u("tables().nodes()", "table().node()", function () { return this.iterator("table", function (a) { return a.nTable }, 1) }); u("tables().body()", "table().body()", function () { return this.iterator("table", function (a) { return a.nTBody }, 1) }); u("tables().header()", "table().header()", function () { return this.iterator("table", function (a) { return a.nTHead }, 1) }); u("tables().footer()",
"table().footer()", function () { return this.iterator("table", function (a) { return a.nTFoot }, 1) }); u("tables().containers()", "table().container()", function () { return this.iterator("table", function (a) { return a.nTableWrapper }, 1) }); o("draw()", function (a) { return this.iterator("table", function (b) { "page" === a ? P(b) : ("string" === typeof a && (a = "full-hold" === a ? !1 : !0), T(b, !1 === a)) }) }); o("page()", function (a) { return a === k ? this.page.info().page : this.iterator("table", function (b) { Ta(b, a) }) }); o("page.info()", function () {
if (0 ===
this.context.length) return k; var a = this.context[0], b = a._iDisplayStart, c = a.oFeatures.bPaginate ? a._iDisplayLength : -1, d = a.fnRecordsDisplay(), e = -1 === c; return { page: e ? 0 : Math.floor(b / c), pages: e ? 1 : Math.ceil(d / c), start: b, end: a.fnDisplayEnd(), length: c, recordsTotal: a.fnRecordsTotal(), recordsDisplay: d, serverSide: "ssp" === y(a) }
}); o("page.len()", function (a) { return a === k ? 0 !== this.context.length ? this.context[0]._iDisplayLength : k : this.iterator("table", function (b) { Ra(b, a) }) }); var Sb = function (a, b, c) {
if (c) {
var d = new s(a);
d.one("draw", function () { c(d.ajax.json()) })
} if ("ssp" == y(a)) T(a, b); else { C(a, !0); var e = a.jqXHR; e && 4 !== e.readyState && e.abort(); sa(a, [], function (c) { oa(a); for (var c = ta(a, c), d = 0, e = c.length; d < e; d++)O(a, c[d]); T(a, b); C(a, !1) }) }
}; o("ajax.json()", function () { var a = this.context; if (0 < a.length) return a[0].json }); o("ajax.params()", function () { var a = this.context; if (0 < a.length) return a[0].oAjaxData }); o("ajax.reload()", function (a, b) { return this.iterator("table", function (c) { Sb(c, !1 === b, a) }) }); o("ajax.url()", function (a) {
var b =
this.context; if (a === k) { if (0 === b.length) return k; b = b[0]; return b.ajax ? h.isPlainObject(b.ajax) ? b.ajax.url : b.ajax : b.sAjaxSource } return this.iterator("table", function (b) { h.isPlainObject(b.ajax) ? b.ajax.url = a : b.ajax = a })
}); o("ajax.url().load()", function (a, b) { return this.iterator("table", function (c) { Sb(c, !1 === b, a) }) }); var ab = function (a, b, c, d, e) {
var f = [], g, j, i, m, l, n; i = typeof b; if (!b || "string" === i || "function" === i || b.length === k) b = [b]; i = 0; for (m = b.length; i < m; i++) {
j = b[i] && b[i].split && !b[i].match(/[\[\(:]/) ? b[i].split(",") :
[b[i]]; l = 0; for (n = j.length; l < n; l++)(g = c("string" === typeof j[l] ? h.trim(j[l]) : j[l])) && g.length && (f = f.concat(g))
} a = x.selector[a]; if (a.length) { i = 0; for (m = a.length; i < m; i++)f = a[i](d, e, f) } return qa(f)
}, bb = function (a) { a || (a = {}); a.filter && a.search === k && (a.search = a.filter); return h.extend({ search: "none", order: "current", page: "all" }, a) }, cb = function (a) { for (var b = 0, c = a.length; b < c; b++)if (0 < a[b].length) return a[0] = a[b], a[0].length = 1, a.length = 1, a.context = [a.context[b]], a; a.length = 0; return a }, Ba = function (a, b) {
var c,
d, e, f = [], g = a.aiDisplay; e = a.aiDisplayMaster; var j = b.search; c = b.order; d = b.page; if ("ssp" == y(a)) return "removed" === j ? [] : Y(0, e.length); if ("current" == d) { c = a._iDisplayStart; for (d = a.fnDisplayEnd(); c < d; c++)f.push(g[c]) } else if ("current" == c || "applied" == c) if ("none" == j) f = e.slice(); else if ("applied" == j) f = g.slice(); else { if ("removed" == j) { var i = {}; c = 0; for (d = g.length; c < d; c++)i[g[c]] = null; f = h.map(e, function (a) { return !i.hasOwnProperty(a) ? a : null }) } } else if ("index" == c || "original" == c) {
c = 0; for (d = a.aoData.length; c < d; c++)"none" ==
j ? f.push(c) : (e = h.inArray(c, g), (-1 === e && "removed" == j || 0 <= e && "applied" == j) && f.push(c))
} return f
}; o("rows()", function (a, b) {
a === k ? a = "" : h.isPlainObject(a) && (b = a, a = ""); var b = bb(b), c = this.iterator("table", function (c) {
var e = b, f; return ab("row", a, function (a) {
var b = Nb(a), i = c.aoData; if (b !== null && !e) return [b]; f || (f = Ba(c, e)); if (b !== null && h.inArray(b, f) !== -1) return [b]; if (a === null || a === k || a === "") return f; if (typeof a === "function") return h.map(f, function (b) { var c = i[b]; return a(b, c._aData, c.nTr) ? b : null }); if (a.nodeName) {
var b =
a._DT_RowIndex, m = a._DT_CellIndex; if (b !== k) return i[b] && i[b].nTr === a ? [b] : []; if (m) return i[m.row] && i[m.row].nTr === a ? [m.row] : []; b = h(a).closest("*[data-dt-row]"); return b.length ? [b.data("dt-row")] : []
} if (typeof a === "string" && a.charAt(0) === "#") { b = c.aIds[a.replace(/^#/, "")]; if (b !== k) return [b.idx] } b = Qb(ja(c.aoData, f, "nTr")); return h(b).filter(a).map(function () { return this._DT_RowIndex }).toArray()
}, c, e)
}, 1); c.selector.rows = a; c.selector.opts = b; return c
}); o("rows().nodes()", function () {
return this.iterator("row",
function (a, b) { return a.aoData[b].nTr || k }, 1)
}); o("rows().data()", function () { return this.iterator(!0, "rows", function (a, b) { return ja(a.aoData, b, "_aData") }, 1) }); u("rows().cache()", "row().cache()", function (a) { return this.iterator("row", function (b, c) { var d = b.aoData[c]; return "search" === a ? d._aFilterData : d._aSortData }, 1) }); u("rows().invalidate()", "row().invalidate()", function (a) { return this.iterator("row", function (b, c) { da(b, c, a) }) }); u("rows().indexes()", "row().index()", function () {
return this.iterator("row",
function (a, b) { return b }, 1)
}); u("rows().ids()", "row().id()", function (a) { for (var b = [], c = this.context, d = 0, e = c.length; d < e; d++)for (var f = 0, g = this[d].length; f < g; f++) { var h = c[d].rowIdFn(c[d].aoData[this[d][f]]._aData); b.push((!0 === a ? "#" : "") + h) } return new s(c, b) }); u("rows().remove()", "row().remove()", function () {
var a = this; this.iterator("row", function (b, c, d) {
var e = b.aoData, f = e[c], g, h, i, m, l; e.splice(c, 1); g = 0; for (h = e.length; g < h; g++)if (i = e[g], l = i.anCells, null !== i.nTr && (i.nTr._DT_RowIndex = g), null !== l) {
i = 0; for (m =
l.length; i < m; i++)l[i]._DT_CellIndex.row = g
} pa(b.aiDisplayMaster, c); pa(b.aiDisplay, c); pa(a[d], c, !1); 0 < b._iRecordsDisplay && b._iRecordsDisplay--; Sa(b); c = b.rowIdFn(f._aData); c !== k && delete b.aIds[c]
}); this.iterator("table", function (a) { for (var c = 0, d = a.aoData.length; c < d; c++)a.aoData[c].idx = c }); return this
}); o("rows.add()", function (a) {
var b = this.iterator("table", function (b) { var c, f, g, h = []; f = 0; for (g = a.length; f < g; f++)c = a[f], c.nodeName && "TR" === c.nodeName.toUpperCase() ? h.push(na(b, c)[0]) : h.push(O(b, c)); return h },
1), c = this.rows(-1); c.pop(); h.merge(c, b); return c
}); o("row()", function (a, b) { return cb(this.rows(a, b)) }); o("row().data()", function (a) { var b = this.context; if (a === k) return b.length && this.length ? b[0].aoData[this[0]]._aData : k; var c = b[0].aoData[this[0]]; c._aData = a; h.isArray(a) && c.nTr.id && N(b[0].rowId)(a, c.nTr.id); da(b[0], this[0], "data"); return this }); o("row().node()", function () { var a = this.context; return a.length && this.length ? a[0].aoData[this[0]].nTr || null : null }); o("row.add()", function (a) {
a instanceof h &&
a.length && (a = a[0]); var b = this.iterator("table", function (b) { return a.nodeName && "TR" === a.nodeName.toUpperCase() ? na(b, a)[0] : O(b, a) }); return this.row(b[0])
}); var db = function (a, b) { var c = a.context; if (c.length && (c = c[0].aoData[b !== k ? b : a[0]]) && c._details) c._details.remove(), c._detailsShow = k, c._details = k }, Tb = function (a, b) {
var c = a.context; if (c.length && a.length) {
var d = c[0].aoData[a[0]]; if (d._details) {
(d._detailsShow = b) ? d._details.insertAfter(d.nTr) : d._details.detach(); var e = c[0], f = new s(e), g = e.aoData; f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");
0 < D(g, "_details").length && (f.on("draw.dt.DT_details", function (a, b) { e === b && f.rows({ page: "current" }).eq(0).each(function (a) { a = g[a]; a._detailsShow && a._details.insertAfter(a.nTr) }) }), f.on("column-visibility.dt.DT_details", function (a, b) { if (e === b) for (var c, d = V(b), f = 0, h = g.length; f < h; f++)c = g[f], c._details && c._details.children("td[colspan]").attr("colspan", d) }), f.on("destroy.dt.DT_details", function (a, b) { if (e === b) for (var c = 0, d = g.length; c < d; c++)g[c]._details && db(f, c) }))
}
}
}; o("row().child()", function (a, b) {
var c =
this.context; if (a === k) return c.length && this.length ? c[0].aoData[this[0]]._details : k; if (!0 === a) this.child.show(); else if (!1 === a) db(this); else if (c.length && this.length) {
var d = c[0], c = c[0].aoData[this[0]], e = [], f = function (a, b) { if (h.isArray(a) || a instanceof h) for (var c = 0, k = a.length; c < k; c++)f(a[c], b); else a.nodeName && "tr" === a.nodeName.toLowerCase() ? e.push(a) : (c = h("
").addClass(b), h("td", c).addClass(b).html(a)[0].colSpan = V(d), e.push(c[0])) }; f(a, b); c._details && c._details.detach(); c._details = h(e);
c._detailsShow && c._details.insertAfter(c.nTr)
} return this
}); o(["row().child.show()", "row().child().show()"], function () { Tb(this, !0); return this }); o(["row().child.hide()", "row().child().hide()"], function () { Tb(this, !1); return this }); o(["row().child.remove()", "row().child().remove()"], function () { db(this); return this }); o("row().child.isShown()", function () { var a = this.context; return a.length && this.length ? a[0].aoData[this[0]]._detailsShow || !1 : !1 }); var bc = /^([^:]+):(name|visIdx|visible)$/, Ub = function (a, b,
c, d, e) { for (var c = [], d = 0, f = e.length; d < f; d++)c.push(B(a, e[d], b)); return c }; o("columns()", function (a, b) {
a === k ? a = "" : h.isPlainObject(a) && (b = a, a = ""); var b = bb(b), c = this.iterator("table", function (c) {
var e = a, f = b, g = c.aoColumns, j = D(g, "sName"), i = D(g, "nTh"); return ab("column", e, function (a) {
var b = Nb(a); if (a === "") return Y(g.length); if (b !== null) return [b >= 0 ? b : g.length + b]; if (typeof a === "function") { var e = Ba(c, f); return h.map(g, function (b, f) { return a(f, Ub(c, f, 0, 0, e), i[f]) ? f : null }) } var k = typeof a === "string" ? a.match(bc) :
""; if (k) switch (k[2]) { case "visIdx": case "visible": b = parseInt(k[1], 10); if (b < 0) { var n = h.map(g, function (a, b) { return a.bVisible ? b : null }); return [n[n.length + b]] } return [aa(c, b)]; case "name": return h.map(j, function (a, b) { return a === k[1] ? b : null }); default: return [] }if (a.nodeName && a._DT_CellIndex) return [a._DT_CellIndex.column]; b = h(i).filter(a).map(function () { return h.inArray(this, i) }).toArray(); if (b.length || !a.nodeName) return b; b = h(a).closest("*[data-dt-column]"); return b.length ? [b.data("dt-column")] : []
}, c, f)
},
1); c.selector.cols = a; c.selector.opts = b; return c
}); u("columns().header()", "column().header()", function () { return this.iterator("column", function (a, b) { return a.aoColumns[b].nTh }, 1) }); u("columns().footer()", "column().footer()", function () { return this.iterator("column", function (a, b) { return a.aoColumns[b].nTf }, 1) }); u("columns().data()", "column().data()", function () { return this.iterator("column-rows", Ub, 1) }); u("columns().dataSrc()", "column().dataSrc()", function () {
return this.iterator("column", function (a, b) { return a.aoColumns[b].mData },
1)
}); u("columns().cache()", "column().cache()", function (a) { return this.iterator("column-rows", function (b, c, d, e, f) { return ja(b.aoData, f, "search" === a ? "_aFilterData" : "_aSortData", c) }, 1) }); u("columns().nodes()", "column().nodes()", function () { return this.iterator("column-rows", function (a, b, c, d, e) { return ja(a.aoData, e, "anCells", b) }, 1) }); u("columns().visible()", "column().visible()", function (a, b) {
var c = this.iterator("column", function (b, c) {
if (a === k) return b.aoColumns[c].bVisible; var f = b.aoColumns, g = f[c], j = b.aoData,
i, m, l; if (a !== k && g.bVisible !== a) { if (a) { var n = h.inArray(!0, D(f, "bVisible"), c + 1); i = 0; for (m = j.length; i < m; i++)l = j[i].nTr, f = j[i].anCells, l && l.insertBefore(f[c], f[n] || null) } else h(D(b.aoData, "anCells", c)).detach(); g.bVisible = a; fa(b, b.aoHeader); fa(b, b.aoFooter); b.aiDisplay.length || h(b.nTBody).find("td[colspan]").attr("colspan", V(b)); xa(b) }
}); a !== k && (this.iterator("column", function (c, e) { r(c, null, "column-visibility", [c, e, a, b]) }), (b === k || b) && this.columns.adjust()); return c
}); u("columns().indexes()", "column().index()",
function (a) { return this.iterator("column", function (b, c) { return "visible" === a ? ba(b, c) : c }, 1) }); o("columns.adjust()", function () { return this.iterator("table", function (a) { $(a) }, 1) }); o("column.index()", function (a, b) { if (0 !== this.context.length) { var c = this.context[0]; if ("fromVisible" === a || "toData" === a) return aa(c, b); if ("fromData" === a || "toVisible" === a) return ba(c, b) } }); o("column()", function (a, b) { return cb(this.columns(a, b)) }); o("cells()", function (a, b, c) {
h.isPlainObject(a) && (a.row === k ? (c = a, a = null) : (c = b, b = null));
h.isPlainObject(b) && (c = b, b = null); if (null === b || b === k) return this.iterator("table", function (b) {
var d = a, e = bb(c), f = b.aoData, g = Ba(b, e), j = Qb(ja(f, g, "anCells")), i = h([].concat.apply([], j)), l, m = b.aoColumns.length, n, o, u, s, r, v; return ab("cell", d, function (a) {
var c = typeof a === "function"; if (a === null || a === k || c) { n = []; o = 0; for (u = g.length; o < u; o++) { l = g[o]; for (s = 0; s < m; s++) { r = { row: l, column: s }; if (c) { v = f[l]; a(r, B(b, l, s), v.anCells ? v.anCells[s] : null) && n.push(r) } else n.push(r) } } return n } if (h.isPlainObject(a)) return a.column !==
k && a.row !== k && h.inArray(a.row, g) !== -1 ? [a] : []; c = i.filter(a).map(function (a, b) { return { row: b._DT_CellIndex.row, column: b._DT_CellIndex.column } }).toArray(); if (c.length || !a.nodeName) return c; v = h(a).closest("*[data-dt-row]"); return v.length ? [{ row: v.data("dt-row"), column: v.data("dt-column") }] : []
}, b, e)
}); var d = this.columns(b), e = this.rows(a), f, g, j, i, m; this.iterator("table", function (a, b) { f = []; g = 0; for (j = e[b].length; g < j; g++) { i = 0; for (m = d[b].length; i < m; i++)f.push({ row: e[b][g], column: d[b][i] }) } }, 1); var l = this.cells(f,
c); h.extend(l.selector, { cols: b, rows: a, opts: c }); return l
}); u("cells().nodes()", "cell().node()", function () { return this.iterator("cell", function (a, b, c) { return (a = a.aoData[b]) && a.anCells ? a.anCells[c] : k }, 1) }); o("cells().data()", function () { return this.iterator("cell", function (a, b, c) { return B(a, b, c) }, 1) }); u("cells().cache()", "cell().cache()", function (a) { a = "search" === a ? "_aFilterData" : "_aSortData"; return this.iterator("cell", function (b, c, d) { return b.aoData[c][a][d] }, 1) }); u("cells().render()", "cell().render()",
function (a) { return this.iterator("cell", function (b, c, d) { return B(b, c, d, a) }, 1) }); u("cells().indexes()", "cell().index()", function () { return this.iterator("cell", function (a, b, c) { return { row: b, column: c, columnVisible: ba(a, c) } }, 1) }); u("cells().invalidate()", "cell().invalidate()", function (a) { return this.iterator("cell", function (b, c, d) { da(b, c, a, d) }) }); o("cell()", function (a, b, c) { return cb(this.cells(a, b, c)) }); o("cell().data()", function (a) {
var b = this.context, c = this[0]; if (a === k) return b.length && c.length ? B(b[0],
c[0].row, c[0].column) : k; jb(b[0], c[0].row, c[0].column, a); da(b[0], c[0].row, "data", c[0].column); return this
}); o("order()", function (a, b) { var c = this.context; if (a === k) return 0 !== c.length ? c[0].aaSorting : k; "number" === typeof a ? a = [[a, b]] : a.length && !h.isArray(a[0]) && (a = Array.prototype.slice.call(arguments)); return this.iterator("table", function (b) { b.aaSorting = a.slice() }) }); o("order.listener()", function (a, b, c) { return this.iterator("table", function (d) { Ma(d, a, b, c) }) }); o("order.fixed()", function (a) {
if (!a) {
var b =
this.context, b = b.length ? b[0].aaSortingFixed : k; return h.isArray(b) ? { pre: b } : b
} return this.iterator("table", function (b) { b.aaSortingFixed = h.extend(!0, {}, a) })
}); o(["columns().order()", "column().order()"], function (a) { var b = this; return this.iterator("table", function (c, d) { var e = []; h.each(b[d], function (b, c) { e.push([c, a]) }); c.aaSorting = e }) }); o("search()", function (a, b, c, d) {
var e = this.context; return a === k ? 0 !== e.length ? e[0].oPreviousSearch.sSearch : k : this.iterator("table", function (e) {
e.oFeatures.bFilter && ga(e,
h.extend({}, e.oPreviousSearch, { sSearch: a + "", bRegex: null === b ? !1 : b, bSmart: null === c ? !0 : c, bCaseInsensitive: null === d ? !0 : d }), 1)
})
}); u("columns().search()", "column().search()", function (a, b, c, d) { return this.iterator("column", function (e, f) { var g = e.aoPreSearchCols; if (a === k) return g[f].sSearch; e.oFeatures.bFilter && (h.extend(g[f], { sSearch: a + "", bRegex: null === b ? !1 : b, bSmart: null === c ? !0 : c, bCaseInsensitive: null === d ? !0 : d }), ga(e, e.oPreviousSearch, 1)) }) }); o("state()", function () {
return this.context.length ? this.context[0].oSavedState :
null
}); o("state.clear()", function () { return this.iterator("table", function (a) { a.fnStateSaveCallback.call(a.oInstance, a, {}) }) }); o("state.loaded()", function () { return this.context.length ? this.context[0].oLoadedState : null }); o("state.save()", function () { return this.iterator("table", function (a) { xa(a) }) }); n.versionCheck = n.fnVersionCheck = function (a) { for (var b = n.version.split("."), a = a.split("."), c, d, e = 0, f = a.length; e < f; e++)if (c = parseInt(b[e], 10) || 0, d = parseInt(a[e], 10) || 0, c !== d) return c > d; return !0 }; n.isDataTable =
n.fnIsDataTable = function (a) { var b = h(a).get(0), c = !1; if (a instanceof n.Api) return !0; h.each(n.settings, function (a, e) { var f = e.nScrollHead ? h("table", e.nScrollHead)[0] : null, g = e.nScrollFoot ? h("table", e.nScrollFoot)[0] : null; if (e.nTable === b || f === b || g === b) c = !0 }); return c }; n.tables = n.fnTables = function (a) { var b = !1; h.isPlainObject(a) && (b = a.api, a = a.visible); var c = h.map(n.settings, function (b) { if (!a || a && h(b.nTable).is(":visible")) return b.nTable }); return b ? new s(c) : c }; n.camelToHungarian = J; o("$()", function (a, b) {
var c =
this.rows(b).nodes(), c = h(c); return h([].concat(c.filter(a).toArray(), c.find(a).toArray()))
}); h.each(["on", "one", "off"], function (a, b) { o(b + "()", function () { var a = Array.prototype.slice.call(arguments); a[0] = h.map(a[0].split(/\s/), function (a) { return !a.match(/\.dt\b/) ? a + ".dt" : a }).join(" "); var d = h(this.tables().nodes()); d[b].apply(d, a); return this }) }); o("clear()", function () { return this.iterator("table", function (a) { oa(a) }) }); o("settings()", function () { return new s(this.context, this.context) }); o("init()", function () {
var a =
this.context; return a.length ? a[0].oInit : null
}); o("data()", function () { return this.iterator("table", function (a) { return D(a.aoData, "_aData") }).flatten() }); o("destroy()", function (a) {
a = a || !1; return this.iterator("table", function (b) {
var c = b.nTableWrapper.parentNode, d = b.oClasses, e = b.nTable, f = b.nTBody, g = b.nTHead, j = b.nTFoot, i = h(e), f = h(f), k = h(b.nTableWrapper), l = h.map(b.aoData, function (a) { return a.nTr }), o; b.bDestroying = !0; r(b, "aoDestroyCallback", "destroy", [b]); a || (new s(b)).columns().visible(!0); k.off(".DT").find(":not(tbody *)").off(".DT");
h(E).off(".DT-" + b.sInstance); e != g.parentNode && (i.children("thead").detach(), i.append(g)); j && e != j.parentNode && (i.children("tfoot").detach(), i.append(j)); b.aaSorting = []; b.aaSortingFixed = []; wa(b); h(l).removeClass(b.asStripeClasses.join(" ")); h("th, td", g).removeClass(d.sSortable + " " + d.sSortableAsc + " " + d.sSortableDesc + " " + d.sSortableNone); f.children().detach(); f.append(l); g = a ? "remove" : "detach"; i[g](); k[g](); !a && c && (c.insertBefore(e, b.nTableReinsertBefore), i.css("width", b.sDestroyWidth).removeClass(d.sTable),
(o = b.asDestroyStripes.length) && f.children().each(function (a) { h(this).addClass(b.asDestroyStripes[a % o]) })); c = h.inArray(b, n.settings); -1 !== c && n.settings.splice(c, 1)
})
}); h.each(["column", "row", "cell"], function (a, b) { o(b + "s().every()", function (a) { var d = this.selector.opts, e = this; return this.iterator(b, function (f, g, h, i, m) { a.call(e[b](g, "cell" === b ? h : d, "cell" === b ? d : k), g, h, i, m) }) }) }); o("i18n()", function (a, b, c) {
var d = this.context[0], a = S(a)(d.oLanguage); a === k && (a = b); c !== k && h.isPlainObject(a) && (a = a[c] !== k ? a[c] :
a._); return a.replace("%d", c)
}); n.version = "1.10.18"; n.settings = []; n.models = {}; n.models.oSearch = { bCaseInsensitive: !0, sSearch: "", bRegex: !1, bSmart: !0 }; n.models.oRow = { nTr: null, anCells: null, _aData: [], _aSortData: null, _aFilterData: null, _sFilterRow: null, _sRowStripe: "", src: null, idx: -1 }; n.models.oColumn = {
idx: null, aDataSort: null, asSorting: null, bSearchable: null, bSortable: null, bVisible: null, _sManualType: null, _bAttrSrc: !1, fnCreatedCell: null, fnGetData: null, fnSetData: null, mData: null, mRender: null, nTh: null, nTf: null,
sClass: null, sContentPadding: null, sDefaultContent: null, sName: null, sSortDataType: "std", sSortingClass: null, sSortingClassJUI: null, sTitle: null, sType: null, sWidth: null, sWidthOrig: null
}; n.defaults = {
aaData: null, aaSorting: [[0, "asc"]], aaSortingFixed: [], ajax: null, aLengthMenu: [10, 25, 50, 100], aoColumns: null, aoColumnDefs: null, aoSearchCols: [], asStripeClasses: null, bAutoWidth: !0, bDeferRender: !1, bDestroy: !1, bFilter: !0, bInfo: !0, bLengthChange: !0, bPaginate: !0, bProcessing: !1, bRetrieve: !1, bScrollCollapse: !1, bServerSide: !1,
bSort: !0, bSortMulti: !0, bSortCellsTop: !1, bSortClasses: !0, bStateSave: !1, fnCreatedRow: null, fnDrawCallback: null, fnFooterCallback: null, fnFormatNumber: function (a) { return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, this.oLanguage.sThousands) }, fnHeaderCallback: null, fnInfoCallback: null, fnInitComplete: null, fnPreDrawCallback: null, fnRowCallback: null, fnServerData: null, fnServerParams: null, fnStateLoadCallback: function (a) {
try {
return JSON.parse((-1 === a.iStateDuration ? sessionStorage : localStorage).getItem("DataTables_" +
a.sInstance + "_" + location.pathname))
} catch (b) { }
}, fnStateLoadParams: null, fnStateLoaded: null, fnStateSaveCallback: function (a, b) { try { (-1 === a.iStateDuration ? sessionStorage : localStorage).setItem("DataTables_" + a.sInstance + "_" + location.pathname, JSON.stringify(b)) } catch (c) { } }, fnStateSaveParams: null, iStateDuration: 7200, iDeferLoading: null, iDisplayLength: 10, iDisplayStart: 0, iTabIndex: 0, oClasses: {}, oLanguage: {
oAria: { sSortAscending: ": activate to sort column ascending", sSortDescending: ": activate to sort column descending" },
oPaginate: { sFirst: "First", sLast: "Last", sNext: "Next", sPrevious: "Previous" }, sEmptyTable: "No data available in table", sInfo: "Showing _START_ to _END_ of _TOTAL_ entries", sInfoEmpty: "Showing 0 to 0 of 0 entries", sInfoFiltered: "(filtered from _MAX_ total entries)", sInfoPostFix: "", sDecimal: "", sThousands: ",", sLengthMenu: "Show _MENU_ entries", sLoadingRecords: "Loading...", sProcessing: "Processing...", sSearch: "Search:", sSearchPlaceholder: "", sUrl: "", sZeroRecords: "No matching records found"
}, oSearch: h.extend({},
n.models.oSearch), sAjaxDataProp: "data", sAjaxSource: null, sDom: "lfrtip", searchDelay: null, sPaginationType: "simple_numbers", sScrollX: "", sScrollXInner: "", sScrollY: "", sServerMethod: "GET", renderer: null, rowId: "DT_RowId"
}; Z(n.defaults); n.defaults.column = { aDataSort: null, iDataSort: -1, asSorting: ["asc", "desc"], bSearchable: !0, bSortable: !0, bVisible: !0, fnCreatedCell: null, mData: null, mRender: null, sCellType: "td", sClass: "", sContentPadding: "", sDefaultContent: null, sName: "", sSortDataType: "std", sTitle: null, sType: null, sWidth: null };
Z(n.defaults.column); n.models.oSettings = {
oFeatures: { bAutoWidth: null, bDeferRender: null, bFilter: null, bInfo: null, bLengthChange: null, bPaginate: null, bProcessing: null, bServerSide: null, bSort: null, bSortMulti: null, bSortClasses: null, bStateSave: null }, oScroll: { bCollapse: null, iBarWidth: 0, sX: null, sXInner: null, sY: null }, oLanguage: { fnInfoCallback: null }, oBrowser: { bScrollOversize: !1, bScrollbarLeft: !1, bBounding: !1, barWidth: 0 }, ajax: null, aanFeatures: [], aoData: [], aiDisplay: [], aiDisplayMaster: [], aIds: {}, aoColumns: [], aoHeader: [],
aoFooter: [], oPreviousSearch: {}, aoPreSearchCols: [], aaSorting: null, aaSortingFixed: [], asStripeClasses: null, asDestroyStripes: [], sDestroyWidth: 0, aoRowCallback: [], aoHeaderCallback: [], aoFooterCallback: [], aoDrawCallback: [], aoRowCreatedCallback: [], aoPreDrawCallback: [], aoInitComplete: [], aoStateSaveParams: [], aoStateLoadParams: [], aoStateLoaded: [], sTableId: "", nTable: null, nTHead: null, nTFoot: null, nTBody: null, nTableWrapper: null, bDeferLoading: !1, bInitialised: !1, aoOpenRows: [], sDom: null, searchDelay: null, sPaginationType: "two_button",
iStateDuration: 0, aoStateSave: [], aoStateLoad: [], oSavedState: null, oLoadedState: null, sAjaxSource: null, sAjaxDataProp: null, bAjaxDataGet: !0, jqXHR: null, json: k, oAjaxData: k, fnServerData: null, aoServerParams: [], sServerMethod: null, fnFormatNumber: null, aLengthMenu: null, iDraw: 0, bDrawing: !1, iDrawError: -1, _iDisplayLength: 10, _iDisplayStart: 0, _iRecordsTotal: 0, _iRecordsDisplay: 0, oClasses: {}, bFiltered: !1, bSorted: !1, bSortCellsTop: null, oInit: null, aoDestroyCallback: [], fnRecordsTotal: function () {
return "ssp" == y(this) ? 1 * this._iRecordsTotal :
this.aiDisplayMaster.length
}, fnRecordsDisplay: function () { return "ssp" == y(this) ? 1 * this._iRecordsDisplay : this.aiDisplay.length }, fnDisplayEnd: function () { var a = this._iDisplayLength, b = this._iDisplayStart, c = b + a, d = this.aiDisplay.length, e = this.oFeatures, f = e.bPaginate; return e.bServerSide ? !1 === f || -1 === a ? b + d : Math.min(b + a, this._iRecordsDisplay) : !f || c > d || -1 === a ? d : c }, oInstance: null, sInstance: null, iTabIndex: 0, nScrollHead: null, nScrollFoot: null, aLastSort: [], oPlugins: {}, rowIdFn: null, rowId: null
}; n.ext = x = {
buttons: {},
classes: {}, build: "dt/dt-1.10.18", errMode: "alert", feature: [], search: [], selector: { cell: [], column: [], row: [] }, internal: {}, legacy: { ajax: null }, pager: {}, renderer: { pageButton: {}, header: {} }, order: {}, type: { detect: [], search: {}, order: {} }, _unique: 0, fnVersionCheck: n.fnVersionCheck, iApiIndex: 0, oJUIClasses: {}, sVersion: n.version
}; h.extend(x, { afnFiltering: x.search, aTypes: x.type.detect, ofnSearch: x.type.search, oSort: x.type.order, afnSortData: x.order, aoFeatures: x.feature, oApi: x.internal, oStdClasses: x.classes, oPagination: x.pager });
h.extend(n.ext.classes, {
sTable: "dataTable", sNoFooter: "no-footer", sPageButton: "paginate_button", sPageButtonActive: "current", sPageButtonDisabled: "disabled", sStripeOdd: "odd", sStripeEven: "even", sRowEmpty: "dataTables_empty", sWrapper: "dataTables_wrapper", sFilter: "dataTables_filter", sInfo: "dataTables_info", sPaging: "dataTables_paginate paging_", sLength: "dataTables_length", sProcessing: "dataTables_processing", sSortAsc: "sorting_asc", sSortDesc: "sorting_desc", sSortable: "sorting", sSortableAsc: "sorting_asc_disabled",
sSortableDesc: "sorting_desc_disabled", sSortableNone: "sorting_disabled", sSortColumn: "sorting_", sFilterInput: "", sLengthSelect: "", sScrollWrapper: "dataTables_scroll", sScrollHead: "dataTables_scrollHead", sScrollHeadInner: "dataTables_scrollHeadInner", sScrollBody: "dataTables_scrollBody", sScrollFoot: "dataTables_scrollFoot", sScrollFootInner: "dataTables_scrollFootInner", sHeaderTH: "", sFooterTH: "", sSortJUIAsc: "", sSortJUIDesc: "", sSortJUI: "", sSortJUIAscAllowed: "", sSortJUIDescAllowed: "", sSortJUIWrapper: "", sSortIcon: "",
sJUIHeader: "", sJUIFooter: ""
}); var Kb = n.ext.pager; h.extend(Kb, { simple: function () { return ["previous", "next"] }, full: function () { return ["first", "previous", "next", "last"] }, numbers: function (a, b) { return [ia(a, b)] }, simple_numbers: function (a, b) { return ["previous", ia(a, b), "next"] }, full_numbers: function (a, b) { return ["first", "previous", ia(a, b), "next", "last"] }, first_last_numbers: function (a, b) { return ["first", ia(a, b), "last"] }, _numbers: ia, numbers_length: 7 }); h.extend(!0, n.ext.renderer, {
pageButton: {
_: function (a, b, c, d, e,
f) {
var g = a.oClasses, j = a.oLanguage.oPaginate, i = a.oLanguage.oAria.paginate || {}, m, l, n = 0, o = function (b, d) {
var k, s, u, r, v = function (b) { Ta(a, b.data.action, true) }; k = 0; for (s = d.length; k < s; k++) {
r = d[k]; if (h.isArray(r)) { u = h("<" + (r.DT_el || "div") + "/>").appendTo(b); o(u, r) } else {
m = null; l = ""; switch (r) {
case "ellipsis": b.append('
… '); break; case "first": m = j.sFirst; l = r + (e > 0 ? "" : " " + g.sPageButtonDisabled); break; case "previous": m = j.sPrevious; l = r + (e > 0 ? "" : " " + g.sPageButtonDisabled); break; case "next": m =
j.sNext; l = r + (e < f - 1 ? "" : " " + g.sPageButtonDisabled); break; case "last": m = j.sLast; l = r + (e < f - 1 ? "" : " " + g.sPageButtonDisabled); break; default: m = r + 1; l = e === r ? g.sPageButtonActive : ""
}if (m !== null) { u = h("
", { "class": g.sPageButton + " " + l, "aria-controls": a.sTableId, "aria-label": i[r], "data-dt-idx": n, tabindex: a.iTabIndex, id: c === 0 && typeof r === "string" ? a.sTableId + "_" + r : null }).html(m).appendTo(b); Wa(u, { action: r }, v); n++ }
}
}
}, s; try { s = h(b).find(H.activeElement).data("dt-idx") } catch (u) { } o(h(b).empty(), d); s !== k && h(b).find("[data-dt-idx=" +
s + "]").focus()
}
}
}); h.extend(n.ext.type.detect, [function (a, b) { var c = b.oLanguage.sDecimal; return $a(a, c) ? "num" + c : null }, function (a) { if (a && !(a instanceof Date) && !Zb.test(a)) return null; var b = Date.parse(a); return null !== b && !isNaN(b) || M(a) ? "date" : null }, function (a, b) { var c = b.oLanguage.sDecimal; return $a(a, c, !0) ? "num-fmt" + c : null }, function (a, b) { var c = b.oLanguage.sDecimal; return Pb(a, c) ? "html-num" + c : null }, function (a, b) { var c = b.oLanguage.sDecimal; return Pb(a, c, !0) ? "html-num-fmt" + c : null }, function (a) {
return M(a) ||
"string" === typeof a && -1 !== a.indexOf("<") ? "html" : null
}]); h.extend(n.ext.type.search, { html: function (a) { return M(a) ? a : "string" === typeof a ? a.replace(Mb, " ").replace(Aa, "") : "" }, string: function (a) { return M(a) ? a : "string" === typeof a ? a.replace(Mb, " ") : a } }); var za = function (a, b, c, d) { if (0 !== a && (!a || "-" === a)) return -Infinity; b && (a = Ob(a, b)); a.replace && (c && (a = a.replace(c, "")), d && (a = a.replace(d, ""))); return 1 * a }; h.extend(x.type.order, {
"date-pre": function (a) { a = Date.parse(a); return isNaN(a) ? -Infinity : a }, "html-pre": function (a) {
return M(a) ?
"" : a.replace ? a.replace(/<.*?>/g, "").toLowerCase() : a + ""
}, "string-pre": function (a) { return M(a) ? "" : "string" === typeof a ? a.toLowerCase() : !a.toString ? "" : a.toString() }, "string-asc": function (a, b) { return a < b ? -1 : a > b ? 1 : 0 }, "string-desc": function (a, b) { return a < b ? 1 : a > b ? -1 : 0 }
}); Da(""); h.extend(!0, n.ext.renderer, {
header: {
_: function (a, b, c, d) {
h(a.nTable).on("order.dt.DT", function (e, f, g, h) {
if (a === f) {
e = c.idx; b.removeClass(c.sSortingClass + " " + d.sSortAsc + " " + d.sSortDesc).addClass(h[e] == "asc" ? d.sSortAsc : h[e] == "desc" ? d.sSortDesc :
c.sSortingClass)
}
})
}, jqueryui: function (a, b, c, d) {
h("
").addClass(d.sSortJUIWrapper).append(b.contents()).append(h(" ").addClass(d.sSortIcon + " " + c.sSortingClassJUI)).appendTo(b); h(a.nTable).on("order.dt.DT", function (e, f, g, h) {
if (a === f) {
e = c.idx; b.removeClass(d.sSortAsc + " " + d.sSortDesc).addClass(h[e] == "asc" ? d.sSortAsc : h[e] == "desc" ? d.sSortDesc : c.sSortingClass); b.find("span." + d.sSortIcon).removeClass(d.sSortJUIAsc + " " + d.sSortJUIDesc + " " + d.sSortJUI + " " + d.sSortJUIAscAllowed + " " + d.sSortJUIDescAllowed).addClass(h[e] ==
"asc" ? d.sSortJUIAsc : h[e] == "desc" ? d.sSortJUIDesc : c.sSortingClassJUI)
}
})
}
}
}); var Vb = function (a) { return "string" === typeof a ? a.replace(//g, ">").replace(/"/g, """) : a }; n.render = {
number: function (a, b, c, d, e) {
return {
display: function (f) {
if ("number" !== typeof f && "string" !== typeof f) return f; var g = 0 > f ? "-" : "", h = parseFloat(f); if (isNaN(h)) return Vb(f); h = h.toFixed(c); f = Math.abs(h); h = parseInt(f, 10); f = c ? b + (f - h).toFixed(c).substring(2) : ""; return g + (d || "") + h.toString().replace(/\B(?=(\d{3})+(?!\d))/g,
a) + f + (e || "")
}
}
}, text: function () { return { display: Vb } }
}; h.extend(n.ext.internal, {
_fnExternApiFunc: Lb, _fnBuildAjax: sa, _fnAjaxUpdate: lb, _fnAjaxParameters: ub, _fnAjaxUpdateDraw: vb, _fnAjaxDataSrc: ta, _fnAddColumn: Ea, _fnColumnOptions: ka, _fnAdjustColumnSizing: $, _fnVisibleToColumnIndex: aa, _fnColumnIndexToVisible: ba, _fnVisbleColumns: V, _fnGetColumns: ma, _fnColumnTypes: Ga, _fnApplyColumnDefs: ib, _fnHungarianMap: Z, _fnCamelToHungarian: J, _fnLanguageCompat: Ca, _fnBrowserDetect: gb, _fnAddData: O, _fnAddTr: na, _fnNodeToDataIndex: function (a,
b) { return b._DT_RowIndex !== k ? b._DT_RowIndex : null }, _fnNodeToColumnIndex: function (a, b, c) { return h.inArray(c, a.aoData[b].anCells) }, _fnGetCellData: B, _fnSetCellData: jb, _fnSplitObjNotation: Ja, _fnGetObjectDataFn: S, _fnSetObjectDataFn: N, _fnGetDataMaster: Ka, _fnClearTable: oa, _fnDeleteIndex: pa, _fnInvalidate: da, _fnGetRowElements: Ia, _fnCreateTr: Ha, _fnBuildHead: kb, _fnDrawHead: fa, _fnDraw: P, _fnReDraw: T, _fnAddOptionsHtml: nb, _fnDetectHeader: ea, _fnGetUniqueThs: ra, _fnFeatureHtmlFilter: pb, _fnFilterComplete: ga, _fnFilterCustom: yb,
_fnFilterColumn: xb, _fnFilter: wb, _fnFilterCreateSearch: Pa, _fnEscapeRegex: Qa, _fnFilterData: zb, _fnFeatureHtmlInfo: sb, _fnUpdateInfo: Cb, _fnInfoMacros: Db, _fnInitialise: ha, _fnInitComplete: ua, _fnLengthChange: Ra, _fnFeatureHtmlLength: ob, _fnFeatureHtmlPaginate: tb, _fnPageChange: Ta, _fnFeatureHtmlProcessing: qb, _fnProcessingDisplay: C, _fnFeatureHtmlTable: rb, _fnScrollDraw: la, _fnApplyToChildren: I, _fnCalculateColumnWidths: Fa, _fnThrottle: Oa, _fnConvertToWidth: Eb, _fnGetWidestNode: Fb, _fnGetMaxLenString: Gb, _fnStringToCss: v,
_fnSortFlatten: X, _fnSort: mb, _fnSortAria: Ib, _fnSortListener: Va, _fnSortAttachListener: Ma, _fnSortingClasses: wa, _fnSortData: Hb, _fnSaveState: xa, _fnLoadState: Jb, _fnSettingsFromNode: ya, _fnLog: K, _fnMap: F, _fnBindAction: Wa, _fnCallbackReg: z, _fnCallbackFire: r, _fnLengthOverflow: Sa, _fnRenderer: Na, _fnDataSource: y, _fnRowAttributes: La, _fnExtend: Xa, _fnCalculateEnd: function () { }
}); h.fn.dataTable = n; n.$ = h; h.fn.dataTableSettings = n.settings; h.fn.dataTableExt = n.ext; h.fn.DataTable = function (a) { return h(this).dataTable(a).api() };
h.each(n, function (a, b) { h.fn.DataTable[a] = b }); return h.fn.dataTable
});
(function () {
function C() { var a = "{}"; if ("userDataBehavior" == f) { g.load("jStorage"); try { a = g.getAttribute("jStorage") } catch (b) { } try { r = g.getAttribute("jStorage_update") } catch (c) { } h.jStorage = a } D(); x(); E() } function u() {
var a; clearTimeout(F); F = setTimeout(function () {
if ("localStorage" == f || "globalStorage" == f) a = h.jStorage_update; else if ("userDataBehavior" == f) { g.load("jStorage"); try { a = g.getAttribute("jStorage_update") } catch (b) { } } if (a && a != r) {
r = a; var l = p.parse(p.stringify(c.__jstorage_meta.CRC32)), k; C(); k = p.parse(p.stringify(c.__jstorage_meta.CRC32));
var d, n = [], e = []; for (d in l) l.hasOwnProperty(d) && (k[d] ? l[d] != k[d] && "2." == String(l[d]).substr(0, 2) && n.push(d) : e.push(d)); for (d in k) k.hasOwnProperty(d) && (l[d] || n.push(d)); s(n, "updated"); s(e, "deleted")
}
}, 25)
} function s(a, b) { a = [].concat(a || []); var c, k, d, n; if ("flushed" == b) { a = []; for (c in m) m.hasOwnProperty(c) && a.push(c); b = "deleted" } c = 0; for (d = a.length; c < d; c++) { if (m[a[c]]) for (k = 0, n = m[a[c]].length; k < n; k++)m[a[c]][k](a[c], b); if (m["*"]) for (k = 0, n = m["*"].length; k < n; k++)m["*"][k](a[c], b) } } function v() {
var a = (+new Date).toString();
if ("localStorage" == f || "globalStorage" == f) try { h.jStorage_update = a } catch (b) { f = !1 } else "userDataBehavior" == f && (g.setAttribute("jStorage_update", a), g.save("jStorage")); u()
} function D() { if (h.jStorage) try { c = p.parse(String(h.jStorage)) } catch (a) { h.jStorage = "{}" } else h.jStorage = "{}"; z = h.jStorage ? String(h.jStorage).length : 0; c.__jstorage_meta || (c.__jstorage_meta = {}); c.__jstorage_meta.CRC32 || (c.__jstorage_meta.CRC32 = {}) } function w() {
if (c.__jstorage_meta.PubSub) {
for (var a = +new Date - 2E3, b = 0, l = c.__jstorage_meta.PubSub.length; b <
l; b++)if (c.__jstorage_meta.PubSub[b][0] <= a) { c.__jstorage_meta.PubSub.splice(b, c.__jstorage_meta.PubSub.length - b); break } c.__jstorage_meta.PubSub.length || delete c.__jstorage_meta.PubSub
} try { h.jStorage = p.stringify(c), g && (g.setAttribute("jStorage", h.jStorage), g.save("jStorage")), z = h.jStorage ? String(h.jStorage).length : 0 } catch (k) { }
} function q(a) {
if ("string" != typeof a && "number" != typeof a) throw new TypeError("Key name must be string or numeric"); if ("__jstorage_meta" == a) throw new TypeError("Reserved key name");
return !0
} function x() { var a, b, l, k, d = Infinity, n = !1, e = []; clearTimeout(G); if (c.__jstorage_meta && "object" == typeof c.__jstorage_meta.TTL) { a = +new Date; l = c.__jstorage_meta.TTL; k = c.__jstorage_meta.CRC32; for (b in l) l.hasOwnProperty(b) && (l[b] <= a ? (delete l[b], delete k[b], delete c[b], n = !0, e.push(b)) : l[b] < d && (d = l[b])); Infinity != d && (G = setTimeout(x, Math.min(d - a, 2147483647))); n && (w(), v(), s(e, "deleted")) } } function E() {
var a; if (c.__jstorage_meta.PubSub) {
var b, l = A, k = []; for (a = c.__jstorage_meta.PubSub.length - 1; 0 <= a; a--)b =
c.__jstorage_meta.PubSub[a], b[0] > A && (l = b[0], k.unshift(b)); for (a = k.length - 1; 0 <= a; a--) { b = k[a][1]; var d = k[a][2]; if (t[b]) for (var n = 0, e = t[b].length; n < e; n++)try { t[b][n](b, p.parse(p.stringify(d))) } catch (g) { } } A = l
}
} var y = window.jQuery || window.$ || (window.$ = {}), p = { parse: window.JSON && (window.JSON.parse || window.JSON.decode) || String.prototype.evalJSON && function (a) { return String(a).evalJSON() } || y.parseJSON || y.evalJSON, stringify: Object.toJSON || window.JSON && (window.JSON.stringify || window.JSON.encode) || y.toJSON }; if ("function" !==
typeof p.parse || "function" !== typeof p.stringify) throw Error("No JSON support found, include //cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js to page"); var c = { __jstorage_meta: { CRC32: {} } }, h = { jStorage: "{}" }, g = null, z = 0, f = !1, m = {}, F = !1, r = 0, t = {}, A = +new Date, G, B = {
isXML: function (a) { return (a = (a ? a.ownerDocument || a : 0).documentElement) ? "HTML" !== a.nodeName : !1 }, encode: function (a) { if (!this.isXML(a)) return !1; try { return (new XMLSerializer).serializeToString(a) } catch (b) { try { return a.xml } catch (c) { } } return !1 },
decode: function (a) { var b = "DOMParser" in window && (new DOMParser).parseFromString || window.ActiveXObject && function (a) { var b = new ActiveXObject("Microsoft.XMLDOM"); b.async = "false"; b.loadXML(a); return b }; if (!b) return !1; a = b.call("DOMParser" in window && new DOMParser || window, a, "text/xml"); return this.isXML(a) ? a : !1 }
}; y.jStorage = {
version: "0.4.13", set: function (a, b, l) {
q(a); l = l || {}; if ("undefined" == typeof b) return this.deleteKey(a), b; if (B.isXML(b)) b = { _is_xml: !0, xml: B.encode(b) }; else {
if ("function" == typeof b) return;
b && "object" == typeof b && (b = p.parse(p.stringify(b)))
} c[a] = b; for (var k = c.__jstorage_meta.CRC32, d = p.stringify(b), g = d.length, e = 2538058380 ^ g, h = 0, f; 4 <= g;)f = d.charCodeAt(h) & 255 | (d.charCodeAt(++h) & 255) << 8 | (d.charCodeAt(++h) & 255) << 16 | (d.charCodeAt(++h) & 255) << 24, f = 1540483477 * (f & 65535) + ((1540483477 * (f >>> 16) & 65535) << 16), f ^= f >>> 24, f = 1540483477 * (f & 65535) + ((1540483477 * (f >>> 16) & 65535) << 16), e = 1540483477 * (e & 65535) + ((1540483477 * (e >>> 16) & 65535) << 16) ^ f, g -= 4, ++h; switch (g) {
case 3: e ^= (d.charCodeAt(h + 2) & 255) << 16; case 2: e ^=
(d.charCodeAt(h + 1) & 255) << 8; case 1: e ^= d.charCodeAt(h) & 255, e = 1540483477 * (e & 65535) + ((1540483477 * (e >>> 16) & 65535) << 16)
}e ^= e >>> 13; e = 1540483477 * (e & 65535) + ((1540483477 * (e >>> 16) & 65535) << 16); k[a] = "2." + ((e ^ e >>> 15) >>> 0); this.setTTL(a, l.TTL || 0); s(a, "updated"); return b
}, get: function (a, b) { q(a); return a in c ? c[a] && "object" == typeof c[a] && c[a]._is_xml ? B.decode(c[a].xml) : c[a] : "undefined" == typeof b ? null : b }, deleteKey: function (a) {
q(a); return a in c ? (delete c[a], "object" == typeof c.__jstorage_meta.TTL && a in c.__jstorage_meta.TTL &&
delete c.__jstorage_meta.TTL[a], delete c.__jstorage_meta.CRC32[a], w(), v(), s(a, "deleted"), !0) : !1
}, setTTL: function (a, b) { var l = +new Date; q(a); b = Number(b) || 0; return a in c ? (c.__jstorage_meta.TTL || (c.__jstorage_meta.TTL = {}), 0 < b ? c.__jstorage_meta.TTL[a] = l + b : delete c.__jstorage_meta.TTL[a], w(), x(), v(), !0) : !1 }, getTTL: function (a) { var b = +new Date; q(a); return a in c && c.__jstorage_meta.TTL && c.__jstorage_meta.TTL[a] ? (a = c.__jstorage_meta.TTL[a] - b) || 0 : 0 }, flush: function () {
c = { __jstorage_meta: { CRC32: {} } }; w(); v(); s(null,
"flushed"); return !0
}, storageObj: function () { function a() { } a.prototype = c; return new a }, index: function () { var a = [], b; for (b in c) c.hasOwnProperty(b) && "__jstorage_meta" != b && a.push(b); return a }, storageSize: function () { return z }, currentBackend: function () { return f }, storageAvailable: function () { return !!f }, listenKeyChange: function (a, b) { q(a); m[a] || (m[a] = []); m[a].push(b) }, stopListening: function (a, b) { q(a); if (m[a]) if (b) for (var c = m[a].length - 1; 0 <= c; c--)m[a][c] == b && m[a].splice(c, 1); else delete m[a] }, subscribe: function (a,
b) { a = (a || "").toString(); if (!a) throw new TypeError("Channel not defined"); t[a] || (t[a] = []); t[a].push(b) }, publish: function (a, b) { a = (a || "").toString(); if (!a) throw new TypeError("Channel not defined"); c.__jstorage_meta || (c.__jstorage_meta = {}); c.__jstorage_meta.PubSub || (c.__jstorage_meta.PubSub = []); c.__jstorage_meta.PubSub.unshift([+new Date, a, b]); w(); v() }, reInit: function () { C() }, noConflict: function (a) { delete window.$.jStorage; a && (window.jStorage = this); return this }
}; (function () {
var a = !1; if ("localStorage" in
window) try { window.localStorage.setItem("_tmptest", "tmpval"), a = !0, window.localStorage.removeItem("_tmptest") } catch (b) { } if (a) try { window.localStorage && (h = window.localStorage, f = "localStorage", r = h.jStorage_update) } catch (c) { } else if ("globalStorage" in window) try { window.globalStorage && (h = "localhost" == window.location.hostname ? window.globalStorage["localhost.localdomain"] : window.globalStorage[window.location.hostname], f = "globalStorage", r = h.jStorage_update) } catch (k) { } else if (g = document.createElement("link"),
g.addBehavior) { g.style.behavior = "url(#default#userData)"; document.getElementsByTagName("head")[0].appendChild(g); try { g.load("jStorage") } catch (d) { g.setAttribute("jStorage", "{}"), g.save("jStorage"), g.load("jStorage") } a = "{}"; try { a = g.getAttribute("jStorage") } catch (m) { } try { r = g.getAttribute("jStorage_update") } catch (e) { } h.jStorage = a; f = "userDataBehavior" } else { g = null; return } D(); x(); "localStorage" == f || "globalStorage" == f ? "addEventListener" in window ? window.addEventListener("storage", u, !1) : document.attachEvent("onstorage",
u) : "userDataBehavior" == f && setInterval(u, 1E3); E(); "addEventListener" in window && window.addEventListener("pageshow", function (a) { a.persisted && u() }, !1)
})()
})();
/*! Select2 4.0.6-rc.1 | https://github.com/select2/select2/blob/master/LICENSE.md */!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=function(b,c){return void 0===c&&(c="undefined"!=typeof window?require("jquery"):require("jquery")(b)),a(c),c}:a(jQuery)}(function(a){var b=function(){if(a&&a.fn&&a.fn.select2&&a.fn.select2.amd)var b=a.fn.select2.amd;var b;return function(){if(!b||!b.requirejs){b?c=b:b={};var a,c,d;!function(b){function e(a,b){return v.call(a,b)}function f(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o=b&&b.split("/"),p=t.map,q=p&&p["*"]||{};if(a){for(a=a.split("/"),g=a.length-1,t.nodeIdCompat&&x.test(a[g])&&(a[g]=a[g].replace(x,"")),"."===a[0].charAt(0)&&o&&(n=o.slice(0,o.length-1),a=n.concat(a)),k=0;k 0&&(a.splice(k-1,2),k-=2)}a=a.join("/")}if((o||q)&&p){for(c=a.split("/"),k=c.length;k>0;k-=1){if(d=c.slice(0,k).join("/"),o)for(l=o.length;l>0;l-=1)if((e=p[o.slice(0,l).join("/")])&&(e=e[d])){f=e,h=k;break}if(f)break;!i&&q&&q[d]&&(i=q[d],j=k)}!f&&i&&(f=i,h=j),f&&(c.splice(0,h,f),a=c.join("/"))}return a}function g(a,c){return function(){var d=w.call(arguments,0);return"string"!=typeof d[0]&&1===d.length&&d.push(null),o.apply(b,d.concat([a,c]))}}function h(a){return function(b){return f(b,a)}}function i(a){return function(b){r[a]=b}}function j(a){if(e(s,a)){var c=s[a];delete s[a],u[a]=!0,n.apply(b,c)}if(!e(r,a)&&!e(u,a))throw new Error("No "+a);return r[a]}function k(a){var b,c=a?a.indexOf("!"):-1;return c>-1&&(b=a.substring(0,c),a=a.substring(c+1,a.length)),[b,a]}function l(a){return a?k(a):[]}function m(a){return function(){return t&&t.config&&t.config[a]||{}}}var n,o,p,q,r={},s={},t={},u={},v=Object.prototype.hasOwnProperty,w=[].slice,x=/\.js$/;p=function(a,b){var c,d=k(a),e=d[0],g=b[1];return a=d[1],e&&(e=f(e,g),c=j(e)),e?a=c&&c.normalize?c.normalize(a,h(g)):f(a,g):(a=f(a,g),d=k(a),e=d[0],a=d[1],e&&(c=j(e))),{f:e?e+"!"+a:a,n:a,pr:e,p:c}},q={require:function(a){return g(a)},exports:function(a){var b=r[a];return void 0!==b?b:r[a]={}},module:function(a){return{id:a,uri:"",exports:r[a],config:m(a)}}},n=function(a,c,d,f){var h,k,m,n,o,t,v,w=[],x=typeof d;if(f=f||a,t=l(f),"undefined"===x||"function"===x){for(c=!c.length&&d.length?["require","exports","module"]:c,o=0;o0&&(b.call(arguments,a.prototype.constructor),e=c.prototype.constructor),e.apply(this,arguments)}function e(){this.constructor=d}var f=b(c),g=b(a);c.displayName=a.displayName,d.prototype=new e;for(var h=0;h":">",'"':""","'":"'","/":"/"};return"string"!=typeof a?a:String(a).replace(/[&<>"'\/\\]/g,function(a){return b[a]})},c.appendMany=function(b,c){if("1.7"===a.fn.jquery.substr(0,3)){var d=a();a.map(c,function(a){d=d.add(a)}),c=d}b.append(c)},c.__cache={};var e=0;return c.GetUniqueElementId=function(a){var b=a.getAttribute("data-select2-id");return null==b&&(a.id?(b=a.id,a.setAttribute("data-select2-id",b)):(a.setAttribute("data-select2-id",++e),b=e.toString())),b},c.StoreData=function(a,b,d){var e=c.GetUniqueElementId(a);c.__cache[e]||(c.__cache[e]={}),c.__cache[e][b]=d},c.GetData=function(b,d){var e=c.GetUniqueElementId(b);return d?c.__cache[e]&&null!=c.__cache[e][d]?c.__cache[e][d]:a(b).data(d):c.__cache[e]},c.RemoveData=function(a){var b=c.GetUniqueElementId(a);null!=c.__cache[b]&&delete c.__cache[b]},c}),b.define("select2/results",["jquery","./utils"],function(a,b){function c(a,b,d){this.$element=a,this.data=d,this.options=b,c.__super__.constructor.call(this)}return b.Extend(c,b.Observable),c.prototype.render=function(){var b=a('');return this.options.get("multiple")&&b.attr("aria-multiselectable","true"),this.$results=b,b},c.prototype.clear=function(){this.$results.empty()},c.prototype.displayMessage=function(b){var c=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var d=a(' '),e=this.options.get("translations").get(b.message);d.append(c(e(b.args))),d[0].className+=" select2-results__message",this.$results.append(d)},c.prototype.hideMessages=function(){this.$results.find(".select2-results__message").remove()},c.prototype.append=function(a){this.hideLoading();var b=[];if(null==a.results||0===a.results.length)return void(0===this.$results.children().length&&this.trigger("results:message",{message:"noResults"}));a.results=this.sort(a.results);for(var c=0;c0?b.first().trigger("mouseenter"):a.first().trigger("mouseenter"),this.ensureHighlightVisible()},c.prototype.setClasses=function(){var c=this;this.data.current(function(d){var e=a.map(d,function(a){return a.id.toString()});c.$results.find(".select2-results__option[aria-selected]").each(function(){var c=a(this),d=b.GetData(this,"data"),f=""+d.id;null!=d.element&&d.element.selected||null==d.element&&a.inArray(f,e)>-1?c.attr("aria-selected","true"):c.attr("aria-selected","false")})})},c.prototype.showLoading=function(a){this.hideLoading();var b=this.options.get("translations").get("searching"),c={disabled:!0,loading:!0,text:b(a)},d=this.option(c);d.className+=" loading-results",this.$results.prepend(d)},c.prototype.hideLoading=function(){this.$results.find(".loading-results").remove()},c.prototype.option=function(c){var d=document.createElement("li");d.className="select2-results__option";var e={role:"treeitem","aria-selected":"false"};c.disabled&&(delete e["aria-selected"],e["aria-disabled"]="true"),null==c.id&&delete e["aria-selected"],null!=c._resultId&&(d.id=c._resultId),c.title&&(d.title=c.title),c.children&&(e.role="group",e["aria-label"]=c.text,delete e["aria-selected"]);for(var f in e){var g=e[f];d.setAttribute(f,g)}if(c.children){var h=a(d),i=document.createElement("strong");i.className="select2-results__group";a(i);this.template(c,i);for(var j=[],k=0;k",{class:"select2-results__options select2-results__options--nested"});n.append(j),h.append(i),h.append(n)}else this.template(c,d);return b.StoreData(d,"data",c),d},c.prototype.bind=function(c,d){var e=this,f=c.id+"-results";this.$results.attr("id",f),c.on("results:all",function(a){e.clear(),e.append(a.data),c.isOpen()&&(e.setClasses(),e.highlightFirstItem())}),c.on("results:append",function(a){e.append(a.data),c.isOpen()&&e.setClasses()}),c.on("query",function(a){e.hideMessages(),e.showLoading(a)}),c.on("select",function(){c.isOpen()&&(e.setClasses(),e.highlightFirstItem())}),c.on("unselect",function(){c.isOpen()&&(e.setClasses(),e.highlightFirstItem())}),c.on("open",function(){e.$results.attr("aria-expanded","true"),e.$results.attr("aria-hidden","false"),e.setClasses(),e.ensureHighlightVisible()}),c.on("close",function(){e.$results.attr("aria-expanded","false"),e.$results.attr("aria-hidden","true"),e.$results.removeAttr("aria-activedescendant")}),c.on("results:toggle",function(){var a=e.getHighlightedResults();0!==a.length&&a.trigger("mouseup")}),c.on("results:select",function(){var a=e.getHighlightedResults();if(0!==a.length){var c=b.GetData(a[0],"data");"true"==a.attr("aria-selected")?e.trigger("close",{}):e.trigger("select",{data:c})}}),c.on("results:previous",function(){var a=e.getHighlightedResults(),b=e.$results.find("[aria-selected]"),c=b.index(a);if(!(c<=0)){var d=c-1;0===a.length&&(d=0);var f=b.eq(d);f.trigger("mouseenter");var g=e.$results.offset().top,h=f.offset().top,i=e.$results.scrollTop()+(h-g);0===d?e.$results.scrollTop(0):h-g<0&&e.$results.scrollTop(i)}}),c.on("results:next",function(){var a=e.getHighlightedResults(),b=e.$results.find("[aria-selected]"),c=b.index(a),d=c+1;if(!(d>=b.length)){var f=b.eq(d);f.trigger("mouseenter");var g=e.$results.offset().top+e.$results.outerHeight(!1),h=f.offset().top+f.outerHeight(!1),i=e.$results.scrollTop()+h-g;0===d?e.$results.scrollTop(0):h>g&&e.$results.scrollTop(i)}}),c.on("results:focus",function(a){a.element.addClass("select2-results__option--highlighted")}),c.on("results:message",function(a){e.displayMessage(a)}),a.fn.mousewheel&&this.$results.on("mousewheel",function(a){var b=e.$results.scrollTop(),c=e.$results.get(0).scrollHeight-b+a.deltaY,d=a.deltaY>0&&b-a.deltaY<=0,f=a.deltaY<0&&c<=e.$results.height();d?(e.$results.scrollTop(0),a.preventDefault(),a.stopPropagation()):f&&(e.$results.scrollTop(e.$results.get(0).scrollHeight-e.$results.height()),a.preventDefault(),a.stopPropagation())}),this.$results.on("mouseup",".select2-results__option[aria-selected]",function(c){var d=a(this),f=b.GetData(this,"data");if("true"===d.attr("aria-selected"))return void(e.options.get("multiple")?e.trigger("unselect",{originalEvent:c,data:f}):e.trigger("close",{}));e.trigger("select",{originalEvent:c,data:f})}),this.$results.on("mouseenter",".select2-results__option[aria-selected]",function(c){var d=b.GetData(this,"data");e.getHighlightedResults().removeClass("select2-results__option--highlighted"),e.trigger("results:focus",{data:d,element:a(this)})})},c.prototype.getHighlightedResults=function(){return this.$results.find(".select2-results__option--highlighted")},c.prototype.destroy=function(){this.$results.remove()},c.prototype.ensureHighlightVisible=function(){var a=this.getHighlightedResults();if(0!==a.length){var b=this.$results.find("[aria-selected]"),c=b.index(a),d=this.$results.offset().top,e=a.offset().top,f=this.$results.scrollTop()+(e-d),g=e-d;f-=2*a.outerHeight(!1),c<=2?this.$results.scrollTop(0):(g>this.$results.outerHeight()||g<0)&&this.$results.scrollTop(f)}},c.prototype.template=function(b,c){var d=this.options.get("templateResult"),e=this.options.get("escapeMarkup"),f=d(b,c);null==f?c.style.display="none":"string"==typeof f?c.innerHTML=e(f):a(c).append(f)},c}),b.define("select2/keys",[],function(){return{BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}}),b.define("select2/selection/base",["jquery","../utils","../keys"],function(a,b,c){function d(a,b){this.$element=a,this.options=b,d.__super__.constructor.call(this)}return b.Extend(d,b.Observable),d.prototype.render=function(){var c=a(' ');return this._tabindex=0,null!=b.GetData(this.$element[0],"old-tabindex")?this._tabindex=b.GetData(this.$element[0],"old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),c.attr("title",this.$element.attr("title")),c.attr("tabindex",this._tabindex),this.$selection=c,c},d.prototype.bind=function(a,b){var d=this,e=(a.id,a.id+"-results");this.container=a,this.$selection.on("focus",function(a){d.trigger("focus",a)}),this.$selection.on("blur",function(a){d._handleBlur(a)}),this.$selection.on("keydown",function(a){d.trigger("keypress",a),a.which===c.SPACE&&a.preventDefault()}),a.on("results:focus",function(a){d.$selection.attr("aria-activedescendant",a.data._resultId)}),a.on("selection:update",function(a){d.update(a.data)}),a.on("open",function(){d.$selection.attr("aria-expanded","true"),d.$selection.attr("aria-owns",e),d._attachCloseHandler(a)}),a.on("close",function(){d.$selection.attr("aria-expanded","false"),d.$selection.removeAttr("aria-activedescendant"),d.$selection.removeAttr("aria-owns"),d.$selection.focus(),window.setTimeout(function(){d.$selection.focus()},0),d._detachCloseHandler(a)}),a.on("enable",function(){d.$selection.attr("tabindex",d._tabindex)}),a.on("disable",function(){d.$selection.attr("tabindex","-1")})},d.prototype._handleBlur=function(b){var c=this;window.setTimeout(function(){document.activeElement==c.$selection[0]||a.contains(c.$selection[0],document.activeElement)||c.trigger("blur",b)},1)},d.prototype._attachCloseHandler=function(c){a(document.body).on("mousedown.select2."+c.id,function(c){var d=a(c.target),e=d.closest(".select2");a(".select2.select2-container--open").each(function(){a(this),this!=e[0]&&b.GetData(this,"element").select2("close")})})},d.prototype._detachCloseHandler=function(b){a(document.body).off("mousedown.select2."+b.id)},d.prototype.position=function(a,b){b.find(".selection").append(a)},d.prototype.destroy=function(){this._detachCloseHandler(this.container)},d.prototype.update=function(a){throw new Error("The `update` method must be defined in child classes.")},d}),b.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(a,b,c,d){function e(){e.__super__.constructor.apply(this,arguments)}return c.Extend(e,b),e.prototype.render=function(){var a=e.__super__.render.call(this);return a.addClass("select2-selection--single"),a.html(' '),a},e.prototype.bind=function(a,b){var c=this;e.__super__.bind.apply(this,arguments);var d=a.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",d).attr("role","textbox").attr("aria-readonly","true"),this.$selection.attr("aria-labelledby",d),this.$selection.on("mousedown",function(a){1===a.which&&c.trigger("toggle",{originalEvent:a})}),this.$selection.on("focus",function(a){}),this.$selection.on("blur",function(a){}),a.on("focus",function(b){a.isOpen()||c.$selection.focus()})},e.prototype.clear=function(){var a=this.$selection.find(".select2-selection__rendered");a.empty(),a.removeAttr("title")},e.prototype.display=function(a,b){var c=this.options.get("templateSelection");return this.options.get("escapeMarkup")(c(a,b))},e.prototype.selectionContainer=function(){return a(" ")},e.prototype.update=function(a){if(0===a.length)return void this.clear();var b=a[0],c=this.$selection.find(".select2-selection__rendered"),d=this.display(b,c);c.empty().append(d),c.attr("title",b.title||b.text)},e}),b.define("select2/selection/multiple",["jquery","./base","../utils"],function(a,b,c){function d(a,b){d.__super__.constructor.apply(this,arguments)}return c.Extend(d,b),d.prototype.render=function(){var a=d.__super__.render.call(this);return a.addClass("select2-selection--multiple"),a.html(''),a},d.prototype.bind=function(b,e){var f=this;d.__super__.bind.apply(this,arguments),this.$selection.on("click",function(a){f.trigger("toggle",{originalEvent:a})}),this.$selection.on("click",".select2-selection__choice__remove",function(b){if(!f.options.get("disabled")){var d=a(this),e=d.parent(),g=c.GetData(e[0],"data");f.trigger("unselect",{originalEvent:b,data:g})}})},d.prototype.clear=function(){var a=this.$selection.find(".select2-selection__rendered");a.empty(),a.removeAttr("title")},d.prototype.display=function(a,b){var c=this.options.get("templateSelection");return this.options.get("escapeMarkup")(c(a,b))},d.prototype.selectionContainer=function(){return a('× ')},d.prototype.update=function(a){if(this.clear(),0!==a.length){for(var b=[],d=0;d1||c)return a.call(this,b);this.clear();var d=this.createPlaceholder(this.placeholder);this.$selection.find(".select2-selection__rendered").append(d)},b}),b.define("select2/selection/allowClear",["jquery","../keys","../utils"],function(a,b,c){function d(){}return d.prototype.bind=function(a,b,c){var d=this;a.call(this,b,c),null==this.placeholder&&this.options.get("debug")&&window.console&&console.error&&console.error("Select2: The `allowClear` option should be used in combination with the `placeholder` option."),this.$selection.on("mousedown",".select2-selection__clear",function(a){d._handleClear(a)}),b.on("keypress",function(a){d._handleKeyboardClear(a,b)})},d.prototype._handleClear=function(a,b){if(!this.options.get("disabled")){var d=this.$selection.find(".select2-selection__clear");if(0!==d.length){b.stopPropagation();var e=c.GetData(d[0],"data"),f=this.$element.val();this.$element.val(this.placeholder.id);var g={data:e};if(this.trigger("clear",g),g.prevented)return void this.$element.val(f);for(var h=0;h0||0===d.length)){var e=a('× ');c.StoreData(e[0],"data",d),this.$selection.find(".select2-selection__rendered").prepend(e)}},d}),b.define("select2/selection/search",["jquery","../utils","../keys"],function(a,b,c){function d(a,b,c){a.call(this,b,c)}return d.prototype.render=function(b){var c=a(' ');this.$searchContainer=c,this.$search=c.find("input");var d=b.call(this);return this._transferTabIndex(),d},d.prototype.bind=function(a,d,e){var f=this;a.call(this,d,e),d.on("open",function(){f.$search.trigger("focus")}),d.on("close",function(){f.$search.val(""),f.$search.removeAttr("aria-activedescendant"),f.$search.trigger("focus")}),d.on("enable",function(){f.$search.prop("disabled",!1),f._transferTabIndex()}),d.on("disable",function(){f.$search.prop("disabled",!0)}),d.on("focus",function(a){f.$search.trigger("focus")}),d.on("results:focus",function(a){f.$search.attr("aria-activedescendant",a.id)}),this.$selection.on("focusin",".select2-search--inline",function(a){f.trigger("focus",a)}),this.$selection.on("focusout",".select2-search--inline",function(a){f._handleBlur(a)}),this.$selection.on("keydown",".select2-search--inline",function(a){if(a.stopPropagation(),f.trigger("keypress",a),f._keyUpPrevented=a.isDefaultPrevented(),a.which===c.BACKSPACE&&""===f.$search.val()){var d=f.$searchContainer.prev(".select2-selection__choice");if(d.length>0){var e=b.GetData(d[0],"data");f.searchRemoveChoice(e),a.preventDefault()}}});var g=document.documentMode,h=g&&g<=11;this.$selection.on("input.searchcheck",".select2-search--inline",function(a){if(h)return void f.$selection.off("input.search input.searchcheck");f.$selection.off("keyup.search")}),this.$selection.on("keyup.search input.search",".select2-search--inline",function(a){if(h&&"input"===a.type)return void f.$selection.off("input.search input.searchcheck");var b=a.which;b!=c.SHIFT&&b!=c.CTRL&&b!=c.ALT&&b!=c.TAB&&f.handleSearch(a)})},d.prototype._transferTabIndex=function(a){this.$search.attr("tabindex",this.$selection.attr("tabindex")),this.$selection.attr("tabindex","-1")},d.prototype.createPlaceholder=function(a,b){this.$search.attr("placeholder",b.text)},d.prototype.update=function(a,b){var c=this.$search[0]==document.activeElement;if(this.$search.attr("placeholder",""),a.call(this,b),this.$selection.find(".select2-selection__rendered").append(this.$searchContainer),this.resizeSearch(),c){this.$element.find("[data-select2-tag]").length?this.$element.focus():this.$search.focus()}},d.prototype.handleSearch=function(){if(this.resizeSearch(),!this._keyUpPrevented){var a=this.$search.val();this.trigger("query",{term:a})}this._keyUpPrevented=!1},d.prototype.searchRemoveChoice=function(a,b){this.trigger("unselect",{data:b}),this.$search.val(b.text),this.handleSearch()},d.prototype.resizeSearch=function(){this.$search.css("width","25px");var a="";if(""!==this.$search.attr("placeholder"))a=this.$selection.find(".select2-selection__rendered").innerWidth();else{a=.75*(this.$search.val().length+1)+"em"}this.$search.css("width",a)},d}),b.define("select2/selection/eventRelay",["jquery"],function(a){function b(){}return b.prototype.bind=function(b,c,d){var e=this,f=["open","opening","close","closing","select","selecting","unselect","unselecting","clear","clearing"],g=["opening","closing","selecting","unselecting","clearing"];b.call(this,c,d),c.on("*",function(b,c){if(-1!==a.inArray(b,f)){c=c||{};var d=a.Event("select2:"+b,{params:c});e.$element.trigger(d),-1!==a.inArray(b,g)&&(c.prevented=d.isDefaultPrevented())}})},b}),b.define("select2/translation",["jquery","require"],function(a,b){function c(a){this.dict=a||{}}return c.prototype.all=function(){return this.dict},c.prototype.get=function(a){return this.dict[a]},c.prototype.extend=function(b){this.dict=a.extend({},b.all(),this.dict)},c._cache={},c.loadPath=function(a){if(!(a in c._cache)){var d=b(a);c._cache[a]=d}return new c(c._cache[a])},c}),b.define("select2/diacritics",[],function(){return{"Ⓐ":"A","A":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A","Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","B":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","C":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","D":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","DZ":"DZ","DŽ":"DZ","Dz":"Dz","Dž":"Dz","Ⓔ":"E","E":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","F":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","G":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","H":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","I":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","J":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","K":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","L":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","LJ":"LJ","Lj":"Lj","Ⓜ":"M","M":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","N":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","NJ":"NJ","Nj":"Nj","Ⓞ":"O","O":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","P":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Q":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","R":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","S":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","T":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","U":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","V":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","W":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","X":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Y":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Z":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","a":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","b":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","c":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","d":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","dz":"dz","dž":"dz","ⓔ":"e","e":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","f":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","g":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","h":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","i":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","j":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","k":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","l":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","lj":"lj","ⓜ":"m","m":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","n":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ʼn":"n","ꞑ":"n","ꞥ":"n","nj":"nj","ⓞ":"o","o":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","p":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","q":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","r":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","s":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","t":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","u":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","v":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","w":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","x":"x","ẋ":"x","ẍ":"x","ⓨ":"y","y":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","z":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z","Ά":"Α","Έ":"Ε","Ή":"Η","Ί":"Ι","Ϊ":"Ι","Ό":"Ο","Ύ":"Υ","Ϋ":"Υ","Ώ":"Ω","ά":"α","έ":"ε","ή":"η","ί":"ι","ϊ":"ι","ΐ":"ι","ό":"ο","ύ":"υ","ϋ":"υ","ΰ":"υ","ω":"ω","ς":"σ"}}),b.define("select2/data/base",["../utils"],function(a){function b(a,c){b.__super__.constructor.call(this)}return a.Extend(b,a.Observable),b.prototype.current=function(a){throw new Error("The `current` method must be defined in child classes.")},b.prototype.query=function(a,b){throw new Error("The `query` method must be defined in child classes.")},b.prototype.bind=function(a,b){},b.prototype.destroy=function(){},b.prototype.generateResultId=function(b,c){var d=b.id+"-result-";return d+=a.generateChars(4),null!=c.id?d+="-"+c.id.toString():d+="-"+a.generateChars(4),d},b}),b.define("select2/data/select",["./base","../utils","jquery"],function(a,b,c){function d(a,b){this.$element=a,this.options=b,d.__super__.constructor.call(this)}return b.Extend(d,a),d.prototype.current=function(a){var b=[],d=this;this.$element.find(":selected").each(function(){var a=c(this),e=d.item(a);b.push(e)}),a(b)},d.prototype.select=function(a){var b=this;if(a.selected=!0,c(a.element).is("option"))return a.element.selected=!0,void this.$element.trigger("change");if(this.$element.prop("multiple"))this.current(function(d){var e=[];a=[a],a.push.apply(a,d);for(var f=0;f=0){var k=f.filter(d(j)),l=this.item(k),m=c.extend(!0,{},j,l),n=this.option(m);k.replaceWith(n)}else{var o=this.option(j);if(j.children){var p=this.convertToOptions(j.children);b.appendMany(o,p)}h.push(o)}}return h},d}),b.define("select2/data/ajax",["./array","../utils","jquery"],function(a,b,c){function d(a,b){this.ajaxOptions=this._applyDefaults(b.get("ajax")),null!=this.ajaxOptions.processResults&&(this.processResults=this.ajaxOptions.processResults),d.__super__.constructor.call(this,a,b)}return b.Extend(d,a),d.prototype._applyDefaults=function(a){var b={data:function(a){return c.extend({},a,{q:a.term})},transport:function(a,b,d){var e=c.ajax(a);return e.then(b),e.fail(d),e}};return c.extend({},b,a,!0)},d.prototype.processResults=function(a){return a},d.prototype.query=function(a,b){function d(){var d=f.transport(f,function(d){var f=e.processResults(d,a);e.options.get("debug")&&window.console&&console.error&&(f&&f.results&&c.isArray(f.results)||console.error("Select2: The AJAX results did not return an array in the `results` key of the response.")),b(f)},function(){"status"in d&&(0===d.status||"0"===d.status)||e.trigger("results:message",{message:"errorLoading"})});e._request=d}var e=this;null!=this._request&&(c.isFunction(this._request.abort)&&this._request.abort(),this._request=null);var f=c.extend({type:"GET"},this.ajaxOptions);"function"==typeof f.url&&(f.url=f.url.call(this.$element,a)),"function"==typeof f.data&&(f.data=f.data.call(this.$element,a)),this.ajaxOptions.delay&&null!=a.term?(this._queryTimeout&&window.clearTimeout(this._queryTimeout),this._queryTimeout=window.setTimeout(d,this.ajaxOptions.delay)):d()},d}),b.define("select2/data/tags",["jquery"],function(a){function b(b,c,d){var e=d.get("tags"),f=d.get("createTag");void 0!==f&&(this.createTag=f);var g=d.get("insertTag");if(void 0!==g&&(this.insertTag=g),b.call(this,c,d),a.isArray(e))for(var h=0;h0&&b.term.length>this.maximumInputLength)return void this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:b.term,params:b}});a.call(this,b,c)},a}),b.define("select2/data/maximumSelectionLength",[],function(){function a(a,b,c){this.maximumSelectionLength=c.get("maximumSelectionLength"),a.call(this,b,c)}return a.prototype.query=function(a,b,c){var d=this;this.current(function(e){var f=null!=e?e.length:0;if(d.maximumSelectionLength>0&&f>=d.maximumSelectionLength)return void d.trigger("results:message",{message:"maximumSelected",args:{maximum:d.maximumSelectionLength}});a.call(d,b,c)})},a}),b.define("select2/dropdown",["jquery","./utils"],function(a,b){function c(a,b){this.$element=a,this.options=b,c.__super__.constructor.call(this)}return b.Extend(c,b.Observable),c.prototype.render=function(){var b=a(' ');return b.attr("dir",this.options.get("dir")),this.$dropdown=b,b},c.prototype.bind=function(){},c.prototype.position=function(a,b){},c.prototype.destroy=function(){this.$dropdown.remove()},c}),b.define("select2/dropdown/search",["jquery","../utils"],function(a,b){function c(){}return c.prototype.render=function(b){var c=b.call(this),d=a(' ');return this.$searchContainer=d,this.$search=d.find("input"),c.prepend(d),c},c.prototype.bind=function(b,c,d){var e=this;b.call(this,c,d),this.$search.on("keydown",function(a){e.trigger("keypress",a),e._keyUpPrevented=a.isDefaultPrevented()}),this.$search.on("input",function(b){a(this).off("keyup")}),this.$search.on("keyup input",function(a){e.handleSearch(a)}),c.on("open",function(){e.$search.attr("tabindex",0),e.$search.focus(),window.setTimeout(function(){e.$search.focus()},0)}),c.on("close",function(){e.$search.attr("tabindex",-1),e.$search.val(""),e.$search.blur()}),c.on("focus",function(){c.isOpen()||e.$search.focus()}),c.on("results:all",function(a){if(null==a.query.term||""===a.query.term){e.showSearch(a)?e.$searchContainer.removeClass("select2-search--hide"):e.$searchContainer.addClass("select2-search--hide")}})},c.prototype.handleSearch=function(a){if(!this._keyUpPrevented){var b=this.$search.val();this.trigger("query",{term:b})}this._keyUpPrevented=!1},c.prototype.showSearch=function(a,b){return!0},c}),b.define("select2/dropdown/hidePlaceholder",[],function(){function a(a,b,c,d){this.placeholder=this.normalizePlaceholder(c.get("placeholder")),a.call(this,b,c,d)}return a.prototype.append=function(a,b){b.results=this.removePlaceholder(b.results),a.call(this,b)},a.prototype.normalizePlaceholder=function(a,b){return"string"==typeof b&&(b={id:"",text:b}),b},a.prototype.removePlaceholder=function(a,b){for(var c=b.slice(0),d=b.length-1;d>=0;d--){var e=b[d];this.placeholder.id===e.id&&c.splice(d,1)}return c},a}),b.define("select2/dropdown/infiniteScroll",["jquery"],function(a){function b(a,b,c,d){this.lastParams={},a.call(this,b,c,d),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return b.prototype.append=function(a,b){this.$loadingMore.remove(),this.loading=!1,a.call(this,b),this.showLoadingMore(b)&&this.$results.append(this.$loadingMore)},b.prototype.bind=function(b,c,d){var e=this;b.call(this,c,d),c.on("query",function(a){e.lastParams=a,e.loading=!0}),c.on("query:append",function(a){e.lastParams=a,e.loading=!0}),this.$results.on("scroll",function(){var b=a.contains(document.documentElement,e.$loadingMore[0]);if(!e.loading&&b){e.$results.offset().top+e.$results.outerHeight(!1)+50>=e.$loadingMore.offset().top+e.$loadingMore.outerHeight(!1)&&e.loadMore()}})},b.prototype.loadMore=function(){this.loading=!0;var b=a.extend({},{page:1},this.lastParams);b.page++,this.trigger("query:append",b)},b.prototype.showLoadingMore=function(a,b){return b.pagination&&b.pagination.more},b.prototype.createLoadingMore=function(){var b=a(' '),c=this.options.get("translations").get("loadingMore");return b.html(c(this.lastParams)),b},b}),b.define("select2/dropdown/attachBody",["jquery","../utils"],function(a,b){function c(b,c,d){this.$dropdownParent=d.get("dropdownParent")||a(document.body),b.call(this,c,d)}return c.prototype.bind=function(a,b,c){var d=this,e=!1;a.call(this,b,c),b.on("open",function(){d._showDropdown(),d._attachPositioningHandler(b),e||(e=!0,b.on("results:all",function(){d._positionDropdown(),d._resizeDropdown()}),b.on("results:append",function(){d._positionDropdown(),d._resizeDropdown()}))}),b.on("close",function(){d._hideDropdown(),d._detachPositioningHandler(b)}),this.$dropdownContainer.on("mousedown",function(a){a.stopPropagation()})},c.prototype.destroy=function(a){a.call(this),this.$dropdownContainer.remove()},c.prototype.position=function(a,b,c){b.attr("class",c.attr("class")),b.removeClass("select2"),b.addClass("select2-container--open"),b.css({position:"absolute",top:-999999}),this.$container=c},c.prototype.render=function(b){var c=a(" "),d=b.call(this);return c.append(d),this.$dropdownContainer=c,c},c.prototype._hideDropdown=function(a){this.$dropdownContainer.detach()},c.prototype._attachPositioningHandler=function(c,d){var e=this,f="scroll.select2."+d.id,g="resize.select2."+d.id,h="orientationchange.select2."+d.id,i=this.$container.parents().filter(b.hasScroll);i.each(function(){b.StoreData(this,"select2-scroll-position",{x:a(this).scrollLeft(),y:a(this).scrollTop()})}),i.on(f,function(c){var d=b.GetData(this,"select2-scroll-position");a(this).scrollTop(d.y)}),a(window).on(f+" "+g+" "+h,function(a){e._positionDropdown(),e._resizeDropdown()})},c.prototype._detachPositioningHandler=function(c,d){var e="scroll.select2."+d.id,f="resize.select2."+d.id,g="orientationchange.select2."+d.id;this.$container.parents().filter(b.hasScroll).off(e),a(window).off(e+" "+f+" "+g)},c.prototype._positionDropdown=function(){var b=a(window),c=this.$dropdown.hasClass("select2-dropdown--above"),d=this.$dropdown.hasClass("select2-dropdown--below"),e=null,f=this.$container.offset();f.bottom=f.top+this.$container.outerHeight(!1);var g={height:this.$container.outerHeight(!1)};g.top=f.top,g.bottom=f.top+g.height;var h={height:this.$dropdown.outerHeight(!1)},i={top:b.scrollTop(),bottom:b.scrollTop()+b.height()},j=i.topf.bottom+h.height,l={left:f.left,top:g.bottom},m=this.$dropdownParent;"static"===m.css("position")&&(m=m.offsetParent());var n=m.offset();l.top-=n.top,l.left-=n.left,c||d||(e="below"),k||!j||c?!j&&k&&c&&(e="below"):e="above",("above"==e||c&&"below"!==e)&&(l.top=g.top-n.top-h.height),null!=e&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+e),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+e)),this.$dropdownContainer.css(l)},c.prototype._resizeDropdown=function(){var a={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(a.minWidth=a.width,a.position="relative",a.width="auto"),this.$dropdown.css(a)},c.prototype._showDropdown=function(a){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},c}),b.define("select2/dropdown/minimumResultsForSearch",[],function(){function a(b){for(var c=0,d=0;d0&&(l.dataAdapter=j.Decorate(l.dataAdapter,r)),l.maximumInputLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,s)),l.maximumSelectionLength>0&&(l.dataAdapter=j.Decorate(l.dataAdapter,t)),l.tags&&(l.dataAdapter=j.Decorate(l.dataAdapter,p)),null==l.tokenSeparators&&null==l.tokenizer||(l.dataAdapter=j.Decorate(l.dataAdapter,q)),null!=l.query){var C=b(l.amdBase+"compat/query");l.dataAdapter=j.Decorate(l.dataAdapter,C)}if(null!=l.initSelection){var D=b(l.amdBase+"compat/initSelection");l.dataAdapter=j.Decorate(l.dataAdapter,D)}}if(null==l.resultsAdapter&&(l.resultsAdapter=c,null!=l.ajax&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,x)),null!=l.placeholder&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,w)),l.selectOnClose&&(l.resultsAdapter=j.Decorate(l.resultsAdapter,A))),null==l.dropdownAdapter){if(l.multiple)l.dropdownAdapter=u;else{var E=j.Decorate(u,v);l.dropdownAdapter=E}if(0!==l.minimumResultsForSearch&&(l.dropdownAdapter=j.Decorate(l.dropdownAdapter,z)),l.closeOnSelect&&(l.dropdownAdapter=j.Decorate(l.dropdownAdapter,B)),null!=l.dropdownCssClass||null!=l.dropdownCss||null!=l.adaptDropdownCssClass){var F=b(l.amdBase+"compat/dropdownCss");l.dropdownAdapter=j.Decorate(l.dropdownAdapter,F)}l.dropdownAdapter=j.Decorate(l.dropdownAdapter,y)}if(null==l.selectionAdapter){if(l.multiple?l.selectionAdapter=e:l.selectionAdapter=d,null!=l.placeholder&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,f)),l.allowClear&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,g)),l.multiple&&(l.selectionAdapter=j.Decorate(l.selectionAdapter,h)),null!=l.containerCssClass||null!=l.containerCss||null!=l.adaptContainerCssClass){var G=b(l.amdBase+"compat/containerCss");l.selectionAdapter=j.Decorate(l.selectionAdapter,G)}l.selectionAdapter=j.Decorate(l.selectionAdapter,i)}if("string"==typeof l.language)if(l.language.indexOf("-")>0){var H=l.language.split("-"),I=H[0];l.language=[l.language,I]}else l.language=[l.language];if(a.isArray(l.language)){var J=new k;l.language.push("en");for(var K=l.language,L=0;L0){for(var f=a.extend(!0,{},e),g=e.children.length-1;g>=0;g--){null==c(d,e.children[g])&&f.children.splice(g,1)}return f.children.length>0?f:c(d,f)}var h=b(e.text).toUpperCase(),i=b(d.term).toUpperCase();return h.indexOf(i)>-1?e:null}this.defaults={amdBase:"./",amdLanguageBase:"./i18n/",closeOnSelect:!0,debug:!1,dropdownAutoWidth:!1,escapeMarkup:j.escapeMarkup,language:C,matcher:c,minimumInputLength:0,maximumInputLength:0,maximumSelectionLength:0,minimumResultsForSearch:0,selectOnClose:!1,sorter:function(a){return a},templateResult:function(a){return a.text},templateSelection:function(a){return a.text},theme:"default",width:"resolve"}},D.prototype.set=function(b,c){var d=a.camelCase(b),e={};e[d]=c;var f=j._convertData(e);a.extend(!0,this.defaults,f)},new D}),b.define("select2/options",["require","jquery","./defaults","./utils"],function(a,b,c,d){function e(b,e){if(this.options=b,null!=e&&this.fromElement(e),this.options=c.apply(this.options),e&&e.is("input")){var f=a(this.get("amdBase")+"compat/inputData");this.options.dataAdapter=d.Decorate(this.options.dataAdapter,f)}}return e.prototype.fromElement=function(a){var c=["select2"];null==this.options.multiple&&(this.options.multiple=a.prop("multiple")),null==this.options.disabled&&(this.options.disabled=a.prop("disabled")),null==this.options.language&&(a.prop("lang")?this.options.language=a.prop("lang").toLowerCase():a.closest("[lang]").prop("lang")&&(this.options.language=a.closest("[lang]").prop("lang"))),null==this.options.dir&&(a.prop("dir")?this.options.dir=a.prop("dir"):a.closest("[dir]").prop("dir")?this.options.dir=a.closest("[dir]").prop("dir"):this.options.dir="ltr"),a.prop("disabled",this.options.disabled),a.prop("multiple",this.options.multiple),d.GetData(a[0],"select2Tags")&&(this.options.debug&&window.console&&console.warn&&console.warn('Select2: The `data-select2-tags` attribute has been changed to use the `data-data` and `data-tags="true"` attributes and will be removed in future versions of Select2.'),d.StoreData(a[0],"data",d.GetData(a[0],"select2Tags")),d.StoreData(a[0],"tags",!0)),d.GetData(a[0],"ajaxUrl")&&(this.options.debug&&window.console&&console.warn&&console.warn("Select2: The `data-ajax-url` attribute has been changed to `data-ajax--url` and support for the old attribute will be removed in future versions of Select2."),a.attr("ajax--url",d.GetData(a[0],"ajaxUrl")),d.StoreData(a[0],"ajax-Url",d.GetData(a[0],"ajaxUrl")));var e={};e=b.fn.jquery&&"1."==b.fn.jquery.substr(0,2)&&a[0].dataset?b.extend(!0,{},a[0].dataset,d.GetData(a[0])):d.GetData(a[0]);var f=b.extend(!0,{},e);f=d._convertData(f);for(var g in f)b.inArray(g,c)>-1||(b.isPlainObject(this.options[g])?b.extend(this.options[g],f[g]):this.options[g]=f[g]);return this},e.prototype.get=function(a){return this.options[a]},e.prototype.set=function(a,b){this.options[a]=b},e}),b.define("select2/core",["jquery","./options","./utils","./keys"],function(a,b,c,d){var e=function(a,d){null!=c.GetData(a[0],"select2")&&c.GetData(a[0],"select2").destroy(),this.$element=a,this.id=this._generateId(a),d=d||{},this.options=new b(d,a),e.__super__.constructor.call(this);var f=a.attr("tabindex")||0;c.StoreData(a[0],"old-tabindex",f),a.attr("tabindex","-1");var g=this.options.get("dataAdapter");this.dataAdapter=new g(a,this.options);var h=this.render();this._placeContainer(h);var i=this.options.get("selectionAdapter");this.selection=new i(a,this.options),this.$selection=this.selection.render(),this.selection.position(this.$selection,h);var j=this.options.get("dropdownAdapter");this.dropdown=new j(a,this.options),this.$dropdown=this.dropdown.render(),this.dropdown.position(this.$dropdown,h);var k=this.options.get("resultsAdapter");this.results=new k(a,this.options,this.dataAdapter),this.$results=this.results.render(),this.results.position(this.$results,this.$dropdown);var l=this;this._bindAdapters(),this._registerDomEvents(),this._registerDataEvents(),this._registerSelectionEvents(),this._registerDropdownEvents(),this._registerResultsEvents(),this._registerEvents(),this.dataAdapter.current(function(a){l.trigger("selection:update",{data:a})}),a.addClass("select2-hidden-accessible"),a.attr("aria-hidden","true"),this._syncAttributes(),c.StoreData(a[0],"select2",this),a.data("select2",this)};return c.Extend(e,c.Observable),e.prototype._generateId=function(a){var b="";return b=null!=a.attr("id")?a.attr("id"):null!=a.attr("name")?a.attr("name")+"-"+c.generateChars(2):c.generateChars(4),b=b.replace(/(:|\.|\[|\]|,)/g,""),b="select2-"+b},e.prototype._placeContainer=function(a){a.insertAfter(this.$element);var b=this._resolveWidth(this.$element,this.options.get("width"));null!=b&&a.css("width",b)},e.prototype._resolveWidth=function(a,b){var c=/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;if("resolve"==b){var d=this._resolveWidth(a,"style");return null!=d?d:this._resolveWidth(a,"element")}if("element"==b){var e=a.outerWidth(!1);return e<=0?"auto":e+"px"}if("style"==b){var f=a.attr("style");if("string"!=typeof f)return null;for(var g=f.split(";"),h=0,i=g.length;h=1)return k[1]}return null}return b},e.prototype._bindAdapters=function(){this.dataAdapter.bind(this,this.$container),this.selection.bind(this,this.$container),this.dropdown.bind(this,this.$container),this.results.bind(this,this.$container)},e.prototype._registerDomEvents=function(){var b=this;this.$element.on("change.select2",function(){b.dataAdapter.current(function(a){b.trigger("selection:update",{data:a})})}),this.$element.on("focus.select2",function(a){b.trigger("focus",a)}),this._syncA=c.bind(this._syncAttributes,this),this._syncS=c.bind(this._syncSubtree,this),this.$element[0].attachEvent&&this.$element[0].attachEvent("onpropertychange",this._syncA);var d=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver;null!=d?(this._observer=new d(function(c){a.each(c,b._syncA),a.each(c,b._syncS)}),this._observer.observe(this.$element[0],{attributes:!0,childList:!0,subtree:!1})):this.$element[0].addEventListener&&(this.$element[0].addEventListener("DOMAttrModified",b._syncA,!1),this.$element[0].addEventListener("DOMNodeInserted",b._syncS,!1),this.$element[0].addEventListener("DOMNodeRemoved",b._syncS,!1))},e.prototype._registerDataEvents=function(){var a=this;this.dataAdapter.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerSelectionEvents=function(){var b=this,c=["toggle","focus"];this.selection.on("toggle",function(){b.toggleDropdown()}),this.selection.on("focus",function(a){b.focus(a)}),this.selection.on("*",function(d,e){-1===a.inArray(d,c)&&b.trigger(d,e)})},e.prototype._registerDropdownEvents=function(){var a=this;this.dropdown.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerResultsEvents=function(){var a=this;this.results.on("*",function(b,c){a.trigger(b,c)})},e.prototype._registerEvents=function(){var a=this;this.on("open",function(){a.$container.addClass("select2-container--open")}),this.on("close",function(){a.$container.removeClass("select2-container--open")}),this.on("enable",function(){a.$container.removeClass("select2-container--disabled")}),this.on("disable",function(){a.$container.addClass("select2-container--disabled")}),this.on("blur",function(){a.$container.removeClass("select2-container--focus")}),this.on("query",function(b){a.isOpen()||a.trigger("open",{}),this.dataAdapter.query(b,function(c){a.trigger("results:all",{data:c,query:b})})}),this.on("query:append",function(b){this.dataAdapter.query(b,function(c){a.trigger("results:append",{data:c,query:b})})}),this.on("keypress",function(b){var c=b.which;a.isOpen()?c===d.ESC||c===d.TAB||c===d.UP&&b.altKey?(a.close(),b.preventDefault()):c===d.ENTER?(a.trigger("results:select",{}),b.preventDefault()):c===d.SPACE&&b.ctrlKey?(a.trigger("results:toggle",{}),b.preventDefault()):c===d.UP?(a.trigger("results:previous",{}),b.preventDefault()):c===d.DOWN&&(a.trigger("results:next",{}),b.preventDefault()):(c===d.ENTER||c===d.SPACE||c===d.DOWN&&b.altKey)&&(a.open(),b.preventDefault())})},e.prototype._syncAttributes=function(){this.options.set("disabled",this.$element.prop("disabled")),this.options.get("disabled")?(this.isOpen()&&this.close(),this.trigger("disable",{})):this.trigger("enable",{})},e.prototype._syncSubtree=function(a,b){var c=!1,d=this;if(!a||!a.target||"OPTION"===a.target.nodeName||"OPTGROUP"===a.target.nodeName){if(b)if(b.addedNodes&&b.addedNodes.length>0)for(var e=0;e0&&(c=!0);else c=!0;c&&this.dataAdapter.current(function(a){d.trigger("selection:update",{data:a})})}},e.prototype.trigger=function(a,b){var c=e.__super__.trigger,d={open:"opening",close:"closing",select:"selecting",unselect:"unselecting",clear:"clearing"};if(void 0===b&&(b={}),a in d){var f=d[a],g={prevented:!1,name:a,args:b};if(c.call(this,f,g),g.prevented)return void(b.prevented=!0)}c.call(this,a,b)},e.prototype.toggleDropdown=function(){this.options.get("disabled")||(this.isOpen()?this.close():this.open())},e.prototype.open=function(){this.isOpen()||this.trigger("query",{})},e.prototype.close=function(){this.isOpen()&&this.trigger("close",{})},e.prototype.isOpen=function(){return this.$container.hasClass("select2-container--open")},e.prototype.hasFocus=function(){return this.$container.hasClass("select2-container--focus")},e.prototype.focus=function(a){this.hasFocus()||(this.$container.addClass("select2-container--focus"),this.trigger("focus",{}))},e.prototype.enable=function(a){this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("enable")` method has been deprecated and will be removed in later Select2 versions. Use $element.prop("disabled") instead.'),null!=a&&0!==a.length||(a=[!0]);var b=!a[0];this.$element.prop("disabled",b)},e.prototype.data=function(){this.options.get("debug")&&arguments.length>0&&window.console&&console.warn&&console.warn('Select2: Data can no longer be set using `select2("data")`. You should consider setting the value instead using `$element.val()`.');var a=[];return this.dataAdapter.current(function(b){a=b}),a},e.prototype.val=function(b){if(this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("val")` method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead.'),null==b||0===b.length)return this.$element.val();var c=b[0];a.isArray(c)&&(c=a.map(c,function(a){return a.toString()})),this.$element.val(c).trigger("change")},e.prototype.destroy=function(){this.$container.remove(),this.$element[0].detachEvent&&this.$element[0].detachEvent("onpropertychange",this._syncA),null!=this._observer?(this._observer.disconnect(),this._observer=null):this.$element[0].removeEventListener&&(this.$element[0].removeEventListener("DOMAttrModified",this._syncA,!1),this.$element[0].removeEventListener("DOMNodeInserted",this._syncS,!1),this.$element[0].removeEventListener("DOMNodeRemoved",this._syncS,!1)),this._syncA=null,this._syncS=null,this.$element.off(".select2"),this.$element.attr("tabindex",c.GetData(this.$element[0],"old-tabindex")),this.$element.removeClass("select2-hidden-accessible"),this.$element.attr("aria-hidden","false"),c.RemoveData(this.$element[0]),this.$element.removeData("select2"),this.dataAdapter.destroy(),this.selection.destroy(),this.dropdown.destroy(),this.results.destroy(),this.dataAdapter=null,this.selection=null,this.dropdown=null,this.results=null},e.prototype.render=function(){var b=a(' ');return b.attr("dir",this.options.get("dir")),this.$container=b,this.$container.addClass("select2-container--"+this.options.get("theme")),c.StoreData(b[0],"element",this.$element),b},e}),b.define("select2/compat/utils",["jquery"],function(a){function b(b,c,d){var e,f,g=[];e=a.trim(b.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each(function(){0===this.indexOf("select2-")&&g.push(this)})),e=a.trim(c.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each(function(){0!==this.indexOf("select2-")&&null!=(f=d(this))&&g.push(f)})),b.attr("class",g.join(" "))}return{syncCssClasses:b}}),b.define("select2/compat/containerCss",["jquery","./utils"],function(a,b){function c(a){return null}function d(){}return d.prototype.render=function(d){var e=d.call(this),f=this.options.get("containerCssClass")||"";a.isFunction(f)&&(f=f(this.$element));var g=this.options.get("adaptContainerCssClass");if(g=g||c,-1!==f.indexOf(":all:")){f=f.replace(":all:","");var h=g;g=function(a){var b=h(a);return null!=b?b+" "+a:a}}var i=this.options.get("containerCss")||{};return a.isFunction(i)&&(i=i(this.$element)),b.syncCssClasses(e,this.$element,g),e.css(i),e.addClass(f),e},d}),b.define("select2/compat/dropdownCss",["jquery","./utils"],function(a,b){function c(a){return null}function d(){}return d.prototype.render=function(d){var e=d.call(this),f=this.options.get("dropdownCssClass")||"";a.isFunction(f)&&(f=f(this.$element));var g=this.options.get("adaptDropdownCssClass");if(g=g||c,-1!==f.indexOf(":all:")){f=f.replace(":all:","");var h=g;g=function(a){var b=h(a);return null!=b?b+" "+a:a}}var i=this.options.get("dropdownCss")||{};return a.isFunction(i)&&(i=i(this.$element)),b.syncCssClasses(e,this.$element,g),e.css(i),e.addClass(f),e},d}),b.define("select2/compat/initSelection",["jquery"],function(a){function b(a,b,c){c.get("debug")&&window.console&&console.warn&&console.warn("Select2: The `initSelection` option has been deprecated in favor of a custom data adapter that overrides the `current` method. This method is now called multiple times instead of a single time when the instance is initialized. Support will be removed for the `initSelection` option in future versions of Select2"),this.initSelection=c.get("initSelection"),this._isInitialized=!1,a.call(this,b,c)}return b.prototype.current=function(b,c){var d=this;if(this._isInitialized)return void b.call(this,c);this.initSelection.call(null,this.$element,function(b){d._isInitialized=!0,a.isArray(b)||(b=[b]),c(b)})},b}),b.define("select2/compat/inputData",["jquery","../utils"],function(a,b){function c(a,b,c){this._currentData=[],this._valueSeparator=c.get("valueSeparator")||",","hidden"===b.prop("type")&&c.get("debug")&&console&&console.warn&&console.warn("Select2: Using a hidden input with Select2 is no longer supported and may stop working in the future. It is recommended to use a `` element instead."),a.call(this,b,c)}return c.prototype.current=function(b,c){function d(b,c){var e=[];return b.selected||-1!==a.inArray(b.id,c)?(b.selected=!0,e.push(b)):b.selected=!1,b.children&&e.push.apply(e,d(b.children,c)),e}for(var e=[],f=0;f=0;f--){var g=d.children[f];b(c.term,g.text,g)||e.children.splice(f,1)}if(e.children.length>0)return e}return b(c.term,d.text,d)?e:null}return c}return b}),b.define("select2/compat/query",[],function(){function a(a,b,c){c.get("debug")&&window.console&&console.warn&&console.warn("Select2: The `query` option has been deprecated in favor of a custom data adapter that overrides the `query` method. Support will be removed for the `query` option in future versions of Select2."),a.call(this,b,c)}return a.prototype.query=function(a,b,c){b.callback=c,this.options.get("query").call(null,b)},a}),b.define("select2/dropdown/attachContainer",[],function(){function a(a,b,c){a.call(this,b,c)}return a.prototype.position=function(a,b,c){c.find(".dropdown-wrapper").append(b),b.addClass("select2-dropdown--below"),c.addClass("select2-container--below")},a}),b.define("select2/dropdown/stopPropagation",[],function(){function a(){}return a.prototype.bind=function(a,b,c){a.call(this,b,c);var d=["blur","change","click","dblclick","focus","focusin","focusout","input","keydown","keyup","keypress","mousedown","mouseenter","mouseleave","mousemove","mouseover","mouseup","search","touchend","touchstart"];this.$dropdown.on(d.join(" "),function(a){a.stopPropagation()})},a}),b.define("select2/selection/stopPropagation",[],function(){function a(){}return a.prototype.bind=function(a,b,c){a.call(this,b,c);var d=["blur","change","click","dblclick","focus","focusin","focusout","input","keydown","keyup","keypress","mousedown","mouseenter","mouseleave","mousemove","mouseover","mouseup","search","touchend","touchstart"];this.$selection.on(d.join(" "),function(a){a.stopPropagation()})},a}),function(c){"function"==typeof b.define&&b.define.amd?b.define("jquery-mousewheel",["jquery"],c):"object"==typeof exports?module.exports=c:c(a)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||n=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120==0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})}),b.define("jquery.select2",["jquery","jquery-mousewheel","./select2/core","./select2/defaults","./select2/utils"],function(a,b,c,d,e){if(null==a.fn.select2){var f=["open","close","destroy"];a.fn.select2=function(b){if("object"==typeof(b=b||{}))return this.each(function(){var d=a.extend(!0,{},b);new c(a(this),d)}),this;if("string"==typeof b){var d,g=Array.prototype.slice.call(arguments,1);return this.each(function(){var a=e.GetData(this,"select2");null==a&&window.console&&console.error&&console.error("The select2('"+b+"') method was called on an element that is not using Select2."),d=a[b].apply(a,g)}),a.inArray(b,f)>-1?this:d}throw new Error("Invalid arguments for Select2: "+b)}}return null==a.fn.select2.defaults&&(a.fn.select2.defaults=d),c}),{define:b.define,require:b.require}}(),c=b.require("jquery.select2");return a.fn.select2.amd=b,c});
!function(e){var t={};function s(a){if(t[a])return t[a].exports;var n=t[a]={i:a,l:!1,exports:{}};return e[a].call(n.exports,n,n.exports,s),n.l=!0,n.exports}s.m=e,s.c=t,s.d=function(e,t,a){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(s.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)s.d(a,n,function(t){return e[t]}.bind(null,n));return a},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=19)}([function(e,t,s){"use strict";var a,n;s.r(t),s.d(t,"HTMLVerbs",(function(){return a})),s.d(t,"DataTypes",(function(){return n})),s.d(t,"BaseService",(function(){return i})),function(e){e.GET="GET",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE"}(a||(a={})),function(e){e.JSON="json",e.HTML="html"}(n||(n={}));class i{constructor(){}extendBaseRequest(e,t){return $.extend.apply($,[e].concat(t))}request(e,t){const s=this.extendBaseRequest(e,t);return $.ajax(s)}}},function(e,t,s){"use strict";s.r(t),s.d(t,"BaseViewTemplate",(function(){return u})),s.d(t,"SelectTypeEnum",(function(){return a})),s.d(t,"AlertType",(function(){return n}));var a,n,i=s(8),r=s(2),o=s(6),l=s(7),c=s(9);class u{constructor(){this._selectService=null,this._consultantsService=null,this._homeService=null,this._baseConsts={$countScheduleAlerts:()=>$(".schedules .count-info .label"),$countAlerts:()=>$(".alerts .count-info .label"),$countFavourites:()=>$(".favourites .count-info .label"),timeoutTime:1e4},this.InitSelect=(e,t,s,a,n,i,o=null)=>{$.each(e,(e,l)=>{let c=$(l),d=c.find("option").map((e,t)=>{let s=new r.SelectOption({id:$(t).attr("value"),text:$(t).text()});return s.parentId=$(t).attr("data-parent-id"),s}).toArray();c.find("option").remove();let p={placeholder:n?t:"",allowClear:null!=o&&o,ajax:s,multiple:a,closeOnSelect:!a,tags:i||!1,templateResult:function(e){$(this).attr("data-parent-id",e.parentId);let t=$(`${e.text}`);return t.attr("title",e.text),t}};c.select2(p).on("select2:unselecting",(function(){$(this).data("unselecting",!0)})).on("select2:unselect",(function(e){($(e.currentTarget).closest("div[name=basic-informations]").length>0||$(e.currentTarget).closest("tr.filter-table").length>0)&&(new u).FormatMultipleSelects(c)})).on("select2:opening",(function(e){$(this).data("unselecting")&&($(this).removeData("unselecting"),e.preventDefault())})).on("select2:close",(function(e){$(e.currentTarget).next().find(".select2-selection__rendered li").length>1?$(e.currentTarget).next().find(".select2-search--inline").hide():$(e.currentTarget).next().find(".select2-search--inline").show()})).on("select2:select",(function(e){if(($(e.currentTarget).closest("div[name=basic-informations]").length>0||$(e.currentTarget).closest("tr.filter-table").length>0)&&(new u).FormatMultipleSelects(c),(void 0!==$(e.currentTarget).closest(".card-info").attr("data-error")&&"0"!==$(e.currentTarget).closest(".card-info").attr("data-error")||void 0!==$(e.currentTarget).closest(".container-sec-forms").attr("data-error")&&"0"!==$(e.currentTarget).closest(".container-sec-forms").attr("data-error"))&&(new u).ValidateRequiredFields(),"jobPosition"==$(e.currentTarget).attr("name")&&$(e.currentTarget).closest(".experience").find(".present-date").hasClass("present-date-selected")){let t=$(".detail-info-container h4").text();""!=t&&(t+=" / "),t+=$(e.currentTarget)[0].outerText,$(".detail-info-container h4").text(t),$(".detail-info-container h4").attr("title",t)}})),r.Select2Helper.SetSelectedOptions(c,d)})},this.CreateEmailContainer=(e,t,s,a)=>{$("body").append(e),$(".wrapper, .nav-menu").css({opacity:.4,"pointer-events":"none"});let n=$(".send-email-container");$.each(t,(function(e,t){$(n.find(".mailsadd")).before("x "+t+";
")})),n.find(".mailsadd").off().on("change",()=>{if(null!=$(".mailsadd").val()&&this.IsEmail($(".mailsadd").val())){var e=$(".mailsadd").val(),t="";0===s.To.length?s.To+=e:s.To+=";"+e;let r=1==$("#table-"+a+"s").find("[data-"+a+"-email='"+e+"']").length;r&&(t=this.FirstLastName($($("#table-"+a+"s").find("[data-"+a+"-email='"+e+"']").find(".name")).html()));var i=$(document.createElement("p"));i.html("x "+(r?t:e)+";"),i.find("span").off().on("click",e=>{s.To=(new u).DeleteEmailForm(s.To,e)}),$(n.find(".mailsadd")).before(i),$(".mailsadd").val(null)}else this.ToggleAlert(1,"Insira um e-mail válido")}),n.find(".names p span").off().on("click",e=>{s.To=(new u).DeleteEmailForm(s.To,e)}),$("#cancel").off().on("click",e=>{$(".send-email-container").remove();var t=$(".wrapper").css("margin-left");$(".wrapper").removeAttr("style"),$(".nav-menu").css({opacity:"1","pointer-events":"all"}),$(".wrapper").css("margin-left",t)}),n.find("#button-send-email").off().on("click",e=>{this.ToggleLoading();var t=n.find(".signature").html().trim(),a=n.find(".message").val().replace(/(\r\n|\n)/g," "),i=encodeURI(a+t);this._consultantsService.SendEmail(s.To,n.find(".subject").val(),i,{success:e=>{n.remove();var t=$(".wrapper").css("margin-left");$(".wrapper").removeAttr("style"),$(".nav-menu").css({opacity:"1","pointer-events":"all"}),$(".wrapper").css("margin-left",t),this.ToggleAlert(4,"E-mail enviado com sucesso")},error:(e,t)=>{this.ToggleAlert(1,"Erro ao enviar e-mail")},complete:()=>{this.ToggleLoading()}})})},this.FirstLastName=e=>{let t;if(null!=e){var s=e.split(" ");return t=1==s.length?s[0]:s[0]+" "+s[s.length-1],t}},this.DeleteEmailForm=(e,t)=>{var s=e.split(";");return s.splice($(t.currentTarget.parentElement).index(),1),$(t.currentTarget.parentElement).remove(),s.join(";").trim()},this.PageTitle=e=>{$("#pageTitle").text(e);let t=$("head title");t.text(`${t.attr("data-prefix")} - ${e}`)},this.GetQueryStringParameter=e=>new URLSearchParams(window.location.search).get(e),this.DeleteQueryStringParameter=e=>{let t=new URLSearchParams(window.location.search);t.delete(e);let s=t.toString();""!=s.trim()&&(s="?"+s),history.replaceState(null,"",s||window.location.pathname)},this.Back=()=>{$(window).trigger("beforePageBack"),window.history.back()},this._selectService=new i.SelectService,this._consultantsService=new o.ConsultantsService,this._homeService=new c.HomeService,$.datetimepicker.setLocale("pt")}Init(){}Load(){}BindEvents(){}BindSelect(e,t,s,n,i,r,o=null,l=null){let c=null;switch(t){case a.ClientState:c=this._selectService.GetClientStatesAjaxOptions(r);break;case a.ClientVAT:c=this._selectService.GetClientVATsAjaxOptions(r);break;case a.Local:c=this._selectService.GetCitiesAjaxOptions(r);break;case a.Nationality:c=this._selectService.GetNationalitiesAjaxOptions(r);break;case a.ClientStates:c=this._selectService.GetClientStatesAjaxOptions(r);break;case a.JobPosition:c=this._selectService.GetJobPositionsAjaxOptions(r);break;case a.PhoneCode:c=this._selectService.GetPhoneCodesAjaxOptions(r);break;case a.Users:c=this._selectService.GetUsersAjaxOptions(r);break;case a.HistoricTypes:c=this._selectService.GetHistoricTypesjaxOptions(r);break;case a.ScheduleCategories:c=this._selectService.GetScheuduleCategories(r);break;case a.UserClients:c=this._selectService.GetUserClientsAjaxOptions(r);break;case a.RecruitmentRequests:c=this._selectService.GetRecruitmentRequestsToScheduleAjaxOptions(r);break;case a.OperationalStatus:c=this._selectService.GetOperationalStatusAjaxOptions(r);break;case a.FinantialStatus:c=this._selectService.GetFinantialStatusAjaxOptions(r);break;case a.ProjectStates:c=this._selectService.GetProjectStatusAjaxOptions(r);break;case a.Priority:c=this._selectService.GetProjectPriorityAjaxOptions(r);break;case a.ProjectTasks:c=this._selectService.GetProjectTasksAjaxOptions(r);break;case a.ProjectServices:c=this._selectService.GetProjectServicesAjaxOptions(r);break;case a.ConsultantsState:c=this._selectService.GetConsultantsStatesAjaxOptions(r);break;case a.TimesheetsClients:c=this._selectService.GetTimesheetsClientsAjaxOptions(r);break;case a.ClientContactsProject:c=this._selectService.GetProjectClientContactsAjaxOptions(r);break;case a.TimesheetsProducts:c=this._selectService.GetTimesheetsProductsAjaxOptions(r);break;case a.TimesheetsProjects:c=this._selectService.GetTimesheetsProjectsAjaxOptions(r);break;case a.TimesheetsTasks:c=this._selectService.GetTimesheetsTasksAjaxOptions(r);break;case a.ExpensesStates:c=this._selectService.GetExpensesStatesAjaxOptions(r);break;case a.ExpensesTypes:c=this._selectService.GetExpensesTypesAjaxOptions(r);break;case a.ExpensesProjects:c=this._selectService.GetExpensesProjectsAjaxOptions(r);break;case a.ExpensesProjectsSelect:c=this._selectService.GetExpensesProjectsSelectAjaxOptions(r);break;case a.ExpensesConsultants:c=this._selectService.GetExpensesConsultantsAjaxOptions(r);break;case a.BusinessGroup:c=this._selectService.GetBusinessGroupsAjaxOptions(r);break;case a.BusinessArea:c=this._selectService.GetBusinessAreasAjaxOptions(r);break;case a.BusinessAreaSupplier:c=this._selectService.GetBusinessAreasSupplierAjaxOptions(r);break;case a.Company:c=this._selectService.GetCompaniesAjaxOptions(r);break;case a.PaymentCondition:c=this._selectService.GetClientPaymentConditionsAjaxOptions(r);break;case a.TaskCategories:c=this._selectService.GetTaskCategoriesAjaxOptions(r);break;case a.TaskPriorities:c=this._selectService.GetTaskPrioritiesAjaxOptions(r);break;case a.TaskStates:c=this._selectService.GetTaskStatesAjaxOptions(r);break;case a.Consultants:c=this._selectService.GetConsultants(r);break;case a.Managers:c=this._selectService.GetManagersAjaxOptions(r);break;case a.BudgetType:c=this._selectService.GetBudgetTypeAjaxOptions(r);break;case a.BudgetItem:c=this._selectService.GetBudgetItemAjaxOptions(r);break;case a.BudgetSubitem:c=this._selectService.GetBudgetSubitemAjaxOptions(r);break;case a.Suppliers:c=this._selectService.GetSuppliersAjaxOptions(r);break;case a.BudgetExportType:c=this._selectService.GetBudgetExportTypeAjaxOptions(r);break;case a.BudgetExportTemplate:c=this._selectService.GetBudgetExportTemplateAjaxOptions(r);break;case a.BoughtOrderExportTemplate:c=this._selectService.GetBoughtOrderExportTemplateAjaxOptions(r);break;case a.Countries:c=this._selectService.GetCountriesAjaxOptions(r);break;case a.BoughtOrderStates:c=this._selectService.GetBoughtOrderStatesAjaxOptions(r);break;case a.ProductStates:c=this._selectService.GetProductStatesAjaxOptions(r)}null!=c?(this.InitSelect(e,l||t.toString(),c,s,n,i,o),t!=a.Nationality&&t!=a.DriverLicense||this.FormatMultipleSelects(e)):console.log("ERROR! ["+t+"]")}Tooltip(){$('[data-toggle="tooltip"]').tooltip({position:{my:"left-120 center-25",at:"right center"}})}AddMessageiIfNoData(){0==Number($(".list-data").attr("data-row-count"))?($(".no-results-container").css("display","flex"),$(".list-data").hide()):($(".no-results-container").css("display","none"),$(".list-data").show())}FormatMultipleSelects(e){setTimeout(()=>{let t=e.next().find(".select2-selection__choice:eq(0)").nextAll(".select2-selection__choice"),s=t.map((e,t)=>$.trim($(t).text().slice(1,$(t).text().length))).get().join(", ");if(""!==s){t.hide();var a=$(document.createElement("li"));a.addClass("select2-selection__choices").attr("data-toggle","tooltip").attr("title",s),a.text("+"+t.length),a.insertBefore(t.parent().find(".select2-search--inline")),this.Tooltip()}void 0!==e.closest(".card-info").attr("data-error")&&this.ValidateRequiredFields()},150)}FormatMultipleSelectsPlaceHolder(e){let t=$(".search-container");if(""!=e)t.find("li[name="+e+"]").find("input").css("width","100%"),t.find("li[name="+e+"]").find(".select2-search--inline").show();else{t.find("li.search-item").find("input").css("width","100%"),t.find("li.search-item").find(".select2-search--inline").show();let e=t.find("li.search-item").find("ul.select2-selection__rendered");$.each(e,(e,t)=>{$(t).find("li.select2-selection__choice").length>0?$(t).find("li.select2-search--inline").hide():$(t).find("li.select2-search--inline").show()})}}IsEmail(e){return/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(e)}CloseNavBar(){}ToggleLoading(e=null){!0===e?$(".loading").addClass("hide"):!1===e?$(".loading").removeClass("hide"):$(".loading").toggleClass("hide")}ToggleAlert(e,t){let s,a;switch(e){case n.Error:s="alert-danger",a="fas fa-exclamation-triangle";break;case n.Warning:s="alert-warning",a="fas fa-exclamation-triangle";break;case n.Info:s="alert-info",a="fas fa-exclamation-circle";break;case n.Success:s="alert-success",a="far fa-check-circle";break;default:s="alert-danger",a="fas fa-exclamation-triangle"}var i=$(".alert");i.removeAttr("class").addClass("alert").addClass(s),i.find(".icon").removeAttr("class").addClass("icon").addClass(a),i.find(".message").html(t),i.fadeIn(),i.find(".close").on("click",e=>{$(e.target).parent().fadeOut()}),setTimeout((function(){i.fadeOut()}),3e3)}ValidateRequiredFields(e){var t=!0,s=null!=e?e:$(".container-sec-forms, .card-info"),a=(e,s,a,n)=>{let i=$(s).closest(".container-sec-forms").attr("name"),r=null!==$(s).val()&&$(s).val().toString().length>a&&"01/01/2001"!=$(s).val().toString()||$(s).is("select")&&null!==$(s).val();"email"==$(s).attr("type")&&(r=$(s).is(":valid")&&this.IsEmail($(s).val())),r?($(s).is("select")?($(s).next(".select2").find(".select2-selection").addClass("required-correct").removeClass("required-error"),$(s).parent().hasClass("border-left")&&$(s).parent().removeClass("border-left")):$(s).addClass("required-correct").removeClass("required-error"),$(e).attr("data-error",--n)):($(s).is("select")?$(s).next(".select2").find(".select2-selection").addClass("required-error").removeClass("required-correct"):$(s).removeClass("required-correct").addClass("required-error"),$(s).closest(".geral-info").length>0&&$(s).closest(".card-info").addClass("card-error"),$(s).closest(".secondary-info").length>0&&$(s).closest(".secondary-info").find(".nav-item[name="+i+"]").addClass("nav-item-error"),t=!1),"0"==$(e).attr("data-error")&&($(s).closest(".secondary-info").find(".nav-item[name="+i+"]").removeClass("nav-item-error"),$(s).closest(".card-info").removeClass("card-error"))};return $.each(s,(e,t)=>{if($(t).find("[required]").length>0){$(t).attr("data-error",$(t).find("[required]").length);var s=$(t).find("[required]");$.each(s,(e,s)=>{let n=void 0!==$(s).attr("length")&&null!==$(s).attr("length")?Number($(s).attr("length")):1;a($(t),$(s),n,$(t).attr("data-error")),$(s).is("select")||$(s).off("change").on("change",()=>{this.ValidateRequiredFields()})})}else $(t).closest(".secondary-info").find(".nav-item[name="+$(t).attr("name")+"]").removeClass("nav-item-error")}),t}InitDatepicker(e){this.DestroyDatepicker(e),e.datepicker({dateFormat:"dd/mm/yy",gotoCurrent:!0,changeMonth:!0,changeYear:!0,maxDate:new Date})}InitMonthRangePicker(e,t,s=null){let a=s||{Button:!1,MinMonth:"-50y",MaxMonth:"+10y",i18n:{year:"Ano",backTo:"Voltar para",months:["Jan","Fev","Mar","Abril","Maio","Jun","Jul","Ago","Set","Out","Nov","Dez"]}};e.MonthPicker(Object.assign(Object.assign({},a),{OnAfterChooseMonth:function(s){t.MonthPicker("option","MinMonth",s),e.MonthPicker("GetSelectedDate")>t.MonthPicker("GetSelectedDate")&&t.MonthPicker("option","SelectedMonth",e.val()),$(this).change()}})),t.MonthPicker(a)}InitDateRangePicker(e,t,s=null){this.DestroyDatepicker(e),this.DestroyDatepicker(t);let a=s||{dateFormat:"dd/mm/yy",gotoCurrent:!0,changeMonth:!0,changeYear:!0,yearRange:"-50:+10",defaultDate:new Date,showButtonPanel:!0,beforeShow:function(e){setTimeout((function(){let t=$(e).datepicker("widget").find(".ui-datepicker-buttonpane");t.find(".ui-datepicker-close,.ui-datepicker-current").hide(),$("",{class:"ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all",text:"Limpar",click:function(){e.value="",$.datepicker._hideDatepicker()}}).appendTo(t),t.show()}),1)}};e.datepicker(Object.assign(Object.assign({},a),{onSelect:function(e,s){t.datepicker("option","minDate",e),$(this).change()}})),t.datepicker(a),t.datepicker("option","minDate",e.val())}DestroyDatepicker(e){null!=e.data("datepicker")?e.datepicker("destroy"):e.attr("id","").removeClass("hasDatepicker").removeData("datepicker").unbind()}InitDateTimePicker(e,t=null){e.datetimepicker(Object.assign(Object.assign({},{format:"d/m/Y H:i",step:30,timepicker:!0}),t))}InitDateTimeRangePicker(e,t){let s={};s=Object.assign(Object.assign({},s),{format:"d/m/Y H:i",step:30,timepicker:!0}),e.datetimepicker(s),t.datetimepicker(s),e.datetimepicker("validate",null),t.datetimepicker("validate",null),e.on("change",s=>{var a;(null!==(a=e.val())&&void 0!==a?a:"").length>0&&this.SetDateTimePickerMinMax(e,t)}),t.on("change",s=>{var a;(null!==(a=t.val())&&void 0!==a?a:"").length>0&&this.SetDateTimePickerMinMax(e,t)}),this.SetDateTimePickerMinMax(e,t)}SetDateTimePickerMinMax(e,t){var s,a,n,i,r;if(0==(null!==(s=e.val())&&void 0!==s?s:"").length)return;let o=e.datetimepicker("getValue",null),l=(null!==(a=e.val())&&void 0!==a?a:"").split(" ")[0],c=(null!==(n=e.val())&&void 0!==n?n:"").split(" ")[1],u=t.datetimepicker("getValue",null),d=(null!==(i=t.val())&&void 0!==i?i:"").split(" ")[0];(null!==(r=t.val())&&void 0!==r?r:"").split(" ")[1],o>u&&(t.val(e.val()),t.datetimepicker("validate",null)),l==d?t.datetimepicker("setOptions",{minTime:c,formatTime:"H:i"}):(e.datetimepicker("setOptions",{maxTime:!1}),t.datetimepicker("setOptions",{minTime:!1})),t.datetimepicker("setOptions",{minDate:l,formatDate:"d/m/Y"})}PostalCodeMaskToLocation(e,t,s){e.mask("9999-999",{onComplete:a=>function(e,t,s,a){return new(s||(s=Promise))((function(n,i){function r(e){try{l(a.next(e))}catch(e){i(e)}}function o(e){try{l(a.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,o)}l((a=a.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){null!=s&&s.val(""),t.val(""),(new google.maps.Geocoder).geocode({address:a},(a,n)=>{if(n==google.maps.GeocoderStatus.OK){var i=$.grep(a[0].address_components,e=>-1!=$.inArray("locality",e.types));i.length&&t.val(null!=i[0].long_name?i[0].long_name:""),null!=s&&((i=$.grep(a[0].address_components,e=>-1!=$.inArray("administrative_area_level_1",e.types))).length&&s.val(null!=i[0].long_name?i[0].long_name:""),""==t.val()&&((i=$.grep(a[0].address_components,e=>-1!=$.inArray("locality",e.types))).length?t.val(null!=i[0].long_name?i[0].long_name:""):t.val(s.val()))),void 0!==e.closest(".card-info").attr("data-error")&&this.ValidateRequiredFields()}else t.prop("disabled",!1),null!=s&&s.prop("disabled",!1)})}))})}InitAutoCompleteCity(e){var t=document.getElementById(e);if((t.value||"").length>0){var s=new google.maps.places.Autocomplete(t,{types:["(cities)"],componentRestrictions:{country:["PT"]}});google.maps.event.addListener(s,"place_changed",(function(){var t,a=s.getPlace();null!=a.address_components&&(t=$.grep(a.address_components,e=>-1!=$.inArray("locality",e.types))),$("#"+e).val(void 0!==t?t[0].long_name:a.name),void 0!==$("#"+e).closest(".card-info").attr("data-error")&&(new u).ValidateRequiredFields(),$(".details-info-city").text($("#"+e).val())}))}}ClearStorage(){localStorage.removeItem("ConsultantsSelected"),localStorage.removeItem("ConsultantsSelected"),localStorage.removeItem("ClientsSelected"),localStorage.removeItem("SuppliersSelected"),localStorage.removeItem("ProposalsSelected"),localStorage.removeItem("RecruitmentRequestConsultantsSelected")}Masks(e,t){e.mask(t)}Email_Click(){$("#email").off().on("click",e=>{let t,s;if(($(e.currentTarget).closest("body").find("#table-consultants").length>0||$(e.currentTarget).closest("body").find(".container-sec-forms.consultants").length>0)&&(t="consultant"),$(e.currentTarget).closest("body").find("#table-clients").length>0&&(t="client"),$(e.currentTarget).closest("body").find("#table-consultants").length>0&&(t="consultant"),s=$(e.currentTarget).closest("body").find(".container-sec-forms.consultants").length>0?$(e.currentTarget).closest("body").find(".selected-card").map((e,s)=>$(s).closest(".individual-card").data(t+"-id")).get().length:$(".list-data input:checked").map((e,s)=>$(s).closest(".list-line").data(t+"-id")).get().length,s>0){this.ToggleLoading();var a=new l.EmailModel,n=[],i=[];let s;$(e.currentTarget).closest("body").find(".container-sec-forms.consultants").length>0?(s=$(e.currentTarget).closest("body").find(".selected-card").map((e,s)=>(n[e]=$(s).closest(".individual-card").find("h3").html(),i[e]=this.FirstLastName(n[e])," "+$(s).closest(".individual-card").data(t+"-email"))).get().join(";").trim(),a.To=s):(s=$(".list-data input:checked").map((e,s)=>(n[e]=$($(s).closest(".list-line").find(".name")).html(),i[e]=this.FirstLastName(n[e])," "+$(s).closest(".list-line").data(t+"-email"))).get().join(";").trim(),a.To=s),this._consultantsService.GetEmail(a,{success:e=>{e&&this.CreateEmailContainer(e,i,a,t)},error:()=>{this.ToggleAlert(1,"Erro ao obter formulário de e-mail")},complete:()=>{this.ToggleLoading()}})}else"consultant"===t?this.ToggleAlert(1,"Selecione o(s) Candidato(s)"):this.ToggleAlert(1,"Selecione o(s) Cliente(s)")})}GetScheduleAlerts(e=!1){this.IsUserAuth()&&$(".dropdown-schedules").length>0&&this._homeService.GetScheduleAlerts({success:e=>{$(".dropdown-schedules").html(""),$(".dropdown-schedules").html(e),0==$("#count-schedule").data("schedules-count")?$("#no-notifications-schedule").show():$("#no-notifications-schedule").hide()},complete:()=>{this.SetCountScheduleAlerts(),1==e&&setTimeout(()=>{this.GetScheduleAlerts(e)},this._baseConsts.timeoutTime)}})}SetCountScheduleAlerts(){0!==Number($("#count-schedule").data("schedules-count"))?(this._baseConsts.$countScheduleAlerts().show(),this._baseConsts.$countScheduleAlerts().text($("#count-schedule").data("schedules-count"))):this._baseConsts.$countScheduleAlerts().hide()}GetAlerts(e=!1){this.IsUserAuth()&&$(".dropdown-alerts").length>0&&this._homeService.GetAlerts({success:e=>{$(".dropdown-alerts").html(""),$(".dropdown-alerts").html(e),0==$("#count-alert").data("alerts-count")?$("#no-notifications").show():$("#no-notifications").hide(),this.SetAlertCleanBtnAction()},complete:()=>{this.SetCountAlerts(),1==e&&setTimeout(()=>{this.GetAlerts(e)},this._baseConsts.timeoutTime)}})}SetAlertCleanBtnAction(){$(".dropdown-alerts .alertItem .cleanAlertBtn").off().on("click",e=>{let t=$(e.currentTarget),s=(t.attr("data-target-type")||"").toString(),a=(t.attr("data-target-object")||"").toString(),n=Number((t.attr("data-target-object-id")||"").toString());this._homeService.MarkAlertAsRead(s,a,n,{complete:()=>{e.currentTarget.closest(".alertItem").remove(),this.GetAlerts()}})})}SetCountAlerts(){0!==Number($("#count-alert").data("alerts-count"))?(this._baseConsts.$countAlerts().show(),this._baseConsts.$countAlerts().text($("#count-alert").data("alerts-count"))):this._baseConsts.$countAlerts().hide()}GetFavourites(){this.IsUserAuth()&&$(".dropdown-favourites").length>0&&this._homeService.GetFavourites({success:e=>{$(".dropdown-favourites").html(""),$(".dropdown-favourites").html(e),0==$("#count-favourite").data("favourite-count")?$("#no-favourites").show():$("#no-favourites").hide()},complete:()=>{this.SetCountFavourites(),setTimeout(()=>{this.GetFavourites()},this._baseConsts.timeoutTime)}})}SetCountFavourites(){0!==Number($("#count-favourite").data("favourite-count"))?(this._baseConsts.$countFavourites().show(),this._baseConsts.$countFavourites().text($("#count-favourite").data("favourite-count"))):this._baseConsts.$countFavourites().hide()}GetIsoDateOrDefault(e){return null!=e?e.toISOString():null}CopyToClipboard(e){e.on("click",e=>{e.preventDefault();let t=document.createElement("textarea");t.value=$(e.currentTarget).data("title"),document.body.appendChild(t),t.select(),document.execCommand("copy"),t.remove(),this.ToggleAlert(4,"Copiado para Área de Transferências")})}UnableHistoric(e){let t=e.parents(".timeline-inverted"),s=t.find("textarea"),a=t.find(".form-datepicker"),n=t.find(".icons-timeline"),i=t.find("[name=historic-type]");n.css("pointer-events","auto"),s.removeClass("filled-text").removeAttr("readonly"),a.removeAttr("disabled"),i.removeAttr("disabled")}DisableHistoric(){$(".timeline").find(".timeline-inverted").map((e,t)=>{let s=$(t),a=s.find("textarea"),n=s.find(".form-datepicker"),i=s.find(".icons-timeline"),r=s.find("[name=historic-type]");i.css("pointer-events","auto"),a.addClass("filled-text").attr("readonly","readonly"),n.attr("disabled","disabled"),r.attr("disabled","disabled")})}RemoveModal(){$(".modal-backdrop, body > link").remove()}FormatNumeric(e){return e.toLocaleString("de-DE")}OpenFilter(e){$(".open-filter").off().on("click",t=>{e.toggle()})}IsUserAuth(){return"TRUE"==($("body").attr("data-is-auth")||"").toUpperCase()}TranslateCalendar(){$.datepicker.setDefaults({showOn:"focus",dateFormat:"dd/mm/yy",dayNames:["Domingo","Segunda","Terça","Quarte","Quinta","Sexta","Sábado"],dayNamesMin:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"],monthNames:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],firstDay:1})}HideBackward(){$(".back-wrapper").hide()}}!function(e){e.ClientState="Estado",e.ClientVAT="VAT",e.Origin="Origens",e.OriginHideSpontaneous="Origens ",e.AvailabilityStatus="Período",e.AvailabilityStatusToAvailability="Período ",e.Local="Locais",e.Profile="Perfis",e.Area="Áreas",e.Skill="Especializações",e.HabilitationDegree="Habilitações Literárias",e.Gender="Género",e.DriverLicense="Cartas de Condução",e.Nationality="Nacionalidades",e.Language="Linguagem",e.JobPosition="Cargo",e.PhoneCode="351",e.LanguageSkillLevel="Nível",e.Client="Cliente",e.ClientStates="Estado Cliente",e.CompanySector="Sector",e.ActivityType="Atividade",e.RequestedSkill="Último Pedido",e.Users="Gestores",e.HistoricTypes="Atividades",e.ClientLeadSources="Lead Source",e.ClientSaleStages="Sale Stage",e.ScheduleCategories="Categorias",e.RecruitmentRequestConsultantStatus="Estado do Candidato",e.UserClients="Clientes",e.RecruitmentRequests="Oportunidades",e.ProjectStates="Estado do Projeto",e.ConsultantsIsInternal="Recursos",e.Priority="Prioridade",e.ProjectTasks="Tarefas do Projeto",e.ProjectServices="Serviços",e.ContractTypes="Contratos",e.CivilStates="Estado Civil",e.ClientContactsProject="Contactos Cliente",e.HolidayAllowance="Subsídio Férias",e.ConsultantsState="Estado Colaboradores",e.TimesheetsClients="Timesheet Clientes",e.TimesheetsProducts="Timesheet Produtos",e.TimesheetsProjects="Timesheet Projetos",e.TimesheetsTasks="Timesheet Tarefas",e.ExpensesTypes="Estado da Despesa",e.ExpensesStates="Tipo da Despesa",e.ExpensesProjects="Despesas Projetos",e.ExpensesProjectsSelect="Projetos",e.ExpensesConsultants="Colaboradores",e.StateProject="Estado do Projeto",e.Company="Empresa",e.BusinessGroup="Grupo Empresarial",e.BusinessArea="Área de Negócio",e.BusinessAreaSupplier="Área de Negócio Fornecedor",e.PaymentCondition="Condições de Pagamento",e.TaskCategories="Categorias de Tarefas",e.TaskPriorities="Prioridades de Tarefas",e.TaskStates="Estado de Tarefas",e.Consultants="Colaboradores",e.Managers="Managers",e.BudgetType="BudgetType",e.BudgetItem="BudgetItem",e.BudgetSubitem="BudgetSubitem",e.Suppliers="Fornecedores",e.OperationalStatus="Status operacional",e.BudgetExportType="BudgetExportType",e.BudgetExportTemplate="BudgetExportTemplate",e.BoughtOrderExportTemplate="BoughtOrderExportTemplate",e.FinantialStatus="Status financeiro",e.Countries="Países",e.BoughtOrderStates="Status Ordem de Compra",e.ProductStates="Estado do Produto"}(a||(a={})),function(e){e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Success=4]="Success"}(n||(n={}))},function(e,t,s){"use strict";s.r(t),s.d(t,"Select2Helper",(function(){return a})),s.d(t,"SelectOption",(function(){return n}));class a{static GetSelectedIdList(e){return null!=e?e.map(e=>e.id):null}static GetSelectedId(e){return null!=e&&null!=e[0]?e[0].id:null}static GetSelectedName(e){return null!=e?e:null}static GetSelectedText(e){return null!=e&&null!=e[0]?e[0].text:""}static GetSelectedTextList(e){return null!=e?e.map(e=>e.text):null}static AddSelectedOptions(e,t){let s=e.select2("data");s.push(t),this.SetSelectedOptions(e,s)}}a.SetSelectedOptions=(e,t)=>{e.val(null),e.find("option").remove(),$.each(t,(t,s)=>{e.append(`${s.text} `)}),e.trigger("change")};class n{constructor(e){Object.assign(this,e)}}},,,,function(e,t,s){"use strict";s.r(t),s.d(t,"ConsultantInformationType",(function(){return a})),s.d(t,"ConsultantsService",(function(){return i}));var a,n=s(0);!function(e){e.Documents="/Consultants/GetConsultantDocuments",e.History="/Consultants/GetConsultantHistoric",e.Profile="/Consultants/ConsultantProfile",e.Timesheet="/Consultants/GetConsultantTimesheets"}(a||(a={}));class i extends n.BaseService{constructor(){super(),this._getCreate="/Consultants/Create",this._getConsultants="/Consultants/GetConsultants",this._getConsultantEmail="/Consultants/GetConsultantEmail",this._getNewHistoric="/Consultants/GetNewHistoric",this._saveConsultant="/Consultants/SaveConsultant",this._saveConsultantImage="/Consultants/SaveConsultanImage",this._saveConsultantDocuments="/Consultants/SaveConsultantDocuments",this._deleteConsultants="/Consultants/DeleteConsultants",this._deleteDocument="/Consultants/DeleteConsultantDocument",this._sendTokenToEmail="/Consultants/SendTokenToEmail",this._updateConsultantToken="/Consultants/UpdateConsultantToken",this._validateConsultantToken="/Consultants/ValidateConsultantToken",this._sendEmail="/Consultants/SendEmail",this._validateConsultant="/Consultants/ValidateConsultant"}SendEmail(e,t,s,...a){return this.request({url:this._sendEmail,type:n.HTMLVerbs.POST,dataType:n.DataTypes.HTML,data:{mails:e,subject:t,message:s}},a)}GetConsultants(e,...t){return this.request({url:this._getConsultants,type:n.HTMLVerbs.POST,dataType:n.DataTypes.JSON,data:{filter:e}},t)}GetCreate(...e){return this.request({url:this._getCreate,type:n.HTMLVerbs.GET,dataType:n.DataTypes.HTML},e)}GetConsultantInformation(e,t,...s){return this.request({url:e.toString(),type:n.HTMLVerbs.POST,dataType:n.DataTypes.HTML,data:{consultantId:t}},s)}SaveConsultant(e,...t){return this.request({url:this._saveConsultant,type:n.HTMLVerbs.POST,dataType:n.DataTypes.JSON,data:{consultantProfile:e}},t)}SaveConsultantImage(e,t,...s){var a=new FormData;return null!=t&&a.append("UploadedImage",t),a.append("ConsultantId",e.toString()),this.request({type:n.HTMLVerbs.POST,url:this._saveConsultantImage,contentType:!1,processData:!1,data:a},s)}SaveConsultantDocuments(e,t,...s){var a=new FormData;if(null!=t)for(let e=0;e$(".nav-label"),$nav:()=>$(".nav-menu"),$minimizeButton:()=>$("#minimalize-btn"),$page:()=>$(".wrapper"),body:()=>$("body")},this.ToggleMenu=()=>{this._consts.$nav().hasClass("closed")?this.NavMaxStyle():this.NavMinStyle()},this.Minimize_Click=()=>{"Closed"!=localStorage.getItem("NavBar")||this._consts.$nav().hasClass("closed")?""==localStorage.getItem("NavBar")&&this._consts.$nav().hasClass("closed")&&this.NavMaxStyle():this.NavMinStyle(),this._consts.$minimizeButton().off().on("click",e=>{this.ToggleMenu()})}}Init(){this.BindEvents(),""==localStorage.getItem("NavBar")&&this._consts.$nav().hasClass("closed")?this.NavMinStyle():this.NavMaxStyle(),this._consts.body().show()}Load(){}BindEvents(){this.Minimize_Click(),this.Menu_Click(),this.ToggleSubMenu()}ToggleSubMenu(){this._consts.$nav().find(".nav-item.withSubmenu").find(".dropDonwBtn").off().on("click",e=>{e.preventDefault(),e.stopPropagation();let t=$(e.currentTarget),s=t.closest(".nav-item");s.hasClass("collapsedSubmenu")?(s.removeClass("collapsedSubmenu"),s.addClass("expandedSubmenu"),this._consts.$nav().find(`.subNavWrapper[data-sub-menu="${t.attr("data-sub-menu")}"]`).show()):s.hasClass("expandedSubmenu")&&(s.removeClass("expandedSubmenu"),s.addClass("collapsedSubmenu"),this._consts.$nav().find(`.subNavWrapper[data-sub-menu="${t.attr("data-sub-menu")}"]`).hide())})}Menu_Click(){this._consts.$nav().find(".nav-item").off().on("click",e=>{this._consts.$nav().find(".nav-item").removeClass("activeItem"),$(e.currentTarget).addClass("activeItem")})}NavMinStyle(){this._consts.$nav().addClass("closed"),this._consts.$page().css({"margin-left":"65px"}),this._consts.$nav().find(".fa-angle-left").switchClass("fa-angle-left","fa-angle-right"),localStorage.setItem("NavBar","Closed")}NavMaxStyle(){this._consts.$nav().removeClass("closed"),this._consts.$page().css({"margin-left":"150px"}),this._consts.$nav().find(".fa-angle-right").switchClass("fa-angle-right","fa-angle-left"),localStorage.setItem("NavBar","")}}}]);
!function(e){var t={};function s(a){if(t[a])return t[a].exports;var i=t[a]={i:a,l:!1,exports:{}};return e[a].call(i.exports,i,i.exports,s),i.l=!0,i.exports}s.m=e,s.c=t,s.d=function(e,t,a){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(s.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)s.d(a,i,function(t){return e[t]}.bind(null,i));return a},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=11)}([function(e,t,s){"use strict";var a,i;s.r(t),s.d(t,"HTMLVerbs",(function(){return a})),s.d(t,"DataTypes",(function(){return i})),s.d(t,"BaseService",(function(){return r})),function(e){e.GET="GET",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE"}(a||(a={})),function(e){e.JSON="json",e.HTML="html"}(i||(i={}));class r{constructor(){}extendBaseRequest(e,t){return $.extend.apply($,[e].concat(t))}request(e,t){const s=this.extendBaseRequest(e,t);return $.ajax(s)}}},function(e,t,s){"use strict";s.r(t),s.d(t,"BaseViewTemplate",(function(){return d})),s.d(t,"SelectTypeEnum",(function(){return a})),s.d(t,"AlertType",(function(){return i}));var a,i,r=s(8),n=s(2),o=s(6),l=s(7),c=s(9);class d{constructor(){this._selectService=null,this._consultantsService=null,this._homeService=null,this._baseConsts={$countScheduleAlerts:()=>$(".schedules .count-info .label"),$countAlerts:()=>$(".alerts .count-info .label"),$countFavourites:()=>$(".favourites .count-info .label"),timeoutTime:1e4},this.InitSelect=(e,t,s,a,i,r,o=null)=>{$.each(e,(e,l)=>{let c=$(l),u=c.find("option").map((e,t)=>{let s=new n.SelectOption({id:$(t).attr("value"),text:$(t).text()});return s.parentId=$(t).attr("data-parent-id"),s}).toArray();c.find("option").remove();let p={placeholder:i?t:"",allowClear:null!=o&&o,ajax:s,multiple:a,closeOnSelect:!a,tags:r||!1,templateResult:function(e){$(this).attr("data-parent-id",e.parentId);let t=$(`${e.text}`);return t.attr("title",e.text),t}};c.select2(p).on("select2:unselecting",(function(){$(this).data("unselecting",!0)})).on("select2:unselect",(function(e){($(e.currentTarget).closest("div[name=basic-informations]").length>0||$(e.currentTarget).closest("tr.filter-table").length>0)&&(new d).FormatMultipleSelects(c)})).on("select2:opening",(function(e){$(this).data("unselecting")&&($(this).removeData("unselecting"),e.preventDefault())})).on("select2:close",(function(e){$(e.currentTarget).next().find(".select2-selection__rendered li").length>1?$(e.currentTarget).next().find(".select2-search--inline").hide():$(e.currentTarget).next().find(".select2-search--inline").show()})).on("select2:select",(function(e){if(($(e.currentTarget).closest("div[name=basic-informations]").length>0||$(e.currentTarget).closest("tr.filter-table").length>0)&&(new d).FormatMultipleSelects(c),(void 0!==$(e.currentTarget).closest(".card-info").attr("data-error")&&"0"!==$(e.currentTarget).closest(".card-info").attr("data-error")||void 0!==$(e.currentTarget).closest(".container-sec-forms").attr("data-error")&&"0"!==$(e.currentTarget).closest(".container-sec-forms").attr("data-error"))&&(new d).ValidateRequiredFields(),"jobPosition"==$(e.currentTarget).attr("name")&&$(e.currentTarget).closest(".experience").find(".present-date").hasClass("present-date-selected")){let t=$(".detail-info-container h4").text();""!=t&&(t+=" / "),t+=$(e.currentTarget)[0].outerText,$(".detail-info-container h4").text(t),$(".detail-info-container h4").attr("title",t)}})),n.Select2Helper.SetSelectedOptions(c,u)})},this.CreateEmailContainer=(e,t,s,a)=>{$("body").append(e),$(".wrapper, .nav-menu").css({opacity:.4,"pointer-events":"none"});let i=$(".send-email-container");$.each(t,(function(e,t){$(i.find(".mailsadd")).before("x "+t+";
")})),i.find(".mailsadd").off().on("change",()=>{if(null!=$(".mailsadd").val()&&this.IsEmail($(".mailsadd").val())){var e=$(".mailsadd").val(),t="";0===s.To.length?s.To+=e:s.To+=";"+e;let n=1==$("#table-"+a+"s").find("[data-"+a+"-email='"+e+"']").length;n&&(t=this.FirstLastName($($("#table-"+a+"s").find("[data-"+a+"-email='"+e+"']").find(".name")).html()));var r=$(document.createElement("p"));r.html("x "+(n?t:e)+";"),r.find("span").off().on("click",e=>{s.To=(new d).DeleteEmailForm(s.To,e)}),$(i.find(".mailsadd")).before(r),$(".mailsadd").val(null)}else this.ToggleAlert(1,"Insira um e-mail válido")}),i.find(".names p span").off().on("click",e=>{s.To=(new d).DeleteEmailForm(s.To,e)}),$("#cancel").off().on("click",e=>{$(".send-email-container").remove();var t=$(".wrapper").css("margin-left");$(".wrapper").removeAttr("style"),$(".nav-menu").css({opacity:"1","pointer-events":"all"}),$(".wrapper").css("margin-left",t)}),i.find("#button-send-email").off().on("click",e=>{this.ToggleLoading();var t=i.find(".signature").html().trim(),a=i.find(".message").val().replace(/(\r\n|\n)/g," "),r=encodeURI(a+t);this._consultantsService.SendEmail(s.To,i.find(".subject").val(),r,{success:e=>{i.remove();var t=$(".wrapper").css("margin-left");$(".wrapper").removeAttr("style"),$(".nav-menu").css({opacity:"1","pointer-events":"all"}),$(".wrapper").css("margin-left",t),this.ToggleAlert(4,"E-mail enviado com sucesso")},error:(e,t)=>{this.ToggleAlert(1,"Erro ao enviar e-mail")},complete:()=>{this.ToggleLoading()}})})},this.FirstLastName=e=>{let t;if(null!=e){var s=e.split(" ");return t=1==s.length?s[0]:s[0]+" "+s[s.length-1],t}},this.DeleteEmailForm=(e,t)=>{var s=e.split(";");return s.splice($(t.currentTarget.parentElement).index(),1),$(t.currentTarget.parentElement).remove(),s.join(";").trim()},this.PageTitle=e=>{$("#pageTitle").text(e);let t=$("head title");t.text(`${t.attr("data-prefix")} - ${e}`)},this.GetQueryStringParameter=e=>new URLSearchParams(window.location.search).get(e),this.DeleteQueryStringParameter=e=>{let t=new URLSearchParams(window.location.search);t.delete(e);let s=t.toString();""!=s.trim()&&(s="?"+s),history.replaceState(null,"",s||window.location.pathname)},this.Back=()=>{$(window).trigger("beforePageBack"),window.history.back()},this._selectService=new r.SelectService,this._consultantsService=new o.ConsultantsService,this._homeService=new c.HomeService,$.datetimepicker.setLocale("pt")}Init(){}Load(){}BindEvents(){}BindSelect(e,t,s,i,r,n,o=null,l=null){let c=null;switch(t){case a.ClientState:c=this._selectService.GetClientStatesAjaxOptions(n);break;case a.ClientVAT:c=this._selectService.GetClientVATsAjaxOptions(n);break;case a.Local:c=this._selectService.GetCitiesAjaxOptions(n);break;case a.Nationality:c=this._selectService.GetNationalitiesAjaxOptions(n);break;case a.ClientStates:c=this._selectService.GetClientStatesAjaxOptions(n);break;case a.JobPosition:c=this._selectService.GetJobPositionsAjaxOptions(n);break;case a.PhoneCode:c=this._selectService.GetPhoneCodesAjaxOptions(n);break;case a.Users:c=this._selectService.GetUsersAjaxOptions(n);break;case a.HistoricTypes:c=this._selectService.GetHistoricTypesjaxOptions(n);break;case a.ScheduleCategories:c=this._selectService.GetScheuduleCategories(n);break;case a.UserClients:c=this._selectService.GetUserClientsAjaxOptions(n);break;case a.RecruitmentRequests:c=this._selectService.GetRecruitmentRequestsToScheduleAjaxOptions(n);break;case a.OperationalStatus:c=this._selectService.GetOperationalStatusAjaxOptions(n);break;case a.FinantialStatus:c=this._selectService.GetFinantialStatusAjaxOptions(n);break;case a.ProjectStates:c=this._selectService.GetProjectStatusAjaxOptions(n);break;case a.Priority:c=this._selectService.GetProjectPriorityAjaxOptions(n);break;case a.ProjectTasks:c=this._selectService.GetProjectTasksAjaxOptions(n);break;case a.ProjectServices:c=this._selectService.GetProjectServicesAjaxOptions(n);break;case a.ConsultantsState:c=this._selectService.GetConsultantsStatesAjaxOptions(n);break;case a.TimesheetsClients:c=this._selectService.GetTimesheetsClientsAjaxOptions(n);break;case a.ClientContactsProject:c=this._selectService.GetProjectClientContactsAjaxOptions(n);break;case a.TimesheetsProducts:c=this._selectService.GetTimesheetsProductsAjaxOptions(n);break;case a.TimesheetsProjects:c=this._selectService.GetTimesheetsProjectsAjaxOptions(n);break;case a.TimesheetsTasks:c=this._selectService.GetTimesheetsTasksAjaxOptions(n);break;case a.ExpensesStates:c=this._selectService.GetExpensesStatesAjaxOptions(n);break;case a.ExpensesTypes:c=this._selectService.GetExpensesTypesAjaxOptions(n);break;case a.ExpensesProjects:c=this._selectService.GetExpensesProjectsAjaxOptions(n);break;case a.ExpensesProjectsSelect:c=this._selectService.GetExpensesProjectsSelectAjaxOptions(n);break;case a.ExpensesConsultants:c=this._selectService.GetExpensesConsultantsAjaxOptions(n);break;case a.BusinessGroup:c=this._selectService.GetBusinessGroupsAjaxOptions(n);break;case a.BusinessArea:c=this._selectService.GetBusinessAreasAjaxOptions(n);break;case a.BusinessAreaSupplier:c=this._selectService.GetBusinessAreasSupplierAjaxOptions(n);break;case a.Company:c=this._selectService.GetCompaniesAjaxOptions(n);break;case a.PaymentCondition:c=this._selectService.GetClientPaymentConditionsAjaxOptions(n);break;case a.TaskCategories:c=this._selectService.GetTaskCategoriesAjaxOptions(n);break;case a.TaskPriorities:c=this._selectService.GetTaskPrioritiesAjaxOptions(n);break;case a.TaskStates:c=this._selectService.GetTaskStatesAjaxOptions(n);break;case a.Consultants:c=this._selectService.GetConsultants(n);break;case a.Managers:c=this._selectService.GetManagersAjaxOptions(n);break;case a.BudgetType:c=this._selectService.GetBudgetTypeAjaxOptions(n);break;case a.BudgetItem:c=this._selectService.GetBudgetItemAjaxOptions(n);break;case a.BudgetSubitem:c=this._selectService.GetBudgetSubitemAjaxOptions(n);break;case a.Suppliers:c=this._selectService.GetSuppliersAjaxOptions(n);break;case a.BudgetExportType:c=this._selectService.GetBudgetExportTypeAjaxOptions(n);break;case a.BudgetExportTemplate:c=this._selectService.GetBudgetExportTemplateAjaxOptions(n);break;case a.BoughtOrderExportTemplate:c=this._selectService.GetBoughtOrderExportTemplateAjaxOptions(n);break;case a.Countries:c=this._selectService.GetCountriesAjaxOptions(n);break;case a.BoughtOrderStates:c=this._selectService.GetBoughtOrderStatesAjaxOptions(n);break;case a.ProductStates:c=this._selectService.GetProductStatesAjaxOptions(n)}null!=c?(this.InitSelect(e,l||t.toString(),c,s,i,r,o),t!=a.Nationality&&t!=a.DriverLicense||this.FormatMultipleSelects(e)):console.log("ERROR! ["+t+"]")}Tooltip(){$('[data-toggle="tooltip"]').tooltip({position:{my:"left-120 center-25",at:"right center"}})}AddMessageiIfNoData(){0==Number($(".list-data").attr("data-row-count"))?($(".no-results-container").css("display","flex"),$(".list-data").hide()):($(".no-results-container").css("display","none"),$(".list-data").show())}FormatMultipleSelects(e){setTimeout(()=>{let t=e.next().find(".select2-selection__choice:eq(0)").nextAll(".select2-selection__choice"),s=t.map((e,t)=>$.trim($(t).text().slice(1,$(t).text().length))).get().join(", ");if(""!==s){t.hide();var a=$(document.createElement("li"));a.addClass("select2-selection__choices").attr("data-toggle","tooltip").attr("title",s),a.text("+"+t.length),a.insertBefore(t.parent().find(".select2-search--inline")),this.Tooltip()}void 0!==e.closest(".card-info").attr("data-error")&&this.ValidateRequiredFields()},150)}FormatMultipleSelectsPlaceHolder(e){let t=$(".search-container");if(""!=e)t.find("li[name="+e+"]").find("input").css("width","100%"),t.find("li[name="+e+"]").find(".select2-search--inline").show();else{t.find("li.search-item").find("input").css("width","100%"),t.find("li.search-item").find(".select2-search--inline").show();let e=t.find("li.search-item").find("ul.select2-selection__rendered");$.each(e,(e,t)=>{$(t).find("li.select2-selection__choice").length>0?$(t).find("li.select2-search--inline").hide():$(t).find("li.select2-search--inline").show()})}}IsEmail(e){return/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(e)}CloseNavBar(){}ToggleLoading(e=null){!0===e?$(".loading").addClass("hide"):!1===e?$(".loading").removeClass("hide"):$(".loading").toggleClass("hide")}ToggleAlert(e,t){let s,a;switch(e){case i.Error:s="alert-danger",a="fas fa-exclamation-triangle";break;case i.Warning:s="alert-warning",a="fas fa-exclamation-triangle";break;case i.Info:s="alert-info",a="fas fa-exclamation-circle";break;case i.Success:s="alert-success",a="far fa-check-circle";break;default:s="alert-danger",a="fas fa-exclamation-triangle"}var r=$(".alert");r.removeAttr("class").addClass("alert").addClass(s),r.find(".icon").removeAttr("class").addClass("icon").addClass(a),r.find(".message").html(t),r.fadeIn(),r.find(".close").on("click",e=>{$(e.target).parent().fadeOut()}),setTimeout((function(){r.fadeOut()}),3e3)}ValidateRequiredFields(e){var t=!0,s=null!=e?e:$(".container-sec-forms, .card-info"),a=(e,s,a,i)=>{let r=$(s).closest(".container-sec-forms").attr("name"),n=null!==$(s).val()&&$(s).val().toString().length>a&&"01/01/2001"!=$(s).val().toString()||$(s).is("select")&&null!==$(s).val();"email"==$(s).attr("type")&&(n=$(s).is(":valid")&&this.IsEmail($(s).val())),n?($(s).is("select")?($(s).next(".select2").find(".select2-selection").addClass("required-correct").removeClass("required-error"),$(s).parent().hasClass("border-left")&&$(s).parent().removeClass("border-left")):$(s).addClass("required-correct").removeClass("required-error"),$(e).attr("data-error",--i)):($(s).is("select")?$(s).next(".select2").find(".select2-selection").addClass("required-error").removeClass("required-correct"):$(s).removeClass("required-correct").addClass("required-error"),$(s).closest(".geral-info").length>0&&$(s).closest(".card-info").addClass("card-error"),$(s).closest(".secondary-info").length>0&&$(s).closest(".secondary-info").find(".nav-item[name="+r+"]").addClass("nav-item-error"),t=!1),"0"==$(e).attr("data-error")&&($(s).closest(".secondary-info").find(".nav-item[name="+r+"]").removeClass("nav-item-error"),$(s).closest(".card-info").removeClass("card-error"))};return $.each(s,(e,t)=>{if($(t).find("[required]").length>0){$(t).attr("data-error",$(t).find("[required]").length);var s=$(t).find("[required]");$.each(s,(e,s)=>{let i=void 0!==$(s).attr("length")&&null!==$(s).attr("length")?Number($(s).attr("length")):1;a($(t),$(s),i,$(t).attr("data-error")),$(s).is("select")||$(s).off("change").on("change",()=>{this.ValidateRequiredFields()})})}else $(t).closest(".secondary-info").find(".nav-item[name="+$(t).attr("name")+"]").removeClass("nav-item-error")}),t}InitDatepicker(e){this.DestroyDatepicker(e),e.datepicker({dateFormat:"dd/mm/yy",gotoCurrent:!0,changeMonth:!0,changeYear:!0,maxDate:new Date})}InitMonthRangePicker(e,t,s=null){let a=s||{Button:!1,MinMonth:"-50y",MaxMonth:"+10y",i18n:{year:"Ano",backTo:"Voltar para",months:["Jan","Fev","Mar","Abril","Maio","Jun","Jul","Ago","Set","Out","Nov","Dez"]}};e.MonthPicker(Object.assign(Object.assign({},a),{OnAfterChooseMonth:function(s){t.MonthPicker("option","MinMonth",s),e.MonthPicker("GetSelectedDate")>t.MonthPicker("GetSelectedDate")&&t.MonthPicker("option","SelectedMonth",e.val()),$(this).change()}})),t.MonthPicker(a)}InitDateRangePicker(e,t,s=null){this.DestroyDatepicker(e),this.DestroyDatepicker(t);let a=s||{dateFormat:"dd/mm/yy",gotoCurrent:!0,changeMonth:!0,changeYear:!0,yearRange:"-50:+10",defaultDate:new Date,showButtonPanel:!0,beforeShow:function(e){setTimeout((function(){let t=$(e).datepicker("widget").find(".ui-datepicker-buttonpane");t.find(".ui-datepicker-close,.ui-datepicker-current").hide(),$("",{class:"ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all",text:"Limpar",click:function(){e.value="",$.datepicker._hideDatepicker()}}).appendTo(t),t.show()}),1)}};e.datepicker(Object.assign(Object.assign({},a),{onSelect:function(e,s){t.datepicker("option","minDate",e),$(this).change()}})),t.datepicker(a),t.datepicker("option","minDate",e.val())}DestroyDatepicker(e){null!=e.data("datepicker")?e.datepicker("destroy"):e.attr("id","").removeClass("hasDatepicker").removeData("datepicker").unbind()}InitDateTimePicker(e,t=null){e.datetimepicker(Object.assign(Object.assign({},{format:"d/m/Y H:i",step:30,timepicker:!0}),t))}InitDateTimeRangePicker(e,t){let s={};s=Object.assign(Object.assign({},s),{format:"d/m/Y H:i",step:30,timepicker:!0}),e.datetimepicker(s),t.datetimepicker(s),e.datetimepicker("validate",null),t.datetimepicker("validate",null),e.on("change",s=>{var a;(null!==(a=e.val())&&void 0!==a?a:"").length>0&&this.SetDateTimePickerMinMax(e,t)}),t.on("change",s=>{var a;(null!==(a=t.val())&&void 0!==a?a:"").length>0&&this.SetDateTimePickerMinMax(e,t)}),this.SetDateTimePickerMinMax(e,t)}SetDateTimePickerMinMax(e,t){var s,a,i,r,n;if(0==(null!==(s=e.val())&&void 0!==s?s:"").length)return;let o=e.datetimepicker("getValue",null),l=(null!==(a=e.val())&&void 0!==a?a:"").split(" ")[0],c=(null!==(i=e.val())&&void 0!==i?i:"").split(" ")[1],d=t.datetimepicker("getValue",null),u=(null!==(r=t.val())&&void 0!==r?r:"").split(" ")[0];(null!==(n=t.val())&&void 0!==n?n:"").split(" ")[1],o>d&&(t.val(e.val()),t.datetimepicker("validate",null)),l==u?t.datetimepicker("setOptions",{minTime:c,formatTime:"H:i"}):(e.datetimepicker("setOptions",{maxTime:!1}),t.datetimepicker("setOptions",{minTime:!1})),t.datetimepicker("setOptions",{minDate:l,formatDate:"d/m/Y"})}PostalCodeMaskToLocation(e,t,s){e.mask("9999-999",{onComplete:a=>function(e,t,s,a){return new(s||(s=Promise))((function(i,r){function n(e){try{l(a.next(e))}catch(e){r(e)}}function o(e){try{l(a.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(n,o)}l((a=a.apply(e,t||[])).next())}))}(this,void 0,void 0,(function*(){null!=s&&s.val(""),t.val(""),(new google.maps.Geocoder).geocode({address:a},(a,i)=>{if(i==google.maps.GeocoderStatus.OK){var r=$.grep(a[0].address_components,e=>-1!=$.inArray("locality",e.types));r.length&&t.val(null!=r[0].long_name?r[0].long_name:""),null!=s&&((r=$.grep(a[0].address_components,e=>-1!=$.inArray("administrative_area_level_1",e.types))).length&&s.val(null!=r[0].long_name?r[0].long_name:""),""==t.val()&&((r=$.grep(a[0].address_components,e=>-1!=$.inArray("locality",e.types))).length?t.val(null!=r[0].long_name?r[0].long_name:""):t.val(s.val()))),void 0!==e.closest(".card-info").attr("data-error")&&this.ValidateRequiredFields()}else t.prop("disabled",!1),null!=s&&s.prop("disabled",!1)})}))})}InitAutoCompleteCity(e){var t=document.getElementById(e);if((t.value||"").length>0){var s=new google.maps.places.Autocomplete(t,{types:["(cities)"],componentRestrictions:{country:["PT"]}});google.maps.event.addListener(s,"place_changed",(function(){var t,a=s.getPlace();null!=a.address_components&&(t=$.grep(a.address_components,e=>-1!=$.inArray("locality",e.types))),$("#"+e).val(void 0!==t?t[0].long_name:a.name),void 0!==$("#"+e).closest(".card-info").attr("data-error")&&(new d).ValidateRequiredFields(),$(".details-info-city").text($("#"+e).val())}))}}ClearStorage(){localStorage.removeItem("ConsultantsSelected"),localStorage.removeItem("ConsultantsSelected"),localStorage.removeItem("ClientsSelected"),localStorage.removeItem("SuppliersSelected"),localStorage.removeItem("ProposalsSelected"),localStorage.removeItem("RecruitmentRequestConsultantsSelected")}Masks(e,t){e.mask(t)}Email_Click(){$("#email").off().on("click",e=>{let t,s;if(($(e.currentTarget).closest("body").find("#table-consultants").length>0||$(e.currentTarget).closest("body").find(".container-sec-forms.consultants").length>0)&&(t="consultant"),$(e.currentTarget).closest("body").find("#table-clients").length>0&&(t="client"),$(e.currentTarget).closest("body").find("#table-consultants").length>0&&(t="consultant"),s=$(e.currentTarget).closest("body").find(".container-sec-forms.consultants").length>0?$(e.currentTarget).closest("body").find(".selected-card").map((e,s)=>$(s).closest(".individual-card").data(t+"-id")).get().length:$(".list-data input:checked").map((e,s)=>$(s).closest(".list-line").data(t+"-id")).get().length,s>0){this.ToggleLoading();var a=new l.EmailModel,i=[],r=[];let s;$(e.currentTarget).closest("body").find(".container-sec-forms.consultants").length>0?(s=$(e.currentTarget).closest("body").find(".selected-card").map((e,s)=>(i[e]=$(s).closest(".individual-card").find("h3").html(),r[e]=this.FirstLastName(i[e])," "+$(s).closest(".individual-card").data(t+"-email"))).get().join(";").trim(),a.To=s):(s=$(".list-data input:checked").map((e,s)=>(i[e]=$($(s).closest(".list-line").find(".name")).html(),r[e]=this.FirstLastName(i[e])," "+$(s).closest(".list-line").data(t+"-email"))).get().join(";").trim(),a.To=s),this._consultantsService.GetEmail(a,{success:e=>{e&&this.CreateEmailContainer(e,r,a,t)},error:()=>{this.ToggleAlert(1,"Erro ao obter formulário de e-mail")},complete:()=>{this.ToggleLoading()}})}else"consultant"===t?this.ToggleAlert(1,"Selecione o(s) Candidato(s)"):this.ToggleAlert(1,"Selecione o(s) Cliente(s)")})}GetScheduleAlerts(e=!1){this.IsUserAuth()&&$(".dropdown-schedules").length>0&&this._homeService.GetScheduleAlerts({success:e=>{$(".dropdown-schedules").html(""),$(".dropdown-schedules").html(e),0==$("#count-schedule").data("schedules-count")?$("#no-notifications-schedule").show():$("#no-notifications-schedule").hide()},complete:()=>{this.SetCountScheduleAlerts(),1==e&&setTimeout(()=>{this.GetScheduleAlerts(e)},this._baseConsts.timeoutTime)}})}SetCountScheduleAlerts(){0!==Number($("#count-schedule").data("schedules-count"))?(this._baseConsts.$countScheduleAlerts().show(),this._baseConsts.$countScheduleAlerts().text($("#count-schedule").data("schedules-count"))):this._baseConsts.$countScheduleAlerts().hide()}GetAlerts(e=!1){this.IsUserAuth()&&$(".dropdown-alerts").length>0&&this._homeService.GetAlerts({success:e=>{$(".dropdown-alerts").html(""),$(".dropdown-alerts").html(e),0==$("#count-alert").data("alerts-count")?$("#no-notifications").show():$("#no-notifications").hide(),this.SetAlertCleanBtnAction()},complete:()=>{this.SetCountAlerts(),1==e&&setTimeout(()=>{this.GetAlerts(e)},this._baseConsts.timeoutTime)}})}SetAlertCleanBtnAction(){$(".dropdown-alerts .alertItem .cleanAlertBtn").off().on("click",e=>{let t=$(e.currentTarget),s=(t.attr("data-target-type")||"").toString(),a=(t.attr("data-target-object")||"").toString(),i=Number((t.attr("data-target-object-id")||"").toString());this._homeService.MarkAlertAsRead(s,a,i,{complete:()=>{e.currentTarget.closest(".alertItem").remove(),this.GetAlerts()}})})}SetCountAlerts(){0!==Number($("#count-alert").data("alerts-count"))?(this._baseConsts.$countAlerts().show(),this._baseConsts.$countAlerts().text($("#count-alert").data("alerts-count"))):this._baseConsts.$countAlerts().hide()}GetFavourites(){this.IsUserAuth()&&$(".dropdown-favourites").length>0&&this._homeService.GetFavourites({success:e=>{$(".dropdown-favourites").html(""),$(".dropdown-favourites").html(e),0==$("#count-favourite").data("favourite-count")?$("#no-favourites").show():$("#no-favourites").hide()},complete:()=>{this.SetCountFavourites(),setTimeout(()=>{this.GetFavourites()},this._baseConsts.timeoutTime)}})}SetCountFavourites(){0!==Number($("#count-favourite").data("favourite-count"))?(this._baseConsts.$countFavourites().show(),this._baseConsts.$countFavourites().text($("#count-favourite").data("favourite-count"))):this._baseConsts.$countFavourites().hide()}GetIsoDateOrDefault(e){return null!=e?e.toISOString():null}CopyToClipboard(e){e.on("click",e=>{e.preventDefault();let t=document.createElement("textarea");t.value=$(e.currentTarget).data("title"),document.body.appendChild(t),t.select(),document.execCommand("copy"),t.remove(),this.ToggleAlert(4,"Copiado para Área de Transferências")})}UnableHistoric(e){let t=e.parents(".timeline-inverted"),s=t.find("textarea"),a=t.find(".form-datepicker"),i=t.find(".icons-timeline"),r=t.find("[name=historic-type]");i.css("pointer-events","auto"),s.removeClass("filled-text").removeAttr("readonly"),a.removeAttr("disabled"),r.removeAttr("disabled")}DisableHistoric(){$(".timeline").find(".timeline-inverted").map((e,t)=>{let s=$(t),a=s.find("textarea"),i=s.find(".form-datepicker"),r=s.find(".icons-timeline"),n=s.find("[name=historic-type]");r.css("pointer-events","auto"),a.addClass("filled-text").attr("readonly","readonly"),i.attr("disabled","disabled"),n.attr("disabled","disabled")})}RemoveModal(){$(".modal-backdrop, body > link").remove()}FormatNumeric(e){return e.toLocaleString("de-DE")}OpenFilter(e){$(".open-filter").off().on("click",t=>{e.toggle()})}IsUserAuth(){return"TRUE"==($("body").attr("data-is-auth")||"").toUpperCase()}TranslateCalendar(){$.datepicker.setDefaults({showOn:"focus",dateFormat:"dd/mm/yy",dayNames:["Domingo","Segunda","Terça","Quarte","Quinta","Sexta","Sábado"],dayNamesMin:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"],monthNames:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],firstDay:1})}HideBackward(){$(".back-wrapper").hide()}}!function(e){e.ClientState="Estado",e.ClientVAT="VAT",e.Origin="Origens",e.OriginHideSpontaneous="Origens ",e.AvailabilityStatus="Período",e.AvailabilityStatusToAvailability="Período ",e.Local="Locais",e.Profile="Perfis",e.Area="Áreas",e.Skill="Especializações",e.HabilitationDegree="Habilitações Literárias",e.Gender="Género",e.DriverLicense="Cartas de Condução",e.Nationality="Nacionalidades",e.Language="Linguagem",e.JobPosition="Cargo",e.PhoneCode="351",e.LanguageSkillLevel="Nível",e.Client="Cliente",e.ClientStates="Estado Cliente",e.CompanySector="Sector",e.ActivityType="Atividade",e.RequestedSkill="Último Pedido",e.Users="Gestores",e.HistoricTypes="Atividades",e.ClientLeadSources="Lead Source",e.ClientSaleStages="Sale Stage",e.ScheduleCategories="Categorias",e.RecruitmentRequestConsultantStatus="Estado do Candidato",e.UserClients="Clientes",e.RecruitmentRequests="Oportunidades",e.ProjectStates="Estado do Projeto",e.ConsultantsIsInternal="Recursos",e.Priority="Prioridade",e.ProjectTasks="Tarefas do Projeto",e.ProjectServices="Serviços",e.ContractTypes="Contratos",e.CivilStates="Estado Civil",e.ClientContactsProject="Contactos Cliente",e.HolidayAllowance="Subsídio Férias",e.ConsultantsState="Estado Colaboradores",e.TimesheetsClients="Timesheet Clientes",e.TimesheetsProducts="Timesheet Produtos",e.TimesheetsProjects="Timesheet Projetos",e.TimesheetsTasks="Timesheet Tarefas",e.ExpensesTypes="Estado da Despesa",e.ExpensesStates="Tipo da Despesa",e.ExpensesProjects="Despesas Projetos",e.ExpensesProjectsSelect="Projetos",e.ExpensesConsultants="Colaboradores",e.StateProject="Estado do Projeto",e.Company="Empresa",e.BusinessGroup="Grupo Empresarial",e.BusinessArea="Área de Negócio",e.BusinessAreaSupplier="Área de Negócio Fornecedor",e.PaymentCondition="Condições de Pagamento",e.TaskCategories="Categorias de Tarefas",e.TaskPriorities="Prioridades de Tarefas",e.TaskStates="Estado de Tarefas",e.Consultants="Colaboradores",e.Managers="Managers",e.BudgetType="BudgetType",e.BudgetItem="BudgetItem",e.BudgetSubitem="BudgetSubitem",e.Suppliers="Fornecedores",e.OperationalStatus="Status operacional",e.BudgetExportType="BudgetExportType",e.BudgetExportTemplate="BudgetExportTemplate",e.BoughtOrderExportTemplate="BoughtOrderExportTemplate",e.FinantialStatus="Status financeiro",e.Countries="Países",e.BoughtOrderStates="Status Ordem de Compra",e.ProductStates="Estado do Produto"}(a||(a={})),function(e){e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Success=4]="Success"}(i||(i={}))},function(e,t,s){"use strict";s.r(t),s.d(t,"Select2Helper",(function(){return a})),s.d(t,"SelectOption",(function(){return i}));class a{static GetSelectedIdList(e){return null!=e?e.map(e=>e.id):null}static GetSelectedId(e){return null!=e&&null!=e[0]?e[0].id:null}static GetSelectedName(e){return null!=e?e:null}static GetSelectedText(e){return null!=e&&null!=e[0]?e[0].text:""}static GetSelectedTextList(e){return null!=e?e.map(e=>e.text):null}static AddSelectedOptions(e,t){let s=e.select2("data");s.push(t),this.SetSelectedOptions(e,s)}}a.SetSelectedOptions=(e,t)=>{e.val(null),e.find("option").remove(),$.each(t,(t,s)=>{e.append(`${s.text} `)}),e.trigger("change")};class i{constructor(e){Object.assign(this,e)}}},,function(e,t,s){"use strict";s.r(t),s.d(t,"ModalHelper",(function(){return i}));var a=s(5);class i{}i._modalBindClass="bind-modal",i._modalDefaultButtonClass=".modal.in .btn-default",i._modalConfirmation="#dialog-confirmation",i._modalConfirmationBtn="#modal-content-confirm",i._modalConfirmationMessage="#dialog-confirmation-message",i._modalConfirmationTitle=".modal-title",i.BindModal=(e,t)=>{let s=$(e);s.find(".modal-content").attr("id",t);let a=$(".modal.in."+i._modalBindClass);if(0==a.length)s.addClass(i._modalBindClass),s.on("hide.bs.modal",e=>{let t=$(e.target);if(t.find(".modal-content").length>1){let s=t.find(".modal-content:visible").prev();t.find(".modal-content:visible").remove(),s.show(),e.preventDefault()}}).on("hidden.bs.modal",e=>{$(e.target).remove()}).modal("show");else{let e=a.find(".modal-content:visible"),t=s.find(".modal-content").addBack(".modal-content");e.hide(),a.find(".modal-dialog").append(t),t.show()}let r=$(".modal.in."+i._modalBindClass).find(".modal-content:visible"),n=r.find('input:not([type="hidden"])');n.first().focus(),n.keypress((function(e){13==e.keyCode&&r.find('.modal-footer input[type="submit"]').trigger("click")}))},i.ConfirmationDialog=(e,t,s,a,r,n,o)=>{$(i._modalConfirmation).modal(),$(i._modalConfirmation).css("z-index","999999 !important"),$(".modal-backdrop.in:eq(1)").css("z-index","999998 !important"),$(i._modalConfirmationMessage).text(e),$(i._modalConfirmationTitle).text(t),$(i._modalConfirmationBtn).attr("value",s),$(i._modalDefaultButtonClass).focus(),$(i._modalConfirmationBtn).unbind("click").bind("click",e=>{a(r,n),$(i._modalConfirmation).modal("hide")}),null!=o?($(".modal-icon i").removeClass(),$(".modal-icon i").addClass(o)):($(".modal-icon i").removeClass(),$(".modal-icon i").addClass("fas fa-trash"))},i.CloseCurrentModal=()=>{$(".modal.in."+i._modalBindClass).modal("hide")},i.AlertMessage=(e,t)=>{var s,i;switch(e){case a.AlertEnum.SUCCESS:s="alert-success",i="fa fa-check";break;case a.AlertEnum.WARNING:s="alert-warning",i="fa fa-exclamation-triangle";break;case a.AlertEnum.DANGER:s="alert-danger",i="fa fa-exclamation-triangle";break;case a.AlertEnum.INFO:default:s="alert-info",i="fa fa-info-circle"}var r=$(".alert");r.removeAttr("class").addClass("alert").addClass(s),r.find(".icon").removeAttr("class").addClass("icon").addClass(i),r.find(".message").html(t),r.fadeIn(),setTimeout((function(){r.fadeOut()}),6e3)}},function(e,t,s){"use strict";var a,i;s.r(t),s.d(t,"AlertEnum",(function(){return a})),s.d(t,"AlertsMessageEnum",(function(){return i})),function(e){e[e.SUCCESS=1]="SUCCESS",e[e.WARNING=2]="WARNING",e[e.DANGER=3]="DANGER",e[e.INFO=4]="INFO"}(a||(a={})),function(e){e.JsTreeGetListUnsuccessfully="Erro a obter dados para gerar a árvore de registos",e.JsTreeCreateRegisterUnsuccessfully="Não foi possivel criar registo, verificar se existem registos com o mesmo nome no mesmo ramo",e.JsTreeEditRegisterUnsuccessfully="Não foi possivel editar registo, verificar se existem registos com o mesmo nome no mesmo ramo",e.JsTreeDeleteRootRegisterUnsuccessfully="Não é possivel apagar registo de raíz",e.GetListUnsuccessfully="Erro a obter dados para gerar a lista de registos",e.GetDataToCreateUnsuccessfully="Erro a obter dados para criar registo",e.CreateRegisterSuccessfully="Registo criado com sucesso",e.CreateRegisterUnsuccessfully="Erro a criar registo",e.GetDataToEditUnsuccessfully="Erro a obter dados para editar registo",e.EditRegisterSuccessfully="Registo editado com sucesso",e.EditRegisterUnsuccessfully="Erro a editado registo",e.DeleteRegisterSuccessfully="Registo eliminado com sucesso",e.DeleteRegisterUnsuccessfully="Erro a eliminar registo",e.DeleteRegisterUnsuccessfullyFK="Erro a eliminar registo, verificar se o registo está a ser utilizado por outros registos",e.RequestPasswordResetSuccessfully="Pedido de redefinição de password enviado",e.RequestPasswordResetUnsuccessfully="Erro ao efectuar pedido de redefinição de password",e.RequestPasswordResetUnsuccessfullyFK="Erro ao efectuar pedido de redefinição de password, verificar se o registo está a ser utilizado por outros registos"}(i||(i={}))},function(e,t,s){"use strict";s.r(t),s.d(t,"ConsultantInformationType",(function(){return a})),s.d(t,"ConsultantsService",(function(){return r}));var a,i=s(0);!function(e){e.Documents="/Consultants/GetConsultantDocuments",e.History="/Consultants/GetConsultantHistoric",e.Profile="/Consultants/ConsultantProfile",e.Timesheet="/Consultants/GetConsultantTimesheets"}(a||(a={}));class r extends i.BaseService{constructor(){super(),this._getCreate="/Consultants/Create",this._getConsultants="/Consultants/GetConsultants",this._getConsultantEmail="/Consultants/GetConsultantEmail",this._getNewHistoric="/Consultants/GetNewHistoric",this._saveConsultant="/Consultants/SaveConsultant",this._saveConsultantImage="/Consultants/SaveConsultanImage",this._saveConsultantDocuments="/Consultants/SaveConsultantDocuments",this._deleteConsultants="/Consultants/DeleteConsultants",this._deleteDocument="/Consultants/DeleteConsultantDocument",this._sendTokenToEmail="/Consultants/SendTokenToEmail",this._updateConsultantToken="/Consultants/UpdateConsultantToken",this._validateConsultantToken="/Consultants/ValidateConsultantToken",this._sendEmail="/Consultants/SendEmail",this._validateConsultant="/Consultants/ValidateConsultant"}SendEmail(e,t,s,...a){return this.request({url:this._sendEmail,type:i.HTMLVerbs.POST,dataType:i.DataTypes.HTML,data:{mails:e,subject:t,message:s}},a)}GetConsultants(e,...t){return this.request({url:this._getConsultants,type:i.HTMLVerbs.POST,dataType:i.DataTypes.JSON,data:{filter:e}},t)}GetCreate(...e){return this.request({url:this._getCreate,type:i.HTMLVerbs.GET,dataType:i.DataTypes.HTML},e)}GetConsultantInformation(e,t,...s){return this.request({url:e.toString(),type:i.HTMLVerbs.POST,dataType:i.DataTypes.HTML,data:{consultantId:t}},s)}SaveConsultant(e,...t){return this.request({url:this._saveConsultant,type:i.HTMLVerbs.POST,dataType:i.DataTypes.JSON,data:{consultantProfile:e}},t)}SaveConsultantImage(e,t,...s){var a=new FormData;return null!=t&&a.append("UploadedImage",t),a.append("ConsultantId",e.toString()),this.request({type:i.HTMLVerbs.POST,url:this._saveConsultantImage,contentType:!1,processData:!1,data:a},s)}SaveConsultantDocuments(e,t,...s){var a=new FormData;if(null!=t)for(let e=0;e$("#datepicker"),$datepickerNextMonth:()=>$("#datepickerNextMonth"),$fileupload:()=>$("#fileupload"),$backwardIcon:()=>$(".back-wrapper"),$scheduleMoreUsersCount:()=>$(".more-shared-users-count"),$scheduleMoreUsers:()=>$(".more-shared-users"),$alertsBtn:()=>$(".dropdown.alerts"),$alertsContainer:()=>$(".dropdown-menu.alerts"),$countAlerts:()=>$(".alerts .count-info .label"),$reference:()=>$("span.reference"),$scheduleAlerts:()=>$(".dropdown.schedules"),$favouritesBtn:()=>$(".dropdown.favourites"),$countFavourites:()=>$(".favourites .count-info .label"),serviceWorker:"/service-worker-notifications",isSubscribed:!1,$pushButton:()=>$(".push-btn"),timeoutTime:1e4,$logOutBtn:()=>$(".user-login-container"),$toggleListFilters:()=>$("#listFilter"),$listFilter:()=>$(".list-selected-filters"),$addPopup:()=>$("#addPopup"),$pauseBtn:()=>$(".pauseBtn"),$stopBtn:()=>$(".stopBtn"),$stickyPause:()=>$(".timerContainer").find(".iconOptionTimer").find(".fas.fa-pause"),$stickyContinue:()=>$(".timerContainer").find(".iconOptionTimer").find(".fas.fa-play"),$stickyStop:()=>$(".timerContainer").find(".iconOptionTimer").find(".fas.fa-stop"),$stickyExpandModal:()=>$(".iconTimerWrapper").find(".fas.fa-stopwatch"),$stickyModal:()=>$(".modalContainer.stickyModal"),$stickyContainer:()=>$(".stickyTimerWrapper"),$optionsCounterWrapper:()=>$(".optionsCounterWrapper"),$confirmStart:()=>$(".modalWrapper:visible").find("#modal-content-confirm-start"),$timerWrapper:()=>$(".timerWrapper"),$timesheetTableWrapper:()=>$(".timesheetWrapper"),$totalLine:()=>$(".timesheetListWrapper.totalLine"),$totalWrapper:()=>$(".timesheetItemLine.totalWrapper"),$timesheetItemLine:()=>$(".timesheetItemLine"),$timesheetItemLineTotal:()=>$(".timesheetItemLine.total"),$timesheetLine:()=>$(".timesheetLine"),$hour:()=>$(".hour"),$minutes:()=>$(".minutes"),$modalContainer:()=>$(".modalContainer"),$addTaskModal:()=>$(".modalContainer.addTaskModal"),$stickyIconWrapper:()=>$(".sitckyIconWrapper"),$iconOptionTimer:()=>$(".timerContainer").find(".iconOptionTimer"),stickyActiveOption:()=>"activeOption"},this._siteLoginService=new r.LoginService,this._timesheetsService=new n.TimesheetsService}InitMenus(){this._navbar=new a.Navbar,this._navbar.Init(),this.IsUserAuth()&&(this.GetAlerts(!0),this.GetScheduleAlerts(!0),this.GetFavourites())}Init(){this.InitMenus(),this.BindEvents(),this.Datepicker(),this.Fileupload(),this.ValidatePermission(),this.ContinueTimer()}Load(){$(document).unbind("ajaxError").bind("ajaxError",(function(e,t,s,a){"401"==t.status&&(window.location.href="/Account/Login")})),this.Init()}BindEvents(){this.InitButtonEvents()}ContinueTimer(){var e=sessionStorage.getItem("timerSeconds");if(""!=e&&null!=e){if($(".timerWrapper").find("p").text(sessionStorage.getItem("timerSeconds")),clearInterval(Number(sessionStorage.getItem("timerId"))),"00:00:00"!=e){var t=setInterval((new c).Timer,1e3);sessionStorage.setItem("timerId",t.toString())}this._consts.$stickyContainer().show(),this._consts.$stickyPause().closest(".iconOptionTimer").addClass("activeOption"),this._consts.$stickyStop().closest(".iconOptionTimer").addClass("activeOption"),this._consts.$stickyContinue().closest(".iconOptionTimer").removeClass("activeOption")}}InitButtonEvents(){$(window).bind("beforeunload",(function(){var e=sessionStorage.getItem("timesheet");""!=e&&null!=e&&sessionStorage.setItem("timerSeconds",$(".timerWrapper").find("p").text())})),this._consts.$stickyPause().off().on("click",e=>{clearInterval(Number(sessionStorage.getItem("timerId"))),sessionStorage.setItem("timerId","0"),this._consts.$stickyPause().closest(".iconOptionTimer").removeClass("activeOption"),this._consts.$stickyContinue().closest(".iconOptionTimer").addClass("activeOption")}),this._consts.$stickyContinue().off().on("click",e=>{var t=setInterval(this.Timer,1e3);sessionStorage.setItem("timerId",t.toString()),this._consts.$stickyPause().closest(".iconOptionTimer").addClass("activeOption"),this._consts.$stickyContinue().closest(".iconOptionTimer").removeClass("activeOption")}),this.StartCounter_Click(),this._consts.$stickyStop().off().on("click",e=>{this.StopTimer()}),this._consts.$stickyExpandModal().off().on("click",e=>{this._consts.$stickyModal().css("display","flex").addClass("counterModal"),"00:00:00"!=$(".timerWrapper").find("p").text()?(this._consts.$optionsCounterWrapper().css("display","flex"),this._consts.$confirmStart().hide(),this._consts.$stickyContinue().closest(".iconOptionTimer").hasClass("activeOption")&&(this._consts.$pauseBtn().find("h3").text("Continuar"),this._consts.$pauseBtn().css("background-color","#359BB1"))):this._consts.$confirmStart().show(),this._consts.$stickyContainer().hide(),this.StartCounter_Click()}),this._consts.$scheduleAlerts().on("shown.bs.dropdown",e=>{this.AskPermission()}),this._consts.$logOutBtn().on("click",()=>{sessionStorage.clear()}),$(".schedules a, .alerts a, .favourites a").unbind("click").on("click",e=>{$(".schedules a, .alerts a, .favourites a").not($(e.currentTarget)).closest("li").find("ul").hide(),$(e.currentTarget).closest("li").find("ul").toggle()}),$(document).on("mouseup",e=>{let t=$(e.target),s=this._consts.$alertsBtn(),a=this._consts.$scheduleAlerts(),i=this._consts.$favouritesBtn(),r=this._consts.$toggleListFilters(),n=this._consts.$listFilter(),o=$(".toggle-more"),l=$(".open-list-skills"),c=this._consts.$addPopup().find(".popup-wrapper"),d=this._consts.$addPopup().find(".cancel-candidates-selection"),u=this._consts.$scheduleMoreUsersCount();s.is(t)||0!==s.has(t).length||a.is(t)||0!==a.has(t).length||i.is(t)||0!==i.has(t).length||n.is(t)||0!==n.has(t).length||r.is(t)||0!==r.has(t).length||o.is(t)||0!==o.has(t).length||l.is(t)||0!==l.has(t).length||d.is(t)||0!==d.has(t).length||c.is(t)||0!==c.has(t).length||u.is(t)||0!==u.has(t).length||($(".dropdown-menu").hide(),this._consts.$listFilter().hide(),l.hide(),this._consts.$scheduleMoreUsers().hide(),this._consts.$addPopup().hide())})}Datepicker(){this._consts.$datepicker().datepicker(),this._consts.$datepickerNextMonth().datepicker({defaultDate:"+1m"}),$.datepicker.setDefaults($.datepicker.regional.pt)}GetParameterByName(e){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var t=new RegExp("[\\?&]"+e+"=([^]*)").exec(location.search);return null===t?"":decodeURIComponent(t[1].replace(/\+/g," "))}StartCounter_Click(){this._consts.$confirmStart().off().on("click",e=>{this._consts.$optionsCounterWrapper().css("display","flex"),this._consts.$confirmStart().hide();var t=setInterval(this.Timer,1e3);sessionStorage.setItem("timerId",t.toString()),this._consts.$stickyPause().closest(".iconOptionTimer").addClass("activeOption"),this._consts.$stickyStop().closest(".iconOptionTimer").addClass("activeOption"),this._consts.$stickyContinue().closest(".iconOptionTimer").removeClass("activeOption")})}Fileupload(){this._consts.$fileupload().fileupload({dataType:"json",done:function(e,t){$.each(t.result.files,(function(e,t){$("
").text(t.name).appendTo(document.body)}))}})}UrlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),s=window.atob(t),a=new Uint8Array(s.length);for(let e=0;e(this.ValidatePermission(),e))}ValidatePermission(){}SubscribeUserToPush(){this.IsUserAuth()&&this._siteLoginService.GetNotificationPublicKey({success:e=>navigator.serviceWorker.register("/Scripts/TS/Services/service-worker-notifications.js").then(t=>t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this.UrlBase64ToUint8Array(e)})).then(e=>{let t=JSON.parse(JSON.stringify(e));return this._siteLoginService.AddUserNotification(t.keys.auth,JSON.stringify(e),{success:e=>{}}),e})})}UnSubscribeUserToPush(){this.IsUserAuth()&&this._siteLoginService.AddUserNotification(null,null,{success:e=>{}})}Timer(){var e=$(".timerWrapper").find("p").text(),t=Number(e.split(":")[0]),s=Number(e.split(":")[1]),a=Number(e.split(":")[2]);60==(a+=1)&&(s+=1,a=0),60==s&&(t+=1,s=0),$(".timerWrapper").attr("data-seconds",a),$(".timerWrapper").find("h1").text(("0"+t).slice(-2)+":"+("0"+s).slice(-2)+":"+("0"+a).slice(-2)),$(".timerWrapper").find("p").text(("0"+t).slice(-2)+":"+("0"+s).slice(-2)+":"+("0"+a).slice(-2))}PauseTimer(){if("Pausa"==$(".pauseBtn:visible").find("h3").text())clearInterval(Number(sessionStorage.getItem("timerId"))),sessionStorage.setItem("timerId","0"),this._consts.$pauseBtn().find("h3").text("Continuar"),this._consts.$pauseBtn().css("background-color","#359BB1");else{var e=setInterval(this.Timer,1e3);sessionStorage.setItem("timerId",e.toString()),this._consts.$pauseBtn().find("h3").text("Pausa"),this._consts.$pauseBtn().css("background-color","#C4C4C4")}}StopTimer(){this.SaveTimesheetChronometer(),this._consts.$stickyContainer().hide()}SaveTimesheetChronometer(){var e=this._consts.$timerWrapper().find("p").text(),t=Number(e.split(":")[0]),s=Number(e.split(":")[1]),a=Number(e.split(":")[2])+60*s+3600*t,r=JSON.parse(sessionStorage.getItem("timesheet"));r.TimeSeconds=a,r.Date=(new Date).toISOString(),clearInterval(Number(sessionStorage.getItem("timerId"))),sessionStorage.removeItem("timerId"),sessionStorage.removeItem("timerSeconds"),sessionStorage.removeItem("timesheet"),this._timesheetsService.SaveTimesheets(r,!0,{success:e=>{this.CancelModal(),this.ToggleAlert(i.AlertType.Success,"Timesheet guardada com sucesso"),$(".timesheetWrapper").length>0&&(new l.TimesheetIndex).GetTimesheets(new Date)},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao guardar a timesheet")},complete:()=>{}})}CancelModal(){this._consts.$modalContainer().css("display","none"),this._consts.$addTaskModal().attr("data-timesheet-id",""),this._consts.$optionsCounterWrapper().css("display","NONE"),this._consts.$confirmStart().show(),this._consts.$timerWrapper().find("h1").text("00:00:00"),this._consts.$timerWrapper().find("p").text("00:00:00"),this._consts.$timerWrapper().attr("data-seconds",0),this._consts.$pauseBtn().find("h3").text("Pausa"),this._consts.$stickyPause().closest(this._consts.$iconOptionTimer()).removeClass(this._consts.stickyActiveOption),this._consts.$stickyStop().closest(this._consts.$iconOptionTimer()).removeClass(this._consts.stickyActiveOption),this._consts.$stickyContinue().closest(this._consts.$iconOptionTimer()).removeClass(this._consts.stickyActiveOption),clearInterval(Number(sessionStorage.getItem("timerId"))),sessionStorage.removeItem("timerId"),sessionStorage.removeItem("timerSeconds"),sessionStorage.removeItem("timesheet"),this._consts.$stickyContainer().hide()}GetTimesheets(e){let t=new o.Timesheets({BeginDate:e.toLocaleDateString()});this._timesheetsService.GetTimesheets(t,{success:e=>{this._consts.$timesheetTableWrapper().html(e),this.InitButtonEvents(),this.CalculateRowColTotal()},complete:()=>{}})}CalculateRowColTotal(){var e=this._consts.$totalLine().find(this._consts.$timesheetItemLine().not(".biggerItem")).map(e=>0).toArray();$.each(this._consts.$timesheetLine(),(t,s)=>{var a=0;$.each($(s).find(this._consts.$timesheetItemLine().not(".biggerItem").not(".total")),(t,s)=>{var i=60*Number($(s).find(this._consts.$hour()).val())*60+60*Number($(s).find(this._consts.$minutes()).val());a+=i,e[t]+=i}),$(s).find(this._consts.$timesheetItemLineTotal()).find(this._consts.$hour()).val(("0"+a/3600).toString().split(".")[0].slice(-2)),$(s).find(this._consts.$timesheetItemLineTotal()).find(this._consts.$minutes()).val(("0"+a%3600/60).toString().slice(-2))}),$.each(this._consts.$totalLine().find(this._consts.$timesheetItemLine().not(".biggerItem").not(".totalWrapper")),(t,s)=>{$(s).find(this._consts.$hour()).val(("0"+e[t]/3600).toString().split(".")[0].slice(-2)),$(s).find(this._consts.$minutes()).val(("0"+e[t]%3600/60).toString().slice(-2))});let t=this._consts.$totalLine().find(this._consts.$totalWrapper());var s=e.reduce((e,t)=>e+t,0);t.find(this._consts.$hour()).val(("0"+s/3600).toString().split(".")[0].slice(-2)),t.find(this._consts.$minutes()).val(("0"+s%3600/60).toString().slice(-2))}}$(()=>{(new c).Load()})},,,function(e,t,s){"use strict";s.r(t),s.d(t,"TimesheetsService",(function(){return i}));var a=s(0);class i extends a.BaseService{constructor(){super()}GetTimesheets(e,...t){return this.request({url:"/Timesheet/GetTimesheets",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{filter:e}},t)}SaveTimesheets(e,t,...s){return this.request({url:"/Timesheet/SaveTimesheets",type:a.HTMLVerbs.POST,dataType:a.DataTypes.JSON,data:{timesheet:e,incrementTime:t}},s)}DeleteTimesheets(e,...t){return this.request({url:"/Timesheet/DeleteTimesheets",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{timesheetIds:e}},t)}DuplicateTimesheets(e,...t){return this.request({url:"/Timesheet/DuplicateTimesheets",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{timesheets:e}},t)}EditTimesheets(e,...t){return this.request({url:"/Timesheet/EditTimesheets",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{timesheets:e}},t)}GetClientsById(e,...t){return this.request({url:"/Timesheet/GetClientsById",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{clientId:e}},t)}GetProductsById(e,...t){return this.request({url:"/Timesheet/GetProductsById",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{productId:e}},t)}GetProjectsById(e,...t){return this.request({url:"/Timesheet/GetProjectsById",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{projectId:e}},t)}ValidateTimesheets(e,...t){return this.request({url:"/Timesheet/ValidateTimesheets",type:a.HTMLVerbs.POST,dataType:a.DataTypes.HTML,data:{timesheet:e}},t)}GetTimesheetsHoursForCurrentYear(...e){return this.request({url:"/Timesheet/GetTimesheetsHoursForCurrentYear",type:a.HTMLVerbs.GET},e)}ValidateCreatePermissions(...e){return this.request({url:"/Timesheet/ValidateCreatePermissions",type:a.HTMLVerbs.POST,dataType:a.DataTypes.JSON,data:{}},e)}ValidateDeletePermissions(...e){return this.request({url:"/Timesheet/ValidateDeletePermissions",type:a.HTMLVerbs.POST,dataType:a.DataTypes.JSON,data:{}},e)}ValidateOpenPermissions(...e){return this.request({url:"/Timesheet/ValidateOpenPermissions",type:a.HTMLVerbs.POST,dataType:a.DataTypes.JSON,data:{}},e)}}},,,function(e,t,s){"use strict";s.r(t),s.d(t,"LoginService",(function(){return i}));var a=s(0);class i extends a.BaseService{constructor(){super()}SendRequestResetPassword(e,...t){return this.request({url:"/Account/RequestResetPassword",type:a.HTMLVerbs.POST,dataType:a.DataTypes.JSON,data:{email:e}},t)}AddUserNotification(e,t,...s){return this.request({url:"/Account/AddUserNotification",type:a.HTMLVerbs.POST,dataType:a.DataTypes.JSON,data:{notificationAuth:e,notificationJson:t}},s)}GetNotificationPublicKey(...e){return this.request({url:"/Account/GetNotificationPublicKey",type:a.HTMLVerbs.POST,dataType:a.DataTypes.JSON},e)}}},,function(e,t,s){"use strict";s.r(t),s.d(t,"Navbar",(function(){return i}));var a=s(1);class i extends a.BaseViewTemplate{constructor(){super(),this._consts={$navLabel:()=>$(".nav-label"),$nav:()=>$(".nav-menu"),$minimizeButton:()=>$("#minimalize-btn"),$page:()=>$(".wrapper"),body:()=>$("body")},this.ToggleMenu=()=>{this._consts.$nav().hasClass("closed")?this.NavMaxStyle():this.NavMinStyle()},this.Minimize_Click=()=>{"Closed"!=localStorage.getItem("NavBar")||this._consts.$nav().hasClass("closed")?""==localStorage.getItem("NavBar")&&this._consts.$nav().hasClass("closed")&&this.NavMaxStyle():this.NavMinStyle(),this._consts.$minimizeButton().off().on("click",e=>{this.ToggleMenu()})}}Init(){this.BindEvents(),""==localStorage.getItem("NavBar")&&this._consts.$nav().hasClass("closed")?this.NavMinStyle():this.NavMaxStyle(),this._consts.body().show()}Load(){}BindEvents(){this.Minimize_Click(),this.Menu_Click(),this.ToggleSubMenu()}ToggleSubMenu(){this._consts.$nav().find(".nav-item.withSubmenu").find(".dropDonwBtn").off().on("click",e=>{e.preventDefault(),e.stopPropagation();let t=$(e.currentTarget),s=t.closest(".nav-item");s.hasClass("collapsedSubmenu")?(s.removeClass("collapsedSubmenu"),s.addClass("expandedSubmenu"),this._consts.$nav().find(`.subNavWrapper[data-sub-menu="${t.attr("data-sub-menu")}"]`).show()):s.hasClass("expandedSubmenu")&&(s.removeClass("expandedSubmenu"),s.addClass("collapsedSubmenu"),this._consts.$nav().find(`.subNavWrapper[data-sub-menu="${t.attr("data-sub-menu")}"]`).hide())})}Menu_Click(){this._consts.$nav().find(".nav-item").off().on("click",e=>{this._consts.$nav().find(".nav-item").removeClass("activeItem"),$(e.currentTarget).addClass("activeItem")})}NavMinStyle(){this._consts.$nav().addClass("closed"),this._consts.$page().css({"margin-left":"65px"}),this._consts.$nav().find(".fa-angle-left").switchClass("fa-angle-left","fa-angle-right"),localStorage.setItem("NavBar","Closed")}NavMaxStyle(){this._consts.$nav().removeClass("closed"),this._consts.$page().css({"margin-left":"150px"}),this._consts.$nav().find(".fa-angle-right").switchClass("fa-angle-right","fa-angle-left"),localStorage.setItem("NavBar","")}}},function(e,t,s){"use strict";s.r(t),s.d(t,"TimesheetIndex",(function(){return c}));var a=s(2),i=s(1),r=s(4),n=s(14),o=s(10),l=s(11);class c extends i.BaseViewTemplate{constructor(){super(),this._timesheetsService=null,this._consts={$timesheetViewWrapper:()=>$(".timesheetViewWrapper"),$timesheetWrapper:()=>$(".timesheetWrapper"),$timesheetTableWrapper:()=>$(".timesheetTableWrapper"),$selectWeekBtn:()=>$(".selectWeekBtn"),$selectLastWeekWithDataBtn:()=>$(".last-week-with-data"),$collapseBtn:()=>$(".collapseBtn").find(".iconWrapper"),$timesheetLine:()=>$(".timesheetLine"),$checkboxContainer:()=>$(".checkboxWrapper").find(".container").find("input:checkbox"),$duplicateBtn:()=>$(".optionBtnWrapper.duplicate"),$chronometerBtn:()=>$(".optionBtnWrapper.chronometer"),$hour:()=>$(".timesheetListWrapper .hour"),$minutes:()=>$(".timesheetListWrapper .minutes"),$infoWrapper:()=>$(".infoWrapper"),$timesheetItemLine:()=>$(".timesheetItemLine"),$timesheetItemLineTotal:()=>$(".timesheetItemLine.total"),$deleteBtn:()=>$(".iconBtnWrapper").find(".fas.fa-trash"),$editBtn:()=>$(".iconBtnWrapper").find(".fas.fa-pen"),$duplicateBtnHover:()=>$(".iconBtnWrapper").find(".fas.fa-copy"),$totalLine:()=>$(".timesheetListWrapper.totalLine"),$totalWrapper:()=>$(".timesheetItemLine.totalWrapper"),$timesheetList:()=>$(".timesheeList"),$observations:()=>$('input[name="observations"]:visible'),$clientsSelect:()=>$('select[name="clients"]'),$productsSelect:()=>$('select[name="products"]'),$projectsSelect:()=>$('select[name="projects"]'),$tasksSelect:()=>$('select[name="tasks"]'),$modalContainer:()=>$(".modalContainer"),$closeModalBtn:()=>$(".timesheetViewWrapper, .stickyTimerWrapper").nextAll().find(".close-btn-container"),$manuallyModalBtn:()=>$(".optionAddBtn.manually"),$chronometerModalBtn:()=>$(".optionAddBtn.chronometer"),$confirmChronometer:()=>$("#modal-content-confirm-chronometer"),$confirmStart:()=>$("#modal-content-confirm-start"),$pauseBtn:()=>$(".pauseBtn"),$stopBtn:()=>$(".stopBtn"),$saveTaskBtn:()=>$("#modal-content-confirm-task"),$duplicateTaskBtn:()=>$("#modal-content-confirm-duplicate"),$closeCounterModel:()=>$(".modalContainer.timerModal.counterModal").find(".close-wrapper"),$addTaskModal:()=>$(".modalContainer.addTaskModal"),$duplicateTaskModal:()=>$(".modalContainer.duplicateTaskModal"),$timerModal:()=>$(".modalContainer.timerModal:not(.counterModal)"),$counterModal:()=>$(".modalContainer.timerModal.counterModal"),$optionsCounterWrapper:()=>$(".optionsCounterWrapper"),$timerWrapper:()=>$(".timerWrapper"),$stickyContainer:()=>$(".stickyTimerWrapper"),$stickyIconWrapper:()=>$(".sitckyIconWrapper"),$iconOptionTimer:()=>$(".timerContainer").find(".iconOptionTimer"),$stickyPause:()=>$(".timerContainer").find(".iconOptionTimer").find(".fas.fa-pause"),$stickyStop:()=>$(".timerContainer").find(".iconOptionTimer").find(".fas.fa-stop"),$stickyContinue:()=>$(".timerContainer").find(".iconOptionTimer").find(".fas.fa-play"),expandedLineClass:()=>"expandedLine",enabledBtnClass:()=>"enabledBtn",counterModal:()=>"counterModal",stickyActiveOption:()=>"activeOption",$datepicker:()=>$("#datepicker"),$backwardIcon:()=>$(".back-wrapper")},this.DeleteTimesheet=(e,t)=>{var s=$(t).find(e._consts.$timesheetItemLine()).map((function(e,t){if(""!=$(t).attr("data-timesheet-id"))return $(t).attr("data-timesheet-id")})).get().join(",").trim();e._timesheetsService.DeleteTimesheets(s,{success:e=>{this.ToggleAlert(i.AlertType.Success,"Timesheet eliminada com sucesso");let t=new Date(this._consts.$timesheetTableWrapper().attr("data-begin-date"));this.GetTimesheets(t),this.GetTimesheetsHours()},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao eliminar a timesheet")},complete:()=>{}})},this._timesheetsService=new n.TimesheetsService}Load(){this.Init()}Init(){if(this.InitSelects(),this.InitButtonEvents(),this.ClearStorage(),this.CloseNavBar(),this.ValidateOpenEdit(),this.PageTitle("Timesheets"),this.Tooltip(),this.TranslateCalendar(),this._consts.$backwardIcon().off().on("click",()=>{this.Back()}),this.IsUserAuth()&&this._consts.$timesheetViewWrapper()&&this._consts.$timesheetViewWrapper().attr("data-begin-date"))try{let e=new Date(this._consts.$timesheetViewWrapper().attr("data-begin-date"));this.GetTimesheets(e)}catch(e){}(new l.Site).ContinueTimer()}InitButtonEvents(){this._consts.$selectWeekBtn().off().on("click",e=>{let t=new Date(this._consts.$timesheetTableWrapper().attr("data-begin-date"));$(e.currentTarget).hasClass("previousWeek")?t.setDate(t.getDate()-7):t.setDate(t.getDate()+7),this._consts.$timesheetTableWrapper().attr("data-begin-date",t.getMonth()+1+"/"+t.getDate()+"/"+t.getFullYear()),this._consts.$timesheetTableWrapper().attr("data-end-date",t.getMonth()+1+"/"+(t.getDate()+6)+"/"+t.getFullYear()),this.GetTimesheets(t)}),this._consts.$selectLastWeekWithDataBtn().off().on("click",e=>{let t=new Date($(e.currentTarget).attr("data-last-week"));null!=t&&(t.setDate(t.getDate()-(t.getDay()+6)%7),this._consts.$timesheetTableWrapper().attr("data-begin-date",t.getMonth()+1+"/"+t.getDate()+"/"+t.getFullYear()),this._consts.$timesheetTableWrapper().attr("data-end-date",t.getMonth()+1+"/"+(t.getDate()+6)+"/"+t.getFullYear()),this.GetTimesheets(t))}),this._consts.$manuallyModalBtn().off().on("click",e=>{this._timesheetsService.ValidateCreatePermissions({success:e=>{0==e.IsOperationSuccessful?this.ToggleAlert(1,"Não tem permissões"):(this._consts.$addTaskModal().css("display","flex"),$(".timesheetTittle").text("Adicionar Timesheet"),this._consts.$clientsSelect().val(null).trigger("change"),this._consts.$productsSelect().val(null).trigger("change"),this._consts.$projectsSelect().val(null).trigger("change"),this._consts.$tasksSelect().val(null).trigger("change"),this._consts.$observations().val(null))}})}),this._consts.$chronometerModalBtn().off().on("click",e=>{this._timesheetsService.ValidateCreatePermissions({success:e=>{0==e.IsOperationSuccessful?this.ToggleAlert(1,"Não tem permissões"):0!=Number($(".timerWrapper").attr("data-seconds"))?(this._consts.$counterModal().css("display","flex"),this._consts.$optionsCounterWrapper().css("display","flex"),this._consts.$stickyContinue().closest(this._consts.$iconOptionTimer()).hasClass(this._consts.stickyActiveOption())&&(this._consts.$pauseBtn().find("h3").text("Continuar"),this._consts.$pauseBtn().css("background-color","#359BB1"))):(this._consts.$timerModal().css("display","flex"),this._consts.$clientsSelect().val(null).trigger("change"),this._consts.$productsSelect().val(null).trigger("change"),this._consts.$projectsSelect().val(null).trigger("change"),this._consts.$tasksSelect().val(null).trigger("change"),this._consts.$observations().val(null))}})}),this._consts.$confirmChronometer().off().on("click",e=>{let t=this.GetFormValues();t.Chronometer=!0,this._timesheetsService.ValidateTimesheets(t,{success:e=>{-1==e?this.ToggleAlert(i.AlertType.Warning,"Já existe a timesheet para esta semana"):-2==e?this.ToggleAlert(i.AlertType.Warning,"Tem de preencher pelo menos um dos campos: Cliente, Produto, Projeto ou Tarefa"):(this._consts.$timerModal().css("display","none"),this._consts.$counterModal().css("display","flex"),sessionStorage.setItem("timesheet",JSON.stringify(t)))},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao validar a timesheet")},complete:()=>{}})}),this._consts.$confirmStart().off().on("click",e=>{this._consts.$optionsCounterWrapper().css("display","flex"),this._consts.$confirmStart().hide();var t=setInterval((new l.Site).Timer,1e3);sessionStorage.setItem("timerId",t.toString()),this._consts.$stickyPause().closest(this._consts.$iconOptionTimer()).addClass(this._consts.stickyActiveOption),this._consts.$stickyStop().closest(this._consts.$iconOptionTimer()).addClass(this._consts.stickyActiveOption)}),this._consts.$closeModalBtn().off().on("click",e=>{this.CancelModal()}),this._consts.$collapseBtn().off().on("click",e=>{$(e.currentTarget).closest(this._consts.$timesheetLine()).toggleClass(this._consts.expandedLineClass())}),this._consts.$checkboxContainer().off().on("change",e=>{this._consts.$checkboxContainer().filter(":checked").length>0?(this._consts.$duplicateBtn().addClass(this._consts.enabledBtnClass()),1==this._consts.$checkboxContainer().filter(":checked").length&&0==Number($(".timerWrapper").attr("data-seconds"))?this._consts.$chronometerBtn().addClass(this._consts.enabledBtnClass()):this._consts.$chronometerBtn().removeClass(this._consts.enabledBtnClass())):(this._consts.$duplicateBtn().removeClass(this._consts.enabledBtnClass()),this._consts.$chronometerBtn().removeClass(this._consts.enabledBtnClass()))}),this._consts.$pauseBtn().off().on("click",e=>{(new l.Site).PauseTimer()}),this._consts.$stopBtn().off().on("click",e=>{(new l.Site).StopTimer()}),this._consts.$stickyIconWrapper().off().on("click",e=>{this._consts.$modalContainer().css("display","none"),this._consts.$stickyContainer().show()}),this._consts.$hour().off().on("focus",e=>{let t=parseInt($(e.currentTarget).val().toString());t>0?$(e.currentTarget).val(t):$(e.currentTarget).val("")}).on("keydown",e=>{if(Number($(e.currentTarget).val().toString().length)>1&&"Backspace"!==e.key&&"Delete"!==e.key)return!1}).on("change",e=>{this.SaveTimesheetDay(e),$(e.currentTarget).val($(e.currentTarget).val().toString().padStart(2,"0"))}),this._consts.$minutes().off().on("focus",e=>{let t=parseInt($(e.currentTarget).val().toString());t>0?$(e.currentTarget).val(t):$(e.currentTarget).val("")}).on("keydown",e=>{if(Number($(e.currentTarget).val().toString().length)>1&&"Backspace"!==e.key&&"Delete"!==e.key)return!1}).on("change",e=>{this.SaveTimesheetDay(e),$(e.currentTarget).val($(e.currentTarget).val().toString().padStart(2,"0"))}),this._consts.$saveTaskBtn().off().on("click",e=>{if(""!=this._consts.$addTaskModal().attr("data-timesheet-id"))this.EditTimesheet();else if(this.ValidateRequiredFields()){let e=this.GetFormValues();this._timesheetsService.ValidateTimesheets(e,{success:t=>{-1==t?this.ToggleAlert(i.AlertType.Warning,"Já existe a timesheet para esta semana"):-2==t?this.ToggleAlert(i.AlertType.Warning,"Tem de preencher pelo menos um dos campos: Cliente, Produto, Projeto ou Tarefa"):(this.ToggleLoading(),this._timesheetsService.SaveTimesheets(e,!1,{success:e=>{if(1==e.IsManual)this.ToggleAlert(i.AlertType.Warning,"Já existe uma timesheet com os dados inseridos");else if(1==e.IsOperationSuccessful&&0!=e.ObjectResult){this.ToggleAlert(i.AlertType.Success,"Timesheet guardada com sucesso"),this._consts.$addTaskModal().css("display","none");let e=new Date(this._consts.$timesheetTableWrapper().attr("data-current-date"));this.GetTimesheets(e),this.GetTimesheetsHours()}else this.ToggleAlert(i.AlertType.Error,e.Message)},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao guardar a timesheet")},complete:()=>{this.ToggleLoading()}}))},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao validar a timesheet")},complete:()=>{}})}else this.ToggleAlert(i.AlertType.Warning,"Por favor, valide os campos obrigatórios")}),this._consts.$editBtn().off().on("click",e=>{this._timesheetsService.ValidateCreatePermissions({success:t=>{if(0==t.IsOperationSuccessful)this.ToggleAlert(1,"Não tem permissões");else{let t=$(e.currentTarget).closest(".timesheetLine");var s=t.find(this._consts.$timesheetItemLine()).map((function(e,t){if(""!=$(t).attr("data-timesheet-id"))return $(t).attr("data-timesheet-id")})).get().join(",").trim();this._consts.$addTaskModal().css("display","flex"),$(".timesheetTittle").text("Editar Timesheet"),this._consts.$addTaskModal().attr("data-timesheet-id",s);let n=t.find(this._consts.$infoWrapper());var i=[],r={id:n.attr("data-client-id"),text:n.find(".client").text()};i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$clientsSelect(),i),i=[],r={id:n.attr("data-product-id"),text:n.find(".product").text()},i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$productsSelect(),i),i=[],r={id:n.attr("data-project-id"),text:n.find(".project").text()},i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$projectsSelect(),i),i=[],r={id:n.attr("data-task-id"),text:n.find(".task").text().split(" - ")[0]},i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$tasksSelect(),i),this._consts.$observations().val(n.attr("data-observations"))}}})}),this._consts.$deleteBtn().off().on("click",e=>{this._timesheetsService.ValidateDeletePermissions({success:t=>{if(0==t.IsOperationSuccessful)this.ToggleAlert(1,"Não tem permissões");else{let t=$(e.currentTarget).closest(this._consts.$timesheetLine());r.ModalHelper.ConfirmationDialog("Tem a certeza que pretende eliminar a timesheet?","","Eliminar",this.DeleteTimesheet,this,t)}}})}),this._consts.$duplicateBtnHover().off().on("click",e=>{this._timesheetsService.ValidateCreatePermissions({success:t=>{if(0==t.IsOperationSuccessful)this.ToggleAlert(1,"Não tem permissões");else{let t=$(e.currentTarget).closest(".timesheetLine");var s=t.find(this._consts.$timesheetItemLine()).map((function(e,t){if(""!=$(t).attr("data-timesheet-id"))return $(t).attr("data-timesheet-id")})).get().join(",").trim();this._consts.$duplicateTaskModal().css("display","flex"),this._consts.$duplicateTaskModal().attr("data-timesheet-id",s);let n=t.find(this._consts.$infoWrapper());var i=[],r={id:n.attr("data-client-id"),text:n.find(".client").text()};i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$clientsSelect(),i),i=[],r={id:n.attr("data-product-id"),text:n.find(".product").text()},i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$productsSelect(),i),i=[],r={id:n.attr("data-project-id"),text:n.find(".project").text()},i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$projectsSelect(),i),i=[],r={id:n.attr("data-task-id"),text:n.find(".task").text()},i.push(r),a.Select2Helper.SetSelectedOptions(this._consts.$tasksSelect(),i)}}})}),this._consts.$duplicateTaskBtn().off().on("click",e=>{var t=[],s=this._consts.$duplicateTaskModal().attr("data-timesheet-id").split(",");$.each(s,(e,s)=>{let a=this._consts.$timesheetLine().find(`.timesheetItemLine[data-timesheet-id='${s}']`);var i=60*Number(a.find(this._consts.$hour()).val())*60+60*Number(a.find(this._consts.$minutes()).val());let r=this.GetFormValues();r.Id=null,r.Date=a.attr("data-timesheet-day"),r.TimeSeconds=i,t.push(r)}),t.length>0&&this._timesheetsService.DuplicateTimesheets(t,{success:e=>{if(-1==e)this.ToggleAlert(i.AlertType.Warning,"Já existe a timesheet para esta semana");else{this.CancelModal();let e=new Date(this._consts.$timesheetTableWrapper().attr("data-current-date"));this.GetTimesheets(e),this.GetTimesheetsHours(),this.ToggleAlert(i.AlertType.Success,"Timesheet duplicada com sucesso")}},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao duplicar a timesheet")},complete:()=>{}})}),this._consts.$duplicateBtn().off().on("click",e=>{$(e.currentTarget).hasClass(this._consts.enabledBtnClass())&&this._timesheetsService.ValidateCreatePermissions({success:e=>{if(0==e.IsOperationSuccessful)this.ToggleAlert(1,"Não tem permissões");else{var t=[];$.each(this._consts.$timesheetLine(),(e,s)=>{$(s).find("input:checkbox:checked").length>0&&$.each($(s).find(this._consts.$timesheetItemLine().not(".biggerItem").not(".total")),(e,s)=>{if(""!=$(s).attr("data-timesheet-id")){var a=this.GetDuplicateTimesheet($(s)),i=new Date(Number(a.Date.split("/")[2]),Number(a.Date.split("/")[1])-1,Number(a.Date.split("/")[0]),12);i.setDate(i.getDate()+7),a.Date=i.toISOString(),t.push(a)}})}),t.length>0&&this._timesheetsService.DuplicateTimesheets(t,{success:e=>{if(-1==e)this.ToggleAlert(i.AlertType.Warning,"Já existe a timesheet para a semana seguinte");else{let e=new Date(this._consts.$timesheetTableWrapper().attr("data-begin-date"));e.setDate(e.getDate()+7),this.GetTimesheets(e),this.GetTimesheetsHours(),this.ToggleAlert(i.AlertType.Success,"Timesheet duplicada com sucesso")}},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao duplicar a timesheet")},complete:()=>{}})}}})}),this._consts.$chronometerBtn().off().on("click",e=>{$(e.currentTarget).hasClass(this._consts.enabledBtnClass())&&this._timesheetsService.ValidateCreatePermissions({success:e=>{if(0==e.IsOperationSuccessful)this.ToggleAlert(1,"Não tem permissões");else{let e=$(this._consts.$timesheetList).find("input:checkbox:checked").closest(this._consts.$timesheetLine()),s=e.find(this._consts.$infoWrapper());var t=new o.Timesheets({ClientId:0!=Number(s.attr("data-client-id"))?Number(s.attr("data-client-id")):null,ProductId:0!=Number(s.attr("data-product-id"))?Number(s.attr("data-product-id")):null,ProjectId:0!=Number(s.attr("data-project-id"))?Number(s.attr("data-project-id")):null,TaskId:0!=Number(s.attr("data-task-id"))?Number(s.attr("data-task-id")):null,Date:(new Date).toISOString()});e.find(this._consts.$timesheetItemLine().not(".biggerItem").not(".total")).map((function(e,s){""!=$(s).attr("data-timesheet-id")&&$(s).attr("data-timesheet-day")==(new Date).getDate()+"/"+((new Date).getMonth()+1).toString().padStart(2,"0")+"/"+(new Date).getFullYear()&&(t.Id=Number($(s).attr("data-timesheet-id")))})),this._consts.$timerModal().css("display","none"),this._consts.$counterModal().css("display","flex"),sessionStorage.setItem("timesheet",JSON.stringify(t))}}})}),this._consts.$datepicker().datepicker("option","firstDay",1),this._consts.$datepicker().datepicker({dateFormat:"yy-mm-dd"}),this._consts.$datepicker().off().on("change",()=>{this.GetTimesheets(new Date(this._consts.$datepicker().val()))}),this._consts.$clientsSelect().unbind("change.clients"),this._consts.$clientsSelect().bind("change.clients",e=>{a.Select2Helper.GetSelectedIdList($(e.target).select2("data")).length>0&&null!=$(e.target).select2("data")[0].parentId&&(a.Select2Helper.SetSelectedOptions($('select[name="products"]:visible'),[]),a.Select2Helper.SetSelectedOptions($('select[name="projects"]:visible'),[]),a.Select2Helper.SetSelectedOptions($('select[name="tasks"]:visible'),[]))}),this._consts.$productsSelect().unbind("change.products"),this._consts.$productsSelect().bind("change.products",e=>{if(a.Select2Helper.GetSelectedIdList($(e.target).select2("data")).length>0){let t=null;null!=$(e.target).select2("data")[0].parentId?(t=$(e.target).select2("data")[0].parentId,a.Select2Helper.SetSelectedOptions($('select[name="projects"]:visible'),[]),a.Select2Helper.SetSelectedOptions($('select[name="tasks"]:visible'),[])):"undefined"!=$(e.target).select2("data")[0].element.dataset.parentId&&(t=$(e.target).select2("data")[0].element.dataset.parentId),null!=t&&this._timesheetsService.GetClientsById(Number(t),{success:e=>{var t=$.parseJSON(e),s=[],i={id:t[0].id,text:t[0].text};s.push(i),a.Select2Helper.SetSelectedOptions($('select[name="clients"]:visible'),s)},error:e=>{this.ToggleAlert(i.AlertType.Error,"aasdas")},complete:()=>{}})}}),this._consts.$projectsSelect().unbind("change.projects"),this._consts.$projectsSelect().bind("change.projects",e=>{if(a.Select2Helper.GetSelectedIdList($(e.target).select2("data")).length>0){let t=null;null!=$(e.target).select2("data")[0].parentId?(t=$(e.target).select2("data")[0].parentId,a.Select2Helper.SetSelectedOptions($('select[name="tasks"]:visible'),[])):"undefined"!=$(e.target).select2("data")[0].element.dataset.parentId&&(t=$(e.target).select2("data")[0].element.dataset.parentId),null!=t&&this._timesheetsService.GetProductsById(Number(t),{success:e=>{var t=$.parseJSON(e),s=[],i={id:t[0].id,text:t[0].text};i.parentId=t[0].parentId,s.push(i),a.Select2Helper.SetSelectedOptions($('select[name="products"]:visible'),s)},complete:()=>{}})}}),this._consts.$tasksSelect().unbind("change.tasks"),this._consts.$tasksSelect().bind("change.tasks",e=>{if(a.Select2Helper.GetSelectedIdList($(e.target).select2("data")).length>0){let t=null;null!=$(e.target).select2("data")[0].parentId?t=$(e.target).select2("data")[0].parentId:"undefined"!=$(e.target).select2("data")[0].element.dataset.parentId&&(t=$(e.target).select2("data")[0].element.dataset.parentId),null!=t&&this._timesheetsService.GetProjectsById(Number(t),{success:e=>{var t=$.parseJSON(e),s=[],i={id:t[0].id,text:t[0].text};i.parentId=t[0].parentId,s.push(i),a.Select2Helper.SetSelectedOptions($('select[name="projects"]:visible'),s)},complete:()=>{}})}})}InitSelects(){super.BindSelect($("select[name='clients']"),i.SelectTypeEnum.TimesheetsClients,!1,!1,!1,e=>e,!0),super.BindSelect($("select[name='products']"),i.SelectTypeEnum.TimesheetsProducts,!1,!1,!1,(function(e){return e.param=Number($("select[name='clients']:visible").val()),e}),!0),super.BindSelect($("select[name='projects']"),i.SelectTypeEnum.TimesheetsProjects,!1,!1,!1,(function(e){return e.param=new o.Timesheets({ClientId:Number($("select[name='clients']:visible").val()),ProductId:Number($("select[name='products']:visible").val())}),e}),!0),super.BindSelect($("select[name='tasks']"),i.SelectTypeEnum.TimesheetsTasks,!1,!1,!1,(function(e){return e.param=new o.Timesheets({ClientId:Number($("select[name='clients']:visible").val()),ProductId:Number($("select[name='products']:visible").val()),ProjectId:Number($("select[name='projects']:visible").val())}),e}),!0),$("select[name='clients']").on("select2:select",()=>{$("select[name='products']").empty(),$("select[name='projects']").empty(),$("select[name='tasks']").empty()}),$("select[name='products']").on("select2:select",()=>{$("select[name='projects']").empty(),$("select[name='tasks']").empty()}),$("select[name='projects']").on("select2:select",()=>{$("select[name='tasks']").empty()})}ValidateOpenEdit(){let e=this.GetQueryStringParameter("taskId"),t=this.GetQueryStringParameter("taskName"),s=this.GetQueryStringParameter("projectId");null!=e&&""!=e.trim()&&(this._timesheetsService.ValidateCreatePermissions({success:i=>{if(0==i.IsOperationSuccessful)this.ToggleAlert(1,"Não tem permissões");else{this._consts.$addTaskModal().css("display","flex"),this._consts.$clientsSelect().val(null).trigger("change"),this._consts.$productsSelect().val(null).trigger("change"),this._consts.$projectsSelect().val(null).trigger("change"),this._consts.$tasksSelect().val(null).trigger("change"),this._consts.$observations().val(null);var r=[],n={id:e,text:t};r.push(n),n.parentId=s,a.Select2Helper.SetSelectedOptions(this._consts.$tasksSelect(),r),this._consts.$tasksSelect().trigger("change")}}}),this.DeleteQueryStringParameter("taskId"),this.DeleteQueryStringParameter("taskName"),this.DeleteQueryStringParameter("projectId"))}GetTimesheets(e){this.ToggleLoading();let t=Number(this._consts.$timesheetWrapper().attr("data-user-id")||""),s=Number(this._consts.$timesheetWrapper().attr("data-user-id")||"");try{let t=Date.parse(e);e instanceof Date&&!isNaN(t)||(e=new Date)}catch(t){e=new Date}let a=new o.TimesheetsFilter({BeginDate:e.toISOString(),UserId:t,ConsultantId:s});this._timesheetsService.GetTimesheets(a,{success:e=>{this._consts.$timesheetWrapper().html(e),this.InitButtonEvents(),this.CalculateRowColTotal()},complete:()=>{this.ToggleLoading()}})}GetFormValues(){return new o.Timesheets({ClientId:0!=Number($("select[name='clients']:visible").val())?Number($("select[name='clients']:visible").val()):null,ProductId:0!=Number($("select[name='products']:visible").val())?Number($("select[name='products']:visible").val()):null,ProjectId:0!=Number($("select[name='projects']:visible").val())?Number($("select[name='projects']:visible").val()):null,TaskId:0!=Number($("select[name='tasks']:visible").val())?Number($("select[name='tasks']:visible").val()):null,Observations:this._consts.$observations().val(),CurrentDate:(new Date).toISOString(),Date:new Date(this._consts.$timesheetTableWrapper().attr("data-current-date")).toISOString()})}SaveTimesheetDay(e){let t=$(e.currentTarget).closest(this._consts.$timesheetLine()).find(this._consts.$infoWrapper()),s=$(e.currentTarget).closest(this._consts.$timesheetItemLine());Number(s.find(this._consts.$hour()).val())>=23&&s.find(this._consts.$hour()).val(23);var a=60*Number(s.find(this._consts.$hour()).val())*60+60*Number(s.find(this._consts.$minutes()).val()),r=new o.Timesheets({Id:0!=Number(s.attr("data-timesheet-id"))?Number(s.attr("data-timesheet-id")):null,ClientId:0!=Number(t.attr("data-client-id"))?Number(t.attr("data-client-id")):null,ProductId:0!=Number(t.attr("data-product-id"))?Number(t.attr("data-product-id")):null,ProjectId:0!=Number(t.attr("data-project-id"))?Number(t.attr("data-project-id")):null,TaskId:0!=Number(t.attr("data-task-id"))?Number(t.attr("data-task-id")):null,Date:s.attr("data-timesheet-day"),TimeSeconds:a});this._timesheetsService.SaveTimesheets(r,!1,{success:e=>{let t=new Date(this._consts.$timesheetTableWrapper().attr("data-begin-date"));this.GetTimesheets(t),this.GetTimesheetsHours()},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao guardar a timesheet")},complete:()=>{}})}GetDuplicateTimesheet(e){let t=$(e).closest(this._consts.$timesheetLine()).find(this._consts.$infoWrapper()),s=$(e).closest(this._consts.$timesheetItemLine());var a=60*Number(s.find(this._consts.$hour()).val())*60+60*Number(s.find(this._consts.$minutes()).val());return new o.Timesheets({Id:null,ClientId:0!=Number(t.attr("data-client-id"))?Number(t.attr("data-client-id")):null,ProductId:0!=Number(t.attr("data-product-id"))?Number(t.attr("data-product-id")):null,ProjectId:0!=Number(t.attr("data-project-id"))?Number(t.attr("data-project-id")):null,TaskId:0!=Number(t.attr("data-task-id"))?Number(t.attr("data-task-id")):null,Date:s.attr("data-timesheet-day"),TimeSeconds:a})}CalculateRowColTotal(){var e=this._consts.$totalLine().find(this._consts.$timesheetItemLine().not(".biggerItem")).map(e=>0).toArray();$.each(this._consts.$timesheetLine(),(t,s)=>{var a=0;$.each($(s).find(this._consts.$timesheetItemLine().not(".biggerItem").not(".total")),(t,s)=>{var i=60*Number($(s).find(this._consts.$hour()).val())*60+60*Number($(s).find(this._consts.$minutes()).val());a+=i,e[t]+=i}),$(s).find(this._consts.$timesheetItemLineTotal()).find(this._consts.$hour()).val(("0"+a/3600).toString().split(".")[0].slice(-2)),$(s).find(this._consts.$timesheetItemLineTotal()).find(this._consts.$minutes()).val(("0"+a%3600/60).toString().slice(-2))}),$.each(this._consts.$totalLine().find(this._consts.$timesheetItemLine().not(".biggerItem").not(".totalWrapper")),(t,s)=>{$(s).find(this._consts.$hour()).val(("0"+e[t]/3600).toString().split(".")[0].slice(-2)),$(s).find(this._consts.$minutes()).val(("0"+e[t]%3600/60).toString().slice(-2))});let t=this._consts.$totalLine().find(this._consts.$totalWrapper());var s=e.reduce((e,t)=>e+t,0);t.find(this._consts.$hour()).val(("0"+s/3600).toString().split(".")[0].slice(-2)),t.find(this._consts.$minutes()).val(("0"+s%3600/60).toString().slice(-2))}GetTimesheetsHours(){this._timesheetsService.GetTimesheetsHoursForCurrentYear({success:e=>{$("#currentYearHours").text(e+"h")}})}CancelModal(){this._consts.$modalContainer().css("display","none"),this._consts.$addTaskModal().attr("data-timesheet-id",""),this._consts.$optionsCounterWrapper().css("display","NONE"),this._consts.$confirmStart().show(),this._consts.$timerWrapper().find("h1").text("00:00:00"),this._consts.$timerWrapper().find("p").text("00:00:00"),this._consts.$timerWrapper().attr("data-seconds",0),this._consts.$pauseBtn().find("h3").text("Pausa"),this._consts.$stickyPause().closest(this._consts.$iconOptionTimer()).removeClass(this._consts.stickyActiveOption),this._consts.$stickyStop().closest(this._consts.$iconOptionTimer()).removeClass(this._consts.stickyActiveOption),this._consts.$stickyContinue().closest(this._consts.$iconOptionTimer()).removeClass(this._consts.stickyActiveOption),clearInterval(Number(sessionStorage.getItem("timerId"))),sessionStorage.removeItem("timerId"),sessionStorage.removeItem("timerSeconds"),sessionStorage.removeItem("timesheet"),this._consts.$stickyContainer().hide()}EditTimesheet(){var e=[],t=this._consts.$addTaskModal().attr("data-timesheet-id").split(",");$.each(t,(t,s)=>{let a=this._consts.$timesheetLine().find(`.timesheetItemLine[data-timesheet-id='${s}']`);var i=60*Number(a.find(this._consts.$hour()).val())*60+60*Number(a.find(this._consts.$minutes()).val());let r=this.GetFormValues();r.Id=Number(s),r.Date=a.attr("data-timesheet-day"),r.TimeSeconds=0!=i?i:null,e.push(r)}),e.length>0&&this._timesheetsService.EditTimesheets(e,{success:e=>{if(-1==e)this.ToggleAlert(i.AlertType.Warning,"Já existe a timesheet para esta seguinte");else{this.CancelModal();let e=new Date(this._consts.$timesheetTableWrapper().attr("data-begin-date"));this.GetTimesheets(e),this.GetTimesheetsHours(),this.ToggleAlert(i.AlertType.Success,"Timesheet atualizada com sucesso")}},error:()=>{this.ToggleAlert(i.AlertType.Error,"Erro ao atualizar a timesheet")},complete:()=>{}})}}$(()=>{(new c).Load()})}]);
/**
* jquery.mask.js
* @version: v1.14.15
* @author: Igor Escobar
*
* Created by Igor Escobar on 2012-03-10. Please report any bug at github.com/igorescobar/jQuery-Mask-Plugin
*
* Copyright (c) 2012 Igor Escobar http://igorescobar.com
*
* The MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/* jshint laxbreak: true */
/* jshint maxcomplexity:17 */
/* global define */
// UMD (Universal Module Definition) patterns for JavaScript modules that work everywhere.
// https://github.com/umdjs/umd/blob/master/templates/jqueryPlugin.js
(function (factory, jQuery, Zepto) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery || Zepto);
}
}(function ($) {
'use strict';
var Mask = function (el, mask, options) {
var p = {
invalid: [],
getCaret: function () {
try {
var sel,
pos = 0,
ctrl = el.get(0),
dSel = document.selection,
cSelStart = ctrl.selectionStart;
// IE Support
if (dSel && navigator.appVersion.indexOf('MSIE 10') === -1) {
sel = dSel.createRange();
sel.moveStart('character', -p.val().length);
pos = sel.text.length;
}
// Firefox support
else if (cSelStart || cSelStart === '0') {
pos = cSelStart;
}
return pos;
} catch (e) {}
},
setCaret: function(pos) {
try {
if (el.is(':focus')) {
var range, ctrl = el.get(0);
// Firefox, WebKit, etc..
if (ctrl.setSelectionRange) {
ctrl.setSelectionRange(pos, pos);
} else { // IE
range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
} catch (e) {}
},
events: function() {
el
.on('keydown.mask', function(e) {
el.data('mask-keycode', e.keyCode || e.which);
el.data('mask-previus-value', el.val());
el.data('mask-previus-caret-pos', p.getCaret());
p.maskDigitPosMapOld = p.maskDigitPosMap;
})
.on($.jMaskGlobals.useInput ? 'input.mask' : 'keyup.mask', p.behaviour)
.on('paste.mask drop.mask', function() {
setTimeout(function() {
el.keydown().keyup();
}, 100);
})
.on('change.mask', function(){
el.data('changed', true);
})
.on('blur.mask', function(){
if (oldValue !== p.val() && !el.data('changed')) {
el.trigger('change');
}
el.data('changed', false);
})
// it's very important that this callback remains in this position
// otherwhise oldValue it's going to work buggy
.on('blur.mask', function() {
oldValue = p.val();
})
// select all text on focus
.on('focus.mask', function (e) {
if (options.selectOnFocus === true) {
$(e.target).select();
}
})
// clear the value if it not complete the mask
.on('focusout.mask', function() {
if (options.clearIfNotMatch && !regexMask.test(p.val())) {
p.val('');
}
});
},
getRegexMask: function() {
var maskChunks = [], translation, pattern, optional, recursive, oRecursive, r;
for (var i = 0; i < mask.length; i++) {
translation = jMask.translation[mask.charAt(i)];
if (translation) {
pattern = translation.pattern.toString().replace(/.{1}$|^.{1}/g, '');
optional = translation.optional;
recursive = translation.recursive;
if (recursive) {
maskChunks.push(mask.charAt(i));
oRecursive = {digit: mask.charAt(i), pattern: pattern};
} else {
maskChunks.push(!optional && !recursive ? pattern : (pattern + '?'));
}
} else {
maskChunks.push(mask.charAt(i).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
}
}
r = maskChunks.join('');
if (oRecursive) {
r = r.replace(new RegExp('(' + oRecursive.digit + '(.*' + oRecursive.digit + ')?)'), '($1)?')
.replace(new RegExp(oRecursive.digit, 'g'), oRecursive.pattern);
}
return new RegExp(r);
},
destroyEvents: function() {
el.off(['input', 'keydown', 'keyup', 'paste', 'drop', 'blur', 'focusout', ''].join('.mask '));
},
val: function(v) {
var isInput = el.is('input'),
method = isInput ? 'val' : 'text',
r;
if (arguments.length > 0) {
if (el[method]() !== v) {
el[method](v);
}
r = el;
} else {
r = el[method]();
}
return r;
},
calculateCaretPosition: function() {
var oldVal = el.data('mask-previus-value') || '',
newVal = p.getMasked(),
caretPosNew = p.getCaret();
if (oldVal !== newVal) {
var caretPosOld = el.data('mask-previus-caret-pos') || 0,
newValL = newVal.length,
oldValL = oldVal.length,
maskDigitsBeforeCaret = 0,
maskDigitsAfterCaret = 0,
maskDigitsBeforeCaretAll = 0,
maskDigitsBeforeCaretAllOld = 0,
i = 0;
for (i = caretPosNew; i < newValL; i++) {
if (!p.maskDigitPosMap[i]) {
break;
}
maskDigitsAfterCaret++;
}
for (i = caretPosNew - 1; i >= 0; i--) {
if (!p.maskDigitPosMap[i]) {
break;
}
maskDigitsBeforeCaret++;
}
for (i = caretPosNew - 1; i >= 0; i--) {
if (p.maskDigitPosMap[i]) {
maskDigitsBeforeCaretAll++;
}
}
for (i = caretPosOld - 1; i >= 0; i--) {
if (p.maskDigitPosMapOld[i]) {
maskDigitsBeforeCaretAllOld++;
}
}
// if the cursor is at the end keep it there
if (caretPosNew > oldValL) {
caretPosNew = newValL * 10;
} else if (caretPosOld >= caretPosNew && caretPosOld !== oldValL) {
if (!p.maskDigitPosMapOld[caretPosNew]) {
var caretPos = caretPosNew;
caretPosNew -= maskDigitsBeforeCaretAllOld - maskDigitsBeforeCaretAll;
caretPosNew -= maskDigitsBeforeCaret;
if (p.maskDigitPosMap[caretPosNew]) {
caretPosNew = caretPos;
}
}
}
else if (caretPosNew > caretPosOld) {
caretPosNew += maskDigitsBeforeCaretAll - maskDigitsBeforeCaretAllOld;
caretPosNew += maskDigitsAfterCaret;
}
}
return caretPosNew;
},
behaviour: function(e) {
e = e || window.event;
p.invalid = [];
var keyCode = el.data('mask-keycode');
if ($.inArray(keyCode, jMask.byPassKeys) === -1) {
var newVal = p.getMasked(),
caretPos = p.getCaret();
// this is a compensation to devices/browsers that don't compensate
// caret positioning the right way
setTimeout(function() {
p.setCaret(p.calculateCaretPosition());
}, $.jMaskGlobals.keyStrokeCompensation);
p.val(newVal);
p.setCaret(caretPos);
return p.callbacks(e);
}
},
getMasked: function(skipMaskChars, val) {
var buf = [],
value = val === undefined ? p.val() : val + '',
m = 0, maskLen = mask.length,
v = 0, valLen = value.length,
offset = 1, addMethod = 'push',
resetPos = -1,
maskDigitCount = 0,
maskDigitPosArr = [],
lastMaskChar,
check;
if (options.reverse) {
addMethod = 'unshift';
offset = -1;
lastMaskChar = 0;
m = maskLen - 1;
v = valLen - 1;
check = function () {
return m > -1 && v > -1;
};
} else {
lastMaskChar = maskLen - 1;
check = function () {
return m < maskLen && v < valLen;
};
}
var lastUntranslatedMaskChar;
while (check()) {
var maskDigit = mask.charAt(m),
valDigit = value.charAt(v),
translation = jMask.translation[maskDigit];
if (translation) {
if (valDigit.match(translation.pattern)) {
buf[addMethod](valDigit);
if (translation.recursive) {
if (resetPos === -1) {
resetPos = m;
} else if (m === lastMaskChar && m !== resetPos) {
m = resetPos - offset;
}
if (lastMaskChar === resetPos) {
m -= offset;
}
}
m += offset;
} else if (valDigit === lastUntranslatedMaskChar) {
// matched the last untranslated (raw) mask character that we encountered
// likely an insert offset the mask character from the last entry; fall
// through and only increment v
maskDigitCount--;
lastUntranslatedMaskChar = undefined;
} else if (translation.optional) {
m += offset;
v -= offset;
} else if (translation.fallback) {
buf[addMethod](translation.fallback);
m += offset;
v -= offset;
} else {
p.invalid.push({p: v, v: valDigit, e: translation.pattern});
}
v += offset;
} else {
if (!skipMaskChars) {
buf[addMethod](maskDigit);
}
if (valDigit === maskDigit) {
maskDigitPosArr.push(v);
v += offset;
} else {
lastUntranslatedMaskChar = maskDigit;
maskDigitPosArr.push(v + maskDigitCount);
maskDigitCount++;
}
m += offset;
}
}
var lastMaskCharDigit = mask.charAt(lastMaskChar);
if (maskLen === valLen + 1 && !jMask.translation[lastMaskCharDigit]) {
buf.push(lastMaskCharDigit);
}
var newVal = buf.join('');
p.mapMaskdigitPositions(newVal, maskDigitPosArr, valLen);
return newVal;
},
mapMaskdigitPositions: function(newVal, maskDigitPosArr, valLen) {
var maskDiff = options.reverse ? newVal.length - valLen : 0;
p.maskDigitPosMap = {};
for (var i = 0; i < maskDigitPosArr.length; i++) {
p.maskDigitPosMap[maskDigitPosArr[i] + maskDiff] = 1;
}
},
callbacks: function (e) {
var val = p.val(),
changed = val !== oldValue,
defaultArgs = [val, e, el, options],
callback = function(name, criteria, args) {
if (typeof options[name] === 'function' && criteria) {
options[name].apply(this, args);
}
};
callback('onChange', changed === true, defaultArgs);
callback('onKeyPress', changed === true, defaultArgs);
callback('onComplete', val.length === mask.length, defaultArgs);
callback('onInvalid', p.invalid.length > 0, [val, e, el, p.invalid, options]);
}
};
el = $(el);
var jMask = this, oldValue = p.val(), regexMask;
mask = typeof mask === 'function' ? mask(p.val(), undefined, el, options) : mask;
// public methods
jMask.mask = mask;
jMask.options = options;
jMask.remove = function() {
var caret = p.getCaret();
if (jMask.options.placeholder) {
el.removeAttr('placeholder');
}
if (el.data('mask-maxlength')) {
el.removeAttr('maxlength');
}
p.destroyEvents();
p.val(jMask.getCleanVal());
p.setCaret(caret);
return el;
};
// get value without mask
jMask.getCleanVal = function() {
return p.getMasked(true);
};
// get masked value without the value being in the input or element
jMask.getMaskedVal = function(val) {
return p.getMasked(false, val);
};
jMask.init = function(onlyMask) {
onlyMask = onlyMask || false;
options = options || {};
jMask.clearIfNotMatch = $.jMaskGlobals.clearIfNotMatch;
jMask.byPassKeys = $.jMaskGlobals.byPassKeys;
jMask.translation = $.extend({}, $.jMaskGlobals.translation, options.translation);
jMask = $.extend(true, {}, jMask, options);
regexMask = p.getRegexMask();
if (onlyMask) {
p.events();
p.val(p.getMasked());
} else {
if (options.placeholder) {
el.attr('placeholder' , options.placeholder);
}
// this is necessary, otherwise if the user submit the form
// and then press the "back" button, the autocomplete will erase
// the data. Works fine on IE9+, FF, Opera, Safari.
if (el.data('mask')) {
el.attr('autocomplete', 'off');
}
// detect if is necessary let the user type freely.
// for is a lot faster than forEach.
for (var i = 0, maxlength = true; i < mask.length; i++) {
var translation = jMask.translation[mask.charAt(i)];
if (translation && translation.recursive) {
maxlength = false;
break;
}
}
if (maxlength) {
el.attr('maxlength', mask.length).data('mask-maxlength', true);
}
p.destroyEvents();
p.events();
var caret = p.getCaret();
p.val(p.getMasked());
p.setCaret(caret);
}
};
jMask.init(!el.is('input'));
};
$.maskWatchers = {};
var HTMLAttributes = function () {
var input = $(this),
options = {},
prefix = 'data-mask-',
mask = input.attr('data-mask');
if (input.attr(prefix + 'reverse')) {
options.reverse = true;
}
if (input.attr(prefix + 'clearifnotmatch')) {
options.clearIfNotMatch = true;
}
if (input.attr(prefix + 'selectonfocus') === 'true') {
options.selectOnFocus = true;
}
if (notSameMaskObject(input, mask, options)) {
return input.data('mask', new Mask(this, mask, options));
}
},
notSameMaskObject = function(field, mask, options) {
options = options || {};
var maskObject = $(field).data('mask'),
stringify = JSON.stringify,
value = $(field).val() || $(field).text();
try {
if (typeof mask === 'function') {
mask = mask(value);
}
return typeof maskObject !== 'object' || stringify(maskObject.options) !== stringify(options) || maskObject.mask !== mask;
} catch (e) {}
},
eventSupported = function(eventName) {
var el = document.createElement('div'), isSupported;
eventName = 'on' + eventName;
isSupported = (eventName in el);
if ( !isSupported ) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] === 'function';
}
el = null;
return isSupported;
};
$.fn.mask = function(mask, options) {
options = options || {};
var selector = this.selector,
globals = $.jMaskGlobals,
interval = globals.watchInterval,
watchInputs = options.watchInputs || globals.watchInputs,
maskFunction = function() {
if (notSameMaskObject(this, mask, options)) {
return $(this).data('mask', new Mask(this, mask, options));
}
};
$(this).each(maskFunction);
if (selector && selector !== '' && watchInputs) {
clearInterval($.maskWatchers[selector]);
$.maskWatchers[selector] = setInterval(function(){
$(document).find(selector).each(maskFunction);
}, interval);
}
return this;
};
$.fn.masked = function(val) {
return this.data('mask').getMaskedVal(val);
};
$.fn.unmask = function() {
clearInterval($.maskWatchers[this.selector]);
delete $.maskWatchers[this.selector];
return this.each(function() {
var dataMask = $(this).data('mask');
if (dataMask) {
dataMask.remove().removeData('mask');
}
});
};
$.fn.cleanVal = function() {
return this.data('mask').getCleanVal();
};
$.applyDataMask = function(selector) {
selector = selector || $.jMaskGlobals.maskElements;
var $selector = (selector instanceof $) ? selector : $(selector);
$selector.filter($.jMaskGlobals.dataMaskAttr).each(HTMLAttributes);
};
var globals = {
maskElements: 'input,td,span,div',
dataMaskAttr: '*[data-mask]',
dataMask: true,
watchInterval: 300,
watchInputs: true,
keyStrokeCompensation: 10,
// old versions of chrome dont work great with input event
useInput: !/Chrome\/[2-4][0-9]|SamsungBrowser/.test(window.navigator.userAgent) && eventSupported('input'),
watchDataMask: false,
byPassKeys: [9, 16, 17, 18, 36, 37, 38, 39, 40, 91],
translation: {
'0': {pattern: /\d/},
'9': {pattern: /\d/, optional: true},
'#': {pattern: /\d/, recursive: true},
'A': {pattern: /[a-zA-Z0-9]/},
'S': {pattern: /[a-zA-Z]/}
}
};
$.jMaskGlobals = $.jMaskGlobals || {};
globals = $.jMaskGlobals = $.extend(true, {}, globals, $.jMaskGlobals);
// looking for inputs with data-mask attribute
if (globals.dataMask) {
$.applyDataMask();
}
setInterval(function() {
if ($.jMaskGlobals.watchDataMask) {
$.applyDataMask();
}
}, globals.watchInterval);
}, window.jQuery, window.Zepto));
/*
* jQuery File Upload Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, require, window, document, location, Blob, FormData */
;(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'jquery-ui/ui/widget'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('./vendor/jquery.ui.widget')
);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Detect file input support, based on
// http://viljamis.com/blog/2012/file-upload-support-on-mobile/
$.support.fileInput = !(new RegExp(
// Handle devices which give false positives for the feature detection:
'(Android (1\\.[0156]|2\\.[01]))' +
'|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' +
'|(w(eb)?OSBrowser)|(webOS)' +
'|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
).test(window.navigator.userAgent) ||
// Feature detection for all other devices:
$(' ').prop('disabled'));
// The FileReader API is not actually used, but works as feature detection,
// as some Safari versions (5?) support XHR file uploads via the FormData API,
// but not non-multipart XHR file uploads.
// window.XMLHttpRequestUpload is not available on IE10, so we check for
// window.ProgressEvent instead to detect XHR2 file upload capability:
$.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader);
$.support.xhrFormDataFileUpload = !!window.FormData;
// Detect support for Blob slicing (required for chunked uploads):
$.support.blobSlice = window.Blob && (Blob.prototype.slice ||
Blob.prototype.webkitSlice || Blob.prototype.mozSlice);
// Helper function to create drag handlers for dragover/dragenter/dragleave:
function getDragHandler(type) {
var isDragOver = type === 'dragover';
return function (e) {
e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
var dataTransfer = e.dataTransfer;
if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 &&
this._trigger(
type,
$.Event(type, {delegatedEvent: e})
) !== false) {
e.preventDefault();
if (isDragOver) {
dataTransfer.dropEffect = 'copy';
}
}
};
}
// The fileupload widget listens for change events on file input fields defined
// via fileInput setting and paste or drop events of the given dropZone.
// In addition to the default jQuery Widget methods, the fileupload widget
// exposes the "add" and "send" methods, to add or directly send files using
// the fileupload API.
// By default, files added via file input selection, paste, drag & drop or
// "add" method are uploaded immediately, but it is possible to override
// the "add" callback option to queue file uploads.
$.widget('blueimp.fileupload', {
options: {
// The drop target element(s), by the default the complete document.
// Set to null to disable drag & drop support:
dropZone: $(document),
// The paste target element(s), by the default undefined.
// Set to a DOM node or jQuery object to enable file pasting:
pasteZone: undefined,
// The file input field(s), that are listened to for change events.
// If undefined, it is set to the file input fields inside
// of the widget element on plugin initialization.
// Set to null to disable the change listener.
fileInput: undefined,
// By default, the file input field is replaced with a clone after
// each input field change event. This is required for iframe transport
// queues and allows change events to be fired for the same file
// selection, but can be disabled by setting the following option to false:
replaceFileInput: true,
// The parameter name for the file form data (the request argument name).
// If undefined or empty, the name property of the file input field is
// used, or "files[]" if the file input name property is also empty,
// can be a string or an array of strings:
paramName: undefined,
// By default, each file of a selection is uploaded using an individual
// request for XHR type uploads. Set to false to upload file
// selections in one request each:
singleFileUploads: true,
// To limit the number of files uploaded with one XHR request,
// set the following option to an integer greater than 0:
limitMultiFileUploads: undefined,
// The following option limits the number of files uploaded with one
// XHR request to keep the request size under or equal to the defined
// limit in bytes:
limitMultiFileUploadSize: undefined,
// Multipart file uploads add a number of bytes to each uploaded file,
// therefore the following option adds an overhead for each file used
// in the limitMultiFileUploadSize configuration:
limitMultiFileUploadSizeOverhead: 512,
// Set the following option to true to issue all file upload requests
// in a sequential order:
sequentialUploads: false,
// To limit the number of concurrent uploads,
// set the following option to an integer greater than 0:
limitConcurrentUploads: undefined,
// Set the following option to true to force iframe transport uploads:
forceIframeTransport: false,
// Set the following option to the location of a redirect url on the
// origin server, for cross-domain iframe transport uploads:
redirect: undefined,
// The parameter name for the redirect url, sent as part of the form
// data and set to 'redirect' if this option is empty:
redirectParamName: undefined,
// Set the following option to the location of a postMessage window,
// to enable postMessage transport uploads:
postMessage: undefined,
// By default, XHR file uploads are sent as multipart/form-data.
// The iframe transport is always using multipart/form-data.
// Set to false to enable non-multipart XHR uploads:
multipart: true,
// To upload large files in smaller chunks, set the following option
// to a preferred maximum chunk size. If set to 0, null or undefined,
// or the browser does not support the required Blob API, files will
// be uploaded as a whole.
maxChunkSize: undefined,
// When a non-multipart upload or a chunked multipart upload has been
// aborted, this option can be used to resume the upload by setting
// it to the size of the already uploaded bytes. This option is most
// useful when modifying the options object inside of the "add" or
// "send" callbacks, as the options are cloned for each file upload.
uploadedBytes: undefined,
// By default, failed (abort or error) file uploads are removed from the
// global progress calculation. Set the following option to false to
// prevent recalculating the global progress data:
recalculateProgress: true,
// Interval in milliseconds to calculate and trigger progress events:
progressInterval: 100,
// Interval in milliseconds to calculate progress bitrate:
bitrateInterval: 500,
// By default, uploads are started automatically when adding files:
autoUpload: true,
// Error and info messages:
messages: {
uploadedBytes: 'Uploaded bytes exceed file size'
},
// Translation function, gets the message key to be translated
// and an object with context specific data as arguments:
i18n: function (message, context) {
message = this.messages[message] || message.toString();
if (context) {
$.each(context, function (key, value) {
message = message.replace('{' + key + '}', value);
});
}
return message;
},
// Additional form data to be sent along with the file uploads can be set
// using this option, which accepts an array of objects with name and
// value properties, a function returning such an array, a FormData
// object (for XHR file uploads), or a simple object.
// The form of the first fileInput is given as parameter to the function:
formData: function (form) {
return form.serializeArray();
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop, paste or add API call).
// If the singleFileUploads option is enabled, this callback will be
// called once for each file in the selection for XHR file uploads, else
// once for each file selection.
//
// The upload starts when the submit method is invoked on the data parameter.
// The data object contains a files property holding the added files
// and allows you to override plugin options as well as define ajax settings.
//
// Listeners for this callback can also be bound the following way:
// .bind('fileuploadadd', func);
//
// data.submit() returns a Promise object and allows to attach additional
// handlers using jQuery's Deferred callbacks:
// data.submit().done(func).fail(func).always(func);
add: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
if (data.autoUpload || (data.autoUpload !== false &&
$(this).fileupload('option', 'autoUpload'))) {
data.process().done(function () {
data.submit();
});
}
},
// Other callbacks:
// Callback for the submit event of each file upload:
// submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
// Callback for the start of each file upload request:
// send: function (e, data) {}, // .bind('fileuploadsend', func);
// Callback for successful uploads:
// done: function (e, data) {}, // .bind('fileuploaddone', func);
// Callback for failed (abort or error) uploads:
// fail: function (e, data) {}, // .bind('fileuploadfail', func);
// Callback for completed (success, abort or error) requests:
// always: function (e, data) {}, // .bind('fileuploadalways', func);
// Callback for upload progress events:
// progress: function (e, data) {}, // .bind('fileuploadprogress', func);
// Callback for global upload progress events:
// progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
// Callback for uploads start, equivalent to the global ajaxStart event:
// start: function (e) {}, // .bind('fileuploadstart', func);
// Callback for uploads stop, equivalent to the global ajaxStop event:
// stop: function (e) {}, // .bind('fileuploadstop', func);
// Callback for change events of the fileInput(s):
// change: function (e, data) {}, // .bind('fileuploadchange', func);
// Callback for paste events to the pasteZone(s):
// paste: function (e, data) {}, // .bind('fileuploadpaste', func);
// Callback for drop events of the dropZone(s):
// drop: function (e, data) {}, // .bind('fileuploaddrop', func);
// Callback for dragover events of the dropZone(s):
// dragover: function (e) {}, // .bind('fileuploaddragover', func);
// Callback before the start of each chunk upload request (before form data initialization):
// chunkbeforesend: function (e, data) {}, // .bind('fileuploadchunkbeforesend', func);
// Callback for the start of each chunk upload request:
// chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);
// Callback for successful chunk uploads:
// chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);
// Callback for failed (abort or error) chunk uploads:
// chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);
// Callback for completed (success, abort or error) chunk upload requests:
// chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);
// The plugin options are used as settings object for the ajax calls.
// The following are jQuery ajax settings required for the file uploads:
processData: false,
contentType: false,
cache: false,
timeout: 0
},
// A list of options that require reinitializing event listeners and/or
// special initialization code:
_specialOptions: [
'fileInput',
'dropZone',
'pasteZone',
'multipart',
'forceIframeTransport'
],
_blobSlice: $.support.blobSlice && function () {
var slice = this.slice || this.webkitSlice || this.mozSlice;
return slice.apply(this, arguments);
},
_BitrateTimer: function () {
this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
this.loaded = 0;
this.bitrate = 0;
this.getBitrate = function (now, loaded, interval) {
var timeDiff = now - this.timestamp;
if (!this.bitrate || !interval || timeDiff > interval) {
this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
this.loaded = loaded;
this.timestamp = now;
}
return this.bitrate;
};
},
_isXHRUpload: function (options) {
return !options.forceIframeTransport &&
((!options.multipart && $.support.xhrFileUpload) ||
$.support.xhrFormDataFileUpload);
},
_getFormData: function (options) {
var formData;
if ($.type(options.formData) === 'function') {
return options.formData(options.form);
}
if ($.isArray(options.formData)) {
return options.formData;
}
if ($.type(options.formData) === 'object') {
formData = [];
$.each(options.formData, function (name, value) {
formData.push({name: name, value: value});
});
return formData;
}
return [];
},
_getTotal: function (files) {
var total = 0;
$.each(files, function (index, file) {
total += file.size || 1;
});
return total;
},
_initProgressObject: function (obj) {
var progress = {
loaded: 0,
total: 0,
bitrate: 0
};
if (obj._progress) {
$.extend(obj._progress, progress);
} else {
obj._progress = progress;
}
},
_initResponseObject: function (obj) {
var prop;
if (obj._response) {
for (prop in obj._response) {
if (obj._response.hasOwnProperty(prop)) {
delete obj._response[prop];
}
}
} else {
obj._response = {};
}
},
_onProgress: function (e, data) {
if (e.lengthComputable) {
var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
loaded;
if (data._time && data.progressInterval &&
(now - data._time < data.progressInterval) &&
e.loaded !== e.total) {
return;
}
data._time = now;
loaded = Math.floor(
e.loaded / e.total * (data.chunkSize || data._progress.total)
) + (data.uploadedBytes || 0);
// Add the difference from the previously loaded state
// to the global loaded counter:
this._progress.loaded += (loaded - data._progress.loaded);
this._progress.bitrate = this._bitrateTimer.getBitrate(
now,
this._progress.loaded,
data.bitrateInterval
);
data._progress.loaded = data.loaded = loaded;
data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
now,
loaded,
data.bitrateInterval
);
// Trigger a custom progress event with a total data property set
// to the file size(s) of the current upload and a loaded data
// property calculated accordingly:
this._trigger(
'progress',
$.Event('progress', {delegatedEvent: e}),
data
);
// Trigger a global progress event for all current file uploads,
// including ajax calls queued for sequential file uploads:
this._trigger(
'progressall',
$.Event('progressall', {delegatedEvent: e}),
this._progress
);
}
},
_initProgressListener: function (options) {
var that = this,
xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
// Accesss to the native XHR object is required to add event listeners
// for the upload progress event:
if (xhr.upload) {
$(xhr.upload).bind('progress', function (e) {
var oe = e.originalEvent;
// Make sure the progress event properties get copied over:
e.lengthComputable = oe.lengthComputable;
e.loaded = oe.loaded;
e.total = oe.total;
that._onProgress(e, options);
});
options.xhr = function () {
return xhr;
};
}
},
_deinitProgressListener: function (options) {
var xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
if (xhr.upload) {
$(xhr.upload).unbind('progress');
}
},
_isInstanceOf: function (type, obj) {
// Cross-frame instanceof check
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
},
_initXHRData: function (options) {
var that = this,
formData,
file = options.files[0],
// Ignore non-multipart setting if not supported:
multipart = options.multipart || !$.support.xhrFileUpload,
paramName = $.type(options.paramName) === 'array' ?
options.paramName[0] : options.paramName;
options.headers = $.extend({}, options.headers);
if (options.contentRange) {
options.headers['Content-Range'] = options.contentRange;
}
if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
options.headers['Content-Disposition'] = 'attachment; filename="' +
encodeURI(file.uploadName || file.name) + '"';
}
if (!multipart) {
options.contentType = file.type || 'application/octet-stream';
options.data = options.blob || file;
} else if ($.support.xhrFormDataFileUpload) {
if (options.postMessage) {
// window.postMessage does not allow sending FormData
// objects, so we just add the File/Blob objects to
// the formData array and let the postMessage window
// create the FormData object out of this array:
formData = this._getFormData(options);
if (options.blob) {
formData.push({
name: paramName,
value: options.blob
});
} else {
$.each(options.files, function (index, file) {
formData.push({
name: ($.type(options.paramName) === 'array' &&
options.paramName[index]) || paramName,
value: file
});
});
}
} else {
if (that._isInstanceOf('FormData', options.formData)) {
formData = options.formData;
} else {
formData = new FormData();
$.each(this._getFormData(options), function (index, field) {
formData.append(field.name, field.value);
});
}
if (options.blob) {
formData.append(
paramName,
options.blob,
file.uploadName || file.name
);
} else {
$.each(options.files, function (index, file) {
// This check allows the tests to run with
// dummy objects:
if (that._isInstanceOf('File', file) ||
that._isInstanceOf('Blob', file)) {
formData.append(
($.type(options.paramName) === 'array' &&
options.paramName[index]) || paramName,
file,
file.uploadName || file.name
);
}
});
}
}
options.data = formData;
}
// Blob reference is not needed anymore, free memory:
options.blob = null;
},
_initIframeSettings: function (options) {
var targetHost = $(' ').prop('href', options.url).prop('host');
// Setting the dataType to iframe enables the iframe transport:
options.dataType = 'iframe ' + (options.dataType || '');
// The iframe transport accepts a serialized array as form data:
options.formData = this._getFormData(options);
// Add redirect url to form data on cross-domain uploads:
if (options.redirect && targetHost && targetHost !== location.host) {
options.formData.push({
name: options.redirectParamName || 'redirect',
value: options.redirect
});
}
},
_initDataSettings: function (options) {
if (this._isXHRUpload(options)) {
if (!this._chunkedUpload(options, true)) {
if (!options.data) {
this._initXHRData(options);
}
this._initProgressListener(options);
}
if (options.postMessage) {
// Setting the dataType to postmessage enables the
// postMessage transport:
options.dataType = 'postmessage ' + (options.dataType || '');
}
} else {
this._initIframeSettings(options);
}
},
_getParamName: function (options) {
var fileInput = $(options.fileInput),
paramName = options.paramName;
if (!paramName) {
paramName = [];
fileInput.each(function () {
var input = $(this),
name = input.prop('name') || 'files[]',
i = (input.prop('files') || [1]).length;
while (i) {
paramName.push(name);
i -= 1;
}
});
if (!paramName.length) {
paramName = [fileInput.prop('name') || 'files[]'];
}
} else if (!$.isArray(paramName)) {
paramName = [paramName];
}
return paramName;
},
_initFormSettings: function (options) {
// Retrieve missing options from the input field and the
// associated form, if available:
if (!options.form || !options.form.length) {
options.form = $(options.fileInput.prop('form'));
// If the given file input doesn't have an associated form,
// use the default widget file input's form:
if (!options.form.length) {
options.form = $(this.options.fileInput.prop('form'));
}
}
options.paramName = this._getParamName(options);
if (!options.url) {
options.url = options.form.prop('action') || location.href;
}
// The HTTP request method must be "POST" or "PUT":
options.type = (options.type ||
($.type(options.form.prop('method')) === 'string' &&
options.form.prop('method')) || ''
).toUpperCase();
if (options.type !== 'POST' && options.type !== 'PUT' &&
options.type !== 'PATCH') {
options.type = 'POST';
}
if (!options.formAcceptCharset) {
options.formAcceptCharset = options.form.attr('accept-charset');
}
},
_getAJAXSettings: function (data) {
var options = $.extend({}, this.options, data);
this._initFormSettings(options);
this._initDataSettings(options);
return options;
},
// jQuery 1.6 doesn't provide .state(),
// while jQuery 1.8+ removed .isRejected() and .isResolved():
_getDeferredState: function (deferred) {
if (deferred.state) {
return deferred.state();
}
if (deferred.isResolved()) {
return 'resolved';
}
if (deferred.isRejected()) {
return 'rejected';
}
return 'pending';
},
// Maps jqXHR callbacks to the equivalent
// methods of the given Promise object:
_enhancePromise: function (promise) {
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.always;
return promise;
},
// Creates and returns a Promise object enhanced with
// the jqXHR methods abort, success, error and complete:
_getXHRPromise: function (resolveOrReject, context, args) {
var dfd = $.Deferred(),
promise = dfd.promise();
context = context || this.options.context || promise;
if (resolveOrReject === true) {
dfd.resolveWith(context, args);
} else if (resolveOrReject === false) {
dfd.rejectWith(context, args);
}
promise.abort = dfd.promise;
return this._enhancePromise(promise);
},
// Adds convenience methods to the data callback argument:
_addConvenienceMethods: function (e, data) {
var that = this,
getPromise = function (args) {
return $.Deferred().resolveWith(that, args).promise();
};
data.process = function (resolveFunc, rejectFunc) {
if (resolveFunc || rejectFunc) {
data._processQueue = this._processQueue =
(this._processQueue || getPromise([this])).then(
function () {
if (data.errorThrown) {
return $.Deferred()
.rejectWith(that, [data]).promise();
}
return getPromise(arguments);
}
).then(resolveFunc, rejectFunc);
}
return this._processQueue || getPromise([this]);
};
data.submit = function () {
if (this.state() !== 'pending') {
data.jqXHR = this.jqXHR =
(that._trigger(
'submit',
$.Event('submit', {delegatedEvent: e}),
this
) !== false) && that._onSend(e, this);
}
return this.jqXHR || that._getXHRPromise();
};
data.abort = function () {
if (this.jqXHR) {
return this.jqXHR.abort();
}
this.errorThrown = 'abort';
that._trigger('fail', null, this);
return that._getXHRPromise(false);
};
data.state = function () {
if (this.jqXHR) {
return that._getDeferredState(this.jqXHR);
}
if (this._processQueue) {
return that._getDeferredState(this._processQueue);
}
};
data.processing = function () {
return !this.jqXHR && this._processQueue && that
._getDeferredState(this._processQueue) === 'pending';
};
data.progress = function () {
return this._progress;
};
data.response = function () {
return this._response;
};
},
// Parses the Range header from the server response
// and returns the uploaded bytes:
_getUploadedBytes: function (jqXHR) {
var range = jqXHR.getResponseHeader('Range'),
parts = range && range.split('-'),
upperBytesPos = parts && parts.length > 1 &&
parseInt(parts[1], 10);
return upperBytesPos && upperBytesPos + 1;
},
// Uploads a file in multiple, sequential requests
// by splitting the file up in multiple blob chunks.
// If the second parameter is true, only tests if the file
// should be uploaded in chunks, but does not invoke any
// upload requests:
_chunkedUpload: function (options, testOnly) {
options.uploadedBytes = options.uploadedBytes || 0;
var that = this,
file = options.files[0],
fs = file.size,
ub = options.uploadedBytes,
mcs = options.maxChunkSize || fs,
slice = this._blobSlice,
dfd = $.Deferred(),
promise = dfd.promise(),
jqXHR,
upload;
if (!(this._isXHRUpload(options) && slice && (ub || ($.type(mcs) === 'function' ? mcs(options) : mcs) < fs)) ||
options.data) {
return false;
}
if (testOnly) {
return true;
}
if (ub >= fs) {
file.error = options.i18n('uploadedBytes');
return this._getXHRPromise(
false,
options.context,
[null, 'error', file.error]
);
}
// The chunk upload method:
upload = function () {
// Clone the options object for each chunk upload:
var o = $.extend({}, options),
currentLoaded = o._progress.loaded;
o.blob = slice.call(
file,
ub,
ub + ($.type(mcs) === 'function' ? mcs(o) : mcs),
file.type
);
// Store the current chunk size, as the blob itself
// will be dereferenced after data processing:
o.chunkSize = o.blob.size;
// Expose the chunk bytes position range:
o.contentRange = 'bytes ' + ub + '-' +
(ub + o.chunkSize - 1) + '/' + fs;
// Trigger chunkbeforesend to allow form data to be updated for this chunk
that._trigger('chunkbeforesend', null, o);
// Process the upload data (the blob and potential form data):
that._initXHRData(o);
// Add progress listeners for this chunk upload:
that._initProgressListener(o);
jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
that._getXHRPromise(false, o.context))
.done(function (result, textStatus, jqXHR) {
ub = that._getUploadedBytes(jqXHR) ||
(ub + o.chunkSize);
// Create a progress event if no final progress event
// with loaded equaling total has been triggered
// for this chunk:
if (currentLoaded + o.chunkSize - o._progress.loaded) {
that._onProgress($.Event('progress', {
lengthComputable: true,
loaded: ub - o.uploadedBytes,
total: ub - o.uploadedBytes
}), o);
}
options.uploadedBytes = o.uploadedBytes = ub;
o.result = result;
o.textStatus = textStatus;
o.jqXHR = jqXHR;
that._trigger('chunkdone', null, o);
that._trigger('chunkalways', null, o);
if (ub < fs) {
// File upload not yet complete,
// continue with the next chunk:
upload();
} else {
dfd.resolveWith(
o.context,
[result, textStatus, jqXHR]
);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
o.jqXHR = jqXHR;
o.textStatus = textStatus;
o.errorThrown = errorThrown;
that._trigger('chunkfail', null, o);
that._trigger('chunkalways', null, o);
dfd.rejectWith(
o.context,
[jqXHR, textStatus, errorThrown]
);
})
.always(function () {
that._deinitProgressListener(o);
});
};
this._enhancePromise(promise);
promise.abort = function () {
return jqXHR.abort();
};
upload();
return promise;
},
_beforeSend: function (e, data) {
if (this._active === 0) {
// the start callback is triggered when an upload starts
// and no other uploads are currently running,
// equivalent to the global ajaxStart event:
this._trigger('start');
// Set timer for global bitrate progress calculation:
this._bitrateTimer = new this._BitrateTimer();
// Reset the global progress values:
this._progress.loaded = this._progress.total = 0;
this._progress.bitrate = 0;
}
// Make sure the container objects for the .response() and
// .progress() methods on the data object are available
// and reset to their initial state:
this._initResponseObject(data);
this._initProgressObject(data);
data._progress.loaded = data.loaded = data.uploadedBytes || 0;
data._progress.total = data.total = this._getTotal(data.files) || 1;
data._progress.bitrate = data.bitrate = 0;
this._active += 1;
// Initialize the global progress values:
this._progress.loaded += data.loaded;
this._progress.total += data.total;
},
_onDone: function (result, textStatus, jqXHR, options) {
var total = options._progress.total,
response = options._response;
if (options._progress.loaded < total) {
// Create a progress event if no final progress event
// with loaded equaling total has been triggered:
this._onProgress($.Event('progress', {
lengthComputable: true,
loaded: total,
total: total
}), options);
}
response.result = options.result = result;
response.textStatus = options.textStatus = textStatus;
response.jqXHR = options.jqXHR = jqXHR;
this._trigger('done', null, options);
},
_onFail: function (jqXHR, textStatus, errorThrown, options) {
var response = options._response;
if (options.recalculateProgress) {
// Remove the failed (error or abort) file upload from
// the global progress calculation:
this._progress.loaded -= options._progress.loaded;
this._progress.total -= options._progress.total;
}
response.jqXHR = options.jqXHR = jqXHR;
response.textStatus = options.textStatus = textStatus;
response.errorThrown = options.errorThrown = errorThrown;
this._trigger('fail', null, options);
},
_onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
// jqXHRorResult, textStatus and jqXHRorError are added to the
// options object via done and fail callbacks
this._trigger('always', null, options);
},
_onSend: function (e, data) {
if (!data.submit) {
this._addConvenienceMethods(e, data);
}
var that = this,
jqXHR,
aborted,
slot,
pipe,
options = that._getAJAXSettings(data),
send = function () {
that._sending += 1;
// Set timer for bitrate progress calculation:
options._bitrateTimer = new that._BitrateTimer();
jqXHR = jqXHR || (
((aborted || that._trigger(
'send',
$.Event('send', {delegatedEvent: e}),
options
) === false) &&
that._getXHRPromise(false, options.context, aborted)) ||
that._chunkedUpload(options) || $.ajax(options)
).done(function (result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
}).always(function (jqXHRorResult, textStatus, jqXHRorError) {
that._deinitProgressListener(options);
that._onAlways(
jqXHRorResult,
textStatus,
jqXHRorError,
options
);
that._sending -= 1;
that._active -= 1;
if (options.limitConcurrentUploads &&
options.limitConcurrentUploads > that._sending) {
// Start the next queued upload,
// that has not been aborted:
var nextSlot = that._slots.shift();
while (nextSlot) {
if (that._getDeferredState(nextSlot) === 'pending') {
nextSlot.resolve();
break;
}
nextSlot = that._slots.shift();
}
}
if (that._active === 0) {
// The stop callback is triggered when all uploads have
// been completed, equivalent to the global ajaxStop event:
that._trigger('stop');
}
});
return jqXHR;
};
this._beforeSend(e, options);
if (this.options.sequentialUploads ||
(this.options.limitConcurrentUploads &&
this.options.limitConcurrentUploads <= this._sending)) {
if (this.options.limitConcurrentUploads > 1) {
slot = $.Deferred();
this._slots.push(slot);
pipe = slot.then(send);
} else {
this._sequence = this._sequence.then(send, send);
pipe = this._sequence;
}
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe.abort = function () {
aborted = [undefined, 'abort', 'abort'];
if (!jqXHR) {
if (slot) {
slot.rejectWith(options.context, aborted);
}
return send();
}
return jqXHR.abort();
};
return this._enhancePromise(pipe);
}
return send();
},
_onAdd: function (e, data) {
var that = this,
result = true,
options = $.extend({}, this.options, data),
files = data.files,
filesLength = files.length,
limit = options.limitMultiFileUploads,
limitSize = options.limitMultiFileUploadSize,
overhead = options.limitMultiFileUploadSizeOverhead,
batchSize = 0,
paramName = this._getParamName(options),
paramNameSet,
paramNameSlice,
fileSet,
i,
j = 0;
if (!filesLength) {
return false;
}
if (limitSize && files[0].size === undefined) {
limitSize = undefined;
}
if (!(options.singleFileUploads || limit || limitSize) ||
!this._isXHRUpload(options)) {
fileSet = [files];
paramNameSet = [paramName];
} else if (!(options.singleFileUploads || limitSize) && limit) {
fileSet = [];
paramNameSet = [];
for (i = 0; i < filesLength; i += limit) {
fileSet.push(files.slice(i, i + limit));
paramNameSlice = paramName.slice(i, i + limit);
if (!paramNameSlice.length) {
paramNameSlice = paramName;
}
paramNameSet.push(paramNameSlice);
}
} else if (!options.singleFileUploads && limitSize) {
fileSet = [];
paramNameSet = [];
for (i = 0; i < filesLength; i = i + 1) {
batchSize += files[i].size + overhead;
if (i + 1 === filesLength ||
((batchSize + files[i + 1].size + overhead) > limitSize) ||
(limit && i + 1 - j >= limit)) {
fileSet.push(files.slice(j, i + 1));
paramNameSlice = paramName.slice(j, i + 1);
if (!paramNameSlice.length) {
paramNameSlice = paramName;
}
paramNameSet.push(paramNameSlice);
j = i + 1;
batchSize = 0;
}
}
} else {
paramNameSet = paramName;
}
data.originalFiles = files;
$.each(fileSet || files, function (index, element) {
var newData = $.extend({}, data);
newData.files = fileSet ? element : [element];
newData.paramName = paramNameSet[index];
that._initResponseObject(newData);
that._initProgressObject(newData);
that._addConvenienceMethods(e, newData);
result = that._trigger(
'add',
$.Event('add', {delegatedEvent: e}),
newData
);
return result;
});
return result;
},
_replaceFileInput: function (data) {
var input = data.fileInput,
inputClone = input.clone(true),
restoreFocus = input.is(document.activeElement);
// Add a reference for the new cloned file input to the data argument:
data.fileInputClone = inputClone;
$('').append(inputClone)[0].reset();
// Detaching allows to insert the fileInput on another form
// without loosing the file input value:
input.after(inputClone).detach();
// If the fileInput had focus before it was detached,
// restore focus to the inputClone.
if (restoreFocus) {
inputClone.focus();
}
// Avoid memory leaks with the detached file input:
$.cleanData(input.unbind('remove'));
// Replace the original file input element in the fileInput
// elements set with the clone, which has been copied including
// event handlers:
this.options.fileInput = this.options.fileInput.map(function (i, el) {
if (el === input[0]) {
return inputClone[0];
}
return el;
});
// If the widget has been initialized on the file input itself,
// override this.element with the file input clone:
if (input[0] === this.element[0]) {
this.element = inputClone;
}
},
_handleFileTreeEntry: function (entry, path) {
var that = this,
dfd = $.Deferred(),
entries = [],
dirReader,
errorHandler = function (e) {
if (e && !e.entry) {
e.entry = entry;
}
// Since $.when returns immediately if one
// Deferred is rejected, we use resolve instead.
// This allows valid files and invalid items
// to be returned together in one set:
dfd.resolve([e]);
},
successHandler = function (entries) {
that._handleFileTreeEntries(
entries,
path + entry.name + '/'
).done(function (files) {
dfd.resolve(files);
}).fail(errorHandler);
},
readEntries = function () {
dirReader.readEntries(function (results) {
if (!results.length) {
successHandler(entries);
} else {
entries = entries.concat(results);
readEntries();
}
}, errorHandler);
};
path = path || '';
if (entry.isFile) {
if (entry._file) {
// Workaround for Chrome bug #149735
entry._file.relativePath = path;
dfd.resolve(entry._file);
} else {
entry.file(function (file) {
file.relativePath = path;
dfd.resolve(file);
}, errorHandler);
}
} else if (entry.isDirectory) {
dirReader = entry.createReader();
readEntries();
} else {
// Return an empty list for file system items
// other than files or directories:
dfd.resolve([]);
}
return dfd.promise();
},
_handleFileTreeEntries: function (entries, path) {
var that = this;
return $.when.apply(
$,
$.map(entries, function (entry) {
return that._handleFileTreeEntry(entry, path);
})
).then(function () {
return Array.prototype.concat.apply(
[],
arguments
);
});
},
_getDroppedFiles: function (dataTransfer) {
dataTransfer = dataTransfer || {};
var items = dataTransfer.items;
if (items && items.length && (items[0].webkitGetAsEntry ||
items[0].getAsEntry)) {
return this._handleFileTreeEntries(
$.map(items, function (item) {
var entry;
if (item.webkitGetAsEntry) {
entry = item.webkitGetAsEntry();
if (entry) {
// Workaround for Chrome bug #149735:
entry._file = item.getAsFile();
}
return entry;
}
return item.getAsEntry();
})
);
}
return $.Deferred().resolve(
$.makeArray(dataTransfer.files)
).promise();
},
_getSingleFileInputFiles: function (fileInput) {
fileInput = $(fileInput);
var entries = fileInput.prop('webkitEntries') ||
fileInput.prop('entries'),
files,
value;
if (entries && entries.length) {
return this._handleFileTreeEntries(entries);
}
files = $.makeArray(fileInput.prop('files'));
if (!files.length) {
value = fileInput.prop('value');
if (!value) {
return $.Deferred().resolve([]).promise();
}
// If the files property is not available, the browser does not
// support the File API and we add a pseudo File object with
// the input value as name with path information removed:
files = [{name: value.replace(/^.*\\/, '')}];
} else if (files[0].name === undefined && files[0].fileName) {
// File normalization for Safari 4 and Firefox 3:
$.each(files, function (index, file) {
file.name = file.fileName;
file.size = file.fileSize;
});
}
return $.Deferred().resolve(files).promise();
},
_getFileInputFiles: function (fileInput) {
if (!(fileInput instanceof $) || fileInput.length === 1) {
return this._getSingleFileInputFiles(fileInput);
}
return $.when.apply(
$,
$.map(fileInput, this._getSingleFileInputFiles)
).then(function () {
return Array.prototype.concat.apply(
[],
arguments
);
});
},
_onChange: function (e) {
var that = this,
data = {
fileInput: $(e.target),
form: $(e.target.form)
};
this._getFileInputFiles(data.fileInput).always(function (files) {
data.files = files;
if (that.options.replaceFileInput) {
that._replaceFileInput(data);
}
if (that._trigger(
'change',
$.Event('change', {delegatedEvent: e}),
data
) !== false) {
that._onAdd(e, data);
}
});
},
_onPaste: function (e) {
var items = e.originalEvent && e.originalEvent.clipboardData &&
e.originalEvent.clipboardData.items,
data = {files: []};
if (items && items.length) {
$.each(items, function (index, item) {
var file = item.getAsFile && item.getAsFile();
if (file) {
data.files.push(file);
}
});
if (this._trigger(
'paste',
$.Event('paste', {delegatedEvent: e}),
data
) !== false) {
this._onAdd(e, data);
}
}
},
_onDrop: function (e) {
e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
var that = this,
dataTransfer = e.dataTransfer,
data = {};
if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
e.preventDefault();
this._getDroppedFiles(dataTransfer).always(function (files) {
data.files = files;
if (that._trigger(
'drop',
$.Event('drop', {delegatedEvent: e}),
data
) !== false) {
that._onAdd(e, data);
}
});
}
},
_onDragOver: getDragHandler('dragover'),
_onDragEnter: getDragHandler('dragenter'),
_onDragLeave: getDragHandler('dragleave'),
_initEventHandlers: function () {
if (this._isXHRUpload(this.options)) {
this._on(this.options.dropZone, {
dragover: this._onDragOver,
drop: this._onDrop,
// event.preventDefault() on dragenter is required for IE10+:
dragenter: this._onDragEnter,
// dragleave is not required, but added for completeness:
dragleave: this._onDragLeave
});
this._on(this.options.pasteZone, {
paste: this._onPaste
});
}
if ($.support.fileInput) {
this._on(this.options.fileInput, {
change: this._onChange
});
}
},
_destroyEventHandlers: function () {
this._off(this.options.dropZone, 'dragenter dragleave dragover drop');
this._off(this.options.pasteZone, 'paste');
this._off(this.options.fileInput, 'change');
},
_destroy: function () {
this._destroyEventHandlers();
},
_setOption: function (key, value) {
var reinit = $.inArray(key, this._specialOptions) !== -1;
if (reinit) {
this._destroyEventHandlers();
}
this._super(key, value);
if (reinit) {
this._initSpecialOptions();
this._initEventHandlers();
}
},
_initSpecialOptions: function () {
var options = this.options;
if (options.fileInput === undefined) {
options.fileInput = this.element.is('input[type="file"]') ?
this.element : this.element.find('input[type="file"]');
} else if (!(options.fileInput instanceof $)) {
options.fileInput = $(options.fileInput);
}
if (!(options.dropZone instanceof $)) {
options.dropZone = $(options.dropZone);
}
if (!(options.pasteZone instanceof $)) {
options.pasteZone = $(options.pasteZone);
}
},
_getRegExp: function (str) {
var parts = str.split('/'),
modifiers = parts.pop();
parts.shift();
return new RegExp(parts.join('/'), modifiers);
},
_isRegExpOption: function (key, value) {
return key !== 'url' && $.type(value) === 'string' &&
/^\/.*\/[igm]{0,3}$/.test(value);
},
_initDataAttributes: function () {
var that = this,
options = this.options,
data = this.element.data();
// Initialize options set via HTML5 data-attributes:
$.each(
this.element[0].attributes,
function (index, attr) {
var key = attr.name.toLowerCase(),
value;
if (/^data-/.test(key)) {
// Convert hyphen-ated key to camelCase:
key = key.slice(5).replace(/-[a-z]/g, function (str) {
return str.charAt(1).toUpperCase();
});
value = data[key];
if (that._isRegExpOption(key, value)) {
value = that._getRegExp(value);
}
options[key] = value;
}
}
);
},
_create: function () {
this._initDataAttributes();
this._initSpecialOptions();
this._slots = [];
this._sequence = this._getXHRPromise(true);
this._sending = this._active = 0;
this._initProgressObject(this);
this._initEventHandlers();
},
// This method is exposed to the widget API and allows to query
// the number of active uploads:
active: function () {
return this._active;
},
// This method is exposed to the widget API and allows to query
// the widget upload progress.
// It returns an object with loaded, total and bitrate properties
// for the running uploads:
progress: function () {
return this._progress;
},
// This method is exposed to the widget API and allows adding files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('add', {files: filesList});
add: function (data) {
var that = this;
if (!data || this.options.disabled) {
return;
}
if (data.fileInput && !data.files) {
this._getFileInputFiles(data.fileInput).always(function (files) {
data.files = files;
that._onAdd(null, data);
});
} else {
data.files = $.makeArray(data.files);
this._onAdd(null, data);
}
},
// This method is exposed to the widget API and allows sending files
// using the fileupload API. The data parameter accepts an object which
// must have a files or fileInput property and can contain additional options:
// .fileupload('send', {files: filesList});
// The method returns a Promise object for the file upload call.
send: function (data) {
if (data && !this.options.disabled) {
if (data.fileInput && !data.files) {
var that = this,
dfd = $.Deferred(),
promise = dfd.promise(),
jqXHR,
aborted;
promise.abort = function () {
aborted = true;
if (jqXHR) {
return jqXHR.abort();
}
dfd.reject(null, 'abort', 'abort');
return promise;
};
this._getFileInputFiles(data.fileInput).always(
function (files) {
if (aborted) {
return;
}
if (!files.length) {
dfd.reject();
return;
}
data.files = files;
jqXHR = that._onSend(null, data);
jqXHR.then(
function (result, textStatus, jqXHR) {
dfd.resolve(result, textStatus, jqXHR);
},
function (jqXHR, textStatus, errorThrown) {
dfd.reject(jqXHR, textStatus, errorThrown);
}
);
}
);
return this._enhancePromise(promise);
}
data.files = $.makeArray(data.files);
if (data.files.length) {
return this._onSend(null, data);
}
}
return this._getXHRPromise(false, data && data.context);
}
});
}));
/*
PDFObject v2.1.1
https://github.com/pipwerks/PDFObject
Copyright (c) 2008-2018 Philip Hutchison
MIT-style license: http://pipwerks.mit-license.org/
UMD module pattern from https://github.com/umdjs/umd/blob/master/templates/returnExports.js
*/
(function(root,factory){if(typeof define==='function'&&define.amd){define([],factory);}else if(typeof module==='object'&&module.exports){module.exports=factory();}else{root.PDFObject=factory();}}(this,function(){"use strict";if(typeof window==="undefined"||typeof navigator==="undefined"){return false;}
var pdfobjectversion="2.1.1",ua=window.navigator.userAgent,supportsPDFs,isIE,supportsPdfMimeType=(typeof navigator.mimeTypes['application/pdf']!=="undefined"),supportsPdfActiveX,isModernBrowser=(function(){return(typeof window.Promise!=="undefined");})(),isFirefox=(function(){return(ua.indexOf("irefox")!==-1);})(),isFirefoxWithPDFJS=(function(){if(!isFirefox){return false;}
return(parseInt(ua.split("rv:")[1].split(".")[0],10)>18);})(),isIOS=(function(){return(/iphone|ipad|ipod/i.test(ua.toLowerCase()));})(),createAXO,buildFragmentString,log,embedError,embed,getTargetElement,generatePDFJSiframe,generateEmbedElement;createAXO=function(type){var ax;try{ax=new ActiveXObject(type);}catch(e){ax=null;}
return ax;};isIE=function(){return!!(window.ActiveXObject||"ActiveXObject"in window);};supportsPdfActiveX=function(){return!!(createAXO("AcroPDF.PDF")||createAXO("PDF.PdfCtrl"));};supportsPDFs=(!isIOS&&(isFirefoxWithPDFJS||supportsPdfMimeType||(isIE()&&supportsPdfActiveX())));buildFragmentString=function(pdfParams){var string="",prop;if(pdfParams){for(prop in pdfParams){if(pdfParams.hasOwnProperty(prop)){string+=encodeURIComponent(prop)+"="+encodeURIComponent(pdfParams[prop])+"&";}}
if(string){string="#"+string;string=string.slice(0,string.length-1);}}
return string;};log=function(msg){if(typeof console!=="undefined"&&console.log){console.log("[PDFObject] "+msg);}};embedError=function(msg){log(msg);return false;};getTargetElement=function(targetSelector){var targetNode=document.body;if(typeof targetSelector==="string"){targetNode=document.querySelector(targetSelector);}else if(typeof jQuery!=="undefined"&&targetSelector instanceof jQuery&&targetSelector.length){targetNode=targetSelector.get(0);}else if(typeof targetSelector.nodeType!=="undefined"&&targetSelector.nodeType===1){targetNode=targetSelector;}
return targetNode;};generatePDFJSiframe=function(targetNode,url,pdfOpenFragment,PDFJS_URL,id){var fullURL=PDFJS_URL+"?file="+encodeURIComponent(url)+pdfOpenFragment;var scrollfix=(isIOS)?"-webkit-overflow-scrolling: touch; overflow-y: scroll; ":"overflow: hidden; ";var iframe="
";targetNode.className+=" pdfobject-container";targetNode.style.position="relative";targetNode.style.overflow="auto";targetNode.innerHTML=iframe;return targetNode.getElementsByTagName("iframe")[0];};generateEmbedElement=function(targetNode,targetSelector,url,pdfOpenFragment,width,height,id){var style="";if(targetSelector&&targetSelector!==document.body){style="width: "+width+"; height: "+height+";";}else{style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100%; height: 100%;";}
targetNode.className+=" pdfobject-container";targetNode.innerHTML=" ";return targetNode.getElementsByTagName("embed")[0];};embed=function(url,targetSelector,options){if(typeof url!=="string"){return embedError("URL is not valid");}
targetSelector=(typeof targetSelector!=="undefined")?targetSelector:false;options=(typeof options!=="undefined")?options:{};var id=(options.id&&typeof options.id==="string")?"id='"+options.id+"'":"",page=(options.page)?options.page:false,pdfOpenParams=(options.pdfOpenParams)?options.pdfOpenParams:{},fallbackLink=(typeof options.fallbackLink!=="undefined")?options.fallbackLink:true,width=(options.width)?options.width:"100%",height=(options.height)?options.height:"100%",assumptionMode=(typeof options.assumptionMode==="boolean")?options.assumptionMode:true,forcePDFJS=(typeof options.forcePDFJS==="boolean")?options.forcePDFJS:false,PDFJS_URL=(options.PDFJS_URL)?options.PDFJS_URL:false,targetNode=getTargetElement(targetSelector),fallbackHTML="",pdfOpenFragment="",fallbackHTML_default="This browser does not support inline PDFs. Please download the PDF to view it: Download PDF
";if(!targetNode){return embedError("Target element cannot be determined");}
if(page){pdfOpenParams.page=page;}
pdfOpenFragment=buildFragmentString(pdfOpenParams);if(forcePDFJS&&PDFJS_URL){return generatePDFJSiframe(targetNode,url,pdfOpenFragment,PDFJS_URL,id);}else if(supportsPDFs||(assumptionMode&&isModernBrowser&&!isIOS)){return generateEmbedElement(targetNode,targetSelector,url,pdfOpenFragment,width,height,id);}else if(PDFJS_URL){return generatePDFJSiframe(targetNode,url,pdfOpenFragment,PDFJS_URL,id);}else{if(fallbackLink){fallbackHTML=(typeof fallbackLink==="string")?fallbackLink:fallbackHTML_default;targetNode.innerHTML=fallbackHTML.replace(/\[url\]/g,url);}
return embedError("This browser does not support embedded PDFs");}};return{embed:function(a,b,c){return embed(a,b,c);},pdfobjectversion:(function(){return pdfobjectversion;})(),supportsPDFs:(function(){return supportsPDFs;})()};}));
/*
* jQuery Iframe Transport Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, require, window, document, JSON */
;(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(require('jquery'));
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0,
jsonAPI = $,
jsonParse = 'parseJSON';
if ('JSON' in window && 'parse' in JSON) {
jsonAPI = JSON;
jsonParse = 'parse';
}
// The iframe transport accepts four additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
// options.initialIframeSrc: the URL of the initial iframe src,
// by default set to "javascript:false;"
$.ajaxTransport('iframe', function (options) {
if (options.async) {
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6:
/*jshint scripturl: true */
var initialIframeSrc = options.initialIframeSrc || 'javascript:false;',
/*jshint scripturl: false */
form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
counter += 1;
iframe = $(
''
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('')
.appendTo(form);
window.setTimeout(function () {
// Removing the form in a setTimeout call
// allows Chrome's developer tools to display
// the response result
form.remove();
}, 0);
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$(' ')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
// Remove the HTML5 form attribute from the input(s):
options.fileInput.removeAttr('form');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
// Restore the original name and form properties:
$(input)
.prop('name', clone.prop('name'))
.attr('form', clone.attr('form'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', initialIframeSrc);
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, xml
// and script.
// Please note that the Content-Type for JSON responses has to be text/plain
// or text/html, if the browser doesn't include application/json in the
// Accept header, else IE will show a download dialog.
// The Content-Type for XML responses on the other hand has to be always
// application/xml or text/xml, so IE properly parses the XML response.
// See also
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && jsonAPI[jsonParse]($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe xml': function (iframe) {
var xmlDoc = iframe && iframe[0];
return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
$.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
$(xmlDoc.body).html());
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
}));
/*!
* @fileOverview TouchSwipe - jQuery Plugin
* @version 1.6.18
*
* @author Matt Bryson http://www.github.com/mattbryson
* @see https://github.com/mattbryson/TouchSwipe-Jquery-Plugin
* @see http://labs.rampinteractive.co.uk/touchSwipe/
* @see http://plugins.jquery.com/project/touchSwipe
* @license
* Copyright (c) 2010-2015 Matt Bryson
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
/*
*
* Changelog
* $Date: 2010-12-12 (Wed, 12 Dec 2010) $
* $version: 1.0.0
* $version: 1.0.1 - removed multibyte comments
*
* $Date: 2011-21-02 (Mon, 21 Feb 2011) $
* $version: 1.1.0 - added allowPageScroll property to allow swiping and scrolling of page
* - changed handler signatures so one handler can be used for multiple events
* $Date: 2011-23-02 (Wed, 23 Feb 2011) $
* $version: 1.2.0 - added click handler. This is fired if the user simply clicks and does not swipe. The event object and click target are passed to handler.
* - If you use the http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ plugin, you can also assign jQuery mouse events to children of a touchSwipe object.
* $version: 1.2.1 - removed console log!
*
* $version: 1.2.2 - Fixed bug where scope was not preserved in callback methods.
*
* $Date: 2011-28-04 (Thurs, 28 April 2011) $
* $version: 1.2.4 - Changed licence terms to be MIT or GPL inline with jQuery. Added check for support of touch events to stop non compatible browsers erroring.
*
* $Date: 2011-27-09 (Tues, 27 September 2011) $
* $version: 1.2.5 - Added support for testing swipes with mouse on desktop browser (thanks to https://github.com/joelhy)
*
* $Date: 2012-14-05 (Mon, 14 May 2012) $
* $version: 1.2.6 - Added timeThreshold between start and end touch, so user can ignore slow swipes (thanks to Mark Chase). Default is null, all swipes are detected
*
* $Date: 2012-05-06 (Tues, 05 June 2012) $
* $version: 1.2.7 - Changed time threshold to have null default for backwards compatibility. Added duration param passed back in events, and refactored how time is handled.
*
* $Date: 2012-05-06 (Tues, 05 June 2012) $
* $version: 1.2.8 - Added the possibility to return a value like null or false in the trigger callback. In that way we can control when the touch start/move should take effect or not (simply by returning in some cases return null; or return false;) This effects the ontouchstart/ontouchmove event.
*
* $Date: 2012-06-06 (Wed, 06 June 2012) $
* $version: 1.3.0 - Refactored whole plugin to allow for methods to be executed, as well as exposed defaults for user override. Added 'enable', 'disable', and 'destroy' methods
*
* $Date: 2012-05-06 (Fri, 05 June 2012) $
* $version: 1.3.1 - Bug fixes - bind() with false as last argument is no longer supported in jQuery 1.6, also, if you just click, the duration is now returned correctly.
*
* $Date: 2012-29-07 (Sun, 29 July 2012) $
* $version: 1.3.2 - Added fallbackToMouseEvents option to NOT capture mouse events on non touch devices.
* - Added "all" fingers value to the fingers property, so any combination of fingers triggers the swipe, allowing event handlers to check the finger count
*
* $Date: 2012-09-08 (Thurs, 9 Aug 2012) $
* $version: 1.3.3 - Code tidy prep for minefied version
*
* $Date: 2012-04-10 (wed, 4 Oct 2012) $
* $version: 1.4.0 - Added pinch support, pinchIn and pinchOut
*
* $Date: 2012-11-10 (Thurs, 11 Oct 2012) $
* $version: 1.5.0 - Added excludedElements, a jquery selector that specifies child elements that do NOT trigger swipes. By default, this is .noSwipe
*
* $Date: 2012-22-10 (Mon, 22 Oct 2012) $
* $version: 1.5.1 - Fixed bug with jQuery 1.8 and trailing comma in excludedElements
* - Fixed bug with IE and eventPreventDefault()
* $Date: 2013-01-12 (Fri, 12 Jan 2013) $
* $version: 1.6.0 - Fixed bugs with pinching, mainly when both pinch and swipe enabled, as well as adding time threshold for multifinger gestures, so releasing one finger beofre the other doesnt trigger as single finger gesture.
* - made the demo site all static local HTML pages so they can be run locally by a developer
* - added jsDoc comments and added documentation for the plugin
* - code tidy
* - added triggerOnTouchLeave property that will end the event when the user swipes off the element.
* $Date: 2013-03-23 (Sat, 23 Mar 2013) $
* $version: 1.6.1 - Added support for ie8 touch events
* $version: 1.6.2 - Added support for events binding with on / off / bind in jQ for all callback names.
* - Deprecated the 'click' handler in favour of tap.
* - added cancelThreshold property
* - added option method to update init options at runtime
* $version 1.6.3 - added doubletap, longtap events and longTapThreshold, doubleTapThreshold property
*
* $Date: 2013-04-04 (Thurs, 04 April 2013) $
* $version 1.6.4 - Fixed bug with cancelThreshold introduced in 1.6.3, where swipe status no longer fired start event, and stopped once swiping back.
*
* $Date: 2013-08-24 (Sat, 24 Aug 2013) $
* $version 1.6.5 - Merged a few pull requests fixing various bugs, added AMD support.
*
* $Date: 2014-06-04 (Wed, 04 June 2014) $
* $version 1.6.6 - Merge of pull requests.
* - IE10 touch support
* - Only prevent default event handling on valid swipe
* - Separate license/changelog comment
* - Detect if the swipe is valid at the end of the touch event.
* - Pass fingerdata to event handlers.
* - Add 'hold' gesture
* - Be more tolerant about the tap distance
* - Typos and minor fixes
*
* $Date: 2015-22-01 (Thurs, 22 Jan 2015) $
* $version 1.6.7 - Added patch from https://github.com/mattbryson/TouchSwipe-Jquery-Plugin/issues/206 to fix memory leak
*
* $Date: 2015-2-2 (Mon, 2 Feb 2015) $
* $version 1.6.8 - Added preventDefaultEvents option to proxy events regardless.
* - Fixed issue with swipe and pinch not triggering at the same time
*
* $Date: 2015-9-6 (Tues, 9 June 2015) $
* $version 1.6.9 - Added PR from jdalton/hybrid to fix pointer events
* - Added scrolling demo
* - Added version property to plugin
*
* $Date: 2015-1-10 (Wed, 1 October 2015) $
* $version 1.6.10 - Added PR from beatspace to fix tap events
* $version 1.6.11 - Added PRs from indri-indri ( Doc tidyup), kkirsche ( Bower tidy up ), UziTech (preventDefaultEvents fixes )
* - Allowed setting multiple options via .swipe("options", options_hash) and more simply .swipe(options_hash) or exisitng instances
* $version 1.6.12 - Fixed bug with multi finger releases above 2 not triggering events
*
* $Date: 2015-12-18 (Fri, 18 December 2015) $
* $version 1.6.13 - Added PRs
* - Fixed #267 allowPageScroll not working correctly
* $version 1.6.14 - Fixed #220 / #248 doubletap not firing with swipes, #223 commonJS compatible
* $version 1.6.15 - More bug fixes
*
* $Date: 2016-04-29 (Fri, 29 April 2016) $
* $version 1.6.16 - Swipes with 0 distance now allow default events to trigger. So tapping any form elements or A tags will allow default interaction, but swiping will trigger a swipe.
Removed the a, input, select etc from the excluded Children list as the 0 distance tap solves that issue.
* $Date: 2016-05-19 (Fri, 29 April 2016) $
* $version 1.6.17 - Fixed context issue when calling instance methods via $("selector").swipe("method");
* $version 1.6.18 - now honors fallbackToMouseEvents=false for MS Pointer events when a Mouse is used.
*/
/**
* See (http://jquery.com/).
* @name $
* @class
* See the jQuery Library (http://jquery.com/) for full details. This just
* documents the function and classes that are added to jQuery by this plug-in.
*/
/**
* See (http://jquery.com/)
* @name fn
* @class
* See the jQuery Library (http://jquery.com/) for full details. This just
* documents the function and classes that are added to jQuery by this plug-in.
* @memberOf $
*/
(function (factory) {
if (typeof define === 'function' && define.amd && define.amd.jQuery) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof module !== 'undefined' && module.exports) {
// CommonJS Module
factory(require("jquery"));
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
"use strict";
//Constants
var VERSION = "1.6.18",
LEFT = "left",
RIGHT = "right",
UP = "up",
DOWN = "down",
IN = "in",
OUT = "out",
NONE = "none",
AUTO = "auto",
SWIPE = "swipe",
PINCH = "pinch",
TAP = "tap",
DOUBLE_TAP = "doubletap",
LONG_TAP = "longtap",
HOLD = "hold",
HORIZONTAL = "horizontal",
VERTICAL = "vertical",
ALL_FINGERS = "all",
DOUBLE_TAP_THRESHOLD = 10,
PHASE_START = "start",
PHASE_MOVE = "move",
PHASE_END = "end",
PHASE_CANCEL = "cancel",
SUPPORTS_TOUCH = 'ontouchstart' in window,
SUPPORTS_POINTER_IE10 = window.navigator.msPointerEnabled && !window.PointerEvent && !SUPPORTS_TOUCH,
SUPPORTS_POINTER = (window.PointerEvent || window.navigator.msPointerEnabled) && !SUPPORTS_TOUCH,
PLUGIN_NS = 'TouchSwipe';
/**
* The default configuration, and available options to configure touch swipe with.
* You can set the default values by updating any of the properties prior to instantiation.
* @name $.fn.swipe.defaults
* @namespace
* @property {int} [fingers=1] The number of fingers to detect in a swipe. Any swipes that do not meet this requirement will NOT trigger swipe handlers.
* @property {int} [threshold=75] The number of pixels that the user must move their finger by before it is considered a swipe.
* @property {int} [cancelThreshold=null] The number of pixels that the user must move their finger back from the original swipe direction to cancel the gesture.
* @property {int} [pinchThreshold=20] The number of pixels that the user must pinch their finger by before it is considered a pinch.
* @property {int} [maxTimeThreshold=null] Time, in milliseconds, between touchStart and touchEnd must NOT exceed in order to be considered a swipe.
* @property {int} [fingerReleaseThreshold=250] Time in milliseconds between releasing multiple fingers. If 2 fingers are down, and are released one after the other, if they are within this threshold, it counts as a simultaneous release.
* @property {int} [longTapThreshold=500] Time in milliseconds between tap and release for a long tap
* @property {int} [doubleTapThreshold=200] Time in milliseconds between 2 taps to count as a double tap
* @property {function} [swipe=null] A handler to catch all swipes. See {@link $.fn.swipe#event:swipe}
* @property {function} [swipeLeft=null] A handler that is triggered for "left" swipes. See {@link $.fn.swipe#event:swipeLeft}
* @property {function} [swipeRight=null] A handler that is triggered for "right" swipes. See {@link $.fn.swipe#event:swipeRight}
* @property {function} [swipeUp=null] A handler that is triggered for "up" swipes. See {@link $.fn.swipe#event:swipeUp}
* @property {function} [swipeDown=null] A handler that is triggered for "down" swipes. See {@link $.fn.swipe#event:swipeDown}
* @property {function} [swipeStatus=null] A handler triggered for every phase of the swipe. See {@link $.fn.swipe#event:swipeStatus}
* @property {function} [pinchIn=null] A handler triggered for pinch in events. See {@link $.fn.swipe#event:pinchIn}
* @property {function} [pinchOut=null] A handler triggered for pinch out events. See {@link $.fn.swipe#event:pinchOut}
* @property {function} [pinchStatus=null] A handler triggered for every phase of a pinch. See {@link $.fn.swipe#event:pinchStatus}
* @property {function} [tap=null] A handler triggered when a user just taps on the item, rather than swipes it. If they do not move, tap is triggered, if they do move, it is not.
* @property {function} [doubleTap=null] A handler triggered when a user double taps on the item. The delay between taps can be set with the doubleTapThreshold property. See {@link $.fn.swipe.defaults#doubleTapThreshold}
* @property {function} [longTap=null] A handler triggered when a user long taps on the item. The delay between start and end can be set with the longTapThreshold property. See {@link $.fn.swipe.defaults#longTapThreshold}
* @property (function) [hold=null] A handler triggered when a user reaches longTapThreshold on the item. See {@link $.fn.swipe.defaults#longTapThreshold}
* @property {boolean} [triggerOnTouchEnd=true] If true, the swipe events are triggered when the touch end event is received (user releases finger). If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
* @property {boolean} [triggerOnTouchLeave=false] If true, then when the user leaves the swipe object, the swipe will end and trigger appropriate handlers.
* @property {string|undefined} [allowPageScroll='auto'] How the browser handles page scrolls when the user is swiping on a touchSwipe object. See {@link $.fn.swipe.pageScroll}.
"auto" : all undefined swipes will cause the page to scroll in that direction.
"none" : the page will not scroll when user swipes.
"horizontal" : will force page to scroll on horizontal swipes.
"vertical" : will force page to scroll on vertical swipes.
* @property {boolean} [fallbackToMouseEvents=true] If true mouse events are used when run on a non touch device, false will stop swipes being triggered by mouse events on non touch devices.
* @property {string} [excludedElements=".noSwipe"] A jquery selector that specifies child elements that do NOT trigger swipes. By default this excludes elements with the class .noSwipe .
* @property {boolean} [preventDefaultEvents=true] by default default events are cancelled, so the page doesn't move. You can disable this so both native events fire as well as your handlers.
*/
var defaults = {
fingers: 1,
threshold: 75,
cancelThreshold: null,
pinchThreshold: 20,
maxTimeThreshold: null,
fingerReleaseThreshold: 250,
longTapThreshold: 500,
doubleTapThreshold: 200,
swipe: null,
swipeLeft: null,
swipeRight: null,
swipeUp: null,
swipeDown: null,
swipeStatus: null,
pinchIn: null,
pinchOut: null,
pinchStatus: null,
click: null, //Deprecated since 1.6.2
tap: null,
doubleTap: null,
longTap: null,
hold: null,
triggerOnTouchEnd: true,
triggerOnTouchLeave: false,
allowPageScroll: "auto",
fallbackToMouseEvents: true,
excludedElements: ".noSwipe",
preventDefaultEvents: true
};
/**
* Applies TouchSwipe behaviour to one or more jQuery objects.
* The TouchSwipe plugin can be instantiated via this method, or methods within
* TouchSwipe can be executed via this method as per jQuery plugin architecture.
* An existing plugin can have its options changed simply by re calling .swipe(options)
* @see TouchSwipe
* @class
* @param {Mixed} method If the current DOMNode is a TouchSwipe object, and method is a TouchSwipe method, then
* the method is executed, and any following arguments are passed to the TouchSwipe method.
* If method is an object, then the TouchSwipe class is instantiated on the current DOMNode, passing the
* configuration properties defined in the object. See TouchSwipe
*
*/
$.fn.swipe = function (method) {
var $this = $(this),
plugin = $this.data(PLUGIN_NS);
//Check if we are already instantiated and trying to execute a method
if (plugin && typeof method === 'string') {
if (plugin[method]) {
return plugin[method].apply(plugin, Array.prototype.slice.call(arguments, 1));
} else {
$.error('Method ' + method + ' does not exist on jQuery.swipe');
}
}
//Else update existing plugin with new options hash
else if (plugin && typeof method === 'object') {
plugin['option'].apply(plugin, arguments);
}
//Else not instantiated and trying to pass init object (or nothing)
else if (!plugin && (typeof method === 'object' || !method)) {
return init.apply(this, arguments);
}
return $this;
};
/**
* The version of the plugin
* @readonly
*/
$.fn.swipe.version = VERSION;
//Expose our defaults so a user could override the plugin defaults
$.fn.swipe.defaults = defaults;
/**
* The phases that a touch event goes through. The phase is passed to the event handlers.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @property {string} PHASE_START Constant indicating the start phase of the touch event. Value is "start".
* @property {string} PHASE_MOVE Constant indicating the move phase of the touch event. Value is "move".
* @property {string} PHASE_END Constant indicating the end phase of the touch event. Value is "end".
* @property {string} PHASE_CANCEL Constant indicating the cancel phase of the touch event. Value is "cancel".
*/
$.fn.swipe.phases = {
PHASE_START: PHASE_START,
PHASE_MOVE: PHASE_MOVE,
PHASE_END: PHASE_END,
PHASE_CANCEL: PHASE_CANCEL
};
/**
* The direction constants that are passed to the event handlers.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @property {string} LEFT Constant indicating the left direction. Value is "left".
* @property {string} RIGHT Constant indicating the right direction. Value is "right".
* @property {string} UP Constant indicating the up direction. Value is "up".
* @property {string} DOWN Constant indicating the down direction. Value is "cancel".
* @property {string} IN Constant indicating the in direction. Value is "in".
* @property {string} OUT Constant indicating the out direction. Value is "out".
*/
$.fn.swipe.directions = {
LEFT: LEFT,
RIGHT: RIGHT,
UP: UP,
DOWN: DOWN,
IN: IN,
OUT: OUT
};
/**
* The page scroll constants that can be used to set the value of allowPageScroll option
* These properties are read only
* @namespace
* @readonly
* @see $.fn.swipe.defaults#allowPageScroll
* @property {string} NONE Constant indicating no page scrolling is allowed. Value is "none".
* @property {string} HORIZONTAL Constant indicating horizontal page scrolling is allowed. Value is "horizontal".
* @property {string} VERTICAL Constant indicating vertical page scrolling is allowed. Value is "vertical".
* @property {string} AUTO Constant indicating either horizontal or vertical will be allowed, depending on the swipe handlers registered. Value is "auto".
*/
$.fn.swipe.pageScroll = {
NONE: NONE,
HORIZONTAL: HORIZONTAL,
VERTICAL: VERTICAL,
AUTO: AUTO
};
/**
* Constants representing the number of fingers used in a swipe. These are used to set both the value of fingers in the
* options object, as well as the value of the fingers event property.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @see $.fn.swipe.defaults#fingers
* @property {string} ONE Constant indicating 1 finger is to be detected / was detected. Value is 1.
* @property {string} TWO Constant indicating 2 fingers are to be detected / were detected. Value is 2.
* @property {string} THREE Constant indicating 3 finger are to be detected / were detected. Value is 3.
* @property {string} FOUR Constant indicating 4 finger are to be detected / were detected. Not all devices support this. Value is 4.
* @property {string} FIVE Constant indicating 5 finger are to be detected / were detected. Not all devices support this. Value is 5.
* @property {string} ALL Constant indicating any combination of finger are to be detected. Value is "all".
*/
$.fn.swipe.fingers = {
ONE: 1,
TWO: 2,
THREE: 3,
FOUR: 4,
FIVE: 5,
ALL: ALL_FINGERS
};
/**
* Initialise the plugin for each DOM element matched
* This creates a new instance of the main TouchSwipe class for each DOM element, and then
* saves a reference to that instance in the elements data property.
* @internal
*/
function init(options) {
//Prep and extend the options
if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) {
options.allowPageScroll = NONE;
}
//Check for deprecated options
//Ensure that any old click handlers are assigned to the new tap, unless we have a tap
if (options.click !== undefined && options.tap === undefined) {
options.tap = options.click;
}
if (!options) {
options = {};
}
//pass empty object so we dont modify the defaults
options = $.extend({}, $.fn.swipe.defaults, options);
//For each element instantiate the plugin
return this.each(function () {
var $this = $(this);
//Check we havent already initialised the plugin
var plugin = $this.data(PLUGIN_NS);
if (!plugin) {
plugin = new TouchSwipe(this, options);
$this.data(PLUGIN_NS, plugin);
}
});
}
/**
* Main TouchSwipe Plugin Class.
* Do not use this to construct your TouchSwipe object, use the jQuery plugin method $.fn.swipe(); {@link $.fn.swipe}
* @private
* @name TouchSwipe
* @param {DOMNode} element The HTML DOM object to apply to plugin to
* @param {Object} options The options to configure the plugin with. @link {$.fn.swipe.defaults}
* @see $.fh.swipe.defaults
* @see $.fh.swipe
* @class
*/
function TouchSwipe(element, options) {
//take a local/instacne level copy of the options - should make it this.options really...
var options = $.extend({}, options);
var useTouchEvents = (SUPPORTS_TOUCH || SUPPORTS_POINTER || !options.fallbackToMouseEvents),
START_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerDown' : 'pointerdown') : 'touchstart') : 'mousedown',
MOVE_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerMove' : 'pointermove') : 'touchmove') : 'mousemove',
END_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerUp' : 'pointerup') : 'touchend') : 'mouseup',
LEAVE_EV = useTouchEvents ? (SUPPORTS_POINTER ? 'mouseleave' : null) : 'mouseleave', //we manually detect leave on touch devices, so null event here
CANCEL_EV = (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerCancel' : 'pointercancel') : 'touchcancel');
//touch properties
var distance = 0,
direction = null,
currentDirection = null,
duration = 0,
startTouchesDistance = 0,
endTouchesDistance = 0,
pinchZoom = 1,
pinchDistance = 0,
pinchDirection = 0,
maximumsMap = null;
//jQuery wrapped element for this instance
var $element = $(element);
//Current phase of th touch cycle
var phase = "start";
// the current number of fingers being used.
var fingerCount = 0;
//track mouse points / delta
var fingerData = {};
//track times
var startTime = 0,
endTime = 0,
previousTouchEndTime = 0,
fingerCountAtRelease = 0,
doubleTapStartTime = 0;
//Timeouts
var singleTapTimeout = null,
holdTimeout = null;
// Add gestures to all swipable areas if supported
try {
$element.on(START_EV, touchStart);
$element.on(CANCEL_EV, touchCancel);
} catch (e) {
$.error('events not supported ' + START_EV + ',' + CANCEL_EV + ' on jQuery.swipe');
}
//
//Public methods
//
/**
* re-enables the swipe plugin with the previous configuration
* @function
* @name $.fn.swipe#enable
* @return {DOMNode} The Dom element that was registered with TouchSwipe
* @example $("#element").swipe("enable");
*/
this.enable = function () {
//Incase we are already enabled, clean up...
this.disable();
$element.on(START_EV, touchStart);
$element.on(CANCEL_EV, touchCancel);
return $element;
};
/**
* disables the swipe plugin
* @function
* @name $.fn.swipe#disable
* @return {DOMNode} The Dom element that is now registered with TouchSwipe
* @example $("#element").swipe("disable");
*/
this.disable = function () {
removeListeners();
return $element;
};
/**
* Destroy the swipe plugin completely. To use any swipe methods, you must re initialise the plugin.
* @function
* @name $.fn.swipe#destroy
* @example $("#element").swipe("destroy");
*/
this.destroy = function () {
removeListeners();
$element.data(PLUGIN_NS, null);
$element = null;
};
/**
* Allows run time updating of the swipe configuration options.
* @function
* @name $.fn.swipe#option
* @param {String} property The option property to get or set, or a has of multiple options to set
* @param {Object} [value] The value to set the property to
* @return {Object} If only a property name is passed, then that property value is returned. If nothing is passed the current options hash is returned.
* @example $("#element").swipe("option", "threshold"); // return the threshold
* @example $("#element").swipe("option", "threshold", 100); // set the threshold after init
* @example $("#element").swipe("option", {threshold:100, fingers:3} ); // set multiple properties after init
* @example $("#element").swipe({threshold:100, fingers:3} ); // set multiple properties after init - the "option" method is optional!
* @example $("#element").swipe("option"); // Return the current options hash
* @see $.fn.swipe.defaults
*
*/
this.option = function (property, value) {
if (typeof property === 'object') {
options = $.extend(options, property);
} else if (options[property] !== undefined) {
if (value === undefined) {
return options[property];
} else {
options[property] = value;
}
} else if (!property) {
return options;
} else {
$.error('Option ' + property + ' does not exist on jQuery.swipe.options');
}
return null;
}
//
// Private methods
//
//
// EVENTS
//
/**
* Event handler for a touch start event.
* Stops the default click event from triggering and stores where we touched
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchStart(jqEvent) {
//If we already in a touch event (a finger already in use) then ignore subsequent ones..
if (getTouchInProgress()) {
return;
}
//Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe
if ($(jqEvent.target).closest(options.excludedElements, $element).length > 0) {
return;
}
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
//If we have a pointer event, whoes type is 'mouse' and we have said NO mouse events, then dont do anything.
if (event.pointerType && event.pointerType == "mouse" && options.fallbackToMouseEvents == false) {
return;
};
var ret,
touches = event.touches,
evt = touches ? touches[0] : event;
phase = PHASE_START;
//If we support touches, get the finger count
if (touches) {
// get the total number of fingers touching the screen
fingerCount = touches.length;
}
//Else this is the desktop, so stop the browser from dragging content
else if (options.preventDefaultEvents !== false) {
jqEvent.preventDefault(); //call this on jq event so we are cross browser
}
//clear vars..
distance = 0;
direction = null;
currentDirection = null;
pinchDirection = null;
duration = 0;
startTouchesDistance = 0;
endTouchesDistance = 0;
pinchZoom = 1;
pinchDistance = 0;
maximumsMap = createMaximumsData();
cancelMultiFingerRelease();
//Create the default finger data
createFingerData(0, evt);
// check the number of fingers is what we are looking for, or we are capturing pinches
if (!touches || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) {
// get the coordinates of the touch
startTime = getTimeStamp();
if (fingerCount == 2) {
//Keep track of the initial pinch distance, so we can calculate the diff later
//Store second finger data as start
createFingerData(1, touches[1]);
startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
}
if (options.swipeStatus || options.pinchStatus) {
ret = triggerHandler(event, phase);
}
} else {
//A touch with more or less than the fingers we are looking for, so cancel
ret = false;
}
//If we have a return value from the users handler, then return and cancel
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
return ret;
} else {
if (options.hold) {
holdTimeout = setTimeout($.proxy(function () {
//Trigger the event
$element.trigger('hold', [event.target]);
//Fire the callback
if (options.hold) {
ret = options.hold.call($element, event, event.target);
}
}, this), options.longTapThreshold);
}
setTouchInProgress(true);
}
return null;
};
/**
* Event handler for a touch move event.
* If we change fingers during move, then cancel the event
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchMove(jqEvent) {
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
//If we are ending, cancelling, or within the threshold of 2 fingers being released, don't track anything..
if (phase === PHASE_END || phase === PHASE_CANCEL || inMultiFingerRelease())
return;
var ret,
touches = event.touches,
evt = touches ? touches[0] : event;
//Update the finger data
var currentFinger = updateFingerData(evt);
endTime = getTimeStamp();
if (touches) {
fingerCount = touches.length;
}
if (options.hold) {
clearTimeout(holdTimeout);
}
phase = PHASE_MOVE;
//If we have 2 fingers get Touches distance as well
if (fingerCount == 2) {
//Keep track of the initial pinch distance, so we can calculate the diff later
//We do this here as well as the start event, in case they start with 1 finger, and the press 2 fingers
if (startTouchesDistance == 0) {
//Create second finger if this is the first time...
createFingerData(1, touches[1]);
startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
} else {
//Else just update the second finger
updateFingerData(touches[1]);
endTouchesDistance = calculateTouchesDistance(fingerData[0].end, fingerData[1].end);
pinchDirection = calculatePinchDirection(fingerData[0].end, fingerData[1].end);
}
pinchZoom = calculatePinchZoom(startTouchesDistance, endTouchesDistance);
pinchDistance = Math.abs(startTouchesDistance - endTouchesDistance);
}
if ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !touches || hasPinches()) {
//The overall direction of the swipe. From start to now.
direction = calculateDirection(currentFinger.start, currentFinger.end);
//The immediate direction of the swipe, direction between the last movement and this one.
currentDirection = calculateDirection(currentFinger.last, currentFinger.end);
//Check if we need to prevent default event (page scroll / pinch zoom) or not
validateDefaultEvent(jqEvent, currentDirection);
//Distance and duration are all off the main finger
distance = calculateDistance(currentFinger.start, currentFinger.end);
duration = calculateDuration();
//Cache the maximum distance we made in this direction
setMaxDistance(direction, distance);
//Trigger status handler
ret = triggerHandler(event, phase);
//If we trigger end events when threshold are met, or trigger events when touch leaves element
if (!options.triggerOnTouchEnd || options.triggerOnTouchLeave) {
var inBounds = true;
//If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit)
if (options.triggerOnTouchLeave) {
var bounds = getbounds(this);
inBounds = isInBounds(currentFinger.end, bounds);
}
//Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these..
if (!options.triggerOnTouchEnd && inBounds) {
phase = getNextPhase(PHASE_MOVE);
}
//We end if out of bounds here, so set current phase to END, and check if its modified
else if (options.triggerOnTouchLeave && !inBounds) {
phase = getNextPhase(PHASE_END);
}
if (phase == PHASE_CANCEL || phase == PHASE_END) {
triggerHandler(event, phase);
}
}
} else {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
}
/**
* Event handler for a touch end event.
* Calculate the direction and trigger events
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchEnd(jqEvent) {
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent,
touches = event.touches;
//If we are still in a touch with the device wait a fraction and see if the other finger comes up
//if it does within the threshold, then we treat it as a multi release, not a single release and end the touch / swipe
if (touches) {
if (touches.length && !inMultiFingerRelease()) {
startMultiFingerRelease(event);
return true;
} else if (touches.length && inMultiFingerRelease()) {
return true;
}
}
//If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release.
//This is used to allow 2 fingers to release fractionally after each other, whilst maintaining the event as containing 2 fingers, not 1
if (inMultiFingerRelease()) {
fingerCount = fingerCountAtRelease;
}
//Set end of swipe
endTime = getTimeStamp();
//Get duration incase move was never fired
duration = calculateDuration();
//If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase
if (didSwipeBackToCancel() || !validateSwipeDistance()) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
} else if (options.triggerOnTouchEnd || (options.triggerOnTouchEnd === false && phase === PHASE_MOVE)) {
//call this on jq event so we are cross browser
if (options.preventDefaultEvents !== false && jqEvent.cancelable !== false) {
jqEvent.preventDefault();
}
phase = PHASE_END;
triggerHandler(event, phase);
}
//Special cases - A tap should always fire on touch end regardless,
//So here we manually trigger the tap end handler by itself
//We dont run trigger handler as it will re-trigger events that may have fired already
else if (!options.triggerOnTouchEnd && hasTap()) {
//Trigger the pinch events...
phase = PHASE_END;
triggerHandlerForGesture(event, phase, TAP);
} else if (phase === PHASE_MOVE) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
setTouchInProgress(false);
return null;
}
/**
* Event handler for a touch cancel event.
* Clears current vars
* @inner
*/
function touchCancel() {
// reset the variables back to default values
fingerCount = 0;
endTime = 0;
startTime = 0;
startTouchesDistance = 0;
endTouchesDistance = 0;
pinchZoom = 1;
//If we were in progress of tracking a possible multi touch end, then re set it.
cancelMultiFingerRelease();
setTouchInProgress(false);
}
/**
* Event handler for a touch leave event.
* This is only triggered on desktops, in touch we work this out manually
* as the touchleave event is not supported in webkit
* @inner
*/
function touchLeave(jqEvent) {
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
//If we have the trigger on leave property set....
if (options.triggerOnTouchLeave) {
phase = getNextPhase(PHASE_END);
triggerHandler(event, phase);
}
}
/**
* Removes all listeners that were associated with the plugin
* @inner
*/
function removeListeners() {
$element.off(START_EV, touchStart);
$element.off(CANCEL_EV, touchCancel);
$element.off(MOVE_EV, touchMove);
$element.off(END_EV, touchEnd);
//we only have leave events on desktop, we manually calculate leave on touch as its not supported in webkit
if (LEAVE_EV) {
$element.off(LEAVE_EV, touchLeave);
}
setTouchInProgress(false);
}
/**
* Checks if the time and distance thresholds have been met, and if so then the appropriate handlers are fired.
*/
function getNextPhase(currentPhase) {
var nextPhase = currentPhase;
// Ensure we have valid swipe (under time and over distance and check if we are out of bound...)
var validTime = validateSwipeTime();
var validDistance = validateSwipeDistance();
var didCancel = didSwipeBackToCancel();
//If we have exceeded our time, then cancel
if (!validTime || didCancel) {
nextPhase = PHASE_CANCEL;
}
//Else if we are moving, and have reached distance then end
else if (validDistance && currentPhase == PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave)) {
nextPhase = PHASE_END;
}
//Else if we have ended by leaving and didn't reach distance, then cancel
else if (!validDistance && currentPhase == PHASE_END && options.triggerOnTouchLeave) {
nextPhase = PHASE_CANCEL;
}
return nextPhase;
}
/**
* Trigger the relevant event handler
* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
* @param {object} event the original event object
* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
* @inner
*/
function triggerHandler(event, phase) {
var ret,
touches = event.touches;
// SWIPE GESTURES
if (didSwipe() || hasSwipes()) {
ret = triggerHandlerForGesture(event, phase, SWIPE);
}
// PINCH GESTURES (if the above didn't cancel)
if ((didPinch() || hasPinches()) && ret !== false) {
ret = triggerHandlerForGesture(event, phase, PINCH);
}
// CLICK / TAP (if the above didn't cancel)
if (didDoubleTap() && ret !== false) {
//Trigger the tap events...
ret = triggerHandlerForGesture(event, phase, DOUBLE_TAP);
}
// CLICK / TAP (if the above didn't cancel)
else if (didLongTap() && ret !== false) {
//Trigger the tap events...
ret = triggerHandlerForGesture(event, phase, LONG_TAP);
}
// CLICK / TAP (if the above didn't cancel)
else if (didTap() && ret !== false) {
//Trigger the tap event..
ret = triggerHandlerForGesture(event, phase, TAP);
}
// If we are cancelling the gesture, then manually trigger the reset handler
if (phase === PHASE_CANCEL) {
touchCancel(event);
}
// If we are ending the gesture, then manually trigger the reset handler IF all fingers are off
if (phase === PHASE_END) {
//If we support touch, then check that all fingers are off before we cancel
if (touches) {
if (!touches.length) {
touchCancel(event);
}
} else {
touchCancel(event);
}
}
return ret;
}
/**
* Trigger the relevant event handler
* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
* @param {object} event the original event object
* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
* @param {string} gesture the gesture to trigger a handler for : PINCH or SWIPE {@link $.fn.swipe.gestures}
* @return Boolean False, to indicate that the event should stop propagation, or void.
* @inner
*/
function triggerHandlerForGesture(event, phase, gesture) {
var ret;
//SWIPES....
if (gesture == SWIPE) {
//Trigger status every time..
$element.trigger('swipeStatus', [phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData, currentDirection]);
if (options.swipeStatus) {
ret = options.swipeStatus.call($element, event, phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData, currentDirection);
//If the status cancels, then dont run the subsequent event handlers..
if (ret === false) return false;
}
if (phase == PHASE_END && validateSwipe()) {
//Cancel any taps that were in progress...
clearTimeout(singleTapTimeout);
clearTimeout(holdTimeout);
$element.trigger('swipe', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
if (options.swipe) {
ret = options.swipe.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
//If the status cancels, then dont run the subsequent event handlers..
if (ret === false) return false;
}
//trigger direction specific event handlers
switch (direction) {
case LEFT:
$element.trigger('swipeLeft', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
if (options.swipeLeft) {
ret = options.swipeLeft.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
}
break;
case RIGHT:
$element.trigger('swipeRight', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
if (options.swipeRight) {
ret = options.swipeRight.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
}
break;
case UP:
$element.trigger('swipeUp', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
if (options.swipeUp) {
ret = options.swipeUp.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
}
break;
case DOWN:
$element.trigger('swipeDown', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
if (options.swipeDown) {
ret = options.swipeDown.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
}
break;
}
}
}
//PINCHES....
if (gesture == PINCH) {
$element.trigger('pinchStatus', [phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
if (options.pinchStatus) {
ret = options.pinchStatus.call($element, event, phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
//If the status cancels, then dont run the subsequent event handlers..
if (ret === false) return false;
}
if (phase == PHASE_END && validatePinch()) {
switch (pinchDirection) {
case IN:
$element.trigger('pinchIn', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
if (options.pinchIn) {
ret = options.pinchIn.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
}
break;
case OUT:
$element.trigger('pinchOut', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
if (options.pinchOut) {
ret = options.pinchOut.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
}
break;
}
}
}
if (gesture == TAP) {
if (phase === PHASE_CANCEL || phase === PHASE_END) {
clearTimeout(singleTapTimeout);
clearTimeout(holdTimeout);
//If we are also looking for doubelTaps, wait incase this is one...
if (hasDoubleTap() && !inDoubleTap()) {
doubleTapStartTime = getTimeStamp();
//Now wait for the double tap timeout, and trigger this single tap
//if its not cancelled by a double tap
singleTapTimeout = setTimeout($.proxy(function () {
doubleTapStartTime = null;
$element.trigger('tap', [event.target]);
if (options.tap) {
ret = options.tap.call($element, event, event.target);
}
}, this), options.doubleTapThreshold);
} else {
doubleTapStartTime = null;
$element.trigger('tap', [event.target]);
if (options.tap) {
ret = options.tap.call($element, event, event.target);
}
}
}
} else if (gesture == DOUBLE_TAP) {
if (phase === PHASE_CANCEL || phase === PHASE_END) {
clearTimeout(singleTapTimeout);
clearTimeout(holdTimeout);
doubleTapStartTime = null;
$element.trigger('doubletap', [event.target]);
if (options.doubleTap) {
ret = options.doubleTap.call($element, event, event.target);
}
}
} else if (gesture == LONG_TAP) {
if (phase === PHASE_CANCEL || phase === PHASE_END) {
clearTimeout(singleTapTimeout);
doubleTapStartTime = null;
$element.trigger('longtap', [event.target]);
if (options.longTap) {
ret = options.longTap.call($element, event, event.target);
}
}
}
return ret;
}
//
// GESTURE VALIDATION
//
/**
* Checks the user has swipe far enough
* @return Boolean if threshold has been set, return true if the threshold was met, else false.
* If no threshold was set, then we return true.
* @inner
*/
function validateSwipeDistance() {
var valid = true;
//If we made it past the min swipe distance..
if (options.threshold !== null) {
valid = distance >= options.threshold;
}
return valid;
}
/**
* Checks the user has swiped back to cancel.
* @return Boolean if cancelThreshold has been set, return true if the cancelThreshold was met, else false.
* If no cancelThreshold was set, then we return true.
* @inner
*/
function didSwipeBackToCancel() {
var cancelled = false;
if (options.cancelThreshold !== null && direction !== null) {
cancelled = (getMaxDistance(direction) - distance) >= options.cancelThreshold;
}
return cancelled;
}
/**
* Checks the user has pinched far enough
* @return Boolean if pinchThreshold has been set, return true if the threshold was met, else false.
* If no threshold was set, then we return true.
* @inner
*/
function validatePinchDistance() {
if (options.pinchThreshold !== null) {
return pinchDistance >= options.pinchThreshold;
}
return true;
}
/**
* Checks that the time taken to swipe meets the minimum / maximum requirements
* @return Boolean
* @inner
*/
function validateSwipeTime() {
var result;
//If no time set, then return true
if (options.maxTimeThreshold) {
if (duration >= options.maxTimeThreshold) {
result = false;
} else {
result = true;
}
} else {
result = true;
}
return result;
}
/**
* Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
* This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
* @param {object} jqEvent The normalised jQuery representation of the event object.
* @param {string} direction The direction of the event. See {@link $.fn.swipe.directions}
* @see $.fn.swipe.directions
* @inner
*/
function validateDefaultEvent(jqEvent, direction) {
//If the option is set, allways allow the event to bubble up (let user handle weirdness)
if (options.preventDefaultEvents === false) {
return;
}
if (options.allowPageScroll === NONE) {
jqEvent.preventDefault();
} else {
var auto = options.allowPageScroll === AUTO;
switch (direction) {
case LEFT:
if ((options.swipeLeft && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
jqEvent.preventDefault();
}
break;
case RIGHT:
if ((options.swipeRight && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
jqEvent.preventDefault();
}
break;
case UP:
if ((options.swipeUp && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
jqEvent.preventDefault();
}
break;
case DOWN:
if ((options.swipeDown && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
jqEvent.preventDefault();
}
break;
case NONE:
break;
}
}
}
// PINCHES
/**
* Returns true of the current pinch meets the thresholds
* @return Boolean
* @inner
*/
function validatePinch() {
var hasCorrectFingerCount = validateFingers();
var hasEndPoint = validateEndPoint();
var hasCorrectDistance = validatePinchDistance();
return hasCorrectFingerCount && hasEndPoint && hasCorrectDistance;
}
/**
* Returns true if any Pinch events have been registered
* @return Boolean
* @inner
*/
function hasPinches() {
//Enure we dont return 0 or null for false values
return !!(options.pinchStatus || options.pinchIn || options.pinchOut);
}
/**
* Returns true if we are detecting pinches, and have one
* @return Boolean
* @inner
*/
function didPinch() {
//Enure we dont return 0 or null for false values
return !!(validatePinch() && hasPinches());
}
// SWIPES
/**
* Returns true if the current swipe meets the thresholds
* @return Boolean
* @inner
*/
function validateSwipe() {
//Check validity of swipe
var hasValidTime = validateSwipeTime();
var hasValidDistance = validateSwipeDistance();
var hasCorrectFingerCount = validateFingers();
var hasEndPoint = validateEndPoint();
var didCancel = didSwipeBackToCancel();
// if the user swiped more than the minimum length, perform the appropriate action
// hasValidDistance is null when no distance is set
var valid = !didCancel && hasEndPoint && hasCorrectFingerCount && hasValidDistance && hasValidTime;
return valid;
}
/**
* Returns true if any Swipe events have been registered
* @return Boolean
* @inner
*/
function hasSwipes() {
//Enure we dont return 0 or null for false values
return !!(options.swipe || options.swipeStatus || options.swipeLeft || options.swipeRight || options.swipeUp || options.swipeDown);
}
/**
* Returns true if we are detecting swipes and have one
* @return Boolean
* @inner
*/
function didSwipe() {
//Enure we dont return 0 or null for false values
return !!(validateSwipe() && hasSwipes());
}
/**
* Returns true if we have matched the number of fingers we are looking for
* @return Boolean
* @inner
*/
function validateFingers() {
//The number of fingers we want were matched, or on desktop we ignore
return ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH);
}
/**
* Returns true if we have an end point for the swipe
* @return Boolean
* @inner
*/
function validateEndPoint() {
//We have an end value for the finger
return fingerData[0].end.x !== 0;
}
// TAP / CLICK
/**
* Returns true if a click / tap events have been registered
* @return Boolean
* @inner
*/
function hasTap() {
//Enure we dont return 0 or null for false values
return !!(options.tap);
}
/**
* Returns true if a double tap events have been registered
* @return Boolean
* @inner
*/
function hasDoubleTap() {
//Enure we dont return 0 or null for false values
return !!(options.doubleTap);
}
/**
* Returns true if any long tap events have been registered
* @return Boolean
* @inner
*/
function hasLongTap() {
//Enure we dont return 0 or null for false values
return !!(options.longTap);
}
/**
* Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
* @return Boolean
* @inner
*/
function validateDoubleTap() {
if (doubleTapStartTime == null) {
return false;
}
var now = getTimeStamp();
return (hasDoubleTap() && ((now - doubleTapStartTime) <= options.doubleTapThreshold));
}
/**
* Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
* @return Boolean
* @inner
*/
function inDoubleTap() {
return validateDoubleTap();
}
/**
* Returns true if we have a valid tap
* @return Boolean
* @inner
*/
function validateTap() {
return ((fingerCount === 1 || !SUPPORTS_TOUCH) && (isNaN(distance) || distance < options.threshold));
}
/**
* Returns true if we have a valid long tap
* @return Boolean
* @inner
*/
function validateLongTap() {
//slight threshold on moving finger
return ((duration > options.longTapThreshold) && (distance < DOUBLE_TAP_THRESHOLD));
}
/**
* Returns true if we are detecting taps and have one
* @return Boolean
* @inner
*/
function didTap() {
//Enure we dont return 0 or null for false values
return !!(validateTap() && hasTap());
}
/**
* Returns true if we are detecting double taps and have one
* @return Boolean
* @inner
*/
function didDoubleTap() {
//Enure we dont return 0 or null for false values
return !!(validateDoubleTap() && hasDoubleTap());
}
/**
* Returns true if we are detecting long taps and have one
* @return Boolean
* @inner
*/
function didLongTap() {
//Enure we dont return 0 or null for false values
return !!(validateLongTap() && hasLongTap());
}
// MULTI FINGER TOUCH
/**
* Starts tracking the time between 2 finger releases, and keeps track of how many fingers we initially had up
* @inner
*/
function startMultiFingerRelease(event) {
previousTouchEndTime = getTimeStamp();
fingerCountAtRelease = event.touches.length + 1;
}
/**
* Cancels the tracking of time between 2 finger releases, and resets counters
* @inner
*/
function cancelMultiFingerRelease() {
previousTouchEndTime = 0;
fingerCountAtRelease = 0;
}
/**
* Checks if we are in the threshold between 2 fingers being released
* @return Boolean
* @inner
*/
function inMultiFingerRelease() {
var withinThreshold = false;
if (previousTouchEndTime) {
var diff = getTimeStamp() - previousTouchEndTime
if (diff <= options.fingerReleaseThreshold) {
withinThreshold = true;
}
}
return withinThreshold;
}
/**
* gets a data flag to indicate that a touch is in progress
* @return Boolean
* @inner
*/
function getTouchInProgress() {
//strict equality to ensure only true and false are returned
return !!($element.data(PLUGIN_NS + '_intouch') === true);
}
/**
* Sets a data flag to indicate that a touch is in progress
* @param {boolean} val The value to set the property to
* @inner
*/
function setTouchInProgress(val) {
//If destroy is called in an event handler, we have no el, and we have already cleaned up, so return.
if (!$element) { return; }
//Add or remove event listeners depending on touch status
if (val === true) {
$element.on(MOVE_EV, touchMove);
$element.on(END_EV, touchEnd);
//we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
if (LEAVE_EV) {
$element.on(LEAVE_EV, touchLeave);
}
} else {
$element.off(MOVE_EV, touchMove, false);
$element.off(END_EV, touchEnd, false);
//we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
if (LEAVE_EV) {
$element.off(LEAVE_EV, touchLeave, false);
}
}
//strict equality to ensure only true and false can update the value
$element.data(PLUGIN_NS + '_intouch', val === true);
}
/**
* Creates the finger data for the touch/finger in the event object.
* @param {int} id The id to store the finger data under (usually the order the fingers were pressed)
* @param {object} evt The event object containing finger data
* @return finger data object
* @inner
*/
function createFingerData(id, evt) {
var f = {
start: {
x: 0,
y: 0
},
last: {
x: 0,
y: 0
},
end: {
x: 0,
y: 0
}
};
f.start.x = f.last.x = f.end.x = evt.pageX || evt.clientX;
f.start.y = f.last.y = f.end.y = evt.pageY || evt.clientY;
fingerData[id] = f;
return f;
}
/**
* Updates the finger data for a particular event object
* @param {object} evt The event object containing the touch/finger data to upadte
* @return a finger data object.
* @inner
*/
function updateFingerData(evt) {
var id = evt.identifier !== undefined ? evt.identifier : 0;
var f = getFingerData(id);
if (f === null) {
f = createFingerData(id, evt);
}
f.last.x = f.end.x;
f.last.y = f.end.y;
f.end.x = evt.pageX || evt.clientX;
f.end.y = evt.pageY || evt.clientY;
return f;
}
/**
* Returns a finger data object by its event ID.
* Each touch event has an identifier property, which is used
* to track repeat touches
* @param {int} id The unique id of the finger in the sequence of touch events.
* @return a finger data object.
* @inner
*/
function getFingerData(id) {
return fingerData[id] || null;
}
/**
* Sets the maximum distance swiped in the given direction.
* If the new value is lower than the current value, the max value is not changed.
* @param {string} direction The direction of the swipe
* @param {int} distance The distance of the swipe
* @inner
*/
function setMaxDistance(direction, distance) {
if (direction == NONE) return;
distance = Math.max(distance, getMaxDistance(direction));
maximumsMap[direction].distance = distance;
}
/**
* gets the maximum distance swiped in the given direction.
* @param {string} direction The direction of the swipe
* @return int The distance of the swipe
* @inner
*/
function getMaxDistance(direction) {
if (maximumsMap[direction]) return maximumsMap[direction].distance;
return undefined;
}
/**
* Creats a map of directions to maximum swiped values.
* @return Object A dictionary of maximum values, indexed by direction.
* @inner
*/
function createMaximumsData() {
var maxData = {};
maxData[LEFT] = createMaximumVO(LEFT);
maxData[RIGHT] = createMaximumVO(RIGHT);
maxData[UP] = createMaximumVO(UP);
maxData[DOWN] = createMaximumVO(DOWN);
return maxData;
}
/**
* Creates a map maximum swiped values for a given swipe direction
* @param {string} The direction that these values will be associated with
* @return Object Maximum values
* @inner
*/
function createMaximumVO(dir) {
return {
direction: dir,
distance: 0
}
}
//
// MATHS / UTILS
//
/**
* Calculate the duration of the swipe
* @return int
* @inner
*/
function calculateDuration() {
return endTime - startTime;
}
/**
* Calculate the distance between 2 touches (pinch)
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int;
* @inner
*/
function calculateTouchesDistance(startPoint, endPoint) {
var diffX = Math.abs(startPoint.x - endPoint.x);
var diffY = Math.abs(startPoint.y - endPoint.y);
return Math.round(Math.sqrt(diffX * diffX + diffY * diffY));
}
/**
* Calculate the zoom factor between the start and end distances
* @param {int} startDistance Distance (between 2 fingers) the user started pinching at
* @param {int} endDistance Distance (between 2 fingers) the user ended pinching at
* @return float The zoom value from 0 to 1.
* @inner
*/
function calculatePinchZoom(startDistance, endDistance) {
var percent = (endDistance / startDistance) * 1;
return percent.toFixed(2);
}
/**
* Returns the pinch direction, either IN or OUT for the given points
* @return string Either {@link $.fn.swipe.directions.IN} or {@link $.fn.swipe.directions.OUT}
* @see $.fn.swipe.directions
* @inner
*/
function calculatePinchDirection() {
if (pinchZoom < 1) {
return OUT;
} else {
return IN;
}
}
/**
* Calculate the length / distance of the swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int
* @inner
*/
function calculateDistance(startPoint, endPoint) {
return Math.round(Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2)));
}
/**
* Calculate the angle of the swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int
* @inner
*/
function calculateAngle(startPoint, endPoint) {
var x = startPoint.x - endPoint.x;
var y = endPoint.y - startPoint.y;
var r = Math.atan2(y, x); //radians
var angle = Math.round(r * 180 / Math.PI); //degrees
//ensure value is positive
if (angle < 0) {
angle = 360 - Math.abs(angle);
}
return angle;
}
/**
* Calculate the direction of the swipe
* This will also call calculateAngle to get the latest angle of swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return string Either {@link $.fn.swipe.directions.LEFT} / {@link $.fn.swipe.directions.RIGHT} / {@link $.fn.swipe.directions.DOWN} / {@link $.fn.swipe.directions.UP}
* @see $.fn.swipe.directions
* @inner
*/
function calculateDirection(startPoint, endPoint) {
if (comparePoints(startPoint, endPoint)) {
return NONE;
}
var angle = calculateAngle(startPoint, endPoint);
if ((angle <= 45) && (angle >= 0)) {
return LEFT;
} else if ((angle <= 360) && (angle >= 315)) {
return LEFT;
} else if ((angle >= 135) && (angle <= 225)) {
return RIGHT;
} else if ((angle > 45) && (angle < 135)) {
return DOWN;
} else {
return UP;
}
}
/**
* Returns a MS time stamp of the current time
* @return int
* @inner
*/
function getTimeStamp() {
var now = new Date();
return now.getTime();
}
/**
* Returns a bounds object with left, right, top and bottom properties for the element specified.
* @param {DomNode} The DOM node to get the bounds for.
*/
function getbounds(el) {
el = $(el);
var offset = el.offset();
var bounds = {
left: offset.left,
right: offset.left + el.outerWidth(),
top: offset.top,
bottom: offset.top + el.outerHeight()
}
return bounds;
}
/**
* Checks if the point object is in the bounds object.
* @param {object} point A point object.
* @param {int} point.x The x value of the point.
* @param {int} point.y The x value of the point.
* @param {object} bounds The bounds object to test
* @param {int} bounds.left The leftmost value
* @param {int} bounds.right The righttmost value
* @param {int} bounds.top The topmost value
* @param {int} bounds.bottom The bottommost value
*/
function isInBounds(point, bounds) {
return (point.x > bounds.left && point.x < bounds.right && point.y > bounds.top && point.y < bounds.bottom);
};
/**
* Checks if the two points are equal
* @param {object} point A point object.
* @param {object} point B point object.
* @return true of the points match
*/
function comparePoints(pointA, pointB) {
return (pointA.x == pointB.x && pointA.y == pointB.y);
}
}
/**
* A catch all handler that is triggered for all swipe directions.
* @name $.fn.swipe#swipe
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
* @param {string} currentDirection The current direction the user is swiping.
*/
/**
* A handler that is triggered for "left" swipes.
* @name $.fn.swipe#swipeLeft
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
* @param {string} currentDirection The current direction the user is swiping.
*/
/**
* A handler that is triggered for "right" swipes.
* @name $.fn.swipe#swipeRight
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
* @param {string} currentDirection The current direction the user is swiping.
*/
/**
* A handler that is triggered for "up" swipes.
* @name $.fn.swipe#swipeUp
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
* @param {string} currentDirection The current direction the user is swiping.
*/
/**
* A handler that is triggered for "down" swipes.
* @name $.fn.swipe#swipeDown
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
* @param {string} currentDirection The current direction the user is swiping.
*/
/**
* A handler triggered for every phase of the swipe. This handler is constantly fired for the duration of the pinch.
* This is triggered regardless of swipe thresholds.
* @name $.fn.swipe#swipeStatus
* @event
* @default null
* @param {EventObject} event The original event object
* @param {string} phase The phase of the swipe event. See {@link $.fn.swipe.phases}
* @param {string} direction The direction the user swiped in. This is null if the user has yet to move. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped. This is 0 if the user has yet to move.
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
* @param {string} currentDirection The current direction the user is swiping.
*/
/**
* A handler triggered for pinch in events.
* @name $.fn.swipe#pinchIn
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for pinch out events.
* @name $.fn.swipe#pinchOut
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for all pinch events. This handler is constantly fired for the duration of the pinch. This is triggered regardless of thresholds.
* @name $.fn.swipe#pinchStatus
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A click handler triggered when a user simply clicks, rather than swipes on an element.
* This is deprecated since version 1.6.2, any assignment to click will be assigned to the tap handler.
* You cannot use on to bind to this event as the default jQ click event will be triggered.
* Use the tap event instead.
* @name $.fn.swipe#click
* @event
* @deprecated since version 1.6.2, please use {@link $.fn.swipe#tap} instead
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A click / tap handler triggered when a user simply clicks or taps, rather than swipes on an element.
* @name $.fn.swipe#tap
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A double tap handler triggered when a user double clicks or taps on an element.
* You can set the time delay for a double tap with the {@link $.fn.swipe.defaults#doubleTapThreshold} property.
* Note: If you set both doubleTap and tap handlers, the tap event will be delayed by the doubleTapThreshold
* as the script needs to check if its a double tap.
* @name $.fn.swipe#doubleTap
* @see $.fn.swipe.defaults#doubleTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A long tap handler triggered once a tap has been release if the tap was longer than the longTapThreshold.
* You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
* @name $.fn.swipe#longTap
* @see $.fn.swipe.defaults#longTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A hold tap handler triggered as soon as the longTapThreshold is reached
* You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
* @name $.fn.swipe#hold
* @see $.fn.swipe.defaults#longTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
}));
//! moment.js
; (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) {
if (Object.getOwnPropertyNames) {
return (Object.getOwnPropertyNames(obj).length === 0);
} else {
var k;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
return false;
}
}
return true;
}
}
function isUndefined(input) {
return input === void 0;
}
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,
rfc2822: false,
weekdayMismatch: false
};
}
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;
};
}
function isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m);
var parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
});
var isNowValid = !isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.weekdayMismatch &&
!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;
}
// 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 = 0; i < momentProperties.length; i++) {
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 _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = new RegExp(
(this._dayOfMonthOrdinalParse.source || 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 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 defaultDayOfMonthOrdinalParse = /\d{1,2}/;
function ordinal(number) {
return this._ordinal.replace('%d', number);
}
var defaultRelativeTime = {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
ss: '%d seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
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 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 += isFunction(array[i]) ? 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]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
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;
// 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 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() && !isNaN(value)) {
if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
}
else {
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 mod(n, x) {
return ((n % x) + x) % x;
}
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;
};
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
}
// 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 isArray(this._months) ? this._months :
this._months['standalone'];
}
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 isArray(this._monthsShort) ? this._monthsShort :
this._monthsShort['standalone'];
}
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.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.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');
}
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date;
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
date = new Date(y + 400, m, d, h, M, s, ms);
if (isFinite(date.getFullYear())) {
date.setFullYear(y);
}
} else {
date = new Date(y, m, d, h, M, s, ms);
}
return date;
}
function createUTCDate(y) {
var date;
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
var args = Array.prototype.slice.call(arguments);
// preserve leap years using a full 400 year cycle, then reset
args[0] = y + 400;
date = new Date(Date.UTC.apply(null, args));
if (isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
} else {
date = new Date(Date.UTC.apply(null, arguments));
}
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;
}
// https://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 6th 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
function shiftWeekdays(ws, n) {
return ws.slice(n, 7).concat(ws.slice(0, n));
}
var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
function localeWeekdays(m, format) {
var weekdays = isArray(this._weekdays) ? this._weekdays :
this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone'];
return (m === true) ? shiftWeekdays(weekdays, this._week.dow)
: (m) ? weekdays[m.day()] : weekdays;
}
var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function localeWeekdaysShort(m) {
return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow)
: (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}
var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
function localeWeekdaysMin(m) {
return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow)
: (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.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.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('k', match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);
addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);
addParseToken(['H', 'HH'], HOUR);
addParseToken(['k', 'kk'], function (input, array, config) {
var kInput = toInt(input);
array[HOUR] = kInput === 24 ? 0 : kInput;
});
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 they want. 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);
var baseConfig = {
calendar: defaultCalendar,
longDateFormat: defaultLongDateFormat,
invalidDate: defaultInvalidDate,
ordinal: defaultOrdinal,
dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
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 globalLocale;
}
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;
var aliasedRequire = require;
aliasedRequire('./locale/' + name);
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;
}
else {
if ((typeof console !== 'undefined') && console.warn) {
//warn user if arguments are passed but the locale could not be set
console.warn('Locale ' + key + ' not found. Did you forget to load it?');
}
}
}
return globalLocale._abbr;
}
function defineLocale(name, config) {
if (config !== null) {
var locale, 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 {
locale = loadLocale(config.parentLocale);
if (locale != null) {
parentConfig = locale._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, tmpLocale, parentConfig = baseConfig;
// MERGE
tmpLocale = loadLocale(name);
if (tmpLocale != null) {
parentConfig = tmpLocale._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(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;
}
// 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, expectedWeekday, 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 != null) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
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);
expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
// 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;
}
// check for mismatching day of week
if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
getParsingFlags(config).weekdayMismatch = true;
}
}
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 beginning of week
weekday = w.e + dow;
if (w.e < 0 || w.e > 6) {
weekdayOverflow = true;
}
} else {
// default to beginning 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;
}
}
// 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;
}
}
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
var result = [
untruncateYear(yearStr),
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10)
];
if (secondStr) {
result.push(parseInt(secondStr, 10));
}
return result;
}
function untruncateYear(yearStr) {
var year = parseInt(yearStr, 10);
if (year <= 49) {
return 2000 + year;
} else if (year <= 999) {
return 1900 + year;
}
return year;
}
function preprocessRFC2822(s) {
// Remove comments and folding whitespace and replace multiple-spaces with a single space
return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function checkWeekday(weekdayStr, parsedInput, config) {
if (weekdayStr) {
// TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
if (weekdayProvided !== weekdayActual) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return false;
}
}
return true;
}
var obsOffsets = {
UT: 0,
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60
};
function calculateOffset(obsOffset, militaryOffset, numOffset) {
if (obsOffset) {
return obsOffsets[obsOffset];
} else if (militaryOffset) {
// the only allowed military tz is Z
return 0;
} else {
var hm = parseInt(numOffset, 10);
var m = hm % 100, h = (hm - m) / 100;
return h * 60 + m;
}
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i));
if (match) {
var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
if (!checkWeekday(match[1], parsedArray, config)) {
return;
}
config._a = parsedArray;
config._tzm = calculateOffset(match[8], match[9], match[10]);
config._d = createUTCDate.apply(null, config._a);
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
getParsingFlags(config).rfc2822 = true;
} 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;
} else {
return;
}
configFromRFC2822(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
// Final attempt, use Input Fallback
hooks.createFromInputFallback(config);
}
hooks.createFromInputFallback = deprecate(
'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
'discouraged 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' : ''));
}
);
// constant that refers to the ISO standard
hooks.ISO_8601 = function () { };
// constant that refers to the RFC 2822 form
hooks.RFC_2822 = 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;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(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 (isUndefined(input)) {
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 (isObject(input)) {
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());
};
var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
function isDurationValid(m) {
for (var key in m) {
if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
return false;
}
}
var unitHasDecimal = false;
for (var i = 0; i < ordering.length; ++i) {
if (m[ordering[i]]) {
if (unitHasDecimal) {
return false; // only allow non-integers for smallest unit
}
if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
unitHasDecimal = true;
}
}
}
return true;
}
function isValid$1() {
return this._isValid;
}
function createInvalid$1() {
return createDuration(NaN);
}
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
this._isValid = isDurationValid(normalizedInput);
// 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 to 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, keepMinutes) {
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 && !keepMinutes) {
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, false, true);
} 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;
createDuration.invalid = createInvalid$1;
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 = {};
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 (months) {
setMonth(mom, get(mom, 'Month') + months * isAdding);
}
if (days) {
set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
}
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * 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(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(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) {
var localFrom = isMoment(from) ? from : createLocal(from),
localTo = isMoment(to) ? to : createLocal(to);
if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
return false;
}
inclusivity = inclusivity || '()';
return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) &&
(inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, 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,
output;
if (!this.isValid()) {
return NaN;
}
that = cloneWithOffset(input, this);
if (!that.isValid()) {
return NaN;
}
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
units = normalizeUnits(units);
switch (units) {
case 'year': output = monthDiff(this, that) / 12; break;
case 'month': output = monthDiff(this, that); break;
case 'quarter': output = monthDiff(this, that) / 3; break;
case 'second': output = (this - that) / 1e3; break; // 1000
case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
default: output = this - that;
}
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(keepOffset) {
if (!this.isValid()) {
return null;
}
var utc = keepOffset !== true;
var m = utc ? this.clone().utc() : this;
if (m.year() < 0 || m.year() > 9999) {
return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
}
if (isFunction(Date.prototype.toISOString)) {
// native implementation is ~50x faster, use it when we can
if (utc) {
return this.toDate().toISOString();
} else {
return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
}
}
return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
}
/**
* 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;
}
var MS_PER_SECOND = 1000;
var MS_PER_MINUTE = 60 * MS_PER_SECOND;
var MS_PER_HOUR = 60 * MS_PER_MINUTE;
var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
// actual modulo - handles negative numbers (for dates before 1970):
function mod$1(dividend, divisor) {
return (dividend % divisor + divisor) % divisor;
}
function localStartOfDate(y, m, d) {
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return new Date(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return new Date(y, m, d).valueOf();
}
}
function utcStartOfDate(y, m, d) {
// Date.UTC remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return Date.UTC(y, m, d);
}
}
function startOf(units) {
var time;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year(), 0, 1);
break;
case 'quarter':
time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
break;
case 'month':
time = startOfDate(this.year(), this.month(), 1);
break;
case 'week':
time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
break;
case 'isoWeek':
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date());
break;
case 'hour':
time = this._d.valueOf();
time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
break;
case 'minute':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_MINUTE);
break;
case 'second':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_SECOND);
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function endOf(units) {
var time;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year() + 1, 0, 1) - 1;
break;
case 'quarter':
time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
break;
case 'month':
time = startOfDate(this.year(), this.month() + 1, 1) - 1;
break;
case 'week':
time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
break;
case 'isoWeek':
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
break;
case 'hour':
time = this._d.valueOf();
time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
break;
case 'minute':
time = this._d.valueOf();
time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
break;
case 'second':
time = this._d.valueOf();
time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
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$2() {
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');
// PRIORITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict ?
(locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0]);
});
// 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$2;
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;
proto.year = getSetYear;
proto.isLeapYear = getIsLeapYear;
proto.weekYear = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;
proto.quarter = proto.quarters = getSetQuarter;
proto.month = getSetMonth;
proto.daysInMonth = getDaysInMonth;
proto.week = proto.weeks = getSetWeek;
proto.isoWeek = proto.isoWeeks = getSetISOWeek;
proto.weeksInYear = getWeeksInYear;
proto.isoWeeksInYear = getISOWeeksInYear;
proto.date = getSetDayOfMonth;
proto.day = proto.days = getSetDayOfWeek;
proto.weekday = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear = getSetDayOfYear;
proto.hour = proto.hours = getSetHour;
proto.minute = proto.minutes = getSetMinute;
proto.second = proto.seconds = getSetSecond;
proto.millisecond = proto.milliseconds = getSetMillisecond;
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;
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;
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;
proto$1.months = localeMonths;
proto$1.monthsShort = localeMonthsShort;
proto$1.monthsParse = localeMonthsParse;
proto$1.monthsRegex = monthsRegex;
proto$1.monthsShortRegex = monthsShortRegex;
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;
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;
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', {
dayOfMonthOrdinalParse: /\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) {
if (!this.isValid()) {
return NaN;
}
var days;
var months;
var milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === 'month' || units === 'quarter' || units === 'year') {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
switch (units) {
case 'month': return months;
case 'quarter': return months / 3;
case 'year': return 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() {
if (!this.isValid()) {
return NaN;
}
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 asQuarters = makeAs('Q');
var asYears = makeAs('y');
function clone$1() {
return createDuration(this);
}
function get$2(units) {
units = normalizeUnits(units);
return this.isValid() ? this[units + 's']() : NaN;
}
function makeGetter(name) {
return function () {
return this.isValid() ? this._data[name] : NaN;
};
}
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 = {
ss: 44, // a few seconds to seconds
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.ss && ['s', seconds] ||
seconds < thresholds.s && ['ss', 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;
if (threshold === 's') {
thresholds.ss = limit - 1;
}
return true;
}
function humanize(withSuffix) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
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 sign(x) {
return ((x > 0) - (x < 0)) || +x;
}
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)
if (!this.isValid()) {
return this.localeData().invalidDate();
}
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 ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
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';
}
var totalSign = total < 0 ? '-' : '';
var ymSign = sign(this._months) !== sign(total) ? '-' : '';
var daysSign = sign(this._days) !== sign(total) ? '-' : '';
var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
return totalSign + 'P' +
(Y ? ymSign + Y + 'Y' : '') +
(M ? ymSign + M + 'M' : '') +
(D ? daysSign + D + 'D' : '') +
((h || m || s) ? 'T' : '') +
(h ? hmsSign + h + 'H' : '') +
(m ? hmsSign + m + 'M' : '') +
(s ? hmsSign + s + 'S' : '');
}
var proto$2 = Duration.prototype;
proto$2.isValid = isValid$1;
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.asQuarters = asQuarters;
proto$2.asYears = asYears;
proto$2.valueOf = valueOf$1;
proto$2._bubble = bubble;
proto$2.clone = clone$1;
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;
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.24.0';
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;
// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', //
DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', //
DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', //
DATE: 'YYYY-MM-DD', //
TIME: 'HH:mm', //
TIME_SECONDS: 'HH:mm:ss', //
TIME_MS: 'HH:mm:ss.SSS', //
WEEK: 'GGGG-[W]WW', //
MONTH: 'YYYY-MM' //
};
return hooks;
})));
/*
* @class Calendar ~jquery-calendar plugin~ (https://github.com/ArrobeFr/jquery-calendar-bs4)
* @author Developped by Arrobe (https://www.arrobe.fr)
* @license Licensed under MIT (https://github.com/ArrobeFr/jquery-calendar/blob/master/LICENSE)
*/
jQuery(document).ready(function(f){function n(e,t){if("function"==typeof moment){var n=["#C62828","#AD1457","#6A1B9A","#4527A0","#283593","#1565C0","#0277BD","#00838F","#00695C","#2E7D32","#558B2F","#9E9D24","#F9A825","#FF8F00","#EF6C00","#D84315","#4E342E","#424242","#37474F","#212121"],a=["#EF9A9A","#F48FB1","#CE93D8","#B39DDB","#9FA8DA","#90CAF9","#81D4FA","#80DEEA","#80CBC4","#A5D6A7","#C5E1A5","#E6EE9C","#FFF59D","#FFE082","#FFCC80","#FFAB91","#BCAAA4","#EEEEEE","#B0BEC5"];this.conf={locale:t.locale?t.locale:"fr",view:"week",enableKeyboard:!t.enableKeyboard||t.enableKeyboard,defaultView:{largeScreen:t.defaultView&&t.defaultView.largeScreen?t.defaultView.largeScreen:"week",smallScreen:t.defaultView&&t.defaultView.smallScreen?t.defaultView.smallScreen:"day",smallScreenThreshold:t.defaultView&&t.defaultView.smallScreenThreshold?t.defaultView.smallScreenThreshold:1e3},weekday:{timeline:{fromHour:t.weekday&&t.weekday.timeline&&t.weekday.timeline.fromHour?t.weekday.timeline.fromHour:7,toHour:t.weekday&&t.weekday.timeline&&t.weekday.timeline.toHour?t.weekday.timeline.toHour:20,intervalMinutes:t.weekday&&t.weekday.timeline&&t.weekday.timeline.intervalMinutes?t.weekday.timeline.intervalMinutes:60,format:t.weekday&&t.weekday.timeline&&t.weekday.timeline.format?t.weekday.timeline.format:"HH:mm",heightPx:t.weekday&&t.weekday.timeline&&t.weekday.timeline.heightPx?t.weekday.timeline.heightPx:50,autoResize:!t.weekday||(!t.weekday.timeline||(void 0===t.weekday.timeline.autoResize||t.weekday.timeline.autoResize))},dayline:{weekdays:t.weekday&&t.weekday.dayline&&t.weekday.dayline.weekdays?t.weekday.dayline.weekdays:[0,1,2,3,4,5,6],format:t.weekday&&t.weekday.dayline&&t.weekday.dayline.format?t.weekday.dayline.format:"dddd DD/MM",heightPx:t.weekday&&t.weekday.dayline&&t.weekday.dayline.heightPx&&t.weekday.dayline.heightPx&&31=n.closest("ul").height()/2-t.conf.weekday.timeline.heightPx?(heightPx=parseInt(n.css("top"))+parseInt(n.css("height")),n.css("z-index",10).animate({height:heightPx,top:0,width:"100%",left:0},50)):(heightPx=n.closest("ul").height()-parseInt(n.css("top")),n.css("z-index",10).animate({height:heightPx,width:"100%",left:0},50)),n.find(".event-name").removeClass("invisible"),n.find(".event-content").removeClass("invisible"))};f(self.element).off("Calendar.event-mouseenter",e).on("Calendar.event-mouseenter",e),f(self.element).off("Calendar.daynote-mouseenter",e).on("Calendar.daynote-mouseenter",e);var t=function(e,t,n){e.isDefaultPrevented()||(n.css("z-index","auto").animate({height:parseFloat(n.attr("data-height"))+"px",top:parseFloat(n.attr("data-top")),width:parseFloat(n.attr("data-width"))+"%",left:parseFloat(n.attr("data-left"))+"%"},50),n.find(".event-content").addClass("invisible"))};f(self.element).off("Calendar.event-mouseleave",t).on("Calendar.event-mouseleave",t),f(self.element).off("Calendar.daynote-mouseleave",t).on("Calendar.daynote-mouseleave",t);var n=function(e,t,n,a){e.isDefaultPrevented()||(modal=f(t.element).find("#calendar-modal"),rgb=t.hexToRgb(n.attr("data-color")),modal.css("background","rgba("+rgb.r+", "+rgb.g+", "+rgb.b+", 0.5)"),modal.find(".modal-title").append(n.attr("data-title")+" "),modal.find(".modal-body").append(f("").append(f(this).closest(".calendar-events-day").find("span").html()).append(" ").append(f("").text(n.find(".event-date").text()))),modal.find(".modal-body").append(n.find(".event-content").html()),modal.modal("show"),modal.on("hidden.bs.modal",function(e){f(e.target).find(".modal-title").html(""),f(e.target).find(".modal-body").html("")}))};f(self.element).off("Calendar.event-click",n).on("Calendar.event-click",n),f(self.element).off("Calendar.daynote-click",n).on("Calendar.daynote-click",n);var a=function(e,t,n){if(!e.isDefaultPrevented()){var a=t.element.find('.calendar-event[data-category="'+f(n).text()+'"]');"false"==f(n).attr("data-clicked")&&a.animate({opacity:0},200,function(){a.css("display","none"),f(n).css("background-color","#E0E0E0"),f(n).attr("data-clicked",!0)}),"true"==f(n).attr("data-clicked")&&(a.css("display","list-item"),f(n).css("background-color",f(n).attr("data-color")),a.animate({opacity:1},200,function(){f(n).attr("data-clicked",!1)}))}};f(self.element).off("Calendar.category-event-click",a).on("Calendar.category-event-click",a),f(self.element).off("Calendar.category-daynote-click",a).on("Calendar.category-daynote-click",a);var o=function(e,t,n){e.isDefaultPrevented()||t.element.find(".calendar-event").each(function(e,t){f(t).attr("data-category")!=n.text()&&f(t).css("opacity",.2)})};f(self.element).off("Calendar.category-event-mouseenter",o).on("Calendar.category-event-mouseenter",o),f(self.element).off("Calendar.category-daynote-mouseenter",o).on("Calendar.category-daynote-mouseenter",o);var i=function(e,t,n){e.isDefaultPrevented()||t.element.find(".calendar-event").each(function(e,t){f(t).css("opacity",1)})};f(self.element).off("Calendar.category-event-mouseleave",i).on("Calendar.category-event-mouseleave",i),f(self.element).off("Calendar.category-daynote-mouseleave",i).on("Calendar.category-daynote-mouseleave",i),this.binded=!0}},n.prototype.weekDrawTime=function(){f(this.element).append(f("",{class:"calendar-timeline"})),f(this.element).find("div.calendar-timeline").css("padding-top",this.conf.weekday.dayline.heightPx+"px");var e=this.conf.weekday.dayline.month.heightPx;this.conf.categories.enable&&(e+=30),f(this.element).find("div.calendar-timeline").css("margin-top",e+"px"),f(this.element).find("div.calendar-timeline").append(f("
")),ul=f(this.element).find("div.calendar-timeline").find("ul"),time=moment(moment()).startOf("Week"),time.add(this.conf.weekday.timeline.fromHour,"H");for(var t=(60*(this.conf.weekday.timeline.toHour+1)-60*this.conf.weekday.timeline.fromHour)/this.conf.weekday.timeline.intervalMinutes,n=0;n"),li.append(f("").text(time.format(this.conf.weekday.timeline.format))),li.height(this.conf.weekday.timeline.heightPx),ul.append(li),time.add(this.conf.weekday.timeline.intervalMinutes,"m"),n++},n.prototype.weekDrawDays=function(){f(this.element).append(f("",{class:"calendar-events"}));var e=f("
",{class:"calendar-month"}).css("height",this.conf.weekday.dayline.month.heightPx+"px").css("text-align","center").css("padding-top",(this.conf.weekday.dayline.month.heightPx-20)/2+"px");"week"==this.getView()&&(e.text(this.miscUcfirstString(moment.unix(this.conf.unixTimestamp).format(this.conf.weekday.dayline.month.format))),e.addClass("weektomonth")),"day"==this.getView()&&(e.text(this.miscUcfirstString(moment.unix(this.conf.unixTimestamp).format(this.conf.weekday.dayline.month.weekFormat))),e.addClass("daytoweek")),f(this.element).find("div.calendar-events").append(e),f(this.element).find("div.calendar-events").append(f("
")),ul=f(this.element).find("div.calendar-events").find("ul");for(var t=this.getViewDays(),n=0;n",{class:"calendar-events-day"}),li.css("width",100/t.length+"%"),(e=f("",{class:"calendar-day-header"})).height(this.conf.weekday.dayline.heightPx),0==n&&"desktop"==this.mobileQuery()&&e.append(f("
",{class:"btn btn-sm btn-light btn-move-calendar"}).attr("data-direction","left").append(f("",{class:"fas fa-arrow-left"}))),e.append(f("").addClass("weektoday").css("width","100%").text(this.miscUcfirstString(time.format(this.conf.weekday.dayline.format)))),n==t.length-1&&"desktop"==this.mobileQuery()&&e.append(f("",{class:"btn btn-sm btn-light btn-move-calendar"}).attr("data-direction","right").append(f("",{class:"fas fa-arrow-right"}))),li.append(e),li.attr("data-time",time.startOf("day").format("X")),li.append(f("