/*! jQuery Validation Plugin - v1.14.0 - 6/30/2015
 * http://jqueryvalidation.org/
 * Copyright (c) 2015 Jörn Zaefferer; Licensed MIT */
!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a(jQuery) }(function (a) { a.extend(a.fn, { validate: function (b) { if (!this.length) return void (b && b.debug && window.console && console.warn("Nothing selected, can't validate, returning nothing.")); var c = a.data(this[0], "validator"); return c ? c : (this.attr("novalidate", "novalidate"), c = new a.validator(b, this[0]), a.data(this[0], "validator", c), c.settings.onsubmit && (this.on("click.validate", ":submit", function (b) { c.settings.submitHandler && (c.submitButton = b.target), a(this).hasClass("cancel") && (c.cancelSubmit = !0), void 0 !== a(this).attr("formnovalidate") && (c.cancelSubmit = !0) }), this.on("submit.validate", function (b) { function d() { var d, e; return c.settings.submitHandler ? (c.submitButton && (d = a("<input type='hidden'/>").attr("name", c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)), e = c.settings.submitHandler.call(c, c.currentForm, b), c.submitButton && d.remove(), void 0 !== e ? e : !1) : !0 } return c.settings.debug && b.preventDefault(), c.cancelSubmit ? (c.cancelSubmit = !1, d()) : c.form() ? c.pendingRequest ? (c.formSubmitted = !0, !1) : d() : (c.focusInvalid(), !1) })), c) }, valid: function () { var b, c, d; return a(this[0]).is("form") ? b = this.validate().form() : (d = [], b = !0, c = a(this[0].form).validate(), this.each(function () { b = c.element(this) && b, d = d.concat(c.errorList) }), c.errorList = d), b }, rules: function (b, c) { var d, e, f, g, h, i, j = this[0]; if (b) switch (d = a.data(j.form, "validator").settings, e = d.rules, f = a.validator.staticRules(j), b) { case "add": a.extend(f, a.validator.normalizeRule(c)), delete f.messages, e[j.name] = f, c.messages && (d.messages[j.name] = a.extend(d.messages[j.name], c.messages)); break; case "remove": return c ? (i = {}, a.each(c.split(/\s/), function (b, c) { i[c] = f[c], delete f[c], "required" === c && a(j).removeAttr("aria-required") }), i) : (delete e[j.name], f) } return g = a.validator.normalizeRules(a.extend({}, a.validator.classRules(j), a.validator.attributeRules(j), a.validator.dataRules(j), a.validator.staticRules(j)), j), g.required && (h = g.required, delete g.required, g = a.extend({ required: h }, g), a(j).attr("aria-required", "true")), g.remote && (h = g.remote, delete g.remote, g = a.extend(g, { remote: h })), g } }), a.extend(a.expr[":"], { blank: function (b) { return !a.trim("" + a(b).val()) }, filled: function (b) { return !!a.trim("" + a(b).val()) }, unchecked: function (b) { return !a(b).prop("checked") } }), a.validator = function (b, c) { this.settings = a.extend(!0, {}, a.validator.defaults, b), this.currentForm = c, this.init() }, a.validator.format = function (b, c) { return 1 === arguments.length ? function () { var c = a.makeArray(arguments); return c.unshift(b), a.validator.format.apply(this, c) } : (arguments.length > 2 && c.constructor !== Array && (c = a.makeArray(arguments).slice(1)), c.constructor !== Array && (c = [c]), a.each(c, function (a, c) { b = b.replace(new RegExp("\\{" + a + "\\}", "g"), function () { return c }) }), b) }, a.extend(a.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", validClass: "valid", errorElement: "label", focusCleanup: !1, focusInvalid: !0, errorContainer: a([]), errorLabelContainer: a([]), onsubmit: !0, ignore: ":hidden", ignoreTitle: !1, onfocusin: function (a) { this.lastActive = a, this.settings.focusCleanup && (this.settings.unhighlight && this.settings.unhighlight.call(this, a, this.settings.errorClass, this.settings.validClass), this.hideThese(this.errorsFor(a))) }, onfocusout: function (a) { this.checkable(a) || !(a.name in this.submitted) && this.optional(a) || this.element(a) }, onkeyup: function (b, c) { var d = [16, 17, 18, 20, 35, 36, 37, 38, 39, 40, 45, 144, 225]; 9 === c.which && "" === this.elementValue(b) || -1 !== a.inArray(c.keyCode, d) || (b.name in this.submitted || b === this.lastElement) && this.element(b) }, onclick: function (a) { a.name in this.submitted ? this.element(a) : a.parentNode.name in this.submitted && this.element(a.parentNode) }, highlight: function (b, c, d) { "radio" === b.type ? this.findByName(b.name).addClass(c).removeClass(d) : a(b).addClass(c).removeClass(d) }, unhighlight: function (b, c, d) { "radio" === b.type ? this.findByName(b.name).removeClass(c).addClass(d) : a(b).removeClass(c).addClass(d) } }, setDefaults: function (b) { a.extend(a.validator.defaults, b) }, messages: { required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date ( ISO ).", number: "Please enter a valid number.", digits: "Please enter only digits.", creditcard: "Please enter a valid credit card number.", equalTo: "Please enter the same value again.", maxlength: a.validator.format("Please enter no more than {0} characters."), minlength: a.validator.format("Please enter at least {0} characters."), rangelength: a.validator.format("Please enter a value between {0} and {1} characters long."), range: a.validator.format("Please enter a value between {0} and {1}."), max: a.validator.format("Please enter a value less than or equal to {0}."), min: a.validator.format("Please enter a value greater than or equal to {0}.") }, autoCreateRanges: !1, prototype: { init: function () { function b(b) { var c = a.data(this.form, "validator"), d = "on" + b.type.replace(/^validate/, ""), e = c.settings; e[d] && !a(this).is(e.ignore) && e[d].call(c, this, b) } this.labelContainer = a(this.settings.errorLabelContainer), this.errorContext = this.labelContainer.length && this.labelContainer || a(this.currentForm), this.containers = a(this.settings.errorContainer).add(this.settings.errorLabelContainer), this.submitted = {}, this.valueCache = {}, this.pendingRequest = 0, this.pending = {}, this.invalid = {}, this.reset(); var c, d = this.groups = {}; a.each(this.settings.groups, function (b, c) { "string" == typeof c && (c = c.split(/\s/)), a.each(c, function (a, c) { d[c] = b }) }), c = this.settings.rules, a.each(c, function (b, d) { c[b] = a.validator.normalizeRule(d) }), a(this.currentForm).on("focusin.validate focusout.validate keyup.validate", ":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox']", b).on("click.validate", "select, option, [type='radio'], [type='checkbox']", b), this.settings.invalidHandler && a(this.currentForm).on("invalid-form.validate", this.settings.invalidHandler), a(this.currentForm).find("[required], [data-rule-required], .required").attr("aria-required", "true") }, form: function () { return this.checkForm(), a.extend(this.submitted, this.errorMap), this.invalid = a.extend({}, this.errorMap), this.valid() || a(this.currentForm).triggerHandler("invalid-form", [this]), this.showErrors(), this.valid() }, checkForm: function () { this.prepareForm(); for (var a = 0, b = this.currentElements = this.elements() ; b[a]; a++) this.check(b[a]); return this.valid() }, element: function (b) { var c = this.clean(b), d = this.validationTargetFor(c), e = !0; return this.lastElement = d, void 0 === d ? delete this.invalid[c.name] : (this.prepareElement(d), this.currentElements = a(d), e = this.check(d) !== !1, e ? delete this.invalid[d.name] : this.invalid[d.name] = !0), a(b).attr("aria-invalid", !e), this.numberOfInvalids() || (this.toHide = this.toHide.add(this.containers)), this.showErrors(), e }, showErrors: function (b) { if (b) { a.extend(this.errorMap, b), this.errorList = []; for (var c in b) this.errorList.push({ message: b[c], element: this.findByName(c)[0] }); this.successList = a.grep(this.successList, function (a) { return !(a.name in b) }) } this.settings.showErrors ? this.settings.showErrors.call(this, this.errorMap, this.errorList) : this.defaultShowErrors() }, resetForm: function () { a.fn.resetForm && a(this.currentForm).resetForm(), this.submitted = {}, this.lastElement = null, this.prepareForm(), this.hideErrors(); var b, c = this.elements().removeData("previousValue").removeAttr("aria-invalid"); if (this.settings.unhighlight) for (b = 0; c[b]; b++) this.settings.unhighlight.call(this, c[b], this.settings.errorClass, ""); else c.removeClass(this.settings.errorClass) }, numberOfInvalids: function () { return this.objectLength(this.invalid) }, objectLength: function (a) { var b, c = 0; for (b in a) c++; return c }, hideErrors: function () { this.hideThese(this.toHide) }, hideThese: function (a) { a.not(this.containers).text(""), this.addWrapper(a).hide() }, valid: function () { return 0 === this.size() }, size: function () { return this.errorList.length }, focusInvalid: function () { if (this.settings.focusInvalid) try { a(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus().trigger("focusin") } catch (b) { } }, findLastActive: function () { var b = this.lastActive; return b && 1 === a.grep(this.errorList, function (a) { return a.element.name === b.name }).length && b }, elements: function () { var b = this, c = {}; return a(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function () { return !this.name && b.settings.debug && window.console && console.error("%o has no name assigned", this), this.name in c || !b.objectLength(a(this).rules()) ? !1 : (c[this.name] = !0, !0) }) }, clean: function (b) { return a(b)[0] }, errors: function () { var b = this.settings.errorClass.split(" ").join("."); return a(this.settings.errorElement + "." + b, this.errorContext) }, reset: function () { this.successList = [], this.errorList = [], this.errorMap = {}, this.toShow = a([]), this.toHide = a([]), this.currentElements = a([]) }, prepareForm: function () { this.reset(), this.toHide = this.errors().add(this.containers) }, prepareElement: function (a) { this.reset(), this.toHide = this.errorsFor(a) }, elementValue: function (b) { var c, d = a(b), e = b.type; return "radio" === e || "checkbox" === e ? this.findByName(b.name).filter(":checked").val() : "number" === e && "undefined" != typeof b.validity ? b.validity.badInput ? !1 : d.val() : (c = d.val(), "string" == typeof c ? c.replace(/\r/g, "") : c) }, check: function (b) { b = this.validationTargetFor(this.clean(b)); var c, d, e, f = a(b).rules(), g = a.map(f, function (a, b) { return b }).length, h = !1, i = this.elementValue(b); for (d in f) { e = { method: d, parameters: f[d] }; try { if (c = a.validator.methods[d].call(this, i, b, e.parameters), "dependency-mismatch" === c && 1 === g) { h = !0; continue } if (h = !1, "pending" === c) return void (this.toHide = this.toHide.not(this.errorsFor(b))); if (!c) return this.formatAndAdd(b, e), !1 } catch (j) { throw this.settings.debug && window.console && console.log("Exception occurred when checking element " + b.id + ", check the '" + e.method + "' method.", j), j instanceof TypeError && (j.message += ".  Exception occurred when checking element " + b.id + ", check the '" + e.method + "' method."), j } } if (!h) return this.objectLength(f) && this.successList.push(b), !0 }, customDataMessage: function (b, c) { return a(b).data("msg" + c.charAt(0).toUpperCase() + c.substring(1).toLowerCase()) || a(b).data("msg") }, customMessage: function (a, b) { var c = this.settings.messages[a]; return c && (c.constructor === String ? c : c[b]) }, findDefined: function () { for (var a = 0; a < arguments.length; a++) if (void 0 !== arguments[a]) return arguments[a]; return void 0 }, defaultMessage: function (b, c) { return this.findDefined(this.customMessage(b.name, c), this.customDataMessage(b, c), !this.settings.ignoreTitle && b.title || void 0, a.validator.messages[c], "<strong>Warning: No message defined for " + b.name + "</strong>") }, formatAndAdd: function (b, c) { var d = this.defaultMessage(b, c.method), e = /\$?\{(\d+)\}/g; "function" == typeof d ? d = d.call(this, c.parameters, b) : e.test(d) && (d = a.validator.format(d.replace(e, "{$1}"), c.parameters)), this.errorList.push({ message: d, element: b, method: c.method }), this.errorMap[b.name] = d, this.submitted[b.name] = d }, addWrapper: function (a) { return this.settings.wrapper && (a = a.add(a.parent(this.settings.wrapper))), a }, defaultShowErrors: function () { var a, b, c; for (a = 0; this.errorList[a]; a++) c = this.errorList[a], this.settings.highlight && this.settings.highlight.call(this, c.element, this.settings.errorClass, this.settings.validClass), this.showLabel(c.element, c.message); if (this.errorList.length && (this.toShow = this.toShow.add(this.containers)), this.settings.success) for (a = 0; this.successList[a]; a++) this.showLabel(this.successList[a]); if (this.settings.unhighlight) for (a = 0, b = this.validElements() ; b[a]; a++) this.settings.unhighlight.call(this, b[a], this.settings.errorClass, this.settings.validClass); this.toHide = this.toHide.not(this.toShow), this.hideErrors(), this.addWrapper(this.toShow).show() }, validElements: function () { return this.currentElements.not(this.invalidElements()) }, invalidElements: function () { return a(this.errorList).map(function () { return this.element }) }, showLabel: function (b, c) { var d, e, f, g = this.errorsFor(b), h = this.idOrName(b), i = a(b).attr("aria-describedby"); g.length ? (g.removeClass(this.settings.validClass).addClass(this.settings.errorClass), g.html(c)) : (g = a("<" + this.settings.errorElement + ">").attr("id", h + "-error").addClass(this.settings.errorClass).html(c || ""), d = g, this.settings.wrapper && (d = g.hide().show().wrap("<" + this.settings.wrapper + "/>").parent()), this.labelContainer.length ? this.labelContainer.append(d) : this.settings.errorPlacement ? this.settings.errorPlacement(d, a(b)) : d.insertAfter(b), g.is("label") ? g.attr("for", h) : 0 === g.parents("label[for='" + h + "']").length && (f = g.attr("id").replace(/(:|\.|\[|\]|\$)/g, "\\$1"), i ? i.match(new RegExp("\\b" + f + "\\b")) || (i += " " + f) : i = f, a(b).attr("aria-describedby", i), e = this.groups[b.name], e && a.each(this.groups, function (b, c) { c === e && a("[name='" + b + "']", this.currentForm).attr("aria-describedby", g.attr("id")) }))), !c && this.settings.success && (g.text(""), "string" == typeof this.settings.success ? g.addClass(this.settings.success) : this.settings.success(g, b)), this.toShow = this.toShow.add(g) }, errorsFor: function (b) { var c = this.idOrName(b), d = a(b).attr("aria-describedby"), e = "label[for='" + c + "'], label[for='" + c + "'] *"; return d && (e = e + ", #" + d.replace(/\s+/g, ", #")), this.errors().filter(e) }, idOrName: function (a) { return this.groups[a.name] || (this.checkable(a) ? a.name : a.id || a.name) }, validationTargetFor: function (b) { return this.checkable(b) && (b = this.findByName(b.name)), a(b).not(this.settings.ignore)[0] }, checkable: function (a) { return /radio|checkbox/i.test(a.type) }, findByName: function (b) { return a(this.currentForm).find("[name='" + b + "']") }, getLength: function (b, c) { switch (c.nodeName.toLowerCase()) { case "select": return a("option:selected", c).length; case "input": if (this.checkable(c)) return this.findByName(c.name).filter(":checked").length } return b.length }, depend: function (a, b) { return this.dependTypes[typeof a] ? this.dependTypes[typeof a](a, b) : !0 }, dependTypes: { "boolean": function (a) { return a }, string: function (b, c) { return !!a(b, c.form).length }, "function": function (a, b) { return a(b) } }, optional: function (b) { var c = this.elementValue(b); return !a.validator.methods.required.call(this, c, b) && "dependency-mismatch" }, startRequest: function (a) { this.pending[a.name] || (this.pendingRequest++, this.pending[a.name] = !0) }, stopRequest: function (b, c) { this.pendingRequest--, this.pendingRequest < 0 && (this.pendingRequest = 0), delete this.pending[b.name], c && 0 === this.pendingRequest && this.formSubmitted && this.form() ? (a(this.currentForm).submit(), this.formSubmitted = !1) : !c && 0 === this.pendingRequest && this.formSubmitted && (a(this.currentForm).triggerHandler("invalid-form", [this]), this.formSubmitted = !1) }, previousValue: function (b) { return a.data(b, "previousValue") || a.data(b, "previousValue", { old: null, valid: !0, message: this.defaultMessage(b, "remote") }) }, destroy: function () { this.resetForm(), a(this.currentForm).off(".validate").removeData("validator") } }, classRuleSettings: { required: { required: !0 }, email: { email: !0 }, url: { url: !0 }, date: { date: !0 }, dateISO: { dateISO: !0 }, number: { number: !0 }, digits: { digits: !0 }, creditcard: { creditcard: !0 } }, addClassRules: function (b, c) { b.constructor === String ? this.classRuleSettings[b] = c : a.extend(this.classRuleSettings, b) }, classRules: function (b) { var c = {}, d = a(b).attr("class"); return d && a.each(d.split(" "), function () { this in a.validator.classRuleSettings && a.extend(c, a.validator.classRuleSettings[this]) }), c }, normalizeAttributeRule: function (a, b, c, d) { /min|max/.test(c) && (null === b || /number|range|text/.test(b)) && (d = Number(d), isNaN(d) && (d = void 0)), d || 0 === d ? a[c] = d : b === c && "range" !== b && (a[c] = !0) }, attributeRules: function (b) { var c, d, e = {}, f = a(b), g = b.getAttribute("type"); for (c in a.validator.methods) "required" === c ? (d = b.getAttribute(c), "" === d && (d = !0), d = !!d) : d = f.attr(c), this.normalizeAttributeRule(e, g, c, d); return e.maxlength && /-1|2147483647|524288/.test(e.maxlength) && delete e.maxlength, e }, dataRules: function (b) { var c, d, e = {}, f = a(b), g = b.getAttribute("type"); for (c in a.validator.methods) d = f.data("rule" + c.charAt(0).toUpperCase() + c.substring(1).toLowerCase()), this.normalizeAttributeRule(e, g, c, d); return e }, staticRules: function (b) { var c = {}, d = a.data(b.form, "validator"); return d.settings.rules && (c = a.validator.normalizeRule(d.settings.rules[b.name]) || {}), c }, normalizeRules: function (b, c) { return a.each(b, function (d, e) { if (e === !1) return void delete b[d]; if (e.param || e.depends) { var f = !0; switch (typeof e.depends) { case "string": f = !!a(e.depends, c.form).length; break; case "function": f = e.depends.call(c, c) } f ? b[d] = void 0 !== e.param ? e.param : !0 : delete b[d] } }), a.each(b, function (d, e) { b[d] = a.isFunction(e) ? e(c) : e }), a.each(["minlength", "maxlength"], function () { b[this] && (b[this] = Number(b[this])) }), a.each(["rangelength", "range"], function () { var c; b[this] && (a.isArray(b[this]) ? b[this] = [Number(b[this][0]), Number(b[this][1])] : "string" == typeof b[this] && (c = b[this].replace(/[\[\]]/g, "").split(/[\s,]+/), b[this] = [Number(c[0]), Number(c[1])])) }), a.validator.autoCreateRanges && (null != b.min && null != b.max && (b.range = [b.min, b.max], delete b.min, delete b.max), null != b.minlength && null != b.maxlength && (b.rangelength = [b.minlength, b.maxlength], delete b.minlength, delete b.maxlength)), b }, normalizeRule: function (b) { if ("string" == typeof b) { var c = {}; a.each(b.split(/\s/), function () { c[this] = !0 }), b = c } return b }, addMethod: function (b, c, d) { a.validator.methods[b] = c, a.validator.messages[b] = void 0 !== d ? d : a.validator.messages[b], c.length < 3 && a.validator.addClassRules(b, a.validator.normalizeRule(b)) }, methods: { required: function (b, c, d) { if (!this.depend(d, c)) return "dependency-mismatch"; if ("select" === c.nodeName.toLowerCase()) { var e = a(c).val(); return e && e.length > 0 } return this.checkable(c) ? this.getLength(b, c) > 0 : b.length > 0 }, email: function (a, b) { return this.optional(b) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a) }, url: function (a, b) { return this.optional(b) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(a) }, date: function (a, b) { return this.optional(b) || !/Invalid|NaN/.test(new Date(a).toString()) }, dateISO: function (a, b) { return this.optional(b) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a) }, number: function (a, b) { return this.optional(b) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a) }, digits: function (a, b) { return this.optional(b) || /^\d+$/.test(a) }, creditcard: function (a, b) { if (this.optional(b)) return "dependency-mismatch"; if (/[^0-9 \-]+/.test(a)) return !1; var c, d, e = 0, f = 0, g = !1; if (a = a.replace(/\D/g, ""), a.length < 13 || a.length > 19) return !1; for (c = a.length - 1; c >= 0; c--) d = a.charAt(c), f = parseInt(d, 10), g && (f *= 2) > 9 && (f -= 9), e += f, g = !g; return e % 10 === 0 }, minlength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(b, c); return this.optional(c) || e >= d }, maxlength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(b, c); return this.optional(c) || d >= e }, rangelength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(b, c); return this.optional(c) || e >= d[0] && e <= d[1] }, min: function (a, b, c) { return this.optional(b) || a >= c }, max: function (a, b, c) { return this.optional(b) || c >= a }, range: function (a, b, c) { return this.optional(b) || a >= c[0] && a <= c[1] }, equalTo: function (b, c, d) { var e = a(d); return this.settings.onfocusout && e.off(".validate-equalTo").on("blur.validate-equalTo", function () { a(c).valid() }), b === e.val() }, remote: function (b, c, d) { if (this.optional(c)) return "dependency-mismatch"; var e, f, g = this.previousValue(c); return this.settings.messages[c.name] || (this.settings.messages[c.name] = {}), g.originalMessage = this.settings.messages[c.name].remote, this.settings.messages[c.name].remote = g.message, d = "string" == typeof d && { url: d } || d, g.old === b ? g.valid : (g.old = b, e = this, this.startRequest(c), f = {}, f[c.name] = b, a.ajax(a.extend(!0, { mode: "abort", port: "validate" + c.name, dataType: "json", data: f, context: e.currentForm, success: function (d) { var f, h, i, j = d === !0 || "true" === d; e.settings.messages[c.name].remote = g.originalMessage, j ? (i = e.formSubmitted, e.prepareElement(c), e.formSubmitted = i, e.successList.push(c), delete e.invalid[c.name], e.showErrors()) : (f = {}, h = d || e.defaultMessage(c, "remote"), f[c.name] = g.message = a.isFunction(h) ? h(b) : h, e.invalid[c.name] = !0, e.showErrors(f)), g.valid = j, e.stopRequest(c, j) } }, d)), "pending") } } }); var b, c = {}; a.ajaxPrefilter ? a.ajaxPrefilter(function (a, b, d) { var e = a.port; "abort" === a.mode && (c[e] && c[e].abort(), c[e] = d) }) : (b = a.ajax, a.ajax = function (d) { var e = ("mode" in d ? d : a.ajaxSettings).mode, f = ("port" in d ? d : a.ajaxSettings).port; return "abort" === e ? (c[f] && c[f].abort(), c[f] = b.apply(this, arguments), c[f]) : b.apply(this, arguments) }) });

/*

This file contains external jQuery plugins. Ie plugins that are not written by Medialab and are not subject to minification.

*/

/*jshint curly: true, eqeqeq: true, noempty: true, strict: true, undef: true, browser: true */
/*global jQuery: false */
;(function($, undefined) {
'use strict';

// Taken from http://www.bennadel.com/blog/1563-jQuery-Comments-Plug-in-To-Access-HTML-Comments-For-DOM-Templating.htm
// Selects all the comment nodes, code edited.
jQuery.fn.comments = function (blnDeep) {
   var blnDeep = (blnDeep || false);
   var jComments = $([]);

   // Loop over each node to search its children for
   // comment nodes and element nodes (if deep search).
   this.each(
   function (intI, objNode) {
      var objChildNode = objNode.firstChild;
      var strParentID = $(this).attr("id");

      // Keep looping over the top-level children
      // while we have a node to examine.
      while (objChildNode) {

         // Check to see if this node is a comment.
         if (objChildNode.nodeType === 8) {
            // found a comment.
            jComments.add($(objChildNode))

         } else if (blnDeep && (objChildNode.nodeType === 1)) {
            jComments.concat(objChildNode.comments(true));
         }
         // Move to the next sibling.
         objChildNode = objChildNode.nextSibling;
      }
   }
   );

   return (jComments);
}
})(jQuery);

(function ($) {
   
   $.fn.eachReverse = function(f) {
      if (!this.size() || !f || typeof f !== "function") {
         return this;
      }
      for(var i = this.size() - 1; i >= 0; i--) {
         if (f.apply(this[i], [i, this[i]]) === false) {
            break;
         }
      }

      return this;
   };

})(jQuery);

// MJ: a simple plugin to stop the wheel event perculating from say popups preventing stuff underneath scrolling
(function ($) {

   $.fn.stopMouseWheel = function() {
      
      if (!this.size()) {
         return;
      }

      this.unbind(".stopMouseWheel");
      this.bind("DOMMouseScroll.stopMouseWheel mousewheel.stopMouseWheel", function (e) {
         // if no scrollbar, just continue
         if (this.scrollHeight <= this.clientHeight) {
            return;
         }

         e.preventDefault();

         var scrollTo;
         if (e.type == 'mousewheel') {
            scrollTo = (e.originalEvent.wheelDelta * -1);
         }
         else if (e.type == 'DOMMouseScroll') {
            scrollTo = 40 * e.originalEvent.detail;
         }

         $el = $(this);
         $el.scrollTop(scrollTo + $el.scrollTop());
      });
   };

})(jQuery);

//WH check this for URI: https://github.com/allmarkedup/jQuery-URL-Parser

/*
 * An URI datatype.  Based upon examples in RFC3986.
 *
 * TODO %-escaping
 * TODO split apart authority
 * TODO split apart query_string (on demand, anyway)
 *
 * @(#) $Id$
 */

// Constructor for the URI object.  Parse a string into its components.
function URI(strOrObject) {
   var result = [];
   if (!strOrObject) strOrObject = "";
   if (typeof strOrObject == 'string') {
      // Based on the regex in RFC2396 Appendix B.
      var parser = /^(?:([^:\/?\#]+):)?(?:\/\/([^\/?\#]*))?([^?\#]*)(?:\?([^\#]*))?(?:\#(.*))?/;
      result = strOrObject.match(parser);
   }
   else if (typeof strOrObject === 'object') {
      result[1] = strOrObject['scheme'];
      result[2] = strOrObject['authority'];
      result[3] = strOrObject['path'];
      result[4] = strOrObject['query'];
      result[5] = strOrObject['fragment'];
   }   
   this.scheme = result[1] || null;
   this.authority = result[2] || null;
   this.path = result[3] || null;
   this.query = result[4] || null;
   this.fragment = result[5] || null;
}

URI.asURI = function (o) {
   if (!o) { return new URI(''); }
   if (o instanceof URI) {
      return o;
   }
   return new URI(o);
};
   
// Restore the URI to it's stringy glory.
URI.prototype.toString = function (noScheme, noAuthority, noPath, noQuery, noFragment) {
    var str = "";
    if (this.scheme && !noScheme) {
        str += this.scheme + ":";
    }
    if (this.authority && !noAuthority) {
        str += "//" + this.authority;
    }
    if (this.path && !noPath) {
        str += this.path;
    }
    if (this.query && !noQuery) {
        str += "?" + this.query;
    }
    if (this.fragment && !noFragment) {
        str += "#" + this.fragment;
    }
    return str;
};

// Introduce a new scope to define some private helper functions.
(function () {
    // RFC3986 §5.2.3 (Merge Paths)
    function merge(base, rel_path) {
        var dirname = /^(.*)\//;
        if (base.authority && !base.path) {
            return "/" + rel_path;
        }
        else {
            return base.path.match(dirname)[0] + rel_path;
        }
    }

    // Match two path segments, where the second is ".." and the first must
    // not be "..".
    var DoubleDot = /\/((?!\.\.\/)[^\/]*)\/\.\.\//;

    function remove_dot_segments(path) {
        if (!path) return "";
        // Remove any single dots
        var newpath = path.replace(/\/\.\//g, '/');
        // Remove any trailing single dots.
        newpath = newpath.replace(/\/\.$/, '/');
        // Remove any double dots and the path previous.  NB: We can't use
        // the "g", modifier because we are changing the string that we're
        // matching over.
        while (newpath.match(DoubleDot)) {
            newpath = newpath.replace(DoubleDot, '/');
        }
        // Remove any trailing double dots.
        newpath = newpath.replace(/\/([^\/]*)\/\.\.$/, '/');
        // If there are any remaining double dot bits, then they're wrong
        // and must be nuked.  Again, we can't use the g modifier.
        while (newpath.match(/\/\.\.\//)) {
            newpath = newpath.replace(/\/\.\.\//, '/');
        }
        return newpath;
    }

    // RFC3986 §5.2.2. Transform References;
    URI.prototype.resolve = function (base) {
        var target = new URI();
        if (this.scheme) {
            target.scheme    = this.scheme;
            target.authority = this.authority;
            target.path      = remove_dot_segments(this.path);
            target.query     = this.query;
        }
        else {
            if (this.authority) {
                target.authority = this.authority;
                target.path      = remove_dot_segments(this.path);
                target.query     = this.query;
            }
            else {
                // XXX Original spec says "if defined and empty"…;
                if (!this.path) {
                    target.path = base.path;
                    if (this.query) {
                        target.query = this.query;
                    }
                    else {
                        target.query = base.query;
                    }
                }
                else {
                    if (this.path.charAt(0) === '/') {
                        target.path = remove_dot_segments(this.path);
                    } else {
                        target.path = merge(base, this.path);
                        target.path = remove_dot_segments(target.path);
                    }
                    target.query = this.query;
                }
                target.authority = base.authority;
            }
            target.scheme = base.scheme;
        }

        target.fragment = this.fragment;

        return target;
    };
})();

/*********************************************************************************
 * @name: bPopup
 * @author: (c)Bjoern Klinggaard (http://dinbror.dk/bpopup - twitter@bklinggaard)
 * @version: 0.7.0.min
 *********************************************************************************/
(function(b) {
   b.fn.bPopup = function(n, p) {
      function t() {
         k = (e.data("bPopup") || 0) + 1;
         d = "__bPopup" + k;
         l = "auto" !== a.position[1];
         m = "auto" !== a.position[0];
         i = "fixed" === a.positionStyle;
         j = r(c, a.amsl);
         f = l ? a.position[1] : j[1];
         g = m ? a.position[0] : j[0];
         q = s();
         a.modal && b('<div class="bModal ' + d + '"></div>').css({"background-color": a.modalColor,height: "100%",left: 0,opacity: 0,position: "fixed",top: 0,width: "100%","z-index": a.zIndex + k}).each(function() {
            a.appending && b(this).appendTo(a.appendTo)
         }).animate({opacity: a.opacity}, a.fadeSpeed);
         c.data("bPopup", a).data("id", d).css({left: !a.follow[0] && m || i ? g : h.scrollLeft() + g,position: a.positionStyle || "absolute",top: !a.follow[1] && l || i ? f : h.scrollTop() + f,"z-index": a.zIndex + k + 1}).each(function() {
            a.appending && b(this).appendTo(a.appendTo);
            if (null != a.loadUrl)
               switch (a.contentContainer = b(a.contentContainer || c), a.content) {
                  case "iframe":
                     b('<iframe scrolling="no" frameborder="0" role="presentation"></iframe>').attr("src", a.loadUrl).appendTo(a.contentContainer);
                     break;
                  default:
                     a.contentContainer.load(a.loadUrl)
               }
         }).fadeIn(a.fadeSpeed, function() {
               b.isFunction(p) && p.call(c);
               u()
               b.isFunction(a.onOpen) && a.onOpen.call(c);
            })
      }
      function o() {
         a.modal && b(".bModal." + c.data("id")).fadeOut(a.fadeSpeed, function() {
            b(this).remove()
         });
         c.stop().fadeOut(a.fadeSpeed, function() {
            null != a.loadUrl && a.contentContainer.empty()
         });
         e.data("bPopup", 0 < e.data("bPopup") - 1 ? e.data("bPopup") - 1 : null);
         a.scrollBar || b("html").css("overflow", "auto");
         b("." + a.closeClass).die("click." + d);
         b(".bModal." + d).die("click");
         h.unbind("keydown." + d);
         e.unbind("." + d);
         b.isFunction(a.onClose) && setTimeout(function() {
            a.onClose.call(c)
         }, a.fadeSpeed);
         c.data("bPopup", null);
         return !1
      }
      function u() {
         e.data("bPopup", k);
         b("." + a.closeClass).live("click." + d, o);
         a.modalClose && b(".bModal." + d).live("click", o).css("cursor", "pointer");
         (a.follow[0] || a.follow[1]) && e.bind("scroll." + d, function() {
            q && c.stop().animate({left: a.follow[0] && !i ? h.scrollLeft() + g : g,top: a.follow[1] && !i ? h.scrollTop() + f : f}, a.followSpeed)
         }).bind("resize." + d, function() {
               if (q = s())
                  j = r(c, a.amsl), a.follow[0] && (g = m ? g : j[0]), a.follow[1] && (f = l ? f : j[1]), c.stop().each(function() {
                     i ? b(this).css({left: g,top: f}, a.followSpeed) : b(this).animate({left: m ? g : g + h.scrollLeft(),top: l ? f : f + h.scrollTop()}, a.followSpeed)
                  })
            });
         a.escClose && h.bind("keydown." + d, function(a) {
            27 == a.which && o()
         })
      }
      function r(a, b) {
         var c = (e.width() - a.outerWidth(!0)) / 2, d = (e.height() - a.outerHeight(!0)) / 2 - b;
         return [c, 20 > d ? 20 : d]
      }
      function s() {
         return e.height() > c.outerHeight(!0) + 20 && e.width() > c.outerWidth(!0) + 20
      }
      b.isFunction(n) && (p = n, n = null);
      var a = b.extend({}, b.fn.bPopup.defaults, n);
      a.scrollBar || b("html").css("overflow", "hidden");
      var c = this, h = b(document), e = b(window), k, d, q, l, m, i, j, f, g;
      this.close = function() {
         a = c.data("bPopup");
         o()
      };
      return this.each(function() {
         c.data("bPopup") || t()
      })
   };
   b.fn.bPopup.defaults = {amsl: 50,appending: !0,appendTo: "body",closeClass: "bClose",content: "ajax",contentContainer: null,escClose: !0,fadeSpeed: 250,follow: [!0, !0],followSpeed: 500,loadUrl: null,modal: !0,modalClose: !0,modalColor: "#fff",onClose: null,onOpen: null,opacity: 0.7,position: ["auto", "auto"],positionStyle: "absolute",scrollBar: !0,zIndex: 9997}
})(jQuery);

// https://github.com/pathable/truncate
// 
(function ($) {

   // Matches trailing non-space characters.
   var chop = /(\s*\S+|\s)$/;

   // Return a truncated html string.  Delegates to $.fn.truncate.
   $.truncateHtml = function (html, options) {
      return $('<div></div>').append(html).truncateHtml(options).html();
   };

   // Truncate the contents of an element in place.
   $.fn.truncateHtml = function (options) {
      if ($.isNumeric(options)) options = { length: options };
      var o = $.extend({}, $.truncateHtml.defaults, options);

      return this.each(function () {
         var self = $(this);

         if (o.noBreaks) self.find('br').replaceWith(' ');

         var text = self.text();
         var excess = text.length - o.length;

         if (o.stripTags) self.text(text);

         // Chop off any partial words if appropriate.
         if (o.words && excess > 0) {
            excess = text.length - text.slice(0, o.length).replace(chop, '').length - 1;
         }

         if (excess < 0 || !excess && !o.truncated) return;

         // Iterate over each child node in reverse, removing excess text.
         $.each(self.contents().get().reverse(), function (i, el) {
            var $el = $(el);
            var text = $el.text();
            var length = text.length;

            // If the text is longer than the excess, remove the node and continue.
            if (length <= excess) {
               o.truncated = true;
               excess -= length;
               $el.remove();
               return;
            }

            // Remove the excess text and append the ellipsis.
            if (el.nodeType === 3) {
               $(el.splitText(length - excess - 1)).replaceWith(o.ellipsis);
               return false;
            }

            // Recursively truncate child nodes.
            $el.truncateHtml($.extend(o, { length: length - excess }));
            return false;
         });
      });
   };

   $.truncateHtml.defaults = {

      // Strip all html elements, leaving only plain text.
      stripTags: false,

      // Only truncate at word boundaries.
      words: false,

      // Replace instances of <br> with a single space.
      noBreaks: false,

      // The maximum length of the truncated html.
      length: Infinity,

      // The character to use as the ellipsis.  The word joiner (U+2060) can be
      // used to prevent a hanging ellipsis, but displays incorrectly in Chrome
      // on Windows 7.
      // http://code.google.com/p/chromium/issues/detail?id=68323
      ellipsis: '\u2026' // '\u2060\u2026'

   };

})(jQuery);
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
* 
* Open source under the BSD License. 
* 
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend(jQuery.easing,
{
   def: 'easeOutQuad',
   swing: function (x, t, b, c, d) {
      //alert(jQuery.easing.default);
      return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
   },
   easeInQuad: function (x, t, b, c, d) {
      return c * (t /= d) * t + b;
   },
   easeOutQuad: function (x, t, b, c, d) {
      return -c * (t /= d) * (t - 2) + b;
   },
   easeInOutQuad: function (x, t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t + b;
      return -c / 2 * ((--t) * (t - 2) - 1) + b;
   },
   easeInCubic: function (x, t, b, c, d) {
      return c * (t /= d) * t * t + b;
   },
   easeOutCubic: function (x, t, b, c, d) {
      return c * ((t = t / d - 1) * t * t + 1) + b;
   },
   easeInOutCubic: function (x, t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
      return c / 2 * ((t -= 2) * t * t + 2) + b;
   },
   easeInQuart: function (x, t, b, c, d) {
      return c * (t /= d) * t * t * t + b;
   },
   easeOutQuart: function (x, t, b, c, d) {
      return -c * ((t = t / d - 1) * t * t * t - 1) + b;
   },
   easeInOutQuart: function (x, t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
      return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
   },
   easeInQuint: function (x, t, b, c, d) {
      return c * (t /= d) * t * t * t * t + b;
   },
   easeOutQuint: function (x, t, b, c, d) {
      return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
   },
   easeInOutQuint: function (x, t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
      return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
   },
   easeInSine: function (x, t, b, c, d) {
      return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
   },
   easeOutSine: function (x, t, b, c, d) {
      return c * Math.sin(t / d * (Math.PI / 2)) + b;
   },
   easeInOutSine: function (x, t, b, c, d) {
      return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
   },
   easeInExpo: function (x, t, b, c, d) {
      return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
   },
   easeOutExpo: function (x, t, b, c, d) {
      return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
   },
   easeInOutExpo: function (x, t, b, c, d) {
      if (t == 0) return b;
      if (t == d) return b + c;
      if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
      return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
   },
   easeInCirc: function (x, t, b, c, d) {
      return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
   },
   easeOutCirc: function (x, t, b, c, d) {
      return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
   },
   easeInOutCirc: function (x, t, b, c, d) {
      if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
      return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
   },
   easeInElastic: function (x, t, b, c, d) {
      var s = 1.70158; var p = 0; var a = c;
      if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
      if (a < Math.abs(c)) { a = c; var s = p / 4; }
      else var s = p / (2 * Math.PI) * Math.asin(c / a);
      return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
   },
   easeOutElastic: function (x, t, b, c, d) {
      var s = 1.70158; var p = 0; var a = c;
      if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
      if (a < Math.abs(c)) { a = c; var s = p / 4; }
      else var s = p / (2 * Math.PI) * Math.asin(c / a);
      return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
   },
   easeInOutElastic: function (x, t, b, c, d) {
      var s = 1.70158; var p = 0; var a = c;
      if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5);
      if (a < Math.abs(c)) { a = c; var s = p / 4; }
      else var s = p / (2 * Math.PI) * Math.asin(c / a);
      if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
      return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
   },
   easeInBack: function (x, t, b, c, d, s) {
      if (s == undefined) s = 1.70158;
      return c * (t /= d) * t * ((s + 1) * t - s) + b;
   },
   easeOutBack: function (x, t, b, c, d, s) {
      if (s == undefined) s = 1.70158;
      return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
   },
   easeInOutBack: function (x, t, b, c, d, s) {
      if (s == undefined) s = 1.70158;
      if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
      return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
   },
   easeInBounce: function (x, t, b, c, d) {
      return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b;
   },
   easeOutBounce: function (x, t, b, c, d) {
      if ((t /= d) < (1 / 2.75)) {
         return c * (7.5625 * t * t) + b;
      } else if (t < (2 / 2.75)) {
         return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
      } else if (t < (2.5 / 2.75)) {
         return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
      } else {
         return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
      }
   },
   easeInOutBounce: function (x, t, b, c, d) {
      if (t < d / 2) return jQuery.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b;
      return jQuery.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b;
   }
});/*
 * ----------------------------- JSTORAGE -------------------------------------
 * Simple local storage wrapper to save data on the browser side, supporting
 * all major browsers - IE6+, Firefox2+, Safari4+, Chrome4+ and Opera 10.5+
 *
 * Copyright (c) 2010 - 2012 Andris Reinman, andris.reinman@gmail.com
 * Project homepage: www.jstorage.info
 *
 * Licensed under MIT-style license:
 *
 * 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 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.
 */
(function(f){if(!f||!(f.toJSON||Object.toJSON||window.JSON)){throw new Error("jQuery, MooTools or Prototype needs to be loaded before jStorage!")}var g={},d={jStorage:"{}"},h=null,j=0,l=f.toJSON||Object.toJSON||(window.JSON&&(JSON.encode||JSON.stringify)),e=f.evalJSON||(window.JSON&&(JSON.decode||JSON.parse))||function(m){return String(m).evalJSON()},i=false;_XMLService={isXML:function(n){var m=(n?n.ownerDocument||n:0).documentElement;return m?m.nodeName!=="HTML":false},encode:function(n){if(!this.isXML(n)){return false}try{return new XMLSerializer().serializeToString(n)}catch(m){try{return n.xml}catch(o){}}return false},decode:function(n){var m=("DOMParser" in window&&(new DOMParser()).parseFromString)||(window.ActiveXObject&&function(p){var q=new ActiveXObject("Microsoft.XMLDOM");q.async="false";q.loadXML(p);return q}),o;if(!m){return false}o=m.call("DOMParser" in window&&(new DOMParser())||window,n,"text/xml");return this.isXML(o)?o:false}};function k(){if("localStorage" in window){try{if(window.localStorage){d=window.localStorage;i="localStorage"}}catch(p){}}else{if("globalStorage" in window){try{if(window.globalStorage){d=window.globalStorage[window.location.hostname];i="globalStorage"}}catch(o){}}else{h=document.createElement("link");if(h.addBehavior){h.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(h);h.load("jStorage");var n="{}";try{n=h.getAttribute("jStorage")}catch(m){}d.jStorage=n;i="userDataBehavior"}else{h=null;return}}}b()}function b(){if(d.jStorage){try{g=e(String(d.jStorage))}catch(m){d.jStorage="{}"}}else{d.jStorage="{}"}j=d.jStorage?String(d.jStorage).length:0}function c(){try{d.jStorage=l(g);if(h){h.setAttribute("jStorage",d.jStorage);h.save("jStorage")}j=d.jStorage?String(d.jStorage).length:0}catch(m){}}function a(m){if(!m||(typeof m!="string"&&typeof m!="number")){throw new TypeError("Key name must be string or numeric")}return true}f.jStorage={version:"0.1.5.0",set:function(m,n){a(m);if(_XMLService.isXML(n)){n={_is_xml:true,xml:_XMLService.encode(n)}}g[m]=n;c();return n},get:function(m,n){a(m);if(m in g){if(typeof g[m]=="object"&&g[m]._is_xml&&g[m]._is_xml){return _XMLService.decode(g[m].xml)}else{return g[m]}}return typeof(n)=="undefined"?null:n},deleteKey:function(m){a(m);if(m in g){delete g[m];c();return true}return false},flush:function(){g={};c();try{window.localStorage.clear()}catch(m){}return true},storageObj:function(){function m(){}m.prototype=g;return new m()},index:function(){var m=[],n;for(n in g){if(g.hasOwnProperty(n)){m.push(n)}}return m},storageSize:function(){return j},currentBackend:function(){return i},storageAvailable:function(){return !!i},reInit:function(){var m,o;if(h&&h.addBehavior){m=document.createElement("link");h.parentNode.replaceChild(m,h);h=m;h.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(h);h.load("jStorage");o="{}";try{o=h.getAttribute("jStorage")}catch(n){}d.jStorage=o;i="userDataBehavior"}b()}};k()})(window.jQuery||window.$);/*!
 * imagesLoaded PACKAGED v3.2.0
 * JavaScript is all like "You images are done yet or what?"
 * MIT License
 */

(function () { "use strict"; function e() { } function t(e, t) { for (var n = e.length; n--;) if (e[n].listener === t) return n; return -1 } function n(e) { return function () { return this[e].apply(this, arguments) } } var i = e.prototype, r = this, s = r.EventEmitter; i.getListeners = function (e) { var t, n, i = this._getEvents(); if ("object" == typeof e) { t = {}; for (n in i) i.hasOwnProperty(n) && e.test(n) && (t[n] = i[n]) } else t = i[e] || (i[e] = []); return t }, i.flattenListeners = function (e) { var t, n = []; for (t = 0; t < e.length; t += 1) n.push(e[t].listener); return n }, i.getListenersAsObject = function (e) { var t, n = this.getListeners(e); return n instanceof Array && (t = {}, t[e] = n), t || n }, i.addListener = function (e, n) { var i, r = this.getListenersAsObject(e), s = "object" == typeof n; for (i in r) r.hasOwnProperty(i) && -1 === t(r[i], n) && r[i].push(s ? n : { listener: n, once: !1 }); return this }, i.on = n("addListener"), i.addOnceListener = function (e, t) { return this.addListener(e, { listener: t, once: !0 }) }, i.once = n("addOnceListener"), i.defineEvent = function (e) { return this.getListeners(e), this }, i.defineEvents = function (e) { for (var t = 0; t < e.length; t += 1) this.defineEvent(e[t]); return this }, i.removeListener = function (e, n) { var i, r, s = this.getListenersAsObject(e); for (r in s) s.hasOwnProperty(r) && (i = t(s[r], n), -1 !== i && s[r].splice(i, 1)); return this }, i.off = n("removeListener"), i.addListeners = function (e, t) { return this.manipulateListeners(!1, e, t) }, i.removeListeners = function (e, t) { return this.manipulateListeners(!0, e, t) }, i.manipulateListeners = function (e, t, n) { var i, r, s = e ? this.removeListener : this.addListener, o = e ? this.removeListeners : this.addListeners; if ("object" != typeof t || t instanceof RegExp) for (i = n.length; i--;) s.call(this, t, n[i]); else for (i in t) t.hasOwnProperty(i) && (r = t[i]) && ("function" == typeof r ? s.call(this, i, r) : o.call(this, i, r)); return this }, i.removeEvent = function (e) { var t, n = typeof e, i = this._getEvents(); if ("string" === n) delete i[e]; else if ("object" === n) for (t in i) i.hasOwnProperty(t) && e.test(t) && delete i[t]; else delete this._events; return this }, i.removeAllListeners = n("removeEvent"), i.emitEvent = function (e, t) { var n, i, r, s, o = this.getListenersAsObject(e); for (r in o) if (o.hasOwnProperty(r)) for (i = o[r].length; i--;) n = o[r][i], n.once === !0 && this.removeListener(e, n.listener), s = n.listener.apply(this, t || []), s === this._getOnceReturnValue() && this.removeListener(e, n.listener); return this }, i.trigger = n("emitEvent"), i.emit = function (e) { var t = Array.prototype.slice.call(arguments, 1); return this.emitEvent(e, t) }, i.setOnceReturnValue = function (e) { return this._onceReturnValue = e, this }, i._getOnceReturnValue = function () { return this.hasOwnProperty("_onceReturnValue") ? this._onceReturnValue : !0 }, i._getEvents = function () { return this._events || (this._events = {}) }, e.noConflict = function () { return r.EventEmitter = s, e }, "function" == typeof define && define.amd ? define("eventEmitter/EventEmitter", [], function () { return e }) : "object" == typeof module && module.exports ? module.exports = e : this.EventEmitter = e }).call(this), function (e) { function t(t) { var n = e.event; return n.target = n.target || n.srcElement || t, n } var n = document.documentElement, i = function () { }; n.addEventListener ? i = function (e, t, n) { e.addEventListener(t, n, !1) } : n.attachEvent && (i = function (e, n, i) { e[n + i] = i.handleEvent ? function () { var n = t(e); i.handleEvent.call(i, n) } : function () { var n = t(e); i.call(e, n) }, e.attachEvent("on" + n, e[n + i]) }); var r = function () { }; n.removeEventListener ? r = function (e, t, n) { e.removeEventListener(t, n, !1) } : n.detachEvent && (r = function (e, t, n) { e.detachEvent("on" + t, e[t + n]); try { delete e[t + n] } catch (i) { e[t + n] = void 0 } }); var s = { bind: i, unbind: r }; "function" == typeof define && define.amd ? define("eventie/eventie", s) : e.eventie = s }(this), function (e, t) { "use strict"; "function" == typeof define && define.amd ? define(["eventEmitter/EventEmitter", "eventie/eventie"], function (n, i) { return t(e, n, i) }) : "object" == typeof module && module.exports ? module.exports = t(e, require("wolfy87-eventemitter"), require("eventie")) : e.imagesLoaded = t(e, e.EventEmitter, e.eventie) }(window, function (e, t, n) { function i(e, t) { for (var n in t) e[n] = t[n]; return e } function r(e) { return "[object Array]" == f.call(e) } function s(e) { var t = []; if (r(e)) t = e; else if ("number" == typeof e.length) for (var n = 0; n < e.length; n++) t.push(e[n]); else t.push(e); return t } function o(e, t, n) { if (!(this instanceof o)) return new o(e, t, n); "string" == typeof e && (e = document.querySelectorAll(e)), this.elements = s(e), this.options = i({}, this.options), "function" == typeof t ? n = t : i(this.options, t), n && this.on("always", n), this.getImages(), u && (this.jqDeferred = new u.Deferred); var r = this; setTimeout(function () { r.check() }) } function h(e) { this.img = e } function a(e, t) { this.url = e, this.element = t, this.img = new Image } var u = e.jQuery, c = e.console, f = Object.prototype.toString; o.prototype = new t, o.prototype.options = {}, o.prototype.getImages = function () { this.images = []; for (var e = 0; e < this.elements.length; e++) { var t = this.elements[e]; this.addElementImages(t) } }, o.prototype.addElementImages = function (e) { "IMG" == e.nodeName && this.addImage(e), this.options.background === !0 && this.addElementBackgroundImages(e); var t = e.nodeType; if (t && d[t]) { for (var n = e.querySelectorAll("img"), i = 0; i < n.length; i++) { var r = n[i]; this.addImage(r) } if ("string" == typeof this.options.background) { var s = e.querySelectorAll(this.options.background); for (i = 0; i < s.length; i++) { var o = s[i]; this.addElementBackgroundImages(o) } } } }; var d = { 1: !0, 9: !0, 11: !0 }; o.prototype.addElementBackgroundImages = function (e) { for (var t = m(e), n = /url\(['"]*([^'"\)]+)['"]*\)/gi, i = n.exec(t.backgroundImage) ; null !== i;) { var r = i && i[1]; r && this.addBackground(r, e), i = n.exec(t.backgroundImage) } }; var m = e.getComputedStyle || function (e) { return e.currentStyle }; return o.prototype.addImage = function (e) { var t = new h(e); this.images.push(t) }, o.prototype.addBackground = function (e, t) { var n = new a(e, t); this.images.push(n) }, o.prototype.check = function () { function e(e, n, i) { setTimeout(function () { t.progress(e, n, i) }) } var t = this; if (this.progressedCount = 0, this.hasAnyBroken = !1, !this.images.length) return void this.complete(); for (var n = 0; n < this.images.length; n++) { var i = this.images[n]; i.once("progress", e), i.check() } }, o.prototype.progress = function (e, t, n) { this.progressedCount++, this.hasAnyBroken = this.hasAnyBroken || !e.isLoaded, this.emit("progress", this, e, t), this.jqDeferred && this.jqDeferred.notify && this.jqDeferred.notify(this, e), this.progressedCount == this.images.length && this.complete(), this.options.debug && c && c.log("progress: " + n, e, t) }, o.prototype.complete = function () { var e = this.hasAnyBroken ? "fail" : "done"; if (this.isComplete = !0, this.emit(e, this), this.emit("always", this), this.jqDeferred) { var t = this.hasAnyBroken ? "reject" : "resolve"; this.jqDeferred[t](this) } }, h.prototype = new t, h.prototype.check = function () { var e = this.getIsImageComplete(); return e ? void this.confirm(0 !== this.img.naturalWidth, "naturalWidth") : (this.proxyImage = new Image, n.bind(this.proxyImage, "load", this), n.bind(this.proxyImage, "error", this), n.bind(this.img, "load", this), n.bind(this.img, "error", this), void (this.proxyImage.src = this.img.src)) }, h.prototype.getIsImageComplete = function () { return this.img.complete && void 0 !== this.img.naturalWidth }, h.prototype.confirm = function (e, t) { this.isLoaded = e, this.emit("progress", this, this.img, t) }, h.prototype.handleEvent = function (e) { var t = "on" + e.type; this[t] && this[t](e) }, h.prototype.onload = function () { this.confirm(!0, "onload"), this.unbindEvents() }, h.prototype.onerror = function () { this.confirm(!1, "onerror"), this.unbindEvents() }, h.prototype.unbindEvents = function () { n.unbind(this.proxyImage, "load", this), n.unbind(this.proxyImage, "error", this), n.unbind(this.img, "load", this), n.unbind(this.img, "error", this) }, a.prototype = new h, a.prototype.check = function () { n.bind(this.img, "load", this), n.bind(this.img, "error", this), this.img.src = this.url; var e = this.getIsImageComplete(); e && (this.confirm(0 !== this.img.naturalWidth, "naturalWidth"), this.unbindEvents()) }, a.prototype.unbindEvents = function () { n.unbind(this.img, "load", this), n.unbind(this.img, "error", this) }, a.prototype.confirm = function (e, t) { this.isLoaded = e, this.emit("progress", this, this.element, t) }, o.makeJQueryPlugin = function (t) { t = t || e.jQuery, t && (u = t, u.fn.imagesLoaded = function (e, t) { var n = new o(this, e, t); return n.jqDeferred.promise(u(this)) }) }, o.makeJQueryPlugin(), o });/*!
 * jQuery Expander Plugin - v1.7.0 - 2016-03-12
 * http://plugins.learningjquery.com/expander/
 * Copyright (c) 2016 Karl Swedberg
 * Licensed MIT (http://www.opensource.org/licenses/mit-license.php)
 */
!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : "object" == typeof module && "object" == typeof module.exports ? module.exports = a : a(jQuery) }(function (a) { a.expander = { version: "1.7.0", defaults: { slicePoint: 100, sliceOn: null, preserveWords: !0, normalizeWhitespace: !0, showWordCount: !1, detailPrefix: " ", wordCountText: " ({{count}} words)", widow: 4, expandText: "read more", expandPrefix: "&hellip; ", expandAfterSummary: !1, wordEnd: /(&(?:[^;]+;)?|[0-9a-zA-Z\u00C0-\u0100]+|[^\u0000-\u007F]+)$/, summaryClass: "summary", detailClass: "details", moreClass: "read-more", lessClass: "read-less", moreLinkClass: "more-link", lessLinkClass: "less-link", collapseTimer: 0, expandEffect: "slideDown", expandSpeed: 250, collapseEffect: "slideUp", collapseSpeed: 200, userCollapse: !0, userCollapseText: "read less", userCollapsePrefix: " ", onSlice: null, beforeExpand: null, afterExpand: null, onCollapse: null, afterCollapse: null } }, a.fn.expander = function (b) { function c(a, b) { var c = "span", d = a.summary, e = q.exec(d), f = e ? e[2].toLowerCase() : ""; return b ? (c = "div", e && "a" !== f && !a.expandAfterSummary ? d = d.replace(q, a.moreLabel + "$1") : d += a.moreLabel, d = '<div class="' + a.summaryClass + '">' + d + "</div>") : d += a.moreLabel, [d, a.detailPrefix || "", "<", c + ' class="' + a.detailClass + '"', ">", a.details, "</" + c + ">"].join("") } function d(a, b) { var c = '<span class="' + a.moreClass + '">' + a.expandPrefix; return a.showWordCount ? a.wordCountText = a.wordCountText.replace(/\{\{count\}\}/, b.replace(n, "").replace(/\&(?:amp|nbsp);/g, "").replace(/(?:^\s+|\s+$)/, "").match(/\w+/g).length) : a.wordCountText = "", c += '<a href="#" class="' + a.moreLinkClass + '">' + a.expandText + a.wordCountText + "</a></span>" } function e(b, c) { return b.lastIndexOf("<") > b.lastIndexOf(">") && (b = b.slice(0, b.lastIndexOf("<"))), c && (b = b.replace(m, "")), a.trim(b) } function f(a, b) { b.stop(!0, !0)[a.collapseEffect](a.collapseSpeed, function () { var c = b.prev("span." + a.moreClass).show(); c.length || b.parent().children("div." + a.summaryClass).show().find("span." + a.moreClass).show(), a.afterCollapse && a.afterCollapse.call(b) }) } function g(b, c, d) { b.collapseTimer && (j = setTimeout(function () { f(b, c), a.isFunction(b.onCollapse) && b.onCollapse.call(d, !1) }, b.collapseTimer)) } function h(b) { var c = "ExpandMoreHere374216623", d = b.summaryText.replace(b.sliceOn, c); d = a("<div>" + d + "</div>").text(); var e = d.indexOf(c), f = b.summaryText.indexOf(b.sliceOn); return -1 !== e && e < b.slicePoint && (b.summaryText = b.allHtml.slice(0, f)), b } var i = "init"; "string" == typeof b && (i = b, b = {}); var j, k = a.extend({}, a.expander.defaults, b), l = /^<(?:area|br|col|embed|hr|img|input|link|meta|param).*>$/i, m = k.wordEnd, n = /<\/?(\w+)[^>]*>/g, o = /<(\w+)[^>]*>/g, p = /<\/(\w+)>/g, q = /(<\/([^>]+)>)\s*$/, r = /^(<[^>]+>)+.?/, s = /\s\s+/g, t = function (b) { return k.normalizeWhitespace ? a.trim(b || "").replace(s, " ") : b }, u = { init: function () { this.each(function () { var b, i, m, q, s, u, v, w, x, y, z, A, B, C, D, E = [], F = [], G = "", H = {}, I = this, J = a(this), K = a([]), L = a.extend({}, k, J.data("expander") || a.meta && J.data() || {}), M = !!J.find("." + L.detailClass).length, N = !!J.find("*").filter(function () { var b = a(this).css("display"); return /^block|table|list/.test(b) }).length, O = N ? "div" : "span", P = O + "." + L.detailClass, Q = L.moreClass + "", R = L.lessClass + "", S = L.expandSpeed || 0, T = t(J.html()), U = T.slice(0, L.slicePoint); if (L.moreSelector = "span." + Q.split(" ").join("."), L.lessSelector = "span." + R.split(" ").join("."), !a.data(this, "expanderInit")) { for (a.data(this, "expanderInit", !0), a.data(this, "expander", L), a.each(["onSlice", "beforeExpand", "afterExpand", "onCollapse", "afterCollapse"], function (b, c) { H[c] = a.isFunction(L[c]) }), U = e(U), s = U.replace(n, "").length; s < L.slicePoint;) q = T.charAt(U.length), "<" === q && (q = T.slice(U.length).match(r)[0]), U += q, s++; for (L.sliceOn && (D = h({ sliceOn: L.sliceOn, slicePoint: L.slicePoint, allHtml: T, summaryText: U }), U = D.summaryText), U = e(U, L.preserveWords && T.slice(U.length).length), u = U.match(o) || [], v = U.match(p) || [], m = [], a.each(u, function (a, b) { l.test(b) || m.push(b) }), u = m, i = v.length, b = 0; i > b; b++) v[b] = v[b].replace(p, "$1"); if (a.each(u, function (b, c) { var d = c.replace(o, "$1"), e = a.inArray(d, v); -1 === e ? (E.push(c), F.push("</" + d + ">")) : v.splice(e, 1) }), F.reverse(), M) x = J.find(P).remove().html(), U = J.html(), T = U + x, w = ""; else { if (x = T.slice(U.length), y = a.trim(x.replace(n, "")), "" === y || y.split(/\s+/).length < L.widow) return; w = F.pop() || "", U += F.join(""), x = E.join("") + x } L.moreLabel = J.find(L.moreSelector).length ? "" : d(L, x), N ? x = T : "&" === U.charAt(U.length - 1) && (G = /^[#\w\d\\]+;/.exec(x), G && (x = x.slice(G[0].length), U += G[0])), U += w, L.summary = U, L.details = x, L.lastCloseTag = w, H.onSlice && (m = L.onSlice.call(I, L), L = m && m.details ? m : L), z = c(L, N), J.empty().append(z), B = J.find(P), C = J.find(L.moreSelector), "slideUp" === L.collapseEffect && "slideDown" !== L.expandEffect || J.is(":hidden") ? B.css({ display: "none" }) : B[L.collapseEffect](0), K = J.find("div." + L.summaryClass), A = function (a) { a.preventDefault(); var b = a.startExpanded ? 0 : S; C.hide(), K.hide(), H.beforeExpand && L.beforeExpand.call(I), B.stop(!1, !0)[L.expandEffect](b, function () { B.css({ zoom: "" }), H.afterExpand && L.afterExpand.call(I), g(L, B, I) }) }, C.find("a").unbind("click.expander").bind("click.expander", A), L.userCollapse && !J.find(L.lessSelector).length && J.find(P).append('<span class="' + L.lessClass + '">' + L.userCollapsePrefix + '<a href="#" class="' + L.lessLinkClass + '">' + L.userCollapseText + "</a></span>"), J.find(L.lessSelector + " a").unbind("click.expander").bind("click.expander", function (b) { b.preventDefault(), clearTimeout(j); var c = a(this).closest(P); f(L, c), H.onCollapse && L.onCollapse.call(I, !0) }), L.startExpanded && A({ preventDefault: function () { }, startExpanded: !0 }) } }) }, destroy: function () { this.each(function () { var b, c, d = a(this); d.data("expanderInit") && (b = a.extend({}, d.data("expander") || {}, k), c = d.find("." + b.detailClass).contents(), d.removeData("expanderInit"), d.removeData("expander"), d.find(b.moreSelector).remove(), d.find("." + b.summaryClass).remove(), d.find("." + b.detailClass).after(c).remove(), d.find(b.lessSelector).remove()) }) } }; return u[i] && u[i].call(this), this }, a.fn.expander.defaults = a.expander.defaults });var Page=(function(){function _fireModuleEvent(event){ABL.LogInfo('_fireModuleEvent('+event+')');jQuery.each(ABL.Modules,function(key,val){if(event in val){val[event]()}})}return{init:function(){ABL.Event.bind('abl:fullrecord:updated',function(){AccessibleHelpers.AttachFocusHandler('#fullRecord .core:first');AccessibleHelpers.ProvideKeyNavigation('#fullRecord','.core, .fullrecord-block, .action-block, .sidebar-info')});$(document).on('click','.result-items .record-info',function(e){if($(e.target).closest('button, a, .undup-info, .debug-info, .result-action-links > *').length==0){$(this).find('a.detaillink').eq(0).click()}});ABL.Event.bind("abl:page:updated",function(){var $dbs=$('#dbsBranchesAnother');$dbs.popover({html:true,content:function(e){return $('<ul class="unstyled">'+$('.branch-items').html()+'</ul>')}});$dbs.click(function(e){e.preventDefault()});$dbs.on("show",function(){$dbs.parent().addClass('popover-shown')});$dbs.on("hidden",function(){$dbs.parent().removeClass('popover-shown')})});ABL.Event.bind('abl:results:updated',function(){AccessibleHelpers.AttachFocusHandler('#resultContainer > li .record:first');var clickSelectorFromDataAttribute=function($el){var clickSelector=$el.data('clickselector');if(!$.IsUndefinedOrEmpty(clickSelector))$el.find(clickSelector).eq(0).click()};AccessibleHelpers.ProvideKeyNavigation('body','#ablSearchform, .standard-feedback, .feedback-results-top-container, #resultContainer, #resultsPaging, .dbs-and-branches, #refineSidebar, #refineTree > .dim, .branch-feedback, #resultContainer > li .record',clickSelectorFromDataAttribute)});ABL.Event.bind('abl:pagetitle:update',function(event,data){if(!$.IsUndefinedOrEmpty(data)){document.title=data}});ABL.Event.bind('abl:advancedsearch:updated',function(){AccessibleHelpers.AttachFocusHandler('#ablAdvancedForm input:visible:first')});ABL.Event.one('abl:page:updated',function(){AccessibleHelpers.SetFocus($('#ablQuery'));window.performance.mark('query_input_has_focus')});ABL.Event.bind('abl:page:updated',function(){ABL.LogInfo('abl:page:updated (logged from page.js init bind())');$(window).scrollTop(0);$(".scrollable").stopMouseWheel();var page=State.GetCurrentSubPage();if(page){ABL.Event.trigger('abl:'+page+':updated');ABL.LogInfo('triggered event: abl:'+page+':updated')}});$(document).on('click','#ablogin',function(e){e.preventDefault();Page.ShowDebugLogin()});$(document).on('click','#ablogout',function(e){e.preventDefault();Page.DebugLogOut()});$(document).on('click','#debugtoggle',function(e){e.preventDefault();Page.DebugToggle()});$(document).on('submit','#debugLoginForm',function(e){LoadingIndicator.show()});$(document).on('click','a[rel^="abl"]',function(e){e.preventDefault();var $this=$(this);if(!$.IsUndefinedOrEmpty(State.Get('t_externalurl'))){State.Set('t_externalurl','');State.Set('t_addstatevars','')}if($this.attr('rel').indexOf('external')>-1){var providedUrl=$this.data('external-url');var stateVars=$this.data('add-state-vars');if(!$.IsUndefinedOrEmpty(providedUrl)){State.Set('t_externalurl',providedUrl);State.Set('t_addstatevars',stateVars)}}if($this.hasClass('disabled')){ABL.LogInfo('Link clicked, but no action taken because of disabled class',this)}else{var href=$this.attr('href');var action=$.getObjectFromQueryString(href);action['href']=ABL.GetSignificantPath(href);State.Set('serverstate',action);Page.ActionHandler(action)}});$(document).on('click keydown','.dropdown-toggle',function(e){if(e.type=='click'||(e.type=='keydown'&&e.keyCode==13)){if($(this).parent().hasClass('open')){$(this).attr('aria-expanded','true')}else{$(this).attr('aria-expanded','false')}}});$(document).on('show','#debugRecordInfo',function(){if($("#debugRecordWrapper").data('loaded')){return}var itemid=$('#debugRecordInfo').data('itemid');var detailLevel=State.Get('detaillevel')||'';if(detailLevel){detailLevel="&detaillevel="+encodeURIComponent(detailLevel)}$.ajax({url:ABL.GetBaseUrl()+"recorddebug/?itemid="+encodeURIComponent(itemid)+"&c_disable_displayidmodule=true&debug="+encodeURIComponent(State.DebugMode())+detailLevel}).done(function(data){$("#debugRecordWrapper").html(data);$("#debugRecordWrapper").data('loaded',true)}).fail(function(jqXHR,status){$("#debugRecordWrapper").append('<div>Could not load debug data</div><div class="error">'+status+'</div>')})});$(document).on('click','a[data-echo]',function(e){var $this=$(this);var selector=$this.attr('data-echo');var $target,d;var $form=$this.parents('form');if(selector){$this.attr('data-echo','');$target=$(selector);if($target.size()){d='<root>';d+=$target.text();d=d.replace(/>( |\r\n|\n)+/g,'>');d=d.replace(/( |\r\n|\n)+</g,'<');d+='</root>';if($form.size()){$form.find('input[name=d]').attr('value',d)}else{$this.attr('href',$this.attr('href')+window.encodeURIComponent(d))}}}if($form.size()){$form.submit();e.preventDefault()}});$(document).on('click','a.summary-show',function(e){e.preventDefault();var data=$(this).data()||{};$('.summary').filter(function(){return $(this).data('summary-id')===data.summaryId}).toggleClass('hidden');if(data.summaryHideAfterClick){$(this).hide()}});$(document).on('click','a[data-scroll="true"]',function(e){e.preventDefault();PageHelpers.ScrollTo($(this))});$(document).on('click','a.branch-more',function(e){e.preventDefault();$('.branch-items').slideToggle(function(){AccessibleHelpers.SetFocus($(this).find(AccessibleHelpers.FocusableElementsString).eq(0))})});$(document).on('click keydown','a.simple-browser-back',function(e){if(e.type=='click'||(e.type=='keydown'&&e.keyCode==13)){e.preventDefault();window.history.back()}});$(document).on('click keydown','a.hide-sitedebug',function(e){if(e.type=='click'||(e.type=='keydown'&&e.keyCode==13)){var hiding=State.Get('c_hide_site_status');if(hiding){State.Set('c_hide_site_status','')}else{State.Set('c_hide_site_status',true)}DiscoveryPane.UpdateQueryBox();Page.Actions.generic(State.AsObject())}});this.Modal.init();jQuery.each(State.Settings.Get('actions'),function(key,value){if(!(key in Page.Actions)){Page.Actions[key]=function(state){state=state||{};state['action']=key;Page.Actions.generic(state)}}})},Actions:{generic:function(state){var newState={};var action=state['action'];var actionSettings=State.Settings.Get('actions')[state.action];if(!action){ABL.LogError('Actions.generic, could not find action in settings object, which means I can\'t take some action! - Just executing the received state, no guarantees it\'ll work...')}else{if('defaults'in actionSettings){$.each(actionSettings['defaults'],function(key,value){newState[key]=value})}if('overrides'in actionSettings){$.each(actionSettings['overrides'],function(key,value){newState[key]=value})}if('required'in actionSettings){$.each(actionSettings['required'],function(key,_){if(key in newState){return}else if(key in state){newState[key]=state[key]}else{throw"Action: the key: "+key+" is required, but not found in the provided object";}})}}jQuery.each(state,function(key,val){if(!(key in newState)){newState[key]=val}});if(!('si'in newState)){newState.si='user'}State.ExtendWithObject(newState);if(State.Get('cmd')===('find')){_fireModuleEvent("HandlePreSearch")}if(State.Get('cmd')===('nav')){_fireModuleEvent("HandlePreNav")}ABL.Request()},search:function(state){var $debugElement,key;var provider=DiscoveryPane.GetProviderFromDropdown()||State.Get('provider');var newState=jQuery.extend({si:'user',action:'search',provider:provider,hardsort:''},state);var extUrl=State.Get('t_externalurl');if(!$.IsUndefinedOrEmpty(extUrl)){var addStateVars=State.Get('t_addstatevars');if(!$.IsUndefinedOrEmpty(addStateVars)){extUrl+='?';var vars=addStateVars.split('|');for(var i=0;i<vars.length;i++){var stateVar=newState[vars[i]];if(typeof stateVar=='undefined')stateVar=State.Get(vars[i]);extUrl+=vars[i]+'='+stateVar+(i!=vars.length-1?'&':'')}}document.location.href=extUrl;return}if($.IsUndefinedOrEmpty(state.q)){ABL.LogInfo('empty q - Probably nothing in the searchbox... doing nothing');return false}switch(state.q){case'/#':try{$debugElement=$('<div id="debugInfo"/>').html(State.AsHtmlString());Page.Modal.show('Debug information - Liquid v'+State.Settings.Get('version')+State.Settings.Get('clusterid'),$debugElement)}catch(e){ABL.LogError(e)}return false;case'/!':DiscoveryPane.UpdateQueryBox();Page.ShowDebugLogin();return false;case'/!!':Page.DebugLogout();DiscoveryPane.UpdateQueryBox();Page.Actions.generic(State.AsObject());return false;case'/l':State.Set('detaillevel','librarian');DiscoveryPane.UpdateQueryBox();Page.Actions.generic(State.AsObject());return false;case'/ll':State.Set('detaillevel','default');DiscoveryPane.UpdateQueryBox();Page.Actions.generic(State.AsObject());return false}Page.Actions.generic(newState);return true},getpage:function(state){var subPage=State.GetCurrentSubPage(state.page);if(subPage=='welcome'){ABL.Reset()}Page.Actions.generic(state)},branch:function(state){DiscoveryPane.UpdateQueryBoxDropdown({branch:state.branch,provider:state.provider});AccessibleHelpers.SetFocus($('#ablQuery'));return false},provider:function(state){DiscoveryPane.UpdateQueryBoxDropdown({provider:state.provider});AccessibleHelpers.SetFocus($('#ablQuery'));return false},providersearch:function(state){state=state||{};state['href']=State.Settings.Get("applicationpath")+ABL.GetProviderUrlPrefix(state['provider']);Page.Actions.generic(state)},advsearchlink:function(state){state=state||{};if(State.GetCurrentSubPage()=='advancedsearch'&&State.Get("provider")===DiscoveryPane.GetProviderFromDropdown()){return false}state['action']='advsearchlink';Page.Actions.generic(state)}},ActionHandler:function(state){var action=state['action'];if(typeof action=='undefined'){ABL.LogError('Page.ActionHandler: action is undefined')}if(action in Page.Actions){if(Page.Actions[action](state)===false){return false}}else{Page.Actions.generic(state)}},Print:function(){if($.browser.msie){document.execCommand("Print")}else{window.print()}},DebugLogOut:function(){State.Set('debug','');State.Set('detaillevel','default');$.post(ABL.GetBaseUrl()+'login.ashx',{logout:true}).always(function(){Page.Actions.generic(State.AsObject());location.reload()})},DebugToggle:function(){if(!State.DebugMode()){State.Set('debug','true');State.Set('DetailLevel','debug')}else{State.Set('debug','');State.Set('detaillevel','Default')}location.href=ABL.GetBaseUrl()+'?'+State.AsArgString()},ShowDebugLogin:function(){var $loginModal=$('<div id="login"/>');var jqXHRFormPage=$.ajax({type:'GET',cache:false,url:ABL.GetBaseUrl()+'login/'});jqXHRFormPage.done(function(data){var $form=$(data);$loginModal.html($form);$form.on('submit',$form,function(e){e.preventDefault();var data={};var getDataByClass=function(name){var v=$form.find('[name="'+name+'"]').val();if(v)data[name]=v};var getCheckboxDataByClass=function(name){var v=$form.find('[name="'+name+'"]').is(':checked');if(v)data[name]=v};getDataByClass('user');getDataByClass('password');getDataByClass('csrf');getDataByClass('logout');getCheckboxDataByClass('viewdebug');getCheckboxDataByClass('persist');$.post(ABL.GetBaseUrl()+'login.ashx',data).done(function(){if(data.viewdebug){State.Set('debug','true');State.Set('DetailLevel','debug')}location.href=ABL.GetBaseUrl()+'?'+State.AsArgString()}).always(function(){Page.Modal.hide();$loginModal.remove()})});Page.Modal.show('Debug login - Liquid v'+State.Settings.Get('version')+State.Settings.Get('clusterid'),$loginModal)});jqXHRFormPage.fail(function(){ABL.LogError('login screen could not be loaded');$loginModal.remove();Page.Actions.generic(State.AsObject())})},Modal:(function(){var $modal,$header,$body,$focusedElementBeforeModal;return{init:function(){$modal=$('#ablModal');if($modal.length==0){ABL.LogError("Page.Modal : No modal element found in page!")}$header=$modal.find('.abl-modal-header .heading');this.Header=$header;$body=$modal.find('.abl-modal-body');this.Body=$body;var modal=this;$modal.find('*[data-close]').on('click',function(e){e.preventDefault();modal.hide()});$(document).on('abl:page:unload',function(){modal.hide()})},TrapTabKey:function(){AccessibleHelpers.TrapTabKeyToElement($modal)},show:function(header,$contentElement,optionalCallbackOnOpen,optionalCallbackOnClose,size){size=size||'medium';$modal.removeClass('small medium large').addClass(size);$focusedElementBeforeModal=$(':focus').eq(0);$body.html($contentElement);$header.html(header);$modal.bPopup({opacity:0.1,transitionClose:0,positionStyle:'fixed',modalColor:'#FFF',zIndex:500,onOpen:function(){this.find(".abl-modal-body").stopMouseWheel();Page.Modal.TrapTabKey();$modal.attr('aria-hidden','false');$('body div:first').attr('aria-hidden','true');$modal.find('input:visible').eq(0).focus();if($.isFunction(optionalCallbackOnOpen)){optionalCallbackOnOpen.apply(this,arguments)}},onClose:function(){$modal.attr('aria-hidden','true');$('body div:first').removeAttr('aria-hidden');AccessibleHelpers.SetFocus($focusedElementBeforeModal);if($.isFunction(optionalCallbackOnClose)){optionalCallbackOnClose.apply(this,arguments)}}})},hide:function(){if($modal.is(':visible')){$modal.bPopup().close()}}}})()}})();ABL.RegisterModule(Page);var AccessibleHelpers=(function(){var $currentFocusElement;return{SetFocus:function($el){var setFocus=function($el){if(typeof $el==='string'){$el=$($el)}if(typeof $currentFocusElement!='undefined'&&!$el.is($currentFocusElement)){$currentFocusElement.attr('tabindex','-1')}$currentFocusElement=$el;if($el.attr('tabindex')!='0'){$el.one('blur',function(){$el.attr('tabindex','-1')})}$el.attr('tabindex','0');if($el.is(':visible')){$el.focus()}else{$el.triggerHandler('focus')}};return setFocus($el)},RemoveFocus:function($el){$el.attr('tabindex','-1')},AttachFocusHandler:function(resultSelector){var firstTime=true;$(document).off('.focushandler');$(document).on('keydown.focushandler click.focushandler',function(event){if(event.keyCode==9&&!event.shiftKey){AccessibleHelpers.SetFocus($(resultSelector));event.preventDefault();$(document).off('.focushandler')}if(event.type=='click'){$(document).off('.focushandler')}})},FocusableElementsString:"a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]",ProvideKeyNavigation:function(elementSelector,navigableSelector,defaultActionCallback){var $els=$(elementSelector);var $navigableElements=$els.find(navigableSelector);$navigableElements.attr('tabindex','-1').addClass('focusable');$currentFocusElement=$navigableElements.eq(0);$els.each(function(){var $el=$(this);$el.off('.accessiblenav');$el.on('blur.accessiblenav',function(){AccessibleHelpers.RemoveFocus($(this))});$el.on('keydown.accessiblenav',function(event){var $target=$(event.target);if($target.is('input, textarea, select'))return;if(event.keyCode==36){AccessibleHelpers.SetFocus($navigableElements.eq(0))}if(event.keyCode==35){AccessibleHelpers.SetFocus($navigableElements.last())}if(event.keyCode==37||event.keyCode==38||event.keyCode==39||event.keyCode==40||event.keyCode==13){var $parent=$navigableElements.is($target)?$target:$navigableElements.has($target);if($parent.length>1){$parent=$parent.last()}var index=$navigableElements.index($target);var parentIndex=$navigableElements.index($parent);if(event.keyCode==37){if(!$navigableElements.is($target)){AccessibleHelpers.SetFocus($parent)}}if(event.keyCode==39){}if(event.keyCode==38){if($navigableElements.is($parent)&&parentIndex>0){if($navigableElements.eq(parentIndex-1).is(':empty')&&parentIndex>1)AccessibleHelpers.SetFocus($navigableElements.eq(parentIndex-2));else AccessibleHelpers.SetFocus($navigableElements.eq(parentIndex-1))}}if(event.keyCode==40){if($navigableElements.is($parent)&&parentIndex<$navigableElements.length){if($navigableElements.eq(parentIndex+1).is(':empty')&&(parentIndex+1)<$navigableElements.length)AccessibleHelpers.SetFocus($navigableElements.eq(parentIndex+2));else AccessibleHelpers.SetFocus($navigableElements.eq(parentIndex+1))}}if(event.keyCode==13){if($.isFunction(defaultActionCallback)&&$navigableElements.is($target)){defaultActionCallback($parent)}}else{event.preventDefault()}}else if((event.keyCode==13||event.keyCode==32)){}})})},TrapTabKeyToElement:function($el,optionalFirstFocusElementSelector){if(typeof optionalFirstFocusElementSelector=='undefined'){$el.find(AccessibleHelpers.FocusableElementsString).first().focus()}else{$el.find(optionalFirstFocusElementSelector).focus()}$el.off('.tabtrap');$el.on('keydown.tabtrap',function(evt){if(evt.which==9){var o=$el.find('*');var focusableItems=o.filter(AccessibleHelpers.FocusableElementsString).filter(':visible');var focusedItem=$(':focus');var numberOfFocusableItems=focusableItems.length;var focusedItemIndex=focusableItems.index(focusedItem);if(evt.shiftKey){if(focusedItemIndex==0){focusableItems.get(numberOfFocusableItems-1).focus();evt.preventDefault()}}else{if(focusedItemIndex==numberOfFocusableItems-1){focusableItems.get(0).focus();evt.preventDefault()}}}})}}})();ABL.RegisterModule(AccessibleHelpers);var PageHelpers={init:function(){PageHelpers.FixElement.init();PageHelpers.KeyBinder.init();ABL.Event.bind('abl:page:updated',function(){PageHelpers.bindExpander();$("#refineSidebar .count").each(function(){var $count=$(this);var $link=$count.prev();if($count.position().left===$link.position().left){$count.parent().css({whiteSpace:"nowrap"})}})});$(document).on('click','.md-tags-show-more',function(e){e.preventDefault();$(this).hide();$('.md-tags-more').show()});ABL.Event.bind('abl:page:updated',function(data){PageHelpers.checkCovers($('span.cover-images'))});$(document).on('click','.list-more',function(e){e.preventDefault();PageHelpers.ListMoreShow($(this))});$(document).on('click','.continuationmarker-less-link',function(e){e.preventDefault();var activePane=$('.tab-pane.active .wrap-text');activePane.find('.details').hide();activePane.find('.summary').show();activePane.find('.summary .read-more').show()});if($.browser.msie){switch($.browser.version){case'8.0':$('html').addClass('ie8');break;default:$('html').addClass('ienew');break}$('html').addClass("ie")}},checkCovers:function($coverImageContainer){var getImage=function($image){var dfd=$.Deferred();var i=new Image;var src=$image.data('src');if($.IsUndefinedOrEmpty(src)){dfd.reject("no source",$image);return dfd}i.src=src;$(i).imagesLoaded().done(function(images){var width=i.width;if(width>1){var $coverContainer=$image.parents('.cover-images');$coverContainer.siblings('.default-cover').remove();$image.siblings('img.external-cover').remove();$image.attr('src',i.src).fadeIn(function(){if(State.GetCurrentSubPage()=='fullrecord'){if(width-$image.width()>10){$('<i class="fa fa-search enlarge-icon"/>').insertBefore($image).fadeIn(100);$coverContainer.click(function(e){e.preventDefault();var size='medium';if(i.width<600)size='small';if(i.width>950)size='large';Page.Modal.show(Localization.Trans('cover-image-large'),$('<div class="text-center"><a href="'+i.src+'" rel="external"><img src="'+i.src+'" class="cover-popup '+size+'" /></a></div>'),false,false,size)}).addClass('fakelink')}}});dfd.resolve(src)}else{dfd.reject("1x1: "+src)}}).fail(function(images){dfd.reject("failed load: "+src)});return dfd};var findFirstValidImage=function($images){var dfd=$.Deferred();var loadSequential=function(index){if(index>=$images.length){dfd.resolve()}else{getImage($images.eq(index)).fail(function(status){loadSequential(index+1)}).done(function(status){dfd.resolve(status)})}};loadSequential(0);return dfd.promise()};$coverImageContainer.each(function(){findFirstValidImage($(this).find('img.external-cover')).done(function(info){})})},skinAshx:function(u,skin){var actualSkin=skin||State.Get("skin");var bld=State.Settings.Get("bld");return(ABL.GetBaseUrl())+"assets/resources/"+encodeURIComponent(u)+'?skin='+encodeURIComponent(actualSkin)+"&bld="+encodeURIComponent(bld)},bindExpander:function(optionaljQueryElement){var $tobind=optionaljQueryElement||$('.wrap-text');$tobind.each(function(){var bindObj=$(this);var gaAction=bindObj.attr('data-ga-action-template');var gaSource=bindObj.attr('data-ga-source');var slicePoint=bindObj.data('wraplength')||450;var minWordCountToShow=bindObj.data('widow')||15;var expanderOptions={slicePoint:slicePoint,preserveWords:true,widow:minWordCountToShow,expandText:Localization.Trans('read-more'),userCollapse:true,userCollapseText:Localization.Trans('read-less'),expandEffect:'fadeIn',expandSpeed:250,collapseEffect:'fadeOut',collapseSpeed:0};bindObj.expander($.extend(expanderOptions,{onCollapse:function(){$(window).scrollTop($(this).parent().offset().top-100);if("GA"in window&&gaAction){window.GA.Fire(gaAction,{openclose:"expander-close",source:gaSource})}},beforeExpand:function(e){var $this=$(this);if("GA"in window&&gaAction){window.GA.Fire(gaAction,{openclose:"expander-open",source:gaSource})}var addContinuationMarker=$(this).data('addcontinuationmarker')||false;if(!addContinuationMarker){return}if($(this).find('.continuationmarker').length>0){return}var $details=$(this).find('.'+$.expander.defaults.detailClass);var detailsHtml=$details.html();var readMoreHtml=$(this).find('.'+$.expander.defaults.moreClass).clone().wrap('<p>').parent().html();var escapeRegex=function(string){return string.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1")};var sliceRegex=new RegExp('(<[^\>]+>)?'+escapeRegex(readMoreHtml));var slicePoint=$(this).find('.'+$.expander.defaults.summaryClass).html().search(sliceRegex);if(slicePoint<0){slicePoint=$(this).find('.'+$.expander.defaults.summaryClass+' div').html().indexOf('<',($(this).data('wraplength')||450))}var textToAdd='<span class="continuationmarker"> <a href="#" class="continuationmarker-less-link">'+Localization.Trans('continuation-marker')+'</a></span>';var $readLess=$details.find('.'+$.expander.defaults.lessClass).clone(true,true);$details.html(detailsHtml.substring(0,slicePoint)+textToAdd+detailsHtml.substring(slicePoint,detailsHtml.length-$readLess.html().length));$details.append($readLess)}}))})},ScrollTo:function($el,noFocus){var $scrollToEl;var offset=PageHelpers.FixElement.GetOffset();var id=$el.attr('href');if(id==='#'){$scrollToEl=$('body');$('html, body').animate({scrollTop:0});if(!noFocus){$scrollToEl.focus()}}else{$scrollToEl=$(id);if($scrollToEl.length>0){var scrollToPos=$scrollToEl.offset().top-offset;if(scrollToPos>80&&$('body').scrollTop()==0){$('html, body').animate({scrollTop:scrollToPos})}if(!noFocus){AccessibleHelpers.SetFocus($scrollToEl)}}}if("GA"in window){window.GA.FireOn($(this))}},ListMoreShow:function($el){var targetSelector=$el.data('target')||'';if(targetSelector!=''){$(targetSelector+':hidden').show();$el.hide()}else{ABL.LogWarning('list-more was clicked, but no data-target attribute found, so do not now what to show')}},SetContainerVisible:function($el){var showContainer=$el.data('show-container');if(typeof showContainer!=undefined){$(showContainer).show()}},FixElement:{_elements:[],init:function(){var that=this;$(window).scroll(function(){that.UpdatePositions()})},GetOffset:function(){var height=0;$.each(this._elements,function(index,value){if($(value).hasClass('fixed-element')){height+=$(value).height()}else{height+=$(value).height()*2}});return height},Register:function($element){if($element.length>0){if(jQuery.inArray(this._elements,$element==-1)){this._elements.push($element)}else{ABL.LogInfo("FixElement Register, element already stored",$element)}$element.data('float-original-top',$element.offset().top)}else{ABL.LogError('FixElement Register, element:',$element)}},UpdatePositions:function(){var len=this._elements.length;var $currentElement,elTop;var addTop=0;for(var i=0;i<len;i++){$currentElement=$(this._elements[i]);elTop=$currentElement.data('float-original-top')==0?$('#searchbox').position().top+$('#searchbox').height():$currentElement.data('float-original-top');this.UpdatePosition($currentElement,elTop,addTop);addTop+=$currentElement.outerHeight()}},UpdatePosition:function($element,elTop,addTop){var scrollPosition=$(window).scrollTop();if(scrollPosition>=elTop&&$element.is(':visible')){$element.addClass('fixed-element').css({top:addTop})}else{$element.removeClass('fixed-element').css({top:''})}}},GetFormHiddenFieldsObject:function($form,searchAllDescendants){var $inputFields,length,result,$input,i;if(typeof searchAllDescendants=='undefined'){searchAllDescendants=false}if($form.length==0){return null}$inputFields=searchAllDescendants?$form.find('input[type="hidden"]'):$form.children('input[type="hidden"]');length=$inputFields.size();if(!length){return null}result={};for(i=0;i<length;i++){$input=$($inputFields.get(i));result[$input.attr('name')]=$input.attr('value')}return result},KeyBinder:{init:function(){$(document).keydown(function(e){if(!$(e.target).is('input:not([type=checkbox]), textarea, select')){if((!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey)&&((e.keyCode>=48&&e.keyCode<=57)||(e.keyCode>=65&&e.keyCode<=90))){$('#ablQuery').val($('#ablQuery').val()+' ');$('#ablQuery').focus()}if(e.shiftKey){var key=e.which;switch(key){case 37:$('.previous a').eq(0).trigger('click');break;case 39:$('.next a').eq(0).trigger('click');break;case 35:$('.last a').eq(0).trigger('click');break;case 36:$('.first a').eq(0).trigger('click');break;case 65:$('.da-toggle').eq(0).trigger('click');break;case 83:$(document).one('keydown',function(secondEvent){var hardsortIndex=0;switch(secondEvent.keyCode){case 49:hardsortIndex=0;break;case 50:hardsortIndex=1;break;case 51:hardsortIndex=2;break;case 52:hardsortIndex=3;break}$('.feedback-hardsort a').eq(hardsortIndex).trigger('click')});break;case 82:AccessibleHelpers.SetFocus($('#refineTree').eq(0));break;case 90:case 191:AccessibleHelpers.SetFocus('#ablQuery');$('#ablQuery').val('');e.preventDefault();break}}}})}}};ABL.RegisterModule(PageHelpers);var Feedbacks={_feedbackCount:0,init:function(){$('#ablContent').on('click','#feedbackToggle',function(e){e.preventDefault();$('.feedback-hidden').toggle()});ABL.Event.bind('abl:feedback:added',function(){Feedbacks.addFeedbacks()});ABL.Event.bind('abl:results:updated',function(){Feedbacks.addFeedbacks()})},addFeedbacks:function(){var $feedbackElements=$('.feedback-hidden .feedback[data-feedbackcollapsedvalue]:not(.hidden)');Feedbacks._feedbackCount=$feedbackElements.length;var shouldCollapse=State.Settings.Get('collapsiblefeedback');if(Feedbacks._feedbackCount>=1){if(shouldCollapse){var tempText='';$feedbackElements.each(function(index){tempText+=$(this).attr('data-feedbackcollapsedvalue')+(index+1<Feedbacks._feedbackCount?Localization.Trans('feedback-collapsed-and')+' ':' ')});$('#feedbackToggle').show().text(Localization.Trans('feedback-about-your-query')+' '+tempText+' '+Localization.Trans('feedback-collapsed-moreinfo'))}else{$('.feedback-hidden').removeClass('feedback-hidden')}$('#feedbackCollapsible').fadeIn()}}};ABL.RegisterModule(Feedbacks);var SpotlightingModule={init:function(){$(document).on('mouseover mouseout',".spotlight.pop-covers ol li",function(ev){if(!$(this).hasClass('enabled')){return}var $figCaption=$(this).find("figcaption");var innerHeight=$figCaption.find("span").height();innerHeight=Math.min(innerHeight,$figCaption.siblings("div").height());if(ev.type=='mouseover'){$figCaption.stop(true);$figCaption.animate({height:innerHeight+"px"},200)}else{$figCaption.stop(true);$figCaption.animate({height:'14px'},200)}})}};ABL.RegisterModule(SpotlightingModule);var LoadingIndicator={_delay:800,_timer:null,init:function(){var L=LoadingIndicator;ABL.Event.bind('abl:page:updated',function(){LoadingIndicator._internalHide()});$('#loadingIndicator').hide(true).ajaxStart(L._start).ajaxStop(L._stop)},_start:function(){var L=LoadingIndicator;L._stop();if(L._timer===null){L._timer=setTimeout(L.show,L._delay)}},_stop:function(){var L=LoadingIndicator;if(L._timer!==null){clearTimeout(L._timer);L._timer=null}L.hide()},showError:function(url){var $debuginfo;var $li=$('#loadingIndicator');$li.addClass('error').text(Localization.Trans('ldr-request-failed'));if(State.DebugMode()){if(typeof url!='undefined'){$debuginfo=$('<a/>').attr('href',url).text('(url)');$li.append('<br/>').append($debuginfo)}else{$li.append('<br/>(check js console)')}}LoadingIndicator.show();LoadingIndicator.removeLoadingTitle()},show:function(){var $statusbar=$('.statusbar-wrapper:visible');var $li=$('#loadingIndicator');if($statusbar.length>0&&$statusbar.hasClass('attached')){$li.css({top:$statusbar.height()}).show()}else{$li.css({top:0}).show()}$li.attr('aria-hidden','true');document.title=Localization.Trans('ldr-loading')+" "+document.title;$li.one('click',function(){LoadingIndicator._internalHide()})},hide:function(force){if($('#loadingIndicator').hasClass('error')){if(force){LoadingIndicator._internalHide()}else{ABL.LogInfo('Loading indicator has error, not hiding')}}else{LoadingIndicator._internalHide()}},removeLoadingTitle:function(){var loadingString=Localization.Trans('ldr-loading');var indexOfLoadingString=document.title.indexOf(loadingString);if(indexOfLoadingString>=0){document.title=document.title.substr(loadingString.length+1)}},_internalHide:function(){$('#loadingIndicator').hide().removeClass('error').text(Localization.Trans('ldr-loading')).attr('aria-hidden','true');LoadingIndicator.removeLoadingTitle()}};ABL.RegisterModule(LoadingIndicator);var AdvancedSearchBox=(function(){return{_defaultText:"",fieldCollection:[],fieldValueCollection:{},init:function(){var A=AdvancedSearchBox,$ablContent=$('#ablContent');this._defaultText=Localization.Trans('adv-search-info');ABL.Event.bind("abl:page:updated",AdvancedSearchBox.updateUI.bind(AdvancedSearchBox));$ablContent.on('click','#advancedClear',function(e){e.preventDefault();A.clear()});$ablContent.on('click','#advancedCancel',function(e){e.preventDefault();A.clear()});$ablContent.on('click','#advancedsearchcategories li a',function(e){e.preventDefault();A._switchCategory($(this))});$ablContent.on('change','#ablAdvancedForm input[type=checkbox]',function(){var $e=$(this),field=$e.attr('name').substring(12),fields=A.fieldCollection,o,f;for(o in fields){f=fields[o];if(f.id==field){f.mode=$e.is(':checked')?'=':':'}}A._updateQuery()});$ablContent.on('input change','#ablAdvancedForm input[data-provide=datepicker]',function(){var $e=$(this);$e.datepicker('hide');if($e.attr('data-mode')==='range'){if($.isNumeric($e.val())){var dateRange=$e.attr('data-range'),name=$e.attr('name'),value=parseInt($e.val()),$elementToUpdate;switch(dateRange){case'start':$elementToUpdate=$('#'+name+'_end');if($elementToUpdate.val().length===0||($.isNumeric($elementToUpdate.val())&&(parseInt($elementToUpdate.val())<value))){$elementToUpdate.val(value+1)}$elementToUpdate.datepicker('show');$elementToUpdate.datepicker('update');break;case'end':$elementToUpdate=$('#'+name+'_start');if($elementToUpdate.val().length===0||($.isNumeric($elementToUpdate.val())&&(parseInt($elementToUpdate.val())>value))){$elementToUpdate.val(value-1)}break}}}A._updateQuery()});$ablContent.on('change','#ablAdvancedForm select',A._onChange);$ablContent.on('keyup blur change input','#ablAdvancedForm input[type=text], #ablAdvancedForm textarea',A._onChange);$ablContent.on('submit','#ablAdvancedForm',function(e){e.preventDefault();var $form=$(this);var q=$.trim($('#ablAdvancedQuery').val());if(q.length&&q!=A._defaultText){var tempStateObject=$.extend(PageHelpers.GetFormHiddenFieldsObject($form),{q:q});tempStateObject["href"]=$form.attr("action");Page.Actions.search(tempStateObject)}})},clear:function(){$('#ablAdvancedForm')[0].reset();$('#ablAdvancedQuery').val('');AdvancedSearchBox.fieldValueCollection={}},_switchCategory:function($el){$parentEl=$el.parent('li');$('#ablAdvancedForm').children('fieldset').removeClass('active');$("#"+$parentEl.data('advanced-search-category')).addClass('active');$('#advancedsearchcategories').children().removeClass('active');$parentEl.addClass('active');AdvancedSearchBox.updateUI()},_onChange:function(e){var A=AdvancedSearchBox;var $e=$(this),v=$.trim($e.val()),id=$e.attr('id'),dataProvide=$e.attr('data-provide'),mode=$e.attr('data-mode'),name=$e.attr('name');var activeCat=$('#advancedsearchcategories li.active').data("advanced-search-category");if(A.fieldValueCollection[activeCat]===undefined){A.fieldValueCollection[activeCat]={}}if(dataProvide==='datepicker'&&mode==='range'){var rangeStart=$('#'+name+'_start').val();var rangeEnd=$('#'+name+'_end').val();rangeStart=typeof rangeStart=='undefined'?'':rangeStart;rangeEnd=typeof rangeEnd=='undefined'?'':rangeEnd;if(rangeStart+rangeEnd!=''){A.fieldValueCollection[activeCat][name]=rangeStart+'..'+rangeEnd}else{A.fieldValueCollection[activeCat][name]=""}}else{A.fieldValueCollection[activeCat][id]=v}A._updateQuery()},updateUI:function(){A=AdvancedSearchBox;A.fieldCollection=[];A.fieldValueCollection={};AccessibleHelpers.SetFocus($('#ablAdvancedForm').find('input:visible, select:visible').eq(0));$('#ablAdvancedQuery').val(A._defaultText);$('#ablAdvancedForm').find('input,select').each(function(){var $e=$(this),mode=($e.data('mode')=="exact")?'=':':',method=$e.data('method'),itype=$e.attr('type'),id=$e.attr('id'),dataProvide=$e.attr('data-provide'),dataMode=$e.attr('data-mode'),name=$e.attr('name');if(itype=='hidden'||itype=='checkbox'){return}if(dataProvide==='datepicker'&&dataMode==='range'){if($.grep(A.fieldCollection,function(element){return element.id==name}).length<=0){A.fieldCollection.push({id:name,method:method,mode:mode})}}else{A.fieldCollection.push({id:id,method:method,mode:mode})}});A._updateQuery()},update:function(){if(State.GetCurrentSubPage()==='advancedsearch'){ABL.Log("updating adv search");ABL.Log("Not doing anything ATM")}},_updateQuery:function(){var A=AdvancedSearchBox,i=0,f,v,a=[];var activeCat=$('#advancedsearchcategories li.active').data("advanced-search-category");var activeVals=A.fieldValueCollection[activeCat];if(activeVals){for(i;i<A.fieldCollection.length;i++){f=A.fieldCollection[i];v=activeVals[f.id];if(v&&v.length){a.push(f.method+f.mode+'"'+v+'"')}var n=$.trim(a.join(' '));if(n.length){var queryFormat=$('.advancedsearchcategory.active').data('query-format');$('#ablAdvancedQuery').val(queryFormat.replace('{query}',n))}else{$('#ablAdvancedQuery').val(A._defaultText)}}}else{$('#ablAdvancedQuery').val(A._defaultText)}}}})();ABL.RegisterModule(AdvancedSearchBox);var DiscoveryPane=(function(){function _DiscoveryPane(){}__extends(_DiscoveryPane,Observable);var dropdownOptions=[];var $searchBox;var $searchForm;var $searchButton;var $searchInput;var $searchInputClearButton;var _inDropdown;_DiscoveryPane.prototype=$.extend(_DiscoveryPane.prototype,{init:function(){var DP=DiscoveryPane;$searchBox=$('#searchbox');$searchForm=$searchBox.find('#ablSearchform');$searchButton=$searchBox.find('#ablSearch');$searchInput=$searchBox.find('#ablQuery');$searchInputClearButton=$searchBox.find('.search-clear');dropdownOptions=$searchForm.find('.search-preselection').find('a').map(function(i,el){return $(el).text()});State.Observe('q').subscribe(DP.UpdateQueryBox.bind(DP));DP.UpdateQueryBox();$searchForm.on('click','.search-icon',function(){$searchForm.submit()});$searchForm.submit(function(e){e.preventDefault();DP.DoSearch($(this),null)});$searchInput.on({click:function(){var $this=$(this);if($this.val()!=''){DP.ShowClearButton()}},focus:function(){var $this=$(this);if($this.val()!=''){DP.ShowClearButton()}else{DP.HideClearButton()}},blur:function(){var $this=$(this);if($this.val()==''){DP.HideClearButton()}},keydown:function(e){DP.ShowClearButton()}});$searchInputClearButton.click(function(){DP.HideClearButton()});ABL.Event.bind('abl:page:updated',function(){var dpValues={branch:State.Get('branch'),provider:State.Get('provider')};DP.UpdateQueryBoxDropdown(dpValues);DP.UpdateProviderStyling()})},DoSearch:function($form,stateObject){stateObject=stateObject||{};query=stateObject.q||$("#ablQuery").val();$form=$form||$searchForm;var tempStateObject=$.extend(PageHelpers.GetFormHiddenFieldsObject($form),{q:query},stateObject);tempStateObject["href"]=$form.attr("action");try{Page.Actions.search(tempStateObject)}catch(ex){ABL.LogError(ex)}},ShowClearButton:function(){$searchInputClearButton.removeClass('invisible').find('button').attr('aria-hidden','false')},HideClearButton:function(){$searchInputClearButton.addClass('invisible').find('button').attr('aria-hidden','true');$searchInputClearButton.blur()},UpdateQueryBox:function(){if(State.Get('i_silent')!='true'){$searchInput.val(State.Get('q'))}},GetProviderFromDropdown:function(){var localizedProviderName=$searchForm.find('.search-preselection .search-preselect-text').text();var provider=$searchForm.find('.search-preselection').find('.dropdown-menu a').map(function(){if($(this).text()==localizedProviderName){return $(this).data('providerPrefix')}});if(provider.length)provider=provider[0];else provider='';return ABL.GetProviderFromUrlPrefix(provider)||''},UpdateQueryBoxDropdown:function(optValues){optValues=optValues||{};var hasValue={branch:!$.IsUndefinedOrEmpty(optValues.branch),provider:!$.IsUndefinedOrEmpty(optValues.provider)};var isProviderBranchSearch=hasValue.branch&&hasValue.provider;var isProviderSearch=!hasValue.branch&&hasValue.provider;var isBranchSearch=hasValue.branch&&!hasValue.provider;var $providerSelectionText=$searchForm.find('.search-preselection').find('.search-preselect-text');var currentDropdownText=$providerSelectionText.text();var providerText=Localization.Trans('btn-searchprovider-'+optValues.provider);var branchText=optValues.branch!=""?Localization.TransBranch(optValues.branch):providerText;var updateDropdownText=function(text){if($.inArray(text,dropdownOptions)>-1){$providerSelectionText.text(text)}else{ABL.LogWarning("Tried to set dropdown to text that is not valid: "+text)}};$searchForm.attr('action',ABL.GetBaseUrl(optValues.provider));if(!isProviderSearch&&hasValue.branch){$searchForm.append('<input type="hidden" name="branch" value="'+optValues.branch+'"/>')}else{$searchForm.find('input[name="branch"]').remove();$searchForm.append('<input type="hidden" name="branch" value=""/>')}if(isProviderSearch){updateDropdownText(Localization.Trans('btn-searchprovider-'+optValues.provider))}if(isProviderBranchSearch||isBranchSearch){updateDropdownText(branchText)}},UpdateProviderStyling:function(optProvider){var provider=optProvider||State.Get('provider');var classNames=$("body").attr('class');if(typeof classNames!='undefined'){classNames=classNames.split(' ');for(var i=0;i<classNames.length;i++){if(classNames[i].indexOf('provider-')==0){classNames[i]="provider-"+provider}}$('body').removeClass().addClass(classNames.join(' '))}}});function onProviderUpdate(p){p=p||State.Get("provider");var providerSettings=State.Settings.Get("providers");var haveAdvSearch=providerSettings[p].advSearchEnabled;var $btngroup=$searchButton.parents(".btn-group");if(haveAdvSearch){$btngroup.removeClass("hide-options");$searchBox.find('.btn-advancedsearch').fadeIn()}else{$btngroup.addClass("hide-options");$searchBox.find('.btn-advancedsearch').fadeOut()}var $link=$("a.btn-advancedsearch");var href=$link.attr("href");href=ABL.GetBaseUrl(p)+"advancedsearch"+URI.asURI(href).toString(true,true,true,false,false);$link.attr("href",href)}var result=new _DiscoveryPane;result.Observe().subscribe(onProviderUpdate);ABL.Event.bind("abl:page:updated",function(){onProviderUpdate()});return result})();ABL.RegisterModule(DiscoveryPane);var GoogleBooks={_config:{},init:function(){var G=GoogleBooks,C=G._config;var _gbSettings=State.Settings.Get('googlebooks');if(_gbSettings){if(_gbSettings.info){C.info=true;if(_gbSettings.fallbacktosearchurl){C.fallbacktosearchurl=_gbSettings.fallbacktosearchurl}}if(_gbSettings.preview){C.preview=true}}},info:function(url,infoSelector,previewSelector){$.getJSON(url,function(data){var G=GoogleBooks,C=G._config,k,v,info,preview,$sel=$(infoSelector),enable=false;for(k in data){v=data[k];if(C.info&&v.info_url){enable=true;var $infoLink=($('<a class="googlebooks-info"/>').attr({href:v.info_url,target:'_blank',rel:'external'}).html(Localization.Trans('googlebooks-infolink')));$(infoSelector).html($infoLink).show();PageHelpers.SetContainerVisible($(infoSelector))}if(C.preview&&(v.preview!="noview")){enable=true;var preview_text=null;switch(v.preview){case'partial':preview_text=Localization.Trans('googlebooks-preview-partial');break;case'full':preview_text=Localization.Trans('googlebooks-preview-full');break}var $previewLink=$('<a class="googlebooks-preview"/>').attr({href:v.preview_url,target:'_blank',rel:"external"}).text(preview_text).prepend($('<i class="fa fa-google fa-inverse google-books-icon"></i>'));$(previewSelector).html($previewLink).show();PageHelpers.SetContainerVisible($(previewSelector))}}if(C.info&&C.fallbacktosearchurl&&!enable){var directLink=C.fallbacktosearchurl+"&q="+encodeURIComponent($("#fullrecordContainer").data("title"));$sel.replaceWith("<a href='"+directLink+"' target='_blank' rel='external'>"+Localization.Trans('googlebooks-search-fallback')+"</a>");$sel.show()}})}};ABL.RegisterModule(GoogleBooks);var LibraryThing={_config:{},init:function(){var L=LibraryThing,C=L._config;var _ltSettings=State.Settings.Get('librarything');if(_ltSettings){if(_ltSettings.showcopies){C.showcopies=true}if(_ltSettings.showrating){C.showrating=true}if(_ltSettings.showreviews){C.showreviews=true}}},info:function(url,selector,callback){$.getJSON(url,function(data){var L,C,LT_data,link,rating_image,display,obj_id,haveData=false;var $target=$(selector);var hideIfEmpty=$target.data('hide-if-empty');if(data){L=LibraryThing,C=L._config;for(obj_id in data){LT_data=data[obj_id];C.data=LT_data;var href=LT_data.link;if(State.Get('uilang')=='nl'){href=href.replace('www.librarything.com','www.librarything.nl')}else if(State.Get('uilang')=='fr'){href=href.replace('www.librarything.com','www.librarything.fr')}else if(State.Get('uilang')=='de'){href=href.replace('www.librarything.com','www.librarything.de')}else if(State.Get('uilang')=='es'){href=href.replace('www.librarything.com','www.librarything.es')}link=$("<a>").attr({href:href,target:'_blank',rel:'external'});rating_image=$("<img>").attr({src:LT_data.rating_img});display=false;if(C.showreviews&&LT_data.reviews!=0){if(LT_data.reviews==1){link.append(Localization.Trans('lt-1-reviewed')+' ')}else if(LT_data.reviews>1){link.append(Localization.Trans('lt-x-reviewed',LT_data.reviews)+' ')}display=true}if(C.showcopies&&LT_data.copies>0){if(LT_data.reviews!=0){link.append('; ')}link.append(Localization.Trans('lt-owned-by-x-members',LT_data.copies)+' ');display=true}if(C.showrating&&LT_data.rating_img){link.append(rating_image);display=true}if(display){$target.append(link);haveData=true;PageHelpers.SetContainerVisible($target)}}}if(haveData&&hideIfEmpty){$target.parent().find(".spinner").remove();$target.parent().prev(".fullrecord-title").show();if(jQuery.isFunction(callback)){callback()}}else if(hideIfEmpty){ABL.FullRecord.BlockManager.RemoveBlock($target.parents(".fullrecord-block"))}})}};ABL.RegisterModule(LibraryThing);var Userstats={_supportsPerf:false,_config:{},_storedState:{},active:false,init:function(){var U=Userstats;U._supportsPerf='performance'in window&&'getEntriesByName'in window.performance;if(U._supportsPerf&&'timing'in window){U._config=State.Settings.Get('timings');if(U._config&&U._config.active){U.active=true;ABL.Event.bind('abl:page:updated',function(){U.storeState()});ABL.Event.on('abl:page:unload',function(){U.sendPageStats(U._storedState)});$(window).on('unload',function(){U.sendPageStats(U._storedState)})}}},sendPageStats:function(){var U=Userstats;if(Math.random()<=U._config.samplerate){jQuery.each(window.timing.getTimes({simple:true}),function(key,val){U._storedState["t_"+key]=val});if(performance.getEntriesByName("query_input_has_focus").length)window.performance.measure('query_input_has_focus_time','navigationStart','query_input_has_focus');var measurements=window.performance.getEntriesByType('measure');for(var i=0;i<measurements.length;i++){if(measurements[i].name.indexOf('req_')===-1)U._storedState['t_'+measurements[i].name]=measurements[i].duration}}else U._storedState["t_active"]=false;window.performance.clearMarks();window.performance.clearMeasures();U.sendStats(U._storedState)},sendStats:function(obj,urlEndpoint){var U=Userstats;var url=U._config.url+(urlEndpoint||"beacon");var dnt='doNotTrack'in navigator?navigator.doNotTrack:0;obj['s_dnt']=dnt==1?1:0;if(!('s_t'in obj))obj['s_t']=performance.timing.navigationStart+performance.now();obj['s_ua']=navigator.userAgent;if('State'in window&&'Settings'in State){obj['s_dbg']=State.DebugMode();obj['s_sid']=State.Settings.Get('sessionid');obj['s_st']=State.Settings.Get('sitetitle');obj['s_gid']=State.Settings.Get('guid');obj['s_v']=State.Settings.Get('version');obj['s_c']=State.Settings.Get('clusterid')}ABL.LogInfo("Will send usagestats data to:"+U._config.url,obj);var stats=new Blob([JSON.stringify(obj,null,2)],{type:'text/plain'});try{navigator.sendBeacon(url,stats)}catch(e){if('sendBeaconFallback'in navigator)navigator.sendBeaconFallback(url,stats);else ABL.LogError(e)}},storeState:function(state){var s=state||State.AsObject();var U=Userstats;U._storedState={ab_cmd:s.cmd||'',ab_q:s.q||'',ab_pg:s.page||'',ab_a:s.action||'',ab_dim:s.dim.join('|')||'',ab_p:s.provider||'',ab_id:s.itemid||'',ab_cs:s.cs||'',s_t:performance.timing.navigationStart+performance.now()}}};ABL.RegisterModule(Userstats);(function(){function Spinner(){this.id=0}var requestAnimationFrame=(function(){var fn=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60)};return function(callback){fn(callback)}})();Spinner.prototype={Update:function(){var outer=this;var crappyBrowser=!Modernizr.canvas||($.browser.mozilla&&$.browser.version.slice(0,3)*1<2);$('div.spinner').each(function(){if(crappyBrowser){var loaderGif="PageHelpers"in window?PageHelpers.skinAshx("img/loader-white-bg.gif"):"skins/liquid/img/loader-white-bg.gif";$(this).html("<img src='"+loaderGif+"' />");return}if(!$(this).find('canvas').size()){outer.id+=1;$("<canvas width='100' height='100' id='spinner"+outer.id+"'></canvas>").appendTo(this)}});if(crappyBrowser){return}var $canvasList=$('.spinner canvas');var currentMaster=this.masterCanvas;this.ctxClones=[];if(this.masterCanvas&&!this._IsCanvasAttached(this.masterCanvas)){this.masterCanvas=null}for(i=0;i<$canvasList.size();i++){if(i==0&&!this.masterCanvas){this.masterCanvas=$canvasList.get(i)}else{var ctx=$canvasList.get(i).getContext("2d");this.ctxClones.push(ctx)}}return currentMaster!==this.masterCanvas},_Reset:function(){},_AllDetached:function(){if(this.masterCanvas!=null&&this._IsCanvasAttached(this.masterCanvas)){return false}for(var i=0;i<this.ctxClones.length;i++){if(this._IsCanvasAttached(this.ctxClones[i].canvas)){return false}}return true},_IsCanvasAttached:function(canvasDomObject){if(!canvasDomObject){return false}while((canvasDomObject=canvasDomObject.parentNode)){if(canvasDomObject==document){return true}}return false},Start:function(){var i;if(!this.Update()){return}if(!this.masterCanvas){return}var outer=this;var ctx=this.masterCanvas.getContext("2d");var startX=50,startY=50;var PI=Math.PI;ctx.translate(startX,startY);ctx.globalCompositeOperation="destination-out";this._Reset();ctx.save();this._Reset=function(){ctx.restore()};function Circle(){this.x=startX+this.radius;this.y=startY+this.radius};Circle.prototype={draw:function(){ctx.save();ctx.globalCompositeOperation="source-over";ctx.globalAlpha=1;ctx.fillStyle="rgb("+this.fillStyle[0]+","+this.fillStyle[1]+","+this.fillStyle[2]+")";ctx.rotate(-this.angle);ctx.beginPath();ctx.arc(this.x,this.y,this.radius,0,2*PI);ctx.closePath();ctx.fill();ctx.restore()},fillStyle:[235,235,235],radius:25,x:0,y:0,angle:0,clone:function(){var result=new Circle;result.fillStyle=this.fillStyle;result.x=this.x;result.y=this.y;result.radius=this.radius;return result}};function Model(){}Model.prototype={Members:[],draw:function(){for(var i=0;i<this.Members.length;i++){this.Members[i].draw()}}};function AnimateModel(model,interval,time,updateModel,stop){var startTime=(new Date).getTime();var frameCount=0;var ourMasterCanvas=outer.masterCanvas;stop=stop||$.noop;var handler=function(){if(!outer.masterCanvas||outer.masterCanvas!==ourMasterCanvas){stop();return}frameCount+=1;if(frameCount%80==0){if(outer._AllDetached()){stop();return}}updateModel();ctx.fillStyle="pink";ctx.globalAlpha=0.14;ctx.fillRect(-startX,-startY,outer.masterCanvas.width+startX,outer.masterCanvas.height+startY);model.draw();var imgData=ctx.getImageData(-startX,-startY,outer.masterCanvas.width+startX,outer.masterCanvas.height+startY);for(var i=0;i<outer.ctxClones.length;i++){outer.ctxClones[i].putImageData(imgData,-startX,-startY)}if(time<0||((new Date).getTime()-startTime-interval)<time){requestAnimationFrame(handler)}};handler()}var circler=function(_c,arcStart){var rDir=1;var xDir=-1;var cDir=1;var start=_c.x;var red=_c.fillStyle[0],green=_c.fillStyle[1],blue=_c.fillStyle[2];var redStart=red;var r=23;var radDir=1;var arc=arcStart||0;var x=_c.x;y=_c.y;return function(){if(_c.radius<=4||_c.radius>=10){if(_c.radius<4){_c.radius=4}else if(_c.radius>10){_c.radius=10}rDir=-rDir}if(red>=255||red<=redStart){if(red>=255){red=255}else{red=redStart}cDir=-cDir}red=redStart;green=red;blue=red;_c.radius+=rDir*0.1;_c.angle=arc;arc-=0.06;_c.fillStyle=[red,green,blue]}};var circle=new Circle;circle.radius=10;circle.x=20;circle.y=20;var model=new Model;(function(){var otherCircle,updaterList=[];for(var i=0;i<4;i++){otherCircle=circle.clone();otherCircle.radius=10-i*2;model.Members.push(otherCircle);updaterList.push(circler(otherCircle,i+1))}AnimateModel(model,13,-1,function(){for(var i=0;i<updaterList.length;i++){updaterList[i]()}})})()}};var spinner=new Spinner;var readyRun=$.isFunction($.readyRun)?$.readyRun:$(document).ready;readyRun(function(){spinner.Start();if(typeof ABL!=="undefined"){ABL.Event.on('abl:page:updated abl:page:spinner',function(){spinner.Start()})}else{$(document).on("abl:page:spinner",function(){spinner.Start()})}})})();(function(){function GetScroll(info,isLeft){var $content=info.content;var $scroller=info.scroller;var $enabledItem=$content.find('.scroll-item.enabled');$enabledItem=isLeft?$enabledItem.filter(":first"):$enabledItem.filter(":last");var $targetItem=isLeft?$enabledItem.prev():$enabledItem.next();if(!$targetItem.size()){return 0}var $leftBtn,$rightBtn;$leftBtn=info.leftButton;$rightBtn=info.rightButton;var $lastItem=info.lastItem;var $firstItem=info.firstItem;buttonWidth=info.buttonWidth||0;var _scroll,delta;if(isLeft){_scroll=$rightBtn.offset().left+($rightBtn.width()-buttonWidth)-$targetItem.offset().left-$targetItem.width();delta=$firstItem.offset().left+_scroll-$leftBtn.offset().left-buttonWidth;if(delta>0){_scroll-=delta}}else{_scroll=$targetItem.offset().left-$leftBtn.offset().left-buttonWidth;delta=$rightBtn.offset().left+($rightBtn.width()-buttonWidth)-($lastItem.offset().left+$lastItem.width()-_scroll);if(delta>0){_scroll-=delta}}_scroll=Math.max(0,_scroll);return isLeft?-_scroll:_scroll}function CheckEnable(info,isLeft){var $content=info.content;var $scroller=info.scroller;var $btn=info.activeButton;function _enable($el,enable){if(enable){$el.addClass('enabled')}else{$el.removeClass('enabled')}}if(isLeft){_enable($btn,GetScroll(info,true)<0);_enable($btn.siblings('.scroll-button'),GetScroll(info,false)>0)}else{_enable($btn,GetScroll(info,false)>0);_enable($btn.siblings('.scroll-button'),GetScroll(info,true)<0)}}function CheckItemsVisible(info){var $leftBtn,$rightBtn;$leftBtn=info.leftButton;$rightBtn=info.rightButton;buttonWidth=info.buttonWidth;var left=$leftBtn.offset().left;var right=$rightBtn.offset().left+$rightBtn.width();info.content.find(".scroll-item").each(function(){var $this=$(this);var enable=true;if(enable&&$this.offset().left<left){enable=false}if(enable&&$this.offset().left+$this.width()>right){enable=false}if(enable){$this.addClass('enabled')}else{$this.removeClass('enabled')}})}function GetScrollerInfo($btn){if($btn.size()){var info={content:$btn.siblings('.scroll-content'),scroller:$btn.parent('.scroller')};info.buttonWidth=info.content.data('buttonWidth');info.lastItem=info.content.find('.scroll-item:last');info.firstItem=info.content.find('.scroll-item:first');info.leftButton=info.scroller.find(".scroll-button.left");info.rightButton=info.scroller.find(".scroll-button.right");info.activeButton=$btn;return info}return null}function Init($btn){if($btn.size()){var info=GetScrollerInfo($btn);var $content=info.content;var $scroller=info.scroller;var w;info.buttonWidth=$content.position().left;$content.data('buttonWidth',info.buttonWidth);w=0;$content.find(".scroll-item").each(function(){w+=$(this).outerWidth(true)});if(w>$content.width()){$content.css({width:w})}CheckItemsVisible(info);CheckEnable(info,$btn.hasClass('left'))}}$(document).on('abl:fullrecord:blockinit','.fullrecord-block',function(){var $btn=$(this).find('.scroll-button.right');Init($btn)});ABL.Event.bind('abl:results:updated',function(){$('.scroll-button.right').each(function(){Init($(this))})});$(document).on('keydown','.scroller',function(e){if(e.keyCode==9){var $target=$(e.target);var $parent=$target.is('.scroll-item')?$target:$target.parents('.scroll-item').eq(0);if(e.shiftKey&&$parent.prev().length&&!$parent.prev().hasClass('enabled')){$parent.parents('.scroller').find('.scroll-button.left').trigger('click')}if(!e.shiftKey&&$parent.next().length&&!$parent.next().hasClass('enabled')){$parent.parents('.scroller').find('.scroll-button.right').trigger('click')}}});$(document).on('click','.scroll-button',function(e){e.preventDefault();e.stopPropagation();var $btn=$(this);var info=GetScrollerInfo($btn);if(!$btn.hasClass('enabled')){return}var $content=info.content;var $scroller=info.scroller;if($scroller.hasClass("scrolling")){$scroller.data("scroll-pending-clicks",($scroller.data("scroll-pending-clicks")||0)+1);return}var isLeft=$btn.hasClass('left');var scroll=GetScroll(info,isLeft);if(scroll==0){return}$scroller.addClass("scrolling");$btn.siblings('.scroll-button').addClass('enabled');$content.animate({left:$content.position().left-scroll},{duration:700,easing:"easeInOutCubic",step:function(){CheckItemsVisible(info)},complete:function(){CheckEnable(info,isLeft);CheckItemsVisible(info);$scroller.removeClass("scrolling");if($btn.hasClass("enabled")&&$scroller.data("scroll-pending-clicks")>0){$scroller.data("scroll-pending-clicks",$scroller.data("scroll-pending-clicks")-1);$btn.trigger("click")}else{$scroller.data("scroll-pending-clicks",0)}}})});$('.scroll-button').on('dblclick',function(e){e.preventDefault();e.stopPropagation()})})();$("a.xml-element-name").on("click",function(e){e.preventDefault();var $this=$(this);var $parent=$this.parent().parent();if($parent.hasClass('xml-collapse')){$parent.removeClass('xml-collapse')}else{$parent.addClass('xml-collapse')}});$(document).on('show','.tab-control .accordion-group',function(e){var target=$(e.target);var jThis=$(this);if(target.hasClass('accordion-toggle')||target.hasClass('accordion-body')){jThis.parent().find('.accordion-body.in').collapse('hide');jThis.parent().find('.accordion-heading.active').removeClass('active')}jThis.find('.accordion-heading').addClass('active');if(target.hasClass("accordion-body")){var activeTabs=target.find("li.active a");if(activeTabs.length>0){activeTabs.first().parent().removeClass('active');activeTabs.first().tab('show')}else{target.find("li a").first().tab('show')}}});$(document).on('hide','.tab-control .accordion-group',function(e){$(this).find('.accordion-heading').removeClass('active')});function RecordSelectionModule(){this._resultWindow=null;this._shown=false;this._maxRequests=10;this._items=[];this._sortMethods=['TITLE','AUTHOR','PROVIDER'];this._sortMethod='TITLE';this._$detailsContainer=$('<div id="recordselection-details-container"/>');this._gajson;this._xhr}RecordSelectionModule.prototype={Initialize:function(state){var rs=RecordSelection;this._gajson=$("#recordSelectionAction").data("ga-request");var that=this;$(document).on('click','#recordSelectionShow',function(e){e.preventDefault();RecordSelection.Show()});$(document).on('click','#recordSelectionClear',function(e){e.preventDefault();RecordSelection.Clear(Localization.Trans('recordselection-confirm-clear'))});$(document).on('click','.recordselection-remove-action',function(e){e.preventDefault();var id=$(this).data('extid');RecordSelection.RemoveFromStorage(id)});$(document).on('click','.recordselection-detail-action',function(e){e.preventDefault();var $btn=$(this);var id=$btn.data('extid');var provider='main';var extIdMatch=/\|([^\/]+)\/([^\|]+)\|/.exec(id);var activeProviders=$.map(State.Settings.Get('providers'),function(obj,key){return key});if(extIdMatch&&extIdMatch.length>2){if(extIdMatch[1].toLowerCase()==='universal'){provider=extIdMatch[2]}if(id.indexOf('CDR')>-1&&$.inArray(activeProviders,"muziekweb"))provider="muziekweb";if(provider==="sru"&&$.inArray(activeProviders,"landelijk"))provider="landelijk"}var takeAction=function(id,provider){var href=State.Settings.Get("applicationpath")+ABL.GetProviderUrlPrefix(provider);Page.Actions.detail({itemid:id,cs:'recordselection-details',provider:provider,href:href})};if(provider==='landelijk'){var url=State.Settings.Get("applicationpath")+'api/v1/details/';var btnText=$btn.text();var loaderGif="PageHelpers"in window?PageHelpers.skinAshx("img/loader-color-bg.gif"):"skins/liquid/img/loader-color-bg.gif";$btn.html("<img src='"+loaderGif+"' />");var o={id:id,output:'json',detaillevel:'basic'};$.ajax({url:url,method:'GET',cache:true,data:o,global:false,headers:{Authorization:'Bearer '+State.Get('recordselection')['authorization']},traditional:true,dataType:'json'}).done(function(data){$btn.html(btnText);if(data.record.titles){takeAction(id,'')}else{takeAction(id,'landelijk')}}).fail(function(err){ABL.LogError(err);$btn.html(btnText);takeAction(id,'landelijk')})}else{takeAction(id,provider)}});$(document).on('click','.recordselection-details-sort',function(e){e.preventDefault();that._sortMethod=$(this).data('sortmethod');ABL.Event.trigger('abl:recordselection:updated')});ABL.Event.bind('abl:results:updated',function(data){PageHelpers.FixElement.Register($(".statusbar-wrapper"))});ABL.Event.bind('abl:recordselection:detail:shown',function(data){rs.AddActions()});ABL.Event.bind('abl:page:updated',function(data){rs.AddActions();rs.UpdateRecords();rs.UpdateFeedback(true)});ABL.Event.bind('abl:recordselection:updated',function(){rs.UpdateRecords();rs.UpdateFeedback(true);if(that._shown)rs._RenderDetails()});$('#ablContent').on('click','.record-selection-toggle',function(){var $el=$(this),extid=$el.attr('id');ABL.LogInfo('Record selected: '+extid);if($el.data('record-selected')!=true){rs.CheckRecord($el);if(extid){rs.AddToStorage(extid)}else{}rs.UpdateFeedback();var r=$(this).closest('.record'),s=$('#recordSelectionCount'),rh=r.height(),rw=r.width(),rp=r.offset(),sh=s.height(),sw=s.width(),sp=s.offset();var b=$('<div />').css({position:'absolute',width:rw,height:rh,border:'1px solid #ffd348',top:rp.top,left:rp.left});b.appendTo('body').animate({top:sp.top,left:sp.left,height:sh,width:sw},function(){$(this).remove()})}else{rs.UncheckRecord($el);rs.RemoveFromStorage(extid);rs.UpdateFeedback()}})},AddActions:function(){var rs=RecordSelection;$('#recordSelectionAction a, .recordselection-details-actions .dropdown-menu a').off('.action').on('click.action keydown.action',function(e){if(e.type==='click'||(e.type==='keydown'&&e.keyCode===13)){e.preventDefault();var $el=$(this),action=$el.data('action'),text=$el.text(),url=$el.attr('href'),type=null;if(action.indexOf("export-")>=0){type=action.substr("export-".length);action="export"}if(window.GA&&rs._gajson){window.GA.Fire($.extend(true,{},rs._gajson),{action:action})}var selection=rs.GetStorage();switch(action){case"email":Email.Plugins.Email.ShowDialog(selection);break;case"sms":Email.Plugins.SMS.ShowDialog(selection);break;case"add-to-list-new":case"add-to-list-existing":case"add-to-list":rs.AddToList(url);break;case"export":rs.Export(type);break;case"remove-all":rs.Clear(Localization.Trans('recordselection-confirm-clear-reset'));break;case"show-all":rs.ShowDetailed();break;case"print":rs.Print();break;default:ABL.Log('Action not found for: ',action);break}}})},UpdateFeedback:function(isPageUpdate){var rs=RecordSelection,$statusbar=$('#statusbar'),$num=$('#recordSelectionCount'),len=rs.GetStorage().length;var lenText=(len===1)?Localization.Trans('recordselection-numitems-single'):Localization.Trans('recordselection-numitems',len);if(len>0){$('#recordSelectionCount').html(lenText);if(isPageUpdate){$statusbar.show()}else{$statusbar.slideDown('fast')}}else{$statusbar.slideUp('fast')}PageHelpers.FixElement.UpdatePosition($statusbar)},UpdateRecords:function(){var rs=RecordSelection;$('.record .record-selection-toggle').each(function(){var e=$(this),extid=e.attr('id');if(jQuery.inArray(extid,rs.GetStorage())!=-1){rs.CheckRecord(e)}else{rs.UncheckRecord(e)}})},CheckRecord:function($el){$el.parents('.record').addClass('record-selected');$el.data('record-selected',true);if($el.hasClass('record-selection-checkbox')){var inputBox=$el.find('input')[0];if(typeof inputBox!='undefined'){inputBox.checked=true}$el.attr('title',Localization.Trans('action-select-remove')).find('span').text(Localization.Trans('action-select-remove'))}else{$el.addClass('active');$el.find('i').attr('class','fa fa-times');$el.find('a').text(Localization.Trans('action-select-remove'))}},UncheckRecord:function($el){$el.parents('.record').removeClass('record-selected');$el.data('record-selected',false);if($el.hasClass('record-selection-checkbox')){var inputBox=$el.find('input')[0];if(typeof inputBox!='undefined'){inputBox.checked=false}$el.attr('title',Localization.Trans('action-select')).find('span').text(Localization.Trans('action-select'))}else{$el.removeClass('active');$el.find('i').attr('class','fa fa-list');$el.find('a').text(Localization.Trans('action-select'))}},AddToStorage:function(extid){var storage=this.GetStorage();storage.push(extid);$.jStorage.set("ABLRecordSelection",storage);$.jStorage.set("ABLStorageSessionID",this.GetSessionID())},GetSessionID:function(){var nameEQ="ASP.NET_SessionId=",ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' '){c=c.substring(1,c.length)}if(c.indexOf(nameEQ)==0){return c.substring(nameEQ.length,c.length)}}return""},RemoveFromStorage:function(extid){var storage=this.GetStorage();var idx=jQuery.inArray(extid,storage);if(idx>=0){storage.splice(idx,1);$.jStorage.set("ABLRecordSelection",storage)}this._items=this._items.filter(function(i){return i.id!=extid});ABL.Event.trigger('abl:recordselection:updated')},ClearStorage:function(){this._items=[];$.jStorage.deleteKey("ABLRecordSelection");ABL.Event.trigger('abl:recordselection:updated')},GetStorage:function(){var sessionID=$.jStorage.get("ABLStorageSessionID",'');if(sessionID==this.GetSessionID()){return $.jStorage.get("ABLRecordSelection",[])}else{this.ClearStorage();return[]}},Clear:function(confirmText){var rs=RecordSelection;if(rs.GetStorage().length==0){return}var sure=confirm(confirmText);if(sure){rs.ClearStorage();rs.UpdateFeedback();rs.UpdateRecords()}},_detailTitleText:function(len){var selection=len?len:RecordSelection.GetStorage().length;return(selection===1)?Localization.Trans('recordselection-numitems-single'):Localization.Trans('recordselection-numitems',selection)},Show:function(){var that=this;Page.Modal.show(RecordSelection._detailTitleText(),that._$detailsContainer,function(){that._shown=true;RecordSelection._RenderDetails(true)},function(){RecordSelection._RemoveDetailsHtml();that._shown=false;ABL.Event.trigger('abl:recordselection:detail:closed')})},_SortDetails:function(){var sortFunction=null;switch(this._sortMethod){case'CLICKED':sortFunction=function(a,b){if(b.error)return 1;return $.inArray(a,RecordSelection.GetStorage())-$.inArray(b,RecordSelection.GetStorage())};break;case'TITLE':sortFunction=function(a,b){if(b.error)return 1;if(a.titles&&a.titles.length>0)return a.titles[0].localeCompare(b.titles[0]);return 1};break;case'AUTHOR':sortFunction=function(a,b){if(b.error)return 1;var authorA=(a.authors&&a.authors.length)?a.authors[0]:Localization.Trans('recordselection-details-no-author');var authorB=(b.authors&&b.authors.length)?b.authors[0]:Localization.Trans('recordselection-details-no-author');return authorA.localeCompare(authorB)};break;case'PROVIDER':sortFunction=function(a,b){if(b.error)return 1;return a.id.localeCompare(b.id)};break}if(sortFunction)this._items.sort(sortFunction)},_RemoveDetailsHtml:function($container){this._$detailsContainer.children().remove();var $header=$('#ablModalHeader').find('.heading').text('')},_RenderDetails:function(showSpinner){var that=this;var selection=RecordSelection.GetStorage();RecordSelection._RemoveDetailsHtml();var $header=$('#ablModalHeader');$header.find('.heading').text(RecordSelection._detailTitleText(selection.length));if(showSpinner)that._$detailsContainer.append('<span class="spinner recordselection-details-spinner" ><img src="~/assets/resources/img/loader-white-bg.gif" alt="" /></span>');var _renderItems=function($container){var $itemListContainer=$('<ul id="recordselection-details" class="media-list"/>');RecordSelection._SortDetails();if(that._items.length==0){$container.append("<div class='no-results'>"+Localization.Trans("recordselection-details-empty")+"</div>");return}$.each(that._items,function(idx,item){$itemListContainer.append(item.$item)});var $actions=$('<div class="recordselection-details-actions btn-group"/>').appendTo($container);var $actionsSort=$('<div class="recordselection-details-sort-actions btn-group"/>').appendTo($container);$('<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">'+Localization.Trans('recordselection-details-action')+'<span class= "caret"></span></a>').appendTo($actions);$('<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">'+Localization.Trans('recordselection-details-action-sort')+'<span class= "caret"></span></a>').appendTo($actionsSort);var $menu=$('<ul class="dropdown-menu"/>').appendTo($actions);var $sortMenu=$menu.clone().appendTo($actionsSort);var showMessage=Localization.Trans('recordselection-details-action-showall')+(selection.length>50?' '+Localization.Trans('recordselection-details-action-showall-warning'):'');var deleteMessage=Localization.Trans('recordselection-details-action-removeall');$menu.append('<li><a href="#" class="recordselection-details-removeall" data-action="remove-all">'+deleteMessage+'</a></li>');$('#recordSelectionDropdown').siblings('.dropdown-menu').find('li').each(function(idx,el){var $clonedOption=$(el).clone();$menu.append($clonedOption)});$.each(that._sortMethods,function(idx,method){$sortMenu.append('<li><a href="#" class="recordselection-details-sort" data-sortmethod="'+method+'">'+Localization.Trans('recordselection-details-action-sort-'+method)+'</a></li>')});$container.append($itemListContainer);ABL.Event.trigger('abl:recordselection:detail:shown')};var _addContent=function(name,item,$container,prefix){var content=item[name];if(content){if($.isArray(content)){$.each(content,function(i,c){var separateClass='';if(i<content.length-1)separateClass=' by-comma';$container.append('<span class="'+name+separateClass+'">'+(prefix?prefix:'')+c+'</span>')})}else{$container.append('<span class="'+name+' item-content">'+(prefix?prefix:'')+content+'</span>')}}};var extIdsPerProvider={catalog:[]};var tempItemCollection=[];$.each(this._items,function(idx,item){if($.inArray(item.id,selection)!=-1){tempItemCollection.push(item)}else{ABL.LogInfo('recsel, removing item from cache: '+item.id)}});this._items=tempItemCollection;var activeProviders=$.map(State.Settings.Get('providers'),function(obj,key){return key});$.each(selection,function(idx,extid){var extIdMatch=/\|([^\/]+)\/([^\|]+)\|/.exec(extid);if(extIdMatch&&extIdMatch.length>2){if(extIdMatch[1].toLowerCase()==='universal'){var universalProvider=extIdMatch[2];if(extid.indexOf('CDR')>-1&&$.inArray(activeProviders,"muziekweb"))universalProvider="muziekweb";if(universalProvider==="sru"&&$.inArray(activeProviders,"landelijk"))universalProvider="landelijk";if(extIdsPerProvider[universalProvider]){extIdsPerProvider[universalProvider].push(extid)}else{extIdsPerProvider[universalProvider]=[extid]}}else{extIdsPerProvider.catalog.push(extid)}}else{extIdsPerProvider.catalog.push(extid)}});var requests=[];$.each(extIdsPerProvider,function(provider,extids){var actualIdsToRetrieve=[];$.each(extids,function(idx,extid){if(!that._items.find(function(i){return i.id===extid}))actualIdsToRetrieve.push(extid)});var chunkedIds=$.Chunk(actualIdsToRetrieve,that._maxRequests);var url=State.Settings.Get("applicationpath")+(provider==='catalog'?'':(provider+'/'))+'api/v1/search/';jQuery.each(chunkedIds,function(idx,chunk){var o={id:chunk,q:'special:list',output:'json',pagesize:that._maxRequests,detaillevel:'basic'};var dfd=$.Deferred();if(chunk.length>0){setTimeout(function(){$.ajax({url:url,method:'GET',cache:true,data:o,global:false,headers:{Authorization:'Bearer '+State.Get('recordselection')['authorization']},traditional:true,dataType:'json'}).done(function(data){that._items=that._items.concat(data.results);dfd.resolve('OK')}).fail(function(err){var errorItems=that._items.filter(function(i){return i.error});var errorItem={};if(errorItems.length){errorItem.itemsMissing=(errorItems[0].itemsMissing||[]).concat(chunk);errorItem.titles=[Localization.Trans('recordselection-details-retrieve-error',errorItems[0].itemsMissing.length)];errorItem.error=errorItems[0].error.concat(err)}else{errorItem={id:'error',titles:[Localization.Trans('recordselection-details-retrieve-error',chunk.length)],error:[err],itemsMissing:chunk};that._items.push(errorItem)}dfd.resolve('ERROR')})},requests.length*400);requests.push(dfd.promise())}})});$.when.apply($,requests).always(function(data){that._$detailsContainer.find('.recordselection-details-spinner').hide();$.each(that._items,function(idx,item){var $item=$('<li class="recordselection-detail-item media"/>');item.$item=$item;var $imgContainer=$('<div class="coverimage-container media-object pull-left" />').appendTo($item);var $img=$('<img class="coverimage" />').appendTo($imgContainer);if(item.coverimages&&item.coverimages.length){$img.attr('src',item.coverimages[0])}else if(item.error){$img.attr('src','~/assets/resources/img/icon-error.png').attr('style',"height:35px;")}else{$img.attr('src','~/assets/resources/img/cover.png')}$item.attr('data-extid',item.id);var $body=$('<div class="media-body"/>').appendTo($item);var title=item.titles&&item.titles.length?item.titles[0]:Localization.Trans('recordselection-details-no-title');$body.append('<h4 class="media-heading">'+title+'</h4>');if(item.error){return true}var $description=$('<div class="media-description separate"/>').appendTo($body);_addContent('authors',item,$description);if(item.authors&&item.authors.length>0&&item.publisher&&item.publisher.length>0)$description.append('<span class="sep-pipe"></span>');_addContent('publisher',item,$description);_addContent('isbn',item,$description,'ISBN: ');var $buttonContainer=$('<p class="recordselection-detail-actions"/>').appendTo($description);$buttonContainer.append('<a class="details-item recordselection-detail-action btn btn-mini btn-primary" href="'+item.detailLink+'" data-extid="'+item.id+'" >'+Localization.Trans('recordselection-details-action-details')+'</a>');$buttonContainer.append('<a class="remove-item recordselection-remove-action btn btn-mini btn-link btn-danger" data-extid="'+item.id+'"><i class="fa fa-times"></i> '+Localization.Trans('recordselection-details-action-remove')+'</a>')});_renderItems(that._$detailsContainer)})},ShowDetailed:function(recordsPerPage){var requestObj={q:'special:selection',cs:'selection',itemid:this.GetStorage(),href:ABL.GetBaseUrl()};if(typeof recordsPerPage!='undefined'){requestObj['i_recsperpage']=recordsPerPage}Page.Actions.search(requestObj)},Print:function(){if(!this._shown){ABL.Event.one('abl:recordselection:detail:shown',function(){ABL.LogInfo('hiding abl content for printing (would do it on window.beforePrint etc, but that has very buggy browser support');$('#ablContent').hide();window.print();setTimeout(function(){$('#ablContent').show()},300)});RecordSelection.Show()}else{ABL.LogInfo('hiding abl content for printing (would do it on window.beforePrint etc, but that has very buggy browser support');$('#ablContent').hide();window.print();setTimeout(function(){$('#ablContent').show()},300)}},Export:function(type,extension){var rs=RecordSelection;var selection=rs.GetStorage();var typeObject=State.Settings.Get('recordselection')['export-'+type];if(typeof typeObject!='undefined'){if(type=="text"){extension="txt"}if(typeObject["extension"]){extension=typeObject["extension"]}}if(!rs._shown){ABL.Event.one('abl:recordselection:detail:shown',function(data){var o={filename:'export.'+extension,items:rs._items,type:'text/plain'};rs._SendData(o)});rs.Show()}else{var o={filename:'export.'+extension,items:rs._items,type:'text/plain'};rs._SendData(o)}},_SendData:function(data){var textContent="";var _addContent=function(name,item,title){var val=item[name],content="";if(val){if($.isArray(val)){$.each(val,function(i,c){var sep='';if(i<content.length-1)sep=', ';content+=sep+c})}else{content=val}if(title){content=title+": "+content}return content+'\r\n'}return""};$.each(data.items,function(idx,item){textContent+=_addContent('titles',item);textContent+=_addContent('authors',item);textContent+=_addContent('publisher',item);textContent+=_addContent('isbn',item,"ISBN");textContent+=_addContent('detailLink',item,"URL");textContent+='\r\n';textContent+='--------------';textContent+='\r\n'});var file=new Blob([textContent],{type:data.type});if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveOrOpenBlob(file,data.filename);else{var a=document.createElement("a"),url=URL.createObjectURL(file);a.href=url;a.download=data.filename;document.body.appendChild(a);a.click();setTimeout(function(){document.body.removeChild(a);window.URL.revokeObjectURL(url)},0)}},_CreateFormHiddenFields:function(o){var result="";for(var k in o){if(o[k]instanceof Array){for(var q in o[k]){result+="<input type='hidden' name='"+k+"' value='"+o[k][q]+"' />\n"}}else{result+="<input type='hidden' name='"+k+"' value='"+o[k]+"' />\n"}}return result},AddToList:function(url){var selection=RecordSelection.GetStorage();var data={id:selection,catalog:('https:'==location.protocol?'https://':'http://')+encodeURI(window.location.hostname)};$("body").append("<form method='POST' id='addToListForm' target='_blank' action='"+url+"'>"+RecordSelection._CreateFormHiddenFields(data)+"</form>");$('#addToListForm').submit().remove()},HandleReset:function(state){RecordSelection.Clear(Localization.Trans('recordselection-confirm-clear-reset'))},HandlePreSearch:function(){if(State.Get('q').indexOf('special:selection')>=0){State.Set('itemid',RecordSelection.GetStorage());State.Settings.Set("undup",false)}else{State.Settings.Set("undup",true)}},HandlePreNav:function(){RecordSelection.HandlePreSearch()}};ABL.RegisterLegacyModule("RecordSelection",RecordSelectionModule);var RefineModule=function(){};RefineModule.prototype={Initialize:function(){var R=Refine;ABL.Event.bind('abl:results:updated',function(){R.UpdateRefineCollapseState()});var updateCollapse=function(){var $this=$(this);var rd=State.Settings.Get('collapseddims');if($.isEmptyObject(rd)||typeof rd==='undefined'){rd=State.Settings.Get('collapseddims')};if($.isEmptyObject(rd)||typeof rd==='undefined'){rd={}}var data=$this.data('rawlbl');var collapsed=$this.hasClass('collapsed');if(typeof data!=='undefined'){rd[data]=collapsed}State.Set('collapseddims',rd)};$(document).on("collapsed expanded",'#refineSidebar .dim',updateCollapse)},UpdateRefineCollapseState:function(){var $dims=$('#refineSidebar .dim');var rd=State.Get('collapseddims');if($.isEmptyObject(rd)||typeof rd==='undefined'){rd=State.Settings.Get('collapseddims')};if($.isEmptyObject(rd)||typeof rd==='undefined'){rd={}}$dims.each(function(){var $dim=$(this);var lbl=$dim.data('rawlbl');if(rd[lbl]===true){$dim.addClass('collapsed');$dim.removeClass('expanded')}else{$dim.addClass('expanded');$dim.removeClass('collapsed')}})},HandlePreSearch:function(){if(!State.Settings.Get('fixaterefinekeys')&&ABL.SearchMethod()!='undup'){this.Reset(false)}},HandleReset:function(){this.Reset(true)},Fixate:function(key){var fk=State.Get('fixatekeys');key=(key).toString();fk.push(key);State.Set('fixatekeys',fk)},Unfixate:function(key){var fkeys=State.Get('fixatekeys');key=(key).toString();var i=jQuery.inArray(key,fkeys);if(i!==-1){delete fkeys[i]}State.Set('fixatekeys',fkeys)},Reset:function(resetFixateKeys){if(resetFixateKeys){State.Set('dim',[""]);State.Set('chain',[]);State.Set('fixatekeys',[])}else{State.Set('chain',State.Get('fixatekeys').slice(0));State.Set('dim',[""])}}};ABL.RegisterLegacyModule("Refine",RefineModule);var FullRefine=(function(){var _pos={top:0,left:0};var _$elem=null;var _jqXHRFullRefine={};var _reqcnt=0;var _$focusedElementBeforeModal={};return{bind:function(){$(document).on('click','#refineFull a.refine-close',function(e){e.preventDefault();FullRefine.close({restoreFocus:true})});$(document).on('click','#refineFull a.full-refine-sort',function(e){e.preventDefault();var href=$(e.target).attr('href');FullRefine.sort(href)});$(document).on('click','#refineSidebar a.more',function(e){e.preventDefault();FullRefine.close();var $elem=$(e.target);var href=$elem.attr('href');FullRefine.show(href,$elem,true);_$focusedElementBeforeModal=$elem})},show:function(href,$elem,anim){var F=FullRefine;var pos;if($elem===null||typeof $elem==='undefined'){pos=pos||_pos}else{pos=$elem.closest('.dim').position();_$elem=$elem}_pos=pos;var url=href;if('abort'in _jqXHRFullRefine&&_jqXHRFullRefine.readyState!=4){_jqXHRFullRefine.abort();ABL.LogInfo('Will abort previous Fullrefine AJAX request aborted, you clickery person!')}var q=$.getQueryStringParams(href);if(Userstats.active)window.performance.mark('req_refine_full_start');_jqXHRFullRefine=$.ajax(url,{global:false});if(Userstats.active){_jqXHRFullRefine.complete(function(){_reqcnt++;window.performance.mark("req_refine_full_end");window.performance.measure('req_refine_full','req_refine_full_start','req_refine_full_end');var m=performance.getEntriesByName("req_refine_full");if(m.length>0){var statsObj={ab_a:'full_refine',ab_dim:q['t_dim'],ab_sort:q['t_method'],ab_q:State.Get('q'),ab_p:State.Get('provider'),ab_req_cnt:_reqcnt,t_ms:m[0].duration};Userstats.sendStats(statsObj)}window.performance.clearMarks("req_refine_full_start");window.performance.clearMarks("req_refine_full_end");window.performance.clearMeasures("req_refine_full")})}_jqXHRFullRefine.fail(function(req,status){F.close();if(status==='abort'){ABL.LogInfo('Hi, I\'m the previous request, and aborted :(');return true}else{LoadingIndicator.showError(req,url)}});_jqXHRFullRefine.done(function(req,status,jqHXR){F.close();var html=$(jqHXR.responseText);html.appendTo('#ablContent');html.css({top:pos.top-7,left:pos.left-2});if(anim){html.fadeIn('fast')}else{html.show()}AccessibleHelpers.TrapTabKeyToElement($('#refineFull'),'.inner a:first');var windowHeight=$(window).height();var refineHeight=$('#refineFull').height();var spaceLeft=Math.max(0,windowHeight-refineHeight);var arbitrarySpacingAboveRefinePopup=100;if(spaceLeft<(refineHeight*0.4)&&(pos.top-$('body').scrollTop())>arbitrarySpacingAboveRefinePopup){$('html, body').animate({scrollTop:Math.max(0,pos.top-arbitrarySpacingAboveRefinePopup)})}$(window).on('resize.fullrefine',function(){pos=_$elem.closest('.dim').position();html.css({top:pos.top-7,left:pos.left-2})});$(document).on('mousedown.fullrefine keyup.fullrefine',function(event){if(event.type=='keyup'&&event.keyCode==27){F.close({restoreFocus:true})}if($(event.target).parents('#refineFull').length||$(event.target).prop('tagName')=="HTML"){event.stopPropagation()}else if(event.type=='mousedown'){F.close({restoreFocus:true})}})})},close:function(options){options=options||{};var anim=(options.anim!==false);var $refElement=$('#refineFull');if($refElement.length){$refElement.attr('id','')}if(anim){$refElement.fadeOut('fast',function(){$(this).remove()})}else{$refElement.hide();$refElement.remove()}$(document).off('.fullrefine');if(options.restoreFocus&&!$.isEmptyObject(_$focusedElementBeforeModal)){_$focusedElementBeforeModal.focus()}},sort:function(href){FullRefine.show(href,null,false)}}})();FullRefine.bind();function UndupModule(){}UndupModule.prototype={Initialize:function(){ABL.Event.on('abl:page:updated',function(){$('.undup-year-popover').popover({html:true,content:function(e){var id=$(this).data('contentId');return $('<ul class="unstyled">'+$(this).parent().find('#'+id).html()+'</ul>')}});$('.undup-year-popover').click(function(e){e.preventDefault()})});$('body').on('click',function(e){$('[data-toggle="popover"]').each(function(){if(!$(this).is(e.target)&&$(this).has(e.target).length===0&&$('.popover').has(e.target).length===0){$(this).popover('hide')}})})},Expand:function(){Page.Actions.undup({undup:false})},Collapse:function(){Page.Actions.undup({undup:true})},SearchKey:function(key){Page.Actions.undupsearch({q:'undup:"'+key+'"',cs:'resultlist'})},HandlePreSearch:function(){if(ABL.SearchMethod()=='undup'||ABL.SearchMethod()=='frabl'){ABL.LogInfo('UNDUP: Found frbr search, setting undup to false');State.Set('undup',false)}else{State.Set('undup',State.Settings.Get('undup'))}}};ABL.RegisterLegacyModule('Undup',UndupModule);var Availability=(function(){var $=window.$;var $availPopupHtml=$("<div id='availabilityPopup'></div>"),$availSearchFormHtml,$originalAvailHtml,spinner="<div class='spinner' />",requestStartTime=0,googleAutocomplete,xhr,xhrId=0;$availPopupHtml.html(spinner);function flashUpdate($el){var currentTime=new Date;if((currentTime.getTime()-requestStartTime)>2000){$el.find('.avail-icon').fadeOut().fadeIn()}}return{retrievedInfo:{},placeholdUrl:{},currentLocation:'',init:function(){var A=Availability;ABL.Event.bind('abl:availability:updated',function(){A.updateLocationAvailability()});$(document).on('click keydown','#availabilityStatic .avail-link',function(e){A.currentLocation=$(this).data('location');if(e.type=='keydown'&&e.keyCode==13){A.showAvailabilityModalPopup();e.preventDefault()}if(e.type=='click'){A.showAvailabilityModalPopup();e.preventDefault()}});$(document).on('click keydown','#availabilityStatic .avail-show-all',function(e){if(e.type=='keydown'&&e.keyCode==13){A.showAvailabilityModalPopup();e.preventDefault()}if(e.type=='click'){A.showAvailabilityModalPopup();e.preventDefault()}});$(document).on('click','.avail-show-all-branches',function(e){e.preventDefault();var $parent=$(this).parents('.availability-info');$parent.find('.full-avail-item.hidden').removeClass('hidden').addClass('shown').filter(':first').addClass('avail-separator');$parent.find('.avail-all-branches-heading').hide();ABL.Event.trigger('abl:availability:showallbranches')});$(document).on('click','#availabilityHolding .avail-holding-more-info, #availabilityHolding .close',function(e){e.preventDefault();var $parent=$(this).parents('.availability-info');var $this=$(this).parents('#availabilityHolding').find('#holding-full-info');var isOpen=$this.hasClass('show');var library=$this.data('ga-library');var gaData=$this.data('ga-request');if(gaData&&'GA'in window){window.GA.Fire(gaData,{library:library,openState:isOpen+''})}$parent.find('#holding-full-info').removeClass('show').addClass('hidden');if(!isOpen){$this.addClass('show').removeClass('hidden')}else{$this.addClass('hidden').removeClass('show')}});ABL.Event.bind("abl:fullrecord:updated",function(){var $avail=$('#availabilityStatic');var showFull=State.Get('c_showfullavail');if(showFull){State.Set('c_showfullavail','')}if($avail.length>0||$('#fullrecord-availability-search').length>0||$avail.data('is-services-only')){A.beginGetAvailabilityData();if(showFull&&$avail.is(':visible')){ABL.Event.one('abl:availability:updated',function(){A.showAvailabilityModalPopup()})}}});ABL.Event.on('abl:availability:fullclose',function(){$('#availabilityFull').show()});ABL.Event.on('abl:searchavailability:updated',function(e){$('#searchAvailability').find('.loader').fadeOut(50);$('#searchAvailability').find('button[type="submit"]').prop("disabled",false)});A.initializeStupidTable();$(document).on('abl:page:unload',function(){if(xhr){try{xhr.abort()}catch(_){}xhr=null}})},initializeStupidTable:function(){if(typeof $.fn.stupidtable!=='undefined'){ABL.Event.on('abl:availability:fullshow',function(e){var $tables=$('.avail-table:has(tr:nth-of-type(2))').stupidtable({year:function(a,b){var re=new RegExp(".*(\\d{4}).*","mgi");return a.replace(re,'$1')-b.replace(re,'$1')}});$tables.addClass("table-sorted");var getSortIcon=function($th){var s=$th.data('sort');var icon='alpha';if(s=='year'||s=='int'){icon='numeric'}return icon};$tables.on('aftertablesort',function(e,data){var $ths=$(this).find("th").removeClass("sorted");var $th=$ths.eq(data.column);var icon=getSortIcon($th);$ths.find(".sort").remove();$ths.filter('[data-sort]').not($th).append('<i class="sort fa fa-sort"></i>');$ths.eq(data.column).append('<i class="sort fa fa-sort-'+icon+'-'+data.direction+'"></i>').addClass("sorted")});$tables.find("th[data-sort]").each(function(){var $th=$(this);if(!$th.has('.sort').length){var icon=getSortIcon($th);$th.append('<i class="sort fa fa-sort"></i>');if($th.hasClass('avail-publication')){$th.stupidsort('desc')}}})})}},beginGetAvailabilityData:function(){if(xhr){try{xhr.abort()}catch(_){}xhr=null}xhrId+=1;var localXhrId=xhrId;var loaderTimeout=setTimeout(function(){$('.availability-info').find('.loader').fadeIn(50)},200);$availPopupHtml.html(spinner);var currentTime=new Date;requestStartTime=currentTime.getTime();var requestString="?";var stateObj=State.AsObject(true);if('page'in stateObj){stateObj.page=''}requestString+=State.AsArgString(stateObj);requestString+='&t_availtype=online';if(Userstats.active)window.performance.mark('req_availability_start');Availability.placeholdUrl={};Availability.retrievedInfo={};xhr=$.ajax({url:ABL.GetBaseUrl()+'availability/'+requestString,global:false}).done(function(data){if(localXhrId!==xhrId){return}$availPopupHtml.html(data);$availSearchFormHtml=$availPopupHtml.find('#searchAvailability').clone();ABL.Log('availability, data: ',Availability.retrievedInfo);ABL.Event.trigger('abl:availability:updated')}).fail(function(jqXHR,status,error){ABL.Event.trigger('abl:availability:error');if(localXhrId!==xhrId){return}$availPopupHtml.html('<span>'+Localization.Trans('avail-retrieve-error')+'</span>');if(State.DebugMode()){$availPopupHtml.append('<span>Error: '+error+'</span>')}}).complete(function(){clearTimeout(loaderTimeout);if(Userstats.active){window.performance.mark('req_availability_end');window.performance.measure('req_availability','req_availability_start','req_availability_end');var m=performance.getEntriesByName("req_availability");if(m.length>0){var statsObj={ab_a:'availability',ab_id:stateObj['itemid'],ab_p:stateObj['provider'],ab_req_cnt:xhrId,t_ms:m[0].duration};Userstats.sendStats(statsObj)}window.performance.clearMarks("req_availability_start");window.performance.clearMarks("req_availability_end");window.performance.clearMeasures("req_availability")}$('.availability-info').find('.loader').fadeOut(50)})},showAvailabilityModalPopup:function(){Page.Modal.show($('#availabilityStatic').data('record-title'),$availPopupHtml,this.onShowFullAvailability,this.onCloseFullAvailability,'large');ABL.Event.trigger("abl:page:spinner")},onCloseFullAvailability:function(){Availability.removeHighlightLocation();ABL.Log('abl:availability:fullclose');ABL.Event.trigger('abl:availability:fullclose')},onShowFullAvailability:function(){Availability.showFullAvailability();ABL.Log('abl:availability:fullshow');ABL.Event.trigger('abl:availability:fullshow')},highlightLocation:function(loc){Page.Modal.Body.find('.avail-item, .full-avail-item').filter(function(index){var location=$(this).data('location')||"";if(location.toLowerCase()===loc.toLowerCase()){$(this).addClass('highlight')}})},removeHighlightLocation:function(){Page.Modal.Body.find('.highlight').filter(function(index){$(this).removeClass('highlight')});Availability.currentLocation=""},updateLocationAvailability:function(){if(typeof Availability.retrievedInfo==='undefined'||$.isEmptyObject(Availability.retrievedInfo)){return}var setAvailStatusClass=function($el,availStatus){var classNames=$el.attr('class').split(" ");var changedClassNames=[];var cnLength=classNames.length;for(var i=0;i<cnLength;i++){if(classNames[i].indexOf('availstatus-')>=0){changedClassNames.push('availstatus-'+availStatus)}else if(classNames[i].indexOf('avail-icon-')>=0){changedClassNames.push('avail-icon-'+availStatus)}else{changedClassNames.push(classNames[i])}}$el.attr('class',changedClassNames.join(' '))};$('#availabilityStatic .avail-item').each(function(idx,el){var $el=$(el);var locData=decodeURI(JSON.parse('"'+$el.find('a').data('location').replace(/"/g,'\\"')+'"'));var availStatus=Availability.retrievedInfo[locData];if(typeof availStatus!=='undefined'){setAvailStatusClass($el,availStatus);setAvailStatusClass($el.find('.avail-icon:first i'),availStatus);if(availStatus=='unknown'){$el.find('.avail-icon span.hidden-text').text(Localization.Trans('avail-show-for'))}else{$el.find('.avail-icon span.hidden-text').text(Localization.Trans('avail-status-'+availStatus)+' '+'in:')}}else{setAvailStatusClass($el,'unknown');setAvailStatusClass($el.find('.avail-icon:first i'),'unknown');$el.find('.avail-icon span.hidden-text').text(Localization.Trans('avail-show-for'))}});flashUpdate($('.avail-items'));if(($('.avail-items .avail-item.availstatus-none:visible').length+$('.avail-items .avail-item.availstatus-notonloan:visible').length+$('.avail-items .avail-item.availstatus-noloaninfo:visible').length)==0){$('#availabilityStatic').find('.heading:first').text(Localization.Trans('detail-unavail'))}if($('#placehold').length===1&&typeof Availability.placeholdUrl!=='undefined'&&Availability.placeholdUrl.length>1){$('.placehold-button-js').attr('href',Availability.placeholdUrl).show()}},showFullAvailability:function(){var A=Availability;if(!$.IsUndefinedOrEmpty(A.currentLocation)&&A.currentLocation!='all'){A.highlightLocation(A.currentLocation);var $locEl=$('.full-avail-item').has('tr.avail-item[data-location="'+A.currentLocation+'"]');if($locEl.length===0){$locEl=$('.full-avail-item[data-location="'+A.currentLocation+'"]')}if($locEl.length){var $body=$(".abl-modal-body");if($locEl.position().top+$locEl.height()>$body.height()){$body.animate({scrollTop:$body.scrollTop()+$locEl.position().top-$locEl.height()})}}}Page.Modal.TrapTabKey()}}})();ABL.RegisterModule(Availability);var Plugins=Plugins||{};Plugins.SoundPlayer=(function(){var p={};var idWithSrc={};var srcWithId={};var soundElementsWithSrc={};var srcWithHowl={};var initialized=false;var playElementsSelector='.play-sound';var soundLoaded=function(){return(!$.isEmptyObject(p.sound)&&('state'in p.sound&&p.sound.state()==='loaded'))};var getElementFromSrcOrId=function(srcOrId){var src,id,$el;id=srcWithId[srcOrId];src=idWithSrc[srcOrId];if(src){$el=soundElementsWithSrc[src]}else{$el=soundElementsWithSrc[srcOrId]}if($el){return $el}ABL.LogInfo('Could not find sound or src: '+srcOrId);return $()};var getHowlFromSrcOrId=function(srcOrId){var h,src;src=idWithSrc[srcOrId];if(typeof id==='undefined'&&typeof src==='undefined'){return srcWithHowl[srcOrId]}return srcWithHowl[src]};var startHandler=function(soundID){var src=this._src;srcWithId[src]=soundID;idWithSrc[soundID]=src;ABL.Log('EVENT: Playing sample ('+soundID+'), src='+src);getElementFromSrcOrId(soundID).addClass('playing')};var stopHandler=function(soundID){ABL.Log('EVENT: Stopped playing sample ('+soundID+')');getElementFromSrcOrId(soundID).removeClass('playing buffering')};var loadHandler=function(){var src=this._src;getElementFromSrcOrId(src).removeClass('buffering');ABL.LogInfo('EVENT: loaded sound src: '+src)};var loadErrorHandler=function(soundID,error){var src=this._src;getElementFromSrcOrId(src).removeClass('buffering playing').addClass('error').find('.error').show();ABL.LogInfo('EVENT: Error loading sound player. ID='+soundID+', error='+error)};p.soundTemplate={format:'mp3',preload:false,html5:true};var playScriptLoaded=function(){try{bindPlayControls();initialized=true}catch(e){initialized=false;throw e;}};var bindPlayControls=function(){$(document).off('.soundplayer');$(document).on('click.soundplayer keydown.soundplayer',playElementsSelector,function(e){p.loadSounds();var src=$(this).data('sound');if(e.type==='keydown'){if(e.keyCode==13||e.keyCode==32){p.playPause(src);e.preventDefault()}}if(e.type==='click'){p.playPause(src);e.preventDefault()}})};p.loadSounds=function(){if(!$.isEmptyObject(soundElementsWithSrc)){return}var i=0;$(playElementsSelector).each(function(){var $this=$(this);var soundSource=$this.data('sound');soundElementsWithSrc[soundSource]=$this;var s=new Howl(jQuery.extend(p.soundTemplate,{src:soundSource}));s.on('end',stopHandler);s.on('play',startHandler);s.on('pause',stopHandler);s.on('stop',stopHandler);s.on('load',loadHandler);s.on('loaderror',loadErrorHandler);srcWithHowl[soundSource]=s;i++});ABL.LogInfo('Loaded '+i+' sounds')};p.init=function(callback){$(document).off('.soundplayer');ABL.Event.on('abl:page:unload',function(){p.reset()});ABL.Event.on('abl:page:updated',function(){if(initialized){}});if('Howler'in window){ABL.LogInfo('Howler is already loaded');playScriptLoaded();if($.isFunction(callback)){callback()}}else{$.cachedScript('https://cdnjs.cloudflare.com/ajax/libs/howler/2.2.3/howler.core.min.js').done(function(){playScriptLoaded();if($.isFunction(callback)){callback()}}).fail(function(){ABL.LogError('HOWL core script could not be loaded.');p.reset()})}};p.reset=function(){ABL.LogInfo('sound.reset()');$.each(srcWithHowl,function(src,howl){if(howl){howl.unload()}});idWithSrc={};srcWithId={};soundElementsWithSrc={};srcWithHowl={}};p.playPause=function(src){var howl=getHowlFromSrcOrId(src);if(typeof howl==='undefined'){ABL.LogWarning('Could not find howl object for '+src);return}if(howl.playing())howl.pause();else p.play(src)},p.play=function(src){if(initialized){var howl=getHowlFromSrcOrId(src);if(howl.state()=='unloaded'){getElementFromSrcOrId(src).removeClass('playing').addClass('buffering');howl.load()}$.each(srcWithHowl,function(src,howl){if(howl){howl.stop()}});howl.play()}};p.stop=function(soundID){if(initialized){var howl=getHowlFromSrcOrId(src);if(howl){howl.stop()}}};return p})();Plugins.SoundPlayer.init();var Plugins=Plugins||{};Plugins.CDR=(function(){var cdr={};var initialized=false;var $nowPlayingElement={};cdr.initPlayer=function(){$(document).off(".cdr");ABL.Event.on('abl:page:unload',function(){cdr.reset()});if('mwplayer'in window){ABL.LogInfo('mwplayer is already loaded');initSuccesful()}else{$.cachedScript('//media.cdr.nl/AUDIO/js/mwplayer.js').done(attachEvents).fail(function(){ABL.LogError('CDR mwplayer script could not be loaded.');cdr.Reset()})}};var initSuccesful=function(){initialized=true;bindPlayControls('.cdr-play-track');$('.cdr-play-track').css({display:'block'})};var attachEvents=function(){ABL.LogInfo('loaded mwplayer, adding addEventListeners');mwplayer.addEventListener('mwPlayerStart',function(titlenumber,tracknumber){var cdrID=titlenumber.titelnummer+'-'+titlenumber.track;$('.cdr-play-track[data-cdr!="'+cdrID+'"]').animate({opacity:0.5},200);ABL.Log('EVENT: Playing sample ('+cdrID+')');$nowPlayingElement=$('.cdr-play-track[data-cdr="'+cdrID+'"]');var gaData=$nowPlayingElement.attr('data-ga-playpause');if(gaData&&'GA'in window){window.GA.Fire(gaData,{action:"play",id:cdrID})}$nowPlayingElement.addClass('playing').removeClass('buffering')});mwplayer.addEventListener('mwPlayerStop',function(titlenumber,tracknumber){var cdrID=titlenumber.titelnummer+'-'+titlenumber.track;ABL.Log('EVENT: Stopped playing sample ('+cdrID+')');$('.cdr-play-track').animate({opacity:1},200);if(!$.isEmptyObject($nowPlayingElement)){var gaData=$nowPlayingElement.attr('data-ga-playpause');if(gaData&&'GA'in window){window.GA.Fire(gaData,{action:"stop",id:cdrID})}$nowPlayingElement.removeClass('playing buffering');$nowPlayingElement={}}else{ABL.LogInfo('mwPlayerStop $nowPlayingElement is empty')}});mwplayer.addEventListener('mwPlayerMessage',function(message){ABL.Log('CDR player event: ',message)});mwplayer.addEventListener('mwProgress',function(titlenumber,tracknumber,progressPerc,timePlayed,timeLeft){});initSuccesful()};var bindPlayControls=function(elementsSelector){$(document).off(".cdr");$(document).on('click.cdr keydown.cdr',elementsSelector,function(e){var $this=$(this);var playPause=function(){var cdrID=$this.data('cdr');var nowPlayingID='';if(!$.isEmptyObject($nowPlayingElement)){nowPlayingID=$nowPlayingElement.data('cdr');if($nowPlayingElement.hasClass('buffering')){ABL.Log('CDR player buffering, stop command ignored');return false}else if($nowPlayingElement.hasClass('playing')){if(cdrID!=nowPlayingID){cdr.play(cdrID)}else{cdr.stop()}}}else{cdr.play(cdrID)}};if(e.type==='keydown'){if(e.keyCode==13||e.keyCode==32){playPause();e.preventDefault()}}if(e.type==='click'){playPause();e.preventDefault()}})};cdr.reset=function(){ABL.LogInfo('cdr.reset()');cdr.stop();$nowPlayingElement={};initialized=false};cdr.play=function(cdrID){if(initialized){var $el=$('.cdr-play-track[data-cdr="'+cdrID+'"]');$el.addClass('buffering');mwplayer.play(cdrID)}};cdr.stop=function(cdrID){if(initialized){mwStop()}};return cdr})();/*
http://blog.patrickmeenan.com/2013/07/measuring-performance-of-user-experience.html / https://gist.github.com/pmeenan/5902672
Strategically place:
markUserTime('some event');
Through your code to get measurements for when various activities complete.  It 
will also generate timeline events so you can see them in Chrome's dev tools.  
A good use case is to add them inline to sections of your site that are 
above-the fold (right after the menu, right after the main story, etc) and also 
in the onload handler for any critical above-the-fold images.
*/
; (function () {
   var w = typeof window != 'undefined' ? window : exports,
      marks = [];
   w.performance || (w.performance = {});
   w.performance.now || (
      w.performance.now = performance.now || performance.webkitNow ||
      performance.msNow || performance.mozNow);
   if (!w.performance.now) {
      var s = Date.now ? Date.now() : +(new Date());
      if (performance.timing && performance.timing)
         s = performance.timing.navigationStart
      w.performance.now = (function () {
         var n = Date.now ? Date.now() : +(new Date());
         return n - s;
      });
   }
   w.performance.mark || (
      w.performance.mark =
      w.performance.webkitMark ? w.performance.webkitMark :
         (function (l) {
            marks.push({ 'name': l, 'entryType': 'mark', 'startTime': w.performance.now(), 'duration': 0 });
         }));
   w.performance.getEntriesByType || (
      w.performance.getEntriesByType =
      w.performance.webkitGetEntriesByType ? w.performance.webkitGetEntriesByType :
         (function (t) {
            return t == 'mark' ? marks : undefined;
         }));
}());
window.markUserTime = function (l) {
   var raf = window['requestAnimationFrame'] ||
      (function (callback) { setTimeout(callback, 0); });
   raf(function () {
      window.performance.mark(l);
      if (window['console'] && console['timeStamp'])
         console.timeStamp(l);
   });
};

/**
 * Timing.js 1.2.0
 * Copyright 2016 Addy Osmani
 * forked: https://github.com/abclassic/timing.js/blob/master/timing.js
 */
(function(window) {
    'use strict';

    /**
     * Navigation Timing API helpers
     * timing.getTimes();
     **/
    window.timing = window.timing || {
        /**
         * Outputs extended measurements using Navigation Timing API
         * @param  Object opts Options (simple (bool) - opts out of full data view)
         * @return Object      measurements
         */
        getTimes: function(opts) {
            var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;

            if (performance === undefined) {
                return false;
            }

            var timing = performance.timing;
            var api = {};
            opts = opts || {};

            if (timing) {
                if(opts && !opts.simple) {
                    for (var k in timing) {
                        // hasOwnProperty does not work because properties are
                        // added by modifying the object prototype
                        if(isNumeric(timing[k])) {
                            api[k] = parseFloat(timing[k]);
                        }
                    }
                }


                // Time to first paint
                if (api.firstPaint === undefined) {
                    // All times are relative times to the start time within the
                    // same objects
                    var firstPaint = 0;

                    // IE
                    if (typeof timing.msFirstPaint === 'number') {
                        firstPaint = timing.msFirstPaint;
                        api.firstPaintTime = firstPaint - timing.navigationStart;
                    } else if (performance.getEntriesByName !== undefined) {
                        var firstPaintPerformanceEntry = performance.getEntriesByName('first-paint');
                        if (firstPaintPerformanceEntry.length === 1) {
                            var firstPaintTime = firstPaintPerformanceEntry[0].startTime;
                            firstPaint = performance.timeOrigin + firstPaintTime;
                            api.firstPaintTime = firstPaintTime;
                        }
                    }
                    if (opts && !opts.simple) {
                        api.firstPaint = firstPaint;
                    }
                }

                // Total time from start to load
                api.loadTime = timing.loadEventEnd - timing.fetchStart;
                // Time spent constructing the DOM tree
                api.domReadyTime = timing.domComplete - timing.domInteractive;
                // Time consumed preparing the new page
                api.readyStart = timing.fetchStart - timing.navigationStart;
                // Time spent during redirection
                api.redirectTime = timing.redirectEnd - timing.redirectStart;
                // AppCache
                api.appcacheTime = timing.domainLookupStart - timing.fetchStart;
                // Time spent unloading documents
                api.unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart;
                // DNS query time
                api.lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart;
                // TCP connection time
                api.connectTime = timing.connectEnd - timing.connectStart;
                // Time spent during the request
                api.requestTime = timing.responseEnd - timing.requestStart;
                // Request to completion of the DOM loading
                api.initDomTreeTime = timing.domInteractive - timing.responseEnd;
                // Load event time
                api.loadEventTime = timing.loadEventEnd - timing.loadEventStart;
                // Could be used as timestamp
                api.navigationStart = timing.navigationStart;
            }

            return api;
        }
    };

    function isNumeric(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
})(typeof window !== 'undefined' ? window : {});
// sendBeacon polyfill
// https://github.com/miguelmota/Navigator.sendBeacon
;(function(root) {
  'use strict';

  var isSupported = (('navigator' in root) &&
                     ('sendBeacon' in root.navigator));

  var sendBeacon = function (url, data) {
    var xhr = ('XMLHttpRequest' in window) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    xhr.open('POST', url, false);
    xhr.withCredentials = true;
    xhr.setRequestHeader('Accept', '*/*');
    if (typeof data === 'string') {
      xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
      xhr.responseType = 'text/plain';
    } else if (({}).toString.call(data) === '[object Blob]') {
      if (data.type) {
        xhr.setRequestHeader('Content-Type', data.type);
      }
    }

    try {
      xhr.send(data);
    } catch (error) {}
    return true;
  }

  if (isSupported) {
     sendBeacon = navigator.sendBeacon.bind(navigator);
     // added due to bug in chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=490015
     // can then use this as xhr request fallback
     root.navigator.sendBeaconFallback = sendBeacon;
  }
  else {
    root.navigator.sendBeacon = sendBeacon;
  }
})(typeof window === 'object' ? window : this);
var Stats={STATSURL:"~/logclientdata.ashx",_iteration:0,_queue:[],_running:false,_runQueue:function(){this._running=true;if(this._queue.length){var uri=this._queue.splice(0,1);var XHRLogger=jQuery.ajax({url:uri,global:false,cache:false});XHRLogger.fail=function(){ABL.LogInfo('Logging to '+uri+' failed')}}else{this._running=false}},SpiderExtDeeplink:function(url,source){this.Log('spiderdeeplink',{cs:source,url:url})},MDExtDeeplink:function(url,source){this.Log('mddeeplink',{cs:source,url:url})},LibraryExtDeeplink:function(url,source){this.Log('librarydeeplink',{cs:source,url:url})},MiscExtDeeplink:function(url,source){this.Log('miscdeeplink',{cs:source,url:url})},OtherExtDeeplink:function(url,source){this.Log('otherdeeplink',{cs:source,url:url})},Deeplink:function(bsid,url,source){this.Log('bsiddeeplink',{bsid:bsid,cs:source,url:url})},Reservation:function(){this.Log('reservation',{})},Custom:function(action,p0,p1,p2){this.Log('custom',{act:action,p0:p0,p1:p1,p2:p2})},Back:function(){this.Log('back',{})},Forward:function(){this.Log("forward",{})},RefinePanelOpen:function(){this.Log('fullrefopen',{cs:'resultlist'})},RefinePanelSwitch:function(tab){this.Log('fullrefswitch',{cs:'resultlist',tab:tab})},LHSSwitch:function(tab){this.Log('lhsswitch',{cs:'lhs',tab:tab})},ClientData:function(){var fv="";var skin=State.Get('skin');var screensize=screen.width+"x"+screen.height;this.Log('clientdata',{d2:fv,d1:skin,d0:screensize,d3:State.Get('inlibrary')})},Log:function(action,args){var uri=State.Settings.Get('applicationpath')+this.STATSURL+"?a="+action+"&"+jQuery.param(args)+"&t="+(new Date).getTime()+"_"+this._iteration;this._iteration++;this._queue.push(uri);if(!this._running){this._runQueue()}}};ABL.Initialize=function(){State.LoadServerSettings();var triggerStateChange=false;if(ABL.initialHash){stateObject=$.getObjectFromQueryString(ABL.initialHash);State.ReplaceWithObject(stateObject);ABL.History.Store.Set(ABL.initialHash,{});triggerStateChange=true}else{}ABL.SetHistoryState();ABL.Event.trigger('abl:initialize');Stats.ClientData();ABL.BindStateChange();if(triggerStateChange){ABL.HandleStateChange(State.AsObject())}ABL.Initialized=true};var ExtLink={Create:function(exturl){var url="html/extlink.html";State.Set('exturl',exturl);State.Set('ts',(new Date).getTime());return url+'?'+State.AsArgString()},Open:function(exturl){window.open(this.Create(exturl))}};$(function(){ABL.Initialize()});var AutoComplete=(function(ABL,undefined){function AutoCompleteProvider(){this.settings={}}AutoCompleteProvider.extend=function(fn,proto){fn.prototype=$.extend(Object.create(AutoCompleteProvider.prototype),proto);fn.prototype.constructor=fn};AutoCompleteProvider.prototype={init:function(settings){this.settings=settings},fetchAC:function(q,cb){cb([])}};var ret={};var acXHR={};var ignoreQuery=null;var searchProviderToAcProviderMap={};var highLightAndChop=function(text){var splittedText=text.split(' ');var textLength=0;for(var i=0;i<splittedText.length;i++){textLength+=splittedText[i].replace(/<\/?em>/g,'').length+1;if(textLength>=AutoComplete.settings.MAX_TEXT_LENGTH){text=splittedText.slice(0,i).join(' ')+'...';break}}text=$.escapeUserContent(text);return text.replace(/&lt;em&gt;(.*?)&lt;\/em&gt;/g,'<mark>$1</mark>')};ret.settings={MAX_ITEMS:8,MAX_TITLES:2,SHOW_TYPE:false,MAX_TEXT_LENGTH:75};ret.getCurrentSearchProvider=function(){return DiscoveryPane.GetProviderFromDropdown()};ret.getAcProvider=function(searchProvider,cb){var provider=searchProviderToAcProviderMap[searchProvider];if(typeof provider==='function'){provider(cb);return}if(typeof provider==='object'){cb(provider);return}var url=State.Settings.Get('autocomplete')['acproviders'][searchProvider];if(!url){searchProviderToAcProviderMap[searchProvider]=provider=new AutoCompleteProvider;cb(provider);return}var loadProvider=function(){var deferred=$.ajax({cache:true,url:url,dataType:'text'}).done(function(data){searchProviderToAcProviderMap[searchProvider]=provider=eval(data);provider.init(State.Settings.Get('autocomplete')['settings'][searchProvider]||{});cb(provider)}).fail(function(){ABL.LogError('Could not load AC provider for '+searchProvider)});return function(newCallback){deferred.done(function(){newCallback(searchProviderToAcProviderMap[searchProvider])})}};searchProviderToAcProviderMap[searchProvider]=loadProvider()};ret.renderQuery=function(q){return $('<li class="ac-item active" data-actype="userquery"><a href="#">'+highLightAndChop(q)+'</a></li>').data('value',{value:q,type:'userquery'})};ret.init=function(){ret.debug=State.DebugMode()!='';var provider=ret.getCurrentSearchProvider();ret.getAcProvider(provider,function(){});var renderItem=function(item){var type='',author='',titleExtra='';if(item.type=='title'||item.type=='titlecopy'){if('authors'in item)author=item.authors[0].value;if('author_main'in item)author=item.author_main;if(author!=''&&'display'in item&&item.display.indexOf(author)>-1){author=''}}if(author){author='<span class="ac-author by-dash">'+highLightAndChop(author)+'</span>'}if(AutoComplete.settings.SHOW_TYPE&&author==''&&item.type&&item.type!='unknown'){type='<span class="ac-type by-dash">'+Localization.Trans('ac-type-'+item.type)+'</span>'}if('title_extra'in item){titleExtra=': '+item.title_extra+(author?' ':'')}var content='<span class="ac-term by-dash" data-ac="'+item.type+'">'+highLightAndChop(item.value)+'</span>'+titleExtra+author+type;return'<li class="ac-item separate"><a class="ac-type-'+item.type+'" href="#">'+content+'</a></li>'};$(document).ready(function(){$('#ablQuery').typeahead({minLength:1,items:AutoComplete.settings.MAX_ITEMS,matcher:function(){return true},menu:'<ul class="autocomplete-menu"></ul>',item:renderItem,sorter:function(items){var sepItems=$.grep(items,function(item){if(item.showseparate){return item}});items=$.grep(items,function(item){if(!item.showseparate){return item}});function sortItems(a,b){return b.score-a.score}items=items.sort(sortItems);return items.concat(sepItems)},updater:AutoComplete.selectItem,source:AutoComplete.fetchAC,navigateItem:AutoComplete.navigateItem,renderQuery:AutoComplete.renderQuery,footer:'<li class="ac-footer">'+Localization.Trans('ac-footer')+'</li>'});if($('#ablQuery').is(':focus')){$('#ablQuery').focus()}})};var processItems=function(items){var retItems=[];for(var i=0;i<items.length;i++){var item=items[i];if(ret.debug){ABL.LogInfo('['+item.score+']['+item.rank+'] '+item.value)}retItems[i]=item}return retItems};ret.navigateItem=function(item){if(typeof item!=='undefined'){$('#ablQuery').val(ret.formatItem(item))}};ret.fetchAC=function(q,cb){if(typeof q!='undefined'&&q.indexOf('/')==0){cb([]);return}if(ignoreQuery===q){cb([]);return}ignoreQuery=null;var provider=ret.getCurrentSearchProvider();ret.getAcProvider(provider,function(provider){provider.fetchAC(q,function(items){cb(processItems(items))})})};ret.formatItem=function(item){var acType=item.type;var text=item.value.replace(/<em>(.*?)<\/em>/g,'$1');if(acType=='title'&&'authors'in item){text=text+' '+item.authors[0].value.replace(/<em>(.*?)<\/em>/g,'$1')}if(acType!='userquery'){text=text.replace(/-|:|( ){1,}/g,' ')}return text};ret.selectItem=function(item){var text=ret.formatItem(item);var acType=item.type||'unknown';if(acType=='userquery'){text=$('#ablQuery').val();DiscoveryPane.DoSearch(null,{q:text});return text}if(ret.debug){ABL.LogInfo('AC selected: '+text+' - AC type: '+acType)}if(acType=='title'&&('frabl'in item&&item.frabl!=='0')){ABL.LogInfo('The user should go to detail page '+item.frabl+' now');DiscoveryPane.DoSearch(null,{q:text,i_actype:acType,cs:'qb.autocomplete'})}else{DiscoveryPane.DoSearch(null,{q:text,i_actype:acType,cs:'qb.autocomplete'})}return text};return ret})(ABL);ABL.RegisterModule(AutoComplete);/* =============================================================
 * bootstrap-typeahead.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#typeahead
 * =============================================================
 * Copyright 2013 Twitter, Inc.
 *
 * 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($){

  "use strict"; // jshint ;_;


 /* TYPEAHEAD PUBLIC CLASS DEFINITION
  * ================================= */

  var Typeahead = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
    this.matcher = this.options.matcher || this.matcher
    this.sorter = this.options.sorter || this.sorter
    this.highlighter = this.options.highlighter || this.highlighter
    this.updater = this.options.updater || this.updater
    this.footer = this.options.footer || ''
    this.footerClass = this.options.footerClass || 'ac-footer'
    this.source = this.options.source
    this.headingClass = this.options.headingClass || 'ac-heading'
    this.$menu = $(this.options.menu)
    this.navigateItem = this.options.navigateItem
    this.maxItemLength = this.options.maxItemLength || 50
    this.renderQuery = this.options.renderQuery || function () { }
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

  , select: function () {
      var active = this.$menu.find('.active');
      var val = active.data('value');
      if (active.hasClass(this.footerClass) || active.hasClass(this.headingClass) || typeof val == 'undefined') {
         // weirdness, create your own query
         val = { type: "userquery", value: this.query };
      }
      this.$element
        .val(this.updater(val))
        .change()
      return this.hide()
    }

  , updater: function (item) {
      return item
    }

  , show: function () {
      var pos = $.extend({}, this.$element.position(), {
        height: this.$element[0].offsetHeight
      })

      this.$menu
        .insertAfter(this.$element)
        .css({
          top: pos.top + pos.height
        , left: pos.left
        })
        .show()

      this.shown = true
      return this
    }

  , hide: function () {
      this.$menu.hide()
      this.shown = false
      return this
    }

  , lookup: function (event) {
      var items

      this.query = this.$element.val()

      if (!this.query || this.query.length < this.options.minLength) {
        return this.shown ? this.hide() : this
      }

      items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source

      return items ? this.process(items) : this
    }

  , process: function (items) {
      var that = this

      items = $.grep(items, function (item) {
        return that.matcher(item)
      })

      items = this.sorter(items)

      if (!items.length) {
        return this.shown ? this.hide() : this
      }

      return this.render(items.slice(0, this.options.items)).show()
    }

  , matcher: function (item) {
      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
    }

  , sorter: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item

      while (item = items.shift()) {
        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
        else if (~item.indexOf(this.query)) caseSensitive.push(item)
        else caseInsensitive.push(item)
      }

      return beginswith.concat(caseSensitive, caseInsensitive)
    }

  , highlighter: function (item) {
      var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
      return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
        return '<strong>' + match + '</strong>'
      })
  }
  ,
   chopToMaxLength: function(text) {
      return $.trunc(text, this.maxItemLength)
  }

  , render: function (items) {
      var tmpType, that = this
      
      items = $(items).map(function (i, item) {
        var el = $.isFunction(that.options.item) ? that.options.item(item) : that.options.item;
        i = $(el).data('value', item)
        return i[0]
      })

      that.$menu.children().remove();
      that.$menu.append(that.renderQuery(this.query))
      items.each(function () {
         var val = $(this).data('value');
         var type = val.type;
         if (tmpType != type && val.showseparate) {
            tmpType = type;
            that.$menu.append('<li class="' + that.headingClass + '">' + Localization.Trans('ac-heading-' + type) + '</li>');
         }
         that.$menu.append(this);
      })
      that.$menu.append(that.options.footer);
      
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.next()

      if (next.hasClass(this.headingClass) || next.hasClass(this.footerClass)) {
         next = next.next();
      }
      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }
      this.navigateItem(next.data('value'));
      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prev()

      if (prev.hasClass(this.headingClass) || prev.hasClass(this.footerClass)) {
         prev = prev.prev();
      }
      if (!prev.length) {
        prev = this.$menu.find('li:not(.'+this.footerClass+')').last()
      }
      this.navigateItem(prev.data('value'));
      prev.addClass('active')
    }

  , listen: function () {
      this.$element
        .on('focus',    $.proxy(this.focus, this))
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

      if (this.eventSupported('keydown')) {
        this.$element.on('keydown', $.proxy(this.keydown, this))
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
        .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
    }

  , eventSupported: function(eventName) {
      var isSupported = eventName in this.$element
      if (!isSupported) {
        this.$element.setAttribute(eventName, 'return;')
        isSupported = typeof this.$element[eventName] === 'function'
      }
      return isSupported
    }

  , move: function (e) {
      if (!this.shown) return

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow (only check on type=keydown, azerty emits 38 for ampersand key :S0
           if (!e.shiftKey && e.type == 'keydown') {
              e.preventDefault()
              this.prev()
           }
          break

         case 40: // down arrow
            if (!e.shiftKey && e.type == 'keydown') {
               e.preventDefault()
               this.next()
            }
          break
      }

      e.stopPropagation()
    }

  , keydown: function (e) {
      this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27])
      this.move(e)
    }

  , keypress: function (e) {
      if (this.suppressKeyPressRepeat) return
      this.move(e)
    }

  , keyup: function (e) {
      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
        case 16: // shift
        case 17: // ctrl
        case 18: // alt
          break

        case 9: // tab
        case 13: // enter
          if (!this.shown) return
          this.select()
          break

        case 27: // escape
          if (!this.shown) return
          this.hide()
          break

        default:
          this.lookup()
      }

      e.stopPropagation()
      e.preventDefault()
  }

  , focus: function (e) {
      this.focused = true
    }

  , blur: function (e) {
      this.focused = false
      if (!this.mousedover && this.shown) this.hide()
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      var $el = $(e.srcElement);
      if ($el.hasClass(this.headingClass) || $el.hasClass(this.footerClass)) {
         return false;
      }
      this.select()
      this.$element.focus()
    }

  , mouseenter: function (e) {
      this.mousedover = true
      this.$menu.find('.active').removeClass('active')
      var $el = $(e.currentTarget);
      if (!$el.hasClass(this.headingClass) && !$el.hasClass(this.footerClass)) {
         $el.addClass('active')
      }
    }

  , mouseleave: function (e) {
      this.mousedover = false
      if (!this.focused && this.shown) this.hide()
    }

  }


  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  var old = $.fn.typeahead

  $.fn.typeahead = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
    source: []
  , items: 8
  , menu: '<ul class="typeahead dropdown-menu"></ul>'
  , item: '<li><a href="#"></a></li>'
  , minLength: 1
  }

  $.fn.typeahead.Constructor = Typeahead


 /* TYPEAHEAD NO CONFLICT
  * =================== */

  $.fn.typeahead.noConflict = function () {
    $.fn.typeahead = old
    return this
  }


 /* TYPEAHEAD DATA-API
  * ================== */

  $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
    var $this = $(this)
    if ($this.data('typeahead')) return
    $this.typeahead($this.data())
  })

}(window.jQuery);
/* ==========================================================
 * bootstrap-alert.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#alerts
 * ==========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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 ($) {

  "use strict"; // jshint ;_;


 /* ALERT CLASS DEFINITION
  * ====================== */

  var dismiss = '[data-dismiss="alert"]'
    , Alert = function (el) {
        $(el).on('click', dismiss, this.close)
      }

  Alert.prototype.close = function (e) {
    var $this = $(this)
      , selector = $this.attr('data-target')
      , $parent

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
    }

    $parent = $(selector)

    e && e.preventDefault()

    $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent())

    $parent.trigger(e = $.Event('close'))

    if (e.isDefaultPrevented()) return

    $parent.removeClass('in')

    function removeElement() {
      $parent
        .trigger('closed')
        .remove()
    }

    $.support.transition && $parent.hasClass('fade') ?
      $parent.on($.support.transition.end, removeElement) :
      removeElement()
  }


 /* ALERT PLUGIN DEFINITION
  * ======================= */

  var old = $.fn.alert

  $.fn.alert = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('alert')
      if (!data) $this.data('alert', (data = new Alert(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  $.fn.alert.Constructor = Alert


 /* ALERT NO CONFLICT
  * ================= */

  $.fn.alert.noConflict = function () {
    $.fn.alert = old
    return this
  }


 /* ALERT DATA-API
  * ============== */

  $(document).on('click.alert.data-api', dismiss, Alert.prototype.close)

}(window.jQuery);/* ===========================================================
 * bootstrap-tooltip.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#tooltips
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ===========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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 ($) {

  "use strict"; // jshint ;_;


 /* TOOLTIP PUBLIC CLASS DEFINITION
  * =============================== */

  var Tooltip = function (element, options) {
    this.init('tooltip', element, options)
  }

  Tooltip.prototype = {

    constructor: Tooltip

  , init: function (type, element, options) {
      var eventIn
        , eventOut
        , triggers
        , trigger
        , i

      this.type = type
      this.$element = $(element)
      this.options = this.getOptions(options)
      this.enabled = true

      triggers = this.options.trigger.split(' ')

      for (i = triggers.length; i--;) {
        trigger = triggers[i]
        if (trigger == 'click') {
          this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
        } else if (trigger != 'manual') {
          eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
          eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
          this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
          this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
        }
      }

      this.options.selector ?
        (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
        this.fixTitle()
    }

  , getOptions: function (options) {
      options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options)

      if (options.delay && typeof options.delay == 'number') {
        options.delay = {
          show: options.delay
        , hide: options.delay
        }
      }

      return options
    }

  , enter: function (e) {
      var defaults = $.fn[this.type].defaults
        , options = {}
        , self

      this._options && $.each(this._options, function (key, value) {
        if (defaults[key] != value) options[key] = value
      }, this)

      self = $(e.currentTarget)[this.type](options).data(this.type)

      if (!self.options.delay || !self.options.delay.show) return self.show()

      clearTimeout(this.timeout)
      self.hoverState = 'in'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'in') self.show()
      }, self.options.delay.show)
    }

  , leave: function (e) {
      var self = $(e.currentTarget)[this.type](this._options).data(this.type)

      if (this.timeout) clearTimeout(this.timeout)
      if (!self.options.delay || !self.options.delay.hide) return self.hide()

      self.hoverState = 'out'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'out') self.hide()
      }, self.options.delay.hide)
    }

  , show: function () {
      var $tip
        , pos
        , actualWidth
        , actualHeight
        , placement
        , tp
        , e = $.Event('show')

      if (this.hasContent() && this.enabled) {
        this.$element.trigger(e)
        if (e.isDefaultPrevented()) return
        $tip = this.tip()
        this.setContent()

        if (this.options.animation) {
          $tip.addClass('fade')
        }

        placement = typeof this.options.placement == 'function' ?
          this.options.placement.call(this, $tip[0], this.$element[0]) :
          this.options.placement

        $tip
          .detach()
          .css({ top: 0, left: 0, display: 'block' })

        this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)

        pos = this.getPosition()

        actualWidth = $tip[0].offsetWidth
        actualHeight = $tip[0].offsetHeight

        switch (placement) {
          case 'bottom':
            tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'top':
            tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'left':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
            break
          case 'right':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
            break
        }

        this.applyPlacement(tp, placement)
        this.$element.trigger('shown')
      }
    }

  , applyPlacement: function(offset, placement){
      var $tip = this.tip()
        , width = $tip[0].offsetWidth
        , height = $tip[0].offsetHeight
        , actualWidth
        , actualHeight
        , delta
        , replace

      $tip
        .offset(offset)
        .addClass(placement)
        .addClass('in')

      actualWidth = $tip[0].offsetWidth
      actualHeight = $tip[0].offsetHeight

      if (placement == 'top' && actualHeight != height) {
        offset.top = offset.top + height - actualHeight
        replace = true
      }

      if (placement == 'bottom' || placement == 'top') {
        delta = 0

        if (offset.left < 0){
          delta = offset.left * -2
          offset.left = 0
          $tip.offset(offset)
          actualWidth = $tip[0].offsetWidth
          actualHeight = $tip[0].offsetHeight
        }

        this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
      } else {
        this.replaceArrow(actualHeight - height, actualHeight, 'top')
      }

      if (replace) $tip.offset(offset)
    }

  , replaceArrow: function(delta, dimension, position){
      this
        .arrow()
        .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
    }

  , setContent: function () {
      var $tip = this.tip()
        , title = this.getTitle()

      $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
      $tip.removeClass('fade in top bottom left right')
    }

  , hide: function () {
      var that = this
        , $tip = this.tip()
        , e = $.Event('hide')

      this.$element.trigger(e)
      if (e.isDefaultPrevented()) return

      $tip.removeClass('in')

      function removeWithAnimation() {
        var timeout = setTimeout(function () {
          $tip.off($.support.transition.end).detach()
        }, 500)

        $tip.one($.support.transition.end, function () {
          clearTimeout(timeout)
          $tip.detach()
        })
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        removeWithAnimation() :
        $tip.detach()

      this.$element.trigger('hidden')

      return this
    }

  , fixTitle: function () {
      var $e = this.$element
      if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
        $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
      }
    }

  , hasContent: function () {
      return this.getTitle()
    }

  , getPosition: function () {
      var el = this.$element[0]
      return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
        width: el.offsetWidth
      , height: el.offsetHeight
      }, this.$element.offset())
    }

  , getTitle: function () {
      var title
        , $e = this.$element
        , o = this.options

      title = $e.attr('data-original-title')
        || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

      return title
    }

  , tip: function () {
      return this.$tip = this.$tip || $(this.options.template)
    }

  , arrow: function(){
      return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
    }

  , validate: function () {
      if (!this.$element[0].parentNode) {
        this.hide()
        this.$element = null
        this.options = null
      }
    }

  , enable: function () {
      this.enabled = true
    }

  , disable: function () {
      this.enabled = false
    }

  , toggleEnabled: function () {
      this.enabled = !this.enabled
    }

  , toggle: function (e) {
      var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this
      self.tip().hasClass('in') ? self.hide() : self.show()
    }

  , destroy: function () {
      this.hide().$element.off('.' + this.type).removeData(this.type)
    }

  }


 /* TOOLTIP PLUGIN DEFINITION
  * ========================= */

  var old = $.fn.tooltip

  $.fn.tooltip = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tooltip')
        , options = typeof option == 'object' && option
      if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tooltip.Constructor = Tooltip

  $.fn.tooltip.defaults = {
    animation: true
  , placement: 'top'
  , selector: false
  , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
  , trigger: 'hover focus'
  , title: ''
  , delay: 0
  , html: false
  , container: false
  }


 /* TOOLTIP NO CONFLICT
  * =================== */

  $.fn.tooltip.noConflict = function () {
    $.fn.tooltip = old
    return this
  }

}(window.jQuery);
/* ============================================================
 * bootstrap-dropdown.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#dropdowns
 * ============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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 ($) {

  "use strict"; // jshint ;_;


 /* DROPDOWN CLASS DEFINITION
  * ========================= */

  var toggle = '[data-toggle=dropdown]'
    , Dropdown = function (element) {
        var $el = $(element).on('click.dropdown.data-api', this.toggle)
        $('html').on('click.dropdown.data-api', function () {
          $el.parent().removeClass('open')
        })
      }

  Dropdown.prototype = {

    constructor: Dropdown

  , toggle: function (e) {
      var $this = $(this)
        , $parent
        , isActive

      if ($this.is('.disabled, :disabled')) return

      $parent = getParent($this)

      isActive = $parent.hasClass('open')

      clearMenus()

      if (!isActive) {
        $parent.toggleClass('open')
      }

      $this.focus()

      return false
    }

  , keydown: function (e) {
      var $this
        , $items
        , $active
        , $parent
        , isActive
        , index

      if (!/(38|40|27)/.test(e.keyCode)) return

      $this = $(this)

      e.preventDefault()
      e.stopPropagation()

      if ($this.is('.disabled, :disabled')) return

      $parent = getParent($this)

      isActive = $parent.hasClass('open')

      if (!isActive || (isActive && e.keyCode == 27)) {
        if (e.which == 27) $parent.find(toggle).focus()
        return $this.click()
      }

      $items = $('[role=menu] li:not(.divider):visible a', $parent)

      if (!$items.length) return

      index = $items.index($items.filter(':focus'))

      if (e.keyCode == 38 && index > 0) index--                                        // up
      if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
      if (!~index) index = 0

      $items
        .eq(index)
        .focus()
    }

  }

  function clearMenus() {
    $(toggle).each(function () {
      getParent($(this)).removeClass('open')
    })
  }

  function getParent($this) {
    var selector = $this.attr('data-target')
      , $parent

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
    }

    $parent = selector && $(selector)

    if (!$parent || !$parent.length) $parent = $this.parent()

    return $parent
  }


  /* DROPDOWN PLUGIN DEFINITION
   * ========================== */

  var old = $.fn.dropdown

  $.fn.dropdown = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('dropdown')
      if (!data) $this.data('dropdown', (data = new Dropdown(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  $.fn.dropdown.Constructor = Dropdown


 /* DROPDOWN NO CONFLICT
  * ==================== */

  $.fn.dropdown.noConflict = function () {
    $.fn.dropdown = old
    return this
  }


  /* APPLY TO STANDARD DROPDOWN ELEMENTS
   * =================================== */

  $(document)
    .on('click.dropdown.data-api', clearMenus)
    .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
    .on('click.dropdown-menu', function (e) { e.stopPropagation() })
    .on('click.dropdown.data-api'  , toggle, Dropdown.prototype.toggle)
    .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)

}(window.jQuery);
/* ===================================================
 * bootstrap-transition.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#transitions
 * ===================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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 ($) {

  "use strict"; // jshint ;_;


  /* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
   * ======================================================= */

  $(function () {

    $.support.transition = (function () {

      var transitionEnd = (function () {

        var el = document.createElement('bootstrap')
          , transEndEventNames = {
               'WebkitTransition' : 'webkitTransitionEnd'
            ,  'MozTransition'    : 'transitionend'
            ,  'OTransition'      : 'oTransitionEnd otransitionend'
            ,  'transition'       : 'transitionend'
            }
          , name

        for (name in transEndEventNames){
          if (el.style[name] !== undefined) {
            return transEndEventNames[name]
          }
        }

      }())

      return transitionEnd && {
        end: transitionEnd
      }

    })()

  })

}(window.jQuery);/* ===========================================================
 * bootstrap-popover.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#popovers
 * ===========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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 ($) {

  "use strict"; // jshint ;_;


 /* POPOVER PUBLIC CLASS DEFINITION
  * =============================== */

  var Popover = function (element, options) {
    this.init('popover', element, options)
  }


  /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
     ========================================== */

  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {

    constructor: Popover

  , setContent: function () {
      var $tip = this.tip()
        , title = this.getTitle()
        , content = this.getContent()

      $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
      $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)

      $tip.removeClass('fade top bottom left right in')
    }

  , hasContent: function () {
      return this.getTitle() || this.getContent()
    }

  , getContent: function () {
      var content
        , $e = this.$element
        , o = this.options

      content = (typeof o.content == 'function' ? o.content.call($e[0]) :  o.content)
        || $e.attr('data-content')

      return content
    }

  , tip: function () {
      if (!this.$tip) {
        this.$tip = $(this.options.template)
      }
      return this.$tip
    }

  , destroy: function () {
      this.hide().$element.off('.' + this.type).removeData(this.type)
    }

  })


 /* POPOVER PLUGIN DEFINITION
  * ======================= */

  var old = $.fn.popover

  $.fn.popover = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('popover')
        , options = typeof option == 'object' && option
      if (!data) $this.data('popover', (data = new Popover(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.popover.Constructor = Popover

  $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
    placement: 'right'
  , trigger: 'click'
  , content: ''
  , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
  })


 /* POPOVER NO CONFLICT
  * =================== */

  $.fn.popover.noConflict = function () {
    $.fn.popover = old
    return this
  }

}(window.jQuery);
/* =============================================================
 * bootstrap-collapse.js v2.0.1
 * http://twitter.github.com/bootstrap/javascript.html#collapse
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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 ($) {

   "use strict"

   var Collapse = function (element, options) {
      this.$element = $(element)
      this.options = $.extend({}, $.fn.collapse.defaults, options)

      if (this.options["parent"]) {
         this.$parent = $(this.options["parent"])
      }

      this.options.toggle && this.toggle()
   }

   Collapse.prototype = {

      constructor: Collapse

   , dimension: function () {
      var hasWidth = this.$element.hasClass('width')
      return hasWidth ? 'width' : 'height'
   }

   , show: function () {
      var dimension = this.dimension()
        , scroll = $.camelCase(['scroll', dimension].join('-'))
        , actives = this.$parent && this.$parent.find('.in')
        , hasData

      if (actives && actives.length) {
         hasData = actives.data('collapse')
         actives.collapse('hide')
         hasData || actives.data('collapse', null)
      }

      this.$element[dimension](0);
      this.transition('addClass', 'show', 'shown')
      $.support.transition && this.$element[dimension]('auto')// WH: from $.support.transition && this.$element[dimension](this.$element[0][scroll])  - auto works better for IE
   }

   , hide: function () {
      var dimension = this.dimension()
      this.reset(this.$element[dimension]())
      this.transition('removeClass', 'hide', 'hidden')
      this.$element[dimension](0)
   }

   , reset: function (size) {
      var dimension = this.dimension()

      this.$element
        .removeClass('collapse')
        [dimension]('auto')// WH: from [dimension](size || 'auto') - auto works better for IE
        [0].offsetWidth

      this.$element.addClass('collapse')
   }

   , transition: function (method, startEvent, completeEvent) {
      var that = this
        , complete = function () {
           if (startEvent == 'show') { that.reset() }
           that.$element.trigger(completeEvent)
        }

      this.$element
        .trigger(startEvent)
        [method]('in')

      $.support.transition && this.$element.hasClass('collapse') ?
        this.$element.one($.support.transition.end, complete) :
        complete()
   }

   , toggle: function () {
      this[this.$element.hasClass('in') ? 'hide' : 'show']()
   }

   }

   /* COLLAPSIBLE PLUGIN DEFINITION
   * ============================== */

   $.fn.collapse = function (option) {
      return this.each(function () {
         var $this = $(this)
           , data = $this.data('collapse')
           , options = typeof option == 'object' && option
         if (!data) { $this.data('collapse', (data = new Collapse(this, options))) }
         if (typeof option == 'string') { data[option]() }
      })
   }

   $.fn.collapse.defaults = {
      toggle: true
   }

   $.fn.collapse.Constructor = Collapse


   /* COLLAPSIBLE DATA-API
    * ==================== */

   $(function () {
      $('body').on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
         var $this = $(this), href
           , target = $this.attr('data-target')
             || e.preventDefault()
             || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
           , option = $(target).data('collapse') ? 'toggle' : $this.data()
         $(target).collapse(option)
      })
   })

}(window.jQuery);/* ========================================================
 * bootstrap-tab.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#tabs
 * ========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * 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 ($) {

  "use strict"; // jshint ;_;


 /* TAB CLASS DEFINITION
  * ==================== */

  var Tab = function (element) {
    this.element = $(element)
  }

  Tab.prototype = {

    constructor: Tab

  , show: function () {
      var $this = this.element
        , $ul = $this.closest('ul:not(.dropdown-menu)')
        , selector = $this.attr('data-target')
        , previous
        , $target
        , e

      if (!selector) {
        selector = $this.attr('href')
        selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
      }

      if ( $this.parent('li').hasClass('active') ) return

      previous = $ul.find('.active:last a')[0]

      e = $.Event('show', {
        relatedTarget: previous
      })

      $this.trigger(e)

      if (e.isDefaultPrevented()) return

      $target = $(selector)

      this.activate($this.parent('li'), $ul)
      this.activate($target, $target.parent(), function () {
        $this.trigger({
          type: 'shown'
        , relatedTarget: previous
        })
      })
    }

  , activate: function ( element, container, callback) {
      var $active = container.find('> .active')
        , transition = callback
            && $.support.transition
            && $active.hasClass('fade')

      function next() {
        $active
          .removeClass('active')
          .find('> .dropdown-menu > .active')
          .removeClass('active')

        element.addClass('active')

        if (transition) {
          element[0].offsetWidth // reflow for transition
          element.addClass('in')
        } else {
          element.removeClass('fade')
        }

        if ( element.parent('.dropdown-menu') ) {
          element.closest('li.dropdown').addClass('active')
        }

        callback && callback()
      }

      transition ?
        $active.one($.support.transition.end, next) :
        next()

      $active.removeClass('in')
    }
  }


 /* TAB PLUGIN DEFINITION
  * ===================== */

  var old = $.fn.tab

  $.fn.tab = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tab')
      if (!data) $this.data('tab', (data = new Tab(this)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tab.Constructor = Tab


 /* TAB NO CONFLICT
  * =============== */

  $.fn.tab.noConflict = function () {
    $.fn.tab = old
    return this
  }


 /* TAB DATA-API
  * ============ */

  $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
    e.preventDefault()
    $(this).tab('show')
  })

}(window.jQuery);