Mercurial > hg > digilib
changeset 1300:7a39ed403635
updated to Annotator.js 1.2.9-dev.
author | robcast |
---|---|
date | Fri, 16 Jan 2015 20:57:20 +0100 |
parents | 49d643f0d658 |
children | b52dee769c6b 72c44a24a0d5 |
files | webapp/src/main/webapp/jquery/annotator-dl.js webapp/src/main/webapp/jquery/annotator-dl.min.js webapp/src/main/webapp/jquery/digilib-ann.html webapp/src/main/webapp/jquery/jquery.digilib.annotator.js |
diffstat | 4 files changed, 709 insertions(+), 362 deletions(-) [+] |
line wrap: on
line diff
--- a/webapp/src/main/webapp/jquery/annotator-dl.js Fri Jan 16 18:20:15 2015 +0100 +++ b/webapp/src/main/webapp/jquery/annotator-dl.js Fri Jan 16 20:57:20 2015 +0100 @@ -1,23 +1,124 @@ + /* -** Annotator 1.2.5-dev-a4cd304 +** Annotator v1.2.9-dev-b091a74 ** https://github.com/okfn/annotator/ ** -** Copyright 2012 Aron Carroll, Rufus Pollock, and Nick Stenning. +** Copyright 2015, the Annotator project contributors. ** Dual licensed under the MIT and GPLv3 licenses. ** https://github.com/okfn/annotator/blob/master/LICENSE ** -** Built at: 2012-11-23 09:46:08Z -*/ - - +** Built at: 2015-01-16 17:56:43Z + */ + + +// + +// Generated by CoffeeScript 1.6.3 (function() { - var $, Annotator, Delegator, LinkParser, Range, base64Decode, base64UrlDecode, createDateFromISO8601, fn, functions, g, gettext, parseToken, util, _Annotator, _gettext, _i, _j, _len, _len1, _ref, _ref1, _t, + var $, Annotator, Delegator, LinkParser, Range, Util, base64Decode, base64UrlDecode, createDateFromISO8601, findChild, fn, functions, g, getNodeName, getNodePosition, gettext, parseToken, simpleXPathJQuery, simpleXPathPure, _Annotator, _gettext, _i, _j, _len, _len1, _ref, _ref1, _ref2, _ref3, _ref4, _t, __slice = [].slice, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + simpleXPathJQuery = function(relativeRoot) { + var jq; + jq = this.map(function() { + var elem, idx, path, tagName; + path = ''; + elem = this; + while ((elem != null ? elem.nodeType : void 0) === Node.ELEMENT_NODE && elem !== relativeRoot) { + tagName = elem.tagName.replace(":", "\\:"); + idx = $(elem.parentNode).children(tagName).index(elem) + 1; + idx = "[" + idx + "]"; + path = "/" + elem.tagName.toLowerCase() + idx + path; + elem = elem.parentNode; + } + return path; + }); + return jq.get(); + }; + + simpleXPathPure = function(relativeRoot) { + var getPathSegment, getPathTo, jq, rootNode; + getPathSegment = function(node) { + var name, pos; + name = getNodeName(node); + pos = getNodePosition(node); + return "" + name + "[" + pos + "]"; + }; + rootNode = relativeRoot; + getPathTo = function(node) { + var xpath; + xpath = ''; + while (node !== rootNode) { + if (node == null) { + throw new Error("Called getPathTo on a node which was not a descendant of @rootNode. " + rootNode); + } + xpath = (getPathSegment(node)) + '/' + xpath; + node = node.parentNode; + } + xpath = '/' + xpath; + xpath = xpath.replace(/\/$/, ''); + return xpath; + }; + jq = this.map(function() { + var path; + path = getPathTo(this); + return path; + }); + return jq.get(); + }; + + findChild = function(node, type, index) { + var child, children, found, name, _i, _len; + if (!node.hasChildNodes()) { + throw new Error("XPath error: node has no children!"); + } + children = node.childNodes; + found = 0; + for (_i = 0, _len = children.length; _i < _len; _i++) { + child = children[_i]; + name = getNodeName(child); + if (name === type) { + found += 1; + if (found === index) { + return child; + } + } + } + throw new Error("XPath error: wanted child not found."); + }; + + getNodeName = function(node) { + var nodeName; + nodeName = node.nodeName.toLowerCase(); + switch (nodeName) { + case "#text": + return "text()"; + case "#comment": + return "comment()"; + case "#cdata-section": + return "cdata-section()"; + default: + return nodeName; + } + }; + + getNodePosition = function(node) { + var pos, tmp; + pos = 0; + tmp = node; + while (tmp) { + if (tmp.nodeName === node.nodeName) { + pos++; + } + tmp = tmp.previousSibling; + } + return pos; + }; + gettext = null; if (typeof Gettext !== "undefined" && Gettext !== null) { @@ -45,9 +146,11 @@ console.error(_t("Annotator requires a JSON implementation: have you included lib/vendor/json2.js?")); } - $ = jQuery.sub(); - - $.flatten = function(array) { + $ = jQuery; + + Util = {}; + + Util.flatten = function(array) { var flatten; flatten = function(ary) { var el, flat, _i, _len; @@ -61,30 +164,25 @@ return flatten(array); }; - $.plugin = function(name, object) { - return jQuery.fn[name] = function(options) { - var args; - args = Array.prototype.slice.call(arguments, 1); - return this.each(function() { - var instance; - instance = $.data(this, name); - if (instance) { - return options && instance[options].apply(instance, args); - } else { - instance = new object(this, options); - return $.data(this, name, instance); - } - }); - }; + Util.contains = function(parent, child) { + var node; + node = child; + while (node != null) { + if (node === parent) { + return true; + } + node = node.parentNode; + } + return false; }; - $.fn.textNodes = function() { + Util.getTextNodes = function(jq) { var getTextNodes; getTextNodes = function(node) { var nodes; - if (node && node.nodeType !== 3) { + if (node && node.nodeType !== Node.TEXT_NODE) { nodes = []; - if (node.nodeType !== 8) { + if (node.nodeType !== Node.COMMENT_NODE) { node = node.lastChild; while (node) { nodes.push(getTextNodes(node)); @@ -96,55 +194,154 @@ return node; } }; - return this.map(function() { - return $.flatten(getTextNodes(this)); + return jq.map(function() { + return Util.flatten(getTextNodes(this)); }); }; - $.fn.xpath = function(relativeRoot) { - var jq; - jq = this.map(function() { - var elem, idx, path; - path = ''; - elem = this; - while (elem && elem.nodeType === 1 && elem !== relativeRoot) { - idx = $(elem.parentNode).children(elem.tagName).index(elem) + 1; - idx = "[" + idx + "]"; - path = "/" + elem.tagName.toLowerCase() + idx + path; - elem = elem.parentNode; - } - return path; - }); - return jq.get(); + Util.getLastTextNodeUpTo = function(n) { + var result; + switch (n.nodeType) { + case Node.TEXT_NODE: + return n; + case Node.ELEMENT_NODE: + if (n.lastChild != null) { + result = Util.getLastTextNodeUpTo(n.lastChild); + if (result != null) { + return result; + } + } + break; + } + n = n.previousSibling; + if (n != null) { + return Util.getLastTextNodeUpTo(n); + } else { + return null; + } }; - $.escape = function(html) { + Util.getFirstTextNodeNotBefore = function(n) { + var result; + switch (n.nodeType) { + case Node.TEXT_NODE: + return n; + case Node.ELEMENT_NODE: + if (n.firstChild != null) { + result = Util.getFirstTextNodeNotBefore(n.firstChild); + if (result != null) { + return result; + } + } + break; + } + n = n.nextSibling; + if (n != null) { + return Util.getFirstTextNodeNotBefore(n); + } else { + return null; + } + }; + + Util.readRangeViaSelection = function(range) { + var sel; + sel = Util.getGlobal().getSelection(); + sel.removeAllRanges(); + sel.addRange(range.toRange()); + return sel.toString(); + }; + + Util.xpathFromNode = function(el, relativeRoot) { + var exception, result; + try { + result = simpleXPathJQuery.call(el, relativeRoot); + } catch (_error) { + exception = _error; + console.log("jQuery-based XPath construction failed! Falling back to manual."); + result = simpleXPathPure.call(el, relativeRoot); + } + return result; + }; + + Util.nodeFromXPath = function(xp, root) { + var idx, name, node, step, steps, _i, _len, _ref1; + steps = xp.substring(1).split("/"); + node = root; + for (_i = 0, _len = steps.length; _i < _len; _i++) { + step = steps[_i]; + _ref1 = step.split("["), name = _ref1[0], idx = _ref1[1]; + idx = idx != null ? parseInt((idx != null ? idx.split("]") : void 0)[0]) : 1; + node = findChild(node, name.toLowerCase(), idx); + } + return node; + }; + + Util.escape = function(html) { return html.replace(/&(?!\w+;)/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); }; - $.fn.escape = function(html) { - if (arguments.length) { - return this.html($.escape(html)); + Util.uuid = (function() { + var counter; + counter = 0; + return function() { + return counter++; + }; + })(); + + Util.getGlobal = function() { + return (function() { + return this; + })(); + }; + + Util.maxZIndex = function($elements) { + var all, el; + all = (function() { + var _i, _len, _results; + _results = []; + for (_i = 0, _len = $elements.length; _i < _len; _i++) { + el = $elements[_i]; + if ($(el).css('position') === 'static') { + _results.push(-1); + } else { + _results.push(parseFloat($(el).css('z-index')) || -1); + } + } + return _results; + })(); + return Math.max.apply(Math, all); + }; + + Util.mousePosition = function(e, offsetEl) { + var offset, _ref1; + if ((_ref1 = $(offsetEl).css('position')) !== 'absolute' && _ref1 !== 'fixed' && _ref1 !== 'relative') { + offsetEl = $(offsetEl).offsetParent()[0]; } - return this.html(); + offset = $(offsetEl).offset(); + return { + top: e.pageY - offset.top, + left: e.pageX - offset.left + }; }; - $.fn.reverse = []._reverse || [].reverse; + Util.preventEventDefault = function(event) { + return event != null ? typeof event.preventDefault === "function" ? event.preventDefault() : void 0 : void 0; + }; functions = ["log", "debug", "info", "warn", "exception", "assert", "dir", "dirxml", "trace", "group", "groupEnd", "groupCollapsed", "time", "timeEnd", "profile", "profileEnd", "count", "clear", "table", "error", "notifyFirebug", "firebug", "userObjects"]; if (typeof console !== "undefined" && console !== null) { - if (!(console.group != null)) { + if (console.group == null) { console.group = function(name) { return console.log("GROUP: ", name); }; } - if (!(console.groupCollapsed != null)) { + if (console.groupCollapsed == null) { console.groupCollapsed = console.group; } for (_i = 0, _len = functions.length; _i < _len; _i++) { fn = functions[_i]; - if (!(console[fn] != null)) { + if (console[fn] == null) { console[fn] = function() { return console.log(_t("Not implemented:") + (" console." + name)); }; @@ -169,7 +366,6 @@ } Delegator = (function() { - Delegator.prototype.events = {}; Delegator.prototype.options = {}; @@ -179,47 +375,62 @@ function Delegator(element, options) { this.options = $.extend(true, {}, this.options, options); this.element = $(element); + this._closures = {}; this.on = this.subscribe; this.addEvents(); } + Delegator.prototype.destroy = function() { + return this.removeEvents(); + }; + Delegator.prototype.addEvents = function() { - var event, functionName, sel, selector, _k, _ref1, _ref2, _results; - _ref1 = this.events; + var event, _k, _len2, _ref1, _results; + _ref1 = Delegator._parseEvents(this.events); _results = []; - for (sel in _ref1) { - functionName = _ref1[sel]; - _ref2 = sel.split(' '), selector = 2 <= _ref2.length ? __slice.call(_ref2, 0, _k = _ref2.length - 1) : (_k = 0, []), event = _ref2[_k++]; - _results.push(this.addEvent(selector.join(' '), event, functionName)); + for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { + event = _ref1[_k]; + _results.push(this._addEvent(event.selector, event.event, event.functionName)); } return _results; }; - Delegator.prototype.addEvent = function(bindTo, event, functionName) { - var closure, isBlankSelector, + Delegator.prototype.removeEvents = function() { + var event, _k, _len2, _ref1, _results; + _ref1 = Delegator._parseEvents(this.events); + _results = []; + for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { + event = _ref1[_k]; + _results.push(this._removeEvent(event.selector, event.event, event.functionName)); + } + return _results; + }; + + Delegator.prototype._addEvent = function(selector, event, functionName) { + var closure, _this = this; closure = function() { return _this[functionName].apply(_this, arguments); }; - isBlankSelector = typeof bindTo === 'string' && bindTo.replace(/\s+/g, '') === ''; - if (isBlankSelector) { - bindTo = this.element; - } - if (typeof bindTo === 'string') { - this.element.delegate(bindTo, event, closure); + if (selector === '' && Delegator._isCustomEvent(event)) { + this.subscribe(event, closure); } else { - if (this.isCustomEvent(event)) { - this.subscribe(event, closure); - } else { - $(bindTo).bind(event, closure); - } + this.element.delegate(selector, event, closure); } + this._closures["" + selector + "/" + event + "/" + functionName] = closure; return this; }; - Delegator.prototype.isCustomEvent = function(event) { - event = event.split('.')[0]; - return $.inArray(event, Delegator.natives) === -1; + Delegator.prototype._removeEvent = function(selector, event, functionName) { + var closure; + closure = this._closures["" + selector + "/" + event + "/" + functionName]; + if (selector === '' && Delegator._isCustomEvent(event)) { + this.unsubscribe(event, closure); + } else { + this.element.undelegate(selector, event, closure); + } + delete this._closures["" + selector + "/" + event + "/" + functionName]; + return this; }; Delegator.prototype.publish = function() { @@ -246,6 +457,21 @@ })(); + Delegator._parseEvents = function(eventsObj) { + var event, events, functionName, sel, selector, _k, _ref1; + events = []; + for (sel in eventsObj) { + functionName = eventsObj[sel]; + _ref1 = sel.split(' '), selector = 2 <= _ref1.length ? __slice.call(_ref1, 0, _k = _ref1.length - 1) : (_k = 0, []), event = _ref1[_k++]; + events.push({ + selector: selector.join(' '), + event: event, + functionName: functionName + }); + } + return events; + }; + Delegator.natives = (function() { var key, specials, val; specials = (function() { @@ -262,6 +488,11 @@ return "blur focus focusin focusout load resize scroll unload click dblclick\nmousedown mouseup mousemove mouseover mouseout mouseenter mouseleave\nchange select submit keydown keypress keyup error".split(/[^a-z]+/).concat(specials); })(); + Delegator._isCustomEvent = function(event) { + event = event.split('.')[0]; + return $.inArray(event, Delegator.natives) === -1; + }; + Range = {}; Range.sniff = function(r) { @@ -283,10 +514,18 @@ root = document; } evaluateXPath = function(xp, nsResolver) { + var exception; if (nsResolver == null) { nsResolver = null; } - return document.evaluate('.' + xp, root, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + try { + return document.evaluate('.' + xp, root, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + } catch (_error) { + exception = _error; + console.log("XPath evaluation failed."); + console.log("Trying fallback..."); + return Util.nodeFromXPath(xp, root); + } }; if (!$.isXMLDoc(document.documentElement)) { return evaluateXPath(xpath); @@ -323,7 +562,6 @@ }; Range.RangeError = (function(_super) { - __extends(RangeError, _super); function RangeError(type, message, parent) { @@ -338,7 +576,6 @@ })(Error); Range.BrowserRange = (function() { - function BrowserRange(obj) { this.commonAncestorContainer = obj.commonAncestorContainer; this.startContainer = obj.startContainer; @@ -348,7 +585,7 @@ } BrowserRange.prototype.normalize = function(root) { - var it, node, nr, offset, p, r, _k, _len2, _ref1; + var n, node, nr, r; if (this.tainted) { console.error(_t("You may only call normalize() once on a BrowserRange!")); return false; @@ -356,44 +593,57 @@ this.tainted = true; } r = {}; - nr = {}; - _ref1 = ['start', 'end']; - for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { - p = _ref1[_k]; - node = this[p + 'Container']; - offset = this[p + 'Offset']; - if (!((node != null) && (offset != null))) { - return false; + if (this.startContainer.nodeType === Node.ELEMENT_NODE) { + r.start = Util.getFirstTextNodeNotBefore(this.startContainer.childNodes[this.startOffset]); + r.startOffset = 0; + } else { + r.start = this.startContainer; + r.startOffset = this.startOffset; + } + if (this.endContainer.nodeType === Node.ELEMENT_NODE) { + node = this.endContainer.childNodes[this.endOffset]; + if (node != null) { + n = node; + while ((n != null) && (n.nodeType !== Node.TEXT_NODE)) { + n = n.firstChild; + } + if (n != null) { + r.end = n; + r.endOffset = 0; + } } - if (node.nodeType === 1) { - it = node.childNodes[offset]; - node = it || node.childNodes[offset - 1]; - if (node.nodeType === 1 && !node.firstChild) { - it = null; - node = node.previousSibling; - } - while (node.nodeType !== 3) { - node = node.firstChild; - } - offset = it ? 0 : node.nodeValue.length; + if (r.end == null) { + node = this.endContainer.childNodes[this.endOffset - 1]; + r.end = Util.getLastTextNodeUpTo(node); + r.endOffset = r.end.nodeValue.length; } - r[p] = node; - r[p + 'Offset'] = offset; + } else { + r.end = this.endContainer; + r.endOffset = this.endOffset; } - nr.start = r.startOffset > 0 ? r.start.splitText(r.startOffset) : r.start; + nr = {}; + if (r.startOffset > 0) { + if (r.start.nodeValue.length > r.startOffset) { + nr.start = r.start.splitText(r.startOffset); + } else { + nr.start = r.start.nextSibling; + } + } else { + nr.start = r.start; + } if (r.start === r.end) { - if ((r.endOffset - r.startOffset) < nr.start.nodeValue.length) { + if (nr.start.nodeValue.length > (r.endOffset - r.startOffset)) { nr.start.splitText(r.endOffset - r.startOffset); } nr.end = nr.start; } else { - if (r.endOffset < r.end.nodeValue.length) { + if (r.end.nodeValue.length > r.endOffset) { r.end.splitText(r.endOffset); } nr.end = r.end; } nr.commonAncestor = this.commonAncestorContainer; - while (nr.commonAncestor.nodeType !== 1) { + while (nr.commonAncestor.nodeType !== Node.ELEMENT_NODE) { nr.commonAncestor = nr.commonAncestor.parentNode; } return new Range.NormalizedRange(nr); @@ -408,7 +658,6 @@ })(); Range.NormalizedRange = (function() { - function NormalizedRange(obj) { this.commonAncestor = obj.commonAncestor; this.start = obj.start; @@ -450,8 +699,8 @@ } else { origParent = $(node).parent(); } - xpath = origParent.xpath(root)[0]; - textNodes = origParent.textNodes(); + xpath = Util.xpathFromNode(origParent, root)[0]; + textNodes = Util.getTextNodes(origParent); nodes = textNodes.slice(0, textNodes.index(node)); offset = 0; for (_k = 0, _len2 = nodes.length; _k < _len2; _k++) { @@ -490,9 +739,9 @@ NormalizedRange.prototype.textNodes = function() { var end, start, textNodes, _ref1; - textNodes = $(this.commonAncestor).textNodes(); + textNodes = Util.getTextNodes($(this.commonAncestor)); _ref1 = [textNodes.index(this.start), textNodes.index(this.end)], start = _ref1[0], end = _ref1[1]; - return $.makeArray(textNodes.slice(start, end + 1 || 9e9)); + return $.makeArray(textNodes.slice(start, +end + 1 || 9e9)); }; NormalizedRange.prototype.toRange = function() { @@ -508,7 +757,6 @@ })(); Range.SerializedRange = (function() { - function SerializedRange(obj) { this.start = obj.start; this.startOffset = obj.startOffset; @@ -517,24 +765,29 @@ } SerializedRange.prototype.normalize = function(root) { - var contains, length, node, p, range, tn, _k, _l, _len2, _len3, _ref1, _ref2; + var contains, e, length, node, p, range, targetOffset, tn, _k, _l, _len2, _len3, _ref1, _ref2; range = {}; _ref1 = ['start', 'end']; for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { p = _ref1[_k]; try { node = Range.nodeFromXPath(this[p], root); - } catch (e) { + } catch (_error) { + e = _error; throw new Range.RangeError(p, ("Error while finding " + p + " node: " + this[p] + ": ") + e, e); } if (!node) { throw new Range.RangeError(p, "Couldn't find " + p + " node: " + this[p]); } length = 0; - _ref2 = $(node).textNodes(); + targetOffset = this[p + 'Offset']; + if (p === 'end') { + targetOffset--; + } + _ref2 = Util.getTextNodes($(node)); for (_l = 0, _len3 = _ref2.length; _l < _len3; _l++) { tn = _ref2[_l]; - if (length + tn.nodeValue.length >= this[p + 'Offset']) { + if (length + tn.nodeValue.length > targetOffset) { range[p + 'Container'] = tn; range[p + 'Offset'] = this[p + 'Offset'] - length; break; @@ -542,16 +795,16 @@ length += tn.nodeValue.length; } } - if (!(range[p + 'Offset'] != null)) { + if (range[p + 'Offset'] == null) { throw new Range.RangeError("" + p + "offset", "Couldn't find offset " + this[p + 'Offset'] + " in element " + this[p]); } } - contains = !(document.compareDocumentPosition != null) ? function(a, b) { + contains = document.compareDocumentPosition == null ? function(a, b) { return a.contains(b); } : function(a, b) { return a.compareDocumentPosition(b) & 16; }; - $(range.startContainer).parents().reverse().each(function() { + $(range.startContainer).parents().each(function() { if (contains(this, range.endContainer)) { range.commonAncestorContainer = this; return false; @@ -577,53 +830,9 @@ })(); - util = { - uuid: (function() { - var counter; - counter = 0; - return function() { - return counter++; - }; - })(), - getGlobal: function() { - return (function() { - return this; - })(); - }, - maxZIndex: function($elements) { - var all, el; - all = (function() { - var _k, _len2, _results; - _results = []; - for (_k = 0, _len2 = $elements.length; _k < _len2; _k++) { - el = $elements[_k]; - if ($(el).css('position') === 'static') { - _results.push(-1); - } else { - _results.push(parseInt($(el).css('z-index'), 10) || -1); - } - } - return _results; - })(); - return Math.max.apply(Math, all); - }, - mousePosition: function(e, offsetEl) { - var offset; - offset = $(offsetEl).offset(); - return { - top: e.pageY - offset.top, - left: e.pageX - offset.left - }; - }, - preventEventDefault: function(event) { - return event != null ? typeof event.preventDefault === "function" ? event.preventDefault() : void 0 : void 0; - } - }; - _Annotator = this.Annotator; Annotator = (function(_super) { - __extends(Annotator, _super); Annotator.prototype.events = { @@ -658,29 +867,17 @@ function Annotator(element, options) { this.onDeleteAnnotation = __bind(this.onDeleteAnnotation, this); - this.onEditAnnotation = __bind(this.onEditAnnotation, this); - this.onAdderClick = __bind(this.onAdderClick, this); - this.onAdderMousedown = __bind(this.onAdderMousedown, this); - this.onHighlightMouseover = __bind(this.onHighlightMouseover, this); - this.checkForEndSelection = __bind(this.checkForEndSelection, this); - this.checkForStartSelection = __bind(this.checkForStartSelection, this); - this.clearViewerHideTimer = __bind(this.clearViewerHideTimer, this); - this.startViewerHideTimer = __bind(this.startViewerHideTimer, this); - this.showViewer = __bind(this.showViewer, this); - this.onEditorSubmit = __bind(this.onEditorSubmit, this); - this.onEditorHide = __bind(this.onEditorHide, this); - this.showEditor = __bind(this.showEditor, this); Annotator.__super__.constructor.apply(this, arguments); this.plugins = {}; @@ -693,6 +890,7 @@ this._setupWrapper()._setupViewer()._setupEditor(); this._setupDynamicStyle(); this.adder = $(this.html.adder).appendTo(this.wrapper).hide(); + Annotator._instances.push(this); } Annotator.prototype._setupWrapper = function() { @@ -711,7 +909,7 @@ this.viewer.hide().on("edit", this.onEditAnnotation).on("delete", this.onDeleteAnnotation).addField({ load: function(field, annotation) { if (annotation.text) { - $(field).escape(annotation.text); + $(field).html(Util.escape(annotation.text)); } else { $(field).html("<i>" + (_t('No Comment')) + "</i>"); } @@ -764,15 +962,46 @@ } return _results; })()).join(''); - max = util.maxZIndex($(document.body).find(sel)); + max = Util.maxZIndex($(document.body).find(sel)); max = Math.max(max, 1000); style.text([".annotator-adder, .annotator-outer, .annotator-notice {", " z-index: " + (max + 20) + ";", "}", ".annotator-filter {", " z-index: " + (max + 10) + ";", "}"].join("\n")); return this; }; + Annotator.prototype.destroy = function() { + var idx, name, plugin, _base, _ref1; + Annotator.__super__.destroy.apply(this, arguments); + $(document).unbind({ + "mouseup": this.checkForEndSelection, + "mousedown": this.checkForStartSelection + }); + $('#annotator-dynamic-style').remove(); + this.adder.remove(); + this.viewer.destroy(); + this.editor.destroy(); + this.wrapper.find('.annotator-hl').each(function() { + $(this).contents().insertBefore(this); + return $(this).remove(); + }); + this.wrapper.contents().insertBefore(this.wrapper); + this.wrapper.remove(); + this.element.data('annotator', null); + _ref1 = this.plugins; + for (name in _ref1) { + plugin = _ref1[name]; + if (typeof (_base = this.plugins[name]).destroy === "function") { + _base.destroy(); + } + } + idx = Annotator._instances.indexOf(this); + if (idx !== -1) { + return Annotator._instances.splice(idx, 1); + } + }; + Annotator.prototype.getSelectedRanges = function() { var browserRange, i, normedRange, r, ranges, rangesToIgnore, selection, _k, _len2; - selection = util.getGlobal().getSelection(); + selection = Util.getGlobal().getSelection(); ranges = []; rangesToIgnore = []; if (!selection.isCollapsed) { @@ -811,11 +1040,8 @@ return annotation; }; - Annotator.prototype.setupAnnotation = function(annotation, fireEvents) { - var normed, normedRanges, r, root, _k, _l, _len2, _len3, _ref1; - if (fireEvents == null) { - fireEvents = true; - } + Annotator.prototype.setupAnnotation = function(annotation) { + var e, normed, normedRanges, r, root, _k, _l, _len2, _len3, _ref1; root = this.wrapper[0]; annotation.ranges || (annotation.ranges = this.selectedRanges); normedRanges = []; @@ -824,7 +1050,8 @@ r = _ref1[_k]; try { normedRanges.push(Range.sniff(r).normalize(root)); - } catch (e) { + } catch (_error) { + e = _error; if (e instanceof Range.RangeError) { this.publish('rangeNormalizeFail', [annotation, r, e]); } else { @@ -843,24 +1070,29 @@ } annotation.quote = annotation.quote.join(' / '); $(annotation.highlights).data('annotation', annotation); - if (fireEvents) { - this.publish('annotationCreated', [annotation]); - } + $(annotation.highlights).attr('data-annotation-id', annotation.id); return annotation; }; Annotator.prototype.updateAnnotation = function(annotation) { this.publish('beforeAnnotationUpdated', [annotation]); + $(annotation.highlights).attr('data-annotation-id', annotation.id); this.publish('annotationUpdated', [annotation]); return annotation; }; Annotator.prototype.deleteAnnotation = function(annotation) { - var h, _k, _len2, _ref1; - _ref1 = annotation.highlights; - for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { - h = _ref1[_k]; - $(h).replaceWith(h.childNodes); + var child, h, _k, _len2, _ref1; + if (annotation.highlights != null) { + _ref1 = annotation.highlights; + for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { + h = _ref1[_k]; + if (!(h.parentNode != null)) { + continue; + } + child = h.childNodes[0]; + $(h).replaceWith(h.childNodes); + } } this.publish('annotationDeleted', [annotation]); return annotation; @@ -880,7 +1112,7 @@ now = annList.splice(0, 10); for (_k = 0, _len2 = now.length; _k < _len2; _k++) { n = now[_k]; - _this.setupAnnotation(n, false); + _this.setupAnnotation(n); } if (annList.length > 0) { return setTimeout((function() { @@ -891,9 +1123,7 @@ } }; clone = annotations.slice(); - if (annotations.length) { - loader(annotations); - } + loader(annotations); return this; }; @@ -901,7 +1131,8 @@ if (this.plugins['Store']) { return this.plugins['Store'].dumpAnnotations(); } else { - return console.warn(_t("Can't dump annotations without Store plugin.")); + console.warn(_t("Can't dump annotations without Store plugin.")); + return false; } }; @@ -968,12 +1199,7 @@ }; Annotator.prototype.onEditorSubmit = function(annotation) { - this.publish('annotationEditorSubmit', [this.editor, annotation]); - if (annotation.ranges === void 0) { - return this.setupAnnotation(annotation); - } else { - return this.updateAnnotation(annotation); - } + return this.publish('annotationEditorSubmit', [this.editor, annotation]); }; Annotator.prototype.showViewer = function(annotations, location) { @@ -996,8 +1222,8 @@ Annotator.prototype.checkForStartSelection = function(event) { if (!(event && this.isAnnotator(event.target))) { this.startViewerHideTimer(); - return this.mouseIsDown = true; } + return this.mouseIsDown = true; }; Annotator.prototype.checkForEndSelection = function(event) { @@ -1012,33 +1238,36 @@ range = _ref1[_k]; container = range.commonAncestor; if ($(container).hasClass('annotator-hl')) { - container = $(container).parents('[class^=annotator-hl]')[0]; + container = $(container).parents('[class!=annotator-hl]')[0]; } if (this.isAnnotator(container)) { return; } } if (event && this.selectedRanges.length) { - return this.adder.css(util.mousePosition(event, this.wrapper[0])).show(); + return this.adder.css(Util.mousePosition(event, this.wrapper[0])).show(); } else { return this.adder.hide(); } }; Annotator.prototype.isAnnotator = function(element) { - return !!$(element).parents().andSelf().filter('[class^=annotator-]').not(this.wrapper).length; + return !!$(element).parents().addBack().filter('[class^=annotator-]').not(this.wrapper).length; }; Annotator.prototype.onHighlightMouseover = function(event) { var annotations; this.clearViewerHideTimer(); - if (this.mouseIsDown || this.viewer.isShown()) { + if (this.mouseIsDown) { return false; } - annotations = $(event.target).parents('.annotator-hl').andSelf().map(function() { + if (this.viewer.isShown()) { + this.viewer.hide(); + } + annotations = $(event.target).parents('.annotator-hl').addBack().map(function() { return $(this).data("annotation"); - }); - return this.showViewer($.makeArray(annotations), util.mousePosition(event, this.wrapper[0])); + }).toArray(); + return this.showViewer(annotations, Util.mousePosition(event, this.wrapper[0])); }; Annotator.prototype.onAdderMousedown = function(event) { @@ -1049,40 +1278,47 @@ }; Annotator.prototype.onAdderClick = function(event) { - var highlights, position, r, ranges; + var annotation, cancel, cleanup, position, save, + _this = this; if (event != null) { event.preventDefault(); } position = this.adder.position(); this.adder.hide(); - if (this.selectedRanges && this.selectedRanges.length) { - ranges = (function() { - var _k, _len2, _ref1, _results; - _ref1 = this.selectedRanges; - _results = []; - for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { - r = _ref1[_k]; - _results.push(Range.sniff(r).normalize()); - } - return _results; - }).call(this); - highlights = this.highlightRanges(ranges, 'annotator-hl annotator-hl-temporary'); - this.editor.element.one('hide', function() { - var h, _k, _len2, _results; - _results = []; - for (_k = 0, _len2 = highlights.length; _k < _len2; _k++) { - h = highlights[_k]; - _results.push($(h).replaceWith(h.childNodes)); - } - return _results; - }); - } - return this.showEditor(this.createAnnotation(), position); + annotation = this.setupAnnotation(this.createAnnotation()); + $(annotation.highlights).addClass('annotator-hl-temporary'); + save = function() { + cleanup(); + $(annotation.highlights).removeClass('annotator-hl-temporary'); + return _this.publish('annotationCreated', [annotation]); + }; + cancel = function() { + cleanup(); + return _this.deleteAnnotation(annotation); + }; + cleanup = function() { + _this.unsubscribe('annotationEditorHidden', cancel); + return _this.unsubscribe('annotationEditorSubmit', save); + }; + this.subscribe('annotationEditorHidden', cancel); + this.subscribe('annotationEditorSubmit', save); + return this.showEditor(annotation, position); }; Annotator.prototype.onEditAnnotation = function(annotation) { - var offset; + var cleanup, offset, update, + _this = this; offset = this.viewer.element.position(); + update = function() { + cleanup(); + return _this.updateAnnotation(annotation); + }; + cleanup = function() { + _this.unsubscribe('annotationEditorHidden', cleanup); + return _this.unsubscribe('annotationEditorSubmit', update); + }; + this.subscribe('annotationEditorHidden', cleanup); + this.subscribe('annotationEditorSubmit', update); this.viewer.hide(); return this.showEditor(annotation, offset); }; @@ -1097,7 +1333,6 @@ })(Delegator); Annotator.Plugin = (function(_super) { - __extends(Plugin, _super); function Plugin(element, options) { @@ -1110,26 +1345,47 @@ })(Delegator); - g = util.getGlobal(); - - if (!(((_ref1 = g.document) != null ? _ref1.evaluate : void 0) != null)) { + g = Util.getGlobal(); + + if (((_ref1 = g.document) != null ? _ref1.evaluate : void 0) == null) { $.getScript('http://assets.annotateit.org/vendor/xpath.min.js'); } - if (!(g.getSelection != null)) { + if (g.getSelection == null) { $.getScript('http://assets.annotateit.org/vendor/ierange.min.js'); } - if (!(g.JSON != null)) { + if (g.JSON == null) { $.getScript('http://assets.annotateit.org/vendor/json2.min.js'); } + if (g.Node == null) { + g.Node = { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }; + } + Annotator.$ = $; Annotator.Delegator = Delegator; Annotator.Range = Range; + Annotator.Util = Util; + + Annotator._instances = []; + Annotator._t = _t; Annotator.supported = function() { @@ -1139,16 +1395,31 @@ }; Annotator.noConflict = function() { - util.getGlobal().Annotator = _Annotator; + Util.getGlobal().Annotator = _Annotator; return this; }; - $.plugin('annotator', Annotator); + $.fn.annotator = function(options) { + var args; + args = Array.prototype.slice.call(arguments, 1); + return this.each(function() { + var instance; + instance = $.data(this, 'annotator'); + if (options === 'destroy') { + $.removeData(this, 'annotator'); + return instance != null ? instance.destroy(args) : void 0; + } else if (instance) { + return options && instance[options].apply(instance, args); + } else { + instance = new Annotator(this, options); + return $.data(this, 'annotator', instance); + } + }); + }; this.Annotator = Annotator; Annotator.Widget = (function(_super) { - __extends(Widget, _super); Widget.prototype.classes = { @@ -1164,10 +1435,15 @@ this.classes = $.extend({}, Annotator.Widget.prototype.classes, this.classes); } + Widget.prototype.destroy = function() { + this.removeEvents(); + return this.element.remove(); + }; + Widget.prototype.checkOrientation = function() { var current, offset, viewport, widget, window; this.resetOrientation(); - window = $(util.getGlobal()); + window = $(Annotator.Util.getGlobal()); widget = this.element.children(":first"); offset = widget.offset(); viewport = { @@ -1215,7 +1491,6 @@ })(Delegator); Annotator.Editor = (function(_super) { - __extends(Editor, _super); Editor.prototype.events = { @@ -1237,15 +1512,10 @@ function Editor(options) { this.onCancelButtonMouseover = __bind(this.onCancelButtonMouseover, this); - this.processKeypress = __bind(this.processKeypress, this); - this.submit = __bind(this.submit, this); - this.load = __bind(this.load, this); - this.hide = __bind(this.hide, this); - this.show = __bind(this.show, this); Editor.__super__.constructor.call(this, $(this.html)[0], options); this.fields = []; @@ -1253,7 +1523,7 @@ } Editor.prototype.show = function(event) { - util.preventEventDefault(event); + Annotator.Util.preventEventDefault(event); this.element.removeClass(this.classes.hide); this.element.find('.annotator-save').addClass(this.classes.focus); this.checkOrientation(); @@ -1263,7 +1533,7 @@ }; Editor.prototype.hide = function(event) { - util.preventEventDefault(event); + Annotator.Util.preventEventDefault(event); this.element.addClass(this.classes.hide); return this.publish('hide'); }; @@ -1282,7 +1552,7 @@ Editor.prototype.submit = function(event) { var field, _k, _len2, _ref2; - util.preventEventDefault(event); + Annotator.Util.preventEventDefault(event); _ref2 = this.fields; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { field = _ref2[_k]; @@ -1295,7 +1565,7 @@ Editor.prototype.addField = function(options) { var element, field, input; field = $.extend({ - id: 'annotator-field-' + util.uuid(), + id: 'annotator-field-' + Annotator.Util.uuid(), type: 'input', label: '', load: function() {}, @@ -1311,6 +1581,9 @@ case 'input': case 'checkbox': input = $('<input />'); + break; + case 'select': + input = $('<select />'); } element.append(input); input.attr({ @@ -1436,7 +1709,6 @@ })(Annotator.Widget); Annotator.Viewer = (function(_super) { - __extends(Viewer, _super); Viewer.prototype.events = { @@ -1460,13 +1732,9 @@ function Viewer(options) { this.onDeleteClick = __bind(this.onDeleteClick, this); - this.onEditClick = __bind(this.onEditClick, this); - this.load = __bind(this.load, this); - this.hide = __bind(this.hide, this); - this.show = __bind(this.show, this); Viewer.__super__.constructor.call(this, $(this.html.element)[0], options); this.item = $(this.html.item)[0]; @@ -1477,7 +1745,7 @@ Viewer.prototype.show = function(event) { var controls, _this = this; - util.preventEventDefault(event); + Annotator.Util.preventEventDefault(event); controls = this.element.find('.annotator-controls').addClass(this.classes.showControls); setTimeout((function() { return controls.removeClass(_this.classes.showControls); @@ -1491,7 +1759,7 @@ }; Viewer.prototype.hide = function(event) { - util.preventEventDefault(event); + Annotator.Util.preventEventDefault(event); this.element.addClass(this.classes.hide); return this.publish('hide'); }; @@ -1511,7 +1779,7 @@ links = new LinkParser(annotation.links || []).get('alternate', { 'type': 'text/html' }); - if (links.length === 0 || !(links[0].href != null)) { + if (links.length === 0 || (links[0].href == null)) { link.remove(); } else { link.attr('href', links[0].href); @@ -1576,7 +1844,6 @@ })(Annotator.Widget); LinkParser = (function() { - function LinkParser(data) { this.data = data; } @@ -1622,7 +1889,6 @@ Annotator = Annotator || {}; Annotator.Notification = (function(_super) { - __extends(Notification, _super); Notification.prototype.events = { @@ -1641,7 +1907,6 @@ function Notification(options) { this.hide = __bind(this.hide, this); - this.show = __bind(this.show, this); Notification.__super__.constructor.call(this, $(this.options.html).appendTo(document.body)[0], options); } @@ -1650,13 +1915,17 @@ if (status == null) { status = Annotator.Notification.INFO; } - $(this.element).addClass(this.options.classes.show).addClass(this.options.classes[status]).escape(message || ""); + this.currentStatus = status; + $(this.element).addClass(this.options.classes.show).addClass(this.options.classes[this.currentStatus]).html(Util.escape(message || "")); setTimeout(this.hide, 5000); return this; }; Notification.prototype.hide = function() { - $(this.element).removeClass(this.options.classes.show); + if (this.currentStatus == null) { + this.currentStatus = Annotator.Notification.INFO; + } + $(this.element).removeClass(this.options.classes.show).removeClass(this.options.classes[this.currentStatus]); return this; }; @@ -1664,7 +1933,7 @@ })(Delegator); - Annotator.Notification.INFO = 'show'; + Annotator.Notification.INFO = 'info'; Annotator.Notification.SUCCESS = 'success'; @@ -1678,11 +1947,11 @@ }); Annotator.Plugin.Unsupported = (function(_super) { - __extends(Unsupported, _super); function Unsupported() { - return Unsupported.__super__.constructor.apply(this, arguments); + _ref2 = Unsupported.__super__.constructor.apply(this, arguments); + return _ref2; } Unsupported.prototype.options = { @@ -1706,8 +1975,8 @@ })(Annotator.Plugin); createDateFromISO8601 = function(string) { - var d, date, offset, regexp, time, _ref2; - regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?"; + var d, date, offset, regexp, time, _ref3; + regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?"; d = string.match(new RegExp(regexp)); offset = 0; date = new Date(d[1], 0, 1); @@ -1731,7 +2000,7 @@ } if (d[14]) { offset = (Number(d[16]) * 60) + Number(d[17]); - offset *= (_ref2 = d[15] === '-') != null ? _ref2 : { + offset *= (_ref3 = d[15] === '-') != null ? _ref3 : { 1: -1 }; } @@ -1777,10 +2046,10 @@ }; base64UrlDecode = function(data) { - var i, m, _k, _ref2; + var i, m, _k, _ref3; m = data.length % 4; if (m !== 0) { - for (i = _k = 0, _ref2 = 4 - m; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) { + for (i = _k = 0, _ref3 = 4 - m; 0 <= _ref3 ? _k < _ref3 : _k > _ref3; i = 0 <= _ref3 ? ++_k : --_k) { data += '='; } } @@ -1790,13 +2059,12 @@ }; parseToken = function(token) { - var head, payload, sig, _ref2; - _ref2 = token.split('.'), head = _ref2[0], payload = _ref2[1], sig = _ref2[2]; + var head, payload, sig, _ref3; + _ref3 = token.split('.'), head = _ref3[0], payload = _ref3[1], sig = _ref3[2]; return JSON.parse(base64UrlDecode(payload)); }; Annotator.Plugin.Auth = (function(_super) { - __extends(Auth, _super); Auth.prototype.options = { @@ -1881,7 +2149,11 @@ Auth.prototype.haveValidToken = function() { var allFields; allFields = this._unsafeToken && this._unsafeToken.issuedAt && this._unsafeToken.ttl && this._unsafeToken.consumerKey; - return allFields && this.timeToExpiry() > 0; + if (allFields && this.timeToExpiry() > 0) { + return true; + } else { + return false; + } }; Auth.prototype.timeToExpiry = function() { @@ -1906,7 +2178,7 @@ }; Auth.prototype.withToken = function(callback) { - if (!(callback != null)) { + if (callback == null) { return; } if (this.haveValidToken()) { @@ -1924,7 +2196,6 @@ })(Annotator.Plugin); Annotator.Plugin.Store = (function(_super) { - __extends(Store, _super); Store.prototype.events = { @@ -1934,10 +2205,10 @@ }; Store.prototype.options = { + annotationData: {}, + emulateHTTP: false, + loadFromSearch: false, prefix: '/store', - autoFetch: true, - annotationData: {}, - loadFromSearch: false, urls: { create: '/annotations', read: '/annotations/:id', @@ -1949,11 +2220,8 @@ function Store(element, options) { this._onError = __bind(this._onError, this); - this._onLoadAnnotationsFromSearch = __bind(this._onLoadAnnotationsFromSearch, this); - this._onLoadAnnotations = __bind(this._onLoadAnnotations, this); - this._getAnnotations = __bind(this._getAnnotations, this); Store.__super__.constructor.apply(this, arguments); this.annotations = []; @@ -1983,7 +2251,7 @@ if (__indexOf.call(this.annotations, annotation) < 0) { this.registerAnnotation(annotation); return this._apiRequest('create', annotation, function(data) { - if (!(data.id != null)) { + if (data.id == null) { console.warn(Annotator._t("Warning: No ID returned from server for annotation "), annotation); } return _this.updateAnnotation(annotation, data); @@ -2033,11 +2301,28 @@ }; Store.prototype._onLoadAnnotations = function(data) { + var a, annotation, annotationMap, newData, _k, _l, _len2, _len3, _ref3; if (data == null) { data = []; } - this.annotations = data; - return this.annotator.loadAnnotations(data.slice()); + annotationMap = {}; + _ref3 = this.annotations; + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + a = _ref3[_k]; + annotationMap[a.id] = a; + } + newData = []; + for (_l = 0, _len3 = data.length; _l < _len3; _l++) { + a = data[_l]; + if (annotationMap[a.id]) { + annotation = annotationMap[a.id]; + this.updateAnnotation(annotation, a); + } else { + newData.push(a); + } + } + this.annotations = this.annotations.concat(newData); + return this.annotator.loadAnnotations(newData.slice()); }; Store.prototype.loadAnnotationsFromSearch = function(searchOptions) { @@ -2052,11 +2337,11 @@ }; Store.prototype.dumpAnnotations = function() { - var ann, _k, _len2, _ref2, _results; - _ref2 = this.annotations; + var ann, _k, _len2, _ref3, _results; + _ref3 = this.annotations; _results = []; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - ann = _ref2[_k]; + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + ann = _ref3[_k]; _results.push(JSON.parse(this._dataFor(ann))); } return _results; @@ -2074,33 +2359,50 @@ }; Store.prototype._apiRequestOptions = function(action, obj, onSuccess) { - var opts; + var data, method, opts; + method = this._methodFor(action); opts = { - type: this._methodFor(action), + type: method, headers: this.element.data('annotator:headers'), dataType: "json", success: onSuccess || function() {}, error: this._onError }; + if (this.options.emulateHTTP && (method === 'PUT' || method === 'DELETE')) { + opts.headers = $.extend(opts.headers, { + 'X-HTTP-Method-Override': method + }); + opts.type = 'POST'; + } if (action === "search") { opts = $.extend(opts, { data: obj }); - } else { - opts = $.extend(opts, { - data: obj && this._dataFor(obj), - contentType: "application/json; charset=utf-8" - }); + return opts; } + data = obj && this._dataFor(obj); + if (this.options.emulateJSON) { + opts.data = { + json: data + }; + if (this.options.emulateHTTP) { + opts.data._method = method; + } + return opts; + } + opts = $.extend(opts, { + data: data, + contentType: "application/json; charset=utf-8" + }); return opts; }; Store.prototype._urlFor = function(action, id) { - var replaceWith, url; - replaceWith = id != null ? '/' + id : ''; - url = this.options.prefix || '/'; + var url; + url = this.options.prefix != null ? this.options.prefix : ''; url += this.options.urls[action]; - url = url.replace(/\/:id/, replaceWith); + url = url.replace(/\/:id/, id != null ? '/' + id : ''); + url = url.replace(/:id/, id != null ? id : ''); return url; }; @@ -2156,7 +2458,6 @@ })(Annotator.Plugin); Annotator.Plugin.Permissions = (function(_super) { - __extends(Permissions, _super); Permissions.prototype.events = { @@ -2187,7 +2488,11 @@ } return false; } else if (annotation.user) { - return user && this.userId(user) === this.userId(annotation.user); + if (user) { + return this.userId(user) === this.userId(annotation.user); + } else { + return false; + } } return true; }, @@ -2202,13 +2507,9 @@ function Permissions(element, options) { this._setAuthFromToken = __bind(this._setAuthFromToken, this); - this.updateViewer = __bind(this.updateViewer, this); - this.updateAnnotationPermissions = __bind(this.updateAnnotationPermissions, this); - this.updatePermissionsField = __bind(this.updatePermissionsField, this); - this.addFieldsToAnnotation = __bind(this.addFieldsToAnnotation, this); Permissions.__super__.constructor.apply(this, arguments); if (this.options.user) { @@ -2256,14 +2557,14 @@ label: Annotator._t('User'), property: 'user', isFiltered: function(input, user) { - var keyword, _k, _len2, _ref2; + var keyword, _k, _len2, _ref3; user = _this.options.userString(user); if (!(input && user)) { return false; } - _ref2 = input.split(/\s*/); - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - keyword = _ref2[_k]; + _ref3 = input.split(/\s*/); + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + keyword = _ref3[_k]; if (user.indexOf(keyword) === -1) { return false; } @@ -2280,7 +2581,7 @@ Permissions.prototype.addFieldsToAnnotation = function(annotation) { if (annotation) { - annotation.permissions = this.options.permissions; + annotation.permissions = $.extend(true, {}, this.options.permissions); if (this.user) { return annotation.user = this.user; } @@ -2315,13 +2616,13 @@ Permissions.prototype.updateAnnotationPermissions = function(type, field, annotation) { var dataKey; if (!annotation.permissions) { - annotation.permissions = this.options.permissions; + annotation.permissions = $.extend(true, {}, this.options.permissions); } dataKey = type + '-permissions'; if ($(field).find('input').is(':checked')) { return annotation.permissions[type] = []; } else { - return annotation.permissions[type] = [this.user]; + return annotation.permissions[type] = [this.options.userId(this.user)]; } }; @@ -2330,7 +2631,7 @@ field = $(field); username = this.options.userString(annotation.user); if (annotation.user && username && typeof username === 'string') { - user = Annotator.$.escape(this.options.userString(annotation.user)); + user = Annotator.Util.escape(this.options.userString(annotation.user)); field.html(user).addClass('annotator-user'); } else { field.remove(); @@ -2354,7 +2655,6 @@ })(Annotator.Plugin); Annotator.Plugin.Filter = (function(_super) { - __extends(Filter, _super); Filter.prototype.events = { @@ -2384,13 +2684,13 @@ filters: [], addAnnotationFilter: true, isFiltered: function(input, property) { - var keyword, _k, _len2, _ref2; + var keyword, _k, _len2, _ref3; if (!(input && property)) { return false; } - _ref2 = input.split(/\s*/); - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - keyword = _ref2[_k]; + _ref3 = input.split(/\s+/); + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + keyword = _ref3[_k]; if (property.indexOf(keyword) === -1) { return false; } @@ -2401,17 +2701,11 @@ function Filter(element, options) { this._onPreviousClick = __bind(this._onPreviousClick, this); - this._onNextClick = __bind(this._onNextClick, this); - this._onFilterKeyup = __bind(this._onFilterKeyup, this); - this._onFilterBlur = __bind(this._onFilterBlur, this); - this._onFilterFocus = __bind(this._onFilterFocus, this); - this.updateHighlights = __bind(this.updateHighlights, this); - var _base; element = $(this.html.element).appendTo((options != null ? options.appendTo : void 0) || this.options.appendTo); Filter.__super__.constructor.call(this, element, options); @@ -2422,10 +2716,10 @@ } Filter.prototype.pluginInit = function() { - var filter, _k, _len2, _ref2; - _ref2 = this.options.filters; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - filter = _ref2[_k]; + var filter, _k, _len2, _ref3; + _ref3 = this.options.filters; + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + filter = _ref3[_k]; this.addFilter(filter); } this.updateHighlights(); @@ -2438,6 +2732,15 @@ } }; + Filter.prototype.destroy = function() { + var currentMargin, html; + Filter.__super__.destroy.apply(this, arguments); + html = $('html'); + currentMargin = parseInt(html.css('padding-top'), 10) || 0; + html.css('padding-top', currentMargin - this.element.outerHeight()); + return this.element.remove(); + }; + Filter.prototype._insertSpacer = function() { var currentMargin, html; html = $('html'); @@ -2464,11 +2767,11 @@ isFiltered: this.options.isFiltered }, options); if (!((function() { - var _k, _len2, _ref2, _results; - _ref2 = this.filters; + var _k, _len2, _ref3, _results; + _ref3 = this.filters; _results = []; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - f = _ref2[_k]; + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + f = _ref3[_k]; if (f.property === filter.property) { _results.push(f); } @@ -2491,7 +2794,7 @@ }; Filter.prototype.updateFilter = function(filter) { - var annotation, annotations, input, property, _k, _len2, _ref2; + var annotation, annotations, input, property, _k, _len2, _ref3; filter.annotations = []; this.updateHighlights(); this.resetHighlights(); @@ -2500,9 +2803,9 @@ annotations = this.highlights.map(function() { return $(this).data('annotation'); }); - _ref2 = $.makeArray(annotations); - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - annotation = _ref2[_k]; + _ref3 = $.makeArray(annotations); + for (_k = 0, _len2 = _ref3.length; _k < _len2; _k++) { + annotation = _ref3[_k]; property = annotation[filter.property]; if (filter.isFiltered(input, property)) { filter.annotations.push(annotation); @@ -2518,11 +2821,11 @@ }; Filter.prototype.filterHighlights = function() { - var activeFilters, annotation, annotations, filtered, highlights, index, uniques, _k, _len2, _ref2; + var activeFilters, annotation, annotations, filtered, highlights, index, uniques, _k, _len2, _ref3; activeFilters = $.grep(this.filters, function(filter) { return !!filter.annotations.length; }); - filtered = ((_ref2 = activeFilters[0]) != null ? _ref2.annotations : void 0) || []; + filtered = ((_ref3 = activeFilters[0]) != null ? _ref3.annotations : void 0) || []; if (activeFilters.length > 1) { annotations = []; $.each(activeFilters, function() { @@ -2626,7 +2929,6 @@ })(Annotator.Plugin); Annotator.Plugin.Markdown = (function(_super) { - __extends(Markdown, _super); Markdown.prototype.events = { @@ -2645,7 +2947,7 @@ Markdown.prototype.updateTextField = function(field, annotation) { var text; - text = Annotator.$.escape(annotation.text || ''); + text = Annotator.Util.escape(annotation.text || ''); return $(field).html(this.convert(text)); }; @@ -2658,14 +2960,13 @@ })(Annotator.Plugin); Annotator.Plugin.Tags = (function(_super) { - __extends(Tags, _super); function Tags() { this.setAnnotationTags = __bind(this.setAnnotationTags, this); - this.updateField = __bind(this.updateField, this); - return Tags.__super__.constructor.apply(this, arguments); + _ref3 = Tags.__super__.constructor.apply(this, arguments); + return _ref3; } Tags.prototype.options = { @@ -2736,7 +3037,7 @@ return field.addClass('annotator-tags').html(function() { var string; return string = $.map(annotation.tags, function(tag) { - return '<span class="annotator-tag">' + Annotator.$.escape(tag) + '</span>'; + return '<span class="annotator-tag">' + Annotator.Util.escape(tag) + '</span>'; }).join(' '); }); } else { @@ -2773,11 +3074,11 @@ }; Annotator.Plugin.DigilibIntegrator = (function(_super) { - __extends(DigilibIntegrator, _super); function DigilibIntegrator() { - return DigilibIntegrator.__super__.constructor.apply(this, arguments); + _ref4 = DigilibIntegrator.__super__.constructor.apply(this, arguments); + return _ref4; } DigilibIntegrator.prototype.events = { @@ -2823,3 +3124,6 @@ })(Annotator.Plugin); }).call(this); + +// +//# sourceMappingURL=annotator-dl.map \ No newline at end of file
--- a/webapp/src/main/webapp/jquery/annotator-dl.min.js Fri Jan 16 18:20:15 2015 +0100 +++ b/webapp/src/main/webapp/jquery/annotator-dl.min.js Fri Jan 16 20:57:20 2015 +0100 @@ -1,11 +1,20 @@ + /* -** Annotator 1.2.5-dev-a4cd304 +** Annotator v1.2.9-dev-b091a74 ** https://github.com/okfn/annotator/ ** -** Copyright 2012 Aron Carroll, Rufus Pollock, and Nick Stenning. +** Copyright 2015, the Annotator project contributors. ** Dual licensed under the MIT and GPLv3 licenses. ** https://github.com/okfn/annotator/blob/master/LICENSE ** -** Built at: 2012-11-23 09:46:08Z -*/(function(){var e,t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w,E,S,x=[].slice,T={}.hasOwnProperty,N=function(e,t){function r(){this.constructor=e}for(var n in t)T.call(t,n)&&(e[n]=t[n]);return r.prototype=t.prototype,e.prototype=new r,e.__super__=t.prototype,e},C=function(e,t){return function(){return e.apply(t,arguments)}},k=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++)if(t in this&&this[t]===e)return t;return-1};c=null,typeof Gettext!="undefined"&&Gettext!==null?(v=new Gettext({domain:"annotator"}),c=function(e){return v.gettext(e)}):c=function(e){return e},S=function(e){return c(e)},(typeof jQuery!="undefined"&&jQuery!==null?(w=jQuery.fn)!=null?w.jquery:void 0:void 0)||console.error(S("Annotator requires jQuery: have you included lib/vendor/jquery.js?")),JSON&&JSON.parse&&JSON.stringify||console.error(S("Annotator requires a JSON implementation: have you included lib/vendor/json2.js?")),e=jQuery.sub(),e.flatten=function(t){var n;return n=function(t){var r,i,s,o;i=[];for(s=0,o=t.length;s<o;s++)r=t[s],i=i.concat(r&&e.isArray(r)?n(r):r);return i},n(t)},e.plugin=function(t,n){return jQuery.fn[t]=function(r){var i;return i=Array.prototype.slice.call(arguments,1),this.each(function(){var s;return s=e.data(this,t),s?r&&s[r].apply(s,i):(s=new n(this,r),e.data(this,t,s))})}},e.fn.textNodes=function(){var t;return t=function(e){var n;if(e&&e.nodeType!==3){n=[];if(e.nodeType!==8){e=e.lastChild;while(e)n.push(t(e)),e=e.previousSibling}return n.reverse()}return e},this.map(function(){return e.flatten(t(this))})},e.fn.xpath=function(t){var n;return n=this.map(function(){var n,r,i;i="",n=this;while(n&&n.nodeType===1&&n!==t)r=e(n.parentNode).children(n.tagName).index(n)+1,r="["+r+"]",i="/"+n.tagName.toLowerCase()+r+i,n=n.parentNode;return i}),n.get()},e.escape=function(e){return e.replace(/&(?!\w+;)/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")},e.fn.escape=function(t){return arguments.length?this.html(e.escape(t)):this.html()},e.fn.reverse=[]._reverse||[].reverse,f=["log","debug","info","warn","exception","assert","dir","dirxml","trace","group","groupEnd","groupCollapsed","time","timeEnd","profile","profileEnd","count","clear","table","error","notifyFirebug","firebug","userObjects"];if(typeof console!="undefined"&&console!==null){console.group==null&&(console.group=function(e){return console.log("GROUP: ",e)}),console.groupCollapsed==null&&(console.groupCollapsed=console.group);for(m=0,y=f.length;m<y;m++)a=f[m],console[a]==null&&(console[a]=function(){return console.log(S("Not implemented:")+(" console."+name))})}else{this.console={};for(g=0,b=f.length;g<b;g++)a=f[g],this.console[a]=function(){};this.console.error=function(){var e;return e=1<=arguments.length?x.call(arguments,0):[],alert("ERROR: "+e.join(", "))},this.console.warn=function(){var e;return e=1<=arguments.length?x.call(arguments,0):[],alert("WARNING: "+e.join(", "))}}n=function(){function t(t,n){this.options=e.extend(!0,{},this.options,n),this.element=e(t),this.on=this.subscribe,this.addEvents()}return t.prototype.events={},t.prototype.options={},t.prototype.element=null,t.prototype.addEvents=function(){var e,t,n,r,i,s,o,u;s=this.events,u=[];for(n in s)t=s[n],o=n.split(" "),r=2<=o.length?x.call(o,0,i=o.length-1):(i=0,[]),e=o[i++],u.push(this.addEvent(r.join(" "),e,t));return u},t.prototype.addEvent=function(t,n,r){var i,s,o=this;return i=function(){return o[r].apply(o,arguments)},s=typeof t=="string"&&t.replace(/\s+/g,"")==="",s&&(t=this.element),typeof t=="string"?this.element.delegate(t,n,i):this.isCustomEvent(n)?this.subscribe(n,i):e(t).bind(n,i),this},t.prototype.isCustomEvent=function(n){return n=n.split(".")[0],e.inArray(n,t.natives)===-1},t.prototype.publish=function(){return this.element.triggerHandler.apply(this.element,arguments),this},t.prototype.subscribe=function(t,n){var r;return r=function(){return n.apply(this,[].slice.call(arguments,1))},r.guid=n.guid=e.guid+=1,this.element.bind(t,r),this},t.prototype.unsubscribe=function(){return this.element.unbind.apply(this.element,arguments),this},t}(),n.natives=function(){var e,t,n;return t=function(){var t,r;t=jQuery.event.special,r=[];for(e in t){if(!T.call(t,e))continue;n=t[e],r.push(e)}return r}(),"blur focus focusin focusout load resize scroll unload click dblclick\nmousedown mouseup mousemove mouseover mouseout mouseenter mouseleave\nchange select submit keydown keypress keyup error".split(/[^a-z]+/).concat(t)}(),i={},i.sniff=function(e){return e.commonAncestorContainer!=null?new i.BrowserRange(e):typeof e.start=="string"?new i.SerializedRange(e):e.start&&typeof e.start=="object"?new i.NormalizedRange(e):(console.error(S("Could not sniff range type")),!1)},i.nodeFromXPath=function(t,n){var r,i,s,o,u;return n==null&&(n=document),i=function(e,t){return t==null&&(t=null),document.evaluate("."+e,n,t,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue},e.isXMLDoc(document.documentElement)?(r=document.createNSResolver(document.ownerDocument===null?document.documentElement:document.ownerDocument.documentElement),o=i(t,r),o||(t=function(){var e,n,r,i;r=t.split("/"),i=[];for(e=0,n=r.length;e<n;e++)u=r[e],u&&u.indexOf(":")===-1?i.push(u.replace(/^([a-z]+)/,"xhtml:$1")):i.push(u);return i}().join("/"),s=document.lookupNamespaceURI(null),r=function(e){return e==="xhtml"?s:document.documentElement.getAttribute("xmlns:"+e)},o=i(t,r)),o):i(t)},i.RangeError=function(e){function t(e,n,r){this.type=e,this.message=n,this.parent=r!=null?r:null,t.__super__.constructor.call(this,this.message)}return N(t,e),t}(Error),i.BrowserRange=function(){function e(e){this.commonAncestorContainer=e.commonAncestorContainer,this.startContainer=e.startContainer,this.startOffset=e.startOffset,this.endContainer=e.endContainer,this.endOffset=e.endOffset}return e.prototype.normalize=function(e){var t,n,r,s,o,u,a,f,l;if(this.tainted)return console.error(S("You may only call normalize() once on a BrowserRange!")),!1;this.tainted=!0,u={},r={},l=["start","end"];for(a=0,f=l.length;a<f;a++){o=l[a],n=this[o+"Container"],s=this[o+"Offset"];if(n==null||s==null)return!1;if(n.nodeType===1){t=n.childNodes[s],n=t||n.childNodes[s-1],n.nodeType===1&&!n.firstChild&&(t=null,n=n.previousSibling);while(n.nodeType!==3)n=n.firstChild;s=t?0:n.nodeValue.length}u[o]=n,u[o+"Offset"]=s}r.start=u.startOffset>0?u.start.splitText(u.startOffset):u.start,u.start===u.end?(u.endOffset-u.startOffset<r.start.nodeValue.length&&r.start.splitText(u.endOffset-u.startOffset),r.end=r.start):(u.endOffset<u.end.nodeValue.length&&u.end.splitText(u.endOffset),r.end=u.end),r.commonAncestor=this.commonAncestorContainer;while(r.commonAncestor.nodeType!==1)r.commonAncestor=r.commonAncestor.parentNode;return new i.NormalizedRange(r)},e.prototype.serialize=function(e,t){return this.normalize(e).serialize(e,t)},e}(),i.NormalizedRange=function(){function t(e){this.commonAncestor=e.commonAncestor,this.start=e.start,this.end=e.end}return t.prototype.normalize=function(e){return this},t.prototype.limit=function(t){var n,r,i,s,o,u;n=e.grep(this.textNodes(),function(n){return n.parentNode===t||e.contains(t,n.parentNode)});if(!n.length)return null;this.start=n[0],this.end=n[n.length-1],i=e(this.start).parents(),u=e(this.end).parents();for(s=0,o=u.length;s<o;s++){r=u[s];if(i.index(r)!==-1){this.commonAncestor=r;break}}return this},t.prototype.serialize=function(t,n){var r,s,o;return s=function(r,i){var s,o,u,a,f,l,c,h;n?a=e(r).parents(":not("+n+")").eq(0):a=e(r).parent(),l=a.xpath(t)[0],f=a.textNodes(),o=f.slice(0,f.index(r)),u=0;for(c=0,h=o.length;c<h;c++)s=o[c],u+=s.nodeValue.length;return i?[l,u+r.nodeValue.length]:[l,u]},o=s(this.start),r=s(this.end,!0),new i.SerializedRange({start:o[0],end:r[0],startOffset:o[1],endOffset:r[1]})},t.prototype.text=function(){var e;return function(){var t,n,r,i;r=this.textNodes(),i=[];for(t=0,n=r.length;t<n;t++)e=r[t],i.push(e.nodeValue);return i}.call(this).join("")},t.prototype.textNodes=function(){var t,n,r,i;return r=e(this.commonAncestor).textNodes(),i=[r.index(this.start),r.index(this.end)],n=i[0],t=i[1],e.makeArray(r.slice(n,t+1||9e9))},t.prototype.toRange=function(){var e;return e=document.createRange(),e.setStartBefore(this.start),e.setEndAfter(this.end),e},t}(),i.SerializedRange=function(){function t(e){this.start=e.start,this.startOffset=e.startOffset,this.end=e.end,this.endOffset=e.endOffset}return t.prototype.normalize=function(t){var n,r,s,o,u,a,f,l,c,h,p,d;u={},p=["start","end"];for(f=0,c=p.length;f<c;f++){o=p[f];try{s=i.nodeFromXPath(this[o],t)}catch(v){throw new i.RangeError(o,"Error while finding "+o+" node: "+this[o]+": "+v,v)}if(!s)throw new i.RangeError(o,"Couldn't find "+o+" node: "+this[o]);r=0,d=e(s).textNodes();for(l=0,h=d.length;l<h;l++){a=d[l];if(r+a.nodeValue.length>=this[o+"Offset"]){u[o+"Container"]=a,u[o+"Offset"]=this[o+"Offset"]-r;break}r+=a.nodeValue.length}if(u[o+"Offset"]==null)throw new i.RangeError(""+o+"offset","Couldn't find offset "+this[o+"Offset"]+" in element "+this[o])}return n=document.compareDocumentPosition==null?function(e,t){return e.contains(t)}:function(e,t){return e.compareDocumentPosition(t)&16},e(u.startContainer).parents().reverse().each(function(){if(n(this,u.endContainer))return u.commonAncestorContainer=this,!1}),(new i.BrowserRange(u)).normalize(t)},t.prototype.serialize=function(e,t){return this.normalize(e).serialize(e,t)},t.prototype.toObject=function(){return{start:this.start,startOffset:this.startOffset,end:this.end,endOffset:this.endOffset}},t}(),p={uuid:function(){var e;return e=0,function(){return e++}}(),getGlobal:function(){return function(){return this}()},maxZIndex:function(t){var n,r;return n=function(){var n,i,s;s=[];for(n=0,i=t.length;n<i;n++)r=t[n],e(r).css("position")==="static"?s.push(-1):s.push(parseInt(e(r).css("z-index"),10)||-1);return s}(),Math.max.apply(Math,n)},mousePosition:function(t,n){var r;return r=e(n).offset(),{top:t.pageY-r.top,left:t.pageX-r.left}},preventEventDefault:function(e){return e!=null?typeof e.preventDefault=="function"?e.preventDefault():void 0:void 0}},d=this.Annotator,t=function(t){function n(t,r){this.onDeleteAnnotation=C(this.onDeleteAnnotation,this),this.onEditAnnotation=C(this.onEditAnnotation,this),this.onAdderClick=C(this.onAdderClick,this),this.onAdderMousedown=C(this.onAdderMousedown,this),this.onHighlightMouseover=C(this.onHighlightMouseover,this),this.checkForEndSelection=C(this.checkForEndSelection,this),this.checkForStartSelection=C(this.checkForStartSelection,this),this.clearViewerHideTimer=C(this.clearViewerHideTimer,this),this.startViewerHideTimer=C(this.startViewerHideTimer,this),this.showViewer=C(this.showViewer,this),this.onEditorSubmit=C(this.onEditorSubmit,this),this.onEditorHide=C(this.onEditorHide,this),this.showEditor=C(this.showEditor,this),n.__super__.constructor.apply(this,arguments),this.plugins={};if(!n.supported())return this;this.options.readOnly||this._setupDocumentEvents(),this._setupWrapper()._setupViewer()._setupEditor(),this._setupDynamicStyle(),this.adder=e(this.html.adder).appendTo(this.wrapper).hide()}return N(n,t),n.prototype.events={".annotator-adder button click":"onAdderClick",".annotator-adder button mousedown":"onAdderMousedown",".annotator-hl mouseover":"onHighlightMouseover",".annotator-hl mouseout":"startViewerHideTimer"},n.prototype.html={adder:'<div class="annotator-adder"><button>'+S("Annotate")+"</button></div>",wrapper:'<div class="annotator-wrapper"></div>'},n.prototype.options={readOnly:!1},n.prototype.plugins={},n.prototype.editor=null,n.prototype.viewer=null,n.prototype.selectedRanges=null,n.prototype.mouseIsDown=!1,n.prototype.ignoreMouseup=!1,n.prototype.viewerHideTimer=null,n.prototype._setupWrapper=function(){return this.wrapper=e(this.html.wrapper),this.element.find("script").remove(),this.element.wrapInner(this.wrapper),this.wrapper=this.element.find(".annotator-wrapper"),this},n.prototype._setupViewer=function(){var t=this;return this.viewer=new n.Viewer({readOnly:this.options.readOnly}),this.viewer.hide().on("edit",this.onEditAnnotation).on("delete",this.onDeleteAnnotation).addField({load:function(n,r){return r.text?e(n).escape(r.text):e(n).html("<i>"+S("No Comment")+"</i>"),t.publish("annotationViewerTextField",[n,r])}}).element.appendTo(this.wrapper).bind({mouseover:this.clearViewerHideTimer,mouseout:this.startViewerHideTimer}),this},n.prototype._setupEditor=function(){return this.editor=new n.Editor,this.editor.hide().on("hide",this.onEditorHide).on("save",this.onEditorSubmit).addField({type:"textarea",label:S("Comments")+"…",load:function(t,n){return e(t).find("textarea").val(n.text||"")},submit:function(t,n){return n.text=e(t).find("textarea").val()}}),this.editor.element.appendTo(this.wrapper),this},n.prototype._setupDocumentEvents=function(){return e(document).bind({mouseup:this.checkForEndSelection,mousedown:this.checkForStartSelection}),this},n.prototype._setupDynamicStyle=function(){var t,n,r,i;return r=e("#annotator-dynamic-style"),r.length||(r=e('<style id="annotator-dynamic-style"></style>').appendTo(document.head)),n="*"+function(){var e,t,n,r;n=["adder","outer","notice","filter"],r=[];for(e=0,t=n.length;e<t;e++)i=n[e],r.push(":not(.annotator-"+i+")");return r}().join(""),t=p.maxZIndex(e(document.body).find(n)),t=Math.max(t,1e3),r.text([".annotator-adder, .annotator-outer, .annotator-notice {"," z-index: "+(t+20)+";","}",".annotator-filter {"," z-index: "+(t+10)+";","}"].join("\n")),this},n.prototype.getSelectedRanges=function(){var t,n,r,s,o,u,a,f,l;a=p.getGlobal().getSelection(),o=[],u=[],a.isCollapsed||(o=function(){var e,o,f;f=[];for(n=e=0,o=a.rangeCount;0<=o?e<o:e>o;n=0<=o?++e:--e)s=a.getRangeAt(n),t=new i.BrowserRange(s),r=t.normalize().limit(this.wrapper[0]),r===null&&u.push(s),f.push(r);return f}.call(this),a.removeAllRanges());for(f=0,l=u.length;f<l;f++)s=u[f],a.addRange(s);return e.grep(o,function(e){return e&&a.addRange(e.toRange()),e})},n.prototype.createAnnotation=function(){var e;return e={},this.publish("beforeAnnotationCreated",[e]),e},n.prototype.setupAnnotation=function(t,n){var r,s,o,u,a,f,l,c,h;n==null&&(n=!0),u=this.wrapper[0],t.ranges||(t.ranges=this.selectedRanges),s=[],h=t.ranges;for(a=0,l=h.length;a<l;a++){o=h[a];try{s.push(i.sniff(o).normalize(u))}catch(p){if(!(p instanceof i.RangeError))throw p;this.publish("rangeNormalizeFail",[t,o,p])}}t.quote=[],t.ranges=[],t.highlights=[];for(f=0,c=s.length;f<c;f++)r=s[f],t.quote.push(e.trim(r.text())),t.ranges.push(r.serialize(this.wrapper[0],".annotator-hl")),e.merge(t.highlights,this.highlightRange(r));return t.quote=t.quote.join(" / "),e(t.highlights).data("annotation",t),n&&this.publish("annotationCreated",[t]),t},n.prototype.updateAnnotation=function(e){return this.publish("beforeAnnotationUpdated",[e]),this.publish("annotationUpdated",[e]),e},n.prototype.deleteAnnotation=function(t){var n,r,i,s;s=t.highlights;for(r=0,i=s.length;r<i;r++)n=s[r],e(n).replaceWith(n.childNodes);return this.publish("annotationDeleted",[t]),t},n.prototype.loadAnnotations=function(e){var t,n,r=this;return e==null&&(e=[]),n=function(e){var i,s,o,u;e==null&&(e=[]),s=e.splice(0,10);for(o=0,u=s.length;o<u;o++)i=s[o],r.setupAnnotation(i,!1);return e.length>0?setTimeout(function(){return n(e)},10):r.publish("annotationsLoaded",[t])},t=e.slice(),e.length&&n(e),this},n.prototype.dumpAnnotations=function(){return this.plugins.Store?this.plugins.Store.dumpAnnotations():console.warn(S("Can't dump annotations without Store plugin."))},n.prototype.highlightRange=function(t,n){var r,i,s,o,u,a,f;n==null&&(n="annotator-hl"),s=/^\s*$/,r=e("<span class='"+n+"'></span>"),a=t.textNodes(),f=[];for(o=0,u=a.length;o<u;o++)i=a[o],s.test(i.nodeValue)||f.push(e(i).wrapAll(r).parent().show()[0]);return f},n.prototype.highlightRanges=function(t,n){var r,i,s,o;n==null&&(n="annotator-hl"),r=[];for(s=0,o=t.length;s<o;s++)i=t[s],e.merge(r,this.highlightRange(i,n));return r},n.prototype.addPlugin=function(e,t){var r,i;return this.plugins[e]?console.error(S("You cannot have more than one instance of any plugin.")):(r=n.Plugin[e],typeof r=="function"?(this.plugins[e]=new r(this.element[0],t),this.plugins[e].annotator=this,typeof (i=this.plugins[e]).pluginInit=="function"&&i.pluginInit()):console.error(S("Could not load ")+e+S(" plugin. Have you included the appropriate <script> tag?"))),this},n.prototype.showEditor=function(e,t){return this.editor.element.css(t),this.editor.load(e),this.publish("annotationEditorShown",[this.editor,e]),this},n.prototype.onEditorHide=function(){return this.publish("annotationEditorHidden",[this.editor]),this.ignoreMouseup=!1},n.prototype.onEditorSubmit=function(e){return this.publish("annotationEditorSubmit",[this.editor,e]),e.ranges===void 0?this.setupAnnotation(e):this.updateAnnotation(e)},n.prototype.showViewer=function(e,t){return this.viewer.element.css(t),this.viewer.load(e),this.publish("annotationViewerShown",[this.viewer,e])},n.prototype.startViewerHideTimer=function(){if(!this.viewerHideTimer)return this.viewerHideTimer=setTimeout(this.viewer.hide,250)},n.prototype.clearViewerHideTimer=function(){return clearTimeout(this.viewerHideTimer),this.viewerHideTimer=!1},n.prototype.checkForStartSelection=function(e){if(!e||!this.isAnnotator(e.target))return this.startViewerHideTimer(),this.mouseIsDown=!0},n.prototype.checkForEndSelection=function(t){var n,r,i,s,o;this.mouseIsDown=!1;if(this.ignoreMouseup)return;this.selectedRanges=this.getSelectedRanges(),o=this.selectedRanges;for(i=0,s=o.length;i<s;i++){r=o[i],n=r.commonAncestor,e(n).hasClass("annotator-hl")&&(n=e(n).parents("[class^=annotator-hl]")[0]);if(this.isAnnotator(n))return}return t&&this.selectedRanges.length?this.adder.css(p.mousePosition(t,this.wrapper[0])).show():this.adder.hide()},n.prototype.isAnnotator=function(t){return!!e(t).parents().andSelf().filter("[class^=annotator-]").not(this.wrapper).length},n.prototype.onHighlightMouseover=function(t){var n;return this.clearViewerHideTimer(),this.mouseIsDown||this.viewer.isShown()?!1:(n=e(t.target).parents(".annotator-hl").andSelf().map(function(){return e(this).data("annotation")}),this.showViewer(e.makeArray(n),p.mousePosition(t,this.wrapper[0])))},n.prototype.onAdderMousedown=function(e){return e!=null&&e.preventDefault(),this.ignoreMouseup=!0},n.prototype.onAdderClick=function(t){var n,r,s,o;return t!=null&&t.preventDefault(),r=this.adder.position(),this.adder.hide(),this.selectedRanges&&this.selectedRanges.length&&(o=function(){var e,t,n,r;n=this.selectedRanges,r=[];for(e=0,t=n.length;e<t;e++)s=n[e],r.push(i.sniff(s).normalize());return r}.call(this),n=this.highlightRanges(o,"annotator-hl annotator-hl-temporary"),this.editor.element.one("hide",function(){var t,r,i,s;s=[];for(r=0,i=n.length;r<i;r++)t=n[r],s.push(e(t).replaceWith(t.childNodes));return s})),this.showEditor(this.createAnnotation(),r)},n.prototype.onEditAnnotation=function(e){var t;return t=this.viewer.element.position(),this.viewer.hide(),this.showEditor(e,t)},n.prototype.onDeleteAnnotation=function(e){return this.viewer.hide(),this.deleteAnnotation(e)},n}(n),t.Plugin=function(e){function t(e,n){t.__super__.constructor.apply(this,arguments)}return N(t,e),t.prototype.pluginInit=function(){},t}(n),l=p.getGlobal(),((E=l.document)!=null?E.evaluate:void 0)==null&&e.getScript("http://assets.annotateit.org/vendor/xpath.min.js"),l.getSelection==null&&e.getScript("http://assets.annotateit.org/vendor/ierange.min.js"),l.JSON==null&&e.getScript("http://assets.annotateit.org/vendor/json2.min.js"),t.$=e,t.Delegator=n,t.Range=i,t._t=S,t.supported=function(){return function(){return!!this.getSelection}()},t.noConflict=function(){return p.getGlobal().Annotator=d,this},e.plugin("annotator",t),this.Annotator=t,t.Widget=function(n){function r(n,i){r.__super__.constructor.apply(this,arguments),this.classes=e.extend({},t.Widget.prototype.classes,this.classes)}return N(r,n),r.prototype.classes={hide:"annotator-hide",invert:{x:"annotator-invert-x",y:"annotator-invert-y"}},r.prototype.checkOrientation=function(){var t,n,r,i,s;return this.resetOrientation(),s=e(p.getGlobal()),i=this.element.children(":first"),n=i.offset(),r={top:s.scrollTop(),right:s.width()+s.scrollLeft()},t={top:n.top,right:n.left+i.width()},t.top-r.top<0&&this.invertY(),t.right-r.right>0&&this.invertX(),this},r.prototype.resetOrientation=function(){return this.element.removeClass(this.classes.invert.x).removeClass(this.classes.invert.y),this},r.prototype.invertX=function(){return this.element.addClass(this.classes.invert.x),this},r.prototype.invertY=function(){return this.element.addClass(this.classes.invert.y),this},r.prototype.isInvertedY=function(){return this.element.hasClass(this.classes.invert.y)},r.prototype.isInvertedX=function(){return this.element.hasClass(this.classes.invert.x)},r}(n),t.Editor=function(t){function n(t){this.onCancelButtonMouseover=C(this.onCancelButtonMouseover,this),this.processKeypress=C(this.processKeypress,this),this.submit=C(this.submit,this),this.load=C(this.load,this),this.hide=C(this.hide,this),this.show=C(this.show,this),n.__super__.constructor.call(this,e(this.html)[0],t),this.fields=[],this.annotation={}}return N(n,t),n.prototype.events={"form submit":"submit",".annotator-save click":"submit",".annotator-cancel click":"hide",".annotator-cancel mouseover":"onCancelButtonMouseover","textarea keydown":"processKeypress"},n.prototype.classes={hide:"annotator-hide",focus:"annotator-focus"},n.prototype.html='<div class="annotator-outer annotator-editor">\n <form class="annotator-widget">\n <ul class="annotator-listing"></ul>\n <div class="annotator-controls">\n <a href="#cancel" class="annotator-cancel">'+S("Cancel")+'</a>\n<a href="#save" class="annotator-save annotator-focus">'+S("Save")+"</a>\n </div>\n </form>\n</div>",n.prototype.options={},n.prototype.show=function(e){return p.preventEventDefault(e),this.element.removeClass(this.classes.hide),this.element.find(".annotator-save").addClass(this.classes.focus),this.checkOrientation(),this.element.find(":input:first").focus(),this.setupDraggables(),this.publish("show")},n.prototype.hide=function(e){return p.preventEventDefault(e),this.element.addClass(this.classes.hide),this.publish("hide")},n.prototype.load=function(e){var t,n,r,i;this.annotation=e,this.publish("load",[this.annotation]),i=this.fields;for(n=0,r=i.length;n<r;n++)t=i[n],t.load(t.element,this.annotation);return this.show()},n.prototype.submit=function(e){var t,n,r,i;p.preventEventDefault(e),i=this.fields;for(n=0,r=i.length;n<r;n++)t=i[n],t.submit(t.element,this.annotation);return this.publish("save",[this.annotation]),this.hide()},n.prototype.addField=function(t){var n,r,i;r=e.extend({id:"annotator-field-"+p.uuid(),type:"input",label:"",load:function(){},submit:function(){}},t),i=null,n=e('<li class="annotator-item" />'),r.element=n[0];switch(r.type){case"textarea":i=e("<textarea />");break;case"input":case"checkbox":i=e("<input />")}return n.append(i),i.attr({id:r.id,placeholder:r.label}),r.type==="checkbox"&&(i[0].type="checkbox",n.addClass("annotator-checkbox"),n.append(e("<label />",{"for":r.id,html:r.label}))),this.element.find("ul:first").append(n),this.fields.push(r),r.element},n.prototype.checkOrientation=function(){var e,t;return n.__super__.checkOrientation.apply(this,arguments),t=this.element.find("ul"),e=this.element.find(".annotator-controls"),this.element.hasClass(this.classes.invert.y)?e.insertBefore(t):e.is(":first-child")&&e.insertAfter(t),this},n.prototype.processKeypress=function(e){if(e.keyCode===27)return this.hide();if(e.keyCode===13&&!e.shiftKey)return this.submit()},n.prototype.onCancelButtonMouseover=function(){return this.element.find("."+this.classes.focus).removeClass(this.classes.focus)},n.prototype.setupDraggables=function(){var t,n,r,i,s,o,u,a,f,l,c,h=this;return this.element.find(".annotator-resize").remove(),this.element.hasClass(this.classes.invert.y)?r=this.element.find(".annotator-item:last"):r=this.element.find(".annotator-item:first"),r&&e('<span class="annotator-resize"></span>').appendTo(r),s=null,t=this.classes,i=this.element,l=null,f=i.find(".annotator-resize"),n=i.find(".annotator-controls"),c=!1,o=function(t){if(t.target===this)return s={element:this,top:t.pageY,left:t.pageX},l=i.find("textarea:first"),e(window).bind({"mouseup.annotator-editor-resize":a,"mousemove.annotator-editor-resize":u}),t.preventDefault()},a=function(){return s=null,e(window).unbind(".annotator-editor-resize")},u=function(e){var r,o,u,a,h;if(s&&c===!1)return r={top:e.pageY-s.top,left:e.pageX-s.left},s.element===f[0]?(a=l.outerHeight(),h=l.outerWidth(),o=i.hasClass(t.invert.x)?-1:1,u=i.hasClass(t.invert.y)?1:-1,l.height(a+r.top*u),l.width(h+r.left*o),l.outerHeight()!==a&&(s.top=e.pageY),l.outerWidth()!==h&&(s.left=e.pageX)):s.element===n[0]&&(i.css({top:parseInt(i.css("top"),10)+r.top,left:parseInt(i.css("left"),10)+r.left}),s.top=e.pageY,s.left=e.pageX),c=!0,setTimeout(function(){return c=!1},1e3/60)},f.bind("mousedown",o),n.bind("mousedown",o)},n}(t.Widget),t.Viewer=function(t){function n(t){this.onDeleteClick=C(this.onDeleteClick,this),this.onEditClick=C(this.onEditClick,this),this.load=C(this.load,this),this.hide=C(this.hide,this),this.show=C(this.show,this),n.__super__.constructor.call(this,e(this.html.element)[0],t),this.item=e(this.html.item)[0],this.fields=[],this.annotations=[]}return N(n,t),n.prototype.events={".annotator-edit click":"onEditClick",".annotator-delete click":"onDeleteClick"},n.prototype.classes={hide:"annotator-hide",showControls:"annotator-visible"},n.prototype.html={element:'<div class="annotator-outer annotator-viewer">\n <ul class="annotator-widget annotator-listing"></ul>\n</div>',item:'<li class="annotator-annotation annotator-item">\n <span class="annotator-controls">\n <a href="#" title="View as webpage" class="annotator-link">View as webpage</a>\n <button title="Edit" class="annotator-edit">Edit</button>\n <button title="Delete" class="annotator-delete">Delete</button>\n </span>\n</li>'},n.prototype.options={readOnly:!1},n.prototype.show=function(e){var t,n=this;return p.preventEventDefault(e),t=this.element.find(".annotator-controls").addClass(this.classes.showControls),setTimeout(function(){return t.removeClass(n.classes.showControls)},500),this.element.removeClass(this.classes.hide),this.checkOrientation().publish("show")},n.prototype.isShown=function(){return!this.element.hasClass(this.classes.hide)},n.prototype.hide=function(e){return p.preventEventDefault(e),this.element.addClass(this.classes.hide),this.publish("hide")},n.prototype.load=function(t){var n,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b;this.annotations=t||[],p=this.element.find("ul:first").empty(),y=this.annotations;for(d=0,m=y.length;d<m;d++){n=y[d],l=e(this.item).clone().appendTo(p).data("annotation",n),s=l.find(".annotator-controls"),c=s.find(".annotator-link"),u=s.find(".annotator-edit"),o=s.find(".annotator-delete"),h=(new r(n.links||[])).get("alternate",{type:"text/html"}),h.length===0||h[0].href==null?c.remove():c.attr("href",h[0].href),this.options.readOnly?(u.remove(),o.remove()):i={showEdit:function(){return u.removeAttr("disabled")},hideEdit:function(){return u.attr("disabled","disabled")},showDelete:function(){return o.removeAttr("disabled")},hideDelete:function(){return o.attr("disabled","disabled")}},b=this.fields;for(v=0,g=b.length;v<g;v++)f=b[v],a=e(f.element).clone().appendTo(l)[0],f.load(a,n,i)}return this.publish("load",[this.annotations]),this.show()},n.prototype.addField=function(t){var n;return n=e.extend({load:function(){}},t),n.element=e("<div />")[0],this.fields.push(n),n.element,this},n.prototype.onEditClick=function(e){return this.onButtonClick(e,"edit")},n.prototype.onDeleteClick=function(e){return this.onButtonClick(e,"delete")},n.prototype.onButtonClick=function(t,n){var r;return r=e(t.target).parents(".annotator-annotation"),this.publish(n,[r.data("annotation")])},n}(t.Widget),r=function(){function t(e){this.data=e}return t.prototype.get=function(t,n){var r,i,s,o,u,a,f,l,c;n==null&&(n={}),n=e.extend({},n,{rel:t}),s=function(){var e;e=[];for(i in n){if(!T.call(n,i))continue;u=n[i],e.push(i)}return e}(),l=this.data,c=[];for(a=0,f=l.length;a<f;a++){r=l[a],o=s.reduce(function(e,t){return e&&r[t]===n[t]},!0);if(!o)continue;c.push(r)}return c},t}(),t=t||{},t.Notification=function(n){function r(t){this.hide=C(this.hide,this),this.show=C(this.show,this),r.__super__.constructor.call(this,e(this.options.html).appendTo(document.body)[0],t)}return N(r,n),r.prototype.events={click:"hide"},r.prototype.options={html:"<div class='annotator-notice'></div>",classes:{show:"annotator-notice-show",info:"annotator-notice-info",success:"annotator-notice-success",error:"annotator-notice-error"}},r.prototype.show=function(n,r){return r==null&&(r=t.Notification.INFO),e(this.element).addClass(this.options.classes.show).addClass(this.options.classes[r]).escape(n||""),setTimeout(this.hide,5e3),this},r.prototype.hide=function(){return e(this.element).removeClass(this.options.classes.show),this},r}(n),t.Notification.INFO="show",t.Notification.SUCCESS="success",t.Notification.ERROR="error",e(function(){var e;return e=new t.Notification,t.showNotification=e.show,t.hideNotification=e.hide}),t.Plugin.Unsupported=function(n){function r(){return r.__super__.constructor.apply(this,arguments)}return N(r,n),r.prototype.options={message:t._t("Sorry your current browser does not support the Annotator")},r.prototype.pluginInit=function(){var n=this;if(!t.supported())return e(function(){t.showNotification(n.options.message);if(window.XMLHttpRequest===void 0&&ActiveXObject!==void 0)return e("html").addClass("ie6")})},r}(t.Plugin),u=function(e){var t,n,r,i,s,o;return i="([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?",t=e.match(new RegExp(i)),r=0,n=new Date(t[1],0,1),t[3]&&n.setMonth(t[3]-1),t[5]&&n.setDate(t[5]),t[7]&&n.setHours(t[7]),t[8]&&n.setMinutes(t[8]),t[10]&&n.setSeconds(t[10]),t[12]&&n.setMilliseconds(Number("0."+t[12])*1e3),t[14]&&(r=Number(t[16])*60+Number(t[17]),r*=(o=t[15]==="-")!=null?o:{1:-1}),r-=n.getTimezoneOffset(),s=Number(n)+r*60*1e3,n.setTime(Number(s)),n},s=function(e){var t,n,r,i,s,o,u,a,f,l,c,h,p;if(typeof atob!="undefined"&&atob!==null)return atob(e);n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f=0,t=0,i="",p=[];if(!e)return e;e+="";while(f<e.length)s=n.indexOf(e.charAt(f++)),o=n.indexOf(e.charAt(f++)),u=n.indexOf(e.charAt(f++)),a=n.indexOf(e.charAt(f++)),r=s<<18|o<<12|u<<6|a,l=r>>16&255,c=r>>8&255,h=r&255,u===64?p[t++]=String.fromCharCode(l):a===64?p[t++]=String.fromCharCode(l,c):p[t++]=String.fromCharCode(l,c,h);return p.join("")},o=function(e){var t,n,r,i;n=e.length%4;if(n!==0)for(t=r=0,i=4-n;0<=i?r<i:r>i;t=0<=i?++r:--r)e+="=";return e=e.replace(/-/g,"+"),e=e.replace(/_/g,"/"),s(e)},h=function(e){var t,n,r,i;return i=e.split("."),t=i[0],n=i[1],r=i[2],JSON.parse(o(n))},t.Plugin.Auth=function(n){function r(e,t){r.__super__.constructor.apply(this,arguments),this.waitingForToken=[],this.options.token?this.setToken(this.options.token):this.requestToken()}return N(r,n),r.prototype.options={token:null,tokenUrl:"/auth/token",autoFetch:!0,requestMethod:"GET",requestData:null,unauthorizedCallback:null},r.prototype.requestToken=function(){var n=this;return this.requestInProgress=!0,e.ajax({url:this.options.tokenUrl,dataType:"text",data:this.options.requestData,type:this.options.requestMethod,xhrFields:{withCredentials:!0}}).done(function(e,t,r){return n.setToken(e)}).fail(function(e,r,i){var s,o;if(e.status===401){s=n.options.unauthorizedCallback;if(s!=null&&s(n)){n.retryTimeout=setTimeout(function(){return n.requestToken()},1e3);return}}return o=t._t("Couldn't get auth token:"),console.error(""+o+" "+i,e),t.showNotification(""+o+" "+e.responseText,t.Notification.ERROR)}).always(function(){return n.requestInProgress=!1})},r.prototype.setToken=function(e){var n,r=this;this.token=e,this._unsafeToken=h(e);if(this.haveValidToken()){this.options.autoFetch&&(this.refreshTimeout=setTimeout(function(){return r.requestToken()},(this.timeToExpiry()-2)*1e3)),this.updateHeaders(),n=[];while(this.waitingForToken.length>0)n.push(this.waitingForToken.pop()(this._unsafeToken));return n}console.warn(t._t("Didn't get a valid token."));if(this.options.autoFetch)return console.warn(t._t("Getting a new token in 10s.")),setTimeout(function(){return r.requestToken()},1e4)},r.prototype.haveValidToken=function(){var e;return e=this._unsafeToken&&this. -_unsafeToken.issuedAt&&this._unsafeToken.ttl&&this._unsafeToken.consumerKey,e&&this.timeToExpiry()>0},r.prototype.timeToExpiry=function(){var e,t,n,r;return n=(new Date).getTime()/1e3,t=u(this._unsafeToken.issuedAt).getTime()/1e3,e=t+this._unsafeToken.ttl,r=e-n,r>0?r:0},r.prototype.updateHeaders=function(){var t;return t=this.element.data("annotator:headers"),this.element.data("annotator:headers",e.extend(t,{"x-annotator-auth-token":this.token}))},r.prototype.withToken=function(e){if(e==null)return;if(this.haveValidToken())return e(this._unsafeToken);this.waitingForToken.push(e);if(!this.requestInProgress)return this.requestToken()},r}(t.Plugin),t.Plugin.Store=function(n){function r(e,t){this._onError=C(this._onError,this),this._onLoadAnnotationsFromSearch=C(this._onLoadAnnotationsFromSearch,this),this._onLoadAnnotations=C(this._onLoadAnnotations,this),this._getAnnotations=C(this._getAnnotations,this),r.__super__.constructor.apply(this,arguments),this.annotations=[]}return N(r,n),r.prototype.events={annotationCreated:"annotationCreated",annotationDeleted:"annotationDeleted",annotationUpdated:"annotationUpdated"},r.prototype.options={prefix:"/store",autoFetch:!0,annotationData:{},loadFromSearch:!1,urls:{create:"/annotations",read:"/annotations/:id",update:"/annotations/:id",destroy:"/annotations/:id",search:"/search"}},r.prototype.pluginInit=function(){if(!t.supported())return;return this.annotator.plugins.Auth?this.annotator.plugins.Auth.withToken(this._getAnnotations):this._getAnnotations()},r.prototype._getAnnotations=function(){return this.options.loadFromSearch?this.loadAnnotationsFromSearch(this.options.loadFromSearch):this.loadAnnotations()},r.prototype.annotationCreated=function(e){var n=this;return k.call(this.annotations,e)<0?(this.registerAnnotation(e),this._apiRequest("create",e,function(r){return r.id==null&&console.warn(t._t("Warning: No ID returned from server for annotation "),e),n.updateAnnotation(e,r)})):this.updateAnnotation(e,{})},r.prototype.annotationUpdated=function(e){var t=this;if(k.call(this.annotations,e)>=0)return this._apiRequest("update",e,function(n){return t.updateAnnotation(e,n)})},r.prototype.annotationDeleted=function(e){var t=this;if(k.call(this.annotations,e)>=0)return this._apiRequest("destroy",e,function(){return t.unregisterAnnotation(e)})},r.prototype.registerAnnotation=function(e){return this.annotations.push(e)},r.prototype.unregisterAnnotation=function(e){return this.annotations.splice(this.annotations.indexOf(e),1)},r.prototype.updateAnnotation=function(n,r){return k.call(this.annotations,n)<0?console.error(t._t("Trying to update unregistered annotation!")):e.extend(n,r),e(n.highlights).data("annotation",n)},r.prototype.loadAnnotations=function(){return this._apiRequest("read",null,this._onLoadAnnotations)},r.prototype._onLoadAnnotations=function(e){return e==null&&(e=[]),this.annotations=e,this.annotator.loadAnnotations(e.slice())},r.prototype.loadAnnotationsFromSearch=function(e){return this._apiRequest("search",e,this._onLoadAnnotationsFromSearch)},r.prototype._onLoadAnnotationsFromSearch=function(e){return e==null&&(e={}),this._onLoadAnnotations(e.rows||[])},r.prototype.dumpAnnotations=function(){var e,t,n,r,i;r=this.annotations,i=[];for(t=0,n=r.length;t<n;t++)e=r[t],i.push(JSON.parse(this._dataFor(e)));return i},r.prototype._apiRequest=function(t,n,r){var i,s,o,u;return i=n&&n.id,u=this._urlFor(t,i),s=this._apiRequestOptions(t,n,r),o=e.ajax(u,s),o._id=i,o._action=t,o},r.prototype._apiRequestOptions=function(t,n,r){var i;return i={type:this._methodFor(t),headers:this.element.data("annotator:headers"),dataType:"json",success:r||function(){},error:this._onError},t==="search"?i=e.extend(i,{data:n}):i=e.extend(i,{data:n&&this._dataFor(n),contentType:"application/json; charset=utf-8"}),i},r.prototype._urlFor=function(e,t){var n,r;return n=t!=null?"/"+t:"",r=this.options.prefix||"/",r+=this.options.urls[e],r=r.replace(/\/:id/,n),r},r.prototype._methodFor=function(e){var t;return t={create:"POST",read:"GET",update:"PUT",destroy:"DELETE",search:"GET"},t[e]},r.prototype._dataFor=function(t){var n,r;return r=t.highlights,delete t.highlights,e.extend(t,this.options.annotationData),n=JSON.stringify(t),r&&(t.highlights=r),n},r.prototype._onError=function(e){var n,r;n=e._action,r=t._t("Sorry we could not ")+n+t._t(" this annotation"),e._action==="search"?r=t._t("Sorry we could not search the store for annotations"):e._action==="read"&&!e._id&&(r=t._t("Sorry we could not ")+n+t._t(" the annotations from the store"));switch(e.status){case 401:r=t._t("Sorry you are not allowed to ")+n+t._t(" this annotation");break;case 404:r=t._t("Sorry we could not connect to the annotations store");break;case 500:r=t._t("Sorry something went wrong with the annotation store")}return t.showNotification(r,t.Notification.ERROR),console.error(t._t("API request failed:")+(" '"+e.status+"'"))},r}(t.Plugin),t.Plugin.Permissions=function(n){function r(e,t){this._setAuthFromToken=C(this._setAuthFromToken,this),this.updateViewer=C(this.updateViewer,this),this.updateAnnotationPermissions=C(this.updateAnnotationPermissions,this),this.updatePermissionsField=C(this.updatePermissionsField,this),this.addFieldsToAnnotation=C(this.addFieldsToAnnotation,this),r.__super__.constructor.apply(this,arguments),this.options.user&&(this.setUser(this.options.user),delete this.options.user)}return N(r,n),r.prototype.events={beforeAnnotationCreated:"addFieldsToAnnotation"},r.prototype.options={showViewPermissionsCheckbox:!0,showEditPermissionsCheckbox:!0,userId:function(e){return e},userString:function(e){return e},userAuthorize:function(e,t,n){var r,i,s,o;if(t.permissions){i=t.permissions[e]||[];if(i.length===0)return!0;for(s=0,o=i.length;s<o;s++){r=i[s];if(this.userId(n)===r)return!0}return!1}return t.user?n&&this.userId(n)===this.userId(t.user):!0},user:"",permissions:{read:[],update:[],"delete":[],admin:[]}},r.prototype.pluginInit=function(){var e,n,r=this;if(!t.supported())return;n=this,e=function(e,t){return function(r,i){return n[e].call(n,t,r,i)}},!this.user&&this.annotator.plugins.Auth&&this.annotator.plugins.Auth.withToken(this._setAuthFromToken),this.options.showViewPermissionsCheckbox===!0&&this.annotator.editor.addField({type:"checkbox",label:t._t("Allow anyone to <strong>view</strong> this annotation"),load:e("updatePermissionsField","read"),submit:e("updateAnnotationPermissions","read")}),this.options.showEditPermissionsCheckbox===!0&&this.annotator.editor.addField({type:"checkbox",label:t._t("Allow anyone to <strong>edit</strong> this annotation"),load:e("updatePermissionsField","update"),submit:e("updateAnnotationPermissions","update")}),this.annotator.viewer.addField({load:this.updateViewer});if(this.annotator.plugins.Filter)return this.annotator.plugins.Filter.addFilter({label:t._t("User"),property:"user",isFiltered:function(e,t){var n,i,s,o;t=r.options.userString(t);if(!e||!t)return!1;o=e.split(/\s*/);for(i=0,s=o.length;i<s;i++){n=o[i];if(t.indexOf(n)===-1)return!1}return!0}})},r.prototype.setUser=function(e){return this.user=e},r.prototype.addFieldsToAnnotation=function(e){if(e){e.permissions=this.options.permissions;if(this.user)return e.user=this.user}},r.prototype.authorize=function(e,t,n){return n===void 0&&(n=this.user),this.options.userAuthorize?this.options.userAuthorize.call(this.options,e,t,n):!0},r.prototype.updatePermissionsField=function(t,n,r){var i;return n=e(n).show(),i=n.find("input").removeAttr("disabled"),this.authorize("admin",r)||n.hide(),this.authorize(t,r||{},null)?i.attr("checked","checked"):i.removeAttr("checked")},r.prototype.updateAnnotationPermissions=function(t,n,r){var i;return r.permissions||(r.permissions=this.options.permissions),i=t+"-permissions",e(n).find("input").is(":checked")?r.permissions[t]=[]:r.permissions[t]=[this.user]},r.prototype.updateViewer=function(n,r,i){var s,o;n=e(n),o=this.options.userString(r.user),r.user&&o&&typeof o=="string"?(s=t.$.escape(this.options.userString(r.user)),n.html(s).addClass("annotator-user")):n.remove();if(i){this.authorize("update",r)||i.hideEdit();if(!this.authorize("delete",r))return i.hideDelete()}},r.prototype._setAuthFromToken=function(e){return this.setUser(e.userId)},r}(t.Plugin),t.Plugin.Filter=function(n){function r(t,n){this._onPreviousClick=C(this._onPreviousClick,this),this._onNextClick=C(this._onNextClick,this),this._onFilterKeyup=C(this._onFilterKeyup,this),this._onFilterBlur=C(this._onFilterBlur,this),this._onFilterFocus=C(this._onFilterFocus,this),this.updateHighlights=C(this.updateHighlights,this);var i;t=e(this.html.element).appendTo((n!=null?n.appendTo:void 0)||this.options.appendTo),r.__super__.constructor.call(this,t,n),(i=this.options).filters||(i.filters=[]),this.filter=e(this.html.filter),this.filters=[],this.current=0}return N(r,n),r.prototype.events={".annotator-filter-property input focus":"_onFilterFocus",".annotator-filter-property input blur":"_onFilterBlur",".annotator-filter-property input keyup":"_onFilterKeyup",".annotator-filter-previous click":"_onPreviousClick",".annotator-filter-next click":"_onNextClick",".annotator-filter-clear click":"_onClearClick"},r.prototype.classes={active:"annotator-filter-active",hl:{hide:"annotator-hl-filtered",active:"annotator-hl-active"}},r.prototype.html={element:'<div class="annotator-filter">\n <strong>'+t._t("Navigate:")+'</strong>\n<span class="annotator-filter-navigation">\n <button class="annotator-filter-previous">'+t._t("Previous")+'</button>\n<button class="annotator-filter-next">'+t._t("Next")+"</button>\n</span>\n<strong>"+t._t("Filter by:")+"</strong>\n</div>",filter:'<span class="annotator-filter-property">\n <label></label>\n <input/>\n <button class="annotator-filter-clear">'+t._t("Clear")+"</button>\n</span>"},r.prototype.options={appendTo:"body",filters:[],addAnnotationFilter:!0,isFiltered:function(e,t){var n,r,i,s;if(!e||!t)return!1;s=e.split(/\s*/);for(r=0,i=s.length;r<i;r++){n=s[r];if(t.indexOf(n)===-1)return!1}return!0}},r.prototype.pluginInit=function(){var e,n,r,i;i=this.options.filters;for(n=0,r=i.length;n<r;n++)e=i[n],this.addFilter(e);this.updateHighlights(),this._setupListeners()._insertSpacer();if(this.options.addAnnotationFilter===!0)return this.addFilter({label:t._t("Annotation"),property:"text"})},r.prototype._insertSpacer=function(){var t,n;return n=e("html"),t=parseInt(n.css("padding-top"),10)||0,n.css("padding-top",t+this.element.outerHeight()),this},r.prototype._setupListeners=function(){var e,t,n,r;t=["annotationsLoaded","annotationCreated","annotationUpdated","annotationDeleted"];for(n=0,r=t.length;n<r;n++)e=t[n],this.annotator.subscribe(e,this.updateHighlights);return this},r.prototype.addFilter=function(n){var r,i;i=e.extend({label:"",property:"",isFiltered:this.options.isFiltered},n);if(!function(){var e,t,n,s;n=this.filters,s=[];for(e=0,t=n.length;e<t;e++)r=n[e],r.property===i.property&&s.push(r);return s}.call(this).length)i.id="annotator-filter-"+i.property,i.annotations=[],i.element=this.filter.clone().appendTo(this.element),i.element.find("label").html(i.label).attr("for",i.id),i.element.find("input").attr({id:i.id,placeholder:t._t("Filter by ")+i.label+"…"}),i.element.find("button").hide(),i.element.data("filter",i),this.filters.push(i);return this},r.prototype.updateFilter=function(t){var n,r,i,s,o,u,a;t.annotations=[],this.updateHighlights(),this.resetHighlights(),i=e.trim(t.element.find("input").val());if(i){r=this.highlights.map(function(){return e(this).data("annotation")}),a=e.makeArray(r);for(o=0,u=a.length;o<u;o++)n=a[o],s=n[t.property],t.isFiltered(i,s)&&t.annotations.push(n);return this.filterHighlights()}},r.prototype.updateHighlights=function(){return this.highlights=this.annotator.element.find(".annotator-hl:visible"),this.filtered=this.highlights.not(this.classes.hl.hide)},r.prototype.filterHighlights=function(){var t,n,r,i,s,o,u,a,f,l;t=e.grep(this.filters,function(e){return!!e.annotations.length}),i=((l=t[0])!=null?l.annotations:void 0)||[],t.length>1&&(r=[],e.each(t,function(){return e.merge(r,this.annotations)}),u=[],i=[],e.each(r,function(){return e.inArray(this,u)===-1?u.push(this):i.push(this)})),s=this.highlights;for(o=a=0,f=i.length;a<f;o=++a)n=i[o],s=s.not(n.highlights);return s.addClass(this.classes.hl.hide),this.filtered=this.highlights.not(this.classes.hl.hide),this},r.prototype.resetHighlights=function(){return this.highlights.removeClass(this.classes.hl.hide),this.filtered=this.highlights,this},r.prototype._onFilterFocus=function(t){var n;return n=e(t.target),n.parent().addClass(this.classes.active),n.next("button").show()},r.prototype._onFilterBlur=function(t){var n;if(!t.target.value)return n=e(t.target),n.parent().removeClass(this.classes.active),n.next("button").hide()},r.prototype._onFilterKeyup=function(t){var n;n=e(t.target).parent().data("filter");if(n)return this.updateFilter(n)},r.prototype._findNextHighlight=function(e){var t,n,r,i,s,o,u,a;return this.highlights.length?(o=e?0:-1,a=e?-1:0,u=e?"lt":"gt",t=this.highlights.not("."+this.classes.hl.hide),r=t.filter("."+this.classes.hl.active),r.length||(r=t.eq(o)),n=r.data("annotation"),i=t.index(r[0]),s=t.filter(":"+u+"("+i+")").not(n.highlights).eq(a),s.length||(s=t.eq(a)),this._scrollToHighlight(s.data("annotation").highlights)):this},r.prototype._onNextClick=function(e){return this._findNextHighlight()},r.prototype._onPreviousClick=function(e){return this._findNextHighlight(!0)},r.prototype._scrollToHighlight=function(t){return t=e(t),this.highlights.removeClass(this.classes.hl.active),t.addClass(this.classes.hl.active),e("html, body").animate({scrollTop:t.offset().top-(this.element.height()+20)},150)},r.prototype._onClearClick=function(t){return e(t.target).prev("input").val("").keyup().blur()},r}(t.Plugin),t.Plugin.Markdown=function(n){function r(e,n){this.updateTextField=C(this.updateTextField,this),(typeof Showdown!=="undefined"&&Showdown!==null?Showdown.converter:void 0)!=null?(r.__super__.constructor.apply(this,arguments),this.converter=new Showdown.converter):console.error(t._t("To use the Markdown plugin, you must include Showdown into the page first."))}return N(r,n),r.prototype.events={annotationViewerTextField:"updateTextField"},r.prototype.updateTextField=function(n,r){var i;return i=t.$.escape(r.text||""),e(n).html(this.convert(i))},r.prototype.convert=function(e){return this.converter.makeHtml(e)},r}(t.Plugin),t.Plugin.Tags=function(n){function r(){return this.setAnnotationTags=C(this.setAnnotationTags,this),this.updateField=C(this.updateField,this),r.__super__.constructor.apply(this,arguments)}return N(r,n),r.prototype.options={parseTags:function(t){var n;return t=e.trim(t),n=[],t&&(n=t.split(/\s+/)),n},stringifyTags:function(e){return e.join(" ")}},r.prototype.field=null,r.prototype.input=null,r.prototype.pluginInit=function(){if(!t.supported())return;return this.field=this.annotator.editor.addField({label:t._t("Add some tags here")+"…",load:this.updateField,submit:this.setAnnotationTags}),this.annotator.viewer.addField({load:this.updateViewer}),this.annotator.plugins.Filter&&this.annotator.plugins.Filter.addFilter({label:t._t("Tag"),property:"tags",isFiltered:t.Plugin.Tags.filterCallback}),this.input=e(this.field).find(":input")},r.prototype.parseTags=function(e){return this.options.parseTags(e)},r.prototype.stringifyTags=function(e){return this.options.stringifyTags(e)},r.prototype.updateField=function(e,t){var n;return n="",t.tags&&(n=this.stringifyTags(t.tags)),this.input.val(n)},r.prototype.setAnnotationTags=function(e,t){return t.tags=this.parseTags(this.input.val())},r.prototype.updateViewer=function(n,r){return n=e(n),r.tags&&e.isArray(r.tags)&&r.tags.length?n.addClass("annotator-tags").html(function(){var n;return n=e.map(r.tags,function(e){return'<span class="annotator-tag">'+t.$.escape(e)+"</span>"}).join(" ")}):n.remove()},r}(t.Plugin),t.Plugin.Tags.filterCallback=function(e,t){var n,r,i,s,o,u,a,f;t==null&&(t=[]),i=0,r=[];if(e){r=e.split(/\s+/g);for(o=0,a=r.length;o<a;o++){n=r[o];if(t.length)for(u=0,f=t.length;u<f;u++)s=t[u],s.indexOf(n)!==-1&&(i+=1)}}return i===r.length},t.Plugin.DigilibIntegrator=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return N(t,e),t.prototype.events={annotationDeleted:"annotationDeleted"},t.prototype.options={hooks:null},t.prototype.pluginInit=function(){return this.annotator.digilib=this.options.hooks,this.annotator.setupRangeAnnotation=this.annotator.setupAnnotation,this.annotator.setupAnnotation=this._setupAnnotation,this},t.prototype._setupAnnotation=function(e,t){return t==null&&(t=!0),this.selectedShapes||e.shapes!=null||this.selectedAreas!=null||e.areas!=null?(e.shapes||(e.shapes=this.selectedShapes),e.areas||(e.areas=this.selectedAreas),e.highlights=[],e.ranges=[],this.digilib.setupAnnotation(e),t&&this.publish("annotationCreated",[e]),e):this.setupRangeAnnotation.apply(this,arguments)},t.prototype.annotationDeleted=function(e){return this.options.hooks.annotationDeleted(e)},t}(t.Plugin)}).call(this); \ No newline at end of file +** Built at: 2015-01-16 17:56:43Z + */ + + +// + +!function(){var $,Annotator,Delegator,LinkParser,Range,Util,base64Decode,base64UrlDecode,createDateFromISO8601,findChild,fn,functions,g,getNodeName,getNodePosition,gettext,parseToken,simpleXPathJQuery,simpleXPathPure,_Annotator,_gettext,_i,_j,_len,_len1,_ref,_ref1,_ref2,_ref3,_ref4,_t,__slice=[].slice,__hasProp={}.hasOwnProperty,__extends=function(child,parent){for(var key in parent){if(__hasProp.call(parent,key))child[key]=parent[key]}function ctor(){this.constructor=child}ctor.prototype=parent.prototype;child.prototype=new ctor;child.__super__=parent.prototype;return child},__bind=function(fn,me){return function(){return fn.apply(me,arguments)}},__indexOf=[].indexOf||function(item){for(var i=0,l=this.length;i<l;i++){if(i in this&&this[i]===item)return i}return-1};simpleXPathJQuery=function(relativeRoot){var jq;jq=this.map(function(){var elem,idx,path,tagName;path="";elem=this;while((elem!=null?elem.nodeType:void 0)===Node.ELEMENT_NODE&&elem!==relativeRoot){tagName=elem.tagName.replace(":","\\:");idx=$(elem.parentNode).children(tagName).index(elem)+1;idx="["+idx+"]";path="/"+elem.tagName.toLowerCase()+idx+path;elem=elem.parentNode}return path});return jq.get()};simpleXPathPure=function(relativeRoot){var getPathSegment,getPathTo,jq,rootNode;getPathSegment=function(node){var name,pos;name=getNodeName(node);pos=getNodePosition(node);return""+name+"["+pos+"]"};rootNode=relativeRoot;getPathTo=function(node){var xpath;xpath="";while(node!==rootNode){if(node==null){throw new Error("Called getPathTo on a node which was not a descendant of @rootNode. "+rootNode)}xpath=getPathSegment(node)+"/"+xpath;node=node.parentNode}xpath="/"+xpath;xpath=xpath.replace(/\/$/,"");return xpath};jq=this.map(function(){var path;path=getPathTo(this);return path});return jq.get()};findChild=function(node,type,index){var child,children,found,name,_i,_len;if(!node.hasChildNodes()){throw new Error("XPath error: node has no children!")}children=node.childNodes;found=0;for(_i=0,_len=children.length;_i<_len;_i++){child=children[_i];name=getNodeName(child);if(name===type){found+=1;if(found===index){return child}}}throw new Error("XPath error: wanted child not found.")};getNodeName=function(node){var nodeName;nodeName=node.nodeName.toLowerCase();switch(nodeName){case"#text":return"text()";case"#comment":return"comment()";case"#cdata-section":return"cdata-section()";default:return nodeName}};getNodePosition=function(node){var pos,tmp;pos=0;tmp=node;while(tmp){if(tmp.nodeName===node.nodeName){pos++}tmp=tmp.previousSibling}return pos};gettext=null;if(typeof Gettext!=="undefined"&&Gettext!==null){_gettext=new Gettext({domain:"annotator"});gettext=function(msgid){return _gettext.gettext(msgid)}}else{gettext=function(msgid){return msgid}}_t=function(msgid){return gettext(msgid)};if(!(typeof jQuery!=="undefined"&&jQuery!==null?(_ref=jQuery.fn)!=null?_ref.jquery:void 0:void 0)){console.error(_t("Annotator requires jQuery: have you included lib/vendor/jquery.js?"))}if(!(JSON&&JSON.parse&&JSON.stringify)){console.error(_t("Annotator requires a JSON implementation: have you included lib/vendor/json2.js?"))}$=jQuery;Util={};Util.flatten=function(array){var flatten;flatten=function(ary){var el,flat,_i,_len;flat=[];for(_i=0,_len=ary.length;_i<_len;_i++){el=ary[_i];flat=flat.concat(el&&$.isArray(el)?flatten(el):el)}return flat};return flatten(array)};Util.contains=function(parent,child){var node;node=child;while(node!=null){if(node===parent){return true}node=node.parentNode}return false};Util.getTextNodes=function(jq){var getTextNodes;getTextNodes=function(node){var nodes;if(node&&node.nodeType!==Node.TEXT_NODE){nodes=[];if(node.nodeType!==Node.COMMENT_NODE){node=node.lastChild;while(node){nodes.push(getTextNodes(node));node=node.previousSibling}}return nodes.reverse()}else{return node}};return jq.map(function(){return Util.flatten(getTextNodes(this))})};Util.getLastTextNodeUpTo=function(n){var result;switch(n.nodeType){case Node.TEXT_NODE:return n;case Node.ELEMENT_NODE:if(n.lastChild!=null){result=Util.getLastTextNodeUpTo(n.lastChild);if(result!=null){return result}}break}n=n.previousSibling;if(n!=null){return Util.getLastTextNodeUpTo(n)}else{return null}};Util.getFirstTextNodeNotBefore=function(n){var result;switch(n.nodeType){case Node.TEXT_NODE:return n;case Node.ELEMENT_NODE:if(n.firstChild!=null){result=Util.getFirstTextNodeNotBefore(n.firstChild);if(result!=null){return result}}break}n=n.nextSibling;if(n!=null){return Util.getFirstTextNodeNotBefore(n)}else{return null}};Util.readRangeViaSelection=function(range){var sel;sel=Util.getGlobal().getSelection();sel.removeAllRanges();sel.addRange(range.toRange());return sel.toString()};Util.xpathFromNode=function(el,relativeRoot){var exception,result;try{result=simpleXPathJQuery.call(el,relativeRoot)}catch(_error){exception=_error;console.log("jQuery-based XPath construction failed! Falling back to manual.");result=simpleXPathPure.call(el,relativeRoot)}return result};Util.nodeFromXPath=function(xp,root){var idx,name,node,step,steps,_i,_len,_ref1;steps=xp.substring(1).split("/");node=root;for(_i=0,_len=steps.length;_i<_len;_i++){step=steps[_i];_ref1=step.split("["),name=_ref1[0],idx=_ref1[1];idx=idx!=null?parseInt((idx!=null?idx.split("]"):void 0)[0]):1;node=findChild(node,name.toLowerCase(),idx)}return node};Util.escape=function(html){return html.replace(/&(?!\w+;)/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")};Util.uuid=function(){var counter;counter=0;return function(){return counter++}}();Util.getGlobal=function(){return function(){return this}()};Util.maxZIndex=function($elements){var all,el;all=function(){var _i,_len,_results;_results=[];for(_i=0,_len=$elements.length;_i<_len;_i++){el=$elements[_i];if($(el).css("position")==="static"){_results.push(-1)}else{_results.push(parseFloat($(el).css("z-index"))||-1)}}return _results}();return Math.max.apply(Math,all)};Util.mousePosition=function(e,offsetEl){var offset,_ref1;if((_ref1=$(offsetEl).css("position"))!=="absolute"&&_ref1!=="fixed"&&_ref1!=="relative"){offsetEl=$(offsetEl).offsetParent()[0]}offset=$(offsetEl).offset();return{top:e.pageY-offset.top,left:e.pageX-offset.left}};Util.preventEventDefault=function(event){return event!=null?typeof event.preventDefault==="function"?event.preventDefault():void 0:void 0};functions=["log","debug","info","warn","exception","assert","dir","dirxml","trace","group","groupEnd","groupCollapsed","time","timeEnd","profile","profileEnd","count","clear","table","error","notifyFirebug","firebug","userObjects"];if(typeof console!=="undefined"&&console!==null){if(console.group==null){console.group=function(name){return console.log("GROUP: ",name)}}if(console.groupCollapsed==null){console.groupCollapsed=console.group}for(_i=0,_len=functions.length;_i<_len;_i++){fn=functions[_i];if(console[fn]==null){console[fn]=function(){return console.log(_t("Not implemented:")+(" console."+name))}}}}else{this.console={};for(_j=0,_len1=functions.length;_j<_len1;_j++){fn=functions[_j];this.console[fn]=function(){}}this.console["error"]=function(){var args;args=1<=arguments.length?__slice.call(arguments,0):[];return alert("ERROR: "+args.join(", "))};this.console["warn"]=function(){var args;args=1<=arguments.length?__slice.call(arguments,0):[];return alert("WARNING: "+args.join(", "))}}Delegator=function(){Delegator.prototype.events={};Delegator.prototype.options={};Delegator.prototype.element=null;function Delegator(element,options){this.options=$.extend(true,{},this.options,options);this.element=$(element);this._closures={};this.on=this.subscribe;this.addEvents()}Delegator.prototype.destroy=function(){return this.removeEvents()};Delegator.prototype.addEvents=function(){var event,_k,_len2,_ref1,_results;_ref1=Delegator._parseEvents(this.events);_results=[];for(_k=0,_len2=_ref1.length;_k<_len2;_k++){event=_ref1[_k];_results.push(this._addEvent(event.selector,event.event,event.functionName))}return _results};Delegator.prototype.removeEvents=function(){var event,_k,_len2,_ref1,_results;_ref1=Delegator._parseEvents(this.events);_results=[];for(_k=0,_len2=_ref1.length;_k<_len2;_k++){event=_ref1[_k];_results.push(this._removeEvent(event.selector,event.event,event.functionName))}return _results};Delegator.prototype._addEvent=function(selector,event,functionName){var closure,_this=this;closure=function(){return _this[functionName].apply(_this,arguments)};if(selector===""&&Delegator._isCustomEvent(event)){this.subscribe(event,closure)}else{this.element.delegate(selector,event,closure)}this._closures[""+selector+"/"+event+"/"+functionName]=closure;return this};Delegator.prototype._removeEvent=function(selector,event,functionName){var closure;closure=this._closures[""+selector+"/"+event+"/"+functionName];if(selector===""&&Delegator._isCustomEvent(event)){this.unsubscribe(event,closure)}else{this.element.undelegate(selector,event,closure)}delete this._closures[""+selector+"/"+event+"/"+functionName];return this};Delegator.prototype.publish=function(){this.element.triggerHandler.apply(this.element,arguments);return this};Delegator.prototype.subscribe=function(event,callback){var closure;closure=function(){return callback.apply(this,[].slice.call(arguments,1))};closure.guid=callback.guid=$.guid+=1;this.element.bind(event,closure);return this};Delegator.prototype.unsubscribe=function(){this.element.unbind.apply(this.element,arguments);return this};return Delegator}();Delegator._parseEvents=function(eventsObj){var event,events,functionName,sel,selector,_k,_ref1;events=[];for(sel in eventsObj){functionName=eventsObj[sel];_ref1=sel.split(" "),selector=2<=_ref1.length?__slice.call(_ref1,0,_k=_ref1.length-1):(_k=0,[]),event=_ref1[_k++];events.push({selector:selector.join(" "),event:event,functionName:functionName})}return events};Delegator.natives=function(){var key,specials,val;specials=function(){var _ref1,_results;_ref1=jQuery.event.special;_results=[];for(key in _ref1){if(!__hasProp.call(_ref1,key))continue;val=_ref1[key];_results.push(key)}return _results}();return"blur focus focusin focusout load resize scroll unload click dblclick\nmousedown mouseup mousemove mouseover mouseout mouseenter mouseleave\nchange select submit keydown keypress keyup error".split(/[^a-z]+/).concat(specials)}();Delegator._isCustomEvent=function(event){event=event.split(".")[0];return $.inArray(event,Delegator.natives)===-1};Range={};Range.sniff=function(r){if(r.commonAncestorContainer!=null){return new Range.BrowserRange(r)}else if(typeof r.start==="string"){return new Range.SerializedRange(r)}else if(r.start&&typeof r.start==="object"){return new Range.NormalizedRange(r)}else{console.error(_t("Could not sniff range type"));return false}};Range.nodeFromXPath=function(xpath,root){var customResolver,evaluateXPath,namespace,node,segment;if(root==null){root=document}evaluateXPath=function(xp,nsResolver){var exception;if(nsResolver==null){nsResolver=null}try{return document.evaluate("."+xp,root,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch(_error){exception=_error;console.log("XPath evaluation failed.");console.log("Trying fallback...");return Util.nodeFromXPath(xp,root)}};if(!$.isXMLDoc(document.documentElement)){return evaluateXPath(xpath)}else{customResolver=document.createNSResolver(document.ownerDocument===null?document.documentElement:document.ownerDocument.documentElement);node=evaluateXPath(xpath,customResolver);if(!node){xpath=function(){var _k,_len2,_ref1,_results;_ref1=xpath.split("/");_results=[];for(_k=0,_len2=_ref1.length;_k<_len2;_k++){segment=_ref1[_k];if(segment&&segment.indexOf(":")===-1){_results.push(segment.replace(/^([a-z]+)/,"xhtml:$1"))}else{_results.push(segment)}}return _results}().join("/");namespace=document.lookupNamespaceURI(null);customResolver=function(ns){if(ns==="xhtml"){return namespace}else{return document.documentElement.getAttribute("xmlns:"+ns)}};node=evaluateXPath(xpath,customResolver)}return node}};Range.RangeError=function(_super){__extends(RangeError,_super);function RangeError(type,message,parent){this.type=type;this.message=message;this.parent=parent!=null?parent:null;RangeError.__super__.constructor.call(this,this.message)}return RangeError}(Error);Range.BrowserRange=function(){function BrowserRange(obj){this.commonAncestorContainer=obj.commonAncestorContainer;this.startContainer=obj.startContainer;this.startOffset=obj.startOffset;this.endContainer=obj.endContainer;this.endOffset=obj.endOffset}BrowserRange.prototype.normalize=function(root){var n,node,nr,r;if(this.tainted){console.error(_t("You may only call normalize() once on a BrowserRange!"));return false}else{this.tainted=true}r={};if(this.startContainer.nodeType===Node.ELEMENT_NODE){r.start=Util.getFirstTextNodeNotBefore(this.startContainer.childNodes[this.startOffset]);r.startOffset=0}else{r.start=this.startContainer;r.startOffset=this.startOffset}if(this.endContainer.nodeType===Node.ELEMENT_NODE){node=this.endContainer.childNodes[this.endOffset];if(node!=null){n=node;while(n!=null&&n.nodeType!==Node.TEXT_NODE){n=n.firstChild}if(n!=null){r.end=n;r.endOffset=0}}if(r.end==null){node=this.endContainer.childNodes[this.endOffset-1];r.end=Util.getLastTextNodeUpTo(node);r.endOffset=r.end.nodeValue.length}}else{r.end=this.endContainer;r.endOffset=this.endOffset}nr={};if(r.startOffset>0){if(r.start.nodeValue.length>r.startOffset){nr.start=r.start.splitText(r.startOffset)}else{nr.start=r.start.nextSibling}}else{nr.start=r.start}if(r.start===r.end){if(nr.start.nodeValue.length>r.endOffset-r.startOffset){nr.start.splitText(r.endOffset-r.startOffset)}nr.end=nr.start}else{if(r.end.nodeValue.length>r.endOffset){r.end.splitText(r.endOffset)}nr.end=r.end}nr.commonAncestor=this.commonAncestorContainer;while(nr.commonAncestor.nodeType!==Node.ELEMENT_NODE){nr.commonAncestor=nr.commonAncestor.parentNode}return new Range.NormalizedRange(nr)};BrowserRange.prototype.serialize=function(root,ignoreSelector){return this.normalize(root).serialize(root,ignoreSelector)};return BrowserRange}();Range.NormalizedRange=function(){function NormalizedRange(obj){this.commonAncestor=obj.commonAncestor;this.start=obj.start;this.end=obj.end}NormalizedRange.prototype.normalize=function(root){return this};NormalizedRange.prototype.limit=function(bounds){var nodes,parent,startParents,_k,_len2,_ref1;nodes=$.grep(this.textNodes(),function(node){return node.parentNode===bounds||$.contains(bounds,node.parentNode)});if(!nodes.length){return null}this.start=nodes[0];this.end=nodes[nodes.length-1];startParents=$(this.start).parents();_ref1=$(this.end).parents();for(_k=0,_len2=_ref1.length;_k<_len2;_k++){parent=_ref1[_k];if(startParents.index(parent)!==-1){this.commonAncestor=parent;break}}return this};NormalizedRange.prototype.serialize=function(root,ignoreSelector){var end,serialization,start;serialization=function(node,isEnd){var n,nodes,offset,origParent,textNodes,xpath,_k,_len2;if(ignoreSelector){origParent=$(node).parents(":not("+ignoreSelector+")").eq(0)}else{origParent=$(node).parent()}xpath=Util.xpathFromNode(origParent,root)[0];textNodes=Util.getTextNodes(origParent);nodes=textNodes.slice(0,textNodes.index(node));offset=0;for(_k=0,_len2=nodes.length;_k<_len2;_k++){n=nodes[_k];offset+=n.nodeValue.length}if(isEnd){return[xpath,offset+node.nodeValue.length]}else{return[xpath,offset]}};start=serialization(this.start);end=serialization(this.end,true);return new Range.SerializedRange({start:start[0],end:end[0],startOffset:start[1],endOffset:end[1]})};NormalizedRange.prototype.text=function(){var node;return function(){var _k,_len2,_ref1,_results;_ref1=this.textNodes();_results=[];for(_k=0,_len2=_ref1.length;_k<_len2;_k++){node=_ref1[_k];_results.push(node.nodeValue)}return _results}.call(this).join("")};NormalizedRange.prototype.textNodes=function(){var end,start,textNodes,_ref1;textNodes=Util.getTextNodes($(this.commonAncestor));_ref1=[textNodes.index(this.start),textNodes.index(this.end)],start=_ref1[0],end=_ref1[1];return $.makeArray(textNodes.slice(start,+end+1||9e9))};NormalizedRange.prototype.toRange=function(){var range;range=document.createRange();range.setStartBefore(this.start);range.setEndAfter(this.end);return range};return NormalizedRange}();Range.SerializedRange=function(){function SerializedRange(obj){this.start=obj.start;this.startOffset=obj.startOffset;this.end=obj.end;this.endOffset=obj.endOffset}SerializedRange.prototype.normalize=function(root){var contains,e,length,node,p,range,targetOffset,tn,_k,_l,_len2,_len3,_ref1,_ref2;range={};_ref1=["start","end"];for(_k=0,_len2=_ref1.length;_k<_len2;_k++){p=_ref1[_k];try{node=Range.nodeFromXPath(this[p],root)}catch(_error){e=_error;throw new Range.RangeError(p,"Error while finding "+p+" node: "+this[p]+": "+e,e)}if(!node){throw new Range.RangeError(p,"Couldn't find "+p+" node: "+this[p])}length=0;targetOffset=this[p+"Offset"];if(p==="end"){targetOffset--}_ref2=Util.getTextNodes($(node));for(_l=0,_len3=_ref2.length;_l<_len3;_l++){tn=_ref2[_l];if(length+tn.nodeValue.length>targetOffset){range[p+"Container"]=tn;range[p+"Offset"]=this[p+"Offset"]-length;break}else{length+=tn.nodeValue.length}}if(range[p+"Offset"]==null){throw new Range.RangeError(""+p+"offset","Couldn't find offset "+this[p+"Offset"]+" in element "+this[p])}}contains=document.compareDocumentPosition==null?function(a,b){return a.contains(b)}:function(a,b){return a.compareDocumentPosition(b)&16};$(range.startContainer).parents().each(function(){if(contains(this,range.endContainer)){range.commonAncestorContainer=this;return false}});return new Range.BrowserRange(range).normalize(root)};SerializedRange.prototype.serialize=function(root,ignoreSelector){return this.normalize(root).serialize(root,ignoreSelector)};SerializedRange.prototype.toObject=function(){return{start:this.start,startOffset:this.startOffset,end:this.end,endOffset:this.endOffset}};return SerializedRange}();_Annotator=this.Annotator;Annotator=function(_super){__extends(Annotator,_super);Annotator.prototype.events={".annotator-adder button click":"onAdderClick",".annotator-adder button mousedown":"onAdderMousedown",".annotator-hl mouseover":"onHighlightMouseover",".annotator-hl mouseout":"startViewerHideTimer"};Annotator.prototype.html={adder:'<div class="annotator-adder"><button>'+_t("Annotate")+"</button></div>",wrapper:'<div class="annotator-wrapper"></div>'};Annotator.prototype.options={readOnly:false};Annotator.prototype.plugins={};Annotator.prototype.editor=null;Annotator.prototype.viewer=null;Annotator.prototype.selectedRanges=null;Annotator.prototype.mouseIsDown=false;Annotator.prototype.ignoreMouseup=false;Annotator.prototype.viewerHideTimer=null;function Annotator(element,options){this.onDeleteAnnotation=__bind(this.onDeleteAnnotation,this);this.onEditAnnotation=__bind(this.onEditAnnotation,this);this.onAdderClick=__bind(this.onAdderClick,this);this.onAdderMousedown=__bind(this.onAdderMousedown,this);this.onHighlightMouseover=__bind(this.onHighlightMouseover,this);this.checkForEndSelection=__bind(this.checkForEndSelection,this);this.checkForStartSelection=__bind(this.checkForStartSelection,this);this.clearViewerHideTimer=__bind(this.clearViewerHideTimer,this);this.startViewerHideTimer=__bind(this.startViewerHideTimer,this);this.showViewer=__bind(this.showViewer,this);this.onEditorSubmit=__bind(this.onEditorSubmit,this);this.onEditorHide=__bind(this.onEditorHide,this);this.showEditor=__bind(this.showEditor,this);Annotator.__super__.constructor.apply(this,arguments);this.plugins={};if(!Annotator.supported()){return this}if(!this.options.readOnly){this._setupDocumentEvents()}this._setupWrapper()._setupViewer()._setupEditor();this._setupDynamicStyle();this.adder=$(this.html.adder).appendTo(this.wrapper).hide();Annotator._instances.push(this)}Annotator.prototype._setupWrapper=function(){this.wrapper=$(this.html.wrapper);this.element.find("script").remove();this.element.wrapInner(this.wrapper);this.wrapper=this.element.find(".annotator-wrapper");return this};Annotator.prototype._setupViewer=function(){var _this=this;this.viewer=new Annotator.Viewer({readOnly:this.options.readOnly});this.viewer.hide().on("edit",this.onEditAnnotation).on("delete",this.onDeleteAnnotation).addField({load:function(field,annotation){if(annotation.text){$(field).html(Util.escape(annotation.text))}else{$(field).html("<i>"+_t("No Comment")+"</i>")}return _this.publish("annotationViewerTextField",[field,annotation])}}).element.appendTo(this.wrapper).bind({mouseover:this.clearViewerHideTimer,mouseout:this.startViewerHideTimer});return this};Annotator.prototype._setupEditor=function(){this.editor=new Annotator.Editor;this.editor.hide().on("hide",this.onEditorHide).on("save",this.onEditorSubmit).addField({type:"textarea",label:_t("Comments")+"…",load:function(field,annotation){return $(field).find("textarea").val(annotation.text||"")},submit:function(field,annotation){return annotation.text=$(field).find("textarea").val()}});this.editor.element.appendTo(this.wrapper);return this};Annotator.prototype._setupDocumentEvents=function(){$(document).bind({mouseup:this.checkForEndSelection,mousedown:this.checkForStartSelection});return this};Annotator.prototype._setupDynamicStyle=function(){var max,sel,style,x;style=$("#annotator-dynamic-style");if(!style.length){style=$('<style id="annotator-dynamic-style"></style>').appendTo(document.head)}sel="*"+function(){var _k,_len2,_ref1,_results;_ref1=["adder","outer","notice","filter"];_results=[];for(_k=0,_len2=_ref1.length;_k<_len2;_k++){x=_ref1[_k];_results.push(":not(.annotator-"+x+")")}return _results}().join("");max=Util.maxZIndex($(document.body).find(sel));max=Math.max(max,1e3);style.text([".annotator-adder, .annotator-outer, .annotator-notice {"," z-index: "+(max+20)+";","}",".annotator-filter {"," z-index: "+(max+10)+";","}"].join("\n"));return this};Annotator.prototype.destroy=function(){var idx,name,plugin,_base,_ref1;Annotator.__super__.destroy.apply(this,arguments);$(document).unbind({mouseup:this.checkForEndSelection,mousedown:this.checkForStartSelection});$("#annotator-dynamic-style").remove();this.adder.remove();this.viewer.destroy();this.editor.destroy();this.wrapper.find(".annotator-hl").each(function(){$(this).contents().insertBefore(this);return $(this).remove()});this.wrapper.contents().insertBefore(this.wrapper);this.wrapper.remove();this.element.data("annotator",null);_ref1=this.plugins;for(name in _ref1){plugin=_ref1[name];if(typeof(_base=this.plugins[name]).destroy==="function"){_base.destroy()}}idx=Annotator._instances.indexOf(this);if(idx!==-1){return Annotator._instances.splice(idx,1)}};Annotator.prototype.getSelectedRanges=function(){var browserRange,i,normedRange,r,ranges,rangesToIgnore,selection,_k,_len2;selection=Util.getGlobal().getSelection();ranges=[];rangesToIgnore=[];if(!selection.isCollapsed){ranges=function(){var _k,_ref1,_results;_results=[];for(i=_k=0,_ref1=selection.rangeCount;0<=_ref1?_k<_ref1:_k>_ref1;i=0<=_ref1?++_k:--_k){r=selection.getRangeAt(i);browserRange=new Range.BrowserRange(r);normedRange=browserRange.normalize().limit(this.wrapper[0]);if(normedRange===null){rangesToIgnore.push(r)}_results.push(normedRange)}return _results}.call(this);selection.removeAllRanges()}for(_k=0,_len2=rangesToIgnore.length;_k<_len2;_k++){r=rangesToIgnore[_k];selection.addRange(r)}return $.grep(ranges,function(range){if(range){selection.addRange(range.toRange())}return range})};Annotator.prototype.createAnnotation=function(){var annotation;annotation={};this.publish("beforeAnnotationCreated",[annotation]);return annotation};Annotator.prototype.setupAnnotation=function(annotation){var e,normed,normedRanges,r,root,_k,_l,_len2,_len3,_ref1;root=this.wrapper[0];annotation.ranges||(annotation.ranges=this.selectedRanges);normedRanges=[];_ref1=annotation.ranges;for(_k=0,_len2=_ref1.length;_k<_len2;_k++){r=_ref1[_k];try{normedRanges.push(Range.sniff(r).normalize(root))}catch(_error){e=_error;if(e instanceof Range.RangeError){this.publish("rangeNormalizeFail",[annotation,r,e])}else{throw e}}}annotation.quote=[];annotation.ranges=[];annotation.highlights=[];for(_l=0,_len3=normedRanges.length;_l<_len3;_l++){normed=normedRanges[_l];annotation.quote.push($.trim(normed.text()));annotation.ranges.push(normed.serialize(this.wrapper[0],".annotator-hl"));$.merge(annotation.highlights,this.highlightRange(normed))}annotation.quote=annotation.quote.join(" / ");$(annotation.highlights).data("annotation",annotation);$(annotation.highlights).attr("data-annotation-id",annotation.id);return annotation};Annotator.prototype.updateAnnotation=function(annotation){this.publish("beforeAnnotationUpdated",[annotation]);$(annotation.highlights).attr("data-annotation-id",annotation.id);this.publish("annotationUpdated",[annotation]);return annotation};Annotator.prototype.deleteAnnotation=function(annotation){var child,h,_k,_len2,_ref1;if(annotation.highlights!=null){_ref1=annotation.highlights;for(_k=0,_len2=_ref1.length;_k<_len2;_k++){h=_ref1[_k];if(!(h.parentNode!=null)){continue}child=h.childNodes[0];$(h).replaceWith(h.childNodes)}}this.publish("annotationDeleted",[annotation]);return annotation};Annotator.prototype.loadAnnotations=function(annotations){var clone,loader,_this=this;if(annotations==null){annotations=[]}loader=function(annList){var n,now,_k,_len2;if(annList==null){annList=[]}now=annList.splice(0,10);for(_k=0,_len2=now.length;_k<_len2;_k++){n=now[_k];_this.setupAnnotation(n)}if(annList.length>0){return setTimeout(function(){return loader(annList)},10)}else{return _this.publish("annotationsLoaded",[clone])}};clone=annotations.slice();loader(annotations);return this};Annotator.prototype.dumpAnnotations=function(){if(this.plugins["Store"]){return this.plugins["Store"].dumpAnnotations()}else{console.warn(_t("Can't dump annotations without Store plugin."));return false}};Annotator.prototype.highlightRange=function(normedRange,cssClass){var hl,node,white,_k,_len2,_ref1,_results;if(cssClass==null){cssClass="annotator-hl"}white=/^\s*$/;hl=$("<span class='"+cssClass+"'></span>");_ref1=normedRange.textNodes();_results=[];for(_k=0,_len2=_ref1.length;_k<_len2;_k++){node=_ref1[_k];if(!white.test(node.nodeValue)){_results.push($(node).wrapAll(hl).parent().show()[0])}}return _results};Annotator.prototype.highlightRanges=function(normedRanges,cssClass){var highlights,r,_k,_len2;if(cssClass==null){cssClass="annotator-hl"}highlights=[];for(_k=0,_len2=normedRanges.length;_k<_len2;_k++){r=normedRanges[_k];$.merge(highlights,this.highlightRange(r,cssClass))}return highlights};Annotator.prototype.addPlugin=function(name,options){var klass,_base;if(this.plugins[name]){console.error(_t("You cannot have more than one instance of any plugin."))}else{klass=Annotator.Plugin[name];if(typeof klass==="function"){this.plugins[name]=new klass(this.element[0],options);this.plugins[name].annotator=this;if(typeof(_base=this.plugins[name]).pluginInit==="function"){_base.pluginInit()}}else{console.error(_t("Could not load ")+name+_t(" plugin. Have you included the appropriate <script> tag?"))}}return this};Annotator.prototype.showEditor=function(annotation,location){this.editor.element.css(location);this.editor.load(annotation);this.publish("annotationEditorShown",[this.editor,annotation]);return this};Annotator.prototype.onEditorHide=function(){this.publish("annotationEditorHidden",[this.editor]);return this.ignoreMouseup=false};Annotator.prototype.onEditorSubmit=function(annotation){return this.publish("annotationEditorSubmit",[this.editor,annotation])};Annotator.prototype.showViewer=function(annotations,location){this.viewer.element.css(location);this.viewer.load(annotations);return this.publish("annotationViewerShown",[this.viewer,annotations])};Annotator.prototype.startViewerHideTimer=function(){if(!this.viewerHideTimer){return this.viewerHideTimer=setTimeout(this.viewer.hide,250)}};Annotator.prototype.clearViewerHideTimer=function(){clearTimeout(this.viewerHideTimer);return this.viewerHideTimer=false};Annotator.prototype.checkForStartSelection=function(event){if(!(event&&this.isAnnotator(event.target))){this.startViewerHideTimer()}return this.mouseIsDown=true};Annotator.prototype.checkForEndSelection=function(event){var container,range,_k,_len2,_ref1;this.mouseIsDown=false;if(this.ignoreMouseup){return}this.selectedRanges=this.getSelectedRanges();_ref1=this.selectedRanges;for(_k=0,_len2=_ref1.length;_k<_len2;_k++){range=_ref1[_k];container=range.commonAncestor;if($(container).hasClass("annotator-hl")){container=$(container).parents("[class!=annotator-hl]")[0]}if(this.isAnnotator(container)){return}}if(event&&this.selectedRanges.length){return this.adder.css(Util.mousePosition(event,this.wrapper[0])).show()}else{return this.adder.hide()}};Annotator.prototype.isAnnotator=function(element){return!!$(element).parents().addBack().filter("[class^=annotator-]").not(this.wrapper).length};Annotator.prototype.onHighlightMouseover=function(event){var annotations;this.clearViewerHideTimer();if(this.mouseIsDown){return false}if(this.viewer.isShown()){this.viewer.hide()}annotations=$(event.target).parents(".annotator-hl").addBack().map(function(){return $(this).data("annotation")}).toArray();return this.showViewer(annotations,Util.mousePosition(event,this.wrapper[0]))};Annotator.prototype.onAdderMousedown=function(event){if(event!=null){event.preventDefault()}return this.ignoreMouseup=true};Annotator.prototype.onAdderClick=function(event){var annotation,cancel,cleanup,position,save,_this=this;if(event!=null){event.preventDefault()}position=this.adder.position();this.adder.hide();annotation=this.setupAnnotation(this.createAnnotation());$(annotation.highlights).addClass("annotator-hl-temporary");save=function(){cleanup();$(annotation.highlights).removeClass("annotator-hl-temporary");return _this.publish("annotationCreated",[annotation])};cancel=function(){cleanup();return _this.deleteAnnotation(annotation)};cleanup=function(){_this.unsubscribe("annotationEditorHidden",cancel);return _this.unsubscribe("annotationEditorSubmit",save)};this.subscribe("annotationEditorHidden",cancel);this.subscribe("annotationEditorSubmit",save);return this.showEditor(annotation,position)};Annotator.prototype.onEditAnnotation=function(annotation){var cleanup,offset,update,_this=this;offset=this.viewer.element.position();update=function(){cleanup();return _this.updateAnnotation(annotation)};cleanup=function(){_this.unsubscribe("annotationEditorHidden",cleanup);return _this.unsubscribe("annotationEditorSubmit",update)};this.subscribe("annotationEditorHidden",cleanup);this.subscribe("annotationEditorSubmit",update);this.viewer.hide();return this.showEditor(annotation,offset)};Annotator.prototype.onDeleteAnnotation=function(annotation){this.viewer.hide();return this.deleteAnnotation(annotation)};return Annotator}(Delegator);Annotator.Plugin=function(_super){__extends(Plugin,_super);function Plugin(element,options){Plugin.__super__.constructor.apply(this,arguments)}Plugin.prototype.pluginInit=function(){};return Plugin}(Delegator);g=Util.getGlobal();if(((_ref1=g.document)!=null?_ref1.evaluate:void 0)==null){$.getScript("http://assets.annotateit.org/vendor/xpath.min.js")}if(g.getSelection==null){$.getScript("http://assets.annotateit.org/vendor/ierange.min.js")}if(g.JSON==null){$.getScript("http://assets.annotateit.org/vendor/json2.min.js")}if(g.Node==null){g.Node={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12}}Annotator.$=$;Annotator.Delegator=Delegator;Annotator.Range=Range;Annotator.Util=Util;Annotator._instances=[];Annotator._t=_t;Annotator.supported=function(){return function(){return!!this.getSelection}()};Annotator.noConflict=function(){Util.getGlobal().Annotator=_Annotator;return this};$.fn.annotator=function(options){var args;args=Array.prototype.slice.call(arguments,1);return this.each(function(){var instance;instance=$.data(this,"annotator"); +if(options==="destroy"){$.removeData(this,"annotator");return instance!=null?instance.destroy(args):void 0}else if(instance){return options&&instance[options].apply(instance,args)}else{instance=new Annotator(this,options);return $.data(this,"annotator",instance)}})};this.Annotator=Annotator;Annotator.Widget=function(_super){__extends(Widget,_super);Widget.prototype.classes={hide:"annotator-hide",invert:{x:"annotator-invert-x",y:"annotator-invert-y"}};function Widget(element,options){Widget.__super__.constructor.apply(this,arguments);this.classes=$.extend({},Annotator.Widget.prototype.classes,this.classes)}Widget.prototype.destroy=function(){this.removeEvents();return this.element.remove()};Widget.prototype.checkOrientation=function(){var current,offset,viewport,widget,window;this.resetOrientation();window=$(Annotator.Util.getGlobal());widget=this.element.children(":first");offset=widget.offset();viewport={top:window.scrollTop(),right:window.width()+window.scrollLeft()};current={top:offset.top,right:offset.left+widget.width()};if(current.top-viewport.top<0){this.invertY()}if(current.right-viewport.right>0){this.invertX()}return this};Widget.prototype.resetOrientation=function(){this.element.removeClass(this.classes.invert.x).removeClass(this.classes.invert.y);return this};Widget.prototype.invertX=function(){this.element.addClass(this.classes.invert.x);return this};Widget.prototype.invertY=function(){this.element.addClass(this.classes.invert.y);return this};Widget.prototype.isInvertedY=function(){return this.element.hasClass(this.classes.invert.y)};Widget.prototype.isInvertedX=function(){return this.element.hasClass(this.classes.invert.x)};return Widget}(Delegator);Annotator.Editor=function(_super){__extends(Editor,_super);Editor.prototype.events={"form submit":"submit",".annotator-save click":"submit",".annotator-cancel click":"hide",".annotator-cancel mouseover":"onCancelButtonMouseover","textarea keydown":"processKeypress"};Editor.prototype.classes={hide:"annotator-hide",focus:"annotator-focus"};Editor.prototype.html='<div class="annotator-outer annotator-editor">\n <form class="annotator-widget">\n <ul class="annotator-listing"></ul>\n <div class="annotator-controls">\n <a href="#cancel" class="annotator-cancel">'+_t("Cancel")+'</a>\n<a href="#save" class="annotator-save annotator-focus">'+_t("Save")+"</a>\n </div>\n </form>\n</div>";Editor.prototype.options={};function Editor(options){this.onCancelButtonMouseover=__bind(this.onCancelButtonMouseover,this);this.processKeypress=__bind(this.processKeypress,this);this.submit=__bind(this.submit,this);this.load=__bind(this.load,this);this.hide=__bind(this.hide,this);this.show=__bind(this.show,this);Editor.__super__.constructor.call(this,$(this.html)[0],options);this.fields=[];this.annotation={}}Editor.prototype.show=function(event){Annotator.Util.preventEventDefault(event);this.element.removeClass(this.classes.hide);this.element.find(".annotator-save").addClass(this.classes.focus);this.checkOrientation();this.element.find(":input:first").focus();this.setupDraggables();return this.publish("show")};Editor.prototype.hide=function(event){Annotator.Util.preventEventDefault(event);this.element.addClass(this.classes.hide);return this.publish("hide")};Editor.prototype.load=function(annotation){var field,_k,_len2,_ref2;this.annotation=annotation;this.publish("load",[this.annotation]);_ref2=this.fields;for(_k=0,_len2=_ref2.length;_k<_len2;_k++){field=_ref2[_k];field.load(field.element,this.annotation)}return this.show()};Editor.prototype.submit=function(event){var field,_k,_len2,_ref2;Annotator.Util.preventEventDefault(event);_ref2=this.fields;for(_k=0,_len2=_ref2.length;_k<_len2;_k++){field=_ref2[_k];field.submit(field.element,this.annotation)}this.publish("save",[this.annotation]);return this.hide()};Editor.prototype.addField=function(options){var element,field,input;field=$.extend({id:"annotator-field-"+Annotator.Util.uuid(),type:"input",label:"",load:function(){},submit:function(){}},options);input=null;element=$('<li class="annotator-item" />');field.element=element[0];switch(field.type){case"textarea":input=$("<textarea />");break;case"input":case"checkbox":input=$("<input />");break;case"select":input=$("<select />")}element.append(input);input.attr({id:field.id,placeholder:field.label});if(field.type==="checkbox"){input[0].type="checkbox";element.addClass("annotator-checkbox");element.append($("<label />",{"for":field.id,html:field.label}))}this.element.find("ul:first").append(element);this.fields.push(field);return field.element};Editor.prototype.checkOrientation=function(){var controls,list;Editor.__super__.checkOrientation.apply(this,arguments);list=this.element.find("ul");controls=this.element.find(".annotator-controls");if(this.element.hasClass(this.classes.invert.y)){controls.insertBefore(list)}else if(controls.is(":first-child")){controls.insertAfter(list)}return this};Editor.prototype.processKeypress=function(event){if(event.keyCode===27){return this.hide()}else if(event.keyCode===13&&!event.shiftKey){return this.submit()}};Editor.prototype.onCancelButtonMouseover=function(){return this.element.find("."+this.classes.focus).removeClass(this.classes.focus)};Editor.prototype.setupDraggables=function(){var classes,controls,cornerItem,editor,mousedown,onMousedown,onMousemove,onMouseup,resize,textarea,throttle,_this=this;this.element.find(".annotator-resize").remove();if(this.element.hasClass(this.classes.invert.y)){cornerItem=this.element.find(".annotator-item:last")}else{cornerItem=this.element.find(".annotator-item:first")}if(cornerItem){$('<span class="annotator-resize"></span>').appendTo(cornerItem)}mousedown=null;classes=this.classes;editor=this.element;textarea=null;resize=editor.find(".annotator-resize");controls=editor.find(".annotator-controls");throttle=false;onMousedown=function(event){if(event.target===this){mousedown={element:this,top:event.pageY,left:event.pageX};textarea=editor.find("textarea:first");$(window).bind({"mouseup.annotator-editor-resize":onMouseup,"mousemove.annotator-editor-resize":onMousemove});return event.preventDefault()}};onMouseup=function(){mousedown=null;return $(window).unbind(".annotator-editor-resize")};onMousemove=function(event){var diff,directionX,directionY,height,width;if(mousedown&&throttle===false){diff={top:event.pageY-mousedown.top,left:event.pageX-mousedown.left};if(mousedown.element===resize[0]){height=textarea.outerHeight();width=textarea.outerWidth();directionX=editor.hasClass(classes.invert.x)?-1:1;directionY=editor.hasClass(classes.invert.y)?1:-1;textarea.height(height+diff.top*directionY);textarea.width(width+diff.left*directionX);if(textarea.outerHeight()!==height){mousedown.top=event.pageY}if(textarea.outerWidth()!==width){mousedown.left=event.pageX}}else if(mousedown.element===controls[0]){editor.css({top:parseInt(editor.css("top"),10)+diff.top,left:parseInt(editor.css("left"),10)+diff.left});mousedown.top=event.pageY;mousedown.left=event.pageX}throttle=true;return setTimeout(function(){return throttle=false},1e3/60)}};resize.bind("mousedown",onMousedown);return controls.bind("mousedown",onMousedown)};return Editor}(Annotator.Widget);Annotator.Viewer=function(_super){__extends(Viewer,_super);Viewer.prototype.events={".annotator-edit click":"onEditClick",".annotator-delete click":"onDeleteClick"};Viewer.prototype.classes={hide:"annotator-hide",showControls:"annotator-visible"};Viewer.prototype.html={element:'<div class="annotator-outer annotator-viewer">\n <ul class="annotator-widget annotator-listing"></ul>\n</div>',item:'<li class="annotator-annotation annotator-item">\n <span class="annotator-controls">\n <a href="#" title="View as webpage" class="annotator-link">View as webpage</a>\n <button title="Edit" class="annotator-edit">Edit</button>\n <button title="Delete" class="annotator-delete">Delete</button>\n </span>\n</li>'};Viewer.prototype.options={readOnly:false};function Viewer(options){this.onDeleteClick=__bind(this.onDeleteClick,this);this.onEditClick=__bind(this.onEditClick,this);this.load=__bind(this.load,this);this.hide=__bind(this.hide,this);this.show=__bind(this.show,this);Viewer.__super__.constructor.call(this,$(this.html.element)[0],options);this.item=$(this.html.item)[0];this.fields=[];this.annotations=[]}Viewer.prototype.show=function(event){var controls,_this=this;Annotator.Util.preventEventDefault(event);controls=this.element.find(".annotator-controls").addClass(this.classes.showControls);setTimeout(function(){return controls.removeClass(_this.classes.showControls)},500);this.element.removeClass(this.classes.hide);return this.checkOrientation().publish("show")};Viewer.prototype.isShown=function(){return!this.element.hasClass(this.classes.hide)};Viewer.prototype.hide=function(event){Annotator.Util.preventEventDefault(event);this.element.addClass(this.classes.hide);return this.publish("hide")};Viewer.prototype.load=function(annotations){var annotation,controller,controls,del,edit,element,field,item,link,links,list,_k,_l,_len2,_len3,_ref2,_ref3;this.annotations=annotations||[];list=this.element.find("ul:first").empty();_ref2=this.annotations;for(_k=0,_len2=_ref2.length;_k<_len2;_k++){annotation=_ref2[_k];item=$(this.item).clone().appendTo(list).data("annotation",annotation);controls=item.find(".annotator-controls");link=controls.find(".annotator-link");edit=controls.find(".annotator-edit");del=controls.find(".annotator-delete");links=new LinkParser(annotation.links||[]).get("alternate",{type:"text/html"});if(links.length===0||links[0].href==null){link.remove()}else{link.attr("href",links[0].href)}if(this.options.readOnly){edit.remove();del.remove()}else{controller={showEdit:function(){return edit.removeAttr("disabled")},hideEdit:function(){return edit.attr("disabled","disabled")},showDelete:function(){return del.removeAttr("disabled")},hideDelete:function(){return del.attr("disabled","disabled")}}}_ref3=this.fields;for(_l=0,_len3=_ref3.length;_l<_len3;_l++){field=_ref3[_l];element=$(field.element).clone().appendTo(item)[0];field.load(element,annotation,controller)}}this.publish("load",[this.annotations]);return this.show()};Viewer.prototype.addField=function(options){var field;field=$.extend({load:function(){}},options);field.element=$("<div />")[0];this.fields.push(field);field.element;return this};Viewer.prototype.onEditClick=function(event){return this.onButtonClick(event,"edit")};Viewer.prototype.onDeleteClick=function(event){return this.onButtonClick(event,"delete")};Viewer.prototype.onButtonClick=function(event,type){var item;item=$(event.target).parents(".annotator-annotation");return this.publish(type,[item.data("annotation")])};return Viewer}(Annotator.Widget);LinkParser=function(){function LinkParser(data){this.data=data}LinkParser.prototype.get=function(rel,cond){var d,k,keys,match,v,_k,_len2,_ref2,_results;if(cond==null){cond={}}cond=$.extend({},cond,{rel:rel});keys=function(){var _results;_results=[];for(k in cond){if(!__hasProp.call(cond,k))continue;v=cond[k];_results.push(k)}return _results}();_ref2=this.data;_results=[];for(_k=0,_len2=_ref2.length;_k<_len2;_k++){d=_ref2[_k];match=keys.reduce(function(m,k){return m&&d[k]===cond[k]},true);if(match){_results.push(d)}else{continue}}return _results};return LinkParser}();Annotator=Annotator||{};Annotator.Notification=function(_super){__extends(Notification,_super);Notification.prototype.events={click:"hide"};Notification.prototype.options={html:"<div class='annotator-notice'></div>",classes:{show:"annotator-notice-show",info:"annotator-notice-info",success:"annotator-notice-success",error:"annotator-notice-error"}};function Notification(options){this.hide=__bind(this.hide,this);this.show=__bind(this.show,this);Notification.__super__.constructor.call(this,$(this.options.html).appendTo(document.body)[0],options)}Notification.prototype.show=function(message,status){if(status==null){status=Annotator.Notification.INFO}this.currentStatus=status;$(this.element).addClass(this.options.classes.show).addClass(this.options.classes[this.currentStatus]).html(Util.escape(message||""));setTimeout(this.hide,5e3);return this};Notification.prototype.hide=function(){if(this.currentStatus==null){this.currentStatus=Annotator.Notification.INFO}$(this.element).removeClass(this.options.classes.show).removeClass(this.options.classes[this.currentStatus]);return this};return Notification}(Delegator);Annotator.Notification.INFO="info";Annotator.Notification.SUCCESS="success";Annotator.Notification.ERROR="error";$(function(){var notification;notification=new Annotator.Notification;Annotator.showNotification=notification.show;return Annotator.hideNotification=notification.hide});Annotator.Plugin.Unsupported=function(_super){__extends(Unsupported,_super);function Unsupported(){_ref2=Unsupported.__super__.constructor.apply(this,arguments);return _ref2}Unsupported.prototype.options={message:Annotator._t("Sorry your current browser does not support the Annotator")};Unsupported.prototype.pluginInit=function(){var _this=this;if(!Annotator.supported()){return $(function(){Annotator.showNotification(_this.options.message);if(window.XMLHttpRequest===void 0&&ActiveXObject!==void 0){return $("html").addClass("ie6")}})}};return Unsupported}(Annotator.Plugin);createDateFromISO8601=function(string){var d,date,offset,regexp,time,_ref3;regexp="([0-9]{4})(-([0-9]{2})(-([0-9]{2})"+"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?"+"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";d=string.match(new RegExp(regexp));offset=0;date=new Date(d[1],0,1);if(d[3]){date.setMonth(d[3]-1)}if(d[5]){date.setDate(d[5])}if(d[7]){date.setHours(d[7])}if(d[8]){date.setMinutes(d[8])}if(d[10]){date.setSeconds(d[10])}if(d[12]){date.setMilliseconds(Number("0."+d[12])*1e3)}if(d[14]){offset=Number(d[16])*60+Number(d[17]);offset*=(_ref3=d[15]==="-")!=null?_ref3:{1:-1}}offset-=date.getTimezoneOffset();time=Number(date)+offset*60*1e3;date.setTime(Number(time));return date};base64Decode=function(data){var ac,b64,bits,dec,h1,h2,h3,h4,i,o1,o2,o3,tmp_arr;if(typeof atob!=="undefined"&&atob!==null){return atob(data)}else{b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i=0;ac=0;dec="";tmp_arr=[];if(!data){return data}data+="";while(i<data.length){h1=b64.indexOf(data.charAt(i++));h2=b64.indexOf(data.charAt(i++));h3=b64.indexOf(data.charAt(i++));h4=b64.indexOf(data.charAt(i++));bits=h1<<18|h2<<12|h3<<6|h4;o1=bits>>16&255;o2=bits>>8&255;o3=bits&255;if(h3===64){tmp_arr[ac++]=String.fromCharCode(o1)}else if(h4===64){tmp_arr[ac++]=String.fromCharCode(o1,o2)}else{tmp_arr[ac++]=String.fromCharCode(o1,o2,o3)}}return tmp_arr.join("")}};base64UrlDecode=function(data){var i,m,_k,_ref3;m=data.length%4;if(m!==0){for(i=_k=0,_ref3=4-m;0<=_ref3?_k<_ref3:_k>_ref3;i=0<=_ref3?++_k:--_k){data+="="}}data=data.replace(/-/g,"+");data=data.replace(/_/g,"/");return base64Decode(data)};parseToken=function(token){var head,payload,sig,_ref3;_ref3=token.split("."),head=_ref3[0],payload=_ref3[1],sig=_ref3[2];return JSON.parse(base64UrlDecode(payload))};Annotator.Plugin.Auth=function(_super){__extends(Auth,_super);Auth.prototype.options={token:null,tokenUrl:"/auth/token",autoFetch:true,requestMethod:"GET",requestData:null,unauthorizedCallback:null};function Auth(element,options){Auth.__super__.constructor.apply(this,arguments);this.waitingForToken=[];if(this.options.token){this.setToken(this.options.token)}else{this.requestToken()}}Auth.prototype.requestToken=function(){var _this=this;this.requestInProgress=true;return $.ajax({url:this.options.tokenUrl,dataType:"text",data:this.options.requestData,type:this.options.requestMethod,xhrFields:{withCredentials:true}}).done(function(data,status,xhr){return _this.setToken(data)}).fail(function(xhr,status,err){var callback,msg;if(xhr.status===401){callback=_this.options.unauthorizedCallback;if(callback!=null&&callback(_this)){_this.retryTimeout=setTimeout(function(){return _this.requestToken()},1e3);return}}msg=Annotator._t("Couldn't get auth token:");console.error(""+msg+" "+err,xhr);return Annotator.showNotification(""+msg+" "+xhr.responseText,Annotator.Notification.ERROR)}).always(function(){return _this.requestInProgress=false})};Auth.prototype.setToken=function(token){var _results,_this=this;this.token=token;this._unsafeToken=parseToken(token);if(this.haveValidToken()){if(this.options.autoFetch){this.refreshTimeout=setTimeout(function(){return _this.requestToken()},(this.timeToExpiry()-2)*1e3)}this.updateHeaders();_results=[];while(this.waitingForToken.length>0){_results.push(this.waitingForToken.pop()(this._unsafeToken))}return _results}else{console.warn(Annotator._t("Didn't get a valid token."));if(this.options.autoFetch){console.warn(Annotator._t("Getting a new token in 10s."));return setTimeout(function(){return _this.requestToken()},10*1e3)}}};Auth.prototype.haveValidToken=function(){var allFields;allFields=this._unsafeToken&&this._unsafeToken.issuedAt&&this._unsafeToken.ttl&&this._unsafeToken.consumerKey;if(allFields&&this.timeToExpiry()>0){return true}else{return false}};Auth.prototype.timeToExpiry=function(){var expiry,issue,now,timeToExpiry;now=(new Date).getTime()/1e3;issue=createDateFromISO8601(this._unsafeToken.issuedAt).getTime()/1e3;expiry=issue+this._unsafeToken.ttl;timeToExpiry=expiry-now;if(timeToExpiry>0){return timeToExpiry}else{return 0}};Auth.prototype.updateHeaders=function(){var current;current=this.element.data("annotator:headers");return this.element.data("annotator:headers",$.extend(current,{"x-annotator-auth-token":this.token}))};Auth.prototype.withToken=function(callback){if(callback==null){return}if(this.haveValidToken()){return callback(this._unsafeToken)}else{this.waitingForToken.push(callback);if(!this.requestInProgress){return this.requestToken()}}};return Auth}(Annotator.Plugin);Annotator.Plugin.Store=function(_super){__extends(Store,_super);Store.prototype.events={annotationCreated:"annotationCreated",annotationDeleted:"annotationDeleted",annotationUpdated:"annotationUpdated"};Store.prototype.options={annotationData:{},emulateHTTP:false,loadFromSearch:false,prefix:"/store",urls:{create:"/annotations",read:"/annotations/:id",update:"/annotations/:id",destroy:"/annotations/:id",search:"/search"}};function Store(element,options){this._onError=__bind(this._onError,this);this._onLoadAnnotationsFromSearch=__bind(this._onLoadAnnotationsFromSearch,this);this._onLoadAnnotations=__bind(this._onLoadAnnotations,this);this._getAnnotations=__bind(this._getAnnotations,this);Store.__super__.constructor.apply(this,arguments);this.annotations=[]}Store.prototype.pluginInit=function(){if(!Annotator.supported()){return}if(this.annotator.plugins.Auth){return this.annotator.plugins.Auth.withToken(this._getAnnotations)}else{return this._getAnnotations()}};Store.prototype._getAnnotations=function(){if(this.options.loadFromSearch){return this.loadAnnotationsFromSearch(this.options.loadFromSearch)}else{return this.loadAnnotations()}};Store.prototype.annotationCreated=function(annotation){var _this=this;if(__indexOf.call(this.annotations,annotation)<0){this.registerAnnotation(annotation);return this._apiRequest("create",annotation,function(data){if(data.id==null){console.warn(Annotator._t("Warning: No ID returned from server for annotation "),annotation)}return _this.updateAnnotation(annotation,data)})}else{return this.updateAnnotation(annotation,{})}};Store.prototype.annotationUpdated=function(annotation){var _this=this;if(__indexOf.call(this.annotations,annotation)>=0){return this._apiRequest("update",annotation,function(data){return _this.updateAnnotation(annotation,data)})}};Store.prototype.annotationDeleted=function(annotation){var _this=this;if(__indexOf.call(this.annotations,annotation)>=0){return this._apiRequest("destroy",annotation,function(){return _this.unregisterAnnotation(annotation)})}};Store.prototype.registerAnnotation=function(annotation){return this.annotations.push(annotation)};Store.prototype.unregisterAnnotation=function(annotation){return this.annotations.splice(this.annotations.indexOf(annotation),1)};Store.prototype.updateAnnotation=function(annotation,data){if(__indexOf.call(this.annotations,annotation)<0){console.error(Annotator._t("Trying to update unregistered annotation!"))}else{$.extend(annotation,data)}return $(annotation.highlights).data("annotation",annotation)};Store.prototype.loadAnnotations=function(){return this._apiRequest("read",null,this._onLoadAnnotations)};Store.prototype._onLoadAnnotations=function(data){var a,annotation,annotationMap,newData,_k,_l,_len2,_len3,_ref3;if(data==null){data=[]}annotationMap={};_ref3=this.annotations;for(_k=0,_len2=_ref3.length;_k<_len2;_k++){a=_ref3[_k];annotationMap[a.id]=a}newData=[];for(_l=0,_len3=data.length;_l<_len3;_l++){a=data[_l];if(annotationMap[a.id]){annotation=annotationMap[a.id];this.updateAnnotation(annotation,a)}else{newData.push(a)}}this.annotations=this.annotations.concat(newData);return this.annotator.loadAnnotations(newData.slice())};Store.prototype.loadAnnotationsFromSearch=function(searchOptions){return this._apiRequest("search",searchOptions,this._onLoadAnnotationsFromSearch)};Store.prototype._onLoadAnnotationsFromSearch=function(data){if(data==null){data={}}return this._onLoadAnnotations(data.rows||[])};Store.prototype.dumpAnnotations=function(){var ann,_k,_len2,_ref3,_results;_ref3=this.annotations;_results=[];for(_k=0,_len2=_ref3.length;_k<_len2;_k++){ann=_ref3[_k];_results.push(JSON.parse(this._dataFor(ann)))}return _results};Store.prototype._apiRequest=function(action,obj,onSuccess){var id,options,request,url;id=obj&&obj.id;url=this._urlFor(action,id);options=this._apiRequestOptions(action,obj,onSuccess);request=$.ajax(url,options);request._id=id;request._action=action;return request};Store.prototype._apiRequestOptions=function(action,obj,onSuccess){var data,method,opts;method=this._methodFor(action);opts={type:method,headers:this.element.data("annotator:headers"),dataType:"json",success:onSuccess||function(){},error:this._onError};if(this.options.emulateHTTP&&(method==="PUT"||method==="DELETE")){opts.headers=$.extend(opts.headers,{"X-HTTP-Method-Override":method});opts.type="POST"}if(action==="search"){opts=$.extend(opts,{data:obj});return opts}data=obj&&this._dataFor(obj);if(this.options.emulateJSON){opts.data={json:data};if(this.options.emulateHTTP){opts.data._method=method}return opts}opts=$.extend(opts,{data:data,contentType:"application/json; charset=utf-8"});return opts};Store.prototype._urlFor=function(action,id){var url;url=this.options.prefix!=null?this.options.prefix:"";url+=this.options.urls[action];url=url.replace(/\/:id/,id!=null?"/"+id:"");url=url.replace(/:id/,id!=null?id:"");return url};Store.prototype._methodFor=function(action){var table;table={create:"POST",read:"GET",update:"PUT",destroy:"DELETE",search:"GET"};return table[action]};Store.prototype._dataFor=function(annotation){var data,highlights;highlights=annotation.highlights;delete annotation.highlights;$.extend(annotation,this.options.annotationData);data=JSON.stringify(annotation);if(highlights){annotation.highlights=highlights}return data};Store.prototype._onError=function(xhr){var action,message;action=xhr._action;message=Annotator._t("Sorry we could not ")+action+Annotator._t(" this annotation");if(xhr._action==="search"){message=Annotator._t("Sorry we could not search the store for annotations")}else if(xhr._action==="read"&&!xhr._id){message=Annotator._t("Sorry we could not ")+action+Annotator._t(" the annotations from the store")}switch(xhr.status){case 401:message=Annotator._t("Sorry you are not allowed to ")+action+Annotator._t(" this annotation");break;case 404:message=Annotator._t("Sorry we could not connect to the annotations store");break;case 500:message=Annotator._t("Sorry something went wrong with the annotation store")}Annotator.showNotification(message,Annotator.Notification.ERROR);return console.error(Annotator._t("API request failed:")+(" '"+xhr.status+"'"))};return Store}(Annotator.Plugin);Annotator.Plugin.Permissions=function(_super){__extends(Permissions,_super);Permissions.prototype.events={beforeAnnotationCreated:"addFieldsToAnnotation"};Permissions.prototype.options={showViewPermissionsCheckbox:true,showEditPermissionsCheckbox:true,userId:function(user){return user},userString:function(user){return user},userAuthorize:function(action,annotation,user){var token,tokens,_k,_len2;if(annotation.permissions){tokens=annotation.permissions[action]||[];if(tokens.length===0){return true}for(_k=0,_len2=tokens.length;_k<_len2;_k++){token=tokens[_k];if(this.userId(user)===token){return true}}return false}else if(annotation.user){if(user){return this.userId(user)===this.userId(annotation.user)}else{return false}}return true},user:"",permissions:{read:[],update:[],"delete":[],admin:[]}};function Permissions(element,options){this._setAuthFromToken=__bind(this._setAuthFromToken,this);this.updateViewer=__bind(this.updateViewer,this);this.updateAnnotationPermissions=__bind(this.updateAnnotationPermissions,this);this.updatePermissionsField=__bind(this.updatePermissionsField,this);this.addFieldsToAnnotation=__bind(this.addFieldsToAnnotation,this);Permissions.__super__.constructor.apply(this,arguments);if(this.options.user){this.setUser(this.options.user);delete this.options.user}}Permissions.prototype.pluginInit=function(){var createCallback,self,_this=this;if(!Annotator.supported()){return}self=this;createCallback=function(method,type){return function(field,annotation){return self[method].call(self,type,field,annotation)}};if(!this.user&&this.annotator.plugins.Auth){this.annotator.plugins.Auth.withToken(this._setAuthFromToken)}if(this.options.showViewPermissionsCheckbox===true){this.annotator.editor.addField({type:"checkbox",label:Annotator._t("Allow anyone to <strong>view</strong> this annotation"),load:createCallback("updatePermissionsField","read"),submit:createCallback("updateAnnotationPermissions","read")})}if(this.options.showEditPermissionsCheckbox===true){this.annotator.editor.addField({type:"checkbox",label:Annotator._t("Allow anyone to <strong>edit</strong> this annotation"),load:createCallback("updatePermissionsField","update"),submit:createCallback("updateAnnotationPermissions","update")})}this.annotator.viewer.addField({load:this.updateViewer});if(this.annotator.plugins.Filter){return this.annotator.plugins.Filter.addFilter({label:Annotator._t("User"),property:"user",isFiltered:function(input,user){var keyword,_k,_len2,_ref3;user=_this.options.userString(user);if(!(input&&user)){return false}_ref3=input.split(/\s*/);for(_k=0,_len2=_ref3.length;_k<_len2;_k++){keyword=_ref3[_k];if(user.indexOf(keyword)===-1){return false}}return true}})}};Permissions.prototype.setUser=function(user){return this.user=user};Permissions.prototype.addFieldsToAnnotation=function(annotation){if(annotation){annotation.permissions=$.extend(true,{},this.options.permissions);if(this.user){return annotation.user=this.user}}};Permissions.prototype.authorize=function(action,annotation,user){if(user===void 0){user=this.user}if(this.options.userAuthorize){return this.options.userAuthorize.call(this.options,action,annotation,user)}else{return true}};Permissions.prototype.updatePermissionsField=function(action,field,annotation){var input;field=$(field).show();input=field.find("input").removeAttr("disabled");if(!this.authorize("admin",annotation)){field.hide()}if(this.authorize(action,annotation||{},null)){return input.attr("checked","checked")}else{return input.removeAttr("checked")}};Permissions.prototype.updateAnnotationPermissions=function(type,field,annotation){var dataKey;if(!annotation.permissions){annotation.permissions=$.extend(true,{},this.options.permissions)}dataKey=type+"-permissions";if($(field).find("input").is(":checked")){return annotation.permissions[type]=[]}else{return annotation.permissions[type]=[this.options.userId(this.user)]}};Permissions.prototype.updateViewer=function(field,annotation,controls){var user,username;field=$(field);username=this.options.userString(annotation.user);if(annotation.user&&username&&typeof username==="string"){user=Annotator.Util.escape(this.options.userString(annotation.user));field.html(user).addClass("annotator-user")}else{field.remove()}if(controls){if(!this.authorize("update",annotation)){controls.hideEdit()}if(!this.authorize("delete",annotation)){return controls.hideDelete()}}};Permissions.prototype._setAuthFromToken=function(token){return this.setUser(token.userId)};return Permissions}(Annotator.Plugin);Annotator.Plugin.Filter=function(_super){__extends(Filter,_super);Filter.prototype.events={".annotator-filter-property input focus":"_onFilterFocus",".annotator-filter-property input blur":"_onFilterBlur",".annotator-filter-property input keyup":"_onFilterKeyup",".annotator-filter-previous click":"_onPreviousClick",".annotator-filter-next click":"_onNextClick",".annotator-filter-clear click":"_onClearClick"};Filter.prototype.classes={active:"annotator-filter-active",hl:{hide:"annotator-hl-filtered",active:"annotator-hl-active"}};Filter.prototype.html={element:'<div class="annotator-filter">\n <strong>'+Annotator._t("Navigate:")+'</strong>\n<span class="annotator-filter-navigation">\n <button class="annotator-filter-previous">'+Annotator._t("Previous")+'</button>\n<button class="annotator-filter-next">'+Annotator._t("Next")+"</button>\n</span>\n<strong>"+Annotator._t("Filter by:")+"</strong>\n</div>",filter:'<span class="annotator-filter-property">\n <label></label>\n <input/>\n <button class="annotator-filter-clear">'+Annotator._t("Clear")+"</button>\n</span>"};Filter.prototype.options={appendTo:"body",filters:[],addAnnotationFilter:true,isFiltered:function(input,property){var keyword,_k,_len2,_ref3;if(!(input&&property)){return false}_ref3=input.split(/\s+/);for(_k=0,_len2=_ref3.length;_k<_len2;_k++){keyword=_ref3[_k];if(property.indexOf(keyword)===-1){return false}}return true}};function Filter(element,options){this._onPreviousClick=__bind(this._onPreviousClick,this);this._onNextClick=__bind(this._onNextClick,this);this._onFilterKeyup=__bind(this._onFilterKeyup,this);this._onFilterBlur=__bind(this._onFilterBlur,this);this._onFilterFocus=__bind(this._onFilterFocus,this);this.updateHighlights=__bind(this.updateHighlights,this);var _base;element=$(this.html.element).appendTo((options!=null?options.appendTo:void 0)||this.options.appendTo);Filter.__super__.constructor.call(this,element,options);(_base=this.options).filters||(_base.filters=[]);this.filter=$(this.html.filter);this.filters=[];this.current=0}Filter.prototype.pluginInit=function(){var filter,_k,_len2,_ref3;_ref3=this.options.filters;for(_k=0,_len2=_ref3.length;_k<_len2;_k++){filter=_ref3[_k];this.addFilter(filter)}this.updateHighlights();this._setupListeners()._insertSpacer();if(this.options.addAnnotationFilter===true){return this.addFilter({label:Annotator._t("Annotation"),property:"text"})}};Filter.prototype.destroy=function(){var currentMargin,html;Filter.__super__.destroy.apply(this,arguments);html=$("html");currentMargin=parseInt(html.css("padding-top"),10)||0;html.css("padding-top",currentMargin-this.element.outerHeight());return this.element.remove()};Filter.prototype._insertSpacer=function(){var currentMargin,html;html=$("html");currentMargin=parseInt(html.css("padding-top"),10)||0;html.css("padding-top",currentMargin+this.element.outerHeight());return this};Filter.prototype._setupListeners=function(){var event,events,_k,_len2;events=["annotationsLoaded","annotationCreated","annotationUpdated","annotationDeleted"];for(_k=0,_len2=events.length;_k<_len2;_k++){event=events[_k];this.annotator.subscribe(event,this.updateHighlights)}return this};Filter.prototype.addFilter=function(options){var f,filter;filter=$.extend({label:"",property:"",isFiltered:this.options.isFiltered},options);if(!function(){var _k,_len2,_ref3,_results;_ref3=this.filters;_results=[];for(_k=0,_len2=_ref3.length;_k<_len2;_k++){f=_ref3[_k];if(f.property===filter.property){_results.push(f) +}}return _results}.call(this).length){filter.id="annotator-filter-"+filter.property;filter.annotations=[];filter.element=this.filter.clone().appendTo(this.element);filter.element.find("label").html(filter.label).attr("for",filter.id);filter.element.find("input").attr({id:filter.id,placeholder:Annotator._t("Filter by ")+filter.label+"…"});filter.element.find("button").hide();filter.element.data("filter",filter);this.filters.push(filter)}return this};Filter.prototype.updateFilter=function(filter){var annotation,annotations,input,property,_k,_len2,_ref3;filter.annotations=[];this.updateHighlights();this.resetHighlights();input=$.trim(filter.element.find("input").val());if(input){annotations=this.highlights.map(function(){return $(this).data("annotation")});_ref3=$.makeArray(annotations);for(_k=0,_len2=_ref3.length;_k<_len2;_k++){annotation=_ref3[_k];property=annotation[filter.property];if(filter.isFiltered(input,property)){filter.annotations.push(annotation)}}return this.filterHighlights()}};Filter.prototype.updateHighlights=function(){this.highlights=this.annotator.element.find(".annotator-hl:visible");return this.filtered=this.highlights.not(this.classes.hl.hide)};Filter.prototype.filterHighlights=function(){var activeFilters,annotation,annotations,filtered,highlights,index,uniques,_k,_len2,_ref3;activeFilters=$.grep(this.filters,function(filter){return!!filter.annotations.length});filtered=((_ref3=activeFilters[0])!=null?_ref3.annotations:void 0)||[];if(activeFilters.length>1){annotations=[];$.each(activeFilters,function(){return $.merge(annotations,this.annotations)});uniques=[];filtered=[];$.each(annotations,function(){if($.inArray(this,uniques)===-1){return uniques.push(this)}else{return filtered.push(this)}})}highlights=this.highlights;for(index=_k=0,_len2=filtered.length;_k<_len2;index=++_k){annotation=filtered[index];highlights=highlights.not(annotation.highlights)}highlights.addClass(this.classes.hl.hide);this.filtered=this.highlights.not(this.classes.hl.hide);return this};Filter.prototype.resetHighlights=function(){this.highlights.removeClass(this.classes.hl.hide);this.filtered=this.highlights;return this};Filter.prototype._onFilterFocus=function(event){var input;input=$(event.target);input.parent().addClass(this.classes.active);return input.next("button").show()};Filter.prototype._onFilterBlur=function(event){var input;if(!event.target.value){input=$(event.target);input.parent().removeClass(this.classes.active);return input.next("button").hide()}};Filter.prototype._onFilterKeyup=function(event){var filter;filter=$(event.target).parent().data("filter");if(filter){return this.updateFilter(filter)}};Filter.prototype._findNextHighlight=function(previous){var active,annotation,current,index,next,offset,operator,resetOffset;if(!this.highlights.length){return this}offset=previous?0:-1;resetOffset=previous?-1:0;operator=previous?"lt":"gt";active=this.highlights.not("."+this.classes.hl.hide);current=active.filter("."+this.classes.hl.active);if(!current.length){current=active.eq(offset)}annotation=current.data("annotation");index=active.index(current[0]);next=active.filter(":"+operator+"("+index+")").not(annotation.highlights).eq(resetOffset);if(!next.length){next=active.eq(resetOffset)}return this._scrollToHighlight(next.data("annotation").highlights)};Filter.prototype._onNextClick=function(event){return this._findNextHighlight()};Filter.prototype._onPreviousClick=function(event){return this._findNextHighlight(true)};Filter.prototype._scrollToHighlight=function(highlight){highlight=$(highlight);this.highlights.removeClass(this.classes.hl.active);highlight.addClass(this.classes.hl.active);return $("html, body").animate({scrollTop:highlight.offset().top-(this.element.height()+20)},150)};Filter.prototype._onClearClick=function(event){return $(event.target).prev("input").val("").keyup().blur()};return Filter}(Annotator.Plugin);Annotator.Plugin.Markdown=function(_super){__extends(Markdown,_super);Markdown.prototype.events={annotationViewerTextField:"updateTextField"};function Markdown(element,options){this.updateTextField=__bind(this.updateTextField,this);if((typeof Showdown!=="undefined"&&Showdown!==null?Showdown.converter:void 0)!=null){Markdown.__super__.constructor.apply(this,arguments);this.converter=new Showdown.converter}else{console.error(Annotator._t("To use the Markdown plugin, you must include Showdown into the page first."))}}Markdown.prototype.updateTextField=function(field,annotation){var text;text=Annotator.Util.escape(annotation.text||"");return $(field).html(this.convert(text))};Markdown.prototype.convert=function(text){return this.converter.makeHtml(text)};return Markdown}(Annotator.Plugin);Annotator.Plugin.Tags=function(_super){__extends(Tags,_super);function Tags(){this.setAnnotationTags=__bind(this.setAnnotationTags,this);this.updateField=__bind(this.updateField,this);_ref3=Tags.__super__.constructor.apply(this,arguments);return _ref3}Tags.prototype.options={parseTags:function(string){var tags;string=$.trim(string);tags=[];if(string){tags=string.split(/\s+/)}return tags},stringifyTags:function(array){return array.join(" ")}};Tags.prototype.field=null;Tags.prototype.input=null;Tags.prototype.pluginInit=function(){if(!Annotator.supported()){return}this.field=this.annotator.editor.addField({label:Annotator._t("Add some tags here")+"…",load:this.updateField,submit:this.setAnnotationTags});this.annotator.viewer.addField({load:this.updateViewer});if(this.annotator.plugins.Filter){this.annotator.plugins.Filter.addFilter({label:Annotator._t("Tag"),property:"tags",isFiltered:Annotator.Plugin.Tags.filterCallback})}return this.input=$(this.field).find(":input")};Tags.prototype.parseTags=function(string){return this.options.parseTags(string)};Tags.prototype.stringifyTags=function(array){return this.options.stringifyTags(array)};Tags.prototype.updateField=function(field,annotation){var value;value="";if(annotation.tags){value=this.stringifyTags(annotation.tags)}return this.input.val(value)};Tags.prototype.setAnnotationTags=function(field,annotation){return annotation.tags=this.parseTags(this.input.val())};Tags.prototype.updateViewer=function(field,annotation){field=$(field);if(annotation.tags&&$.isArray(annotation.tags)&&annotation.tags.length){return field.addClass("annotator-tags").html(function(){var string;return string=$.map(annotation.tags,function(tag){return'<span class="annotator-tag">'+Annotator.Util.escape(tag)+"</span>"}).join(" ")})}else{return field.remove()}};return Tags}(Annotator.Plugin);Annotator.Plugin.Tags.filterCallback=function(input,tags){var keyword,keywords,matches,tag,_k,_l,_len2,_len3;if(tags==null){tags=[]}matches=0;keywords=[];if(input){keywords=input.split(/\s+/g);for(_k=0,_len2=keywords.length;_k<_len2;_k++){keyword=keywords[_k];if(tags.length){for(_l=0,_len3=tags.length;_l<_len3;_l++){tag=tags[_l];if(tag.indexOf(keyword)!==-1){matches+=1}}}}}return matches===keywords.length};Annotator.Plugin.DigilibIntegrator=function(_super){__extends(DigilibIntegrator,_super);function DigilibIntegrator(){_ref4=DigilibIntegrator.__super__.constructor.apply(this,arguments);return _ref4}DigilibIntegrator.prototype.events={annotationDeleted:"annotationDeleted"};DigilibIntegrator.prototype.options={hooks:null};DigilibIntegrator.prototype.pluginInit=function(){this.annotator.digilib=this.options.hooks;this.annotator.setupRangeAnnotation=this.annotator.setupAnnotation;this.annotator.setupAnnotation=this._setupAnnotation;return this};DigilibIntegrator.prototype._setupAnnotation=function(annotation,fireEvents){if(fireEvents==null){fireEvents=true}if(this.selectedShapes||annotation.shapes!=null||this.selectedAreas!=null||annotation.areas!=null){annotation.shapes||(annotation.shapes=this.selectedShapes);annotation.areas||(annotation.areas=this.selectedAreas);annotation.highlights=[];annotation.ranges=[];this.digilib.setupAnnotation(annotation);if(fireEvents){this.publish("annotationCreated",[annotation])}return annotation}else{return this.setupRangeAnnotation.apply(this,arguments)}};DigilibIntegrator.prototype.annotationDeleted=function(annotation){return this.options.hooks.annotationDeleted(annotation)};return DigilibIntegrator}(Annotator.Plugin)}.call(this); +// +//# sourceMappingURL=annotator-dl.min.map \ No newline at end of file
--- a/webapp/src/main/webapp/jquery/digilib-ann.html Fri Jan 16 18:20:15 2015 +0100 +++ b/webapp/src/main/webapp/jquery/digilib-ann.html Fri Jan 16 20:57:20 2015 +0100 @@ -13,7 +13,7 @@ <script type="text/javascript" src="json2.js"></script> <script type="text/javascript" src="jquery.js"></script> - <script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script> + <!-- <script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script> --> <script type="text/javascript" src="jquery.cookie.js"></script> <script type="text/javascript" src="jquery.digilib.js"></script> <link rel="stylesheet" type="text/css" href="jquery.digilib.css" />
--- a/webapp/src/main/webapp/jquery/jquery.digilib.annotator.js Fri Jan 16 18:20:15 2015 +0100 +++ b/webapp/src/main/webapp/jquery/jquery.digilib.annotator.js Fri Jan 16 20:57:20 2015 +0100 @@ -222,7 +222,7 @@ /** * add a mark-annotation where clicked. */ - var setAnnotationMark = function(data) { + var setAnnotationMark = function (data) { var $scaler = data.$scaler; // start event capturing $scaler.one('mousedown.dlSetAnnotationMark', function (evt) { @@ -236,6 +236,23 @@ annotator.selectedShapes = [shape]; // create and edit new annotation var annotation = annotator.createAnnotation(); + var cleanup = function () { + annotator.unsubscribe('annotationEditorSubmit', save); + annotator.unsubscribe('annotationEditorHidden', cancel); + }; + var save = function () { + console.log("annotation save.") + cleanup(); + annotator.setupAnnotation(annotation); + // Fire annotationCreated events so that plugins can react to them + annotator.publish('annotationCreated', [annotation]); + }; + var cancel = function () { + console.log("annotation cancel.") + cleanup(); + }; + annotator.subscribe('annotationEditorSubmit', save); + annotator.subscribe('annotationEditorHidden', cancel); annotator.showEditor(annotation, mpos.getAsCss()); return false; }); @@ -244,7 +261,7 @@ /** * Add a region-annotation where clicked. */ - var setAnnotationRegion = function(data) { + var setAnnotationRegion = function (data) { var annotator = data.annotator; fn.defineArea(data, function (data, rect) { if (rect == null) return; @@ -257,6 +274,23 @@ var pos = rect.getPt1(); var mpos = data.imgTrafo.transform(pos); var annotation = annotator.createAnnotation(); + var cleanup = function () { + annotator.unsubscribe('annotationEditorSubmit', save); + annotator.unsubscribe('annotationEditorHidden', cancel); + }; + var save = function () { + console.log("annotation save.") + cleanup(); + annotator.setupAnnotation(annotation); + // Fire annotationCreated events so that plugins can react to them + annotator.publish('annotationCreated', [annotation]); + }; + var cancel = function () { + console.log("annotation cancel.") + cleanup(); + }; + annotator.subscribe('annotationEditorSubmit', save); + annotator.subscribe('annotationEditorHidden', cancel); annotator.showEditor(annotation, mpos.getAsCss()); }); };