\n";
},
"@display/left-margin": function (state, str) {
return "\n
" + str + "
";
},
"@display/right-inline": function (state, str) {
return "
" + str + "
\n ";
},
"@display/indent": function (state, str) {
return "
" + str + "
\n ";
},
"@showid/true": function (state, str, cslid) {
if (!state.tmp.just_looking && ! state.tmp.suppress_decorations) {
if (cslid) {
return "" + str + "";
} else if ("string" === typeof str) {
var prePunct = "";
if (str) {
var m = str.match(CSL.VARIABLE_WRAPPER_PREPUNCT_REX);
prePunct = m[1];
str = m[2];
}
var postPunct = "";
if (str && CSL.SWAPPING_PUNCTUATION.indexOf(str.slice(-1)) > -1) {
postPunct = str.slice(-1);
str = str.slice(0,-1);
}
return state.sys.variableWrapper(this.params, prePunct, str, postPunct);
} else {
return str;
}
} else {
return str;
}
},
"@URL/true": function (state, str) {
return "" + str + "";
},
"@DOI/true": function (state, str) {
return "" + str + "";
}
};
CSL.Output.Formats.prototype.text = {
"text_escape": function (text) {
if (!text) {
text = "";
}
return text;
},
"bibstart": "",
"bibend": "",
"@font-style/italic": false,
"@font-style/oblique": false,
"@font-style/normal": false,
"@font-variant/small-caps": false,
"@passthrough/true": CSL.Output.Formatters.passthrough,
"@font-variant/normal": false,
"@font-weight/bold": false,
"@font-weight/normal": false,
"@font-weight/light": false,
"@text-decoration/none": false,
"@text-decoration/underline": false,
"@vertical-align/baseline": false,
"@vertical-align/sup": false,
"@vertical-align/sub": false,
"@strip-periods/true": CSL.Output.Formatters.passthrough,
"@strip-periods/false": CSL.Output.Formatters.passthrough,
"@quotes/true": function (state, str) {
if ("undefined" === typeof str) {
return state.getTerm("open-quote");
}
return state.getTerm("open-quote") + str + state.getTerm("close-quote");
},
"@quotes/inner": function (state, str) {
if ("undefined" === typeof str) {
return "\u2019";
}
return state.getTerm("open-inner-quote") + str + state.getTerm("close-inner-quote");
},
"@quotes/false": false,
"@cite/entry": function (state, str) {
return state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);
},
"@bibliography/entry": function (state, str) {
return str+"\n";
},
"@display/block": function (state, str) {
return "\n"+str;
},
"@display/left-margin": function (state, str) {
return str;
},
"@display/right-inline": function (state, str) {
return str;
},
"@display/indent": function (state, str) {
return "\n "+str;
},
"@showid/true": function (state, str, cslid) {
return str;
},
"@URL/true": function (state, str) {
return str;
},
"@DOI/true": function (state, str) {
return str;
}
};
CSL.Output.Formats.prototype.rtf = {
"text_escape": function (text) {
if (!text) {
text = "";
}
return text
.replace(/([\\{}])/g, "\\$1", "g")
.replace(CSL.SUPERSCRIPTS_REGEXP,
function(aChar) {
return "\\super " + CSL.SUPERSCRIPTS[aChar] + "\\nosupersub{}";
})
.replace(/[\u007F-\uFFFF]/g,
function(aChar) { return "\\uc0\\u"+aChar.charCodeAt(0).toString()+"{}"; })
.replace("\t", "\\tab{}", "g");
},
"@passthrough/true": CSL.Output.Formatters.passthrough,
"@font-style/italic":"\\i %%STRING%%\\i0{}",
"@font-style/normal":"\\i0{}%%STRING%%\\i{}",
"@font-style/oblique":"\\i %%STRING%%\\i0{}",
"@font-variant/small-caps":"\\scaps %%STRING%%\\scaps0{}",
"@font-variant/normal":"\\scaps0{}%%STRING%%\\scaps{}",
"@font-weight/bold":"\\b %%STRING%%\\b0{}",
"@font-weight/normal":"\\b0{}%%STRING%%\\b{}",
"@font-weight/light":false,
"@text-decoration/none":false,
"@text-decoration/underline":"\\ul %%STRING%%\\ul0{}",
"@vertical-align/baseline":false,
"@vertical-align/sup":"\\super %%STRING%%\\nosupersub{}",
"@vertical-align/sub":"\\sub %%STRING%%\\nosupersub{}",
"@strip-periods/true": CSL.Output.Formatters.passthrough,
"@strip-periods/false": CSL.Output.Formatters.passthrough,
"@quotes/true": function (state, str) {
if ("undefined" === typeof str) {
return CSL.Output.Formats.rtf.text_escape(state.getTerm("open-quote"));
}
return CSL.Output.Formats.rtf.text_escape(state.getTerm("open-quote")) + str + CSL.Output.Formats.rtf.text_escape(state.getTerm("close-quote"));
},
"@quotes/inner": function (state, str) {
if ("undefined" === typeof str) {
return CSL.Output.Formats.rtf.text_escape("\u2019");
}
return CSL.Output.Formats.rtf.text_escape(state.getTerm("open-inner-quote")) + str + CSL.Output.Formats.rtf.text_escape(state.getTerm("close-inner-quote"));
},
"@quotes/false": false,
"bibstart":"{\\rtf ",
"bibend":"}",
"@display/block": "\\line{}%%STRING%%\\line\r\n",
"@cite/entry": function (state, str) {
return str;
},
"@cite/entry": function (state, str) {
return state.sys.wrapCitationEntry(str, this.item_id, this.locator_txt, this.suffix_txt);
},
"@bibliography/entry": function(state,str){
return str;
},
"@display/left-margin": function(state,str){
return str+"\\tab ";
},
"@display/right-inline": function (state, str) {
return str+"\n";
},
"@display/indent": function (state, str) {
return "\n\\tab "+str;
},
"@showid/true": function (state, str, cslid) {
if (!state.tmp.just_looking && ! state.tmp.suppress_decorations) {
var prePunct = "";
if (str) {
var m = str.match(CSL.VARIABLE_WRAPPER_PREPUNCT_REX);
prePunct = m[1];
str = m[2];
}
var postPunct = "";
if (str && CSL.SWAPPING_PUNCTUATION.indexOf(str.slice(-1)) > -1) {
postPunct = str.slice(-1);
str = str.slice(0,-1);
}
return state.sys.variableWrapper(this.params, prePunct, str, postPunct);
} else {
return str;
}
},
"@URL/true": function (state, str) {
return str;
},
"@DOI/true": function (state, str) {
return str;
}
};
CSL.Output.Formats = new CSL.Output.Formats();
CSL.Registry = function (state) {
var pos, len, ret, i, ilen;
this.debug = false;
this.state = state;
this.registry = {};
this.reflist = [];
this.namereg = new CSL.Registry.NameReg(state);
this.citationreg = new CSL.Registry.CitationReg(state);
this.authorstrings = {};
this.mylist = [];
this.myhash = {};
this.deletes = [];
this.inserts = [];
this.uncited = {};
this.refreshes = {};
this.akeys = {};
this.oldseq = {};
this.return_data = {};
this.ambigcites = {};
this.ambigresets = {};
this.sorter = new CSL.Registry.Comparifier(state, "bibliography_sort");
this.getSortedIds = function () {
ret = [];
for (i = 0, ilen = this.reflist.length; i < ilen; i += 1) {
ret.push("" + this.reflist[i].id);
}
return ret;
};
this.getSortedRegistryItems = function () {
ret = [];
for (i = 0, ilen = this.reflist.length; i < ilen; i += 1) {
ret.push(this.reflist[i]);
}
return ret;
};
};
CSL.Registry.prototype.init = function (itemIDs, uncited_flag) {
var i, ilen;
this.oldseq = {};
if (uncited_flag) {
this.uncited = {};
for (var i=0,ilen=itemIDs.length;i-1; i += -1) {
if (myhash[itemIDs[i]]) {
itemIDs = itemIDs.slice(0, i).concat(itemIDs.slice(i + 1));
} else {
myhash[itemIDs[i]] = true;
}
}
this.mylist = [];
for (var i=0,ilen=itemIDs.length;i-1;i+=-1) {
if (this.citationreg.citationsByItemId) {
if (!this.citationreg.citationsByItemId[this.mylist[i]] && !myhash[this.mylist[i]]) {
delete this.myhash[this.mylist[i]];
this.mylist = this.mylist.slice(0,i).concat(this.mylist.slice(i+1));
}
}
}
this.dodeletes(this.myhash);
};
CSL.Registry.prototype.dodeletes = function (myhash) {
var otheritems, key, ambig, pos, len, items, kkey, mypos, id;
if ("string" === typeof myhash) {
myhash = {};
myhash[myhash] = true;
}
for (key in this.registry) {
if (!myhash[key]) {
if (this.uncited[key]) {
continue;
}
otheritems = this.namereg.delitems(key);
for (kkey in otheritems) {
this.refreshes[kkey] = true;
}
ambig = this.registry[key].ambig;
mypos = this.ambigcites[ambig].indexOf(key);
if (mypos > -1) {
items = this.ambigcites[ambig].slice();
this.ambigcites[ambig] = items.slice(0, mypos).concat(items.slice(mypos+1, items.length));
this.ambigresets[ambig] = this.ambigcites[ambig].length;
}
len = this.ambigcites[ambig].length;
for (pos = 0; pos < len; pos += 1) {
id = "" + this.ambigcites[ambig][pos];
this.refreshes[id] = true;
}
if (this.registry[key].siblings) {
if (this.registry[key].siblings.length == 1) {
var loneSiblingID = this.registry[key].siblings[0];
this.registry[loneSiblingID].master = true;
this.registry[loneSiblingID].siblings.pop();
this.registry[loneSiblingID].parallel = false;
} else if (this.registry[key].siblings.length > 1) {
var removeIDs = [key];
if (this.registry[key].master) {
var newmasterID = this.registry[key].siblings[0];
var newmaster = this.registry[newmasterID];
newmaster.master = true;
newmaster.parallel = false;
removeIDs.push(newmasterID);
for (var k = 0, klen = this.registry[key].siblings.length; k < klen; k += 1) {
this.registry[this.registry[key].siblings[k]].parallel = newmasterID;
}
}
var buffer = [];
for (var k = this.registry[key].siblings.length - 1; k > -1; k += -1) {
var siblingID = this.registry[key].siblings.pop();
if (removeIDs.indexOf(siblingID) === -1) {
buffer.push(siblingID)
}
}
for (var k = buffer.length - 1; k > -1; k += -1) {
this.registry[key].siblings.push(buffer[k]);
}
}
}
delete this.registry[key];
this.return_data.bibchange = true;
}
}
};
CSL.Registry.prototype.doinserts = function (mylist) {
var len, pos, item, Item, akey, newitem, abase, j, jlen, k, klen, i, ilen;
if ("string" === typeof mylist) {
mylist = [mylist];
}
for (i = 0, ilen = mylist.length; i < ilen; i += 1) {
item = mylist[i];
if (!this.registry[item]) {
Item = this.state.retrieveItem(item);
akey = CSL.getAmbiguousCite.call(this.state, Item);
this.ambigsTouched[akey] = true;
if (!Item.legislation_id) {
this.akeys[akey] = true;
}
newitem = {
"id": "" + item,
"seq": 0,
"offset": 0,
"sortkeys": false,
"ambig": false,
"rendered": false,
"disambig": false,
"ref": Item
};
this.registry[item] = newitem;
if (this.citationreg.citationsByItemId && this.citationreg.citationsByItemId[item]) {
this.registry[item]["first-reference-note-number"] = this.citationreg.citationsByItemId[item][0].properties.noteIndex;
}
abase = CSL.getAmbigConfig.call(this.state);
this.registerAmbigToken(akey, item, abase);
this.touched[item] = true;
this.return_data.bibchange = true;
}
}
};
CSL.Registry.prototype.rebuildlist = function () {
var count, len, pos, item;
this.reflist = [];
if (this.state.opt.citation_number_sort_direction === CSL.DESCENDING
&& this.state.opt.citation_number_sort_used) {
}
len = this.mylist.length;
for (pos = 0; pos < len; pos += 1) {
item = this.mylist[pos];
this.reflist.push(this.registry[item]);
this.oldseq[item] = this.registry[item].seq;
this.registry[item].seq = (pos + 1);
}
if (this.state.opt.citation_number_sort_direction === CSL.DESCENDING
&& this.state.opt.citation_number_sort_used) {
}
};
CSL.Registry.prototype.dorefreshes = function () {
var key, regtoken, Item, old_akey, akey, abase;
for (key in this.refreshes) {
regtoken = this.registry[key];
if (!regtoken) {
continue;
}
regtoken.sortkeys = undefined;
Item = this.state.retrieveItem(key);
var akey = regtoken.ambig;
if ("undefined" === typeof akey) {
this.state.tmp.disambig_settings = false;
akey = CSL.getAmbiguousCite.call(this.state, Item);
abase = CSL.getAmbigConfig.call(this.state);
this.registerAmbigToken(akey, key, abase);
}
for (var akkey in this.ambigresets) {
if (this.ambigresets[akkey] === 1) {
var loneKey = this.ambigcites[akey][0];
var Item = this.state.retrieveItem(loneKey);
this.registry[loneKey].disambig = new CSL.AmbigConfig;
this.state.tmp.disambig_settings = false;
var akey = CSL.getAmbiguousCite.call(this.state, Item);
var abase = CSL.getAmbigConfig.call(this.state);
this.registerAmbigToken(akey, loneKey, abase);
}
}
this.state.tmp.taintedItemIDs[key] = true;
this.ambigsTouched[akey] = true;
if (!Item.legislation_id) {
this.akeys[akey] = true;
}
this.touched[key] = true;
}
};
CSL.Registry.prototype.setdisambigs = function () {
var akey, leftovers, key, pos, len, id;
this.leftovers = [];
for (akey in this.ambigsTouched) {
this.state.disambiguate.run(akey);
}
this.ambigsTouched = {};
this.akeys = {};
};
CSL.Registry.prototype.renumber = function () {
var len, pos, item;
if (this.state.opt.citation_number_sort_direction === CSL.DESCENDING
&& this.state.opt.citation_number_sort_used) {
}
len = this.reflist.length;
for (pos = 0; pos < len; pos += 1) {
item = this.reflist[pos];
item.seq = (pos + 1);
if (this.state.opt.update_mode === CSL.NUMERIC && item.seq != this.oldseq[item.id]) {
this.state.tmp.taintedItemIDs[item.id] = true;
}
if (this.state.opt.bib_mode === CSL.NUMERIC && item.seq != this.oldseq[item.id]) {
this.return_data.bibchange = true;
}
}
if (this.state.opt.citation_number_sort_direction === CSL.DESCENDING
&& this.state.opt.citation_number_sort_used) {
this.reflist.reverse();
}
};
CSL.Registry.prototype.setsortkeys = function () {
var key;
for (var i = 0, ilen = this.mylist.length; i < ilen; i += 1) {
var key = this.mylist[i];
if (this.touched[key] || this.state.tmp.taintedItemIDs[key] || !this.registry[key].sortkeys) {
this.registry[key].sortkeys = CSL.getSortKeys.call(this.state, this.state.retrieveItem(key), "bibliography_sort");
}
}
};
CSL.Registry.prototype.sorttokens = function () {
this.reflist.sort(this.sorter.compareKeys);
};
CSL.Registry.Comparifier = function (state, keyset) {
var sort_directions, len, pos, compareKeys;
var sortCompare = CSL.getSortCompare(state.opt["default-locale-sort"]);
sort_directions = state[keyset].opt.sort_directions;
this.compareKeys = function (a, b) {
len = a.sortkeys ? a.sortkeys.length : 0;
for (pos = 0; pos < len; pos += 1) {
var cmp = 0;
if (a.sortkeys[pos] === b.sortkeys[pos]) {
cmp = 0;
} else if ("undefined" === typeof a.sortkeys[pos]) {
cmp = sort_directions[pos][1];
} else if ("undefined" === typeof b.sortkeys[pos]) {
cmp = sort_directions[pos][0];
} else {
cmp = sortCompare(a.sortkeys[pos], b.sortkeys[pos]);
}
if (0 < cmp) {
return sort_directions[pos][1];
} else if (0 > cmp) {
return sort_directions[pos][0];
}
}
if (a.seq > b.seq) {
return 1;
} else if (a.seq < b.seq) {
return -1;
}
return 0;
};
compareKeys = this.compareKeys;
this.compareCompositeKeys = function (a, b) {
return compareKeys(a[1], b[1]);
};
};
CSL.Registry.prototype.compareRegistryTokens = function (a, b) {
if (a.seq > b.seq) {
return 1;
} else if (a.seq < b.seq) {
return -1;
}
return 0;
};
CSL.Registry.prototype.registerAmbigToken = function (akey, id, ambig_config) {
if (this.registry[id] && this.registry[id].disambig && this.registry[id].disambig.names) {
for (var i = 0, ilen = ambig_config.names.length; i < ilen; i += 1) {
var new_names_params = ambig_config.names[i];
var old_names_params = this.registry[id].disambig.names[i];
if (new_names_params !== old_names_params) {
this.state.tmp.taintedItemIDs[id] = true;
} else if (ambig_config.givens[i]) {
for (var j=0,jlen=ambig_config.givens[i].length;j 0) {
return param;
}
if (!gdropt || gdropt === "all-names" || gdropt === "primary-name") {
if (this.namereg[pkey].count > 1) {
param = 1;
}
if ((this.namereg[pkey].ikey
&& this.namereg[pkey].ikey[ikey].count > 1)
|| (this.namereg[pkey].count > 1
&& "string" !== typeof initials)) {
param = 2;
}
} else if (gdropt === "all-names-with-initials" || gdropt === "primary-name-with-initials") {
if (this.namereg[pkey].count > 1) {
param = 1;
} else {
param = 0;
}
}
if (!state.registry.registry[item_id]) {
if (form == "short") {
return 0;
} else if ("string" == typeof initials) {
return 1;
}
} else {
return param;
}
};
delitems = function (ids) {
var item, pos, len, posA, posB, id, fullkey, llen, ppos, otherid;
if ("string" === typeof ids || "number" === typeof ids) {
ids = ["" + ids];
}
ret = {};
len = ids.length;
for (pos = 0; pos < len; pos += 1) {
id = "" + ids[pos];
if (!this.nameind[id]) {
continue;
}
for (fullkey in this.nameind[id]) {
if (this.nameind[id].hasOwnProperty(fullkey)) {
key = fullkey.split("::");
pkey = key[0];
ikey = key[1];
skey = key[2];
if ("undefined" === typeof this.namereg[pkey]) {
continue;
}
items = this.namereg[pkey].items;
if (skey && this.namereg[pkey].ikey[ikey] && this.namereg[pkey].ikey[ikey].skey[skey]) {
myitems = this.namereg[pkey].ikey[ikey].skey[skey].items;
posB = myitems.indexOf("" + id);
if (posB > -1) {
this.namereg[pkey].ikey[ikey].skey[skey].items = myitems.slice(0, posB).concat(myitems.slice([(posB + 1)]));
}
if (this.namereg[pkey].ikey[ikey].skey[skey].items.length === 0) {
delete this.namereg[pkey].ikey[ikey].skey[skey];
this.namereg[pkey].ikey[ikey].count += -1;
if (this.namereg[pkey].ikey[ikey].count < 2) {
for (i = 0, ilen = this.namereg[pkey].ikey[ikey].items.length; i < ilen; i += 1) {
state.tmp.taintedItemIDs[this.namereg[pkey].ikey[ikey].items[i]] = true;
}
}
}
}
if (ikey && this.namereg[pkey].ikey[ikey]) {
posB = this.namereg[pkey].ikey[ikey].items.indexOf("" + id);
if (posB > -1) {
items = this.namereg[pkey].ikey[ikey].items.slice();
this.namereg[pkey].ikey[ikey].items = items.slice(0, posB).concat(items.slice([posB + 1]));
}
if (this.namereg[pkey].ikey[ikey].items.length === 0) {
delete this.namereg[pkey].ikey[ikey];
this.namereg[pkey].count += -1;
if (this.namereg[pkey].count < 2) {
for (i = 0, ilen = this.namereg[pkey].items.length; i < ilen; i += 1) {
state.tmp.taintedItemIDs[this.namereg[pkey].items[i]] = true;
}
}
}
}
if (pkey) {
posB = this.namereg[pkey].items.indexOf("" + id);
if (posB > -1) {
items = this.namereg[pkey].items.slice();
this.namereg[pkey].items = items.slice(0, posB).concat(items.slice([posB + 1], items.length));
}
if (this.namereg[pkey].items.length < 2) {
delete this.namereg[pkey];
}
}
delete this.nameind[id][fullkey];
}
}
delete this.nameind[id];
delete this.nameindpkeys[id];
}
return ret;
};
addname = function (item_id, nameobj, pos) {
var i, ilen;
var res = state.nameOutput.getName(nameobj, "locale-translit", true);
nameobj = res.name;
if (state.citation.opt["givenname-disambiguation-rule"]
&& state.citation.opt["givenname-disambiguation-rule"].slice(0, 8) === "primary-"
&& pos !== 0) {
return;
}
set_keys(this.state, "" + item_id, nameobj);
if (pkey) {
if ("undefined" === typeof this.namereg[pkey]) {
this.namereg[pkey] = {};
this.namereg[pkey].count = 0;
this.namereg[pkey].ikey = {};
this.namereg[pkey].items = [item_id];
} else if (this.namereg[pkey].items.indexOf(item_id) === -1) {
this.namereg[pkey].items.push(item_id);
}
}
if (pkey && ikey) {
if ("undefined" === typeof this.namereg[pkey].ikey[ikey]) {
this.namereg[pkey].ikey[ikey] = {};
this.namereg[pkey].ikey[ikey].count = 0;
this.namereg[pkey].ikey[ikey].skey = {};
this.namereg[pkey].ikey[ikey].items = [item_id];
this.namereg[pkey].count += 1;
if (this.namereg[pkey].count === 2) {
for (i = 0, ilen = this.namereg[pkey].items.length; i < ilen; i += 1) {
state.tmp.taintedItemIDs[this.namereg[pkey].items[i]] = true;
}
}
} else if (this.namereg[pkey].ikey[ikey].items.indexOf(item_id) === -1) {
this.namereg[pkey].ikey[ikey].items.push(item_id);
}
}
if (pkey && ikey && skey) {
if ("undefined" === typeof this.namereg[pkey].ikey[ikey].skey[skey]) {
this.namereg[pkey].ikey[ikey].skey[skey] = {};
this.namereg[pkey].ikey[ikey].skey[skey].items = [item_id];
this.namereg[pkey].ikey[ikey].count += 1;
if (this.namereg[pkey].ikey[ikey].count === 2) {
for (i = 0, ilen = this.namereg[pkey].ikey[ikey].items.length; i < ilen; i += 1) {
state.tmp.taintedItemIDs[this.namereg[pkey].ikey[ikey].items[i]] = true;
}
}
} else if (this.namereg[pkey].ikey[ikey].skey[skey].items.indexOf(item_id) === -1) {
this.namereg[pkey].ikey[ikey].skey[skey].items.push(item_id);
}
}
if ("undefined" === typeof this.nameind[item_id]) {
this.nameind[item_id] = {};
this.nameindpkeys[item_id] = {};
}
if (pkey) {
this.nameind[item_id][pkey + "::" + ikey + "::" + skey] = true;
this.nameindpkeys[item_id][pkey] = this.namereg[pkey];
}
};
this.addname = addname;
this.delitems = delitems;
this.evalname = evalname;
};
CSL.Registry.CitationReg = function (state) {
this.citationById = {};
this.citationByIndex = [];
};
CSL.Disambiguation = function (state) {
this.state = state;
this.sys = this.state.sys;
this.registry = state.registry.registry;
this.ambigcites = state.registry.ambigcites;
this.configModes();
this.debug = false;
};
CSL.Disambiguation.prototype.run = function(akey) {
if (!this.modes.length) {
return;
}
this.akey = akey;
if (this.initVars(akey)) {
this.runDisambig();
}
};
CSL.Disambiguation.prototype.runDisambig = function () {
var pos, len, ppos, llen, pppos, lllen, ismax;
this.initGivens = true;
while (this.lists.length) {
this.gnameset = 0;
this.gname = 0;
this.clashes = [1, 0];
while(this.lists[0][1].length) {
this.listpos = 0;
if (!this.base) {
this.base = this.lists[0][0];
}
var names_used = [];
ismax = this.incrementDisambig();
this.scanItems(this.lists[0]);
this.evalScan(ismax);
}
this.lists = this.lists.slice(1);
}
};
CSL.Disambiguation.prototype.scanItems = function (list) {
var pos, len, Item, otherItem, ItemCite, ignore, base;
this.Item = list[1][0];
this.ItemCite = CSL.getAmbiguousCite.call(this.state, this.Item, this.base, true);
this.scanlist = list[1];
this.partners = [];
this.partners.push(this.Item);
this.nonpartners = [];
var clashes = 0;
for (pos = 1, len = list[1].length; pos < len; pos += 1) {
otherItem = list[1][pos];
var otherItemCite = CSL.getAmbiguousCite.call(this.state, otherItem, this.base, true);
if (this.ItemCite === otherItemCite) {
clashes += 1;
this.partners.push(otherItem);
} else {
this.nonpartners.push(otherItem);
}
}
this.clashes[0] = this.clashes[1];
this.clashes[1] = clashes;
};
CSL.Disambiguation.prototype.evalScan = function (maxed) {
this[this.modes[this.modeindex]](maxed);
if (maxed) {
if (this.modeindex < this.modes.length - 1) {
this.modeindex += 1;
} else {
this.lists[this.listpos + 1] = [this.base, []];
}
}
};
CSL.Disambiguation.prototype.disNames = function (ismax) {
var pos, len, mybase, i, ilen;
if (this.clashes[1] === 0 && this.nonpartners.length === 1) {
this.captureStepToBase();
this.state.registry.registerAmbigToken(this.akey, "" + this.nonpartners[0].id, this.betterbase);
this.state.registry.registerAmbigToken(this.akey, "" + this.partners[0].id, this.betterbase);
this.lists[this.listpos] = [this.betterbase, []];
} else if (this.clashes[1] === 0) {
this.captureStepToBase();
this.state.registry.registerAmbigToken(this.akey, "" + this.partners[0].id, this.betterbase);
this.lists[this.listpos] = [this.betterbase, this.nonpartners];
if (this.nonpartners.length) {
this.initGivens = true;
}
} else if (this.nonpartners.length === 1) {
this.captureStepToBase();
this.state.registry.registerAmbigToken(this.akey, "" + this.nonpartners[0].id, this.betterbase);
this.lists[this.listpos] = [this.betterbase, this.partners];
} else if (this.clashes[1] < this.clashes[0]) {
this.captureStepToBase();
this.lists[this.listpos] = [this.betterbase, this.partners];
this.lists.push([this.betterbase, this.nonpartners]);
} else {
if (ismax) {
this.lists[this.listpos] = [this.betterbase, this.nonpartners];
this.lists.push([this.betterbase, this.partners]);
if (this.modeindex === this.modes.length - 1) {
for (i = 0, ilen = this.partners.length; i < ilen; i += 1) {
this.state.registry.registerAmbigToken(this.akey, "" + this.partners[i].id, this.betterbase);
}
this.lists[this.listpos] = [this.betterbase, []];
}
}
}
};
CSL.Disambiguation.prototype.disExtraText = function () {
var pos, len, mybase;
var done = false;
if (this.clashes[1] === 0 && this.nonpartners.length < 2) {
done = true;
}
if (!done && (!this.base.disambiguate || this.state.tmp.disambiguate_count !== this.state.tmp.disambiguate_maxMax)) {
this.modeindex = 0;
this.base.disambiguate = this.state.tmp.disambiguate_count;
this.betterbase.disambiguate = this.state.tmp.disambiguate_count;
if (!this.base.disambiguate) {
this.initGivens = true;
this.base.disambiguate = 1;
for (var i = 0, ilen = this.lists[this.listpos][1].length; i < ilen; i += 1) {
this.state.tmp.taintedItemIDs[this.lists[this.listpos][1][i].id] = true;
}
} else {
this.disNames();
}
} else if (done || this.state.tmp.disambiguate_count === this.state.tmp.disambiguate_maxMax) {
if (done || this.modeindex === this.modes.length - 1) {
var base = this.lists[this.listpos][0];
for (var i = 0, ilen = this.lists[this.listpos][1].length; i < ilen; i += 1) {
this.state.tmp.taintedItemIDs[this.lists[this.listpos][1][i].id] = true;
this.state.registry.registerAmbigToken(this.akey, "" + this.lists[this.listpos][1][i].id, base);
}
this.lists[this.listpos] = [this.betterbase, []];
} else {
this.modeindex = this.modes.length - 1;
var base = this.lists[this.listpos][0];
base.disambiguate = true;
for (var i = 0, ilen = this.lists[this.listpos][1].length; i < ilen; i += 1) {
this.state.tmp.taintedItemIDs[this.lists[this.listpos][1][i].id] = true;
this.state.registry.registerAmbigToken(this.akey, "" + this.lists[this.listpos][1][i].id, base);
}
}
}
};
CSL.Disambiguation.prototype.disYears = function () {
var pos, len, tokens, token, item;
tokens = [];
var base = this.lists[this.listpos][0];
if (this.clashes[1]) {
for (var i = 0, ilen = this.state.registry.mylist.length; i < ilen; i += 1) {
var origid = this.state.registry.mylist[i];
for (var j = 0, jlen = this.lists[this.listpos][1].length; j < jlen; j += 1) {
var token = this.lists[this.listpos][1][j];
if (token.id == origid) {
tokens.push(this.registry[token.id]);
break;
}
}
}
}
tokens.sort(this.state.registry.sorter.compareKeys);
for (pos = 0, len = tokens.length; pos < len; pos += 1) {
base.year_suffix = ""+pos;
var oldBase = this.state.registry.registry[tokens[pos].id].disambig;
this.state.registry.registerAmbigToken(this.akey, "" + tokens[pos].id, base);
if (CSL.ambigConfigDiff(oldBase,base)) {
this.state.tmp.taintedItemIDs[tokens[pos].id] = true;
}
}
this.lists[this.listpos] = [this.betterbase, []];
};
CSL.Disambiguation.prototype.incrementDisambig = function () {
var val;
if (this.initGivens) {
this.initGivens = false;
return false;
}
var maxed = false;
var increment_names = true;
var increment_givens = true;
if ("disNames" === this.modes[this.modeindex]) {
increment_names = false;
if ("number" !== typeof this.givensMax) {
increment_names = true;
}
var increment_namesets = false;
if ("number" !== typeof this.namesMax) {
increment_namesets = true;
}
if ("number" === typeof this.givensMax) {
if (this.base.givens.length && this.base.givens[this.gnameset][this.gname] < this.givensMax) {
this.base.givens[this.gnameset][this.gname] += 1;
} else {
increment_names = true;
}
}
if ("number" === typeof this.namesMax
&& increment_names) {
if (this.state.opt["disambiguate-add-names"]) {
increment_namesets = false;
if (this.gname < this.namesMax) {
this.base.names[this.gnameset] += 1;
this.gname += 1;
} else {
increment_namesets = true;
}
} else {
increment_namesets = true;
}
}
if ("number" === typeof this.namesetsMax && increment_namesets) {
if (this.gnameset < this.namesetsMax) {
this.gnameset += 1;
this.base.names[this.gnameset] = 1;
this.gname = 0;
} else {
var increment_mode = true;
}
}
if (("number" !== typeof this.namesetsMax || this.namesetsMax === -1 || this.gnameset === this.namesetsMax)
&& (!this.state.opt["disambiguate-add-names"] || "number" !== typeof this.namesMax || this.gname === this.namesMax)
&& ("number" != typeof this.givensMax || "undefined" === typeof this.base.givens[this.gnameset] || "undefined" === typeof this.base.givens[this.gnameset][this.gname] || this.base.givens[this.gnameset][this.gname] === this.givensMax)) {
maxed = true;
}
} else if ("disExtraText" === this.modes[this.modeindex]) {
this.base.disambiguate += 1;
this.betterbase.disambiguate += 1;
}
return maxed;
};
CSL.Disambiguation.prototype.initVars = function (akey) {
var i, ilen, myIds, myItemBundles, myItems;
this.lists = [];
this.base = false;
this.betterbase = false;
this.akey = akey;
this.maxNamesByItemId = {};
myItemBundles = [];
myIds = this.ambigcites[akey];
if (!myIds || !myIds.length) {
return false;
}
var Item = false;
var myItem = this.state.retrieveItem("" + myIds[0]);
this.getCiteData(myItem);
this.base = CSL.getAmbigConfig.call(this.state);
if (myIds && myIds.length > 1) {
myItemBundles.push([this.maxNamesByItemId[myItem.id], myItem]);
for (i = 1, ilen = myIds.length; i < ilen; i += 1) {
myItem = this.state.retrieveItem("" + myIds[i]);
this.getCiteData(myItem, this.base);
myItemBundles.push([this.maxNamesByItemId[myItem.id], myItem]);
}
myItemBundles.sort(
function (a, b) {
if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
} else {
if (a[1].id > b[1].id) {
return 1;
} else if (a[1].id < b[1].id) {
return -1;
} else {
return 0;
}
}
}
);
myItems = [];
for (i = 0, ilen = myItemBundles.length; i < ilen; i += 1) {
myItems.push(myItemBundles[i][1]);
}
this.lists.push([this.base, myItems]);
this.Item = this.lists[0][1][0];
} else {
this.Item = this.state.retrieveItem("" + myIds[0]);
}
this.modeindex = 0;
if (this.state.citation.opt["disambiguate-add-names"] || true) {
this.namesMax = this.maxNamesByItemId[this.Item.id][0];
} else {
var namesMax = this.base.names[0];
for (var i=1,ilen=this.base.names.length;i this.base.names[i]) {
this.base.givens[i] = base.givens[i].slice();
this.base.names[i] = base.names[i];
this.betterbase.names = this.base.names.slice();
this.betterbase.givens = this.base.givens.slice();
this.padBase(this.base);
this.padBase(this.betterbase);
}
}
this.betterbase.givens = this.base.givens.slice();
for (var j = 0, jlen = this.base.givens.length; j < jlen; j += 1) {
this.betterbase.givens[j] = this.base.givens[j].slice();
}
}
};
CSL.Disambiguation.prototype.captureStepToBase = function() {
if (this.state.citation.opt["givenname-disambiguation-rule"] === "by-cite"
&& this.base.givens && this.base.givens.length) {
if ("undefined" !== typeof this.base.givens[this.gnameset][this.gname]) {
this.betterbase.givens[this.gnameset][this.gname] = this.base.givens[this.gnameset][this.gname];
}
}
this.betterbase.names[this.gnameset] = this.base.names[this.gnameset];
};
PK Dq-L
0 0 cite2c/nbext/main.jsrequirejs.config({
shim: {
'nbextensions/cite2c/xmldom': {
deps: [],
exports: "CSL_CHROME"
},
'nbextensions/cite2c/citeproc': {
deps: ['nbextensions/cite2c/xmldom'],
exports: "CSL"
},
'nbextensions/cite2c/typeahead.bundle.min': {
deps: ['jquery'],
exports: "Bloodhound" // Doesn't actually work, because of the shenanigans typeahead does
}
}
});
define(['jquery',
'base/js/dialog',
'base/js/utils',
'services/config',
'nbextensions/cite2c/rendering',
'nbextensions/cite2c/typeahead.bundle.min',
],
function($, dialog, utils, configmod, rendering) {
"use strict";
// There are two different jQuery typeahead plugins. This code uses one,
// and the command palette uses the other. They both add the .typeahead()
// method to jQuery objects. .noConflict() replaces the twitter .typeahead()
// method we loaded with the jquery-typeahead one the command palette needs.
// Then we reattach ours as .twitter_typeahead() so we can use it below.
// Namespaces, anyone?
$.fn.twitter_typeahead = $.fn.typeahead.noConflict();
var make_author_string = function(authors) {
// Make a simple string of the author surnames, to show in the
// typeahead dropdown
var surname = function(auth) { return auth.family || "?"; };
if (!authors) return "";
switch (authors.length) {
case 0:
return "";
case 1:
return surname(authors[0]);
case 2:
return surname(authors[0]) + " & " + surname(authors[1]);
default:
return surname(authors[0]) + " et al.";
}
};
var csl_tokenize = function(item) {
// Turn a CSL JSON object into an array of word tokens for Bloodhound
var tokens = [];
function add_splitted(value) {
if (value) tokens = tokens.concat(value.toString().split(/\s+/));
}
add_splitted(item.title);
if (item.author) {
for (var i=0; i < item.author.length; i++) {
add_splitted(item.author[i].family);
add_splitted(item.author[i].literal);
}
}
if (item.issued) {
if (item.issued['date-parts'])
add_splitted(item.issued['date-parts'][0]);
add_splitted(item.issued.year);
}
return tokens;
};
var get_metadata_items = function() {
// Get an array of citations from the metadata.
var items = (IPython.notebook.metadata.cite2c || {}).citations || {};
return $.map(items, function(obj, id) {return obj;}); // Flatten to array
};
var config = new configmod.ConfigSection('cite2c',
{base_url: utils.get_body_data("baseUrl")});
config.load();
function get_zotero_access() {
// Get the Zotero user ID, either from config, or by prompting the user
// with a dialog. Returns a promise which resolves to the user ID.
return config.loaded.then(function() {
var zotero = (config.data.zotero || {});
if (zotero.user_id && zotero.access_token) {
return zotero;
}
var dialog_body = $("").append(
"
Opened a new tab to authenticate with Zotero. " +
"Once you have done this, please click OK.
");
// Open a new tab for the user to authorize cite2c on Zotero.
window.open(utils.url_path_join(utils.get_body_data("baseUrl"),
'cite2c/zotero_oauth'));
return new Promise(function(resolve, reject) {
var clicked_ok = false;
dialog.modal({
notebook: IPython.notebook,
keyboard_manager: IPython.keyboard_manager,
title : "Zotero User ID",
body : dialog_body,
open: function() {
var that = $(this);
that.find('form').submit(function () {
that.find('.btn-primary').first().click();
return false;
});
},
buttons : {
"Cancel" : {
click : function() { reject("Dialog cancelled"); }
},
"OK" : {
class : "btn-primary",
click: function() { clicked_ok = true; }
}
}
}).on("hidden.bs.modal", function () {
// Sigh. Because this ends up showing another dialog, if we
// do it in the click handler, there's a race condition with
// enabling/disabling the notebook keyboard shortcuts, which
// leads to the shortcuts being active while the second
// dialog is open. Waiting for this hidden event and doing
// setTimeout should be enough to avoid the race.
if (clicked_ok) {
setTimeout(function () {
config.load().then(function (data) {
resolve(data.zotero);
console.log("Authenticated Zotero user ID " + data.zotero.user_id);
});
}, 0);
}
});
});
});
}
var zot_bh_engine;
function get_zot_bh_engine() {
// Retrieve the existing Bloodhound engine for Zotero, or initialise a
// new one. Returns a promise which resolves to the Bloodhound instance.
// May prompt the user for their Zotero ID.
if (zot_bh_engine) {
// Engine already exists; resolve promise once it's initialised.
return new Promise(function(resolve, reject) {
zot_bh_engine.initialize()
.done(function() { resolve(zot_bh_engine); })
.fail(reject);
});
}
return get_zotero_access().then(function(zotero_info) {
zot_bh_engine = new Bloodhound({
name: 'zotero',
datumTokenizer: csl_tokenize,
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
dupDetector: function(remoteMatch, localMatch) { return remoteMatch.id === localMatch.id; },
local: get_metadata_items,
remote: {
url: "https://api.zotero.org/users/"+zotero_info.user_id+"/items?v=3&limit=10&format=csljson&q=%QUERY",
filter: function(result) { return result.items; },
ajax: {
accepts: "application/vnd.citationstyles.csl+json",
dataType: "json",
headers: {
"Zotero-API-Key": zotero_info.access_token
}
}
}
});
return new Promise(function(resolve, reject) {
zot_bh_engine.initialize()
.done(function() { resolve(zot_bh_engine); })
.fail(reject);
});
});
}
var store_citation = function(id, citation) {
// Store citation data to notebook metadata & BH search index
var metadata = IPython.notebook.metadata;
if (!metadata.cite2c) metadata.cite2c = {};
if (!metadata.cite2c.citations) metadata.cite2c.citations = {};
if (!(id in metadata.cite2c.citations)) {
metadata.cite2c.citations[id] = citation;
zot_bh_engine.add(citation);
}
};
function insert_citn() {
// Show the user a dialog to choose and insert a citation
var cell = IPython.notebook.get_selected_cell();
var entry_box = $('');
var dialog_body = $("")
.append($("").text("Start typing below to search Zotero"))
.append($('').append(entry_box));
dialog_body.addClass("cite2c-dialog");
get_zot_bh_engine().then(function(zot_bh_engine) {
// Set up typeahead.js to search Zotero
entry_box.twitter_typeahead({
minLength: 3,
hint: false,
highlight: true,
},
{
name: 'zotero',
source: zot_bh_engine.ttAdapter(),
displayKey: function(value) { return value.title || "Mystery item with no title"; },
templates: {
empty: "No matches",
suggestion: function(value) {
//console.log(value);
return "
"+value.title+"
" +
'
' + (value.type || "?") + "
" +
"
"+ make_author_string(value.author) + "
";
}
}
});
entry_box.on('typeahead:selected', function(ev, suggestion, dataset) {
entry_box.data("csljson", suggestion);
});
// Display dialog
dialog.modal({
notebook: IPython.notebook,
keyboard_manager: IPython.keyboard_manager,
title : "Insert citation",
body : dialog_body,
open: function() {
// Submit on pressing enter
var that = $(this);
that.find('form').submit(function () {
that.find('.btn-primary').first().click();
return false;
});
entry_box.focus();
},
buttons : {
"Cancel" : {},
"Insert" : {
"class" : "btn-primary",
"click" : function() {
// Retrieve the selected citation, add to metadata,
// and insert an HTML tag for it.
var citation = entry_box.data("csljson");
if (!citation) {return;}
var id = citation.id;
delete citation.id;
store_citation(id, citation);
var citn_html = '';
cell.code_mirror.replaceSelection(citn_html);
}
}
}
});
});
}
var insert_biblio = function() {
// Insert HTML tag for bibliography
var cell = IPython.notebook.get_selected_cell();
cell.code_mirror.replaceSelection('');
};
var toolbar_buttons = function () {
// Add toolbar buttons to insert citations and bibliographies
if (!Jupyter.toolbar) {
$([Jupyter.events]).on("app_initialized.NotebookApp", toolbar_buttons);
return;
}
Jupyter.actions.register({
icon: 'fa-mortar-board',
help: 'Insert a citation',
help_index: 'za',
handler: insert_citn
}, 'insert-citation', 'cite2c');
Jupyter.actions.register({
icon: 'fa-list',
help: 'Insert bibliography',
help_index: 'zb',
handler: insert_biblio,
}, 'insert-biblio', 'cite2c');
Jupyter.toolbar.add_buttons_group([
{
'label' : 'Cite',
'action' : 'cite2c:insert-citation'
},
'cite2c:insert-biblio'
], 'cite2c-buttons');
};
function load_ipython_extension() {
toolbar_buttons();
rendering.init_rendering();
$('head').append('');
}
return {load_ipython_extension: load_ipython_extension};
});
PK Q4KRsvu7 u7 cite2c/nbext/rendering.jsdefine(['jquery',
'base/js/utils',
'nbextensions/cite2c/citeproc',
],
function($, utils, CSL) {
"use strict";
/*
* Part 1: Find and render citations using citeproc-js
*/
var cpSys = {
retrieveLocale: function(lang) {
// Any locale you want, so long as it's en-US
return "No.Doc.U.N. Sales No.No.\u201c\u201d\u2018\u2019stndrdthfirstsecondthirdfourthfifthsixthseventheighthninthtenthatinibidaccessedretrievedfromforthcomingreferencereferencesrefrefsn.d.andet al.interviewletteranonymousanon.and othersin pressonlinecitedinternetpresented at theADBCSpringSummerAutumnWinterwithanthropologyastronomybiologybotanychemistryengineeringgeneric basegeographygeologyhistoryhumanitiesliteraturemathmedicinephilosophyphysicspsychologysociologysciencepolitical sciencesocial sciencetheologyzoologybookbookschapterchapterscolumncolumnsfigurefiguresfoliofoliosnumbernumberslinelinesnotenotesopusoperapagepagesparagraphparagraphpartpartssectionsectionsvolumevolumeseditioneditionsverseversessub verbos.vvbk.chap.col.fig.f.no.op.p.pp.para.pt.sec.s.v.s.vv.v.vv.vol.vols.editioned.¶¶¶§§§editoreditorstranslatortranslatorsed.eds.tran.trans.edited bytranslated bytointerview byed.trans.JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecemberJan.Feb.Mar.Apr.MayJun.Jul.Aug.Sep.Oct.Nov.Dec.";
},
retrieveItem: function(id) {
var item = IPython.notebook.metadata.cite2c.citations[id];
item.id = id; // Not documented, but citeproc breaks without this
return item;
}
};
var make_citeproc_pairs = function(citns) {
return citns.map(function(citn) {
return [citn.id, 0];
});
};
var citeproc;
function render_biblio() {
var biblio_targets = $('.cite2c-biblio');
if (biblio_targets.length === 0) {
return;
}
var bibdata = citeproc.makeBibliography();
var bibmetadata = bibdata[0];
var bibhtml = bibmetadata.bibstart + bibdata[1].join('') + bibmetadata.bibend;
biblio_targets.html(bibhtml);
}
function process_cell_citations(cell) {
var i=0;
// Gather citations before and after the current cell
var all_cells = IPython.notebook.get_cells();
var after_current = false;
var citns_before = [];
var citns_after = [];
for (i=0; i < all_cells.length; i++) {
if (all_cells[i] === cell) {
after_current = true;
continue;
}
if (after_current) {
citns_after = citns_after.concat(all_cells[i]._cite2c_citns || []);
} else {
citns_before = citns_before.concat(all_cells[i]._cite2c_citns || []);
}
}
var element = cell.element.find('div.text_cell_render');
var citn_elements = element.find("[data-cite]");
cell._cite2c_citns = [];
var newbiblios = element.find(".cite2c-biblio");
var bibchange = (newbiblios.length > 0);
for (i=0; i < citn_elements.length; i++) {
var citn_element = citn_elements[i];
var id = citn_element.dataset.cite;
var citeproc_citn = {citationItems: [{id: id}],
properties: {noteIndex: 0}
};
var results = citeproc.processCitationCluster(citeproc_citn,
make_citeproc_pairs(citns_before),
make_citeproc_pairs(citns_after));
var citn = {id: citeproc_citn.citationID, element: citn_element};
cell._cite2c_citns.push(citn);
bibchange = bibchange || results[0].bibchange;
var updates = results[1];
var all_citns = citns_before.concat([citn], citns_after);
for (var j=0; j < updates.length; j++) {
var idx = updates[j][0];
var newcontent = updates[j][1];
all_citns[idx].element.innerHTML = newcontent;
}
citns_before.push(citn);
}
// This is false when I would expect it to be true. For now,
// just re-render the bibliography every time.
//if (bibchange) {
render_biblio();
//}
} // end process_cell_citations
function md_cell_rendered(event, data) {
// Event handler to process citations
process_cell_citations(data.cell);
}
function reprocess_all() {
// Process citations in all cells; used on load to render citations.
var all_cells = IPython.notebook.get_cells();
var i = 0;
for (i = 0; i < all_cells.length; i++) {
delete all_cells[i]._cite2c_citns;
}
for (i = 0; i < all_cells.length; i++) {
var cell = all_cells[i];
if (cell.cell_type === "markdown") {
process_cell_citations(cell);
}
}
}
function init_rendering() {
// Create a CSL engine, hook it up to the MarkdownCell rendered event,
// and process all citations already in the document.
$.ajax("/nbextensions/cite2c/chicago-author-date.csl", {
dataType: "text",
success: function(styleAsText, textStatus, jqXHR) {
citeproc = new CSL.Engine(cpSys, styleAsText);
IPython.notebook.events.off("rendered.MarkdownCell", null, md_cell_rendered);
IPython.notebook.events.on("rendered.MarkdownCell", md_cell_rendered);
// Process all citations on load
reprocess_all();
}
});
}
return {init_rendering: init_rendering};
});
PK Q4K߈ cite2c/nbext/styles.css
.cite2c-dialog .twitter-typeahead {
width: 90%;
margin: 8px;
}
.cite2c-dialog .tt-input {
width: 100%;
}
.cite2c-dialog .tt-dropdown-menu {
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
}
.cite2c-dialog .tt-suggestion {
padding: 4px;
}
.cite2c-dialog .tt-suggestion.tt-cursor {
background-color: #eee;
}
.csl-entry {
padding: 0.4em 0;
}
PK Q4KsZxs s $ cite2c/nbext/typeahead.bundle.min.js/*!
* typeahead.js 0.10.5
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/
!function(a){var b=function(){"use strict";return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,getUniqueId:function(){var a=0;return function(){return a++}}(),templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},noop:function(){}}}(),c="0.10.5",d=function(){"use strict";function a(a){return a=b.toStr(a),a?a.split(/\s+/):[]}function c(a){return a=b.toStr(a),a?a.split(/\W+/):[]}function d(a){return function(){var c=[].slice.call(arguments,0);return function(d){var e=[];return b.each(c,function(c){e=e.concat(a(b.toStr(d[c])))}),e}}}return{nonword:c,whitespace:a,obj:{nonword:d(c),whitespace:d(a)}}}(),e=function(){"use strict";function c(c){this.maxSize=b.isNumber(c)?c:100,this.reset(),this.maxSize<=0&&(this.set=this.get=a.noop)}function d(){this.head=this.tail=null}function e(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(c.prototype,{set:function(a,b){var c,d=this.list.tail;this.size>=this.maxSize&&(this.list.remove(d),delete this.hash[d.key]),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new e(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];return b?(this.list.moveToFront(b),b.val):void 0},reset:function(){this.size=0,this.hash={},this.list=new d}}),b.mixin(d.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),c}(),f=function(){"use strict";function a(a){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+b.escapeRegExChars(this.prefix))}function c(){return(new Date).getTime()}function d(a){return JSON.stringify(b.isUndefined(a)?null:a)}function e(a){return JSON.parse(a)}var f,g;try{f=window.localStorage,f.setItem("~~~","!"),f.removeItem("~~~")}catch(h){f=null}return g=f&&window.JSON?{_prefix:function(a){return this.prefix+a},_ttlKey:function(a){return this._prefix(a)+this.ttlKey},get:function(a){return this.isExpired(a)&&this.remove(a),e(f.getItem(this._prefix(a)))},set:function(a,e,g){return b.isNumber(g)?f.setItem(this._ttlKey(a),d(c()+g)):f.removeItem(this._ttlKey(a)),f.setItem(this._prefix(a),d(e))},remove:function(a){return f.removeItem(this._ttlKey(a)),f.removeItem(this._prefix(a)),this},clear:function(){var a,b,c=[],d=f.length;for(a=0;d>a;a++)(b=f.key(a)).match(this.keyMatcher)&&c.push(b.replace(this.keyMatcher,""));for(a=c.length;a--;)this.remove(c[a]);return this},isExpired:function(a){var d=e(f.getItem(this._ttlKey(a)));return b.isNumber(d)&&c()>d?!0:!1}}:{get:b.noop,set:b.noop,remove:b.noop,clear:b.noop,isExpired:b.noop},b.mixin(a.prototype,g),a}(),g=function(){"use strict";function c(b){b=b||{},this.cancelled=!1,this.lastUrl=null,this._send=b.transport?d(b.transport):a.ajax,this._get=b.rateLimiter?b.rateLimiter(this._get):this._get,this._cache=b.cache===!1?new e(0):i}function d(c){return function(d,e){function f(a){b.defer(function(){h.resolve(a)})}function g(a){b.defer(function(){h.reject(a)})}var h=a.Deferred();return c(d,e,f,g),h}}var f=0,g={},h=6,i=new e(10);return c.setMaxPendingRequests=function(a){h=a},c.resetCache=function(){i.reset()},b.mixin(c.prototype,{_get:function(a,b,c){function d(b){c&&c(null,b),k._cache.set(a,b)}function e(){c&&c(!0)}function i(){f--,delete g[a],k.onDeckRequestArgs&&(k._get.apply(k,k.onDeckRequestArgs),k.onDeckRequestArgs=null)}var j,k=this;this.cancelled||a!==this.lastUrl||((j=g[a])?j.done(d).fail(e):h>f?(f++,g[a]=this._send(a,b).done(d).fail(e).always(i)):this.onDeckRequestArgs=[].slice.call(arguments,0))},get:function(a,c,d){var e;return b.isFunction(c)&&(d=c,c={}),this.cancelled=!1,this.lastUrl=a,(e=this._cache.get(a))?b.defer(function(){d&&d(null,e)}):this._get(a,c,d),!!e},cancel:function(){this.cancelled=!0}}),c}(),h=function(){"use strict";function c(b){b=b||{},b.datumTokenizer&&b.queryTokenizer||a.error("datumTokenizer and queryTokenizer are both required"),this.datumTokenizer=b.datumTokenizer,this.queryTokenizer=b.queryTokenizer,this.reset()}function d(a){return a=b.filter(a,function(a){return!!a}),a=b.map(a,function(a){return a.toLowerCase()})}function e(){return{ids:[],children:{}}}function f(a){for(var b={},c=[],d=0,e=a.length;e>d;d++)b[a[d]]||(b[a[d]]=!0,c.push(a[d]));return c}function g(a,b){function c(a,b){return a-b}var d=0,e=0,f=[];a=a.sort(c),b=b.sort(c);for(var g=a.length,h=b.length;g>d&&h>e;)a[d]b[e]?e++:(f.push(a[d]),d++,e++);return f}return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;f=c.datums.push(a)-1,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b.children[g]||(b.children[g]=e()),b.ids.push(f)})})},get:function(a){var c,e,h=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length)return!1;for(b=h.trie,c=a.split("");b&&(d=c.shift());)b=b.children[d];return b&&0===c.length?(f=b.ids.slice(0),void(e=e?g(e,f):f)):(e=[],!1)}),e?b.map(f(e),function(a){return h.datums[a]}):[]},reset:function(){this.datums=[],this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){"use strict";function d(a){return a.local||null}function e(d){var e,f;return f={url:null,thumbprint:"",ttl:864e5,filter:null,ajax:{}},(e=d.prefetch||null)&&(e=b.isString(e)?{url:e}:e,e=b.mixin(f,e),e.thumbprint=c+e.thumbprint,e.ajax.type=e.ajax.type||"GET",e.ajax.dataType=e.ajax.dataType||"json",!e.url&&a.error("prefetch requires url to be set")),e}function f(c){function d(a){return function(c){return b.debounce(c,a)}}function e(a){return function(c){return b.throttle(c,a)}}var f,g;return g={url:null,cache:!0,wildcard:"%QUERY",replace:null,rateLimitBy:"debounce",rateLimitWait:300,send:null,filter:null,ajax:{}},(f=c.remote||null)&&(f=b.isString(f)?{url:f}:f,f=b.mixin(g,f),f.rateLimiter=/^throttle$/i.test(f.rateLimitBy)?e(f.rateLimitWait):d(f.rateLimitWait),f.ajax.type=f.ajax.type||"GET",f.ajax.dataType=f.ajax.dataType||"json",delete f.rateLimitBy,delete f.rateLimitWait,!f.url&&a.error("remote requires url to be set")),f}return{local:d,prefetch:e,remote:f}}();!function(c){"use strict";function e(b){b&&(b.local||b.prefetch||b.remote)||a.error("one of local, prefetch, or remote is required"),this.limit=b.limit||5,this.sorter=j(b.sorter),this.dupDetector=b.dupDetector||k,this.local=i.local(b),this.prefetch=i.prefetch(b),this.remote=i.remote(b),this.cacheKey=this.prefetch?this.prefetch.cacheKey||this.prefetch.url:null,this.index=new h({datumTokenizer:b.datumTokenizer,queryTokenizer:b.queryTokenizer}),this.storage=this.cacheKey?new f(this.cacheKey):null}function j(a){function c(b){return b.sort(a)}function d(a){return a}return b.isFunction(a)?c:d}function k(){return!1}var l,m;return l=c.Bloodhound,m={data:"data",protocol:"protocol",thumbprint:"thumbprint"},c.Bloodhound=e,e.noConflict=function(){return c.Bloodhound=l,e},e.tokenizers=d,b.mixin(e.prototype,{_loadPrefetch:function(b){function c(a){f.clear(),f.add(b.filter?b.filter(a):a),f._saveToStorage(f.index.serialize(),b.thumbprint,b.ttl)}var d,e,f=this;return(d=this._readFromStorage(b.thumbprint))?(this.index.bootstrap(d),e=a.Deferred().resolve()):e=a.ajax(b.url,b.ajax).done(c),e},_getFromRemote:function(a,b){function c(a,c){b(a?[]:f.remote.filter?f.remote.filter(c):c)}var d,e,f=this;if(this.transport)return a=a||"",e=encodeURIComponent(a),d=this.remote.replace?this.remote.replace(this.remote.url,a):this.remote.url.replace(this.remote.wildcard,e),this.transport.get(d,this.remote.ajax,c)},_cancelLastRemoteRequest:function(){this.transport&&this.transport.cancel()},_saveToStorage:function(a,b,c){this.storage&&(this.storage.set(m.data,a,c),this.storage.set(m.protocol,location.protocol,c),this.storage.set(m.thumbprint,b,c))},_readFromStorage:function(a){var b,c={};return this.storage&&(c.data=this.storage.get(m.data),c.protocol=this.storage.get(m.protocol),c.thumbprint=this.storage.get(m.thumbprint)),b=c.thumbprint!==a||c.protocol!==location.protocol,c.data&&!b?c.data:null},_initialize:function(){function c(){e.add(b.isFunction(f)?f():f)}var d,e=this,f=this.local;return d=this.prefetch?this._loadPrefetch(this.prefetch):a.Deferred().resolve(),f&&d.done(c),this.transport=this.remote?new g(this.remote):null,this.initPromise=d.promise()},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){this.index.add(a)},get:function(a,c){function d(a){var d=f.slice(0);b.each(a,function(a){var c;return c=b.some(d,function(b){return e.dupDetector(a,b)}),!c&&d.push(a),d.length0||!this.transport)&&c&&c(f)},clear:function(){this.index.reset()},clearPrefetchCache:function(){this.storage&&this.storage.clear()},clearRemoteCache:function(){this.transport&&g.resetCache()},ttAdapter:function(){return b.bind(this.get,this)}}),e}(this);var j=function(){return{wrapper:'',dropdown:'',dataset:'',suggestions:'',suggestion:''}}(),k=function(){"use strict";var a={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},dropdown:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},suggestions:{display:"block"},suggestion:{whiteSpace:"nowrap",cursor:"pointer"},suggestionChild:{whiteSpace:"normal"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};return b.isMsie()&&b.mixin(a.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),b.isMsie()&&b.isMsie()<=7&&b.mixin(a.input,{marginTop:"-1px"}),a}(),l=function(){"use strict";function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d="typeahead:";return b.mixin(c.prototype,{trigger:function(a){var b=[].slice.call(arguments,1);this.$el.trigger(d+a,b)}}),c}(),m=function(){"use strict";function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0,f=a.length;!d&&f>e;e+=1)d=a[e].apply(b,c)===!1;return!d}return d}function g(){var a;return a=window.setImmediate?function(a){setImmediate(function(){a()})}:function(a){setTimeout(function(){a()},0)}}function h(a,b){return a.bind?a.bind(b):function(){a.apply(b,[].slice.call(arguments,0))}}var i=/\s+/,j=g();return{onSync:c,onAsync:b,off:d,trigger:e}}(),n=function(a){"use strict";function c(a,c,d){for(var e,f=[],g=0,h=a.length;h>g;g++)f.push(b.escapeRegExChars(a[g]));return e=d?"\\b("+f.join("|")+")\\b":"("+f.join("|")+")",c?new RegExp(e):new RegExp(e,"i")}var d={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:!1,caseSensitive:!1};return function(e){function f(b){var c,d,f;return(c=h.exec(b.data))&&(f=a.createElement(e.tagName),e.className&&(f.className=e.className),d=b.splitText(c.index),d.splitText(c[0].length),f.appendChild(d.cloneNode(!0)),b.parentNode.replaceChild(f,d)),!!c}function g(a,b){for(var c,d=3,e=0;e').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),fontStyle:b.css("font-style"),fontVariant:b.css("font-variant"),fontWeight:b.css("font-weight"),wordSpacing:b.css("word-spacing"),letterSpacing:b.css("letter-spacing"),textIndent:b.css("text-indent"),textRendering:b.css("text-rendering"),textTransform:b.css("text-transform")}).insertAfter(b)}function e(a,b){return c.normalizeQuery(a)===c.normalizeQuery(b)}function f(a){return a.altKey||a.ctrlKey||a.metaKey||a.shiftKey}var g;return g={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"},c.normalizeQuery=function(a){return(a||"").replace(/^\s*/g,"").replace(/\s{2,}/g," ")},b.mixin(c.prototype,m,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.trigger("focused")},_onKeydown:function(a){var b=g[a.which||a.keyCode];this._managePreventDefault(b,a),b&&this._shouldTrigger(b,a)&&this.trigger(b+"Keyed",a)},_onInput:function(){this._checkInputValue()},_managePreventDefault:function(a,b){var c,d,e;switch(a){case"tab":d=this.getHint(),e=this.getInputValue(),c=d&&d!==e&&!f(b);break;case"up":case"down":c=!f(b);break;default:c=!1}c&&b.preventDefault()},_shouldTrigger:function(a,b){var c;switch(a){case"tab":c=!f(b);break;default:c=!0}return c},_checkInputValue:function(){var a,b,c;a=this.getInputValue(),b=e(a,this.query),c=b?this.query.length!==a.length:!1,this.query=a,b?c&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query)},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getQuery:function(){return this.query},setQuery:function(a){this.query=a},getInputValue:function(){return this.$input.val()},setInputValue:function(a,b){this.$input.val(a),b?this.clearHint():this._checkInputValue()},resetInputValue:function(){this.setInputValue(this.query,!0)},getHint:function(){return this.$hint.val()},setHint:function(a){this.$hint.val(a)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var a,b,c,d;a=this.getInputValue(),b=this.getHint(),c=a!==b&&0===b.indexOf(a),d=""!==a&&c&&!this.hasOverflow(),!d&&this.clearHint()},getLanguageDirection:function(){return(this.$input.css("direction")||"ltr").toLowerCase()},hasOverflow:function(){var a=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=a},isCursorAtEnd:function(){var a,c,d;return a=this.$input.val().length,c=this.$input[0].selectionStart,b.isNumber(c)?c===a:document.selection?(d=document.selection.createRange(),d.moveStart("character",-a),a===d.text.length):!0},destroy:function(){this.$hint.off(".tt"),this.$input.off(".tt"),this.$hint=this.$input=this.$overflowHelper=null}}),c}(),p=function(){"use strict";function c(c){c=c||{},c.templates=c.templates||{},c.source||a.error("missing source"),c.name&&!f(c.name)&&a.error("invalid dataset name: "+c.name),this.query=null,this.highlight=!!c.highlight,this.name=c.name||b.getUniqueId(),this.source=c.source,this.displayFn=d(c.display||c.displayKey),this.templates=e(c.templates,this.displayFn),this.$el=a(j.dataset.replace("%CLASS%",this.name))}function d(a){function c(b){return b[a]}return a=a||"value",b.isFunction(a)?a:c}function e(a,c){function d(a){return"
"+c(a)+"
"}return{empty:a.empty&&b.templatify(a.empty),header:a.header&&b.templatify(a.header),footer:a.footer&&b.templatify(a.footer),suggestion:a.suggestion||d}}function f(a){return/^[_a-zA-Z0-9-]+$/.test(a)}var g="ttDataset",h="ttValue",i="ttDatum";return c.extractDatasetName=function(b){return a(b).data(g)},c.extractValue=function(b){return a(b).data(h)},c.extractDatum=function(b){return a(b).data(i)},b.mixin(c.prototype,m,{_render:function(c,d){function e(){return p.templates.empty({query:c,isEmpty:!0})}function f(){function e(b){var c;return c=a(j.suggestion).append(p.templates.suggestion(b)).data(g,p.name).data(h,p.displayFn(b)).data(i,b),c.children().each(function(){a(this).css(k.suggestionChild)}),c}var f,l;return f=a(j.suggestions).css(k.suggestions),l=b.map(d,e),f.append.apply(f,l),p.highlight&&n({className:"tt-highlight",node:f[0],pattern:c}),f}function l(){return p.templates.header({query:c,isEmpty:!o})}function m(){return p.templates.footer({query:c,isEmpty:!o})}if(this.$el){var o,p=this;this.$el.empty(),o=d&&d.length,!o&&this.templates.empty?this.$el.html(e()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null):o&&this.$el.html(f()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null),this.trigger("rendered")}},getRoot:function(){return this.$el},update:function(a){function b(b){c.canceled||a!==c.query||c._render(a,b)}var c=this;this.query=a,this.canceled=!1,this.source(a,b)},cancel:function(){this.canceled=!0},clear:function(){this.cancel(),this.$el.empty(),this.trigger("rendered")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=null}}),c}(),q=function(){"use strict";function c(c){var e,f,g,h=this;c=c||{},c.menu||a.error("menu is required"),this.isOpen=!1,this.isEmpty=!0,this.datasets=b.map(c.datasets,d),e=b.bind(this._onSuggestionClick,this),f=b.bind(this._onSuggestionMouseEnter,this),g=b.bind(this._onSuggestionMouseLeave,this),this.$menu=a(c.menu).on("click.tt",".tt-suggestion",e).on("mouseenter.tt",".tt-suggestion",f).on("mouseleave.tt",".tt-suggestion",g),b.each(this.datasets,function(a){h.$menu.append(a.getRoot()),a.onSync("rendered",h._onRendered,h)})}function d(a){return new p(a)}return b.mixin(c.prototype,m,{_onSuggestionClick:function(b){this.trigger("suggestionClicked",a(b.currentTarget))},_onSuggestionMouseEnter:function(b){this._removeCursor(),this._setCursor(a(b.currentTarget),!0)},_onSuggestionMouseLeave:function(){this._removeCursor()},_onRendered:function(){function a(a){return a.isEmpty()}this.isEmpty=b.every(this.datasets,a),this.isEmpty?this._hide():this.isOpen&&this._show(),this.trigger("datasetRendered")},_hide:function(){this.$menu.hide()},_show:function(){this.$menu.css("display","block")},_getSuggestions:function(){return this.$menu.find(".tt-suggestion")},_getCursor:function(){return this.$menu.find(".tt-cursor").first()},_setCursor:function(a,b){a.first().addClass("tt-cursor"),!b&&this.trigger("cursorMoved")},_removeCursor:function(){this._getCursor().removeClass("tt-cursor")},_moveCursor:function(a){var b,c,d,e;if(this.isOpen){if(c=this._getCursor(),b=this._getSuggestions(),this._removeCursor(),d=b.index(c)+a,d=(d+1)%(b.length+1)-1,-1===d)return void this.trigger("cursorRemoved");-1>d&&(d=b.length-1),this._setCursor(e=b.eq(d)),this._ensureVisible(e)}},_ensureVisible:function(a){var b,c,d,e;b=a.position().top,c=b+a.outerHeight(!0),d=this.$menu.scrollTop(),e=this.$menu.height()+parseInt(this.$menu.css("paddingTop"),10)+parseInt(this.$menu.css("paddingBottom"),10),0>b?this.$menu.scrollTop(d+b):c>e&&this.$menu.scrollTop(d+(c-e))},close:function(){this.isOpen&&(this.isOpen=!1,this._removeCursor(),this._hide(),this.trigger("closed"))},open:function(){this.isOpen||(this.isOpen=!0,!this.isEmpty&&this._show(),this.trigger("opened"))},setLanguageDirection:function(a){this.$menu.css("ltr"===a?k.ltr:k.rtl)},moveCursorUp:function(){this._moveCursor(-1)},moveCursorDown:function(){this._moveCursor(1)},getDatumForSuggestion:function(a){var b=null;return a.length&&(b={raw:p.extractDatum(a),value:p.extractValue(a),datasetName:p.extractDatasetName(a)}),b},getDatumForCursor:function(){return this.getDatumForSuggestion(this._getCursor().first())},getDatumForTopSuggestion:function(){return this.getDatumForSuggestion(this._getSuggestions().first())},update:function(a){function c(b){b.update(a)}b.each(this.datasets,c)},empty:function(){function a(a){a.clear()}b.each(this.datasets,a),this.isEmpty=!0},isVisible:function(){return this.isOpen&&!this.isEmpty},destroy:function(){function a(a){a.destroy()}this.$menu.off(".tt"),this.$menu=null,b.each(this.datasets,a)}}),c}(),r=function(){"use strict";function c(c){var e,f,g;c=c||{},c.input||a.error("missing input"),this.isActivated=!1,this.autoselect=!!c.autoselect,this.minLength=b.isNumber(c.minLength)?c.minLength:1,this.$node=d(c.input,c.withHint),e=this.$node.find(".tt-dropdown-menu"),f=this.$node.find(".tt-input"),g=this.$node.find(".tt-hint"),f.on("blur.tt",function(a){var c,d,g;c=document.activeElement,d=e.is(c),g=e.has(c).length>0,b.isMsie()&&(d||g)&&(a.preventDefault(),a.stopImmediatePropagation(),b.defer(function(){f.focus()}))}),e.on("mousedown.tt",function(a){a.preventDefault()}),this.eventBus=c.eventBus||new l({el:f}),this.dropdown=new q({menu:e,datasets:c.datasets}).onSync("suggestionClicked",this._onSuggestionClicked,this).onSync("cursorMoved",this._onCursorMoved,this).onSync("cursorRemoved",this._onCursorRemoved,this).onSync("opened",this._onOpened,this).onSync("closed",this._onClosed,this).onAsync("datasetRendered",this._onDatasetRendered,this),this.input=new o({input:f,hint:g}).onSync("focused",this._onFocused,this).onSync("blurred",this._onBlurred,this).onSync("enterKeyed",this._onEnterKeyed,this).onSync("tabKeyed",this._onTabKeyed,this).onSync("escKeyed",this._onEscKeyed,this).onSync("upKeyed",this._onUpKeyed,this).onSync("downKeyed",this._onDownKeyed,this).onSync("leftKeyed",this._onLeftKeyed,this).onSync("rightKeyed",this._onRightKeyed,this).onSync("queryChanged",this._onQueryChanged,this).onSync("whitespaceChanged",this._onWhitespaceChanged,this),this._setLanguageDirection()}function d(b,c){var d,f,h,i;d=a(b),f=a(j.wrapper).css(k.wrapper),h=a(j.dropdown).css(k.dropdown),i=d.clone().css(k.hint).css(e(d)),i.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly",!0).attr({autocomplete:"off",spellcheck:"false",tabindex:-1}),d.data(g,{dir:d.attr("dir"),autocomplete:d.attr("autocomplete"),spellcheck:d.attr("spellcheck"),style:d.attr("style")}),d.addClass("tt-input").attr({autocomplete:"off",spellcheck:!1}).css(c?k.input:k.inputWithNoHint);try{!d.attr("dir")&&d.attr("dir","auto")}catch(l){}return d.wrap(f).parent().prepend(c?i:null).append(h)}function e(a){return{backgroundAttachment:a.css("background-attachment"),backgroundClip:a.css("background-clip"),backgroundColor:a.css("background-color"),backgroundImage:a.css("background-image"),backgroundOrigin:a.css("background-origin"),backgroundPosition:a.css("background-position"),backgroundRepeat:a.css("background-repeat"),backgroundSize:a.css("background-size")}}function f(a){var c=a.find(".tt-input");b.each(c.data(g),function(a,d){b.isUndefined(a)?c.removeAttr(d):c.attr(d,a)}),c.detach().removeData(g).removeClass("tt-input").insertAfter(a),a.remove()}var g="ttAttrs";return b.mixin(c.prototype,{_onSuggestionClicked:function(a,b){var c;(c=this.dropdown.getDatumForSuggestion(b))&&this._select(c)},_onCursorMoved:function(){var a=this.dropdown.getDatumForCursor();this.input.setInputValue(a.value,!0),this.eventBus.trigger("cursorchanged",a.raw,a.datasetName)},_onCursorRemoved:function(){this.input.resetInputValue(),this._updateHint()},_onDatasetRendered:function(){this._updateHint()},_onOpened:function(){this._updateHint(),this.eventBus.trigger("opened")},_onClosed:function(){this.input.clearHint(),this.eventBus.trigger("closed")},_onFocused:function(){this.isActivated=!0,this.dropdown.open()},_onBlurred:function(){this.isActivated=!1,this.dropdown.empty(),this.dropdown.close()},_onEnterKeyed:function(a,b){var c,d;c=this.dropdown.getDatumForCursor(),d=this.dropdown.getDatumForTopSuggestion(),c?(this._select(c),b.preventDefault()):this.autoselect&&d&&(this._select(d),b.preventDefault())},_onTabKeyed:function(a,b){var c;(c=this.dropdown.getDatumForCursor())?(this._select(c),b.preventDefault()):this._autocomplete(!0)},_onEscKeyed:function(){this.dropdown.close(),this.input.resetInputValue()},_onUpKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorUp(),this.dropdown.open()},_onDownKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorDown(),this.dropdown.open()},_onLeftKeyed:function(){"rtl"===this.dir&&this._autocomplete()},_onRightKeyed:function(){"ltr"===this.dir&&this._autocomplete()},_onQueryChanged:function(a,b){this.input.clearHintIfInvalid(),b.length>=this.minLength?this.dropdown.update(b):this.dropdown.empty(),this.dropdown.open(),this._setLanguageDirection()},_onWhitespaceChanged:function(){this._updateHint(),this.dropdown.open()},_setLanguageDirection:function(){var a;this.dir!==(a=this.input.getLanguageDirection())&&(this.dir=a,this.$node.css("direction",a),this.dropdown.setLanguageDirection(a))},_updateHint:function(){var a,c,d,e,f,g;a=this.dropdown.getDatumForTopSuggestion(),a&&this.dropdown.isVisible()&&!this.input.hasOverflow()?(c=this.input.getInputValue(),d=o.normalizeQuery(c),e=b.escapeRegExChars(d),f=new RegExp("^(?:"+e+")(.+$)","i"),g=f.exec(a.value),g?this.input.setHint(c+g[1]):this.input.clearHint()):this.input.clearHint()},_autocomplete:function(a){var b,c,d,e;b=this.input.getHint(),c=this.input.getQuery(),d=a||this.input.isCursorAtEnd(),b&&c!==b&&d&&(e=this.dropdown.getDatumForTopSuggestion(),e&&this.input.setInputValue(e.value),this.eventBus.trigger("autocompleted",e.raw,e.datasetName))},_select:function(a){this.input.setQuery(a.value),this.input.setInputValue(a.value,!0),this._setLanguageDirection(),this.eventBus.trigger("selected",a.raw,a.datasetName),this.dropdown.close(),b.defer(b.bind(this.dropdown.empty,this.dropdown))},open:function(){this.dropdown.open()},close:function(){this.dropdown.close()},setVal:function(a){a=b.toStr(a),this.isActivated?this.input.setInputValue(a):(this.input.setQuery(a),this.input.setInputValue(a,!0)),this._setLanguageDirection()},getVal:function(){return this.input.getQuery()},destroy:function(){this.input.destroy(),this.dropdown.destroy(),f(this.$node),this.$node=null}}),c}();!function(){"use strict";var c,d,e;c=a.fn.typeahead,d="ttTypeahead",e={initialize:function(c,e){function f(){var f,g,h=a(this);b.each(e,function(a){a.highlight=!!c.highlight}),g=new r({input:h,eventBus:f=new l({el:h}),withHint:b.isUndefined(c.hint)?!0:!!c.hint,minLength:c.minLength,autoselect:c.autoselect,datasets:e}),h.data(d,g)}return e=b.isArray(e)?e:[].slice.call(arguments,1),c=c||{},this.each(f)},open:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.open()}return this.each(b)},close:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.close()}return this.each(b)},val:function(b){function c(){var c,e=a(this);(c=e.data(d))&&c.setVal(b)}function e(a){var b,c;return(b=a.data(d))&&(c=b.getVal()),c}return arguments.length?this.each(c):e(this.first())},destroy:function(){function b(){var b,c=a(this);(b=c.data(d))&&(b.destroy(),c.removeData(d))}return this.each(b)}},a.fn.typeahead=function(b){var c;return e[b]&&"initialize"!==b?(c=this.filter(function(){return!!a(this).data(d)}),e[b].apply(c,[].slice.call(arguments,1))):e.initialize.apply(this,arguments)},a.fn.typeahead.noConflict=function(){return a.fn.typeahead=c,this}}()}(window.jQuery);PK Q4Kx> > cite2c/nbext/typeahead.jquery.js/*!
* typeahead.js 0.10.5
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/
(function($) {
var _ = function() {
"use strict";
return {
isMsie: function() {
return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
},
isBlankString: function(str) {
return !str || /^\s*$/.test(str);
},
escapeRegExChars: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isString: function(obj) {
return typeof obj === "string";
},
isNumber: function(obj) {
return typeof obj === "number";
},
isArray: $.isArray,
isFunction: $.isFunction,
isObject: $.isPlainObject,
isUndefined: function(obj) {
return typeof obj === "undefined";
},
toStr: function toStr(s) {
return _.isUndefined(s) || s === null ? "" : s + "";
},
bind: $.proxy,
each: function(collection, cb) {
$.each(collection, reverseArgs);
function reverseArgs(index, value) {
return cb(value, index);
}
},
map: $.map,
filter: $.grep,
every: function(obj, test) {
var result = true;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
}
});
return !!result;
},
some: function(obj, test) {
var result = false;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
}
});
return !!result;
},
mixin: $.extend,
getUniqueId: function() {
var counter = 0;
return function() {
return counter++;
};
}(),
templatify: function templatify(obj) {
return $.isFunction(obj) ? obj : template;
function template() {
return String(obj);
}
},
defer: function(fn) {
setTimeout(fn, 0);
},
debounce: function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments, later, callNow;
later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
throttle: function(func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
noop: function() {}
};
}();
var html = function() {
return {
wrapper: '',
dropdown: '',
dataset: '',
suggestions: '',
suggestion: ''
};
}();
var css = function() {
"use strict";
var css = {
wrapper: {
position: "relative",
display: "inline-block"
},
hint: {
position: "absolute",
top: "0",
left: "0",
borderColor: "transparent",
boxShadow: "none",
opacity: "1"
},
input: {
position: "relative",
verticalAlign: "top",
backgroundColor: "transparent"
},
inputWithNoHint: {
position: "relative",
verticalAlign: "top"
},
dropdown: {
position: "absolute",
top: "100%",
left: "0",
zIndex: "100",
display: "none"
},
suggestions: {
display: "block"
},
suggestion: {
whiteSpace: "nowrap",
cursor: "pointer"
},
suggestionChild: {
whiteSpace: "normal"
},
ltr: {
left: "0",
right: "auto"
},
rtl: {
left: "auto",
right: " 0"
}
};
if (_.isMsie()) {
_.mixin(css.input, {
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
});
}
if (_.isMsie() && _.isMsie() <= 7) {
_.mixin(css.input, {
marginTop: "-1px"
});
}
return css;
}();
var EventBus = function() {
"use strict";
var namespace = "typeahead:";
function EventBus(o) {
if (!o || !o.el) {
$.error("EventBus initialized without el");
}
this.$el = $(o.el);
}
_.mixin(EventBus.prototype, {
trigger: function(type) {
var args = [].slice.call(arguments, 1);
this.$el.trigger(namespace + type, args);
}
});
return EventBus;
}();
var EventEmitter = function() {
"use strict";
var splitter = /\s+/, nextTick = getNextTick();
return {
onSync: onSync,
onAsync: onAsync,
off: off,
trigger: trigger
};
function on(method, types, cb, context) {
var type;
if (!cb) {
return this;
}
types = types.split(splitter);
cb = context ? bindContext(cb, context) : cb;
this._callbacks = this._callbacks || {};
while (type = types.shift()) {
this._callbacks[type] = this._callbacks[type] || {
sync: [],
async: []
};
this._callbacks[type][method].push(cb);
}
return this;
}
function onAsync(types, cb, context) {
return on.call(this, "async", types, cb, context);
}
function onSync(types, cb, context) {
return on.call(this, "sync", types, cb, context);
}
function off(types) {
var type;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
while (type = types.shift()) {
delete this._callbacks[type];
}
return this;
}
function trigger(types) {
var type, callbacks, args, syncFlush, asyncFlush;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
args = [].slice.call(arguments, 1);
while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
syncFlush() && nextTick(asyncFlush);
}
return this;
}
function getFlush(callbacks, context, args) {
return flush;
function flush() {
var cancelled;
for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
cancelled = callbacks[i].apply(context, args) === false;
}
return !cancelled;
}
}
function getNextTick() {
var nextTickFn;
if (window.setImmediate) {
nextTickFn = function nextTickSetImmediate(fn) {
setImmediate(function() {
fn();
});
};
} else {
nextTickFn = function nextTickSetTimeout(fn) {
setTimeout(function() {
fn();
}, 0);
};
}
return nextTickFn;
}
function bindContext(fn, context) {
return fn.bind ? fn.bind(context) : function() {
fn.apply(context, [].slice.call(arguments, 0));
};
}
}();
var highlight = function(doc) {
"use strict";
var defaults = {
node: null,
pattern: null,
tagName: "strong",
className: null,
wordsOnly: false,
caseSensitive: false
};
return function hightlight(o) {
var regex;
o = _.mixin({}, defaults, o);
if (!o.node || !o.pattern) {
return;
}
o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
traverse(o.node, hightlightTextNode);
function hightlightTextNode(textNode) {
var match, patternNode, wrapperNode;
if (match = regex.exec(textNode.data)) {
wrapperNode = doc.createElement(o.tagName);
o.className && (wrapperNode.className = o.className);
patternNode = textNode.splitText(match.index);
patternNode.splitText(match[0].length);
wrapperNode.appendChild(patternNode.cloneNode(true));
textNode.parentNode.replaceChild(wrapperNode, patternNode);
}
return !!match;
}
function traverse(el, hightlightTextNode) {
var childNode, TEXT_NODE_TYPE = 3;
for (var i = 0; i < el.childNodes.length; i++) {
childNode = el.childNodes[i];
if (childNode.nodeType === TEXT_NODE_TYPE) {
i += hightlightTextNode(childNode) ? 1 : 0;
} else {
traverse(childNode, hightlightTextNode);
}
}
}
};
function getRegex(patterns, caseSensitive, wordsOnly) {
var escapedPatterns = [], regexStr;
for (var i = 0, len = patterns.length; i < len; i++) {
escapedPatterns.push(_.escapeRegExChars(patterns[i]));
}
regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
}
}(window.document);
var Input = function() {
"use strict";
var specialKeyCodeMap;
specialKeyCodeMap = {
9: "tab",
27: "esc",
37: "left",
39: "right",
13: "enter",
38: "up",
40: "down"
};
function Input(o) {
var that = this, onBlur, onFocus, onKeydown, onInput;
o = o || {};
if (!o.input) {
$.error("input is missing");
}
onBlur = _.bind(this._onBlur, this);
onFocus = _.bind(this._onFocus, this);
onKeydown = _.bind(this._onKeydown, this);
onInput = _.bind(this._onInput, this);
this.$hint = $(o.hint);
this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
if (this.$hint.length === 0) {
this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
}
if (!_.isMsie()) {
this.$input.on("input.tt", onInput);
} else {
this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
if (specialKeyCodeMap[$e.which || $e.keyCode]) {
return;
}
_.defer(_.bind(that._onInput, that, $e));
});
}
this.query = this.$input.val();
this.$overflowHelper = buildOverflowHelper(this.$input);
}
Input.normalizeQuery = function(str) {
return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
};
_.mixin(Input.prototype, EventEmitter, {
_onBlur: function onBlur() {
this.resetInputValue();
this.trigger("blurred");
},
_onFocus: function onFocus() {
this.trigger("focused");
},
_onKeydown: function onKeydown($e) {
var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
this._managePreventDefault(keyName, $e);
if (keyName && this._shouldTrigger(keyName, $e)) {
this.trigger(keyName + "Keyed", $e);
}
},
_onInput: function onInput() {
this._checkInputValue();
},
_managePreventDefault: function managePreventDefault(keyName, $e) {
var preventDefault, hintValue, inputValue;
switch (keyName) {
case "tab":
hintValue = this.getHint();
inputValue = this.getInputValue();
preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
break;
case "up":
case "down":
preventDefault = !withModifier($e);
break;
default:
preventDefault = false;
}
preventDefault && $e.preventDefault();
},
_shouldTrigger: function shouldTrigger(keyName, $e) {
var trigger;
switch (keyName) {
case "tab":
trigger = !withModifier($e);
break;
default:
trigger = true;
}
return trigger;
},
_checkInputValue: function checkInputValue() {
var inputValue, areEquivalent, hasDifferentWhitespace;
inputValue = this.getInputValue();
areEquivalent = areQueriesEquivalent(inputValue, this.query);
hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
this.query = inputValue;
if (!areEquivalent) {
this.trigger("queryChanged", this.query);
} else if (hasDifferentWhitespace) {
this.trigger("whitespaceChanged", this.query);
}
},
focus: function focus() {
this.$input.focus();
},
blur: function blur() {
this.$input.blur();
},
getQuery: function getQuery() {
return this.query;
},
setQuery: function setQuery(query) {
this.query = query;
},
getInputValue: function getInputValue() {
return this.$input.val();
},
setInputValue: function setInputValue(value, silent) {
this.$input.val(value);
silent ? this.clearHint() : this._checkInputValue();
},
resetInputValue: function resetInputValue() {
this.setInputValue(this.query, true);
},
getHint: function getHint() {
return this.$hint.val();
},
setHint: function setHint(value) {
this.$hint.val(value);
},
clearHint: function clearHint() {
this.setHint("");
},
clearHintIfInvalid: function clearHintIfInvalid() {
var val, hint, valIsPrefixOfHint, isValid;
val = this.getInputValue();
hint = this.getHint();
valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
!isValid && this.clearHint();
},
getLanguageDirection: function getLanguageDirection() {
return (this.$input.css("direction") || "ltr").toLowerCase();
},
hasOverflow: function hasOverflow() {
var constraint = this.$input.width() - 2;
this.$overflowHelper.text(this.getInputValue());
return this.$overflowHelper.width() >= constraint;
},
isCursorAtEnd: function() {
var valueLength, selectionStart, range;
valueLength = this.$input.val().length;
selectionStart = this.$input[0].selectionStart;
if (_.isNumber(selectionStart)) {
return selectionStart === valueLength;
} else if (document.selection) {
range = document.selection.createRange();
range.moveStart("character", -valueLength);
return valueLength === range.text.length;
}
return true;
},
destroy: function destroy() {
this.$hint.off(".tt");
this.$input.off(".tt");
this.$hint = this.$input = this.$overflowHelper = null;
}
});
return Input;
function buildOverflowHelper($input) {
return $('').css({
position: "absolute",
visibility: "hidden",
whiteSpace: "pre",
fontFamily: $input.css("font-family"),
fontSize: $input.css("font-size"),
fontStyle: $input.css("font-style"),
fontVariant: $input.css("font-variant"),
fontWeight: $input.css("font-weight"),
wordSpacing: $input.css("word-spacing"),
letterSpacing: $input.css("letter-spacing"),
textIndent: $input.css("text-indent"),
textRendering: $input.css("text-rendering"),
textTransform: $input.css("text-transform")
}).insertAfter($input);
}
function areQueriesEquivalent(a, b) {
return Input.normalizeQuery(a) === Input.normalizeQuery(b);
}
function withModifier($e) {
return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
}
}();
var Dataset = function() {
"use strict";
var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
function Dataset(o) {
o = o || {};
o.templates = o.templates || {};
if (!o.source) {
$.error("missing source");
}
if (o.name && !isValidName(o.name)) {
$.error("invalid dataset name: " + o.name);
}
this.query = null;
this.highlight = !!o.highlight;
this.name = o.name || _.getUniqueId();
this.source = o.source;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.templates = getTemplates(o.templates, this.displayFn);
this.$el = $(html.dataset.replace("%CLASS%", this.name));
}
Dataset.extractDatasetName = function extractDatasetName(el) {
return $(el).data(datasetKey);
};
Dataset.extractValue = function extractDatum(el) {
return $(el).data(valueKey);
};
Dataset.extractDatum = function extractDatum(el) {
return $(el).data(datumKey);
};
_.mixin(Dataset.prototype, EventEmitter, {
_render: function render(query, suggestions) {
if (!this.$el) {
return;
}
var that = this, hasSuggestions;
this.$el.empty();
hasSuggestions = suggestions && suggestions.length;
if (!hasSuggestions && this.templates.empty) {
this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
} else if (hasSuggestions) {
this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
}
this.trigger("rendered");
function getEmptyHtml() {
return that.templates.empty({
query: query,
isEmpty: true
});
}
function getSuggestionsHtml() {
var $suggestions, nodes;
$suggestions = $(html.suggestions).css(css.suggestions);
nodes = _.map(suggestions, getSuggestionNode);
$suggestions.append.apply($suggestions, nodes);
that.highlight && highlight({
className: "tt-highlight",
node: $suggestions[0],
pattern: query
});
return $suggestions;
function getSuggestionNode(suggestion) {
var $el;
$el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
$el.children().each(function() {
$(this).css(css.suggestionChild);
});
return $el;
}
}
function getHeaderHtml() {
return that.templates.header({
query: query,
isEmpty: !hasSuggestions
});
}
function getFooterHtml() {
return that.templates.footer({
query: query,
isEmpty: !hasSuggestions
});
}
},
getRoot: function getRoot() {
return this.$el;
},
update: function update(query) {
var that = this;
this.query = query;
this.canceled = false;
this.source(query, render);
function render(suggestions) {
if (!that.canceled && query === that.query) {
that._render(query, suggestions);
}
}
},
cancel: function cancel() {
this.canceled = true;
},
clear: function clear() {
this.cancel();
this.$el.empty();
this.trigger("rendered");
},
isEmpty: function isEmpty() {
return this.$el.is(":empty");
},
destroy: function destroy() {
this.$el = null;
}
});
return Dataset;
function getDisplayFn(display) {
display = display || "value";
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) {
return obj[display];
}
}
function getTemplates(templates, displayFn) {
return {
empty: templates.empty && _.templatify(templates.empty),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return "
" + displayFn(context) + "
";
}
}
function isValidName(str) {
return /^[_a-zA-Z0-9-]+$/.test(str);
}
}();
var Dropdown = function() {
"use strict";
function Dropdown(o) {
var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
o = o || {};
if (!o.menu) {
$.error("menu is required");
}
this.isOpen = false;
this.isEmpty = true;
this.datasets = _.map(o.datasets, initializeDataset);
onSuggestionClick = _.bind(this._onSuggestionClick, this);
onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
_.each(this.datasets, function(dataset) {
that.$menu.append(dataset.getRoot());
dataset.onSync("rendered", that._onRendered, that);
});
}
_.mixin(Dropdown.prototype, EventEmitter, {
_onSuggestionClick: function onSuggestionClick($e) {
this.trigger("suggestionClicked", $($e.currentTarget));
},
_onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
this._removeCursor();
this._setCursor($($e.currentTarget), true);
},
_onSuggestionMouseLeave: function onSuggestionMouseLeave() {
this._removeCursor();
},
_onRendered: function onRendered() {
this.isEmpty = _.every(this.datasets, isDatasetEmpty);
this.isEmpty ? this._hide() : this.isOpen && this._show();
this.trigger("datasetRendered");
function isDatasetEmpty(dataset) {
return dataset.isEmpty();
}
},
_hide: function() {
this.$menu.hide();
},
_show: function() {
this.$menu.css("display", "block");
},
_getSuggestions: function getSuggestions() {
return this.$menu.find(".tt-suggestion");
},
_getCursor: function getCursor() {
return this.$menu.find(".tt-cursor").first();
},
_setCursor: function setCursor($el, silent) {
$el.first().addClass("tt-cursor");
!silent && this.trigger("cursorMoved");
},
_removeCursor: function removeCursor() {
this._getCursor().removeClass("tt-cursor");
},
_moveCursor: function moveCursor(increment) {
var $suggestions, $oldCursor, newCursorIndex, $newCursor;
if (!this.isOpen) {
return;
}
$oldCursor = this._getCursor();
$suggestions = this._getSuggestions();
this._removeCursor();
newCursorIndex = $suggestions.index($oldCursor) + increment;
newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
if (newCursorIndex === -1) {
this.trigger("cursorRemoved");
return;
} else if (newCursorIndex < -1) {
newCursorIndex = $suggestions.length - 1;
}
this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
this._ensureVisible($newCursor);
},
_ensureVisible: function ensureVisible($el) {
var elTop, elBottom, menuScrollTop, menuHeight;
elTop = $el.position().top;
elBottom = elTop + $el.outerHeight(true);
menuScrollTop = this.$menu.scrollTop();
menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
if (elTop < 0) {
this.$menu.scrollTop(menuScrollTop + elTop);
} else if (menuHeight < elBottom) {
this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
}
},
close: function close() {
if (this.isOpen) {
this.isOpen = false;
this._removeCursor();
this._hide();
this.trigger("closed");
}
},
open: function open() {
if (!this.isOpen) {
this.isOpen = true;
!this.isEmpty && this._show();
this.trigger("opened");
}
},
setLanguageDirection: function setLanguageDirection(dir) {
this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
},
moveCursorUp: function moveCursorUp() {
this._moveCursor(-1);
},
moveCursorDown: function moveCursorDown() {
this._moveCursor(+1);
},
getDatumForSuggestion: function getDatumForSuggestion($el) {
var datum = null;
if ($el.length) {
datum = {
raw: Dataset.extractDatum($el),
value: Dataset.extractValue($el),
datasetName: Dataset.extractDatasetName($el)
};
}
return datum;
},
getDatumForCursor: function getDatumForCursor() {
return this.getDatumForSuggestion(this._getCursor().first());
},
getDatumForTopSuggestion: function getDatumForTopSuggestion() {
return this.getDatumForSuggestion(this._getSuggestions().first());
},
update: function update(query) {
_.each(this.datasets, updateDataset);
function updateDataset(dataset) {
dataset.update(query);
}
},
empty: function empty() {
_.each(this.datasets, clearDataset);
this.isEmpty = true;
function clearDataset(dataset) {
dataset.clear();
}
},
isVisible: function isVisible() {
return this.isOpen && !this.isEmpty;
},
destroy: function destroy() {
this.$menu.off(".tt");
this.$menu = null;
_.each(this.datasets, destroyDataset);
function destroyDataset(dataset) {
dataset.destroy();
}
}
});
return Dropdown;
function initializeDataset(oDataset) {
return new Dataset(oDataset);
}
}();
var Typeahead = function() {
"use strict";
var attrsKey = "ttAttrs";
function Typeahead(o) {
var $menu, $input, $hint;
o = o || {};
if (!o.input) {
$.error("missing input");
}
this.isActivated = false;
this.autoselect = !!o.autoselect;
this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
this.$node = buildDom(o.input, o.withHint);
$menu = this.$node.find(".tt-dropdown-menu");
$input = this.$node.find(".tt-input");
$hint = this.$node.find(".tt-hint");
$input.on("blur.tt", function($e) {
var active, isActive, hasActive;
active = document.activeElement;
isActive = $menu.is(active);
hasActive = $menu.has(active).length > 0;
if (_.isMsie() && (isActive || hasActive)) {
$e.preventDefault();
$e.stopImmediatePropagation();
_.defer(function() {
$input.focus();
});
}
});
$menu.on("mousedown.tt", function($e) {
$e.preventDefault();
});
this.eventBus = o.eventBus || new EventBus({
el: $input
});
this.dropdown = new Dropdown({
menu: $menu,
datasets: o.datasets
}).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
this.input = new Input({
input: $input,
hint: $hint
}).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
this._setLanguageDirection();
}
_.mixin(Typeahead.prototype, {
_onSuggestionClicked: function onSuggestionClicked(type, $el) {
var datum;
if (datum = this.dropdown.getDatumForSuggestion($el)) {
this._select(datum);
}
},
_onCursorMoved: function onCursorMoved() {
var datum = this.dropdown.getDatumForCursor();
this.input.setInputValue(datum.value, true);
this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
},
_onCursorRemoved: function onCursorRemoved() {
this.input.resetInputValue();
this._updateHint();
},
_onDatasetRendered: function onDatasetRendered() {
this._updateHint();
},
_onOpened: function onOpened() {
this._updateHint();
this.eventBus.trigger("opened");
},
_onClosed: function onClosed() {
this.input.clearHint();
this.eventBus.trigger("closed");
},
_onFocused: function onFocused() {
this.isActivated = true;
this.dropdown.open();
},
_onBlurred: function onBlurred() {
this.isActivated = false;
this.dropdown.empty();
this.dropdown.close();
},
_onEnterKeyed: function onEnterKeyed(type, $e) {
var cursorDatum, topSuggestionDatum;
cursorDatum = this.dropdown.getDatumForCursor();
topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
if (cursorDatum) {
this._select(cursorDatum);
$e.preventDefault();
} else if (this.autoselect && topSuggestionDatum) {
this._select(topSuggestionDatum);
$e.preventDefault();
}
},
_onTabKeyed: function onTabKeyed(type, $e) {
var datum;
if (datum = this.dropdown.getDatumForCursor()) {
this._select(datum);
$e.preventDefault();
} else {
this._autocomplete(true);
}
},
_onEscKeyed: function onEscKeyed() {
this.dropdown.close();
this.input.resetInputValue();
},
_onUpKeyed: function onUpKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
this.dropdown.open();
},
_onDownKeyed: function onDownKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
this.dropdown.open();
},
_onLeftKeyed: function onLeftKeyed() {
this.dir === "rtl" && this._autocomplete();
},
_onRightKeyed: function onRightKeyed() {
this.dir === "ltr" && this._autocomplete();
},
_onQueryChanged: function onQueryChanged(e, query) {
this.input.clearHintIfInvalid();
query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
this.dropdown.open();
this._setLanguageDirection();
},
_onWhitespaceChanged: function onWhitespaceChanged() {
this._updateHint();
this.dropdown.open();
},
_setLanguageDirection: function setLanguageDirection() {
var dir;
if (this.dir !== (dir = this.input.getLanguageDirection())) {
this.dir = dir;
this.$node.css("direction", dir);
this.dropdown.setLanguageDirection(dir);
}
},
_updateHint: function updateHint() {
var datum, val, query, escapedQuery, frontMatchRegEx, match;
datum = this.dropdown.getDatumForTopSuggestion();
if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
val = this.input.getInputValue();
query = Input.normalizeQuery(val);
escapedQuery = _.escapeRegExChars(query);
frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
match = frontMatchRegEx.exec(datum.value);
match ? this.input.setHint(val + match[1]) : this.input.clearHint();
} else {
this.input.clearHint();
}
},
_autocomplete: function autocomplete(laxCursor) {
var hint, query, isCursorAtEnd, datum;
hint = this.input.getHint();
query = this.input.getQuery();
isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
if (hint && query !== hint && isCursorAtEnd) {
datum = this.dropdown.getDatumForTopSuggestion();
datum && this.input.setInputValue(datum.value);
this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
}
},
_select: function select(datum) {
this.input.setQuery(datum.value);
this.input.setInputValue(datum.value, true);
this._setLanguageDirection();
this.eventBus.trigger("selected", datum.raw, datum.datasetName);
this.dropdown.close();
_.defer(_.bind(this.dropdown.empty, this.dropdown));
},
open: function open() {
this.dropdown.open();
},
close: function close() {
this.dropdown.close();
},
setVal: function setVal(val) {
val = _.toStr(val);
if (this.isActivated) {
this.input.setInputValue(val);
} else {
this.input.setQuery(val);
this.input.setInputValue(val, true);
}
this._setLanguageDirection();
},
getVal: function getVal() {
return this.input.getQuery();
},
destroy: function destroy() {
this.input.destroy();
this.dropdown.destroy();
destroyDomStructure(this.$node);
this.$node = null;
}
});
return Typeahead;
function buildDom(input, withHint) {
var $input, $wrapper, $dropdown, $hint;
$input = $(input);
$wrapper = $(html.wrapper).css(css.wrapper);
$dropdown = $(html.dropdown).css(css.dropdown);
$hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
$hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
autocomplete: "off",
spellcheck: "false",
tabindex: -1
});
$input.data(attrsKey, {
dir: $input.attr("dir"),
autocomplete: $input.attr("autocomplete"),
spellcheck: $input.attr("spellcheck"),
style: $input.attr("style")
});
$input.addClass("tt-input").attr({
autocomplete: "off",
spellcheck: false
}).css(withHint ? css.input : css.inputWithNoHint);
try {
!$input.attr("dir") && $input.attr("dir", "auto");
} catch (e) {}
return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
}
function getBackgroundStyles($el) {
return {
backgroundAttachment: $el.css("background-attachment"),
backgroundClip: $el.css("background-clip"),
backgroundColor: $el.css("background-color"),
backgroundImage: $el.css("background-image"),
backgroundOrigin: $el.css("background-origin"),
backgroundPosition: $el.css("background-position"),
backgroundRepeat: $el.css("background-repeat"),
backgroundSize: $el.css("background-size")
};
}
function destroyDomStructure($node) {
var $input = $node.find(".tt-input");
_.each($input.data(attrsKey), function(val, key) {
_.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
});
$input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
$node.remove();
}
}();
(function() {
"use strict";
var old, typeaheadKey, methods;
old = $.fn.typeahead;
typeaheadKey = "ttTypeahead";
methods = {
initialize: function initialize(o, datasets) {
datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
o = o || {};
return this.each(attach);
function attach() {
var $input = $(this), eventBus, typeahead;
_.each(datasets, function(d) {
d.highlight = !!o.highlight;
});
typeahead = new Typeahead({
input: $input,
eventBus: eventBus = new EventBus({
el: $input
}),
withHint: _.isUndefined(o.hint) ? true : !!o.hint,
minLength: o.minLength,
autoselect: o.autoselect,
datasets: datasets
});
$input.data(typeaheadKey, typeahead);
}
},
open: function open() {
return this.each(openTypeahead);
function openTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.open();
}
}
},
close: function close() {
return this.each(closeTypeahead);
function closeTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.close();
}
}
},
val: function val(newVal) {
return !arguments.length ? getVal(this.first()) : this.each(setVal);
function setVal() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.setVal(newVal);
}
}
function getVal($input) {
var typeahead, query;
if (typeahead = $input.data(typeaheadKey)) {
query = typeahead.getVal();
}
return query;
}
},
destroy: function destroy() {
return this.each(unattach);
function unattach() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.destroy();
$input.removeData(typeaheadKey);
}
}
}
};
$.fn.typeahead = function(method) {
var tts;
if (methods[method] && method !== "initialize") {
tts = this.filter(function() {
return !!$(this).data(typeaheadKey);
});
return methods[method].apply(tts, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
};
$.fn.typeahead.noConflict = function noConflict() {
$.fn.typeahead = old;
return this;
};
})();
})(window.jQuery);PK Q4KH4 4 cite2c/nbext/xmldom.jsif ("undefined" === typeof CSL_IS_IE) {
var CSL_IS_IE;
};
var CSL_CHROME = function () {
if ("undefined" == typeof DOMParser || CSL_IS_IE) {
CSL_IS_IE = true;
DOMParser = function() {};
DOMParser.prototype.parseFromString = function(str, contentType) {
if ("undefined" != typeof ActiveXObject) {
var xmldata = new ActiveXObject('MSXML.DomDocument');
xmldata.async = false;
xmldata.loadXML(str);
return xmldata;
} else if ("undefined" != typeof XMLHttpRequest) {
var xmldata = new XMLHttpRequest;
if (!contentType) {
contentType = 'text/xml';
}
xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);
if(xmldata.overrideMimeType) {
xmldata.overrideMimeType(contentType);
}
xmldata.send(null);
return xmldata.responseXML;
}
};
this.hasAttributes = function (node) {
var ret;
if (node.attributes && node.attributes.length) {
ret = true;
} else {
ret = false;
}
return ret;
};
} else {
this.hasAttributes = function (node) {
var ret;
if (node.attributes && node.attributes.length) {
ret = true;
} else {
ret = false;
}
return ret;
};
}
this.importNode = function (doc, srcElement) {
if ("undefined" == typeof doc.importNode) {
var ret = this._importNode(doc, srcElement, true);
} else {
var ret = doc.importNode(srcElement, true);
}
return ret;
};
this._importNode = function(doc, node, allChildren) {
switch (node.nodeType) {
case 1:
var newNode = doc.createElement(node.nodeName);
if (node.attributes && node.attributes.length > 0)
for (var i = 0, il = node.attributes.length; i < il;)
newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
if (allChildren && node.childNodes && node.childNodes.length > 0)
for (var i = 0, il = node.childNodes.length; i < il;)
newNode.appendChild(this._importNode(doc, node.childNodes[i++], allChildren));
return newNode;
break;
case 3:
case 4:
case 8:
}
};
this.parser = new DOMParser();
var str = "";
var inst_doc = this.parser.parseFromString(str, "text/xml");
var inst_node = inst_doc.getElementsByTagName("institution");
this.institution = inst_node.item(0);
var inst_part_node = inst_doc.getElementsByTagName("institution-part");
this.institutionpart = inst_part_node.item(0);
this.ns = "http://purl.org/net/xbiblio/csl";
};
CSL_CHROME.prototype.clean = function (xml) {
xml = xml.replace(/<\?[^?]+\?>/g, "");
xml = xml.replace(/]+>/g, "");
xml = xml.replace(/^\s+/, "");
xml = xml.replace(/\s+$/, "");
xml = xml.replace(/^\n*/, "");
return xml;
};
CSL_CHROME.prototype.getStyleId = function (myxml) {
var text = "";
var node = myxml.getElementsByTagName("id");
if (node && node.length) {
node = node.item(0);
}
if (node) {
text = node.textContent;
}
if (!text) {
text = node.innerText;
}
if (!text) {
text = node.innerHTML;
}
return text;
};
CSL_CHROME.prototype.children = function (myxml) {
var children, pos, len, ret;
if (myxml) {
ret = [];
children = myxml.childNodes;
for (pos = 0, len = children.length; pos < len; pos += 1) {
if (children[pos].nodeName != "#text") {
ret.push(children[pos]);
}
}
return ret;
} else {
return [];
}
};
CSL_CHROME.prototype.nodename = function (myxml) {
var ret = myxml.nodeName;
return ret;
};
CSL_CHROME.prototype.attributes = function (myxml) {
var ret, attrs, attr, key, xml, pos, len;
ret = new Object();
if (myxml && this.hasAttributes(myxml)) {
attrs = myxml.attributes;
for (pos = 0, len=attrs.length; pos < len; pos += 1) {
attr = attrs[pos];
ret["@" + attr.name] = attr.value;
}
}
return ret;
};
CSL_CHROME.prototype.content = function (myxml) {
var ret;
if ("undefined" != typeof myxml.textContent) {
ret = myxml.textContent;
} else if ("undefined" != typeof myxml.innerText) {
ret = myxml.innerText;
} else {
ret = myxml.txt;
}
return ret;
};
CSL_CHROME.prototype.namespace = {
"xml":"http://www.w3.org/XML/1998/namespace"
}
CSL_CHROME.prototype.numberofnodes = function (myxml) {
if (myxml) {
return myxml.length;
} else {
return 0;
}
};
CSL_CHROME.prototype.getAttributeName = function (attr) {
var ret = attr.name;
return ret;
}
CSL_CHROME.prototype.getAttributeValue = function (myxml,name,namespace) {
var ret = "";
if (namespace) {
name = namespace+":"+name;
}
if (myxml && this.hasAttributes(myxml) && myxml.getAttribute(name)) {
ret = myxml.getAttribute(name);
}
return ret;
}
CSL_CHROME.prototype.getNodeValue = function (myxml,name) {
var ret = "";
if (name){
var vals = myxml.getElementsByTagName(name);
if (vals.length > 0) {
if ("undefined" != typeof vals[0].textContent) {
ret = vals[0].textContent;
} else if ("undefined" != typeof vals[0].innerText) {
ret = vals[0].innerText;
} else {
ret = vals[0].text;
}
}
} else {
ret = myxml;
}
if (ret && ret.childNodes && (ret.childNodes.length == 0 || (ret.childNodes.length == 1 && ret.firstChild.nodeName == "#text"))) {
if ("undefined" != typeof ret.textContent) {
ret = ret.textContent;
} else if ("undefined" != typeof ret.innerText) {
ret = ret.innerText;
} else {
ret = ret.text;
}
}
return ret;
}
CSL_CHROME.prototype.setAttributeOnNodeIdentifiedByNameAttribute = function (myxml,nodename,partname,attrname,val) {
var pos, len, xml, nodes, node;
if (attrname.slice(0,1) === '@'){
attrname = attrname.slice(1);
}
nodes = myxml.getElementsByTagName(nodename);
for (pos = 0, len = nodes.length; pos < len; pos += 1) {
node = nodes[pos];
if (node.getAttribute("name") != partname) {
continue;
}
node.setAttribute(attrname, val);
}
}
CSL_CHROME.prototype.deleteNodeByNameAttribute = function (myxml,val) {
var pos, len, node, nodes;
nodes = myxml.childNodes;
for (pos = 0, len = nodes.length; pos < len; pos += 1) {
node = nodes[pos];
if (!node || node.nodeType == node.TEXT_NODE) {
continue;
}
if (this.hasAttributes(node) && node.getAttribute("name") == val) {
myxml.removeChild(nodes[pos]);
}
}
}
CSL_CHROME.prototype.deleteAttribute = function (myxml,attr) {
myxml.removeAttribute(attr);
}
CSL_CHROME.prototype.setAttribute = function (myxml,attr,val) {
if (!myxml.ownerDocument) {
myxml = myxml.firstChild;
}
if (["function", "unknown"].indexOf(typeof myxml.setAttribute) > -1) {
myxml.setAttribute(attr, val);
}
return false;
}
CSL_CHROME.prototype.nodeCopy = function (myxml) {
var cloned_node = myxml.cloneNode(true);
return cloned_node;
}
CSL_CHROME.prototype.getNodesByName = function (myxml,name,nameattrval) {
var ret, nodes, node, pos, len;
ret = [];
nodes = myxml.getElementsByTagName(name);
for (pos = 0, len = nodes.length; pos < len; pos += 1) {
node = nodes.item(pos);
if (nameattrval && !(this.hasAttributes(node) && node.getAttribute("name") == nameattrval)) {
continue;
}
ret.push(node);
}
return ret;
}
CSL_CHROME.prototype.nodeNameIs = function (myxml,name) {
if (name == myxml.nodeName) {
return true;
}
return false;
}
CSL_CHROME.prototype.makeXml = function (myxml) {
var ret, topnode;
if (!myxml) {
myxml = "";
}
myxml = myxml.replace(/\s*<\?[^>]*\?>\s*\n*/g, "");
var nodetree = this.parser.parseFromString(myxml, "application/xml");
return nodetree.firstChild;
};
CSL_CHROME.prototype.insertChildNodeAfter = function (parent,node,pos,datexml) {
var myxml, xml;
myxml = this.importNode(node.ownerDocument, datexml);
parent.replaceChild(myxml, node);
return parent;
};
CSL_CHROME.prototype.insertPublisherAndPlace = function(myxml) {
var group = myxml.getElementsByTagName("group");
for (var i = 0, ilen = group.length; i < ilen; i += 1) {
var node = group.item(i);
var skippers = [];
for (var j = 0, jlen = node.childNodes.length; j < jlen; j += 1) {
if (node.childNodes.item(j).nodeType !== 1) {
skippers.push(j);
}
}
if (node.childNodes.length - skippers.length === 2) {
var twovars = [];
for (var j = 0, jlen = 2; j < jlen; j += 1) {
if (skippers.indexOf(j) > -1) {
continue;
}
var child = node.childNodes.item(j);
var subskippers = [];
for (var k = 0, klen = child.childNodes.length; k < klen; k += 1) {
if (child.childNodes.item(k).nodeType !== 1) {
subskippers.push(k);
}
}
if (child.childNodes.length - subskippers.length === 0) {
twovars.push(child.getAttribute('variable'));
if (child.getAttribute('suffix')
|| child.getAttribute('prefix')) {
twovars = [];
break;
}
}
}
if (twovars.indexOf("publisher") > -1 && twovars.indexOf("publisher-place") > -1) {
node.setAttribute('has-publisher-and-publisher-place', true);
}
}
}
};
CSL_CHROME.prototype.addMissingNameNodes = function(myxml) {
var nameslist = myxml.getElementsByTagName("names");
for (var i = 0, ilen = nameslist.length; i < ilen; i += 1) {
var names = nameslist.item(i);
var namelist = names.getElementsByTagName("name");
if ((!namelist || namelist.length === 0)
&& names.parentNode.tagName.toLowerCase() !== "substitute") {
var doc = names.ownerDocument;
var name = doc.createElement("name");
names.appendChild(name);
}
}
};
CSL_CHROME.prototype.addInstitutionNodes = function(myxml) {
var names, thenames, institution, theinstitution, name, thename, xml, pos, len;
names = myxml.getElementsByTagName("names");
for (pos = 0, len = names.length; pos < len; pos += 1) {
thenames = names.item(pos);
name = thenames.getElementsByTagName("name");
if (name.length == 0) {
continue;
}
institution = thenames.getElementsByTagName("institution");
if (institution.length == 0) {
theinstitution = this.importNode(myxml.ownerDocument, this.institution);
theinstitutionpart = theinstitution.getElementsByTagName("institution-part").item(0);
thename = name.item(0);
thenames.insertBefore(theinstitution, thename.nextSibling);
for (var j = 0, jlen = CSL.INSTITUTION_KEYS.length; j < jlen; j += 1) {
var attrname = CSL.INSTITUTION_KEYS[j];
var attrval = thename.getAttribute(attrname);
if (attrval) {
theinstitutionpart.setAttribute(attrname, attrval);
}
}
var nameparts = thename.getElementsByTagName("name-part");
for (var j = 0, jlen = nameparts.length; j < jlen; j += 1) {
if ('family' === nameparts[j].getAttribute('name')) {
for (var k = 0, klen = CSL.INSTITUTION_KEYS.length; k < klen; k += 1) {
var attrname = CSL.INSTITUTION_KEYS[k];
var attrval = nameparts[j].getAttribute(attrname);
if (attrval) {
theinstitutionpart.setAttribute(attrname, attrval);
}
}
}
}
}
}
};
CSL_CHROME.prototype.flagDateMacros = function(myxml) {
var pos, len, thenode, thedate;
nodes = myxml.getElementsByTagName("macro");
for (pos = 0, len = nodes.length; pos < len; pos += 1) {
thenode = nodes.item(pos);
thedate = thenode.getElementsByTagName("date");
if (thedate.length) {
thenode.setAttribute('macro-has-date', 'true');
}
}
};
PK Q4Km59 9 cite2c-0.2.1.dist-info/LICENSEThe MIT License (MIT)
Copyright (c) 2016 Thomas Kluyver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
PK !HxyU b cite2c-0.2.1.dist-info/WHEELHM
K-*ϳR03rOK-J,/RH,Q034
/,
(-JLR()*M
ILR(4KM̫#D PK !HZk cite2c-0.2.1.dist-info/METADATAeTn0+; ð=,kbMZ,ѓf'Komi~`Ls=WK@:f>Ww6\:,Ew;Kb̉6I}&ւ0wdYs]n~1|u$R]P4j)