').insertAfter(a(this)).on("click", b); var h = { relatedTarget: this }; if (f.trigger(d = a.Event("show.bs.dropdown", h)), d.isDefaultPrevented()) return; e.trigger("focus").attr("aria-expanded", "true"), f.toggleClass("open").trigger("shown.bs.dropdown", h) } return !1 } }, g.prototype.keydown = function (b) { if (/(38|40|27|32)/.test(b.which) && !/input|textarea/i.test(b.target.tagName)) { var d = a(this); if (b.preventDefault(), b.stopPropagation(), !d.is(".disabled, :disabled")) { var e = c(d), g = e.hasClass("open"); if (!g && 27 != b.which || g && 27 == b.which) return 27 == b.which && e.find(f).trigger("focus"), d.trigger("click"); var h = " li:not(.divider):visible a", i = e.find('[role="menu"]' + h + ', [role="listbox"]' + h); if (i.length) { var j = i.index(b.target); 38 == b.which && j > 0 && j--, 40 == b.which && j < i.length - 1 && j++, ~j || (j = 0), i.eq(j).trigger("focus") } } } }; var h = a.fn.dropdown; a.fn.dropdown = d, a.fn.dropdown.Constructor = g, a.fn.dropdown.noConflict = function () { return a.fn.dropdown = h, this }, a(document).on("click.bs.dropdown.data-api", b).on("click.bs.dropdown.data-api", ".dropdown form", function (a) { a.stopPropagation() }).on("click.bs.dropdown.data-api", f, g.prototype.toggle).on("keydown.bs.dropdown.data-api", f, g.prototype.keydown).on("keydown.bs.dropdown.data-api", '[role="menu"]', g.prototype.keydown).on("keydown.bs.dropdown.data-api", '[role="listbox"]', g.prototype.keydown) }(jQuery), +function (a) { "use strict"; function b(b, d) { return this.each(function () { var e = a(this), f = e.data("bs.modal"), g = a.extend({}, c.DEFAULTS, e.data(), "object" == typeof b && b); f || e.data("bs.modal", f = new c(this, g)), "string" == typeof b ? f[b](d) : g.show && f.show(d) }) } var c = function (b, c) { this.options = c, this.$body = a(document.body), this.$element = a(b), this.$backdrop = this.isShown = null, this.scrollbarWidth = 0, this.options.remote && this.$element.find(".modal-content").load(this.options.remote, a.proxy(function () { this.$element.trigger("loaded.bs.modal") }, this)) }; c.VERSION = "3.3.1", c.TRANSITION_DURATION = 300, c.BACKDROP_TRANSITION_DURATION = 150, c.DEFAULTS = { backdrop: !0, keyboard: !0, show: !0 }, c.prototype.toggle = function (a) { return this.isShown ? this.hide() : this.show(a) }, c.prototype.show = function (b) { var d = this, e = a.Event("show.bs.modal", { relatedTarget: b }); this.$element.trigger(e), this.isShown || e.isDefaultPrevented() || (this.isShown = !0, this.checkScrollbar(), this.setScrollbar(), this.$body.addClass("modal-open"), this.escape(), this.resize(), this.$element.on("click.dismiss.bs.modal", '[data-dismiss="modal"]', a.proxy(this.hide, this)), this.backdrop(function () { var e = a.support.transition && d.$element.hasClass("fade"); d.$element.parent().length || d.$element.appendTo(d.$body), d.$element.show().scrollTop(0), d.options.backdrop && d.adjustBackdrop(), d.adjustDialog(), e && d.$element[0].offsetWidth, d.$element.addClass("in").attr("aria-hidden", !1), d.enforceFocus(); var f = a.Event("shown.bs.modal", { relatedTarget: b }); e ? d.$element.find(".modal-dialog").one("bsTransitionEnd", function () { d.$element.trigger("focus").trigger(f) }).emulateTransitionEnd(c.TRANSITION_DURATION) : d.$element.trigger("focus").trigger(f) })) }, c.prototype.hide = function (b) { b && b.preventDefault(), b = a.Event("hide.bs.modal"), this.$element.trigger(b), this.isShown && !b.isDefaultPrevented() && (this.isShown = !1, this.escape(), this.resize(), a(document).off("focusin.bs.modal"), this.$element.removeClass("in").attr("aria-hidden", !0).off("click.dismiss.bs.modal"), a.support.transition && this.$element.hasClass("fade") ? this.$element.one("bsTransitionEnd", a.proxy(this.hideModal, this)).emulateTransitionEnd(c.TRANSITION_DURATION) : this.hideModal()) }, c.prototype.enforceFocus = function () { a(document).off("focusin.bs.modal").on("focusin.bs.modal", a.proxy(function (a) { this.$element[0] === a.target || this.$element.has(a.target).length || this.$element.trigger("focus") }, this)) }, c.prototype.escape = function () { this.isShown && this.options.keyboard ? this.$element.on("keydown.dismiss.bs.modal", a.proxy(function (a) { 27 == a.which && this.hide() }, this)) : this.isShown || this.$element.off("keydown.dismiss.bs.modal") }, c.prototype.resize = function () { this.isShown ? a(window).on("resize.bs.modal", a.proxy(this.handleUpdate, this)) : a(window).off("resize.bs.modal") }, c.prototype.hideModal = function () { var a = this; this.$element.hide(), this.backdrop(function () { a.$body.removeClass("modal-open"), a.resetAdjustments(), a.resetScrollbar(), a.$element.trigger("hidden.bs.modal") }) }, c.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove(), this.$backdrop = null }, c.prototype.backdrop = function (b) { var d = this, e = this.$element.hasClass("fade") ? "fade" : ""; if (this.isShown && this.options.backdrop) { var f = a.support.transition && e; if (this.$backdrop = a('
').prependTo(this.$element).on("click.dismiss.bs.modal", a.proxy(function (a) { a.target === a.currentTarget && ("static" == this.options.backdrop ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this)) }, this)), f && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), !b) return; f ? this.$backdrop.one("bsTransitionEnd", b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION) : b() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass("in"); var g = function () { d.removeBackdrop(), b && b() }; a.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one("bsTransitionEnd", g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION) : g() } else b && b() }, c.prototype.handleUpdate = function () { this.options.backdrop && this.adjustBackdrop(), this.adjustDialog() }, c.prototype.adjustBackdrop = function () { this.$backdrop.css("height", 0).css("height", this.$element[0].scrollHeight) }, c.prototype.adjustDialog = function () { var a = this.$element[0].scrollHeight > document.documentElement.clientHeight; this.$element.css({ paddingLeft: !this.bodyIsOverflowing && a ? this.scrollbarWidth : "", paddingRight: this.bodyIsOverflowing && !a ? this.scrollbarWidth : "" }) }, c.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: "", paddingRight: "" }) }, c.prototype.checkScrollbar = function () { this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight, this.scrollbarWidth = this.measureScrollbar() }, c.prototype.setScrollbar = function () { var a = parseInt(this.$body.css("padding-right") || 0, 10); this.bodyIsOverflowing && this.$body.css("padding-right", a + this.scrollbarWidth) }, c.prototype.resetScrollbar = function () { this.$body.css("padding-right", "") }, c.prototype.measureScrollbar = function () { var a = document.createElement("div"); a.className = "modal-scrollbar-measure", this.$body.append(a); var b = a.offsetWidth - a.clientWidth; return this.$body[0].removeChild(a), b }; var d = a.fn.modal; a.fn.modal = b, a.fn.modal.Constructor = c, a.fn.modal.noConflict = function () { return a.fn.modal = d, this }, a(document).on("click.bs.modal.data-api", '[data-toggle="modal"]', function (c) { var d = a(this), e = d.attr("href"), f = a(d.attr("data-target") || e && e.replace(/.*(?=#[^\s]+$)/, "")), g = f.data("bs.modal") ? "toggle" : a.extend({ remote: !/#/.test(e) && e }, f.data(), d.data()); d.is("a") && c.preventDefault(), f.one("show.bs.modal", function (a) { a.isDefaultPrevented() || f.one("hidden.bs.modal", function () { d.is(":visible") && d.trigger("focus") }) }), b.call(f, g, this) }) }(jQuery), +function (a) { "use strict"; function b(b) { return this.each(function () { var d = a(this), e = d.data("bs.tooltip"), f = "object" == typeof b && b, g = f && f.selector; (e || "destroy" != b) && (g ? (e || d.data("bs.tooltip", e = {}), e[g] || (e[g] = new c(this, f))) : e || d.data("bs.tooltip", e = new c(this, f)), "string" == typeof b && e[b]()) }) } var c = function (a, b) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null, this.init("tooltip", a, b) }; c.VERSION = "3.3.1", c.TRANSITION_DURATION = 150, c.DEFAULTS = { animation: !0, placement: "top", selector: !1, template: '
', trigger: "hover focus", title: "", delay: 0, html: !1, container: !1, viewport: { selector: "body", padding: 0 } }, c.prototype.init = function (b, c, d) { this.enabled = !0, this.type = b, this.$element = a(c), this.options = this.getOptions(d), this.$viewport = this.options.viewport && a(this.options.viewport.selector || this.options.viewport); for (var e = this.options.trigger.split(" "), f = e.length; f--;) { var g = e[f]; if ("click" == g) this.$element.on("click." + this.type, this.options.selector, a.proxy(this.toggle, this)); else if ("manual" != g) { var h = "hover" == g ? "mouseenter" : "focusin", i = "hover" == g ? "mouseleave" : "focusout"; this.$element.on(h + "." + this.type, this.options.selector, a.proxy(this.enter, this)), this.$element.on(i + "." + this.type, this.options.selector, a.proxy(this.leave, this)) } } this.options.selector ? this._options = a.extend({}, this.options, { trigger: "manual", selector: "" }) : this.fixTitle() }, c.prototype.getDefaults = function () { return c.DEFAULTS }, c.prototype.getOptions = function (b) { return b = a.extend({}, this.getDefaults(), this.$element.data(), b), b.delay && "number" == typeof b.delay && (b.delay = { show: b.delay, hide: b.delay }), b }, c.prototype.getDelegateOptions = function () { var b = {}, c = this.getDefaults(); return this._options && a.each(this._options, function (a, d) { c[a] != d && (b[a] = d) }), b }, c.prototype.enter = function (b) { var c = b instanceof this.constructor ? b : a(b.currentTarget).data("bs." + this.type); return c && c.$tip && c.$tip.is(":visible") ? void (c.hoverState = "in") : (c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c)), clearTimeout(c.timeout), c.hoverState = "in", c.options.delay && c.options.delay.show ? void (c.timeout = setTimeout(function () { "in" == c.hoverState && c.show() }, c.options.delay.show)) : c.show()) }, c.prototype.leave = function (b) { var c = b instanceof this.constructor ? b : a(b.currentTarget).data("bs." + this.type); return c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c)), clearTimeout(c.timeout), c.hoverState = "out", c.options.delay && c.options.delay.hide ? void (c.timeout = setTimeout(function () { "out" == c.hoverState && c.hide() }, c.options.delay.hide)) : c.hide() }, c.prototype.show = function () { var b = a.Event("show.bs." + this.type); if (this.hasContent() && this.enabled) { this.$element.trigger(b); var d = a.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]); if (b.isDefaultPrevented() || !d) return; var e = this, f = this.tip(), g = this.getUID(this.type); this.setContent(), f.attr("id", g), this.$element.attr("aria-describedby", g), this.options.animation && f.addClass("fade"); var h = "function" == typeof this.options.placement ? this.options.placement.call(this, f[0], this.$element[0]) : this.options.placement, i = /\s?auto?\s?/i, j = i.test(h); j && (h = h.replace(i, "") || "top"), f.detach().css({ top: 0, left: 0, display: "block" }).addClass(h).data("bs." + this.type, this), this.options.container ? f.appendTo(this.options.container) : f.insertAfter(this.$element); var k = this.getPosition(), l = f[0].offsetWidth, m = f[0].offsetHeight; if (j) { var n = h, o = this.options.container ? a(this.options.container) : this.$element.parent(), p = this.getPosition(o); h = "bottom" == h && k.bottom + m > p.bottom ? "top" : "top" == h && k.top - m < p.top ? "bottom" : "right" == h && k.right + l > p.width ? "left" : "left" == h && k.left - l < p.left ? "right" : h, f.removeClass(n).addClass(h) } var q = this.getCalculatedOffset(h, k, l, m); this.applyPlacement(q, h); var r = function () { var a = e.hoverState; e.$element.trigger("shown.bs." + e.type), e.hoverState = null, "out" == a && e.leave(e) }; a.support.transition && this.$tip.hasClass("fade") ? f.one("bsTransitionEnd", r).emulateTransitionEnd(c.TRANSITION_DURATION) : r() } }, c.prototype.applyPlacement = function (b, c) { var d = this.tip(), e = d[0].offsetWidth, f = d[0].offsetHeight, g = parseInt(d.css("margin-top"), 10), h = parseInt(d.css("margin-left"), 10); isNaN(g) && (g = 0), isNaN(h) && (h = 0), b.top = b.top + g, b.left = b.left + h, a.offset.setOffset(d[0], a.extend({ using: function (a) { d.css({ top: Math.round(a.top), left: Math.round(a.left) }) } }, b), 0), d.addClass("in"); var i = d[0].offsetWidth, j = d[0].offsetHeight; "top" == c && j != f && (b.top = b.top + f - j); var k = this.getViewportAdjustedDelta(c, b, i, j); k.left ? b.left += k.left : b.top += k.top; var l = /top|bottom/.test(c), m = l ? 2 * k.left - e + i : 2 * k.top - f + j, n = l ? "offsetWidth" : "offsetHeight"; d.offset(b), this.replaceArrow(m, d[0][n], l) }, c.prototype.replaceArrow = function (a, b, c) { this.arrow().css(c ? "left" : "top", 50 * (1 - a / b) + "%").css(c ? "top" : "left", "") }, c.prototype.setContent = function () { var a = this.tip(), b = this.getTitle(); a.find(".tooltip-inner")[this.options.html ? "html" : "text"](b), a.removeClass("fade in top bottom left right") }, c.prototype.hide = function (b) { function d() { "in" != e.hoverState && f.detach(), e.$element.removeAttr("aria-describedby").trigger("hidden.bs." + e.type), b && b() } var e = this, f = this.tip(), g = a.Event("hide.bs." + this.type); return this.$element.trigger(g), g.isDefaultPrevented() ? void 0 : (f.removeClass("in"), a.support.transition && this.$tip.hasClass("fade") ? f.one("bsTransitionEnd", d).emulateTransitionEnd(c.TRANSITION_DURATION) : d(), this.hoverState = null, this) }, c.prototype.fixTitle = function () { var a = this.$element; (a.attr("title") || "string" != typeof a.attr("data-original-title")) && a.attr("data-original-title", a.attr("title") || "").attr("title", "") }, c.prototype.hasContent = function () { return this.getTitle() }, c.prototype.getPosition = function (b) { b = b || this.$element; var c = b[0], d = "BODY" == c.tagName, e = c.getBoundingClientRect(); null == e.width && (e = a.extend({}, e, { width: e.right - e.left, height: e.bottom - e.top })); var f = d ? { top: 0, left: 0 } : b.offset(), g = { scroll: d ? document.documentElement.scrollTop || document.body.scrollTop : b.scrollTop() }, h = d ? { width: a(window).width(), height: a(window).height() } : null; return a.extend({}, e, g, h, f) }, c.prototype.getCalculatedOffset = function (a, b, c, d) { return "bottom" == a ? { top: b.top + b.height, left: b.left + b.width / 2 - c / 2 } : "top" == a ? { top: b.top - d, left: b.left + b.width / 2 - c / 2 } : "left" == a ? { top: b.top + b.height / 2 - d / 2, left: b.left - c } : { top: b.top + b.height / 2 - d / 2, left: b.left + b.width } }, c.prototype.getViewportAdjustedDelta = function (a, b, c, d) { var e = { top: 0, left: 0 }; if (!this.$viewport) return e; var f = this.options.viewport && this.options.viewport.padding || 0, g = this.getPosition(this.$viewport); if (/right|left/.test(a)) { var h = b.top - f - g.scroll, i = b.top + f - g.scroll + d; h < g.top ? e.top = g.top - h : i > g.top + g.height && (e.top = g.top + g.height - i) } else { var j = b.left - f, k = b.left + f + c; j < g.left ? e.left = g.left - j : k > g.width && (e.left = g.left + g.width - k) } return e }, c.prototype.getTitle = function () { var a, b = this.$element, c = this.options; return a = b.attr("data-original-title") || ("function" == typeof c.title ? c.title.call(b[0]) : c.title) }, c.prototype.getUID = function (a) { do a += ~~(1e6 * Math.random()); while (document.getElementById(a)); return a }, c.prototype.tip = function () { return this.$tip = this.$tip || a(this.options.template) }, c.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") }, c.prototype.enable = function () { this.enabled = !0 }, c.prototype.disable = function () { this.enabled = !1 }, c.prototype.toggleEnabled = function () { this.enabled = !this.enabled }, c.prototype.toggle = function (b) { var c = this; b && (c = a(b.currentTarget).data("bs." + this.type), c || (c = new this.constructor(b.currentTarget, this.getDelegateOptions()), a(b.currentTarget).data("bs." + this.type, c))), c.tip().hasClass("in") ? c.leave(c) : c.enter(c) }, c.prototype.destroy = function () { var a = this; clearTimeout(this.timeout), this.hide(function () { a.$element.off("." + a.type).removeData("bs." + a.type) }) }; var d = a.fn.tooltip; a.fn.tooltip = b, a.fn.tooltip.Constructor = c, a.fn.tooltip.noConflict = function () { return a.fn.tooltip = d, this } }(jQuery), +function (a) { "use strict"; function b(b) { return this.each(function () { var d = a(this), e = d.data("bs.popover"), f = "object" == typeof b && b, g = f && f.selector; (e || "destroy" != b) && (g ? (e || d.data("bs.popover", e = {}), e[g] || (e[g] = new c(this, f))) : e || d.data("bs.popover", e = new c(this, f)), "string" == typeof b && e[b]()) }) } var c = function (a, b) { this.init("popover", a, b) }; if (!a.fn.tooltip) throw new Error("Popover requires tooltip.js"); c.VERSION = "3.3.1", c.DEFAULTS = a.extend({}, a.fn.tooltip.Constructor.DEFAULTS, { placement: "right", trigger: "click", content: "", template: '
' }), c.prototype = a.extend({}, a.fn.tooltip.Constructor.prototype), c.prototype.constructor = c, c.prototype.getDefaults = function () { return c.DEFAULTS }, c.prototype.setContent = function () { var a = this.tip(), b = this.getTitle(), c = this.getContent(); a.find(".popover-title")[this.options.html ? "html" : "text"](b), a.find(".popover-content").children().detach().end()[this.options.html ? "string" == typeof c ? "html" : "append" : "text"](c), a.removeClass("fade top bottom left right in"), a.find(".popover-title").html() || a.find(".popover-title").hide() }, c.prototype.hasContent = function () { return this.getTitle() || this.getContent() }, c.prototype.getContent = function () { var a = this.$element, b = this.options; return a.attr("data-content") || ("function" == typeof b.content ? b.content.call(a[0]) : b.content) }, c.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find(".arrow") }, c.prototype.tip = function () { return this.$tip || (this.$tip = a(this.options.template)), this.$tip }; var d = a.fn.popover; a.fn.popover = b, a.fn.popover.Constructor = c, a.fn.popover.noConflict = function () { return a.fn.popover = d, this } }(jQuery), +function (a) { "use strict"; function b(c, d) { var e = a.proxy(this.process, this); this.$body = a("body"), this.$scrollElement = a(a(c).is("body") ? window : c), this.options = a.extend({}, b.DEFAULTS, d), this.selector = (this.options.target || "") + " .nav li > a", this.offsets = [], this.targets = [], this.activeTarget = null, this.scrollHeight = 0, this.$scrollElement.on("scroll.bs.scrollspy", e), this.refresh(), this.process() } function c(c) { return this.each(function () { var d = a(this), e = d.data("bs.scrollspy"), f = "object" == typeof c && c; e || d.data("bs.scrollspy", e = new b(this, f)), "string" == typeof c && e[c]() }) } b.VERSION = "3.3.1", b.DEFAULTS = { offset: 10 }, b.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) }, b.prototype.refresh = function () { var b = "offset", c = 0; a.isWindow(this.$scrollElement[0]) || (b = "position", c = this.$scrollElement.scrollTop()), this.offsets = [], this.targets = [], this.scrollHeight = this.getScrollHeight(); var d = this; this.$body.find(this.selector).map(function () { var d = a(this), e = d.data("target") || d.attr("href"), f = /^#./.test(e) && a(e); return f && f.length && f.is(":visible") && [[f[b]().top + c, e]] || null }).sort(function (a, b) { return a[0] - b[0] }).each(function () { d.offsets.push(this[0]), d.targets.push(this[1]) }) }, b.prototype.process = function () { var a, b = this.$scrollElement.scrollTop() + this.options.offset, c = this.getScrollHeight(), d = this.options.offset + c - this.$scrollElement.height(), e = this.offsets, f = this.targets, g = this.activeTarget; if (this.scrollHeight != c && this.refresh(), b >= d) return g != (a = f[f.length - 1]) && this.activate(a); if (g && b < e[0]) return this.activeTarget = null, this.clear(); for (a = e.length; a--;) g != f[a] && b >= e[a] && (!e[a + 1] || b <= e[a + 1]) && this.activate(f[a]) }, b.prototype.activate = function (b) { this.activeTarget = b, this.clear(); var c = this.selector + '[data-target="' + b + '"],' + this.selector + '[href="' + b + '"]', d = a(c).parents("li").addClass("active"); d.parent(".dropdown-menu").length && (d = d.closest("li.dropdown").addClass("active")), d.trigger("activate.bs.scrollspy") }, b.prototype.clear = function () { a(this.selector).parentsUntil(this.options.target, ".active").removeClass("active") }; var d = a.fn.scrollspy; a.fn.scrollspy = c, a.fn.scrollspy.Constructor = b, a.fn.scrollspy.noConflict = function () { return a.fn.scrollspy = d, this }, a(window).on("load.bs.scrollspy.data-api", function () { a('[data-spy="scroll"]').each(function () { var b = a(this); c.call(b, b.data()) }) }) }(jQuery), +function (a) {
"use strict"; function b(b) { return this.each(function () { var d = a(this), e = d.data("bs.tab"); e || d.data("bs.tab", e = new c(this)), "string" == typeof b && e[b]() }) } var c = function (b) { this.element = a(b) }; c.VERSION = "3.3.1", c.TRANSITION_DURATION = 150, c.prototype.show = function () {
var b = this.element, c = b.closest("ul:not(.dropdown-menu)"), d = b.data("target"); if (d || (d = b.attr("href"), d = d && d.replace(/.*(?=#[^\s]*$)/, "")), !b.parent("li").hasClass("active")) {
var e = c.find(".active:last a"), f = a.Event("hide.bs.tab", { relatedTarget: b[0] }), g = a.Event("show.bs.tab", { relatedTarget: e[0] }); if (e.trigger(f), b.trigger(g), !g.isDefaultPrevented() && !f.isDefaultPrevented()) {
var h = a(d); this.activate(b.closest("li"), c), this.activate(h, h.parent(), function () {
e.trigger({ type: "hidden.bs.tab", relatedTarget: b[0] }), b.trigger({ type: "shown.bs.tab", relatedTarget: e[0] })
})
}
}
}, c.prototype.activate = function (b, d, e) { function f() { g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !1), b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded", !0), h ? (b[0].offsetWidth, b.addClass("in")) : b.removeClass("fade"), b.parent(".dropdown-menu") && b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !0), e && e() } var g = d.find("> .active"), h = e && a.support.transition && (g.length && g.hasClass("fade") || !!d.find("> .fade").length); g.length && h ? g.one("bsTransitionEnd", f).emulateTransitionEnd(c.TRANSITION_DURATION) : f(), g.removeClass("in") }; var d = a.fn.tab; a.fn.tab = b, a.fn.tab.Constructor = c, a.fn.tab.noConflict = function () { return a.fn.tab = d, this }; var e = function (c) { c.preventDefault(), b.call(a(this), "show") }; a(document).on("click.bs.tab.data-api", '[data-toggle="tab"]', e).on("click.bs.tab.data-api", '[data-toggle="pill"]', e)
}(jQuery), +function (a) { "use strict"; function b(b) { return this.each(function () { var d = a(this), e = d.data("bs.affix"), f = "object" == typeof b && b; e || d.data("bs.affix", e = new c(this, f)), "string" == typeof b && e[b]() }) } var c = function (b, d) { this.options = a.extend({}, c.DEFAULTS, d), this.$target = a(this.options.target).on("scroll.bs.affix.data-api", a.proxy(this.checkPosition, this)).on("click.bs.affix.data-api", a.proxy(this.checkPositionWithEventLoop, this)), this.$element = a(b), this.affixed = this.unpin = this.pinnedOffset = null, this.checkPosition() }; c.VERSION = "3.3.1", c.RESET = "affix affix-top affix-bottom", c.DEFAULTS = { offset: 0, target: window }, c.prototype.getState = function (a, b, c, d) { var e = this.$target.scrollTop(), f = this.$element.offset(), g = this.$target.height(); if (null != c && "top" == this.affixed) return c > e ? "top" : !1; if ("bottom" == this.affixed) return null != c ? e + this.unpin <= f.top ? !1 : "bottom" : a - d >= e + g ? !1 : "bottom"; var h = null == this.affixed, i = h ? e : f.top, j = h ? g : b; return null != c && c >= i ? "top" : null != d && i + j >= a - d ? "bottom" : !1 }, c.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset; this.$element.removeClass(c.RESET).addClass("affix"); var a = this.$target.scrollTop(), b = this.$element.offset(); return this.pinnedOffset = b.top - a }, c.prototype.checkPositionWithEventLoop = function () { setTimeout(a.proxy(this.checkPosition, this), 1) }, c.prototype.checkPosition = function () { if (this.$element.is(":visible")) { var b = this.$element.height(), d = this.options.offset, e = d.top, f = d.bottom, g = a("body").height(); "object" != typeof d && (f = e = d), "function" == typeof e && (e = d.top(this.$element)), "function" == typeof f && (f = d.bottom(this.$element)); var h = this.getState(g, b, e, f); if (this.affixed != h) { null != this.unpin && this.$element.css("top", ""); var i = "affix" + (h ? "-" + h : ""), j = a.Event(i + ".bs.affix"); if (this.$element.trigger(j), j.isDefaultPrevented()) return; this.affixed = h, this.unpin = "bottom" == h ? this.getPinnedOffset() : null, this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix", "affixed") + ".bs.affix") } "bottom" == h && this.$element.offset({ top: g - b - f }) } }; var d = a.fn.affix; a.fn.affix = b, a.fn.affix.Constructor = c, a.fn.affix.noConflict = function () { return a.fn.affix = d, this }, a(window).on("load", function () { a('[data-spy="affix"]').each(function () { var c = a(this), d = c.data(); d.offset = d.offset || {}, null != d.offsetBottom && (d.offset.bottom = d.offsetBottom), null != d.offsetTop && (d.offset.top = d.offsetTop), b.call(c, d) }) }) }(jQuery);
/**
* bootstrap-multiselect.js
* https://github.com/davidstutz/bootstrap-multiselect
*
* Copyright 2012 - 2014 David Stutz
*
* Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0.
*/
!function ($) {
"use strict";// jshint ;_;
if (Array.prototype.forEach === null || Array.prototype.forEach === undefined) {
Array.prototype.forEach = function (func) {
var index;
for (index = 0; index < this.length; ++index) {
func(this[index]);
}
};
}
if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
ko.bindingHandlers.multiselect = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var listOfSelectedItems = allBindingsAccessor().selectedOptions,
config = ko.utils.unwrapObservable(valueAccessor());
$(element).multiselect(config);
if (isObservableArray(listOfSelectedItems)) {
// Subscribe to the selectedOptions: ko.observableArray
listOfSelectedItems.subscribe(function (changes) {
var addedArray = [], deletedArray = [];
changes.forEach(function (change) {
switch (change.status) {
case 'added':
addedArray.push(change.value);
break;
case 'deleted':
deletedArray.push(change.value);
break;
}
});
if (addedArray.length > 0) {
$(element).multiselect('select', addedArray);
};
if (deletedArray.length > 0) {
$(element).multiselect('deselect', deletedArray);
};
}, null, "arrayChange");
}
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var listOfItems = allBindingsAccessor().options,
ms = $(element).data('multiselect'),
config = ko.utils.unwrapObservable(valueAccessor());
if (isObservableArray(listOfItems)) {
// Subscribe to the options: ko.observableArray incase it changes later
listOfItems.subscribe(function (theArray) {
$(element).multiselect('rebuild');
});
}
if (!ms) {
$(element).multiselect(config);
}
else {
ms.updateOriginalOptions();
}
}
};
}
function isObservableArray(obj) {
return ko.isObservable(obj) && !(obj.destroyAll === undefined);
}
/**
* Constructor to create a new multiselect using the given select.
*
* @param {jQuery} select
* @param {Object} options
* @returns {Multiselect}
*/
function Multiselect(select, options) {
this.options = this.mergeOptions(options);
this.$select = $(select);
// Initialization.
// We have to clone to create a new reference.
this.originalOptions = this.$select.clone()[0].options;
this.query = '';
this.searchTimeout = null;
this.options.multiple = this.$select.attr('multiple') === "multiple";
this.options.onChange = $.proxy(this.options.onChange, this);
this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
// Build select all if enabled.
this.buildContainer();
this.buildButton();
this.buildDropdown();
this.buildSelectAll();
this.buildDropdownOptions();
this.buildFilter();
this.updateButtonText();
this.updateSelectAll();
this.$select.hide().after(this.$container);
};
Multiselect.prototype = {
defaults: {
/**
* Default text function will either print 'None selected' in case no
* option is selected or a list of the selected options up to a length of 3 selected options.
*
* @param {jQuery} options
* @param {jQuery} select
* @returns {String}
*/
buttonText: function (options, select) {
if (options.length === 0) {
return '
' +this.nonSelectedText + ' ';
}
else {
if (options.length > this.numberDisplayed) {
return '
' + options.length + ' ' + this.nSelectedText + ' ';
}
else {
var selected = '';
options.each(function () {
var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html();
selected += label + ', ';
});
return '
' + selected.substr(0, selected.length - 2) + ' ';
}
}
},
/**
* Updates the title of the button similar to the buttonText function.
* @param {jQuery} options
* @param {jQuery} select
* @returns {@exp;selected@call;substr}
*/
buttonTitle: function (options, select) {
if (options.length === 0) {
return this.nonSelectedText;
}
else {
var selected = '';
options.each(function () {
selected += $(this).text() + ', ';
});
return selected.substr(0, selected.length - 2);
}
},
/**
* Create a label.
*
* @param {jQuery} element
* @returns {String}
*/
label: function (element) {
return $(element).attr('label') || $(element).html();
},
/**
* Triggered on change of the multiselect.
* Not triggered when selecting/deselecting options manually.
*
* @param {jQuery} option
* @param {Boolean} checked
*/
onChange: function (option, checked) {
},
/**
* Triggered when the dropdown is shown.
*
* @param {jQuery} event
*/
onDropdownShow: function (event) {
},
/**
* Triggered when the dropdown is hidden.
*
* @param {jQuery} event
*/
onDropdownHide: function (event) {
},
buttonClass: 'btn btn-default',
dropRight: false,
selectedClass: 'active',
buttonWidth: 'auto',
buttonContainer: '
',
// Maximum height of the dropdown menu.
// If maximum height is exceeded a scrollbar will be displayed.
maxHeight: false,
checkboxName: 'multiselect',
includeSelectAllOption: false,
includeSelectAllIfMoreThan: 0,
selectAllText: ' Select all',
selectAllValue: 'multiselect-all',
enableFiltering: false,
enableCaseInsensitiveFiltering: false,
filterPlaceholder: 'Search',
ajaxNoResults: 'No Results',
ajaxSearch: false,
ajaxURL: null,//'/SecureSystem/OrderingProvider',
maxBuildList:1500,
// possible options: 'text', 'value', 'both'
filterBehavior: 'text',
preventInputChangeEvent: false,
nonSelectedText: 'None selected',
nSelectedText: 'selected',
numberDisplayed: 3,
templates: {
button: '
',
ul: '',
filter: '
',
li: '
',
divider: '
',
liGroup: '
'
}
},
constructor: Multiselect,
/**
* Builds the container of the multiselect.
*/
buildContainer: function () {
this.$container = $(this.options.buttonContainer);
this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
},
/**
* Builds the button of the multiselect.
*/
buildButton: function () {
this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
//if (this.options.buttonID) {
// this.$button.attr('id', 'hammers');
// console.log('dpne');
//}
// Adopt active state.
if (this.$select.prop('disabled')) {
this.disable();
}
else {
this.enable();
}
// Manually add button width if set.
if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
this.$button.css({
'width': this.options.buttonWidth
});
}
// Keep the tab index from the select.
var tabindex = this.$select.attr('tabindex');
if (tabindex) {
this.$button.attr('tabindex', tabindex);
}
this.$container.prepend(this.$button);
},
/**
* Builds the ul representing the dropdown menu.
*/
buildDropdown: function () {
// Build ul.
this.$ul = $(this.options.templates.ul);
if (this.options.dropRight) {
this.$ul.addClass('pull-right');
}
// Set max height of dropdown menu to activate auto scrollbar.
if (this.options.maxHeight) {
// TODO: Add a class for this option to move the css declarations.
this.$ul.css({
'max-height': this.options.maxHeight + 'px',
'overflow-y': 'auto',
'overflow-x': 'hidden'
});
}
this.$container.append(this.$ul);
},
RegisterChangeEvent: function ()
{
$('li input', this.$ul).on('change', $.proxy(function (event) {
var $target = $(event.target);
var checked = $target.prop('checked') || false;
var isSelectAllOption = $target.val() === this.options.selectAllValue;
// Apply or unapply the configured selected class.
if (this.options.selectedClass) {
if (checked) {
$target.parents('li')
.addClass(this.options.selectedClass);
}
else {
$target.parents('li')
.removeClass(this.options.selectedClass);
}
}
// Get the corresponding option.
var value = $target.val();
var $option = this.getOptionByValue(value);
if ($option === undefined && value != this.options.selectAllValue) {
if ($($target).parent()[0].length <= 0) { return;}
var opt = $('
' + $($target).parent()[0].innerText + ' ');
this.$select.append(opt);
$option = this.getOptionByValue(value);
}
var $optionsNotThis = $('option', this.$select).not($option);
var $checkboxesNotThis = $('input', this.$container).not($target);
if (isSelectAllOption) {
if (checked) {
this.selectall();
}
else {
this.deselectall();
}
}
if (!isSelectAllOption) {
if (checked) {
$option.prop('selected', true);
if (this.options.multiple) {
// Simply select additional option.
$option.prop('selected', true);
}
else {
// Unselect all other options and corresponding checkboxes.
if (this.options.selectedClass) {
$($checkboxesNotThis).parents('li').removeClass(this.options.selectedClass);
}
$($checkboxesNotThis).prop('checked', false);
$optionsNotThis.prop('selected', false);
// It's a single selection, so close.
this.$button.click();
}
if (this.options.selectedClass === "active") {
$optionsNotThis.parents("a").css("outline", "");
}
}
else {
// Unselect option.
$option.prop('selected', false);
}
}
this.$select.change();
this.updateButtonText();
this.updateSelectAll();
this.options.onChange($option, checked);
if (this.options.preventInputChangeEvent) {
return false;
}
}, this));
},
/**
* Build the dropdown options and binds all nessecary events.
* Uses createDivider and createOptionValue to create the necessary options.
*/
buildDropdownOptions: function () {
if (this.$select.children().length < this.options.maxBuildList) {
this.$select.children().each($.proxy(function (index, element) {
// Support optgroups and options without a group simultaneously.
var tag = $(element).prop('tagName')
.toLowerCase();
if (tag === 'optgroup') {
this.createOptgroup(element);
}
else if (tag === 'option') {
if ($(element).data('role') === 'divider') {
this.createDivider();
}
else {
this.createOptionValue(element);
}
}
// Other illegal tags will be ignored.
}, this));
} else {
this.$select.children().each($.proxy(function (index, element) {
// Support optgroups and options without a group simultaneously.
var tag = $(element).prop('tagName')
.toLowerCase();
if (tag === 'optgroup') {
this.createOptgroup(element);
}
else if (tag === 'option') {
if ($(element).data('role') === 'divider') {
this.createDivider();
}
else {
//if ($(element).prop('checked')) {
// this.createOptionValue(element);
//}
this.createOptionValue(element);
}
}
// Other illegal tags will be ignored.
}, this));
}
// Bind the change event on the dropdown elements.
//$('li input', this.$ul).on('change', $.proxy(this.Multiselct_li_change(), this));
this.RegisterChangeEvent();
//$('li input', this.$ul).on('change', $.proxy(function (event) {
// var $target = $(event.target);
// var checked = $target.prop('checked') || false;
// var isSelectAllOption = $target.val() === this.options.selectAllValue;
// // Apply or unapply the configured selected class.
// if (this.options.selectedClass) {
// if (checked) {
// $target.parents('li')
// .addClass(this.options.selectedClass);
// }
// else {
// $target.parents('li')
// .removeClass(this.options.selectedClass);
// }
// }
// // Get the corresponding option.
// var value = $target.val();
// var $option = this.getOptionByValue(value);
// var $optionsNotThis = $('option', this.$select).not($option);
// var $checkboxesNotThis = $('input', this.$container).not($target);
// if (isSelectAllOption) {
// if (checked) {
// this.selectall();
// }
// else {
// this.deselectall();
// }
// }
// if (!isSelectAllOption) {
// if (checked) {
// $option.prop('selected', true);
// if (this.options.multiple) {
// // Simply select additional option.
// $option.prop('selected', true);
// }
// else {
// // Unselect all other options and corresponding checkboxes.
// if (this.options.selectedClass) {
// $($checkboxesNotThis).parents('li').removeClass(this.options.selectedClass);
// }
// $($checkboxesNotThis).prop('checked', false);
// $optionsNotThis.prop('selected', false);
// // It's a single selection, so close.
// this.$button.click();
// }
// if (this.options.selectedClass === "active") {
// $optionsNotThis.parents("a").css("outline", "");
// }
// }
// else {
// // Unselect option.
// $option.prop('selected', false);
// }
// }
// this.$select.change();
// this.updateButtonText();
// this.updateSelectAll();
// this.options.onChange($option, checked);
// if (this.options.preventInputChangeEvent) {
// return false;
// }
//}, this));
$('li a', this.$ul).on('touchstart click', function (event) {
event.stopPropagation();
var $target = $(event.target);
if (event.shiftKey) {
var checked = $target.prop('checked') || false;
if (checked) {
var prev = $target.parents('li:last')
.siblings('li[class="active"]:first');
var currentIdx = $target.parents('li')
.index();
var prevIdx = prev.index();
if (currentIdx > prevIdx) {
$target.parents("li:last").prevUntil(prev).each(
function () {
$(this).find("input:first").prop("checked", true)
.trigger("change");
}
);
}
else {
$target.parents("li:last").nextUntil(prev).each(
function () {
$(this).find("input:first").prop("checked", true)
.trigger("change");
}
);
}
}
}
$target.blur();
});
// Keyboard support.
this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function (event) {
if ($('input[type="text"]', this.$container).is(':focus')) {
return;
}
if ((event.keyCode === 9 || event.keyCode === 27)
&& this.$container.hasClass('open')) {
// Close on tab or escape.
this.$button.click();
}
else {
var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible");
if (!$items.length) {
return;
}
var index = $items.index($items.filter(':focus'));
// Navigation up.
if (event.keyCode === 38 && index > 0) {
index--;
}
// Navigate down.
else if (event.keyCode === 40 && index < $items.length - 1) {
index++;
}
else if (!~index) {
index = 0;
}
var $current = $items.eq(index);
$current.focus();
if (event.keyCode === 32 || event.keyCode === 13) {
var $checkbox = $current.find('input');
$checkbox.prop("checked", !$checkbox.prop("checked"));
$checkbox.change();
}
event.stopPropagation();
event.preventDefault();
}
}, this));
},
/**
* Create an option using the given select option.
*
* @param {jQuery} element
*/
createOptionValue: function (element) {
if ($(element).is(':selected')) {
$(element).prop('selected', true);
}
// Support the label attribute on options.
var label = this.options.label(element);
var value = $(element).val();
if (label.trim() == "") {
return;
}
var inputType = this.options.multiple ? "checkbox" : "radio";
var $li = $(this.options.templates.li);
$('label', $li).addClass(inputType);
$('label', $li).append('
');
var selected = $(element).prop('selected') || false;
var $checkbox = $('input', $li);
$checkbox.val(value);
if (value === this.options.selectAllValue) {
$li.addClass("multiselect-item multiselect-all");
$checkbox.parent().parent()
.addClass('multiselect-all');
}
$('label', $li).append(" " + label);
this.$ul.append($li);
if ($(element).is(':disabled')) {
$checkbox.attr('disabled', 'disabled')
.prop('disabled', true)
.parents('a')
.attr("tabindex", "-1")
.parents('li')
.addClass('disabled');
}
$checkbox.prop('checked', selected);
if (selected && this.options.selectedClass) {
$checkbox.parents('li')
.addClass(this.options.selectedClass);
}
},
/**
* Creates a divider using the given select option.
*
* @param {jQuery} element
*/
createDivider: function (element) {
var $divider = $(this.options.templates.divider);
this.$ul.append($divider);
},
/**
* Creates an optgroup.
*
* @param {jQuery} group
*/
createOptgroup: function (group) {
var groupName = $(group).prop('label');
// Add a header for the group.
var $li = $(this.options.templates.liGroup);
$('label', $li).text(groupName);
this.$ul.append($li);
if ($(group).is(':disabled')) {
$li.addClass('disabled');
}
// Add the options of the group.
$('option', group).each($.proxy(function (index, element) {
this.createOptionValue(element);
}, this));
},
/**
* Build the selct all.
* Checks if a select all has already been created.
*/
buildSelectAll: function () {
var alreadyHasSelectAll = this.hasSelectAll();
if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
&& $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {
// Check whether to add a divider after the select all.
if (this.options.includeSelectAllDivider) {
this.$ul.prepend($(this.options.templates.divider));
}
var $li = $(this.options.templates.li);
$('label', $li).addClass("checkbox");
$('label', $li).append('
');
var $checkbox = $('input', $li);
$checkbox.val(this.options.selectAllValue);
$li.addClass("multiselect-item multiselect-all");
$checkbox.parent().parent()
.addClass('multiselect-all');
$('label', $li).append(" " + this.options.selectAllText);
this.$ul.prepend($li);
$checkbox.prop('checked', false);
}
},
/**
* Builds the filter.
*/
buildFilter: function () {
// Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);
if (this.$select.find('option').length >= enableFilterLength) {
this.$filter = $(this.options.templates.filter);
$('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
this.$ul.prepend(this.$filter);
this.$filter.val(this.query).on('click', function (event) {
event.stopPropagation();
}).on('input keydown', $.proxy(function (event) {
// This is useful to catch "keydown" events after the browser has updated the control.
clearTimeout(this.searchTimeout);
this.searchTimeout = this.asyncFunction($.proxy(function () {
if (this.query !== event.target.value) {
this.query = event.target.value;
if (this.options.ajaxSearch) {
this.$ul.find('.multiselect-NoResults').remove();
var wProviderQuery = $('.multiselect-search').val();
var $this = this
if (this.query == "") {
this.rebuild();
} else {
var wAJAXLoading = "
";
var wAJAXNoResults = "
" + this.options.ajaxNoResults + " ";
this.$ul.find('.multiselect-item-value').remove();
$.ajax({
type: "POST",
url: this.options.ajaxURL,
dataType: "json",
data: 'query=' + this.query,
beforeSend: function () {
var opt = $(wAJAXLoading);
//$this.createOptionValue(opt);
$this.$ul.append(opt);
},
success: function (data) {
$this.$ul.find('.multiselect-loading').remove();
if (data.length > 0) {
var $addTo = $('.multiselect-container li.search-results', this.$container);
for (var i = 0; i < (data.length > $this.options.maxBuildList ? $this.options.maxBuildList : data.length); i++) {
var opt = $('
' + data[i]["Text"] + ' ');
//$this.$select.append(opt);
$this.createOptionValue(opt);
//this.options.onChange($option, checked);
}
$this.RegisterChangeEvent();
} else {
var opt = $(wAJAXNoResults);
$this.$ul.append(opt);
}
//$('li input', this.$ul).on('change', $.proxy(Multiselct - li - change(event), this));
}
});
}
$this.refresh();
} else if (this.$select.children().length < this.options.maxBuildList) {
$.each($('li', this.$ul), $.proxy(function (index, element) {
if ($(element)[0].className != "multiselect-item-value" && $(element)[0].className != "multiselect-item-value filter-hidden") {
return;
}
var text = this.options.label(element);
var value = $(element).val();
var filterCandidate = '';
if ((this.options.filterBehavior === 'text')) {
filterCandidate = text;
}
else if ((this.options.filterBehavior === 'value')) {
filterCandidate = value;
}
else if (this.options.filterBehavior === 'both') {
filterCandidate = text + '\n' + value;
}
if (value !== this.options.selectAllValue && text) {
// by default lets assume that element is not
// interesting for this search
var showElement = false;
if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) {
showElement = true;
}
else if (filterCandidate.indexOf(this.query) > -1) {
showElement = true;
}
if (showElement) {
$(element).show().removeClass("filter-hidden");
}
else {
$(element).hide().addClass("filter-hidden");
}
}
}, this));
} else {
this.$select.children().each($.proxy(function (index, element) {
var value = $('input', element).val();
var text = $('label', element).text();
var filterCandidate = '';
if ((this.options.filterBehavior === 'text')) {
filterCandidate = text;
}
else if ((this.options.filterBehavior === 'value')) {
filterCandidate = value;
}
else if (this.options.filterBehavior === 'both') {
filterCandidate = text + '\n' + value;
}
if (value !== this.options.selectAllValue && text) {
// by default lets assume that element is not
// interesting for this search
var showElement = false;
if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) {
showElement = true;
}
else if (filterCandidate.indexOf(this.query) > -1) {
showElement = true;
}
var elm = $('li [value="' + value + '"]');
if (showElement && elm == null) {
var opt = $('
' + text + ' ');
$this.createOptionValue(opt);
} else if (showElement && elm != null) {
$(element).show().removeClass("filter-hidden");
}
else if (!showElement && elm != null) {
$(element).hide().addClass("filter-hidden");
}
}
}, this.$select));
}
}
this.updateSelectAll();
}, this), 300, this);
}, this));
}
}
},
/**
* Unbinds the whole plugin.
*/
destroy: function () {
this.$container.remove();
this.$select.show();
this.$select.data('multiselect', null);
},
/**
* Refreshs the multiselect based on the selected options of the select.
*/
refresh: function () {
$('option', this.$select).each($.proxy(function (index, element) {
var $input = $('li input', this.$ul).filter(function () {
return $(this).val() === $(element).val();
});
if ($(element).is(':selected')) {
$input.prop('checked', true);
if (this.options.selectedClass) {
$input.parents('li')
.addClass(this.options.selectedClass);
}
}
else {
$input.prop('checked', false);
if (this.options.selectedClass) {
$input.parents('li')
.removeClass(this.options.selectedClass);
}
}
if ($(element).is(":disabled")) {
$input.attr('disabled', 'disabled')
.prop('disabled', true)
.parents('li')
.addClass('disabled');
}
else {
$input.prop('disabled', false)
.parents('li')
.removeClass('disabled');
}
}, this));
this.updateButtonText();
this.updateSelectAll();
},
/**
* Select all options of the given values.
*
* @param {Array} selectValues
*/
select: function (selectValues) {
if (!$.isArray(selectValues)) {
selectValues = [selectValues];
}
for (var i = 0; i < selectValues.length; i++) {
var value = selectValues[i];
var $option = this.getOptionByValue(value);
var $checkbox = this.getInputByValue(value);
if (this.options.selectedClass) {
$checkbox.parents('li')
.addClass(this.options.selectedClass);
}
$checkbox.prop('checked', true);
$option.prop('selected', true);
}
this.updateButtonText();
},
/**
* Clears all selected items
*
*/
clearSelection: function () {
this.deselectall(false);
this.updateButtonText();
this.updateSelectAll();
},
/**
* Deselects all options of the given values.
*
* @param {Array} deselectValues
*/
deselect: function (deselectValues) {
if (!$.isArray(deselectValues)) {
deselectValues = [deselectValues];
}
for (var i = 0; i < deselectValues.length; i++) {
var value = deselectValues[i];
var $option = this.getOptionByValue(value);
var $checkbox = this.getInputByValue(value);
if (this.options.selectedClass) {
$checkbox.parents('li')
.removeClass(this.options.selectedClass);
}
$checkbox.prop('checked', false);
$option.prop('selected', false);
}
this.updateButtonText();
},
/**
* Selects all enabled & visible options.
*
*/
selectall: function () {
var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul),
visibleCheckboxes = allCheckboxes.filter(":visible"),
allCheckboxesCount = allCheckboxes.length,
visibleCheckboxesCount = visibleCheckboxes.length;
visibleCheckboxes.prop('checked', true);
$("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").addClass(this.options.selectedClass);
if (allCheckboxesCount === visibleCheckboxesCount) {
$("option:enabled", this.$select).prop('selected', true);
}
else {
var values = visibleCheckboxes.map(function () { return $(this).val() }).get();
$("option:enabled", this.$select).filter(function (index) { return $.inArray($(this).val(), values) !== -1; }).prop('selected', true);
}
},
/**
* Deselects all options.
* If justVisible is true or not specified, only visible options are deselected.
*
* @param {Boolean} justVisible
*/
deselectall: function (justVisible) {
var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul),
justVisible = typeof justVisible === 'undefined' ? true : justVisible,
visibleCheckboxes = void (0);
if (justVisible) {
var values = void (0);
visibleCheckboxes = allCheckboxes.filter(":visible");
visibleCheckboxes.prop('checked', false);
values = visibleCheckboxes.map(function () { return $(this).val() }).get();
$("option:enabled", this.$select).filter(function (index) { return $.inArray($(this).val(), values) !== -1; }).prop('selected', false);
$("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass);
} else {
allCheckboxes.prop('checked', false);
$("option:enabled", this.$select).prop('selected', false);
$("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass);
}
},
/**
* Rebuild the plugin.
* Rebuilds the dropdown, the filter and the select all option.
*/
rebuild: function () {
this.$ul.html('');
// Important to distinguish between radios and checkboxes.
this.options.multiple = this.$select.attr('multiple') === "multiple";
this.buildSelectAll();
this.buildDropdownOptions();
this.buildFilter();
this.updateButtonText();
this.updateSelectAll();
},
/**
* The provided data will be used to build the dropdown.
*
* @param {Array} dataprovider
*/
dataprovider: function (dataprovider) {
var optionDOM = "";
dataprovider.forEach(function (option) {
optionDOM += '
' + option.label + ' ';
});
this.$select.html(optionDOM);
this.rebuild();
},
/**
* Enable the multiselect.
*/
enable: function () {
this.$select.prop('disabled', false);
this.$button.prop('disabled', false)
.removeClass('disabled');
},
/**
* Disable the multiselect.
*/
disable: function () {
this.$select.prop('disabled', true);
this.$button.prop('disabled', true)
.addClass('disabled');
},
/**
* Set the options.
*
* @param {Array} options
*/
setOptions: function (options) {
this.options = this.mergeOptions(options);
},
/**
* Merges the given options with the default options.
*
* @param {Array} options
* @returns {Array}
*/
mergeOptions: function (options) {
return $.extend(true, {}, this.defaults, options);
},
/**
* Checks whether a select all checkbox is present.
*
* @returns {Boolean}
*/
hasSelectAll: function () {
return $('li.' + this.options.selectAllValue, this.$ul).length > 0;
},
/**
* Updates the select all checkbox based on the currently displayed and selected checkboxes.
*/
updateSelectAll: function () {
if (this.hasSelectAll()) {
var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul),
allBoxesLength = allBoxes.length,
checkedBoxesLength = allBoxes.filter(":checked").length,
selectAllLi = $("li." + this.options.selectAllValue, this.$ul),
selectAllInput = selectAllLi.find("input");
if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
selectAllInput.prop("checked", true);
selectAllLi.addClass(this.options.selectedClass);
}
else {
selectAllInput.prop("checked", false);
selectAllLi.removeClass(this.options.selectedClass);
}
}
},
/**
* Update the button text and its title based on the currently selected options.
*/
updateButtonText: function () {
var options = this.getSelected();
// First update the displayed button text.
$('button', this.$container).html(this.options.buttonText(options, this.$select));
// Now update the title attribute of the button.
$('button', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
},
/**
* Get all selected options.
*
* @returns {jQUery}
*/
getSelected: function () {
return $('option', this.$select).filter(":selected");
},
/**
* Gets a select option by its value.
*
* @param {String} value
* @returns {jQuery}
*/
getOptionByValue: function (value) {
var options = $('option', this.$select);
var valueToCompare = value.toString();
for (var i = 0; i < options.length; i = i + 1) {
var option = options[i];
if (option.value === valueToCompare) {
return $(option);
}
}
},
/**
* Get the input (radio/checkbox) by its value.
*
* @param {String} value
* @returns {jQuery}
*/
getInputByValue: function (value) {
var checkboxes = $('li input', this.$ul);
var valueToCompare = value.toString();
for (var i = 0; i < checkboxes.length; i = i + 1) {
var checkbox = checkboxes[i];
if (checkbox.value === valueToCompare) {
return $(checkbox);
}
}
},
/**
* Used for knockout integration.
*/
updateOriginalOptions: function () {
this.originalOptions = this.$select.clone()[0].options;
},
asyncFunction: function (callback, timeout, self) {
var args = Array.prototype.slice.call(arguments, 3);
return setTimeout(function () {
callback.apply(self || window, args);
}, timeout);
}
};
$.fn.multiselect = function (option, parameter) {
return this.each(function () {
var data = $(this).data('multiselect');
var options = typeof option === 'object' && option;
// Initialize the multiselect.
if (!data) {
data = new Multiselect(this, options);
$(this).data('multiselect', data);
}
// Call multiselect method.
if (typeof option === 'string') {
data[option](parameter);
if (option === 'destroy') {
$(this).data('multiselect', false);
}
}
});
};
$.fn.multiselect.Constructor = Multiselect;
$(function () {
$("select[data-role=multiselect]").multiselect();
});
}(window.jQuery);
/* =========================================================
* bootstrap-tabdrop.js
* http://www.eyecon.ro/bootstrap-tabdrop
* =========================================================
* Copyright 2012 Stefan Petre
* Copyright 2014 Jose Ant. Aranda
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
!function ($) {
var WinReszier = (function () {
var registered = [];
var inited = false;
var timer;
var cur_windows_width = $(window).width();
var resize = function (ev) {
if (cur_windows_width != $(window).width()) {
cur_windows_width = $(window).width();
clearTimeout(timer);
timer = setTimeout(notify, 100);
}
};
var notify = function () {
for (var i = 0, cnt = registered.length; i < cnt; i++) {
registered[i].apply();
}
};
return {
register: function (fn) {
registered.push(fn);
if (inited === false) {
$(window).bind('resize', resize);
inited = true;
}
},
unregister: function (fn) {
for (var i = 0, cnt = registered.length; i < cnt; i++) {
if (registered[i] == fn) {
delete registered[i];
break;
}
}
},
refresh: function () {
clearTimeout(timer);
timer = setTimeout(notify, 100);
}
}
}());
var TabDrop = function (element, options) {
this.element = $(element);
this.options = options;
this.dropdown = $('
' + options.text + ' ')
.prependTo(this.element);
if (this.element.parent().is('.tabs-below')) {
this.dropdown.addClass('dropup');
}
WinReszier.register($.proxy(this.layout, this));
this.layout();
};
TabDrop.prototype = {
constructor: TabDrop,
layout: function () {
var collection = [];
var dropdown = this.dropdown;
var options = this.options;
var that = this;
this.dropdown.removeClass('hide');
function setDropdownText(text) {
dropdown.find('a.dropdown-toggle').html('
' + text + ' ');
}
function setDropdownDefaultText() {
dropdown.find('a.dropdown-toggle').html(options.text + '
');
}
this.element
.append(this.dropdown.find('li'))
.find('>li')
.not('.tabdrop')
.each(function () {
if (this.offsetTop > options.offsetTop) {
collection.push(this);
}
});
this.element.find('>li').not('.tabdrop,.notatab').off("click");
this.element.find('>li').not('.tabdrop,.notatab').on("click", function () {
setDropdownDefaultText();
WinReszier.refresh();
//$(window).trigger('resize')
});
if (collection.length > 0) {
collection = $(collection);
this.dropdown
.find('ul')
.empty()
.append(collection);
this.dropdown.on("click", "li:not(.notatab)", function (event) {
var display = $(this).text();
setDropdownText(display);
//$('.drop-tabs').tabdrop('layout');
});
if (this.dropdown.find('.active').length == 1) {
this.dropdown.addClass('active');
setDropdownText(this.dropdown.find('.active > a').text());
} else {
this.dropdown.removeClass('active');
setDropdownDefaultText();
}
} else {
this.dropdown.addClass('hide');
}
}
}
$.fn.tabdrop = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('tabdrop'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('tabdrop', (data = new TabDrop(this, $.extend({}, $.fn.tabdrop.defaults, options))));
}
if (typeof option == 'string') {
data[option]();
}
})
};
$.fn.tabdrop.defaults = {
text: '
',
offsetTop: 0
};
$.fn.tabdrop.Constructor = TabDrop;
}(window.jQuery);
/*! version : 4.17.37
=========================================================
bootstrap-datetimejs
https://github.com/Eonasdan/bootstrap-datetimepicker
Copyright (c) 2015 Jonathan Peterson
=========================================================
*/
/*
The MIT License (MIT)
Copyright (c) 2015 Jonathan Peterson
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.
*/
/*global define:false */
/*global exports:false */
/*global require:false */
/*global jQuery:false */
/*global moment:false */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD is used - Register as an anonymous module.
define(['jquery', 'moment'], factory);
} else if (typeof exports === 'object') {
factory(require('jquery'), require('moment'));
} else {
// Neither AMD nor CommonJS used. Use global variables.
if (typeof jQuery === 'undefined') {
throw 'bootstrap-datetimepicker requires jQuery to be loaded first';
}
if (typeof moment === 'undefined') {
throw 'bootstrap-datetimepicker requires Moment.js to be loaded first';
}
factory(jQuery, moment);
}
}(function ($, moment) {
'use strict';
if (!moment) {
throw new Error('bootstrap-datetimepicker requires Moment.js to be loaded first');
}
var dateTimePicker = function (element, options) {
var picker = {},
date,
viewDate,
unset = true,
input,
component = false,
widget = false,
use24Hours,
minViewModeNumber = 0,
actualFormat,
parseFormats,
currentViewMode,
datePickerModes = [
{
clsName: 'days',
navFnc: 'M',
navStep: 1
},
{
clsName: 'months',
navFnc: 'y',
navStep: 1
},
{
clsName: 'years',
navFnc: 'y',
navStep: 10
},
{
clsName: 'decades',
navFnc: 'y',
navStep: 100
}
],
viewModes = ['days', 'months', 'years', 'decades'],
verticalModes = ['top', 'bottom', 'auto'],
horizontalModes = ['left', 'right', 'auto'],
toolbarPlacements = ['default', 'top', 'bottom'],
keyMap = {
'up': 38,
38: 'up',
'down': 40,
40: 'down',
'left': 37,
37: 'left',
'right': 39,
39: 'right',
'tab': 9,
9: 'tab',
'escape': 27,
27: 'escape',
'enter': 13,
13: 'enter',
'pageUp': 33,
33: 'pageUp',
'pageDown': 34,
34: 'pageDown',
'shift': 16,
16: 'shift',
'control': 17,
17: 'control',
'space': 32,
32: 'space',
't': 84,
84: 't',
'delete': 46,
46: 'delete'
},
keyState = {},
/********************************************************************************
*
* Private functions
*
********************************************************************************/
getMoment = function (d) {
var tzEnabled = false,
returnMoment,
currentZoneOffset,
incomingZoneOffset,
timeZoneIndicator,
dateWithTimeZoneInfo;
if (parseFormats === undefined) {
initFormatting(); // reinit formatting
}
if (moment.tz !== undefined && options.timeZone !== undefined && options.timeZone !== null && options.timeZone !== '') {
tzEnabled = true;
}
if (d === undefined || d === null) {
if (tzEnabled) {
returnMoment = moment().tz(options.timeZone).startOf('d');
} else {
returnMoment = moment().startOf('d');
}
} else {
if (tzEnabled) {
currentZoneOffset = moment().tz(options.timeZone).utcOffset();
incomingZoneOffset = moment(d, parseFormats, options.useStrict).utcOffset();
if (incomingZoneOffset !== currentZoneOffset) {
timeZoneIndicator = moment().tz(options.timeZone).format('Z');
dateWithTimeZoneInfo = moment(d, parseFormats, options.useStrict).format('YYYY-MM-DD[T]HH:mm:ss') + timeZoneIndicator;
returnMoment = moment(dateWithTimeZoneInfo, parseFormats, options.useStrict).tz(options.timeZone);
} else {
returnMoment = moment(d, parseFormats, options.useStrict).tz(options.timeZone);
}
} else {
returnMoment = moment(d, parseFormats, options.useStrict);
}
}
return returnMoment;
},
isEnabled = function (granularity) {
if (typeof granularity !== 'string' || granularity.length > 1) {
throw new TypeError('isEnabled expects a single character string parameter');
}
switch (granularity) {
case 'y':
return actualFormat.indexOf('Y') !== -1;
case 'M':
return actualFormat.indexOf('M') !== -1;
case 'd':
return actualFormat.toLowerCase().indexOf('d') !== -1;
case 'h':
case 'H':
return actualFormat.toLowerCase().indexOf('h') !== -1;
case 'm':
return actualFormat.indexOf('m') !== -1;
case 's':
return actualFormat.indexOf('s') !== -1;
default:
return false;
}
},
hasTime = function () {
return (isEnabled('h') || isEnabled('m') || isEnabled('s'));
},
hasDate = function () {
return (isEnabled('y') || isEnabled('M') || isEnabled('d'));
},
getDatePickerTemplate = function () {
var headTemplate = $('')
.append($('')
.append($('').addClass('prev').attr('data-action', 'previous')
.append($('
').addClass(options.icons.previous))
)
.append($('').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', (options.calendarWeeks ? '6' : '5')))
.append($('').addClass('next').attr('data-action', 'next')
.append($('').addClass(options.icons.next))
)
),
contTemplate = $('')
.append($('')
.append($('').attr('colspan', (options.calendarWeeks ? '8' : '7')))
);
return [
$('').addClass('datepicker-days')
.append($('').addClass('table-condensed')
.append(headTemplate)
.append($(''))
),
$('
').addClass('datepicker-months')
.append($('
').addClass('table-condensed')
.append(headTemplate.clone())
.append(contTemplate.clone())
),
$('
').addClass('datepicker-years')
.append($('
').addClass('table-condensed')
.append(headTemplate.clone())
.append(contTemplate.clone())
),
$('
').addClass('datepicker-decades')
.append($('
').addClass('table-condensed')
.append(headTemplate.clone())
.append(contTemplate.clone())
)
];
},
getTimePickerMainTemplate = function () {
var topRow = $(''),
middleRow = $(''),
bottomRow = $('');
if (isEnabled('h')) {
topRow.append($('
')
.append($('').attr({ href: '#', tabindex: '-1', 'title': options.tooltips.incrementHour }).addClass('btn').attr('data-action', 'incrementHours')
.append($('').addClass(options.icons.up))));
middleRow.append($(' ')
.append($('').addClass('timepicker-hour').attr({ 'data-time-component': 'hours', 'title': options.tooltips.pickHour }).attr('data-action', 'showHours')));
bottomRow.append($(' ')
.append($('').attr({ href: '#', tabindex: '-1', 'title': options.tooltips.decrementHour }).addClass('btn').attr('data-action', 'decrementHours')
.append($('').addClass(options.icons.down))));
}
if (isEnabled('m')) {
if (isEnabled('h')) {
topRow.append($(' ').addClass('separator'));
middleRow.append($(' ').addClass('separator').html(':'));
bottomRow.append($(' ').addClass('separator'));
}
topRow.append($(' ')
.append($('').attr({ href: '#', tabindex: '-1', 'title': options.tooltips.incrementMinute }).addClass('btn').attr('data-action', 'incrementMinutes')
.append($('').addClass(options.icons.up))));
middleRow.append($(' ')
.append($('').addClass('timepicker-minute').attr({ 'data-time-component': 'minutes', 'title': options.tooltips.pickMinute }).attr('data-action', 'showMinutes')));
bottomRow.append($(' ')
.append($('').attr({ href: '#', tabindex: '-1', 'title': options.tooltips.decrementMinute }).addClass('btn').attr('data-action', 'decrementMinutes')
.append($('').addClass(options.icons.down))));
}
if (isEnabled('s')) {
if (isEnabled('m')) {
topRow.append($(' ').addClass('separator'));
middleRow.append($(' ').addClass('separator').html(':'));
bottomRow.append($(' ').addClass('separator'));
}
topRow.append($(' ')
.append($('').attr({ href: '#', tabindex: '-1', 'title': options.tooltips.incrementSecond }).addClass('btn').attr('data-action', 'incrementSeconds')
.append($('').addClass(options.icons.up))));
middleRow.append($(' ')
.append($('').addClass('timepicker-second').attr({ 'data-time-component': 'seconds', 'title': options.tooltips.pickSecond }).attr('data-action', 'showSeconds')));
bottomRow.append($(' ')
.append($('').attr({ href: '#', tabindex: '-1', 'title': options.tooltips.decrementSecond }).addClass('btn').attr('data-action', 'decrementSeconds')
.append($('').addClass(options.icons.down))));
}
if (!use24Hours) {
topRow.append($(' ').addClass('separator'));
middleRow.append($(' ')
.append($('').addClass('btn btn-primary').attr({ 'data-action': 'togglePeriod', tabindex: '-1', 'title': options.tooltips.togglePeriod })));
bottomRow.append($(' ').addClass('separator'));
}
return $('').addClass('timepicker-picker')
.append($('').addClass('table-condensed')
.append([topRow, middleRow, bottomRow]));
},
getTimePickerTemplate = function () {
var hoursView = $('
').addClass('timepicker-hours')
.append($('
').addClass('table-condensed')),
minutesView = $('
').addClass('timepicker-minutes')
.append($('
').addClass('table-condensed')),
secondsView = $('
').addClass('timepicker-seconds')
.append($('
').addClass('table-condensed')),
ret = [getTimePickerMainTemplate()];
if (isEnabled('h')) {
ret.push(hoursView);
}
if (isEnabled('m')) {
ret.push(minutesView);
}
if (isEnabled('s')) {
ret.push(secondsView);
}
return ret;
},
getToolbar = function () {
var row = [];
if (options.showTodayButton) {
row.push($('
').append($('').attr({ 'data-action': 'today', 'title': options.tooltips.today }).append($('').addClass(options.icons.today))));
}
if (!options.sideBySide && hasDate() && hasTime()) {
row.push($(' ').append($('').attr({ 'data-action': 'togglePicker', 'title': options.tooltips.selectTime }).append($('').addClass(options.icons.time))));
}
if (options.showClear) {
row.push($(' ').append($('').attr({ 'data-action': 'clear', 'title': options.tooltips.clear }).append($('').addClass(options.icons.clear))));
}
if (options.showClose) {
row.push($(' ').append($('').attr({ 'data-action': 'close', 'title': options.tooltips.close }).append($('').addClass(options.icons.close))));
}
return $('').addClass('table-condensed').append($('').append($('').append(row)));
},
getTemplate = function () {
var template = $('').addClass('bootstrap-datetimepicker-widget dropdown-menu'),
dateView = $('
').addClass('datepicker').append(getDatePickerTemplate()),
timeView = $('
').addClass('timepicker').append(getTimePickerTemplate()),
content = $('
'),
currentDate = viewDate.clone().startOf('w').startOf('d');
if (options.calendarWeeks === true) {
row.append($('');
if (options.calendarWeeks) {
row.append('');
}
html.push(row);
}
clsName = '';
if (currentDate.isBefore(viewDate, 'M')) {
clsName += ' old';
}
if (currentDate.isAfter(viewDate, 'M')) {
clsName += ' new';
}
if (currentDate.isSame(date, 'd') && !unset) {
clsName += ' active';
}
if (!isValid(currentDate, 'd')) {
clsName += ' disabled';
}
if (currentDate.isSame(getMoment(), 'd')) {
clsName += ' today';
}
if (currentDate.day() === 0 || currentDate.day() === 6) {
clsName += ' weekend';
}
row.append('');
currentDate.add(1, 'd');
}
daysView.find('tbody').empty().append(html);
updateMonths();
updateYears();
updateDecades();
},
fillHours = function () {
var table = widget.find('.timepicker-hours table'),
currentHour = viewDate.clone().startOf('d'),
html = [],
row = $('');
if (viewDate.hour() > 11 && !use24Hours) {
currentHour.hour(12);
}
while (currentHour.isSame(viewDate, 'd') && (use24Hours || (viewDate.hour() < 12 && currentHour.hour() < 12) || viewDate.hour() > 11)) {
if (currentHour.hour() % 4 === 0) {
row = $('');
html.push(row);
}
row.append('');
currentHour.add(1, 'h');
}
table.empty().append(html);
},
fillMinutes = function () {
var table = widget.find('.timepicker-minutes table'),
currentMinute = viewDate.clone().startOf('h'),
html = [],
row = $(''),
step = options.stepping === 1 ? 5 : options.stepping;
while (viewDate.isSame(currentMinute, 'h')) {
if (currentMinute.minute() % (step * 4) === 0) {
row = $('');
html.push(row);
}
row.append('');
currentMinute.add(step, 'm');
}
table.empty().append(html);
},
fillSeconds = function () {
var table = widget.find('.timepicker-seconds table'),
currentSecond = viewDate.clone().startOf('m'),
html = [],
row = $('');
while (viewDate.isSame(currentSecond, 'm')) {
if (currentSecond.second() % 20 === 0) {
row = $('');
html.push(row);
}
row.append('');
currentSecond.add(5, 's');
}
table.empty().append(html);
},
fillTime = function () {
var toggle, newDate, timeComponents = widget.find('.timepicker span[data-time-component]');
if (!use24Hours) {
toggle = widget.find('.timepicker [data-action=togglePeriod]');
newDate = date.clone().add((date.hours() >= 12) ? -12 : 12, 'h');
toggle.text(date.format('A'));
if (isValid(newDate, 'h')) {
toggle.removeClass('disabled');
} else {
toggle.addClass('disabled');
}
}
timeComponents.filter('[data-time-component=hours]').text(date.format(use24Hours ? 'HH' : 'hh'));
timeComponents.filter('[data-time-component=minutes]').text(date.format('mm'));
timeComponents.filter('[data-time-component=seconds]').text(date.format('ss'));
fillHours();
fillMinutes();
fillSeconds();
},
update = function () {
if (!widget) {
return;
}
fillDate();
fillTime();
},
setValue = function (targetMoment) {
var oldDate = unset ? null : date;
// case of calling setValue(null or false)
if (!targetMoment) {
unset = true;
input.val('');
element.data('date', '');
notifyEvent({
type: 'dp.change',
date: false,
oldDate: oldDate
});
update();
return;
}
targetMoment = targetMoment.clone().locale(options.locale);
if (options.stepping !== 1) {
targetMoment.minutes((Math.round(targetMoment.minutes() / options.stepping) * options.stepping) % 60).seconds(0);
}
if (isValid(targetMoment)) {
date = targetMoment;
viewDate = date.clone();
input.val(date.format(actualFormat));
element.data('date', date.format(actualFormat));
unset = false;
update();
notifyEvent({
type: 'dp.change',
date: date.clone(),
oldDate: oldDate
});
} else {
if (!options.keepInvalid) {
input.val(unset ? '' : date.format(actualFormat));
}
notifyEvent({
type: 'dp.error',
date: targetMoment
});
}
},
hide = function () {
///Hides the widget. Possibly will emit dp.hide
var transitioning = false;
if (!widget) {
return picker;
}
// Ignore event if in the middle of a picker transition
widget.find('.collapse').each(function () {
var collapseData = $(this).data('collapse');
if (collapseData && collapseData.transitioning) {
transitioning = true;
return false;
}
return true;
});
if (transitioning) {
return picker;
}
if (component && component.hasClass('btn')) {
component.toggleClass('active');
}
widget.hide();
$(window).off('resize', place);
widget.off('click', '[data-action]');
widget.off('mousedown', false);
widget.remove();
widget = false;
notifyEvent({
type: 'dp.hide',
date: date.clone()
});
input.blur();
return picker;
},
clear = function () {
setValue(null);
},
/********************************************************************************
*
* Widget UI interaction functions
*
********************************************************************************/
actions = {
next: function () {
var navFnc = datePickerModes[currentViewMode].navFnc;
viewDate.add(datePickerModes[currentViewMode].navStep, navFnc);
fillDate();
viewUpdate(navFnc);
},
previous: function () {
var navFnc = datePickerModes[currentViewMode].navFnc;
viewDate.subtract(datePickerModes[currentViewMode].navStep, navFnc);
fillDate();
viewUpdate(navFnc);
},
pickerSwitch: function () {
showMode(1);
},
selectMonth: function (e) {
var month = $(e.target).closest('tbody').find('span').index($(e.target));
viewDate.month(month);
if (currentViewMode === minViewModeNumber) {
setValue(date.clone().year(viewDate.year()).month(viewDate.month()));
if (!options.inline) {
hide();
}
} else {
showMode(-1);
fillDate();
}
viewUpdate('M');
},
selectYear: function (e) {
var year = parseInt($(e.target).text(), 10) || 0;
viewDate.year(year);
if (currentViewMode === minViewModeNumber) {
setValue(date.clone().year(viewDate.year()));
if (!options.inline) {
hide();
}
} else {
showMode(-1);
fillDate();
}
viewUpdate('YYYY');
},
selectDecade: function (e) {
var year = parseInt($(e.target).data('selection'), 10) || 0;
viewDate.year(year);
if (currentViewMode === minViewModeNumber) {
setValue(date.clone().year(viewDate.year()));
if (!options.inline) {
hide();
}
} else {
showMode(-1);
fillDate();
}
viewUpdate('YYYY');
},
selectDay: function (e) {
var day = viewDate.clone();
if ($(e.target).is('.old')) {
day.subtract(1, 'M');
}
if ($(e.target).is('.new')) {
day.add(1, 'M');
}
setValue(day.date(parseInt($(e.target).text(), 10)));
if (!hasTime() && !options.keepOpen && !options.inline) {
hide();
}
},
incrementHours: function () {
var newDate = date.clone().add(1, 'h');
if (isValid(newDate, 'h')) {
setValue(newDate);
}
},
incrementMinutes: function () {
var newDate = date.clone().add(options.stepping, 'm');
if (isValid(newDate, 'm')) {
setValue(newDate);
}
},
incrementSeconds: function () {
var newDate = date.clone().add(1, 's');
if (isValid(newDate, 's')) {
setValue(newDate);
}
},
decrementHours: function () {
var newDate = date.clone().subtract(1, 'h');
if (isValid(newDate, 'h')) {
setValue(newDate);
}
},
decrementMinutes: function () {
var newDate = date.clone().subtract(options.stepping, 'm');
if (isValid(newDate, 'm')) {
setValue(newDate);
}
},
decrementSeconds: function () {
var newDate = date.clone().subtract(1, 's');
if (isValid(newDate, 's')) {
setValue(newDate);
}
},
togglePeriod: function () {
setValue(date.clone().add((date.hours() >= 12) ? -12 : 12, 'h'));
},
togglePicker: function (e) {
var $this = $(e.target),
$parent = $this.closest('ul'),
expanded = $parent.find('.in'),
closed = $parent.find('.collapse:not(.in)'),
collapseData;
if (expanded && expanded.length) {
collapseData = expanded.data('collapse');
if (collapseData && collapseData.transitioning) {
return;
}
if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it
expanded.collapse('hide');
closed.collapse('show');
} else { // otherwise just toggle in class on the two views
expanded.removeClass('in');
closed.addClass('in');
}
if ($this.is('span')) {
$this.toggleClass(options.icons.time + ' ' + options.icons.date);
} else {
$this.find('span').toggleClass(options.icons.time + ' ' + options.icons.date);
}
// NOTE: uncomment if toggled state will be restored in show()
//if (component) {
// component.find('span').toggleClass(options.icons.time + ' ' + options.icons.date);
//}
}
},
showPicker: function () {
widget.find('.timepicker > div:not(.timepicker-picker)').hide();
widget.find('.timepicker .timepicker-picker').show();
},
showHours: function () {
widget.find('.timepicker .timepicker-picker').hide();
widget.find('.timepicker .timepicker-hours').show();
},
showMinutes: function () {
widget.find('.timepicker .timepicker-picker').hide();
widget.find('.timepicker .timepicker-minutes').show();
},
showSeconds: function () {
widget.find('.timepicker .timepicker-picker').hide();
widget.find('.timepicker .timepicker-seconds').show();
},
selectHour: function (e) {
var hour = parseInt($(e.target).text(), 10);
if (!use24Hours) {
if (date.hours() >= 12) {
if (hour !== 12) {
hour += 12;
}
} else {
if (hour === 12) {
hour = 0;
}
}
}
setValue(date.clone().hours(hour));
actions.showPicker.call(picker);
},
selectMinute: function (e) {
setValue(date.clone().minutes(parseInt($(e.target).text(), 10)));
actions.showPicker.call(picker);
},
selectSecond: function (e) {
setValue(date.clone().seconds(parseInt($(e.target).text(), 10)));
actions.showPicker.call(picker);
},
clear: clear,
today: function () {
var todaysDate = getMoment();
if (isValid(todaysDate, 'd')) {
setValue(todaysDate);
}
},
close: hide
},
doAction = function (e) {
if ($(e.currentTarget).is('.disabled')) {
return false;
}
actions[$(e.currentTarget).data('action')].apply(picker, arguments);
return false;
},
show = function () {
///Shows the widget. Possibly will emit dp.show and dp.change
var currentMoment,
useCurrentGranularity = {
'year': function (m) {
return m.month(0).date(1).hours(0).seconds(0).minutes(0);
},
'month': function (m) {
return m.date(1).hours(0).seconds(0).minutes(0);
},
'day': function (m) {
return m.hours(0).seconds(0).minutes(0);
},
'hour': function (m) {
return m.seconds(0).minutes(0);
},
'minute': function (m) {
return m.seconds(0);
}
};
if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly')) || widget) {
return picker;
}
if (input.val() !== undefined && input.val().trim().length !== 0) {
setValue(parseInputDate(input.val().trim()));
} else if (options.useCurrent && unset && ((input.is('input') && input.val().trim().length === 0) || options.inline)) {
currentMoment = getMoment();
if (typeof options.useCurrent === 'string') {
currentMoment = useCurrentGranularity[options.useCurrent](currentMoment);
}
setValue(currentMoment);
}
widget = getTemplate();
fillDow();
fillMonths();
widget.find('.timepicker-hours').hide();
widget.find('.timepicker-minutes').hide();
widget.find('.timepicker-seconds').hide();
update();
showMode();
$(window).on('resize', place);
widget.on('click', '[data-action]', doAction); // this handles clicks on the widget
widget.on('mousedown', false);
if (component && component.hasClass('btn')) {
component.toggleClass('active');
}
widget.show();
place();
if (options.focusOnShow && !input.is(':focus')) {
input.focus();
}
notifyEvent({
type: 'dp.show'
});
return picker;
},
toggle = function () {
/// Shows or hides the widget
return (widget ? hide() : show());
},
parseInputDate = function (inputDate) {
if (options.parseInputDate === undefined) {
if (moment.isMoment(inputDate) || inputDate instanceof Date) {
inputDate = moment(inputDate);
} else {
inputDate = getMoment(inputDate);
}
} else {
inputDate = options.parseInputDate(inputDate);
}
inputDate.locale(options.locale);
return inputDate;
},
keydown = function (e) {
var handler = null,
index,
index2,
pressedKeys = [],
pressedModifiers = {},
currentKey = e.which,
keyBindKeys,
allModifiersPressed,
pressed = 'p';
keyState[currentKey] = pressed;
for (index in keyState) {
if (keyState.hasOwnProperty(index) && keyState[index] === pressed) {
pressedKeys.push(index);
if (parseInt(index, 10) !== currentKey) {
pressedModifiers[index] = true;
}
}
}
for (index in options.keyBinds) {
if (options.keyBinds.hasOwnProperty(index) && typeof (options.keyBinds[index]) === 'function') {
keyBindKeys = index.split(' ');
if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) {
allModifiersPressed = true;
for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) {
if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) {
allModifiersPressed = false;
break;
}
}
if (allModifiersPressed) {
handler = options.keyBinds[index];
break;
}
}
}
}
if (handler) {
handler.call(picker, widget);
e.stopPropagation();
e.preventDefault();
}
},
keyup = function (e) {
keyState[e.which] = 'r';
e.stopPropagation();
e.preventDefault();
},
change = function (e) {
var val = $(e.target).val().trim(),
parsedDate = val ? parseInputDate(val) : null;
setValue(parsedDate);
e.stopImmediatePropagation();
return false;
},
attachDatePickerElementEvents = function () {
input.on({
'change': change,
'blur': options.debug ? '' : hide,
'keydown': keydown,
'keyup': keyup,
'focus': options.allowInputToggle ? show : ''
});
if (element.is('input')) {
input.on({
'focus': show
});
} else if (component) {
component.on('click', toggle);
component.on('mousedown', false);
}
},
detachDatePickerElementEvents = function () {
input.off({
'change': change,
'blur': blur,
'keydown': keydown,
'keyup': keyup,
'focus': options.allowInputToggle ? hide : ''
});
if (element.is('input')) {
input.off({
'focus': show
});
} else if (component) {
component.off('click', toggle);
component.off('mousedown', false);
}
},
indexGivenDates = function (givenDatesArray) {
// Store given enabledDates and disabledDates as keys.
// This way we can check their existence in O(1) time instead of looping through whole array.
// (for example: options.enabledDates['2014-02-27'] === true)
var givenDatesIndexed = {};
$.each(givenDatesArray, function () {
var dDate = parseInputDate(this);
if (dDate.isValid()) {
givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true;
}
});
return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false;
},
indexGivenHours = function (givenHoursArray) {
// Store given enabledHours and disabledHours as keys.
// This way we can check their existence in O(1) time instead of looping through whole array.
// (for example: options.enabledHours['2014-02-27'] === true)
var givenHoursIndexed = {};
$.each(givenHoursArray, function () {
givenHoursIndexed[this] = true;
});
return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false;
},
initFormatting = function () {
var format = options.format || 'L LT';
actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) {
var newinput = date.localeData().longDateFormat(formatInput) || formatInput;
return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740
return date.localeData().longDateFormat(formatInput2) || formatInput2;
});
});
parseFormats = options.extraFormats ? options.extraFormats.slice() : [];
if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(actualFormat) < 0) {
parseFormats.push(actualFormat);
}
use24Hours = (actualFormat.toLowerCase().indexOf('a') < 1 && actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1);
if (isEnabled('y')) {
minViewModeNumber = 2;
}
if (isEnabled('M')) {
minViewModeNumber = 1;
}
if (isEnabled('d')) {
minViewModeNumber = 0;
}
currentViewMode = Math.max(minViewModeNumber, currentViewMode);
if (!unset) {
setValue(date);
}
};
/********************************************************************************
*
* Public API functions
* =====================
*
* Important: Do not expose direct references to private objects or the options
* object to the outer world. Always return a clone when returning values or make
* a clone when setting a private variable.
*
********************************************************************************/
picker.destroy = function () {
///Destroys the widget and removes all attached event listeners
hide();
detachDatePickerElementEvents();
element.removeData('DateTimePicker');
element.removeData('date');
};
picker.toggle = toggle;
picker.show = show;
picker.hide = hide;
picker.disable = function () {
///Disables the input element, the component is attached to, by adding a disabled="true" attribute to it.
///If the widget was visible before that call it is hidden. Possibly emits dp.hide
hide();
if (component && component.hasClass('btn')) {
component.addClass('disabled');
}
input.prop('disabled', true);
return picker;
};
picker.enable = function () {
///Enables the input element, the component is attached to, by removing disabled attribute from it.
if (component && component.hasClass('btn')) {
component.removeClass('disabled');
}
input.prop('disabled', false);
return picker;
};
picker.ignoreReadonly = function (ignoreReadonly) {
if (arguments.length === 0) {
return options.ignoreReadonly;
}
if (typeof ignoreReadonly !== 'boolean') {
throw new TypeError('ignoreReadonly () expects a boolean parameter');
}
options.ignoreReadonly = ignoreReadonly;
return picker;
};
picker.options = function (newOptions) {
if (arguments.length === 0) {
return $.extend(true, {}, options);
}
if (!(newOptions instanceof Object)) {
throw new TypeError('options() options parameter should be an object');
}
$.extend(true, options, newOptions);
$.each(options, function (key, value) {
if (picker[key] !== undefined) {
picker[key](value);
} else {
throw new TypeError('option ' + key + ' is not recognized!');
}
});
return picker;
};
picker.date = function (newDate) {
///
///Returns the component's model current date, a moment object or null if not set.
///date.clone()
///
///
///Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.
/// Takes string, Date, moment, null parameter.
///
if (arguments.length === 0) {
if (unset) {
return null;
}
return date.clone();
}
if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
throw new TypeError('date() parameter must be one of [null, string, moment or Date]');
}
setValue(newDate === null ? null : parseInputDate(newDate));
return picker;
};
picker.format = function (newFormat) {
///test su
/// info about para
///returns foo
if (arguments.length === 0) {
return options.format;
}
if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) {
throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat);
}
options.format = newFormat;
if (actualFormat) {
initFormatting(); // reinit formatting
}
return picker;
};
picker.timeZone = function (newZone) {
if (arguments.length === 0) {
return options.timeZone;
}
options.timeZone = newZone;
return picker;
};
picker.dayViewHeaderFormat = function (newFormat) {
if (arguments.length === 0) {
return options.dayViewHeaderFormat;
}
if (typeof newFormat !== 'string') {
throw new TypeError('dayViewHeaderFormat() expects a string parameter');
}
options.dayViewHeaderFormat = newFormat;
return picker;
};
picker.extraFormats = function (formats) {
if (arguments.length === 0) {
return options.extraFormats;
}
if (formats !== false && !(formats instanceof Array)) {
throw new TypeError('extraFormats() expects an array or false parameter');
}
options.extraFormats = formats;
if (parseFormats) {
initFormatting(); // reinit formatting
}
return picker;
};
picker.disabledDates = function (dates) {
///
///Returns an array with the currently set disabled dates on the component.
///options.disabledDates
///
///
///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
///options.enabledDates if such exist.
/// Takes an [ string or Date or moment ] of values and allows the user to select only from those days.
///
if (arguments.length === 0) {
return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates);
}
if (!dates) {
options.disabledDates = false;
update();
return picker;
}
if (!(dates instanceof Array)) {
throw new TypeError('disabledDates() expects an array parameter');
}
options.disabledDates = indexGivenDates(dates);
options.enabledDates = false;
update();
return picker;
};
picker.enabledDates = function (dates) {
///
///Returns an array with the currently set enabled dates on the component.
///options.enabledDates
///
///
///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.
/// Takes an [ string or Date or moment ] of values and allows the user to select only from those days.
///
if (arguments.length === 0) {
return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates);
}
if (!dates) {
options.enabledDates = false;
update();
return picker;
}
if (!(dates instanceof Array)) {
throw new TypeError('enabledDates() expects an array parameter');
}
options.enabledDates = indexGivenDates(dates);
options.disabledDates = false;
update();
return picker;
};
picker.daysOfWeekDisabled = function (daysOfWeekDisabled) {
if (arguments.length === 0) {
return options.daysOfWeekDisabled.splice(0);
}
if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) {
options.daysOfWeekDisabled = false;
update();
return picker;
}
if (!(daysOfWeekDisabled instanceof Array)) {
throw new TypeError('daysOfWeekDisabled() expects an array parameter');
}
options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) {
currentValue = parseInt(currentValue, 10);
if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) {
return previousValue;
}
if (previousValue.indexOf(currentValue) === -1) {
previousValue.push(currentValue);
}
return previousValue;
}, []).sort();
if (options.useCurrent && !options.keepInvalid) {
var tries = 0;
while (!isValid(date, 'd')) {
date.add(1, 'd');
if (tries === 7) {
throw 'Tried 7 times to find a valid date';
}
tries++;
}
setValue(date);
}
update();
return picker;
};
picker.maxDate = function (maxDate) {
if (arguments.length === 0) {
return options.maxDate ? options.maxDate.clone() : options.maxDate;
}
if ((typeof maxDate === 'boolean') && maxDate === false) {
options.maxDate = false;
update();
return picker;
}
if (typeof maxDate === 'string') {
if (maxDate === 'now' || maxDate === 'moment') {
maxDate = getMoment();
}
}
var parsedDate = parseInputDate(maxDate);
if (!parsedDate.isValid()) {
throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate);
}
if (options.minDate && parsedDate.isBefore(options.minDate)) {
throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat));
}
options.maxDate = parsedDate;
if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) {
setValue(options.maxDate);
}
if (viewDate.isAfter(parsedDate)) {
viewDate = parsedDate.clone().subtract(options.stepping, 'm');
}
update();
return picker;
};
picker.minDate = function (minDate) {
if (arguments.length === 0) {
return options.minDate ? options.minDate.clone() : options.minDate;
}
if ((typeof minDate === 'boolean') && minDate === false) {
options.minDate = false;
update();
return picker;
}
if (typeof minDate === 'string') {
if (minDate === 'now' || minDate === 'moment') {
minDate = getMoment();
}
}
var parsedDate = parseInputDate(minDate);
if (!parsedDate.isValid()) {
throw new TypeError('minDate() Could not parse date parameter: ' + minDate);
}
if (options.maxDate && parsedDate.isAfter(options.maxDate)) {
throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat));
}
options.minDate = parsedDate;
if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) {
setValue(options.minDate);
}
if (viewDate.isBefore(parsedDate)) {
viewDate = parsedDate.clone().add(options.stepping, 'm');
}
update();
return picker;
};
picker.defaultDate = function (defaultDate) {
///
///Returns a moment with the options.defaultDate option configuration or false if not set
///date.clone()
///
///
///Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.
/// Takes a string, Date, moment, boolean:false
///
if (arguments.length === 0) {
return options.defaultDate ? options.defaultDate.clone() : options.defaultDate;
}
if (!defaultDate) {
options.defaultDate = false;
return picker;
}
if (typeof defaultDate === 'string') {
if (defaultDate === 'now' || defaultDate === 'moment') {
defaultDate = getMoment();
}
}
var parsedDate = parseInputDate(defaultDate);
if (!parsedDate.isValid()) {
throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate);
}
if (!isValid(parsedDate)) {
throw new TypeError('defaultDate() date passed is invalid according to component setup validations');
}
options.defaultDate = parsedDate;
if ((options.defaultDate && options.inline) || input.val().trim() === '') {
setValue(options.defaultDate);
}
return picker;
};
picker.locale = function (locale) {
if (arguments.length === 0) {
return options.locale;
}
if (!moment.localeData(locale)) {
throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!');
}
options.locale = locale;
date.locale(options.locale);
viewDate.locale(options.locale);
if (actualFormat) {
initFormatting(); // reinit formatting
}
if (widget) {
hide();
show();
}
return picker;
};
picker.stepping = function (stepping) {
if (arguments.length === 0) {
return options.stepping;
}
stepping = parseInt(stepping, 10);
if (isNaN(stepping) || stepping < 1) {
stepping = 1;
}
options.stepping = stepping;
return picker;
};
picker.useCurrent = function (useCurrent) {
var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute'];
if (arguments.length === 0) {
return options.useCurrent;
}
if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) {
throw new TypeError('useCurrent() expects a boolean or string parameter');
}
if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) {
throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', '));
}
options.useCurrent = useCurrent;
return picker;
};
picker.collapse = function (collapse) {
if (arguments.length === 0) {
return options.collapse;
}
if (typeof collapse !== 'boolean') {
throw new TypeError('collapse() expects a boolean parameter');
}
if (options.collapse === collapse) {
return picker;
}
options.collapse = collapse;
if (widget) {
hide();
show();
}
return picker;
};
picker.icons = function (icons) {
if (arguments.length === 0) {
return $.extend({}, options.icons);
}
if (!(icons instanceof Object)) {
throw new TypeError('icons() expects parameter to be an Object');
}
$.extend(options.icons, icons);
if (widget) {
hide();
show();
}
return picker;
};
picker.tooltips = function (tooltips) {
if (arguments.length === 0) {
return $.extend({}, options.tooltips);
}
if (!(tooltips instanceof Object)) {
throw new TypeError('tooltips() expects parameter to be an Object');
}
$.extend(options.tooltips, tooltips);
if (widget) {
hide();
show();
}
return picker;
};
picker.useStrict = function (useStrict) {
if (arguments.length === 0) {
return options.useStrict;
}
if (typeof useStrict !== 'boolean') {
throw new TypeError('useStrict() expects a boolean parameter');
}
options.useStrict = useStrict;
return picker;
};
picker.sideBySide = function (sideBySide) {
if (arguments.length === 0) {
return options.sideBySide;
}
if (typeof sideBySide !== 'boolean') {
throw new TypeError('sideBySide() expects a boolean parameter');
}
options.sideBySide = sideBySide;
if (widget) {
hide();
show();
}
return picker;
};
picker.viewMode = function (viewMode) {
if (arguments.length === 0) {
return options.viewMode;
}
if (typeof viewMode !== 'string') {
throw new TypeError('viewMode() expects a string parameter');
}
if (viewModes.indexOf(viewMode) === -1) {
throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value');
}
options.viewMode = viewMode;
currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber);
showMode();
return picker;
};
picker.toolbarPlacement = function (toolbarPlacement) {
if (arguments.length === 0) {
return options.toolbarPlacement;
}
if (typeof toolbarPlacement !== 'string') {
throw new TypeError('toolbarPlacement() expects a string parameter');
}
if (toolbarPlacements.indexOf(toolbarPlacement) === -1) {
throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value');
}
options.toolbarPlacement = toolbarPlacement;
if (widget) {
hide();
show();
}
return picker;
};
picker.widgetPositioning = function (widgetPositioning) {
if (arguments.length === 0) {
return $.extend({}, options.widgetPositioning);
}
if (({}).toString.call(widgetPositioning) !== '[object Object]') {
throw new TypeError('widgetPositioning() expects an object variable');
}
if (widgetPositioning.horizontal) {
if (typeof widgetPositioning.horizontal !== 'string') {
throw new TypeError('widgetPositioning() horizontal variable must be a string');
}
widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase();
if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) {
throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')');
}
options.widgetPositioning.horizontal = widgetPositioning.horizontal;
}
if (widgetPositioning.vertical) {
if (typeof widgetPositioning.vertical !== 'string') {
throw new TypeError('widgetPositioning() vertical variable must be a string');
}
widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase();
if (verticalModes.indexOf(widgetPositioning.vertical) === -1) {
throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')');
}
options.widgetPositioning.vertical = widgetPositioning.vertical;
}
update();
return picker;
};
picker.calendarWeeks = function (calendarWeeks) {
if (arguments.length === 0) {
return options.calendarWeeks;
}
if (typeof calendarWeeks !== 'boolean') {
throw new TypeError('calendarWeeks() expects parameter to be a boolean value');
}
options.calendarWeeks = calendarWeeks;
update();
return picker;
};
picker.showTodayButton = function (showTodayButton) {
if (arguments.length === 0) {
return options.showTodayButton;
}
if (typeof showTodayButton !== 'boolean') {
throw new TypeError('showTodayButton() expects a boolean parameter');
}
options.showTodayButton = showTodayButton;
if (widget) {
hide();
show();
}
return picker;
};
picker.showClear = function (showClear) {
if (arguments.length === 0) {
return options.showClear;
}
if (typeof showClear !== 'boolean') {
throw new TypeError('showClear() expects a boolean parameter');
}
options.showClear = showClear;
if (widget) {
hide();
show();
}
return picker;
};
picker.widgetParent = function (widgetParent) {
if (arguments.length === 0) {
return options.widgetParent;
}
if (typeof widgetParent === 'string') {
widgetParent = $(widgetParent);
}
if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) {
throw new TypeError('widgetParent() expects a string or a jQuery object parameter');
}
options.widgetParent = widgetParent;
if (widget) {
hide();
show();
}
return picker;
};
picker.keepOpen = function (keepOpen) {
if (arguments.length === 0) {
return options.keepOpen;
}
if (typeof keepOpen !== 'boolean') {
throw new TypeError('keepOpen() expects a boolean parameter');
}
options.keepOpen = keepOpen;
return picker;
};
picker.focusOnShow = function (focusOnShow) {
if (arguments.length === 0) {
return options.focusOnShow;
}
if (typeof focusOnShow !== 'boolean') {
throw new TypeError('focusOnShow() expects a boolean parameter');
}
options.focusOnShow = focusOnShow;
return picker;
};
picker.inline = function (inline) {
if (arguments.length === 0) {
return options.inline;
}
if (typeof inline !== 'boolean') {
throw new TypeError('inline() expects a boolean parameter');
}
options.inline = inline;
return picker;
};
picker.clear = function () {
clear();
return picker;
};
picker.keyBinds = function (keyBinds) {
options.keyBinds = keyBinds;
return picker;
};
picker.getMoment = function (d) {
return getMoment(d);
};
picker.debug = function (debug) {
if (typeof debug !== 'boolean') {
throw new TypeError('debug() expects a boolean parameter');
}
options.debug = debug;
return picker;
};
picker.allowInputToggle = function (allowInputToggle) {
if (arguments.length === 0) {
return options.allowInputToggle;
}
if (typeof allowInputToggle !== 'boolean') {
throw new TypeError('allowInputToggle() expects a boolean parameter');
}
options.allowInputToggle = allowInputToggle;
return picker;
};
picker.showClose = function (showClose) {
if (arguments.length === 0) {
return options.showClose;
}
if (typeof showClose !== 'boolean') {
throw new TypeError('showClose() expects a boolean parameter');
}
options.showClose = showClose;
return picker;
};
picker.keepInvalid = function (keepInvalid) {
if (arguments.length === 0) {
return options.keepInvalid;
}
if (typeof keepInvalid !== 'boolean') {
throw new TypeError('keepInvalid() expects a boolean parameter');
}
options.keepInvalid = keepInvalid;
return picker;
};
picker.datepickerInput = function (datepickerInput) {
if (arguments.length === 0) {
return options.datepickerInput;
}
if (typeof datepickerInput !== 'string') {
throw new TypeError('datepickerInput() expects a string parameter');
}
options.datepickerInput = datepickerInput;
return picker;
};
picker.parseInputDate = function (parseInputDate) {
if (arguments.length === 0) {
return options.parseInputDate;
}
if (typeof parseInputDate !== 'function') {
throw new TypeError('parseInputDate() sholud be as function');
}
options.parseInputDate = parseInputDate;
return picker;
};
picker.disabledTimeIntervals = function (disabledTimeIntervals) {
///
///Returns an array with the currently set disabled dates on the component.
///options.disabledTimeIntervals
///
///
///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
///options.enabledDates if such exist.
/// Takes an [ string or Date or moment ] of values and allows the user to select only from those days.
///
if (arguments.length === 0) {
return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals);
}
if (!disabledTimeIntervals) {
options.disabledTimeIntervals = false;
update();
return picker;
}
if (!(disabledTimeIntervals instanceof Array)) {
throw new TypeError('disabledTimeIntervals() expects an array parameter');
}
options.disabledTimeIntervals = disabledTimeIntervals;
update();
return picker;
};
picker.disabledHours = function (hours) {
///
///Returns an array with the currently set disabled hours on the component.
///options.disabledHours
///
///
///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
///options.enabledHours if such exist.
/// Takes an [ int ] of values and disallows the user to select only from those hours.
///
if (arguments.length === 0) {
return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours);
}
if (!hours) {
options.disabledHours = false;
update();
return picker;
}
if (!(hours instanceof Array)) {
throw new TypeError('disabledHours() expects an array parameter');
}
options.disabledHours = indexGivenHours(hours);
options.enabledHours = false;
if (options.useCurrent && !options.keepInvalid) {
var tries = 0;
while (!isValid(date, 'h')) {
date.add(1, 'h');
if (tries === 24) {
throw 'Tried 24 times to find a valid date';
}
tries++;
}
setValue(date);
}
update();
return picker;
};
picker.enabledHours = function (hours) {
///
///Returns an array with the currently set enabled hours on the component.
///options.enabledHours
///
///
///Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.
/// Takes an [ int ] of values and allows the user to select only from those hours.
///
if (arguments.length === 0) {
return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours);
}
if (!hours) {
options.enabledHours = false;
update();
return picker;
}
if (!(hours instanceof Array)) {
throw new TypeError('enabledHours() expects an array parameter');
}
options.enabledHours = indexGivenHours(hours);
options.disabledHours = false;
if (options.useCurrent && !options.keepInvalid) {
var tries = 0;
while (!isValid(date, 'h')) {
date.add(1, 'h');
if (tries === 24) {
throw 'Tried 24 times to find a valid date';
}
tries++;
}
setValue(date);
}
update();
return picker;
};
picker.viewDate = function (newDate) {
///
///Returns the component's model current viewDate, a moment object or null if not set.
///viewDate.clone()
///
///
///Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.
/// Takes string, viewDate, moment, null parameter.
///
if (arguments.length === 0) {
return viewDate.clone();
}
if (!newDate) {
viewDate = date.clone();
return picker;
}
if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
throw new TypeError('viewDate() parameter must be one of [string, moment or Date]');
}
viewDate = parseInputDate(newDate);
viewUpdate();
return picker;
};
// initializing element and component attributes
if (element.is('input')) {
input = element;
} else {
input = element.find(options.datepickerInput);
if (input.size() === 0) {
input = element.find('input');
} else if (!input.is('input')) {
throw new Error('CSS class "' + options.datepickerInput + '" cannot be applied to non input element');
}
}
if (element.hasClass('input-group')) {
// in case there is more then one 'input-group-addon' Issue #48
if (element.find('.datepickerbutton').size() === 0) {
component = element.find('.input-group-addon');
} else {
component = element.find('.datepickerbutton');
}
}
if (!options.inline && !input.is('input')) {
throw new Error('Could not initialize DateTimePicker without an input element');
}
// Set defaults for date here now instead of in var declaration
initFormatting();
date = getMoment();
viewDate = date.clone();
$.extend(true, options, dataToOptions());
picker.options(options);
attachDatePickerElementEvents();
if (input.prop('disabled')) {
picker.disable();
}
if (input.is('input') && input.val().trim().length !== 0) {
setValue(parseInputDate(input.val().trim()));
}
else if (options.defaultDate && input.attr('placeholder') === undefined) {
setValue(options.defaultDate);
}
if (options.inline) {
show();
}
return picker;
};
/********************************************************************************
*
* jQuery plugin constructor and defaults object
*
********************************************************************************/
$.fn.datetimepicker = function (options) {
return this.each(function () {
var $this = $(this);
if (!$this.data('DateTimePicker')) {
// create a private copy of the defaults object
options = $.extend(true, {}, $.fn.datetimepicker.defaults, options);
$this.data('DateTimePicker', dateTimePicker($this, options));
}
});
};
$.fn.datetimepicker.defaults = {
timeZone: 'Etc/UTC',
format: false,
dayViewHeaderFormat: 'MMMM YYYY',
extraFormats: false,
stepping: 1,
minDate: false,
maxDate: false,
useCurrent: true,
collapse: true,
locale: moment.locale(),
defaultDate: false,
disabledDates: false,
enabledDates: false,
icons: {
time: 'glyphicon glyphicon-time',
date: 'glyphicon glyphicon-calendar',
up: 'glyphicon glyphicon-chevron-up',
down: 'glyphicon glyphicon-chevron-down',
previous: 'glyphicon glyphicon-chevron-left',
next: 'glyphicon glyphicon-chevron-right',
today: 'glyphicon glyphicon-screenshot',
clear: 'glyphicon glyphicon-trash',
close: 'glyphicon glyphicon-remove'
},
tooltips: {
today: 'Go to today',
clear: 'Clear selection',
close: 'Close the picker',
selectMonth: 'Select Month',
prevMonth: 'Previous Month',
nextMonth: 'Next Month',
selectYear: 'Select Year',
prevYear: 'Previous Year',
nextYear: 'Next Year',
selectDecade: 'Select Decade',
prevDecade: 'Previous Decade',
nextDecade: 'Next Decade',
prevCentury: 'Previous Century',
nextCentury: 'Next Century',
pickHour: 'Pick Hour',
incrementHour: 'Increment Hour',
decrementHour: 'Decrement Hour',
pickMinute: 'Pick Minute',
incrementMinute: 'Increment Minute',
decrementMinute: 'Decrement Minute',
pickSecond: 'Pick Second',
incrementSecond: 'Increment Second',
decrementSecond: 'Decrement Second',
togglePeriod: 'Toggle Period',
selectTime: 'Select Time'
},
useStrict: false,
sideBySide: false,
daysOfWeekDisabled: false,
calendarWeeks: false,
viewMode: 'days',
toolbarPlacement: 'default',
showTodayButton: false,
showClear: false,
showClose: false,
widgetPositioning: {
horizontal: 'auto',
vertical: 'auto'
},
widgetParent: null,
ignoreReadonly: false,
keepOpen: false,
focusOnShow: true,
inline: false,
keepInvalid: false,
datepickerInput: '.datepickerinput',
keyBinds: {
up: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().subtract(7, 'd'));
} else {
this.date(d.clone().add(this.stepping(), 'm'));
}
},
down: function (widget) {
if (!widget) {
this.show();
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().add(7, 'd'));
} else {
this.date(d.clone().subtract(this.stepping(), 'm'));
}
},
'control up': function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().subtract(1, 'y'));
} else {
this.date(d.clone().add(1, 'h'));
}
},
'control down': function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().add(1, 'y'));
} else {
this.date(d.clone().subtract(1, 'h'));
}
},
left: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().subtract(1, 'd'));
}
},
right: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().add(1, 'd'));
}
},
pageUp: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().subtract(1, 'M'));
}
},
pageDown: function (widget) {
if (!widget) {
return;
}
var d = this.date() || this.getMoment();
if (widget.find('.datepicker').is(':visible')) {
this.date(d.clone().add(1, 'M'));
}
},
enter: function () {
this.hide();
},
escape: function () {
this.hide();
},
//tab: function (widget) { //this break the flow of the form. disabling for now
// var toggle = widget.find('.picker-switch a[data-action="togglePicker"]');
// if(toggle.length > 0) toggle.click();
//},
'control space': function (widget) {
if (widget.find('.timepicker').is(':visible')) {
widget.find('.btn[data-action="togglePeriod"]').click();
}
},
t: function () {
this.date(this.getMoment());
},
'delete': function () {
this.clear();
}
},
debug: false,
allowInputToggle: false,
disabledTimeIntervals: false,
disabledHours: false,
enabledHours: false,
viewDate: false
};
}));
!function ($) { "use strict"; var BootstrapPaginator = function (element, options) { this.init(element, options) }, old = null; BootstrapPaginator.prototype = { init: function (element, options) { this.$element = $(element); var version = options && options.bootstrapMajorVersion ? options.bootstrapMajorVersion : $.fn.bootstrapPaginator.defaults.bootstrapMajorVersion, id = this.$element.attr("id"); if (2 === version && !this.$element.is("div")) throw "in Bootstrap version 2 the pagination must be a div element. Or if you are using Bootstrap pagination 3. Please specify it in bootstrapMajorVersion in the option"; if (version > 2 && !this.$element.is("ul")) throw "in Bootstrap version 3 the pagination root item must be an ul element."; this.currentPage = 1, this.lastPage = 1, this.setOptions(options), this.initialized = !0 }, setOptions: function (options) { this.options = $.extend({}, this.options || $.fn.bootstrapPaginator.defaults, options), this.totalPages = parseInt(this.options.totalPages, 10), this.numberOfPages = parseInt(this.options.numberOfPages, 10), options && "undefined" != typeof options.currentPage && this.setCurrentPage(options.currentPage), this.listen(), this.render(), this.initialized || this.lastPage === this.currentPage || this.$element.trigger("page-changed", [this.lastPage, this.currentPage]) }, listen: function () { this.$element.off("page-clicked"), this.$element.off("page-changed"), "function" == typeof this.options.onPageClicked && this.$element.bind("page-clicked", this.options.onPageClicked), "function" == typeof this.options.onPageChanged && this.$element.on("page-changed", this.options.onPageChanged), this.$element.bind("page-clicked", this.onPageClicked) }, destroy: function () { this.$element.off("page-clicked"), this.$element.off("page-changed"), this.$element.removeData("bootstrapPaginator"), this.$element.empty() }, show: function (page) { this.setCurrentPage(page), this.render(), this.lastPage !== this.currentPage && this.$element.trigger("page-changed", [this.lastPage, this.currentPage]) }, showNext: function () { var pages = this.getPages(); pages.next && this.show(pages.next) }, showPrevious: function () { var pages = this.getPages(); pages.prev && this.show(pages.prev) }, showFirst: function () { var pages = this.getPages(); pages.first && this.show(pages.first) }, showLast: function () { var pages = this.getPages(); pages.last && this.show(pages.last) }, onPageItemClicked: function (event) { var type = event.data.type, page = event.data.page; this.$element.trigger("page-clicked", [event, type, page]) }, onPageClicked: function (event, originalEvent, type, page) { var currentTarget = $(event.currentTarget); switch (type) { case "first": currentTarget.bootstrapPaginator("showFirst"); break; case "prev": currentTarget.bootstrapPaginator("showPrevious"); break; case "next": currentTarget.bootstrapPaginator("showNext"); break; case "last": currentTarget.bootstrapPaginator("showLast"); break; case "page": currentTarget.bootstrapPaginator("show", page) } }, render: function () { var containerClass = this.getValueFromOption(this.options.containerClass, this.$element), size = this.options.size || "normal", alignment = this.options.alignment || "left", pages = this.getPages(), listContainer = 2 === this.options.bootstrapMajorVersion ? $("") : this.$element, listContainerClass = 2 === this.options.bootstrapMajorVersion ? this.getValueFromOption(this.options.listContainerClass, listContainer) : null, first = null, prev = null, next = null, last = null, p = null, i = 0; switch (this.$element.prop("class", ""), this.$element.addClass("pagination"), size.toLowerCase()) { case "large": case "small": case "mini": this.$element.addClass($.fn.bootstrapPaginator.sizeArray[this.options.bootstrapMajorVersion][size.toLowerCase()]) } if (2 === this.options.bootstrapMajorVersion) switch (alignment.toLowerCase()) { case "center": this.$element.addClass("pagination-centered"); break; case "right": this.$element.addClass("pagination-right") } for (this.$element.addClass(containerClass), this.$element.empty(), 2 === this.options.bootstrapMajorVersion && (this.$element.append(listContainer), listContainer.addClass(listContainerClass)), this.pageRef = [], pages.first && (first = this.buildPageItem("first", pages.first), first && listContainer.append(first)), pages.prev && (prev = this.buildPageItem("prev", pages.prev), prev && listContainer.append(prev)), i = 0; i < pages.length; i += 1) p = this.buildPageItem("page", pages[i]), p && listContainer.append(p); pages.next && (next = this.buildPageItem("next", pages.next), next && listContainer.append(next)), pages.last && (last = this.buildPageItem("last", pages.last), last && listContainer.append(last)) }, buildPageItem: function (type, page) { var itemContainer = $(" "), itemContent = $(" "), text = "", title = "", itemContainerClass = this.options.itemContainerClass(type, page, this.currentPage), itemContentClass = this.getValueFromOption(this.options.itemContentClass, type, page, this.currentPage), tooltipOpts = null; switch (type) { case "first": if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) return; text = this.options.itemTexts(type, page, this.currentPage), title = this.options.tooltipTitles(type, page, this.currentPage); break; case "last": if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) return; text = this.options.itemTexts(type, page, this.currentPage), title = this.options.tooltipTitles(type, page, this.currentPage); break; case "prev": if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) return; text = this.options.itemTexts(type, page, this.currentPage), title = this.options.tooltipTitles(type, page, this.currentPage); break; case "next": if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) return; text = this.options.itemTexts(type, page, this.currentPage), title = this.options.tooltipTitles(type, page, this.currentPage); break; case "page": if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) return; text = this.options.itemTexts(type, page, this.currentPage), title = this.options.tooltipTitles(type, page, this.currentPage) } return itemContainer.addClass(itemContainerClass).append(itemContent), itemContent.addClass(itemContentClass).html(text).on("click", null, { type: type, page: page }, $.proxy(this.onPageItemClicked, this)), this.options.pageUrl && itemContent.attr("href", this.getValueFromOption(this.options.pageUrl, type, page, this.currentPage)), this.options.useBootstrapTooltip ? (tooltipOpts = $.extend({}, this.options.bootstrapTooltipOptions, { title: title }), itemContent.tooltip(tooltipOpts)) : itemContent.attr("title", title), itemContainer }, setCurrentPage: function (page) { if (page > this.totalPages || 1 > page) throw "Page out of range"; this.lastPage = this.currentPage, this.currentPage = parseInt(page, 10) }, getPages: function () { var totalPages = this.totalPages, pageStart = 0 === this.currentPage % this.numberOfPages ? (parseInt(this.currentPage / this.numberOfPages, 10) - 1) * this.numberOfPages + 1 : parseInt(this.currentPage / this.numberOfPages, 10) * this.numberOfPages + 1, output = [], i = 0, counter = 0; for (pageStart = 1 > pageStart ? 1 : pageStart, i = pageStart, counter = 0; counter < this.numberOfPages && totalPages >= i; i += 1, counter += 1) output.push(i); return output.first = 1, output.prev = this.currentPage > 1 ? this.currentPage - 1 : 1, output.next = this.currentPage < totalPages ? this.currentPage + 1 : totalPages, output.last = totalPages, output.current = this.currentPage, output.total = totalPages, output.numberOfPages = this.options.numberOfPages, output }, getValueFromOption: function (value) { var output = null, args = Array.prototype.slice.call(arguments, 1); return output = "function" == typeof value ? value.apply(this, args) : value } }, old = $.fn.bootstrapPaginator, $.fn.bootstrapPaginator = function (option) { var args = arguments, result = null; return $(this).each(function (index, item) { var $this = $(item), data = $this.data("bootstrapPaginator"), options = "object" != typeof option ? null : option; if (!data) return data = new BootstrapPaginator(this, options), $this = $(data.$element), $this.data("bootstrapPaginator", data), void 0; if ("string" == typeof option) { if (!data[option]) throw "Method " + option + " does not exist"; result = data[option].apply(data, Array.prototype.slice.call(args, 1)) } else result = data.setOptions(option) }), result }, $.fn.bootstrapPaginator.sizeArray = { 2: { large: "pagination-large", small: "pagination-small", mini: "pagination-mini" }, 3: { large: "pagination-lg", small: "pagination-sm", mini: "" } }, $.fn.bootstrapPaginator.defaults = { containerClass: "", size: "normal", alignment: "left", bootstrapMajorVersion: 2, listContainerClass: "", itemContainerClass: function (type, page, current) { return page === current ? "active" : "" }, itemContentClass: function (type, page, current) { return "" }, currentPage: 1, numberOfPages: 5, totalPages: 1, pageUrl: function (type, page, current) { return null }, onPageClicked: null, onPageChanged: null, useBootstrapTooltip: !1, shouldShowPage: function (type, page, current) { var result = !0; switch (type) { case "first": result = 1 !== current; break; case "prev": result = 1 !== current; break; case "next": result = current !== this.totalPages; break; case "last": result = current !== this.totalPages; break; case "page": result = !0 } return result }, itemTexts: function (type, page, current) { switch (type) { case "first": return "<<"; case "prev": return "<"; case "next": return ">"; case "last": return ">>"; case "page": return page } }, tooltipTitles: function (type, page, current) { switch (type) { case "first": return "Go to first page"; case "prev": return "Go to previous page"; case "next": return "Go to next page"; case "last": return "Go to last page"; case "page": return page === current ? "Current page is " + page : "Go to page " + page } }, bootstrapTooltipOptions: { animation: !0, html: !0, placement: "top", selector: !1, title: "", container: !1 } }, $.fn.bootstrapPaginator.Constructor = BootstrapPaginator }(window.jQuery);
/*!
* typeahead.js 0.10.2
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/
!function(a){var b={isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,getUniqueId:function(){var a=0;return function(){return a++}}(),templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},noop:function(){}},c="0.10.2",d=function(){function a(a){return a.split(/\s+/)}function b(a){return a.split(/\W+/)}function c(a){return function(b){return function(c){return a(c[b])}}}return{nonword:b,whitespace:a,obj:{nonword:c(b),whitespace:c(a)}}}(),e=function(){function a(a){this.maxSize=a||100,this.size=0,this.hash={},this.list=new c}function c(){this.head=this.tail=null}function d(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(a.prototype,{set:function(a,b){var c,e=this.list.tail;this.size>=this.maxSize&&(this.list.remove(e),delete this.hash[e.key]),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new d(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];return b?(this.list.moveToFront(b),b.val):void 0}}),b.mixin(c.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),a}(),f=function(){function a(a){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+this.prefix)}function c(){return(new Date).getTime()}function d(a){return JSON.stringify(b.isUndefined(a)?null:a)}function e(a){return JSON.parse(a)}var f,g;try{f=window.localStorage,f.setItem("~~~","!"),f.removeItem("~~~")}catch(h){f=null}return g=f&&window.JSON?{_prefix:function(a){return this.prefix+a},_ttlKey:function(a){return this._prefix(a)+this.ttlKey},get:function(a){return this.isExpired(a)&&this.remove(a),e(f.getItem(this._prefix(a)))},set:function(a,e,g){return b.isNumber(g)?f.setItem(this._ttlKey(a),d(c()+g)):f.removeItem(this._ttlKey(a)),f.setItem(this._prefix(a),d(e))},remove:function(a){return f.removeItem(this._ttlKey(a)),f.removeItem(this._prefix(a)),this},clear:function(){var a,b,c=[],d=f.length;for(a=0;d>a;a++)(b=f.key(a)).match(this.keyMatcher)&&c.push(b.replace(this.keyMatcher,""));for(a=c.length;a--;)this.remove(c[a]);return this},isExpired:function(a){var d=e(f.getItem(this._ttlKey(a)));return b.isNumber(d)&&c()>d?!0:!1}}:{get:b.noop,set:b.noop,remove:b.noop,clear:b.noop,isExpired:b.noop},b.mixin(a.prototype,g),a}(),g=function(){function c(b){b=b||{},this._send=b.transport?d(b.transport):a.ajax,this._get=b.rateLimiter?b.rateLimiter(this._get):this._get}function d(c){return function(d,e){function f(a){b.defer(function(){h.resolve(a)})}function g(a){b.defer(function(){h.reject(a)})}var h=a.Deferred();return c(d,e,f,g),h}}var f=0,g={},h=6,i=new e(10);return c.setMaxPendingRequests=function(a){h=a},c.resetCache=function(){i=new e(10)},b.mixin(c.prototype,{_get:function(a,b,c){function d(b){c&&c(null,b),i.set(a,b)}function e(){c&&c(!0)}function j(){f--,delete g[a],l.onDeckRequestArgs&&(l._get.apply(l,l.onDeckRequestArgs),l.onDeckRequestArgs=null)}var k,l=this;(k=g[a])?k.done(d).fail(e):h>f?(f++,g[a]=this._send(a,b).done(d).fail(e).always(j)):this.onDeckRequestArgs=[].slice.call(arguments,0)},get:function(a,c,d){var e;return b.isFunction(c)&&(d=c,c={}),(e=i.get(a))?b.defer(function(){d&&d(null,e)}):this._get(a,c,d),!!e}}),c}(),h=function(){function c(b){b=b||{},b.datumTokenizer&&b.queryTokenizer||a.error("datumTokenizer and queryTokenizer are both required"),this.datumTokenizer=b.datumTokenizer,this.queryTokenizer=b.queryTokenizer,this.reset()}function d(a){return a=b.filter(a,function(a){return!!a}),a=b.map(a,function(a){return a.toLowerCase()})}function e(){return{ids:[],children:{}}}function f(a){for(var b={},c=[],d=0;db[e]?e++:(f.push(a[d]),d++,e++);return f}return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;f=c.datums.push(a)-1,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b.children[g]||(b.children[g]=e()),b.ids.push(f)})})},get:function(a){var c,e,h=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length)return!1;for(b=h.trie,c=a.split("");b&&(d=c.shift());)b=b.children[d];return b&&0===c.length?(f=b.ids.slice(0),void(e=e?g(e,f):f)):(e=[],!1)}),e?b.map(f(e),function(a){return h.datums[a]}):[]},reset:function(){this.datums=[],this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){function d(a){return a.local||null}function e(d){var e,f;return f={url:null,thumbprint:"",ttl:864e5,filter:null,ajax:{}},(e=d.prefetch||null)&&(e=b.isString(e)?{url:e}:e,e=b.mixin(f,e),e.thumbprint=c+e.thumbprint,e.ajax.type=e.ajax.type||"GET",e.ajax.dataType=e.ajax.dataType||"json",!e.url&&a.error("prefetch requires url to be set")),e}function f(c){function d(a){return function(c){return b.debounce(c,a)}}function e(a){return function(c){return b.throttle(c,a)}}var f,g;return g={url:null,wildcard:"%QUERY",replace:null,rateLimitBy:"debounce",rateLimitWait:300,send:null,filter:null,ajax:{}},(f=c.remote||null)&&(f=b.isString(f)?{url:f}:f,f=b.mixin(g,f),f.rateLimiter=/^throttle$/i.test(f.rateLimitBy)?e(f.rateLimitWait):d(f.rateLimitWait),f.ajax.type=f.ajax.type||"GET",f.ajax.dataType=f.ajax.dataType||"json",delete f.rateLimitBy,delete f.rateLimitWait,!f.url&&a.error("remote requires url to be set")),f}return{local:d,prefetch:e,remote:f}}();!function(c){function e(b){b&&(b.local||b.prefetch||b.remote)||a.error("one of local, prefetch, or remote is required"),this.limit=b.limit||5,this.sorter=j(b.sorter),this.dupDetector=b.dupDetector||k,this.local=i.local(b),this.prefetch=i.prefetch(b),this.remote=i.remote(b),this.cacheKey=this.prefetch?this.prefetch.cacheKey||this.prefetch.url:null,this.index=new h({datumTokenizer:b.datumTokenizer,queryTokenizer:b.queryTokenizer}),this.storage=this.cacheKey?new f(this.cacheKey):null}function j(a){function c(b){return b.sort(a)}function d(a){return a}return b.isFunction(a)?c:d}function k(){return!1}var l,m;return l=c.Bloodhound,m={data:"data",protocol:"protocol",thumbprint:"thumbprint"},c.Bloodhound=e,e.noConflict=function(){return c.Bloodhound=l,e},e.tokenizers=d,b.mixin(e.prototype,{_loadPrefetch:function(b){function c(a){f.clear(),f.add(b.filter?b.filter(a):a),f._saveToStorage(f.index.serialize(),b.thumbprint,b.ttl)}var d,e,f=this;return(d=this._readFromStorage(b.thumbprint))?(this.index.bootstrap(d),e=a.Deferred().resolve()):e=a.ajax(b.url,b.ajax).done(c),e},_getFromRemote:function(a,b){function c(a,c){b(a?[]:f.remote.filter?f.remote.filter(c):c)}var d,e,f=this;return a=a||"",e=encodeURIComponent(a),d=this.remote.replace?this.remote.replace(this.remote.url,a):this.remote.url.replace(this.remote.wildcard,e),this.transport.get(d,this.remote.ajax,c)},_saveToStorage:function(a,b,c){this.storage&&(this.storage.set(m.data,a,c),this.storage.set(m.protocol,location.protocol,c),this.storage.set(m.thumbprint,b,c))},_readFromStorage:function(a){var b,c={};return this.storage&&(c.data=this.storage.get(m.data),c.protocol=this.storage.get(m.protocol),c.thumbprint=this.storage.get(m.thumbprint)),b=c.thumbprint!==a||c.protocol!==location.protocol,c.data&&!b?c.data:null},_initialize:function(){function c(){e.add(b.isFunction(f)?f():f)}var d,e=this,f=this.local;return d=this.prefetch?this._loadPrefetch(this.prefetch):a.Deferred().resolve(),f&&d.done(c),this.transport=this.remote?new g(this.remote):null,this.initPromise=d.promise()},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){this.index.add(a)},get:function(a,c){function d(a){var d=f.slice(0);b.each(a,function(a){var c;return c=b.some(d,function(b){return e.dupDetector(a,b)}),!c&&d.push(a),d.length0||!this.transport)&&c&&c(f)},clear:function(){this.index.reset()},clearPrefetchCache:function(){this.storage&&this.storage.clear()},clearRemoteCache:function(){this.transport&&g.resetCache()},ttAdapter:function(){return b.bind(this.get,this)}}),e}(this);var j={wrapper:'',dropdown:'',dataset:'
',suggestions:' ',suggestion:'
'},k={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},dropdown:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},suggestions:{display:"block"},suggestion:{whiteSpace:"nowrap",cursor:"pointer"},suggestionChild:{whiteSpace:"normal"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};b.isMsie()&&b.mixin(k.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),b.isMsie()&&b.isMsie()<=7&&b.mixin(k.input,{marginTop:"-1px"});var l=function(){function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d="typeahead:";return b.mixin(c.prototype,{trigger:function(a){var b=[].slice.call(arguments,1);this.$el.trigger(d+a,b)}}),c}(),m=function(){function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0;!d&&e').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),fontStyle:b.css("font-style"),fontVariant:b.css("font-variant"),fontWeight:b.css("font-weight"),wordSpacing:b.css("word-spacing"),letterSpacing:b.css("letter-spacing"),textIndent:b.css("text-indent"),textRendering:b.css("text-rendering"),textTransform:b.css("text-transform")}).insertAfter(b)}function e(a,b){return c.normalizeQuery(a)===c.normalizeQuery(b)}function f(a){return a.altKey||a.ctrlKey||a.metaKey||a.shiftKey}var g;return g={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"},c.normalizeQuery=function(a){return(a||"").replace(/^\s*/g,"").replace(/\s{2,}/g," ")},b.mixin(c.prototype,m,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.trigger("focused")},_onKeydown:function(a){var b=g[a.which||a.keyCode];this._managePreventDefault(b,a),b&&this._shouldTrigger(b,a)&&this.trigger(b+"Keyed",a)},_onInput:function(){this._checkInputValue()},_managePreventDefault:function(a,b){var c,d,e;switch(a){case"tab":d=this.getHint(),e=this.getInputValue(),c=d&&d!==e&&!f(b);break;case"up":case"down":c=!f(b);break;default:c=!1}c&&b.preventDefault()},_shouldTrigger:function(a,b){var c;switch(a){case"tab":c=!f(b);break;default:c=!0}return c},_checkInputValue:function(){var a,b,c;a=this.getInputValue(),b=e(a,this.query),c=b?this.query.length!==a.length:!1,b?c&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query=a)},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getQuery:function(){return this.query},setQuery:function(a){this.query=a},getInputValue:function(){return this.$input.val()},setInputValue:function(a,b){this.$input.val(a),b?this.clearHint():this._checkInputValue()},resetInputValue:function(){this.setInputValue(this.query,!0)},getHint:function(){return this.$hint.val()},setHint:function(a){this.$hint.val(a)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var a,b,c,d;a=this.getInputValue(),b=this.getHint(),c=a!==b&&0===b.indexOf(a),d=""!==a&&c&&!this.hasOverflow(),!d&&this.clearHint()},getLanguageDirection:function(){return(this.$input.css("direction")||"ltr").toLowerCase()},hasOverflow:function(){var a=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=a},isCursorAtEnd:function(){var a,c,d;return a=this.$input.val().length,c=this.$input[0].selectionStart,b.isNumber(c)?c===a:document.selection?(d=document.selection.createRange(),d.moveStart("character",-a),a===d.text.length):!0},destroy:function(){this.$hint.off(".tt"),this.$input.off(".tt"),this.$hint=this.$input=this.$overflowHelper=null}}),c}(),p=function(){function c(c){c=c||{},c.templates=c.templates||{},c.source||a.error("missing source"),c.name&&!f(c.name)&&a.error("invalid dataset name: "+c.name),this.query=null,this.highlight=!!c.highlight,this.name=c.name||b.getUniqueId(),this.source=c.source,this.displayFn=d(c.display||c.displayKey),this.templates=e(c.templates,this.displayFn),this.$el=a(j.dataset.replace("%CLASS%",this.name))}function d(a){function c(b){return b[a]}return a=a||"value",b.isFunction(a)?a:c}function e(a,c){function d(a){return""+c(a)+"
"}return{empty:a.empty&&b.templatify(a.empty),header:a.header&&b.templatify(a.header),footer:a.footer&&b.templatify(a.footer),suggestion:a.suggestion||d}}function f(a){return/^[_a-zA-Z0-9-]+$/.test(a)}var g="ttDataset",h="ttValue",i="ttDatum";return c.extractDatasetName=function(b){return a(b).data(g)},c.extractValue=function(b){return a(b).data(h)},c.extractDatum=function(b){return a(b).data(i)},b.mixin(c.prototype,m,{_render:function(c,d){function e(){return p.templates.empty({query:c,isEmpty:!0})}function f(){function e(b){var c;return c=a(j.suggestion).append(p.templates.suggestion(b)).data(g,p.name).data(h,p.displayFn(b)).data(i,b),c.children().each(function(){a(this).css(k.suggestionChild)}),c}var f,l;return f=a(j.suggestions).css(k.suggestions),l=b.map(d,e),f.append.apply(f,l),p.highlight&&n({node:f[0],pattern:c}),f}function l(){return p.templates.header({query:c,isEmpty:!o})}function m(){return p.templates.footer({query:c,isEmpty:!o})}if(this.$el){var o,p=this;this.$el.empty(),o=d&&d.length,!o&&this.templates.empty?this.$el.html(e()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null):o&&this.$el.html(f()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null),this.trigger("rendered")}},getRoot:function(){return this.$el},update:function(a){function b(b){c.canceled||a!==c.query||c._render(a,b)}var c=this;this.query=a,this.canceled=!1,this.source(a,b)},cancel:function(){this.canceled=!0},clear:function(){this.cancel(),this.$el.empty(),this.trigger("rendered")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=null}}),c}(),q=function(){function c(c){var e,f,g,h=this;c=c||{},c.menu||a.error("menu is required"),this.isOpen=!1,this.isEmpty=!0,this.datasets=b.map(c.datasets,d),e=b.bind(this._onSuggestionClick,this),f=b.bind(this._onSuggestionMouseEnter,this),g=b.bind(this._onSuggestionMouseLeave,this),this.$menu=a(c.menu).on("click.tt",".tt-suggestion",e).on("mouseenter.tt",".tt-suggestion",f).on("mouseleave.tt",".tt-suggestion",g),b.each(this.datasets,function(a){h.$menu.append(a.getRoot()),a.onSync("rendered",h._onRendered,h)})}function d(a){return new p(a)}return b.mixin(c.prototype,m,{_onSuggestionClick:function(b){this.trigger("suggestionClicked",a(b.currentTarget))},_onSuggestionMouseEnter:function(b){this._removeCursor(),this._setCursor(a(b.currentTarget),!0)},_onSuggestionMouseLeave:function(){this._removeCursor()},_onRendered:function(){function a(a){return a.isEmpty()}this.isEmpty=b.every(this.datasets,a),this.isEmpty?this._hide():this.isOpen&&this._show(),this.trigger("datasetRendered")},_hide:function(){this.$menu.hide()},_show:function(){this.$menu.css("display","block")},_getSuggestions:function(){return this.$menu.find(".tt-suggestion")},_getCursor:function(){return this.$menu.find(".tt-cursor").first()},_setCursor:function(a,b){a.first().addClass("tt-cursor"),!b&&this.trigger("cursorMoved")},_removeCursor:function(){this._getCursor().removeClass("tt-cursor")},_moveCursor:function(a){var b,c,d,e;if(this.isOpen){if(c=this._getCursor(),b=this._getSuggestions(),this._removeCursor(),d=b.index(c)+a,d=(d+1)%(b.length+1)-1,-1===d)return void this.trigger("cursorRemoved");-1>d&&(d=b.length-1),this._setCursor(e=b.eq(d)),this._ensureVisible(e)}},_ensureVisible:function(a){var b,c,d,e;b=a.position().top,c=b+a.outerHeight(!0),d=this.$menu.scrollTop(),e=this.$menu.height()+parseInt(this.$menu.css("paddingTop"),10)+parseInt(this.$menu.css("paddingBottom"),10),0>b?this.$menu.scrollTop(d+b):c>e&&this.$menu.scrollTop(d+(c-e))},close:function(){this.isOpen&&(this.isOpen=!1,this._removeCursor(),this._hide(),this.trigger("closed"))},open:function(){this.isOpen||(this.isOpen=!0,!this.isEmpty&&this._show(),this.trigger("opened"))},setLanguageDirection:function(a){this.$menu.css("ltr"===a?k.ltr:k.rtl)},moveCursorUp:function(){this._moveCursor(-1)},moveCursorDown:function(){this._moveCursor(1)},getDatumForSuggestion:function(a){var b=null;return a.length&&(b={raw:p.extractDatum(a),value:p.extractValue(a),datasetName:p.extractDatasetName(a)}),b},getDatumForCursor:function(){return this.getDatumForSuggestion(this._getCursor().first())},getDatumForTopSuggestion:function(){return this.getDatumForSuggestion(this._getSuggestions().first())},update:function(a){function c(b){b.update(a)}b.each(this.datasets,c)},empty:function(){function a(a){a.clear()}b.each(this.datasets,a),this.isEmpty=!0},isVisible:function(){return this.isOpen&&!this.isEmpty},destroy:function(){function a(a){a.destroy()}this.$menu.off(".tt"),this.$menu=null,b.each(this.datasets,a)}}),c}(),r=function(){function c(c){var e,f,g;c=c||{},c.input||a.error("missing input"),this.isActivated=!1,this.autoselect=!!c.autoselect,this.minLength=b.isNumber(c.minLength)?c.minLength:1,this.$node=d(c.input,c.withHint),e=this.$node.find(".tt-dropdown-menu"),f=this.$node.find(".tt-input"),g=this.$node.find(".tt-hint"),f.on("blur.tt",function(a){var c,d,g;c=document.activeElement,d=e.is(c),g=e.has(c).length>0,b.isMsie()&&(d||g)&&(a.preventDefault(),a.stopImmediatePropagation(),b.defer(function(){f.focus()}))}),e.on("mousedown.tt",function(a){a.preventDefault()}),this.eventBus=c.eventBus||new l({el:f}),this.dropdown=new q({menu:e,datasets:c.datasets}).onSync("suggestionClicked",this._onSuggestionClicked,this).onSync("cursorMoved",this._onCursorMoved,this).onSync("cursorRemoved",this._onCursorRemoved,this).onSync("opened",this._onOpened,this).onSync("closed",this._onClosed,this).onAsync("datasetRendered",this._onDatasetRendered,this),this.input=new o({input:f,hint:g}).onSync("focused",this._onFocused,this).onSync("blurred",this._onBlurred,this).onSync("enterKeyed",this._onEnterKeyed,this).onSync("tabKeyed",this._onTabKeyed,this).onSync("escKeyed",this._onEscKeyed,this).onSync("upKeyed",this._onUpKeyed,this).onSync("downKeyed",this._onDownKeyed,this).onSync("leftKeyed",this._onLeftKeyed,this).onSync("rightKeyed",this._onRightKeyed,this).onSync("queryChanged",this._onQueryChanged,this).onSync("whitespaceChanged",this._onWhitespaceChanged,this),this._setLanguageDirection()}function d(b,c){var d,f,h,i;d=a(b),f=a(j.wrapper).css(k.wrapper),h=a(j.dropdown).css(k.dropdown),i=d.clone().css(k.hint).css(e(d)),i.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder").prop("disabled",!0).attr({autocomplete:"off",spellcheck:"false"}),d.data(g,{dir:d.attr("dir"),autocomplete:d.attr("autocomplete"),spellcheck:d.attr("spellcheck"),style:d.attr("style")}),d.addClass("tt-input").attr({autocomplete:"off",spellcheck:!1}).css(c?k.input:k.inputWithNoHint);try{!d.attr("dir")&&d.attr("dir","auto")}catch(l){}return d.wrap(f).parent().prepend(c?i:null).append(h)}function e(a){return{backgroundAttachment:a.css("background-attachment"),backgroundClip:a.css("background-clip"),backgroundColor:a.css("background-color"),backgroundImage:a.css("background-image"),backgroundOrigin:a.css("background-origin"),backgroundPosition:a.css("background-position"),backgroundRepeat:a.css("background-repeat"),backgroundSize:a.css("background-size")}}function f(a){var c=a.find(".tt-input");b.each(c.data(g),function(a,d){b.isUndefined(a)?c.removeAttr(d):c.attr(d,a)}),c.detach().removeData(g).removeClass("tt-input").insertAfter(a),a.remove()}var g="ttAttrs";return b.mixin(c.prototype,{_onSuggestionClicked:function(a,b){var c;(c=this.dropdown.getDatumForSuggestion(b))&&this._select(c)},_onCursorMoved:function(){var a=this.dropdown.getDatumForCursor();this.input.setInputValue(a.value,!0),this.eventBus.trigger("cursorchanged",a.raw,a.datasetName)},_onCursorRemoved:function(){this.input.resetInputValue(),this._updateHint()},_onDatasetRendered:function(){this._updateHint()},_onOpened:function(){this._updateHint(),this.eventBus.trigger("opened")},_onClosed:function(){this.input.clearHint(),this.eventBus.trigger("closed")},_onFocused:function(){this.isActivated=!0,this.dropdown.open()},_onBlurred:function(){this.isActivated=!1,this.dropdown.empty(),this.dropdown.close()},_onEnterKeyed:function(a,b){var c,d;c=this.dropdown.getDatumForCursor(),d=this.dropdown.getDatumForTopSuggestion(),c?(this._select(c),b.preventDefault()):this.autoselect&&d&&(this._select(d),b.preventDefault())},_onTabKeyed:function(a,b){var c;(c=this.dropdown.getDatumForCursor())?(this._select(c),b.preventDefault()):this._autocomplete(!0)},_onEscKeyed:function(){this.dropdown.close(),this.input.resetInputValue()},_onUpKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorUp(),this.dropdown.open()},_onDownKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorDown(),this.dropdown.open()},_onLeftKeyed:function(){"rtl"===this.dir&&this._autocomplete()},_onRightKeyed:function(){"ltr"===this.dir&&this._autocomplete()},_onQueryChanged:function(a,b){this.input.clearHintIfInvalid(),b.length>=this.minLength?this.dropdown.update(b):this.dropdown.empty(),this.dropdown.open(),this._setLanguageDirection()},_onWhitespaceChanged:function(){this._updateHint(),this.dropdown.open()},_setLanguageDirection:function(){var a;this.dir!==(a=this.input.getLanguageDirection())&&(this.dir=a,this.$node.css("direction",a),this.dropdown.setLanguageDirection(a))},_updateHint:function(){var a,c,d,e,f,g;a=this.dropdown.getDatumForTopSuggestion(),a&&this.dropdown.isVisible()&&!this.input.hasOverflow()?(c=this.input.getInputValue(),d=o.normalizeQuery(c),e=b.escapeRegExChars(d),f=new RegExp("^(?:"+e+")(.+$)","i"),g=f.exec(a.value),g?this.input.setHint(c+g[1]):this.input.clearHint()):this.input.clearHint()},_autocomplete:function(a){var b,c,d,e;b=this.input.getHint(),c=this.input.getQuery(),d=a||this.input.isCursorAtEnd(),b&&c!==b&&d&&(e=this.dropdown.getDatumForTopSuggestion(),e&&this.input.setInputValue(e.value),this.eventBus.trigger("autocompleted",e.raw,e.datasetName))},_select:function(a){this.input.setQuery(a.value),this.input.setInputValue(a.value,!0),this._setLanguageDirection(),this.eventBus.trigger("selected",a.raw,a.datasetName),this.dropdown.close(),b.defer(b.bind(this.dropdown.empty,this.dropdown))},open:function(){this.dropdown.open()},close:function(){this.dropdown.close()},setVal:function(a){this.isActivated?this.input.setInputValue(a):(this.input.setQuery(a),this.input.setInputValue(a,!0)),this._setLanguageDirection()},getVal:function(){return this.input.getQuery()},destroy:function(){this.input.destroy(),this.dropdown.destroy(),f(this.$node),this.$node=null}}),c}();!function(){var c,d,e;c=a.fn.typeahead,d="ttTypeahead",e={initialize:function(c,e){function f(){var f,g,h=a(this);b.each(e,function(a){a.highlight=!!c.highlight}),g=new r({input:h,eventBus:f=new l({el:h}),withHint:b.isUndefined(c.hint)?!0:!!c.hint,minLength:c.minLength,autoselect:c.autoselect,datasets:e}),h.data(d,g)}return e=b.isArray(e)?e:[].slice.call(arguments,1),c=c||{},this.each(f)},open:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.open()}return this.each(b)},close:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.close()}return this.each(b)},val:function(b){function c(){var c,e=a(this);(c=e.data(d))&&c.setVal(b)}function e(a){var b,c;return(b=a.data(d))&&(c=b.getVal()),c}return arguments.length?this.each(c):e(this.first())},destroy:function(){function b(){var b,c=a(this);(b=c.data(d))&&(b.destroy(),c.removeData(d))}return this.each(b)}},a.fn.typeahead=function(a){return e[a]?e[a].apply(this,[].slice.call(arguments,1)):e.initialize.apply(this,arguments)},a.fn.typeahead.noConflict=function(){return a.fn.typeahead=c,this}}()}(window.jQuery);
/* @license Input Mask plugin for jquery
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2013 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 0.0.0
*/
(function ($) {
if ($.fn.inputmask === undefined) {
$.inputmask = {
//options default
defaults: {
placeholder: "_",
optionalmarker: { start: "[", end: "]" },
quantifiermarker: { start: "{", end: "}" },
groupmarker: { start: "(", end: ")" },
escapeChar: "\\",
mask: null,
oncomplete: $.noop, //executes when the mask is complete
onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
oncleared: $.noop, //executes when the mask is cleared
repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
clearMaskOnLostFocus: true,
insertMode: true, //insert the input or overwrite the input
clearIncomplete: false, //clear the incomplete input on blur
aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
showMaskOnFocus: true, //show the mask-placeholder when the input has focus
showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
showTooltip: false, //show the activemask as tooltip
numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
//numeric basic properties
isNumeric: false, //enable numeric features
radixPoint: "", //".", // | ","
skipRadixDance: false, //disable radixpoint caret positioning
rightAlignNumerics: true, //align numerics to the right
//numeric basic properties
definitions: {
'9': {
validator: "[0-9]",
cardinality: 1
},
'a': {
validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
cardinality: 1
},
'*': {
validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
cardinality: 1
}
},
keyCode: {
ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91
},
//specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
ignorables: [8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123],
getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) {
var calculatedLength = buffer.length;
if (!greedy) {
if (repeat == "*") {
calculatedLength = currentBuffer.length + 1;
} else if (repeat > 1) {
calculatedLength += (buffer.length * (repeat - 1));
}
}
return calculatedLength;
}
},
escapeRegex: function (str) {
var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
}
};
$.fn.inputmask = function (fn, options) {
var opts = $.extend(true, {}, $.inputmask.defaults, options),
msie10 = navigator.userAgent.match(new RegExp("msie 10", "i")) !== null,
iphone = navigator.userAgent.match(new RegExp("iphone", "i")) !== null,
android = navigator.userAgent.match(new RegExp("android.*safari.*", "i")) !== null,
androidchrome = navigator.userAgent.match(new RegExp("android.*chrome.*", "i")) !== null,
pasteEvent = isInputEventSupported('paste') && !msie10 ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange",
masksets,
activeMasksetIndex = 0;
if (typeof fn === "string") {
switch (fn) {
case "mask":
//resolve possible aliases given by options
resolveAlias(opts.alias, options);
masksets = generateMaskSets();
if (masksets.length == 0) { return this; }
return this.each(function () {
maskScope($.extend(true, {}, masksets), 0).mask(this);
});
case "unmaskedvalue":
var $input = $(this), input = this;
if ($input.data('_inputmask')) {
masksets = $input.data('_inputmask')['masksets'];
activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
opts = $input.data('_inputmask')['opts'];
return maskScope(masksets, activeMasksetIndex).unmaskedvalue($input);
} else return $input.val();
case "remove":
return this.each(function () {
var $input = $(this), input = this;
if ($input.data('_inputmask')) {
masksets = $input.data('_inputmask')['masksets'];
activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
opts = $input.data('_inputmask')['opts'];
//writeout the unmaskedvalue
input._valueSet(maskScope(masksets, activeMasksetIndex).unmaskedvalue($input, true));
//clear data
$input.removeData('_inputmask');
//unbind all events
$input.unbind(".inputmask");
$input.removeClass('focus.inputmask');
//restore the value property
var valueProperty;
if (Object.getOwnPropertyDescriptor)
valueProperty = Object.getOwnPropertyDescriptor(input, "value");
if (valueProperty && valueProperty.get) {
if (input._valueGet) {
Object.defineProperty(input, "value", {
get: input._valueGet,
set: input._valueSet
});
}
} else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
if (input._valueGet) {
input.__defineGetter__("value", input._valueGet);
input.__defineSetter__("value", input._valueSet);
}
}
try { //try catch needed for IE7 as it does not supports deleting fns
delete input._valueGet;
delete input._valueSet;
} catch (e) {
input._valueGet = undefined;
input._valueSet = undefined;
}
}
});
break;
case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
if (this.data('_inputmask')) {
masksets = this.data('_inputmask')['masksets'];
activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
return masksets[activeMasksetIndex]['_buffer'].join('');
}
else return "";
case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
return this.data('_inputmask') ? !this.data('_inputmask')['opts'].autoUnmask : false;
case "isComplete":
masksets = this.data('_inputmask')['masksets'];
activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
opts = this.data('_inputmask')['opts'];
return maskScope(masksets, activeMasksetIndex).isComplete(this[0]._valueGet().split(''));
case "getmetadata": //return mask metadata if exists
if (this.data('_inputmask')) {
masksets = this.data('_inputmask')['masksets'];
activeMasksetIndex = this.data('_inputmask')['activeMasksetIndex'];
return masksets[activeMasksetIndex]['metadata'];
}
else return undefined;
default:
//check if the fn is an alias
if (!resolveAlias(fn, options)) {
//maybe fn is a mask so we try
//set mask
opts.mask = fn;
}
masksets = generateMaskSets();
if (masksets.length == 0) { return this; }
return this.each(function () {
maskScope($.extend(true, {}, masksets), activeMasksetIndex).mask(this);
});
break;
}
} else if (typeof fn == "object") {
opts = $.extend(true, {}, $.inputmask.defaults, fn);
resolveAlias(opts.alias, fn); //resolve aliases
masksets = generateMaskSets();
if (masksets.length == 0) { return this; }
return this.each(function () {
maskScope($.extend(true, {}, masksets), activeMasksetIndex).mask(this);
});
} else if (fn == undefined) {
//look for data-inputmask atribute - the attribute should only contain optipns
return this.each(function () {
var attrOptions = $(this).attr("data-inputmask");
if (attrOptions && attrOptions != "") {
try {
attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
var dataoptions = $.parseJSON("{" + attrOptions + "}");
$.extend(true, dataoptions, options);
opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
resolveAlias(opts.alias, dataoptions);
opts.alias = undefined;
$(this).inputmask(opts);
} catch (ex) { } //need a more relax parseJSON
}
});
}
//helper functions
function isInputEventSupported(eventName) {
var el = document.createElement('input'),
eventName = 'on' + eventName,
isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
function resolveAlias(aliasStr, options) {
var aliasDefinition = opts.aliases[aliasStr];
if (aliasDefinition) {
if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias); //alias is another alias
$.extend(true, opts, aliasDefinition); //merge alias definition in the options
$.extend(true, opts, options); //reapply extra given options
return true;
}
return false;
}
function getMaskTemplate(mask) {
if (opts.numericInput) {
mask = mask.split('').reverse().join('');
}
var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat;
if (repeat == "*") greedy = false;
//if (greedy == true && opts.placeholder == "") opts.placeholder = " ";
if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
var singleMask = $.map(mask.split(""), function (element, index) {
var outElem = [];
if (element == opts.escapeChar) {
escaped = true;
}
else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
var maskdef = opts.definitions[element];
if (maskdef && !escaped) {
for (var i = 0; i < maskdef.cardinality; i++) {
outElem.push(getPlaceHolder(outCount + i));
}
} else {
outElem.push(element);
escaped = false;
}
outCount += outElem.length;
return outElem;
}
});
//allocate repetitions
var repeatedMask = singleMask.slice();
for (var i = 1; i < repeat && greedy; i++) {
repeatedMask = repeatedMask.concat(singleMask.slice());
}
return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy };
}
//test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol}
function getTestingChain(mask) {
if (opts.numericInput) {
mask = mask.split('').reverse().join('');
}
var isOptional = false, escaped = false;
var newBlockMarker = false; //indicates wheter the begin/ending of a block should be indicated
return $.map(mask.split(""), function (element, index) {
var outElem = [];
if (element == opts.escapeChar) {
escaped = true;
} else if (element == opts.optionalmarker.start && !escaped) {
isOptional = true;
newBlockMarker = true;
}
else if (element == opts.optionalmarker.end && !escaped) {
isOptional = false;
newBlockMarker = true;
}
else {
var maskdef = opts.definitions[element];
if (maskdef && !escaped) {
var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
for (var i = 1; i < maskdef.cardinality; i++) {
var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
outElem.push({ fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function () { this.test = validator; } : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: isOptional, newBlockMarker: isOptional == true ? newBlockMarker : false, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
if (isOptional == true) //reset newBlockMarker
newBlockMarker = false;
}
outElem.push({ fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function () { this.test = maskdef.validator; } : new RegExp("."), cardinality: maskdef.cardinality, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: maskdef["casing"], def: maskdef["definitionSymbol"] || element });
} else {
outElem.push({ fn: null, cardinality: 0, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: null, def: element });
escaped = false;
}
//reset newBlockMarker
newBlockMarker = false;
return outElem;
}
});
}
function generateMaskSets() {
var ms = [];
var genmasks = []; //used to keep track of the masks that where processed, to avoid duplicates
var maskTokens = [];
function analyseMask(mask) { //just an idea - not in use for the moment
var tokenizer = /(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[]()|\\]+|./g;
function maskToken() {
this.matches = [];
this.isGroup = false;
this.isOptional = false;
this.isQuantifier = false;
};
var currentToken = new maskToken(),
match, m, openenings = [];
maskTokens = [];
while (match = tokenizer.exec(mask)) {
m = match[0];
switch (m.charAt(0)) {
case opts.optionalmarker.end:
// optional closing
case opts.groupmarker.end:
// Group closing
var openingToken = openenings.pop();
if (openenings.length > 0) {
openenings[openenings.length - 1]["matches"].push(openingToken);
} else {
maskTokens.push(openingToken);
currentToken = openingToken; //new maskToken();
}
break;
case opts.optionalmarker.start:
// optional opening
if (!currentToken.isGroup && currentToken.matches.length > 0)
maskTokens.push(currentToken);
currentToken = new maskToken();
currentToken.isOptional = true;
openenings.push(currentToken);
break;
case opts.groupmarker.start:
// Group opening
if (!currentToken.isGroup && currentToken.matches.length > 0)
maskTokens.push(currentToken);
currentToken = new maskToken();
currentToken.isGroup = true;
openenings.push(currentToken);
break;
case opts.quantifiermarker.start:
//Quantifier
var quantifier = new maskToken();
quantifier.isQuantifier = true;
quantifier.matches.push(m);
if (openenings.length > 0) {
openenings[openenings.length - 1]["matches"].push(quantifier);
} else {
currentToken.matches.push(quantifier);
}
break;
default:
if (openenings.length > 0) {
openenings[openenings.length - 1]["matches"].push(m);
} else {
if (currentToken.isGroup || currentToken.isOptional)
currentToken = new maskToken();
currentToken.matches.push(m);
}
}
}
if (currentToken.matches.length > 0)
maskTokens.push(currentToken);
return maskTokens;
}
function markOptional(maskPart) { //needed for the clearOptionalTail functionality
return opts.optionalmarker.start + maskPart + opts.optionalmarker.end;
}
function splitFirstOptionalEndPart(maskPart) {
var optionalStartMarkers = 0, optionalEndMarkers = 0, mpl = maskPart.length;
for (i = 0; i < mpl; i++) {
if (maskPart.charAt(i) == opts.optionalmarker.start) {
optionalStartMarkers++;
}
if (maskPart.charAt(i) == opts.optionalmarker.end) {
optionalEndMarkers++;
}
if (optionalStartMarkers > 0 && optionalStartMarkers == optionalEndMarkers)
break;
}
var maskParts = [maskPart.substring(0, i)];
if (i < mpl) {
maskParts.push(maskPart.substring(i + 1, mpl));
}
return maskParts;
}
function splitFirstOptionalStartPart(maskPart) {
var mpl = maskPart.length;
for (i = 0; i < mpl; i++) {
if (maskPart.charAt(i) == opts.optionalmarker.start) {
break;
}
}
var maskParts = [maskPart.substring(0, i)];
if (i < mpl) {
maskParts.push(maskPart.substring(i + 1, mpl));
}
return maskParts;
}
function generateMask(maskPrefix, maskPart, metadata) {
var maskParts = splitFirstOptionalEndPart(maskPart);
var newMask, maskTemplate;
var masks = splitFirstOptionalStartPart(maskParts[0]);
if (masks.length > 1) {
newMask = maskPrefix + masks[0] + markOptional(masks[1]) + (maskParts.length > 1 ? maskParts[1] : "");
if ($.inArray(newMask, genmasks) == -1 && newMask != "") {
genmasks.push(newMask);
maskTemplate = getMaskTemplate(newMask);
ms.push({
"mask": newMask,
"_buffer": maskTemplate["mask"],
"buffer": maskTemplate["mask"].slice(),
"tests": getTestingChain(newMask),
"lastValidPosition": -1,
"greedy": maskTemplate["greedy"],
"repeat": maskTemplate["repeat"],
"metadata": metadata
});
}
newMask = maskPrefix + masks[0] + (maskParts.length > 1 ? maskParts[1] : "");
if ($.inArray(newMask, genmasks) == -1 && newMask != "") {
genmasks.push(newMask);
maskTemplate = getMaskTemplate(newMask);
ms.push({
"mask": newMask,
"_buffer": maskTemplate["mask"],
"buffer": maskTemplate["mask"].slice(),
"tests": getTestingChain(newMask),
"lastValidPosition": -1,
"greedy": maskTemplate["greedy"],
"repeat": maskTemplate["repeat"],
"metadata": metadata
});
}
if (splitFirstOptionalStartPart(masks[1]).length > 1) { //optional contains another optional
generateMask(maskPrefix + masks[0], masks[1] + maskParts[1], metadata);
}
if (maskParts.length > 1 && splitFirstOptionalStartPart(maskParts[1]).length > 1) {
generateMask(maskPrefix + masks[0] + markOptional(masks[1]), maskParts[1], metadata);
generateMask(maskPrefix + masks[0], maskParts[1], metadata);
}
}
else {
newMask = maskPrefix + maskParts;
if ($.inArray(newMask, genmasks) == -1 && newMask != "") {
genmasks.push(newMask);
maskTemplate = getMaskTemplate(newMask);
ms.push({
"mask": newMask,
"_buffer": maskTemplate["mask"],
"buffer": maskTemplate["mask"].slice(),
"tests": getTestingChain(newMask),
"lastValidPosition": -1,
"greedy": maskTemplate["greedy"],
"repeat": maskTemplate["repeat"],
"metadata": metadata
});
}
}
}
if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
opts.mask = opts.mask.call(this, opts);
}
if ($.isArray(opts.mask)) {
$.each(opts.mask, function (ndx, msk) {
if (msk["mask"] != undefined) {
generateMask("", msk["mask"].toString(), msk);
} else
generateMask("", msk.toString());
});
} else generateMask("", opts.mask.toString());
analyseMask(opts.mask);
return opts.greedy ? ms : ms.sort(function (a, b) { return a["mask"].length - b["mask"].length; });
}
function getPlaceHolder(pos) {
return opts.placeholder.charAt(pos % opts.placeholder.length);
}
function maskScope(masksets, activeMasksetIndex) {
var isRTL = false,
valueOnFocus = getActiveBuffer().join(''),
$el, chromeValueOnInput;
//maskset helperfunctions
function getActiveMaskSet() {
return masksets[activeMasksetIndex];
}
function getActiveTests() {
return getActiveMaskSet()['tests'];
}
function getActiveBufferTemplate() {
return getActiveMaskSet()['_buffer'];
}
function getActiveBuffer() {
return getActiveMaskSet()['buffer'];
}
function isValid(pos, c, strict) { //strict true ~ no correction or autofill
strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
function _isValid(position, activeMaskset, c, strict) {
var testPos = determineTestPosition(position), loopend = c ? 1 : 0, chrs = '', buffer = activeMaskset["buffer"];
for (var i = activeMaskset['tests'][testPos].cardinality; i > loopend; i--) {
chrs += getBufferElement(buffer, testPos - (i - 1));
}
if (c) {
chrs += c;
}
//return is false or a json object => { pos: ??, c: ??} or true
return activeMaskset['tests'][testPos].fn != null ?
activeMaskset['tests'][testPos].fn.test(chrs, buffer, position, strict, opts)
: (c == getBufferElement(activeMaskset['_buffer'], position, true) || c == opts.skipOptionalPartCharacter) ?
{ "refresh": true, c: getBufferElement(activeMaskset['_buffer'], position, true), pos: position }
: false;
}
function PostProcessResults(maskForwards, results) {
var hasValidActual = false;
$.each(results, function (ndx, rslt) {
hasValidActual = $.inArray(rslt["activeMasksetIndex"], maskForwards) == -1 && rslt["result"] !== false;
if (hasValidActual) return false;
});
if (hasValidActual) { //strip maskforwards
results = $.map(results, function (rslt, ndx) {
if ($.inArray(rslt["activeMasksetIndex"], maskForwards) == -1) {
return rslt;
} else {
masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = actualLVP;
}
});
} else { //keep maskforwards with the least forward
var lowestPos = -1, lowestIndex = -1;
$.each(results, function (ndx, rslt) {
if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1 && rslt["result"] !== false & (lowestPos == -1 || lowestPos > rslt["result"]["pos"])) {
lowestPos = rslt["result"]["pos"];
lowestIndex = rslt["activeMasksetIndex"];
}
});
results = $.map(results, function (rslt, ndx) {
if ($.inArray(rslt["activeMasksetIndex"], maskForwards) != -1) {
if (rslt["result"]["pos"] == lowestPos) {
return rslt;
} else if (rslt["result"] !== false) {
for (var i = pos; i < lowestPos; i++) {
rsltValid = _isValid(i, masksets[rslt["activeMasksetIndex"]], masksets[lowestIndex]["buffer"][i], true);
if (rsltValid === false) {
masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos - 1;
break;
} else {
setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], i, masksets[lowestIndex]["buffer"][i], true);
masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = i;
}
}
//also check check for the lowestpos with the new input
rsltValid = _isValid(lowestPos, masksets[rslt["activeMasksetIndex"]], c, true);
if (rsltValid !== false) {
setBufferElement(masksets[rslt["activeMasksetIndex"]]["buffer"], lowestPos, c, true);
masksets[rslt["activeMasksetIndex"]]["lastValidPosition"] = lowestPos;
}
//console.log("ndx " + rslt["activeMasksetIndex"] + " validate " + masksets[rslt["activeMasksetIndex"]]["buffer"].join('') + " lv " + masksets[rslt["activeMasksetIndex"]]['lastValidPosition']);
return rslt;
}
}
});
}
return results;
}
if (strict) {
var result = _isValid(pos, getActiveMaskSet(), c, strict); //only check validity in current mask when validating strict
if (result === true) {
result = { "pos": pos }; //always take a possible corrected maskposition into account
}
return result;
}
var results = [], result = false, currentActiveMasksetIndex = activeMasksetIndex,
actualBuffer = getActiveBuffer().slice(), actualLVP = getActiveMaskSet()["lastValidPosition"],
actualPrevious = seekPrevious(pos),
maskForwards = [];
$.each(masksets, function (index, value) {
if (typeof (value) == "object") {
activeMasksetIndex = index;
var maskPos = pos;
var lvp = getActiveMaskSet()['lastValidPosition'],
rsltValid;
if (lvp == actualLVP) {
if ((maskPos - actualLVP) > 1) {
for (var i = lvp == -1 ? 0 : lvp; i < maskPos; i++) {
rsltValid = _isValid(i, getActiveMaskSet(), actualBuffer[i], true);
if (rsltValid === false) {
break;
} else {
setBufferElement(getActiveBuffer(), i, actualBuffer[i], true);
if (rsltValid === true) {
rsltValid = { "pos": i }; //always take a possible corrected maskposition into account
}
var newValidPosition = rsltValid.pos || i;
if (getActiveMaskSet()['lastValidPosition'] < newValidPosition)
getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid
}
}
}
//does the input match on a further position?
if (!isMask(maskPos) && !_isValid(maskPos, getActiveMaskSet(), c, strict)) {
var maxForward = seekNext(maskPos) - maskPos;
for (var fw = 0; fw < maxForward; fw++) {
if (_isValid(++maskPos, getActiveMaskSet(), c, strict) !== false)
break;
}
maskForwards.push(activeMasksetIndex);
//console.log('maskforward ' + activeMasksetIndex + " pos " + pos + " maskPos " + maskPos);
}
}
if (getActiveMaskSet()['lastValidPosition'] >= actualLVP || activeMasksetIndex == currentActiveMasksetIndex) {
if (maskPos >= 0 && maskPos < getMaskLength()) {
result = _isValid(maskPos, getActiveMaskSet(), c, strict);
if (result !== false) {
if (result === true) {
result = { "pos": maskPos }; //always take a possible corrected maskposition into account
}
var newValidPosition = result.pos || maskPos;
if (getActiveMaskSet()['lastValidPosition'] < newValidPosition)
getActiveMaskSet()['lastValidPosition'] = newValidPosition; //set new position from isValid
}
//console.log("pos " + pos + " ndx " + activeMasksetIndex + " validate " + getActiveBuffer().join('') + " lv " + getActiveMaskSet()['lastValidPosition']);
results.push({ "activeMasksetIndex": index, "result": result });
}
}
}
});
activeMasksetIndex = currentActiveMasksetIndex; //reset activeMasksetIndex
return PostProcessResults(maskForwards, results); //return results of the multiple mask validations
}
function determineActiveMasksetIndex() {
var currentMasksetIndex = activeMasksetIndex,
highestValid = { "activeMasksetIndex": 0, "lastValidPosition": -1, "next": -1 };
$.each(masksets, function (index, value) {
if (typeof (value) == "object") {
activeMasksetIndex = index;
if (getActiveMaskSet()['lastValidPosition'] > highestValid['lastValidPosition']) {
highestValid["activeMasksetIndex"] = index;
highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition'];
highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']);
} else if (getActiveMaskSet()['lastValidPosition'] == highestValid['lastValidPosition'] &&
(highestValid['next'] == -1 || highestValid['next'] > seekNext(getActiveMaskSet()['lastValidPosition']))) {
highestValid["activeMasksetIndex"] = index;
highestValid["lastValidPosition"] = getActiveMaskSet()['lastValidPosition'];
highestValid["next"] = seekNext(getActiveMaskSet()['lastValidPosition']);
}
}
});
activeMasksetIndex = highestValid["lastValidPosition"] != -1 && masksets[currentMasksetIndex]["lastValidPosition"] == highestValid["lastValidPosition"] ? currentMasksetIndex : highestValid["activeMasksetIndex"];
if (currentMasksetIndex != activeMasksetIndex) {
clearBuffer(getActiveBuffer(), seekNext(highestValid["lastValidPosition"]), getMaskLength());
getActiveMaskSet()["writeOutBuffer"] = true;
}
$el.data('_inputmask')['activeMasksetIndex'] = activeMasksetIndex; //store the activeMasksetIndex
}
function isMask(pos) {
var testPos = determineTestPosition(pos);
var test = getActiveTests()[testPos];
return test != undefined ? test.fn : false;
}
function determineTestPosition(pos) {
return pos % getActiveTests().length;
}
function getMaskLength() {
return opts.getMaskLength(getActiveBufferTemplate(), getActiveMaskSet()['greedy'], getActiveMaskSet()['repeat'], getActiveBuffer(), opts);
}
//pos: from position
function seekNext(pos) {
var maskL = getMaskLength();
if (pos >= maskL) return maskL;
var position = pos;
while (++position < maskL && !isMask(position)) {
}
;
return position;
}
//pos: from position
function seekPrevious(pos) {
var position = pos;
if (position <= 0) return 0;
while (--position > 0 && !isMask(position)) {
}
;
return position;
}
function setBufferElement(buffer, position, element, autoPrepare) {
if (autoPrepare) position = prepareBuffer(buffer, position);
var test = getActiveTests()[determineTestPosition(position)];
var elem = element;
if (elem != undefined && test != undefined) {
switch (test.casing) {
case "upper":
elem = element.toUpperCase();
break;
case "lower":
elem = element.toLowerCase();
break;
}
}
buffer[position] = elem;
}
function getBufferElement(buffer, position, autoPrepare) {
if (autoPrepare) position = prepareBuffer(buffer, position);
return buffer[position];
}
//needed to handle the non-greedy mask repetitions
function prepareBuffer(buffer, position) {
var j;
while (buffer[position] == undefined && buffer.length < getMaskLength()) {
j = 0;
while (getActiveBufferTemplate()[j] !== undefined) { //add a new buffer
buffer.push(getActiveBufferTemplate()[j++]);
}
}
return position;
}
function writeBuffer(input, buffer, caretPos) {
input._valueSet(buffer.join(''));
if (caretPos != undefined) {
caret(input, caretPos);
}
}
;
function clearBuffer(buffer, start, end, stripNomasks) {
for (var i = start, maskL = getMaskLength() ; i < end && i < maskL; i++) {
if (stripNomasks === true) {
if (!isMask(i))
setBufferElement(buffer, i, "");
} else
setBufferElement(buffer, i, getBufferElement(getActiveBufferTemplate().slice(), i, true));
}
}
;
function setReTargetPlaceHolder(buffer, pos) {
var testPos = determineTestPosition(pos);
setBufferElement(buffer, pos, getBufferElement(getActiveBufferTemplate(), testPos));
}
function checkVal(input, writeOut, strict, nptvl, intelliCheck) {
var inputValue = nptvl != undefined ? nptvl.slice() : truncateInput(input._valueGet()).split('');
$.each(masksets, function (ndx, ms) {
if (typeof (ms) == "object") {
ms["buffer"] = ms["_buffer"].slice();
ms["lastValidPosition"] = -1;
ms["p"] = -1;
}
});
if (strict !== true) activeMasksetIndex = 0;
if (writeOut) input._valueSet(""); //initial clear
var ml = getMaskLength();
$.each(inputValue, function (ndx, charCode) {
if(intelliCheck === true) {
var p = getActiveMaskSet()["p"], lvp = p == -1 ? p : seekPrevious(p),
pos = lvp == -1 ? ndx : seekNext(lvp);
if ($.inArray(charCode, getActiveBufferTemplate().slice(lvp + 1, pos)) == -1) {
$(input).trigger("_keypress", [true, charCode.charCodeAt(0), writeOut, strict, ndx]);
}
} else {
$(input).trigger("_keypress", [true, charCode.charCodeAt(0), writeOut, strict, ndx]);
}
});
if (strict === true && getActiveMaskSet()["p"] != -1) {
getActiveMaskSet()["lastValidPosition"] = seekPrevious(getActiveMaskSet()["p"]);
}
}
function escapeRegex(str) {
return $.inputmask.escapeRegex.call(this, str);
}
function truncateInput(inputValue) {
return inputValue.replace(new RegExp("(" + escapeRegex(getActiveBufferTemplate().join('')) + ")*$"), "");
}
function clearOptionalTail(input) {
var buffer = getActiveBuffer(), tmpBuffer = buffer.slice(), testPos, pos;
for (var pos = tmpBuffer.length - 1; pos >= 0; pos--) {
var testPos = determineTestPosition(pos);
if (getActiveTests()[testPos].optionality) {
if (!isMask(pos) || !isValid(pos, buffer[pos], true))
tmpBuffer.pop();
else break;
} else break;
}
writeBuffer(input, tmpBuffer);
}
//functionality fn
this.unmaskedvalue = function ($input, skipDatepickerCheck) {
isRTL = $input.data('_inputmask')['isRTL'];
return unmaskedvalue($input, skipDatepickerCheck);
};
function unmaskedvalue($input, skipDatepickerCheck) {
if (getActiveTests() && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
//checkVal(input, false, true);
var umValue = $.map(getActiveBuffer(), function (element, index) {
return isMask(index) && isValid(index, element, true) ? element : null;
});
return (isRTL ? umValue.reverse() : umValue).join('');
} else {
return $input[0]._valueGet();
}
}
function TranslatePosition(pos) {
if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
var bffrLght = getActiveBuffer().length;
pos = bffrLght - pos;
}
return pos;
}
function caret(input, begin, end) {
var npt = input.jquery && input.length > 0 ? input[0] : input, range;
if (typeof begin == 'number') {
begin = TranslatePosition(begin); end = TranslatePosition(end);
if (!$(input).is(':visible')) {
return;
}
end = (typeof end == 'number') ? end : begin;
npt.scrollLeft = npt.scrollWidth;
if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
if (npt.setSelectionRange) {
npt.selectionStart = begin;
npt.selectionEnd = android ? begin : end;
} else if (npt.createTextRange) {
range = npt.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
} else {
if (!$(input).is(':visible')) {
return { "begin": 0, "end": 0 };
}
if (npt.setSelectionRange) {
begin = npt.selectionStart;
end = npt.selectionEnd;
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
begin = TranslatePosition(begin); end = TranslatePosition(end);
return { "begin": begin, "end": end };
}
};
this.isComplete = function (buffer) {
return isComplete(buffer);
};
function isComplete(buffer) { //return true / false / undefined (repeat *)
if (opts.repeat == "*") return undefined;
var complete = false, highestValidPosition = 0, currentActiveMasksetIndex = activeMasksetIndex;
$.each(masksets, function (ndx, ms) {
if (typeof (ms) == "object") {
activeMasksetIndex = ndx;
var aml = seekPrevious(getMaskLength());
if (ms["lastValidPosition"] >= highestValidPosition && ms["lastValidPosition"] == aml) {
var msComplete = true;
for (var i = 0; i <= aml; i++) {
var mask = isMask(i), testPos = determineTestPosition(i);
if ((mask && (buffer[i] == undefined || buffer[i] == getPlaceHolder(i))) || (!mask && buffer[i] != getActiveBufferTemplate()[testPos])) {
msComplete = false;
break;
}
}
complete = complete || msComplete;
if (complete) //break loop
return false;
}
highestValidPosition = ms["lastValidPosition"];
}
});
activeMasksetIndex = currentActiveMasksetIndex; //reset activeMaskset
return complete;
}
function isSelection(begin, end) {
return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
(end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
}
this.mask = function (el) {
$el = $(el);
if (!$el.is(":input")) return;
//store tests & original buffer in the input element - used to get the unmasked value
$el.data('_inputmask', {
'masksets': masksets,
'activeMasksetIndex': activeMasksetIndex,
'opts': opts,
'isRTL': false
});
//show tooltip
if (opts.showTooltip) {
$el.prop("title", getActiveMaskSet()["mask"]);
}
//correct greedy setting if needed
getActiveMaskSet()['greedy'] = getActiveMaskSet()['greedy'] ? getActiveMaskSet()['greedy'] : getActiveMaskSet()['repeat'] == 0;
//handle maxlength attribute
if ($el.attr("maxLength") != null) //only when the attribute is set
{
var maxLength = $el.prop('maxLength');
if (maxLength > -1) { //handle *-repeat
$.each(masksets, function (ndx, ms) {
if (typeof (ms) == "object") {
if (ms["repeat"] == "*") {
ms["repeat"] = maxLength;
}
}
});
}
if (getMaskLength() >= maxLength && maxLength > -1) { //FF sets no defined max length to -1
if (maxLength < getActiveBufferTemplate().length) getActiveBufferTemplate().length = maxLength;
if (getActiveMaskSet()['greedy'] == false) {
getActiveMaskSet()['repeat'] = Math.round(maxLength / getActiveBufferTemplate().length);
}
$el.prop('maxLength', getMaskLength() * 2);
}
}
patchValueProperty(el);
//init vars
var skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
ignorable = false;
if (opts.numericInput) opts.isNumeric = opts.numericInput;
if (el.dir == "rtl" || (opts.numericInput && opts.rightAlignNumerics) || (opts.isNumeric && opts.rightAlignNumerics))
$el.css("text-align", "right");
if (el.dir == "rtl" || opts.numericInput) {
el.dir = "ltr";
$el.removeAttr("dir");
var inputData = $el.data('_inputmask');
inputData['isRTL'] = true;
$el.data('_inputmask', inputData);
isRTL = true;
}
//unbind all events - to make sure that no other mask will interfere when re-masking
$el.unbind(".inputmask");
$el.removeClass('focus.inputmask');
//bind events
$el.closest('form').bind("submit", function () { //trigger change on submit if any
if (valueOnFocus != getActiveBuffer().join('')) {
$el.change();
}
}).bind('reset', function () {
setTimeout(function () {
$el.trigger("setvalue");
}, 0);
});
$el.bind("mouseenter.inputmask", function () {
var $input = $(this), input = this;
if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
if (input._valueGet() != getActiveBuffer().join('')) {
writeBuffer(input, getActiveBuffer());
}
}
}).bind("blur.inputmask", function () {
var $input = $(this), input = this, nptValue = input._valueGet(), buffer = getActiveBuffer();
$input.removeClass('focus.inputmask');
if (valueOnFocus != getActiveBuffer().join('')) {
$input.change();
}
if (opts.clearMaskOnLostFocus && nptValue != '') {
if (nptValue == getActiveBufferTemplate().join(''))
input._valueSet('');
else { //clearout optional tail of the mask
clearOptionalTail(input);
}
}
if (isComplete(buffer) === false) {
$input.trigger("incomplete");
if (opts.clearIncomplete) {
$.each(masksets, function (ndx, ms) {
if (typeof (ms) == "object") {
ms["buffer"] = ms["_buffer"].slice();
ms["lastValidPosition"] = -1;
}
});
activeMasksetIndex = 0;
if (opts.clearMaskOnLostFocus)
input._valueSet('');
else {
buffer = getActiveBufferTemplate().slice();
writeBuffer(input, buffer);
}
}
}
}).bind("focus.inputmask", function () {
var $input = $(this), input = this, nptValue = input._valueGet();
if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
if (input._valueGet() != getActiveBuffer().join('')) {
writeBuffer(input, getActiveBuffer(), seekNext(getActiveMaskSet()["lastValidPosition"]));
}
}
$input.addClass('focus.inputmask');
valueOnFocus = getActiveBuffer().join('');
}).bind("mouseleave.inputmask", function () {
var $input = $(this), input = this;
if (opts.clearMaskOnLostFocus) {
if (!$input.hasClass('focus.inputmask') && input._valueGet() != $input.attr("placeholder")) {
if (input._valueGet() == getActiveBufferTemplate().join('') || input._valueGet() == '')
input._valueSet('');
else { //clearout optional tail of the mask
clearOptionalTail(input);
}
}
}
}).bind("click.inputmask", function () {
var input = this;
setTimeout(function () {
var selectedCaret = caret(input), buffer = getActiveBuffer();
if (selectedCaret.begin == selectedCaret.end) {
var clickPosition = opts.isRTL ? TranslatePosition(selectedCaret.begin) : selectedCaret.begin,
lvp = getActiveMaskSet()["lastValidPosition"],
lastPosition;
if (opts.isNumeric) {
lastPosition = opts.skipRadixDance === false && opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 ?
(opts.numericInput ? seekNext($.inArray(opts.radixPoint, buffer)) : $.inArray(opts.radixPoint, buffer)) :
seekNext(lvp);
} else {
lastPosition = seekNext(lvp);
}
if (clickPosition < lastPosition) {
if (isMask(clickPosition))
caret(input, clickPosition);
else caret(input, seekNext(clickPosition));
} else
caret(input, lastPosition);
}
}, 0);
}).bind('dblclick.inputmask', function () {
var input = this;
setTimeout(function () {
caret(input, 0, seekNext(getActiveMaskSet()["lastValidPosition"]));
}, 0);
}).bind(pasteEvent + ".inputmask dragdrop.inputmask drop.inputmask", function (e) {
var input = this, $input = $(input);
//paste event for IE8 and lower I guess ;-)
if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
return true;
}
setTimeout(function () {
checkVal(input, true, false, undefined, true);
if (isComplete(getActiveBuffer()) === true)
$input.trigger("complete");
$input.click();
}, 0);
}).bind('setvalue.inputmask', function () {
var input = this;
checkVal(input, true);
valueOnFocus = getActiveBuffer().join('');
if (input._valueGet() == getActiveBufferTemplate().join(''))
input._valueSet('');
}).bind("_keypress.inputmask", keypressEvent //will be skipped be the eventruler
).bind('complete.inputmask', opts.oncomplete
).bind('incomplete.inputmask', opts.onincomplete
).bind('cleared.inputmask', opts.oncleared
).bind("keyup.inputmask", keyupEvent);
if (androidchrome) {
$el.bind("input.inputmask", function (e) {
var input = this, $input = $(input);
chromeValueOnInput = getActiveBuffer().join('');
checkVal(input, false, false);
writeBuffer(input, getActiveBuffer());
if (isComplete(getActiveBuffer()) === true)
$input.trigger("complete");
$input.click();
});
} else {
$el.bind("keydown.inputmask", keydownEvent
).bind("keypress.inputmask", keypressEvent);
}
//apply mask
checkVal(el, true, false);
valueOnFocus = getActiveBuffer().join('');
// Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
var activeElement;
try {
activeElement = document.activeElement;
} catch (e) {
}
if (activeElement === el) { //position the caret when in focus
$el.addClass('focus.inputmask');
caret(el, seekNext(getActiveMaskSet()["lastValidPosition"]));
} else if (opts.clearMaskOnLostFocus) {
if (getActiveBuffer().join('') == getActiveBufferTemplate().join('')) {
el._valueSet('');
} else {
clearOptionalTail(el);
}
} else {
writeBuffer(el, getActiveBuffer());
}
installEventRuler(el);
//private functions
function installEventRuler(npt) {
var events = $._data(npt).events;
$.each(events, function (eventType, eventHandlers) {
$.each(eventHandlers, function (ndx, eventHandler) {
if (eventHandler.namespace == "inputmask") {
if (eventHandler.type != "setvalue" && eventHandler.type != "_keypress") {
var handler = eventHandler.handler;
eventHandler.handler = function (e) {
if (this.readOnly || this.disabled)
e.preventDefault;
else
return handler.apply(this, arguments);
};
}
}
});
});
}
function patchValueProperty(npt) {
var valueProperty;
if (Object.getOwnPropertyDescriptor)
valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
if (valueProperty && valueProperty.get) {
if (!npt._valueGet) {
var valueGet = valueProperty.get;
var valueSet = valueProperty.set;
npt._valueGet = function () {
return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
};
npt._valueSet = function (value) {
valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
};
Object.defineProperty(npt, "value", {
get: function () {
var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'],
activeMasksetIndex = inputData['activeMasksetIndex'];
return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : '';
},
set: function (value) {
valueSet.call(this, value);
$(this).triggerHandler('setvalue.inputmask');
}
});
}
} else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
if (!npt._valueGet) {
var valueGet = npt.__lookupGetter__("value");
var valueSet = npt.__lookupSetter__("value");
npt._valueGet = function () {
return isRTL ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
};
npt._valueSet = function (value) {
valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
};
npt.__defineGetter__("value", function () {
var $self = $(this), inputData = $(this).data('_inputmask'), masksets = inputData['masksets'],
activeMasksetIndex = inputData['activeMasksetIndex'];
return inputData && inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : valueGet.call(this) != masksets[activeMasksetIndex]['_buffer'].join('') ? valueGet.call(this) : '';
});
npt.__defineSetter__("value", function (value) {
valueSet.call(this, value);
$(this).triggerHandler('setvalue.inputmask');
});
}
} else {
if (!npt._valueGet) {
npt._valueGet = function () { return isRTL ? this.value.split('').reverse().join('') : this.value; };
npt._valueSet = function (value) { this.value = isRTL ? value.split('').reverse().join('') : value; };
}
if ($.valHooks.text == undefined || $.valHooks.text.inputmaskpatch != true) {
var valueGet = $.valHooks.text && $.valHooks.text.get ? $.valHooks.text.get : function (elem) { return elem.value; };
var valueSet = $.valHooks.text && $.valHooks.text.set ? $.valHooks.text.set : function (elem, value) { elem.value = value; return elem; };
jQuery.extend($.valHooks, {
text: {
get: function (elem) {
var $elem = $(elem);
if ($elem.data('_inputmask')) {
if ($elem.data('_inputmask')['opts'].autoUnmask)
return $elem.inputmask('unmaskedvalue');
else {
var result = valueGet(elem),
inputData = $elem.data('_inputmask'), masksets = inputData['masksets'],
activeMasksetIndex = inputData['activeMasksetIndex'];
return result != masksets[activeMasksetIndex]['_buffer'].join('') ? result : '';
}
} else return valueGet(elem);
},
set: function (elem, value) {
var $elem = $(elem);
var result = valueSet(elem, value);
if ($elem.data('_inputmask')) $elem.triggerHandler('setvalue.inputmask');
return result;
},
inputmaskpatch: true
}
});
}
}
}
//shift chars to left from start to end and put c at end position if defined
function shiftL(start, end, c, maskJumps) {
var buffer = getActiveBuffer();
if (maskJumps !== false) //jumping over nonmask position
while (!isMask(start) && start - 1 >= 0) start--;
for (var i = start; i < end && i < getMaskLength() ; i++) {
if (isMask(i)) {
setReTargetPlaceHolder(buffer, i);
var j = seekNext(i);
var p = getBufferElement(buffer, j);
if (p != getPlaceHolder(j)) {
if (j < getMaskLength() && isValid(i, p, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def) {
setBufferElement(buffer, i, getBufferElement(buffer, j), true);
if (j < end) {
setReTargetPlaceHolder(buffer, j); //cleanup next position
}
} else {
if (isMask(i))
break;
}
} //else if (c == undefined) break;
} else {
setReTargetPlaceHolder(buffer, i);
}
}
if (c != undefined)
setBufferElement(buffer, seekPrevious(end), c);
if (getActiveMaskSet()["greedy"] == false) {
var trbuffer = truncateInput(buffer.join('')).split('');
buffer.length = trbuffer.length;
for (var i = 0, bl = buffer.length; i < bl; i++) {
buffer[i] = trbuffer[i];
}
if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice();
}
return start; //return the used start position
}
function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
var buffer = getActiveBuffer();
for (var i = start; i <= end && i < getMaskLength() ; i++) {
if (isMask(i)) {
var t = getBufferElement(buffer, i, true);
setBufferElement(buffer, i, c, true);
if (t != getPlaceHolder(i)) {
var j = seekNext(i);
if (j < getMaskLength()) {
if (isValid(j, t, true) !== false && getActiveTests()[determineTestPosition(i)].def == getActiveTests()[determineTestPosition(j)].def)
c = t;
else {
if (isMask(j))
break;
else c = t;
}
} else break;
} else {
c = t;
if (full !== true) break;
}
} else
setReTargetPlaceHolder(buffer, i);
}
var lengthBefore = buffer.length;
if (getActiveMaskSet()["greedy"] == false) {
var trbuffer = truncateInput(buffer.join('')).split('');
buffer.length = trbuffer.length;
for (var i = 0, bl = buffer.length; i < bl; i++) {
buffer[i] = trbuffer[i];
}
if (buffer.length == 0) getActiveMaskSet()["buffer"] = getActiveBufferTemplate().slice();
}
return end - (lengthBefore - buffer.length); //return new start position
};
function HandleRemove(input, k, pos) {
if (opts.numericInput || isRTL) {
switch (k) {
case opts.keyCode.BACKSPACE:
k = opts.keyCode.DELETE;
break;
case opts.keyCode.DELETE:
k = opts.keyCode.BACKSPACE;
break;
}
if (isRTL) {
var pend = pos.end;
pos.end = pos.begin;
pos.begin = pend;
}
}
var isSelection = true;
if (pos.begin == pos.end) {
var posBegin = k == opts.keyCode.BACKSPACE ? pos.begin - 1 : pos.begin;
if (opts.isNumeric && opts.radixPoint != "" && getActiveBuffer()[posBegin] == opts.radixPoint) {
pos.begin = (getActiveBuffer().length - 1 == posBegin) /* radixPoint is latest? delete it */ ? pos.begin : k == opts.keyCode.BACKSPACE ? posBegin : seekNext(posBegin);
pos.end = pos.begin;
}
isSelection = false;
if (k == opts.keyCode.BACKSPACE)
pos.begin--;
else if (k == opts.keyCode.DELETE)
pos.end++;
} else if (pos.end - pos.begin == 1 && !opts.insertMode) {
isSelection = false;
if (k == opts.keyCode.BACKSPACE)
pos.begin--;
}
clearBuffer(getActiveBuffer(), pos.begin, pos.end);
var ml = getMaskLength();
if (opts.greedy == false) {
shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
} else {
var newpos = pos.begin;
for (var i = pos.begin; i < pos.end; i++) { //seeknext to skip placeholders at start in selection
if (isMask(i) || !isSelection)
newpos = shiftL(pos.begin, ml, undefined, !isRTL && (k == opts.keyCode.BACKSPACE && !isSelection));
}
if (!isSelection) pos.begin = newpos;
}
var firstMaskPos = seekNext(-1);
clearBuffer(getActiveBuffer(), pos.begin, pos.end, true);
checkVal(input, false, masksets[1] == undefined || firstMaskPos >= pos.end, getActiveBuffer());
if (getActiveMaskSet()['lastValidPosition'] < firstMaskPos) {
getActiveMaskSet()["lastValidPosition"] = -1;
getActiveMaskSet()["p"] = firstMaskPos;
} else {
getActiveMaskSet()["p"] = pos.begin;
}
}
function keydownEvent(e) {
//Safari 5.1.x - modal dialog fires keypress twice workaround
skipKeyPressEvent = false;
var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
//backspace, delete, and escape get special treatment
if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127) || e.ctrlKey && k == 88) { //backspace/delete
e.preventDefault(); //stop default action but allow propagation
if (k == 88) valueOnFocus = getActiveBuffer().join('');
HandleRemove(input, k, pos);
determineActiveMasksetIndex();
writeBuffer(input, getActiveBuffer(), getActiveMaskSet()["p"]);
if (input._valueGet() == getActiveBufferTemplate().join(''))
$input.trigger('cleared');
if (opts.showTooltip) { //update tooltip
$input.prop("title", getActiveMaskSet()["mask"]);
}
}
else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
setTimeout(function () {
var caretPos = seekNext(getActiveMaskSet()["lastValidPosition"]);
if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
}, 0);
} else if ((k == opts.keyCode.HOME && !e.shiftKey) || k == opts.keyCode.PAGE_UP) { //Home or page_up
caret(input, 0, e.shiftKey ? pos.begin : 0);
} else if (k == opts.keyCode.ESCAPE || (k == 90 && e.ctrlKey)) { //escape && undo
checkVal(input, true, false, valueOnFocus.split(''));
$input.click();
} else if (k == opts.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
opts.insertMode = !opts.insertMode;
caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
} else if (opts.insertMode == false && !e.shiftKey) {
if (k == opts.keyCode.RIGHT) {
setTimeout(function () {
var caretPos = caret(input);
caret(input, caretPos.begin);
}, 0);
} else if (k == opts.keyCode.LEFT) {
setTimeout(function () {
var caretPos = caret(input);
caret(input, caretPos.begin - 1);
}, 0);
}
}
var currentCaretPos = caret(input);
if (opts.onKeyDown.call(this, e, getActiveBuffer(), opts) === true) //extra stuff to execute on keydown
caret(input, currentCaretPos.begin, currentCaretPos.end);
ignorable = $.inArray(k, opts.ignorables) != -1;
}
function keypressEvent(e, checkval, k, writeOut, strict, ndx) {
//Safari 5.1.x - modal dialog fires keypress twice workaround
if (k == undefined && skipKeyPressEvent) return false;
skipKeyPressEvent = true;
var input = this, $input = $(input);
e = e || window.event;
var k = k || e.which || e.charCode || e.keyCode;
if ((!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable)) && checkval !== true) {
return true;
} else {
if (k) {
//special treat the decimal separator
if (checkval !== true && k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
var pos, results, result, c = String.fromCharCode(k);
if (checkval) {
var pcaret = strict ? ndx : getActiveMaskSet()["lastValidPosition"] + 1;
pos = { begin: pcaret, end: pcaret };
} else {
pos = caret(input);
}
//should we clear a possible selection??
var isSlctn = isSelection(pos.begin, pos.end), redetermineLVP = false,
initialIndex = activeMasksetIndex;
if (isSlctn) {
activeMasksetIndex = initialIndex;
$.each(masksets, function (ndx, lmnt) { //init undobuffer for recovery when not valid
if (typeof (lmnt) == "object") {
activeMasksetIndex = ndx;
getActiveMaskSet()["undoBuffer"] = getActiveBuffer().join('');
}
});
HandleRemove(input, opts.keyCode.DELETE, pos);
if (!opts.insertMode) { //preserve some space
$.each(masksets, function (ndx, lmnt) {
if (typeof (lmnt) == "object") {
activeMasksetIndex = ndx;
shiftR(pos.begin, getMaskLength(), getPlaceHolder(pos.begin), true);
getActiveMaskSet()["lastValidPosition"] = seekNext(getActiveMaskSet()["lastValidPosition"]);
}
});
}
activeMasksetIndex = initialIndex; //restore index
}
var radixPosition = getActiveBuffer().join('').indexOf(opts.radixPoint);
if (opts.isNumeric && checkval !== true && radixPosition != -1) {
if (opts.greedy && pos.begin <= radixPosition) {
pos.begin = seekPrevious(pos.begin);
pos.end = pos.begin;
} else if (c == opts.radixPoint) {
pos.begin = radixPosition;
pos.end = pos.begin;
}
}
var p = pos.begin;
results = isValid(p, c, strict);
if (strict === true) results = [{ "activeMasksetIndex": activeMasksetIndex, "result": results }];
var minimalForwardPosition = -1;
$.each(results, function (index, result) {
activeMasksetIndex = result["activeMasksetIndex"];
getActiveMaskSet()["writeOutBuffer"] = true;
var np = result["result"];
if (np !== false) {
var refresh = false, buffer = getActiveBuffer();
if (np !== true) {
refresh = np["refresh"]; //only rewrite buffer from isValid
p = np.pos != undefined ? np.pos : p; //set new position from isValid
c = np.c != undefined ? np.c : c; //set new char from isValid
}
if (refresh !== true) {
if (opts.insertMode == true) {
var lastUnmaskedPosition = getMaskLength();
var bfrClone = buffer.slice();
while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) {
lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(lastUnmaskedPosition);
}
if (lastUnmaskedPosition >= p) {
shiftR(p, buffer.length, c);
//shift the lvp if needed
var lvp = getActiveMaskSet()["lastValidPosition"], nlvp = seekNext(lvp);
if (nlvp != getMaskLength() && lvp >= p && (getBufferElement(getActiveBuffer(), nlvp, true) != getPlaceHolder(nlvp))) {
getActiveMaskSet()["lastValidPosition"] = nlvp;
}
} else getActiveMaskSet()["writeOutBuffer"] = false;
} else setBufferElement(buffer, p, c, true);
if (minimalForwardPosition == -1 || minimalForwardPosition > seekNext(p)) {
minimalForwardPosition = seekNext(p);
}
} else if (!strict) {
var nextPos = p < getMaskLength() ? p + 1 : p;
if (minimalForwardPosition == -1 || minimalForwardPosition > nextPos) {
minimalForwardPosition = nextPos;
}
}
if (minimalForwardPosition > getActiveMaskSet()["p"])
getActiveMaskSet()["p"] = minimalForwardPosition; //needed for checkval strict
}
});
if (strict !== true) {
activeMasksetIndex = initialIndex;
determineActiveMasksetIndex();
}
if (writeOut !== false) {
$.each(results, function (ndx, rslt) {
if (rslt["activeMasksetIndex"] == activeMasksetIndex) {
result = rslt;
return false;
}
});
if (result != undefined) {
var self = this;
setTimeout(function () { opts.onKeyValidation.call(self, result["result"], opts); }, 0);
if (getActiveMaskSet()["writeOutBuffer"] && result["result"] !== false) {
var buffer = getActiveBuffer();
var newCaretPosition;
if (checkval) {
newCaretPosition = undefined;
} else if (opts.numericInput) {
if (p > radixPosition) {
newCaretPosition = seekPrevious(minimalForwardPosition);
} else if (c == opts.radixPoint) {
newCaretPosition = minimalForwardPosition - 1;
} else newCaretPosition = seekPrevious(minimalForwardPosition - 1);
} else {
newCaretPosition = minimalForwardPosition;
}
writeBuffer(input, buffer, newCaretPosition);
if (checkval !== true) {
setTimeout(function () { //timeout needed for IE
if (isComplete(buffer) === true)
$input.trigger("complete");
}, 0);
}
} else if (isSlctn) {
getActiveMaskSet()["buffer"] = getActiveMaskSet()["undoBuffer"].split('');
}
}
}
if (opts.showTooltip) { //update tooltip
$input.prop("title", getActiveMaskSet()["mask"]);
}
e.preventDefault();
}
}
}
function keyupEvent(e) {
var $input = $(this), input = this, k = e.keyCode, buffer = getActiveBuffer();
if (androidchrome && k == opts.keyCode.BACKSPACE) {
if (chromeValueOnInput == input._valueGet())
keydownEvent.call(this, e);
}
opts.onKeyUp.call(this, e, buffer, opts); //extra stuff to execute on keyup
if (k == opts.keyCode.TAB && opts.showMaskOnFocus) {
if ($input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
buffer = getActiveBufferTemplate().slice();
writeBuffer(input, buffer);
caret(input, 0);
valueOnFocus = getActiveBuffer().join('');
} else {
writeBuffer(input, buffer);
caret(input, 0, getMaskLength());
}
}
}
};
return this;
};
return this;
};
}
})(jQuery);
/*!
* jQuery Password Strength plugin for Twitter Bootstrap
*
* Copyright (c) 2008-2013 Tane Piper
* Copyright (c) 2013 Alejandro Blanco
* Dual licensed under the MIT and GPL licenses.
*/
(function (jQuery) {
// Source: src/rules.js
var rulesEngine = {};
try {
if (!jQuery && module && module.exports) {
var jQuery = require("jquery"),
jsdom = require("jsdom").jsdom;
jQuery = jQuery(jsdom().parentWindow);
}
} catch (ignore) { }
(function ($, rulesEngine) {
"use strict";
var validation = {};
rulesEngine.forbiddenSequences = [
"0123456789", "abcdefghijklmnopqrstuvwxyz", "qwertyuiop", "asdfghjkl",
"zxcvbnm", "!@#$%^&*()_+"
];
validation.wordNotEmail = function (options, word, score) {
if (word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i)) {
return score;
}
return 0;
};
validation.wordLength = function (options, word, score) {
var wordlen = word.length,
lenScore = Math.pow(wordlen, options.rules.raisePower);
if (wordlen < options.common.minChar) {
lenScore = (lenScore + score);
}
return lenScore;
};
validation.wordSimilarToUsername = function (options, word, score) {
var username = $(options.common.usernameField).val();
if (username && word.toLowerCase().match(username.replace(/[\-\[\]\/\{\}\(\)\*\+\=\?\:\.\\\^\$\|\!\,]/g, "\\$&").toLowerCase())) {
return score;
}
return 0;
};
validation.wordTwoCharacterClasses = function (options, word, score) {
if (word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) ||
(word.match(/([a-zA-Z])/) && word.match(/([0-9])/)) ||
(word.match(/(.[!,@,#,$,%,\^,&,*,?,_,~])/) && word.match(/[a-zA-Z0-9_]/))) {
return score;
}
return 0;
};
validation.wordRepetitions = function (options, word, score) {
if (word.match(/(.)\1\1/)) { return score; }
return 0;
};
validation.wordSequences = function (options, word, score) {
var found = false,
j;
if (word.length > 2) {
$.each(rulesEngine.forbiddenSequences, function (idx, seq) {
if (found) { return; }
var sequences = [seq, seq.split('').reverse().join('')];
$.each(sequences, function (idx, sequence) {
for (j = 0; j < (word.length - 2) ; j += 1) { // iterate the word trough a sliding window of size 3:
if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) {
found = true;
}
}
});
});
if (found) { return score; }
}
return 0;
};
validation.wordLowercase = function (options, word, score) {
return word.match(/[a-z]/) && score;
};
validation.wordUppercase = function (options, word, score) {
return word.match(/[A-Z]/) && score;
};
validation.wordOneNumber = function (options, word, score) {
return word.match(/\d+/) && score;
};
validation.wordThreeNumbers = function (options, word, score) {
return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score;
};
validation.wordOneSpecialChar = function (options, word, score) {
return word.match(/[!,@,#,$,%,\^,&,*,?,_,~]/) && score;
};
validation.wordTwoSpecialChar = function (options, word, score) {
return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score;
};
validation.wordUpperLowerCombo = function (options, word, score) {
return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score;
};
validation.wordLetterNumberCombo = function (options, word, score) {
return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score;
};
validation.wordLetterNumberCharCombo = function (options, word, score) {
return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score;
};
rulesEngine.validation = validation;
rulesEngine.executeRules = function (options, word) {
var totalScore = 0;
$.each(options.rules.activated, function (rule, active) {
if (active) {
var score = options.rules.scores[rule],
funct = rulesEngine.validation[rule],
result,
errorMessage;
if (!$.isFunction(funct)) {
funct = options.rules.extra[rule];
}
if ($.isFunction(funct)) {
result = funct(options, word, score);
if (result) {
totalScore += result;
}
if (result < 0 || (!$.isNumeric(result) && !result)) {
errorMessage = options.ui.spanError(options, rule);
if (errorMessage.length > 0) {
options.instances.errors.push(errorMessage);
}
}
}
}
});
return totalScore;
};
}(jQuery, rulesEngine));
try {
if (module && module.exports) {
module.exports = rulesEngine;
}
} catch (ignore) { }
// Source: src/options.js
var defaultOptions = {};
defaultOptions.common = {};
defaultOptions.common.minChar = 6;
defaultOptions.common.usernameField = "#username";
defaultOptions.common.userInputs = [
// Selectors for input fields with user input
];
defaultOptions.common.onLoad = undefined;
defaultOptions.common.onKeyUp = undefined;
defaultOptions.common.zxcvbn = false;
defaultOptions.common.zxcvbnTerms = [
// List of disrecommended words
];
defaultOptions.common.debug = false;
defaultOptions.rules = {};
defaultOptions.rules.extra = {};
defaultOptions.rules.scores = {
wordNotEmail: -100,
wordLength: -50,
wordSimilarToUsername: -100,
wordSequences: -20,
wordTwoCharacterClasses: 2,
wordRepetitions: -25,
wordLowercase: 1,
wordUppercase: 3,
wordOneNumber: 3,
wordThreeNumbers: 5,
wordOneSpecialChar: 3,
wordTwoSpecialChar: 5,
wordUpperLowerCombo: 2,
wordLetterNumberCombo: 2,
wordLetterNumberCharCombo: 2
};
defaultOptions.rules.activated = {
wordNotEmail: true,
wordLength: true,
wordSimilarToUsername: true,
wordSequences: true,
wordTwoCharacterClasses: false,
wordRepetitions: false,
wordLowercase: true,
wordUppercase: true,
wordOneNumber: true,
wordThreeNumbers: true,
wordOneSpecialChar: true,
wordTwoSpecialChar: true,
wordUpperLowerCombo: true,
wordLetterNumberCombo: true,
wordLetterNumberCharCombo: true
};
defaultOptions.rules.raisePower = 1.4;
defaultOptions.ui = {};
defaultOptions.ui.bootstrap2 = false;
defaultOptions.ui.showProgressBar = true;
defaultOptions.ui.showPopover = false;
defaultOptions.ui.showStatus = false;
defaultOptions.ui.spanError = function (options, key) {
"use strict";
var text = options.ui.errorMessages[key];
if (!text) { return ''; }
return '' + text + ' ';
};
defaultOptions.ui.popoverError = function (errors) {
"use strict";
var message = "Errors:
";
jQuery.each(errors, function (idx, err) {
message += "" + err + " ";
});
message += " ";
return message;
};
defaultOptions.ui.errorMessages = {
wordLength: wPasswordwordLength,//"Your password is too short",
wordNotEmail: wPasswordwordNotEmail,//"Do not use your email as your password",
wordSimilarToUsername: wPasswordwordSimilarToUsername,//"Your password cannot contain your username",
wordTwoCharacterClasses: wPasswordwordTwoCharacterClasses,//"Use different character classes",
wordRepetitions: wPasswordwordRepetitions,//"Too many repetitions",
wordSequences: wPasswordwordSequences//"Your password contains sequences"
};
defaultOptions.ui.verdicts = [wPasswordStrengthWeak, wPasswordStrengthNormal, wPasswordStrengthMedium, wPasswordStrengthStrong, wPasswordStrengthVeryStrong]//["Weak", "Normal", "Medium", "Strong", "Very Strong"];
defaultOptions.ui.showVerdicts = true;
defaultOptions.ui.showVerdictsInsideProgressBar = false;
defaultOptions.ui.useVerdictCssClass = false;
defaultOptions.ui.showErrors = false;
defaultOptions.ui.container = undefined;
defaultOptions.ui.viewports = {
progress: undefined,
verdict: undefined,
errors: undefined
};
defaultOptions.ui.scores = [14, 26, 38, 50];
// Source: src/ui.js
var ui = {};
(function ($, ui) {
"use strict";
var barClasses = ["danger", "warning", "success"],
statusClasses = ["error", "warning", "success"];
ui.getContainer = function (options, $el) {
var $container;
$container = $(options.ui.container);
if (!($container && $container.length === 1)) {
$container = $el.parent();
}
return $container;
};
ui.findElement = function ($container, viewport, cssSelector) {
if (viewport) {
return $container.find(viewport).find(cssSelector);
}
return $container.find(cssSelector);
};
ui.getUIElements = function (options, $el) {
var $container, result;
if (options.instances.viewports) {
return options.instances.viewports;
}
$container = ui.getContainer(options, $el);
result = {};
result.$progressbar = ui.findElement($container, options.ui.viewports.progress, "div.progress");
if (options.ui.showVerdictsInsideProgressBar) {
result.$verdict = result.$progressbar.find("span.password-verdict");
}
if (!options.ui.showPopover) {
if (!options.ui.showVerdictsInsideProgressBar) {
result.$verdict = ui.findElement($container, options.ui.viewports.verdict, "span.password-verdict");
}
result.$errors = ui.findElement($container, options.ui.viewports.errors, "ul.error-list");
}
options.instances.viewports = result;
return result;
};
ui.initProgressBar = function (options, $el) {
var $container = ui.getContainer(options, $el),
progressbar = "";
if (options.ui.showVerdictsInsideProgressBar) {
progressbar += " ";
}
progressbar += "
";
if (options.ui.viewports.progress) {
$container.find(options.ui.viewports.progress).append(progressbar);
} else {
$(progressbar).insertAfter($el);
}
};
ui.initHelper = function (options, $el, html, viewport) {
var $container = ui.getContainer(options, $el);
if (viewport) {
$container.find(viewport).append(html);
} else {
$(html).insertAfter($el);
}
};
ui.initVerdict = function (options, $el) {
ui.initHelper(options, $el, " ",
options.ui.viewports.verdict);
};
ui.initErrorList = function (options, $el) {
ui.initHelper(options, $el, "",
options.ui.viewports.errors);
};
ui.initPopover = function (options, $el) {
$el.popover("destroy");
$el.popover({
html: true,
placement: options.ui.popoverPlacement ? options.ui.popoverPlacement: "top",
trigger: "manual",
content: " "
});
};
ui.initUI = function (options, $el) {
if (options.ui.showPopover) {
ui.initPopover(options, $el);
} else {
if (options.ui.showErrors) { ui.initErrorList(options, $el); }
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.initVerdict(options, $el);
}
}
if (options.ui.showProgressBar) {
ui.initProgressBar(options, $el);
}
};
ui.possibleProgressBarClasses = ["danger", "warning", "success"];
ui.updateProgressBar = function (options, $el, cssClass, percentage) {
var $progressbar = ui.getUIElements(options, $el).$progressbar,
$bar = $progressbar.find(".progress-bar"),
cssPrefix = "progress-";
if (options.ui.bootstrap2) {
$bar = $progressbar.find(".bar");
cssPrefix = "";
}
$.each(ui.possibleProgressBarClasses, function (idx, value) {
$bar.removeClass(cssPrefix + "bar-" + value);
});
$bar.addClass(cssPrefix + "bar-" + barClasses[cssClass]);
$bar.css("width", percentage + '%');
};
ui.updateVerdict = function (options, $el, cssClass, text) {
var $verdict = ui.getUIElements(options, $el).$verdict;
$verdict.removeClass(barClasses.join(' '));
if (cssClass > -1) {
$verdict.addClass(barClasses[cssClass]);
}
$verdict.html(text);
};
ui.updateErrors = function (options, $el) {
var $errors = ui.getUIElements(options, $el).$errors,
html = "";
$.each(options.instances.errors, function (idx, err) {
html += "" + err + " ";
});
$errors.html(html);
};
ui.updatePopover = function (options, $el, verdictText) {
var popover = $el.data("bs.popover"),
html = "",
hide = true;
if (options.ui.showVerdicts &&
!options.ui.showVerdictsInsideProgressBar &&
verdictText.length > 0) {
html = "" + verdictText +
" ";
hide = false;
}
if (options.ui.showErrors) {
if (options.instances.errors.length > 0) {
hide = false;
}
html += options.ui.popoverError(options.instances.errors);
}
if (hide) {
$el.popover("hide");
return;
}
if (options.ui.bootstrap2) { popover = $el.data("popover"); }
if (popover.$arrow && popover.$arrow.parents("body").length > 0) {
$el.find("+ .popover .popover-content").html(html);
} else {
// It's hidden
popover.options.content = html;
$el.popover("show");
}
};
ui.updateFieldStatus = function (options, $el, cssClass) {
var targetClass = options.ui.bootstrap2 ? ".control-group" : ".form-group",
$container = $el.parents(targetClass).first();
$.each(statusClasses, function (idx, css) {
if (!options.ui.bootstrap2) { css = "has-" + css; }
$container.removeClass(css);
});
cssClass = statusClasses[cssClass];
if (!options.ui.bootstrap2) { cssClass = "has-" + cssClass; }
$container.addClass(cssClass);
};
ui.percentage = function (score, maximun) {
var result = Math.floor(100 * score / maximun);
result = result < 0 ? 1 : result; // Don't show the progress bar empty
result = result > 100 ? 100 : result;
return result;
};
ui.getVerdictAndCssClass = function (options, score) {
var cssClass, verdictText, level;
if (score <= 0) {
cssClass = 0;
level = -1;
verdictText = options.ui.verdicts[0];
} else if (score < options.ui.scores[0]) {
cssClass = 0;
level = 0;
verdictText = options.ui.verdicts[0];
} else if (score < options.ui.scores[1]) {
cssClass = 1;
level = 1;
verdictText = options.ui.verdicts[1];
} else if (score < options.ui.scores[2]) {
cssClass = 1;
level = 2;
verdictText = options.ui.verdicts[2];
} else if (score < options.ui.scores[3]) {
cssClass = 2;
level = 3;
verdictText = options.ui.verdicts[3];
} else {
cssClass = 2;
level = 4;
verdictText = options.ui.verdicts[4];
}
return [verdictText, cssClass, level];
};
ui.updateUI = function (options, $el, score) {
var cssClass, barPercentage, verdictText, verdictCssClass;
cssClass = ui.getVerdictAndCssClass(options, score);
verdictText = score === 0 ? '' : cssClass[0];
cssClass = cssClass[1];
verdictCssClass = options.ui.useVerdictCssClass ? cssClass : -1;
if (options.ui.showProgressBar) {
barPercentage = ui.percentage(score, options.ui.scores[3]);
ui.updateProgressBar(options, $el, cssClass, barPercentage);
if (options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
}
if (options.ui.showStatus) {
ui.updateFieldStatus(options, $el, cssClass);
}
if (options.ui.showPopover) {
ui.updatePopover(options, $el, verdictText);
} else {
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
if (options.ui.showErrors) {
ui.updateErrors(options, $el);
}
}
};
}(jQuery, ui));
// Source: src/methods.js
var methods = {};
(function ($, methods) {
"use strict";
var onKeyUp, applyToAll;
onKeyUp = function (event) {
var $el = $(event.target),
options = $el.data("pwstrength-bootstrap"),
word = $el.val(),
userInputs,
verdictText,
verdictLevel,
score;
if (options === undefined) { return; }
options.instances.errors = [];
if (word.length === 0) {
score = 0;
} else {
if (options.common.zxcvbn) {
userInputs = [];
$.each(options.common.userInputs.concat([options.common.usernameField]), function (idx, selector) {
var value = $(selector).val();
if (value) { userInputs.push(value); }
});
userInputs = userInputs.concat(options.common.zxcvbnTerms);
score = zxcvbn(word, userInputs).entropy;
} else {
score = rulesEngine.executeRules(options, word);
}
}
ui.updateUI(options, $el, score);
verdictText = ui.getVerdictAndCssClass(options, score);
verdictLevel = verdictText[2];
verdictText = verdictText[0];
if (options.common.debug) { console.log(score + ' - ' + verdictText); }
if ($.isFunction(options.common.onKeyUp)) {
options.common.onKeyUp(event, {
score: score,
verdictText: verdictText,
verdictLevel: verdictLevel
});
}
};
methods.init = function (settings) {
this.each(function (idx, el) {
// Make it deep extend (first param) so it extends too the
// rules and other inside objects
var clonedDefaults = $.extend(true, {}, defaultOptions),
localOptions = $.extend(true, clonedDefaults, settings),
$el = $(el);
localOptions.instances = {};
$el.data("pwstrength-bootstrap", localOptions);
$el.on("keyup", onKeyUp);
$el.on("change", onKeyUp);
$el.on("onpaste", onKeyUp);
ui.initUI(localOptions, $el);
if ($.trim($el.val())) { // Not empty, calculate the strength
$el.trigger("keyup");
}
if ($.isFunction(localOptions.common.onLoad)) {
localOptions.common.onLoad();
}
});
return this;
};
methods.destroy = function () {
this.each(function (idx, el) {
var $el = $(el),
options = $el.data("pwstrength-bootstrap"),
elements = ui.getUIElements(options, $el);
elements.$progressbar.remove();
elements.$verdict.remove();
elements.$errors.remove();
$el.removeData("pwstrength-bootstrap");
});
};
methods.forceUpdate = function () {
this.each(function (idx, el) {
var event = { target: el };
onKeyUp(event);
});
};
methods.addRule = function (name, method, score, active) {
this.each(function (idx, el) {
var options = $(el).data("pwstrength-bootstrap");
options.rules.activated[name] = active;
options.rules.scores[name] = score;
options.rules.extra[name] = method;
});
};
applyToAll = function (rule, prop, value) {
this.each(function (idx, el) {
$(el).data("pwstrength-bootstrap").rules[prop][rule] = value;
});
};
methods.changeScore = function (rule, score) {
applyToAll.call(this, rule, "scores", score);
};
methods.ruleActive = function (rule, active) {
applyToAll.call(this, rule, "activated", active);
};
$.fn.pwstrength = function (method) {
var result;
if (methods[method]) {
result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
result = methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jQuery.pwstrength-bootstrap");
}
return result;
};
}(jQuery, methods));
}(jQuery));
').addClass('cw').text('#'));
}
while (currentDate.isBefore(viewDate.clone().endOf('w'))) {
row.append($(' ').addClass('dow').text(currentDate.format('dd')));
currentDate.add(1, 'd');
}
widget.find('.datepicker-days thead').append(row);
},
isInDisabledDates = function (testDate) {
return options.disabledDates[testDate.format('YYYY-MM-DD')] === true;
},
isInEnabledDates = function (testDate) {
return options.enabledDates[testDate.format('YYYY-MM-DD')] === true;
},
isInDisabledHours = function (testDate) {
return options.disabledHours[testDate.format('H')] === true;
},
isInEnabledHours = function (testDate) {
return options.enabledHours[testDate.format('H')] === true;
},
isValid = function (targetMoment, granularity) {
if (!targetMoment.isValid()) {
return false;
}
if (options.disabledDates && granularity === 'd' && isInDisabledDates(targetMoment)) {
return false;
}
if (options.enabledDates && granularity === 'd' && !isInEnabledDates(targetMoment)) {
return false;
}
if (options.minDate && targetMoment.isBefore(options.minDate, granularity)) {
return false;
}
if (options.maxDate && targetMoment.isAfter(options.maxDate, granularity)) {
return false;
}
if (options.daysOfWeekDisabled && granularity === 'd' && options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) {
return false;
}
if (options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && isInDisabledHours(targetMoment)) {
return false;
}
if (options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !isInEnabledHours(targetMoment)) {
return false;
}
if (options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) {
var found = false;
$.each(options.disabledTimeIntervals, function () {
if (targetMoment.isBetween(this[0], this[1])) {
found = true;
return false;
}
});
if (found) {
return false;
}
}
return true;
},
fillMonths = function () {
var spans = [],
monthsShort = viewDate.clone().startOf('y').startOf('d');
while (monthsShort.isSame(viewDate, 'y')) {
spans.push($('').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM')));
monthsShort.add(1, 'M');
}
widget.find('.datepicker-months td').empty().append(spans);
},
updateMonths = function () {
var monthsView = widget.find('.datepicker-months'),
monthsViewHeader = monthsView.find('th'),
months = monthsView.find('tbody').find('span');
monthsViewHeader.eq(0).find('span').attr('title', options.tooltips.prevYear);
monthsViewHeader.eq(1).attr('title', options.tooltips.selectYear);
monthsViewHeader.eq(2).find('span').attr('title', options.tooltips.nextYear);
monthsView.find('.disabled').removeClass('disabled');
if (!isValid(viewDate.clone().subtract(1, 'y'), 'y')) {
monthsViewHeader.eq(0).addClass('disabled');
}
monthsViewHeader.eq(1).text(viewDate.year());
if (!isValid(viewDate.clone().add(1, 'y'), 'y')) {
monthsViewHeader.eq(2).addClass('disabled');
}
months.removeClass('active');
if (date.isSame(viewDate, 'y') && !unset) {
months.eq(date.month()).addClass('active');
}
months.each(function (index) {
if (!isValid(viewDate.clone().month(index), 'M')) {
$(this).addClass('disabled');
}
});
},
updateYears = function () {
var yearsView = widget.find('.datepicker-years'),
yearsViewHeader = yearsView.find('th'),
startYear = viewDate.clone().subtract(5, 'y'),
endYear = viewDate.clone().add(6, 'y'),
html = '';
yearsViewHeader.eq(0).find('span').attr('title', options.tooltips.prevDecade);
yearsViewHeader.eq(1).attr('title', options.tooltips.selectDecade);
yearsViewHeader.eq(2).find('span').attr('title', options.tooltips.nextDecade);
yearsView.find('.disabled').removeClass('disabled');
if (options.minDate && options.minDate.isAfter(startYear, 'y')) {
yearsViewHeader.eq(0).addClass('disabled');
}
yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year());
if (options.maxDate && options.maxDate.isBefore(endYear, 'y')) {
yearsViewHeader.eq(2).addClass('disabled');
}
while (!startYear.isAfter(endYear, 'y')) {
html += '' + startYear.year() + ' ';
startYear.add(1, 'y');
}
yearsView.find('td').html(html);
},
updateDecades = function () {
var decadesView = widget.find('.datepicker-decades'),
decadesViewHeader = decadesView.find('th'),
startDecade = moment({ y: viewDate.year() - (viewDate.year() % 100) - 1 }),
endDecade = startDecade.clone().add(100, 'y'),
startedAt = startDecade.clone(),
html = '';
decadesViewHeader.eq(0).find('span').attr('title', options.tooltips.prevCentury);
decadesViewHeader.eq(2).find('span').attr('title', options.tooltips.nextCentury);
decadesView.find('.disabled').removeClass('disabled');
if (startDecade.isSame(moment({ y: 1900 })) || (options.minDate && options.minDate.isAfter(startDecade, 'y'))) {
decadesViewHeader.eq(0).addClass('disabled');
}
decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year());
if (startDecade.isSame(moment({ y: 2000 })) || (options.maxDate && options.maxDate.isBefore(endDecade, 'y'))) {
decadesViewHeader.eq(2).addClass('disabled');
}
while (!startDecade.isAfter(endDecade, 'y')) {
html += '' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + ' ';
startDecade.add(12, 'y');
}
html += ' '; //push the dangling block over, at least this way it's even
decadesView.find('td').html(html);
decadesViewHeader.eq(1).text((startedAt.year() + 1) + '-' + (startDecade.year()));
},
fillDate = function () {
var daysView = widget.find('.datepicker-days'),
daysViewHeader = daysView.find('th'),
currentDate,
html = [],
row,
clsName,
i;
if (!hasDate()) {
return;
}
daysViewHeader.eq(0).find('span').attr('title', options.tooltips.prevMonth);
daysViewHeader.eq(1).attr('title', options.tooltips.selectMonth);
daysViewHeader.eq(2).find('span').attr('title', options.tooltips.nextMonth);
daysView.find('.disabled').removeClass('disabled');
daysViewHeader.eq(1).text(viewDate.format(options.dayViewHeaderFormat));
if (!isValid(viewDate.clone().subtract(1, 'M'), 'M')) {
daysViewHeader.eq(0).addClass('disabled');
}
if (!isValid(viewDate.clone().add(1, 'M'), 'M')) {
daysViewHeader.eq(2).addClass('disabled');
}
currentDate = viewDate.clone().startOf('M').startOf('w').startOf('d');
for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks)
if (currentDate.weekday() === 0) {
row = $(' ' + currentDate.week() + ' ' + currentDate.date() + ' ' + currentHour.format(use24Hours ? 'HH' : 'hh') + ' ' + currentMinute.format('mm') + ' ' + currentSecond.format('ss') + '