// ==UserScript==
// @name re621 - e621 Reimagined
// @namespace re621.github.io
// @version 1.4.10
// @description Subscription manager, mass downloader, thumbnail enhancer, and more for e621
// @author re621 team
// @license GPL-3.0-only
// @supportURL https://github.com/re621/re621/issues
// @homepageURL https://e621.net/forum_topics/25872
// @match https://e621.net/*
// @match https://e926.net/*
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.5.0/jszip.min.js
// @require https://cdn.jsdelivr.net/gh/re621/re621-lib@ca1997acae2ad0f41c4172206ad5a9dc01b8fc19/mousetrap/mousetrap.min.js
// @require https://cdn.jsdelivr.net/gh/re621/re621-lib@d7e3de13d861132cbc7a8d978bba11eb426c06c5/mousetrap/mousetrap-record.min.js
// @require https://cdn.jsdelivr.net/gh/re621/re621-lib@c8a82094eefeefdd4389538f87022bacdcf5c459/lazysizes/lazysizes.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.0/plugins/unload/ls.unload.min.js
// @resource re621_css https://github.com/re621/re621/releases/download/1.4.10/style.min.css
// @grant GM.info
// @grant GM.setValue
// @grant GM.getValue
// @grant GM.deleteValue
// @grant GM.openInTab
// @grant GM.setClipboard
// @grant GM.getResourceUrl
// @grant GM_getResourceURL
// @grant GM_getResourceText
// @grant GM.xmlHttpRequest
// @grant GM_xmlhttpRequest
// @grant GM_addValueChangeListener
// @grant GM_removeValueChangeListener
// @grant unsafeWindow
// @icon https://cdn.jsdelivr.net/gh/re621/re621.github.io@master/images/icons/icon64.png
// @icon64 https://cdn.jsdelivr.net/gh/re621/re621.github.io@master/images/icons/icon64.png
// @connect api.github.com
// @connect static1.e621.net
// @run-at document-start
// ==/UserScript==
window.re621 = new function() {
this.name = "re621";
this.displayName = "re621 - e621 Reimagined";
this.version = "1.4.10";
this.build = "200911:0607";
this.type = "script";
this.links = {
website: "https://e621.net/forum_topics/25872",
repository: "https://github.com/re621/re621/",
issues: "https://github.com/re621/re621/issues/",
releases: "https://github.com/re621/re621/releases",
forum: "https://e621.net/forum_topics/25872",
};
this.useragent = "re621:script/1.4";
this.debug = true;
};
/* This is a minified build. To see the source, visit the project's github page. */
!function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){return o(e[i][1][r]||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ModuleController=void 0;const Debug_1=require("./utility/Debug"),ErrorHandler_1=require("./utility/ErrorHandler");class ModuleController{static async register(moduleList){Array.isArray(moduleList)||(moduleList=[moduleList]),Debug_1.Debug.perfStart("re621.total");let activeModules=0;for(const moduleClass of moduleList){Debug_1.Debug.perfStart(moduleClass.prototype.constructor.name);try{const instance=moduleClass.getInstance();this.modules.set(moduleClass.prototype.constructor.name,instance),await instance.prepare()}catch(error){ErrorHandler_1.ErrorHandler.error(moduleClass.prototype.constructor.name,error.stack,"prepare")}}for(const instance of this.modules.values()){try{instance.canInitialize()&&(instance.isWaitingForDOM()?$(()=>{window.setTimeout(()=>{try{instance.create()}catch(error){ErrorHandler_1.ErrorHandler.error(instance,error.stack,"init")}},50)}):instance.create(),activeModules++)}catch(error){ErrorHandler_1.ErrorHandler.error(instance,error.stack,"init")}Debug_1.Debug.perfEnd(instance.constructor.name)}return Debug_1.Debug.perfEnd("re621.total"),Promise.resolve(activeModules)}static get(module){return"string"==typeof module?this.modules.get(module):this.get(module.prototype.constructor.name)}static getAll(){return this.modules}}exports.ModuleController=ModuleController,ModuleController.modules=new Map},{"./utility/Debug":30,"./utility/ErrorHandler":31}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RE6Module=void 0;const XM_1=require("./api/XM"),Keybinds_1=require("./data/Keybinds"),Page_1=require("./data/Page"),ModuleController_1=require("./ModuleController");exports.RE6Module=class{constructor(constraint,waitForDOM=!1,dependencies=[],settingsTag){this.initialized=!1,this.dependencies=[],this.constraint=[],this.keybinds=[],void 0===constraint?this.constraint=[]:constraint instanceof RegExp?this.constraint.push(constraint):this.constraint=constraint,this.dependencies=dependencies,this.waitForDOM=waitForDOM,this.settingsTag=settingsTag||this.constructor.name}async prepare(){await this.loadSettingsCache(),this.enabled=this.fetchSettings("enabled")}isInitialized(){return this.initialized}canInitialize(){let depend=!0;for(const module of this.dependencies)if(!ModuleController_1.ModuleController.get(module).isEnabled()){depend=!1;break}return!this.initialized&&this.pageMatchesFilter()&&this.enabled&&depend}getSettingsTag(){return this.settingsTag}isWaitingForDOM(){return this.waitForDOM}pageMatchesFilter(){return 0==this.constraint.length||Page_1.Page.matches(this.constraint)}create(){this.initialized=!0}destroy(){this.initialized=!1}isEnabled(){return this.enabled}setEnabled(enabled){this.enabled=enabled}fetchSettings(property,fresh){if(fresh)return new Promise(async resolve=>{await this.loadSettingsCache(),resolve(this.fetchSettings(property))});if(Array.isArray(property)){const result={};return property.forEach(entry=>{result[entry]=this.settings[entry]}),result}return this.settings[property]}async fetchSettingsGently(property){return Promise.resolve((await this.loadSettingsValues())[property])}async pushSettings(property,value){return this.loadSettingsCache().then(()=>("string"==typeof property?this.settings[property]=value:Object.keys(property).forEach(key=>{this.settings[key]=property[key]}),this.saveSettingsCache()))}async clearSettings(){return XM_1.XM.Storage.deleteValue("re621."+this.settingsTag).then(()=>this.loadSettingsCache())}getDefaultSettings(){return{enabled:!0}}async loadSettingsCache(){return this.settings=await this.loadSettingsValues(),Promise.resolve(!0)}async loadSettingsValues(){const defaultValues=this.getDefaultSettings(),result=await XM_1.XM.Storage.getValue("re621."+this.settingsTag,defaultValues);for(const key of Object.keys(defaultValues))void 0===result[key]&&(result[key]=defaultValues[key]);return Promise.resolve(result)}async saveSettingsCache(){return XM_1.XM.Storage.setValue("re621."+this.settingsTag,this.settings)}async refreshSettings(){return this.loadSettingsCache()}async getSavedSettings(){return{name:"re621."+this.settingsTag,data:await XM_1.XM.Storage.getValue("re621."+this.settingsTag,{})}}async resetHotkeys(){await this.loadSettingsCache();const keyMeta=[],keybindObj=[],enabled=this.pageMatchesFilter();for(const keybind of this.keybinds){const meta=this.getSettingsTag+"."+keybind.keys;keybindObj.push({keys:this.fetchSettings(keybind.keys).split("|"),fnct:keybind.fnct,bindMeta:meta,bindName:keybind.name,enabled:enabled}),keyMeta.push(meta)}Keybinds_1.KeybindManager.unregister(keyMeta),Keybinds_1.KeybindManager.register(keybindObj)}registerHotkeys(...keybinds){this.keybinds.push(...keybinds),this.resetHotkeys()}static getInstance(){return null==this.instance&&(this.instance=new this),this.instance}static on(name,callback){$(document).on("re621.module."+this.getInstance().constructor.name+"."+name,(event,data)=>{callback(event,data)})}static off(name){$(document).off("re621.module."+this.getInstance().constructor.name+"."+name)}static trigger(name,data){$(document).trigger("re621.module."+this.getInstance().constructor.name+"."+name,data)}}},{"./ModuleController":1,"./api/XM":6,"./data/Keybinds":15,"./data/Page":16}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Danbooru=void 0;const XM_1=require("./XM");class Danbooru{static getModules(){return XM_1.XM.Window.Danbooru}static hasModules(){return void 0!==XM_1.XM.Window.Danbooru}static notice(input,permanent){Danbooru.hasModules()?Danbooru.getModules().notice(input,permanent):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Notice","notice",[input,permanent])}static error(input){Danbooru.hasModules()?Danbooru.getModules().error(input):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Notice","error",[input])}}exports.Danbooru=Danbooru,Danbooru.Autocomplete={initialize_all(){Danbooru.hasModules()?Danbooru.getModules().Autocomplete.initialize_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Autocomplete","initialize_all")}},Danbooru.Blacklist={apply(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.apply():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","apply")},initialize_anonymous_blacklist(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.initialize_anonymous_blacklist():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","initialize_anonymous_blacklist")},initialize_all(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.initialize_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","initialize_all")},initialize_disable_all_blacklists(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.initialize_disable_all_blacklists():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","initialize_disable_all_blacklists")},stub_vanilla_functions(){Danbooru.hasModules()?(Danbooru.getModules().Blacklist.apply=()=>{},Danbooru.getModules().Blacklist.initialize_disable_all_blacklists=()=>{},Danbooru.getModules().Blacklist.initialize_all=()=>{}):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","stub_vanilla_functions")}},Danbooru.Post={vote(post_id,scoreDifference,preventUnvote){Danbooru.hasModules()?Danbooru.getModules().Post.vote(post_id,scoreDifference,preventUnvote):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","vote",[post_id,scoreDifference,preventUnvote])},initialize_all(){Danbooru.hasModules()?Danbooru.getModules().Post.initialize_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","update")},update(post_id,params){Danbooru.hasModules()?Danbooru.getModules().Post.update(post_id,params):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","update",[post_id,params])},delete_with_reason(post_id,reason,reload_after_delete){Danbooru.hasModules()?Danbooru.getModules().Post.delete_with_reason(post_id,reason,reload_after_delete):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","delete_with_reason",[post_id,reason,reload_after_delete])},undelete(post_id){Danbooru.hasModules()?Danbooru.getModules().Post.undelete(post_id):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","undelete",[post_id])},approve(post_id,should_reload=!1){Danbooru.hasModules()?Danbooru.getModules().Post.approve(post_id,should_reload):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","approve",[post_id,should_reload])},disapprove(post_id,reason,should_reload=!1){Danbooru.hasModules()?Danbooru.getModules().Post.disapprove(post_id,reason,should_reload):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","disapprove",[post_id,reason,should_reload])},unapprove(post_id){Danbooru.hasModules()?Danbooru.getModules().Post.unapprove(post_id):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","unapprove",[post_id])}},Danbooru.PostModeMenu={change(){Danbooru.hasModules()?Danbooru.getModules().PostModeMenu.change():XM_1.XM.Chrome.execInjectorRequest("Danbooru","PostModeMenu","change")},click(e){Danbooru.hasModules()?Danbooru.getModules().PostModeMenu.click(e):XM_1.XM.Chrome.execInjectorRequest("Danbooru","PostModeMenu","click",[e])}},Danbooru.Note={Box:{scale_all(){Danbooru.hasModules()?Danbooru.getModules().Note.Box.scale_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Note.Box","scale_all")}},TranslationMode:{active:state=>Danbooru.hasModules()?(void 0!==state&&(Danbooru.getModules().Note.TranslationMode.active=state),Promise.resolve(Danbooru.getModules().Note.TranslationMode.active)):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Note.TranslationMode","active",[state]),toggle(){Danbooru.hasModules()?Danbooru.getModules().Note.TranslationMode.toggle(new CustomEvent("re621.dummy-event")):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Note.TranslationMode","toggle")}}},Danbooru.Thumbnails={initialize(){Danbooru.hasModules()?Danbooru.getModules().Thumbnails.initialize():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Thumbnails","initialize")}},Danbooru.Utility={disableShortcuts:state=>Danbooru.hasModules()?(void 0!==state&&(Danbooru.getModules().Utility.disableShortcuts=state),Promise.resolve(Danbooru.getModules().Utility.disableShortcuts)):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Utility","disableShortcuts",[state])},Danbooru.E621={addDeferredPosts(posts){Danbooru.hasModules()?(XM_1.XM.Window.___deferred_posts=XM_1.XM.Window.___deferred_posts||{},XM_1.XM.Window.___deferred_posts=$.extend(XM_1.XM.Window.___deferred_posts,posts)):XM_1.XM.Chrome.execInjectorRequest("Danbooru","E621","addDeferredPosts",[posts])}}},{"./XM":6}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DownloadQueue=void 0;const XM_1=require("./XM");class DownloadQueue{constructor(){this.queue=[],this.zip=new JSZip}getThreadCount(){return DownloadQueue.concurrent}getQueueLength(){return this.queue.length}add(file,listeners){file.unid=void 0===file.unid?0:file.unid,file.date=void 0===file.date?new Date:new Date(file.date),file.tags=void 0===file.tags?"":file.tags,listeners.onStart=void 0===listeners.onStart?function(){}:listeners.onStart,listeners.onFinish=void 0===listeners.onFinish?function(){}:listeners.onFinish,listeners.onLoadStart=void 0===listeners.onLoadStart?function(){}:listeners.onLoadStart,listeners.onLoadFinish=void 0===listeners.onLoadFinish?function(){}:listeners.onLoadFinish,listeners.onLoadProgress=void 0===listeners.onLoadProgress?function(){}:listeners.onLoadProgress,listeners.onError=void 0===listeners.onError?function(){}:listeners.onError,this.queue.push({file:file,listeners:listeners})}async run(onArchiveProgress){this.queue=this.queue.reverse();const processes=[];for(let i=0;i<DownloadQueue.concurrent;i++)processes.push(this.createNewProcess(i));return Promise.all(processes).then(()=>this.zip.generateAsync({type:"blob",compression:"STORE",comment:"Downloaded from e621 on "+(new Date).toUTCString()},onArchiveProgress))}async createNewProcess(thread){return new Promise(async resolve=>{let index,item;for(;this.queue.length>0;)index=this.queue.length,item=this.queue.pop(),item.listeners.onStart(item.file,thread,index),await this.zip.file(item.file.name,await this.getDataBlob(item,thread),{binary:!0,date:item.file.date,comment:item.file.tags}),item.listeners.onFinish(item.file,thread,index);void 0!==item&&item.listeners.onWorkerFinish(item.file,thread),resolve()})}async getDataBlob(item,thread){return new Promise((resolve,reject)=>{let timer;XM_1.XM.Connect.xmlHttpRequest({method:"GET",url:item.file.path,headers:{"User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent},responseType:"arraybuffer",onloadstart:event=>{item.listeners.onLoadStart(item.file,thread,event)},onerror:event=>{item.listeners.onError(item.file,thread,event),reject(item.file)},ontimeout:event=>{item.listeners.onError(item.file,thread,event),reject(item.file)},onprogress:event=>{timer&&clearTimeout(timer),timer=window.setTimeout(()=>{item.listeners.onLoadProgress(item.file,thread,event)},500)},onload:event=>{item.listeners.onLoadFinish(item.file,thread,event),resolve(event.response)}})})}}exports.DownloadQueue=DownloadQueue,DownloadQueue.concurrent=4},{"./XM":6}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.E621=void 0;const Debug_1=require("../utility/Debug"),Util_1=require("../utility/Util"),ENDPOINT_DEFS=[{name:"posts",path:"posts.json",node:"posts"},{name:"post",path:"posts/%ID%.json",node:"post"},{name:"post_votes",path:"posts/%ID%/votes.json"},{name:"tags",path:"tags.json"},{name:"tag",path:"tags/%ID%.json"},{name:"tag_aliases",path:"tag_aliases.json"},{name:"tag_implications",path:"tag_implications.json"},{name:"notes",path:"notes.json"},{name:"favorites",path:"favorites.json",node:"posts"},{name:"favorite",path:"favorites/%ID%.json"},{name:"pools",path:"pools.json"},{name:"pool",path:"pools/%ID%.json"},{name:"sets",path:"post_sets.json"},{name:"set",path:"post_sets/%ID%.json"},{name:"set_add_post",path:"post_sets/%ID%/add_posts.json"},{name:"set_remove_post",path:"post_sets/%ID%/remove_posts.json"},{name:"users",path:"users.json"},{name:"user",path:"users/%ID%.json"},{name:"blips",path:"blips.json"},{name:"wiki_pages",path:"wiki_pages.json"},{name:"comments",path:"comments.json"},{name:"comment",path:"comments/%ID%.json"},{name:"forum_posts",path:"forum_posts.json"},{name:"forum_post",path:"forum_posts/%ID%.json"},{name:"forum_topics",path:"forum_topics.json"},{name:"forum_topic",path:"forum_topics/%ID%.json"},{name:"dtext_preview",path:"dtext_preview"},{name:"iqdb_queries",path:"iqdb_queries.json"}];class APIEndpoint{constructor(queue,endpoint){this.queue=queue,this.path=endpoint.path,this.name=endpoint.name,this.node=endpoint.node}id(param){return this.param=param+"",this}async get(query,delay){return this.queue.createRequest(this.getParsedPath(),this.formatParam(query),"GET",{},this.name,this.node,delay).then(response=>{const result=this.formatData(response[0],response[2]);return Promise.resolve(result)},response=>Promise.reject(response[0]))}async first(query,delay){return this.get(query,delay).then(response=>response.length>0?Promise.resolve(response[0]):Promise.resolve(null))}async post(data,delay){return this.queue.createRequest(this.getParsedPath(),{},"POST",this.formatParam(data),this.name,this.node,delay).then(data=>Promise.resolve(data),error=>Promise.reject(error))}async delete(data,delay){return this.queue.createRequest(this.getParsedPath(),{},"DELETE",this.formatParam(data),this.name,this.node,delay).then(data=>Promise.resolve(data),error=>Promise.reject(error))}async put(data,delay){return this.queue.createRequest(this.getParsedPath(),{},"PUT",this.formatParam(data),this.name,this.node,delay).then(data=>Promise.resolve(data),error=>Promise.reject(error))}getParsedPath(){if(this.param){const output=this.path.replace(/%ID%/g,this.param);return this.param=void 0,output}return this.path}formatParam(input){if(Debug_1.Debug.log("input",input),null==input)return{};const response={};for(const[key,value]of Object.entries(input))if(null!=value)if(Array.isArray(value)){for(const[index,elem]of value.entries())value[index]=cleanURIComponent(elem);response[key]=value.join("+")}else if("object"==typeof value)for(const[subkey,subvalue]of Object.entries(value))if(Array.isArray(subvalue)){for(const[index,subelem]of subvalue.entries())subvalue[index]=cleanURIComponent(subelem);response[`${key}[${subkey}]`]=subvalue.join("+")}else response[`${key}[${subkey}]`]=cleanURIComponent(subvalue);else response[key]=cleanURIComponent(value);return Debug_1.Debug.log("output",response),response;function cleanURIComponent(value){return encodeURIComponent(decodeURIComponent(value+""))}}formatData(data,node){return void 0!==node&&(data=data[node]),Array.isArray(data)?data:[data]}}class E621{constructor(){this.emitter=$({}),this.processing=!1,this.requestIndex=0,this.endpoints={},this.authToken=$("head meta[name=csrf-token]").attr("content"),this.queue=[],ENDPOINT_DEFS.forEach(definition=>{this.endpoints[definition.name]=new APIEndpoint(this,definition)})}static getEndpoint(name){return void 0===this.instance&&(this.instance=new E621),this.instance.endpoints[name]}async createRequest(path,query,method,requestBody,endpoint,node,delay){void 0===delay?delay=E621.requestRateLimit:delay<500&&(delay=500);const requestInfo={credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent},method:method,mode:"cors"};"GET"!==method&&(this.authToken=$("meta[name=csrf-token]").attr("content"),requestBody.authenticity_token=encodeURIComponent(this.authToken),requestInfo.body=FormattedAPIQuery.stringify(requestBody)),query._client=window.re621.useragent;const entry=new Request(location.origin+"/"+path+"?"+FormattedAPIQuery.stringify(query),requestInfo),index=this.requestIndex++,final=new Promise((resolve,reject)=>{this.emitter.one("api.re621.result-"+index,(e,data,status,endpoint,node)=>{null===data&&(data=[]),void 0===data[endpoint]||["posts","post"].includes(endpoint)||(data=[]),void 0===data.error?resolve([data,status,node]):reject([data,status,node])})});return this.add({request:entry,index:index,delay:delay,endpoint:endpoint,node:node}),final}async add(newItem){if(this.queue.push(newItem),!this.processing){for(this.processing=!0;this.queue.length>0;){const item=this.queue.shift();Debug_1.Debug.connectLog(item.request.url),await new Promise(async resolve=>{fetch(item.request).then(async response=>{if(response.ok){let responseText=await response.text();responseText||(responseText="[]"),this.emitter.trigger("api.re621.result-"+item.index,[JSON.parse(responseText),response.status,item.endpoint,item.node])}else this.emitter.trigger("api.re621.result-"+item.index,[{error:response.status+" "+response.statusText},response.status,item.endpoint,item.node]);resolve()},error=>{this.emitter.trigger("api.re621.result-"+item.index,[{error:error[1]+" "+error[0].error},error[1],item.endpoint,item.node]),resolve()})}),await Util_1.Util.sleep(item.delay)}this.processing=!1}}}var FormattedAPIQuery;exports.E621=E621,E621.requestRateLimit=1e3,E621.Posts=E621.getEndpoint("posts"),E621.Post=E621.getEndpoint("post"),E621.PostVotes=E621.getEndpoint("post_votes"),E621.Tags=E621.getEndpoint("tags"),E621.Tag=E621.getEndpoint("tag"),E621.TagAliases=E621.getEndpoint("tag_aliases"),E621.TagImplications=E621.getEndpoint("tag_implications"),E621.Notes=E621.getEndpoint("notes"),E621.Favorites=E621.getEndpoint("favorites"),E621.Favorite=E621.getEndpoint("favorite"),E621.Pools=E621.getEndpoint("pools"),E621.Pool=E621.getEndpoint("pool"),E621.Sets=E621.getEndpoint("sets"),E621.Set=E621.getEndpoint("set"),E621.SetAddPost=E621.getEndpoint("set_add_post"),E621.SetRemovePost=E621.getEndpoint("set_remove_post"),E621.Users=E621.getEndpoint("users"),E621.User=E621.getEndpoint("user"),E621.Blips=E621.getEndpoint("blips"),E621.Wiki=E621.getEndpoint("wiki_pages"),E621.Comments=E621.getEndpoint("comments"),E621.Comment=E621.getEndpoint("comment"),E621.ForumPosts=E621.getEndpoint("forum_posts"),E621.ForumPost=E621.getEndpoint("forum_post"),E621.ForumTopics=E621.getEndpoint("forum_topics"),E621.ForumTopic=E621.getEndpoint("forum_topic"),E621.DTextPreview=E621.getEndpoint("dtext_preview"),E621.IQDBQueries=E621.getEndpoint("iqdb_queries"),function(FormattedAPIQuery){FormattedAPIQuery.stringify=function(input){const result=[];for(const[key,value]of Object.entries(input))result.push(key+"="+value);return result.join("&")}}(FormattedAPIQuery||(FormattedAPIQuery={}))},{"../utility/Debug":30,"../utility/Util":33}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XM=void 0;const XMChrome_1=require("./XMChrome"),XMConnect_1=require("./XMConnect"),XMStorage_1=require("./XMStorage"),XMUtil_1=require("./XMUtil");class XM{static info(){return"undefined"==typeof GM?{script:null,scriptMetaStr:null,scriptHandler:window.re621.type,version:"1.0"}:GM.info}}exports.XM=XM,XM.Storage=XMStorage_1.XMStorage,XM.Connect=XMConnect_1.XMConnect,XM.Util=XMUtil_1.XMUtil,XM.Chrome=XMChrome_1.XMChrome,XM.Window="undefined"==typeof unsafeWindow?window:unsafeWindow},{"./XMChrome":7,"./XMConnect":8,"./XMStorage":9,"./XMUtil":10}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMChrome=void 0;const Util_1=require("../utility/Util");class XMChrome{static async execBackgroundRequest(component,module,method,args){return new Promise(resolve=>{chrome.runtime.sendMessage(XMChrome.formatRequestData(component,module,method,args),response=>{XMChrome.requests=XMChrome.requests.filter(e=>e!==response.eventID),resolve(response.data)})})}static async execBackgroundConnection(component){return Promise.resolve(chrome.runtime.connect({name:component}))}static async execInjectorRequest(component,module,method,args){return new Promise(resolve=>{const request=XMChrome.formatRequestData(component,module,method,args),callback=function(event){const response=event.detail;document.removeEventListener("re621.chrome.message.response-"+response.eventID,callback),XMChrome.requests=XMChrome.requests.filter(e=>e!==response.eventID),resolve(response.data)};document.addEventListener("re621.chrome.message.response-"+request.eventID,callback),document.dispatchEvent(new CustomEvent("re621.chrome.message",{detail:request}))})}static formatRequestData(component,module,method,args){return{component:component,module:module,method:method,eventID:function(){let id;do{id=Util_1.Util.ID.make(8,!1)}while(XMChrome.requests.includes(id));return XMChrome.requests.push(id),id}(),args:void 0===args?[]:args}}static getResourceURL(name){return chrome.extension.getURL(name)}}exports.XMChrome=XMChrome,XMChrome.requests=[]},{"../utility/Util":33}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMConnect=void 0;const Debug_1=require("../utility/Debug"),XM_1=require("./XM");class XMConnect{static xmlHttpRequest(details){Debug_1.Debug.connectLog(details.url);const validDetails=XMConnect.validateXHRDetails(details);"undefined"!=typeof GM&&"function"==typeof GM.xmlHttpRequest?GM.xmlHttpRequest(validDetails):"function"==typeof GM_xmlhttpRequest?GM_xmlhttpRequest(validDetails):XM_1.XM.Chrome.execBackgroundConnection("XHR").then(port=>{port.postMessage(validDetails),port.onMessage.addListener(async response=>{"onload"===response.event&&("blob"===details.responseType?response.response=await fetch(response.response).then(r=>r.blob()):"arraybuffer"===details.responseType&&(response.response=await fetch(response.response).then(r=>r.arrayBuffer())),URL.revokeObjectURL(response.responseURL)),details[response.event](response)})})}static xmlHttpPromise(details){const validDetails=XMConnect.validateXHRDetails(details);return new Promise((resolve,reject)=>{const callbacks={onabort:validDetails.onabort,onerror:validDetails.onerror,onload:validDetails.onload,onloadstart:validDetails.onloadstart,onprogress:validDetails.onprogress,onreadystatechange:validDetails.onreadystatechange,ontimeout:validDetails.ontimeout};details.onabort=event=>{callbacks.onabort(event),reject(event)},details.onerror=event=>{callbacks.onerror(event),reject(event)},details.onload=event=>{callbacks.onload(event),resolve(event)},details.onloadstart=event=>{callbacks.onloadstart(event)},details.onprogress=event=>{callbacks.onprogress(event)},details.onreadystatechange=event=>{callbacks.onreadystatechange(event)},details.ontimeout=event=>{callbacks.ontimeout(event),reject(event)},XMConnect.xmlHttpRequest(validDetails)})}static validateXHRDetails(details){return void 0===details.headers&&(details.headers={}),void 0===details.headers["User-Agent"]&&(details.headers["User-Agent"]=window.re621.useragent,details.headers["X-User-Agent"]=window.re621.useragent),void 0===details.onabort&&(details.onabort=()=>{}),void 0===details.onerror&&(details.onerror=()=>{}),void 0===details.onload&&(details.onload=()=>{}),void 0===details.onloadstart&&(details.onloadstart=()=>{}),void 0===details.onprogress&&(details.onprogress=()=>{}),void 0===details.onreadystatechange&&(details.onreadystatechange=()=>{}),void 0===details.ontimeout&&(details.ontimeout=()=>{}),details}static async getResourceText(name){return"function"==typeof GM_getResourceText?Promise.resolve(GM_getResourceText(name)):"undefined"!=typeof GM?XMConnect.getResourceTextGM(name):XMConnect.xmlHttpPromise({url:window.resources[name].startsWith("http")?window.resources[name]:XM_1.XM.Chrome.getResourceURL(window.resources[name]),method:"GET"}).then(data=>Promise.resolve(data.responseText),error=>Promise.reject(error.status+" "+error.statusText))}static async getResourceTextGM(name){const resource="function"==typeof GM.getResourceUrl?await GM.getResourceUrl(name):GM_getResourceURL(name);return resource.startsWith("data:")?Promise.resolve(atob(resource.replace(/^data:(.*);base64,/g,""))):resource.startsWith("blob:")?new Promise(async(resolve,reject)=>{const request=await fetch(resource,{credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent},method:"GET",mode:"cors"});request.ok?resolve(await request.text()):reject()}):Promise.reject()}static async getResourceJSON(name){return XMConnect.getResourceText(name).then(resolved=>Promise.resolve(JSON.parse(resolved)),rejected=>Promise.reject(rejected))}static download(a,b){let timer;"string"==typeof a&&(a={url:a,name:b}),void 0===a.headers&&(a.headers={"User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent}),void 0===a.onerror&&(a.onerror=()=>{}),void 0===a.onload&&(a.onload=()=>{}),void 0===a.onprogress&&(a.onprogress=()=>{}),void 0===a.ontimeout&&(a.ontimeout=()=>{}),XMConnect.xmlHttpRequest({url:a.url,method:"GET",headers:a.headers,responseType:"blob",onerror:event=>{a.onerror(event)},ontimeout:event=>{a.ontimeout(event)},onprogress:event=>{timer&&clearTimeout(timer),timer=window.setTimeout(()=>{a.onprogress(event)},500)},onload:event=>{a.onload(event);const btn=$("<a>").attr({href:URL.createObjectURL(event.response),download:a.name}).html("download").click(()=>{btn.remove()});btn[0].click()}})}}exports.XMConnect=XMConnect},{"../utility/Debug":30,"./XM":6}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMStorage=void 0;exports.XMStorage=class{static async setValue(name,value){return new Promise(async resolve=>{"undefined"==typeof GM?await new Promise(resolve=>{chrome.storage.sync.set({[name]:value},()=>{resolve()})}):await GM.setValue(name,value),resolve(!0)})}static async getValue(name,defaultValue){return new Promise(async resolve=>{"undefined"==typeof GM?chrome.storage.sync.get(name,result=>{void 0===result[name]?resolve(Promise.resolve(defaultValue)):resolve(Promise.resolve(result[name]))}):resolve(GM.getValue(name,defaultValue))})}static async deleteValue(name){return new Promise(async resolve=>{"undefined"==typeof GM?await new Promise(resolve=>{chrome.storage.sync.set({name:void 0},()=>{resolve()})}):await GM.deleteValue(name),resolve()})}static addListener(name,callback){if("undefined"!=typeof GM_addValueChangeListener)return GM_addValueChangeListener(name,callback);chrome.storage.onChanged.addListener((function(changes){for(const key in changes){if(key!==name)return;callback(key,changes[key].oldValue,changes[key].newValue,!0)}}))}static removeListener(listenerId){"undefined"!=typeof GM_removeValueChangeListener&&GM_removeValueChangeListener(listenerId)}}},{}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMUtil=void 0;const XM_1=require("./XM");exports.XMUtil=class{static openInTab(path,active=!0){"undefined"==typeof GM?XM_1.XM.Chrome.execBackgroundRequest("XM","Util","openInTab",[path,active]):GM.openInTab(path,{active:active})}static setClipboard(data,info){"undefined"==typeof GM?XM_1.XM.Chrome.execBackgroundRequest("XM","Util","setClipboard",[data]):GM.setClipboard(data,info)}}},{"./XM":6}],11:[function(require,module,exports){"use strict";var PostRating,PostRatingAliases;Object.defineProperty(exports,"__esModule",{value:!0}),exports.APIPost=exports.PostFlag=exports.PostRating=void 0,function(PostRating){PostRating.Safe="s",PostRating.Questionable="q",PostRating.Explicit="e"}(PostRating=exports.PostRating||(exports.PostRating={})),function(PostRatingAliases){PostRatingAliases.s="s",PostRatingAliases.safe="s",PostRatingAliases.q="q",PostRatingAliases.questionable="q",PostRatingAliases.e="e",PostRatingAliases.explicit="e"}(PostRatingAliases||(PostRatingAliases={})),function(PostFlag){PostFlag.Pending="pending",PostFlag.Flagged="flagged",PostFlag.Deleted="deleted"}(exports.PostFlag||(exports.PostFlag={})),function(PostFlag){PostFlag.get=function(post){const flags=new Set;return post.flags.deleted&&flags.add(PostFlag.Deleted),post.flags.flagged&&flags.add(PostFlag.Flagged),post.flags.pending&&flags.add(PostFlag.Pending),flags},PostFlag.getString=function(post){return[...PostFlag.get(post)].join(" ")},PostFlag.fromSingle=function(input){switch(input=input.toLowerCase().trim()){case"pending":return PostFlag.Pending;case"flagged":return PostFlag.Flagged;case"deleted":return PostFlag.Deleted}return null},PostFlag.fromString=function(input){const parts=new Set(input.split(" ")),flags=new Set;return parts.has("deleted")&&flags.add(PostFlag.Deleted),parts.has("flagged")&&flags.add(PostFlag.Flagged),parts.has("pending")&&flags.add(PostFlag.Pending),flags}}(exports.PostFlag||(exports.PostFlag={})),function(PostRating){PostRating.fromValue=function(value){return PostRatingAliases[value]},PostRating.toString=function(postRating){for(const key of Object.keys(PostRating))if(PostRating[key]===postRating)return key},PostRating.toFullString=function(postRating){switch(postRating.toLowerCase()){case"s":return"safe";case"q":return"questionable";case"e":return"explicit"}return null}}(PostRating=exports.PostRating||(exports.PostRating={})),function(APIPost){APIPost.getTags=function(post){return[...post.tags.artist,...post.tags.character,...post.tags.copyright,...post.tags.general,...post.tags.invalid,...post.tags.lore,...post.tags.meta,...post.tags.species]},APIPost.getTagString=function(post){return APIPost.getTags(post).join(" ")},APIPost.getTagSet=function(post){return new Set(APIPost.getTags(post))},APIPost.fromDomElement=function($element){let md5;$element.attr("data-md5")?md5=$element.attr("data-md5"):$element.attr("data-file-url")&&(md5=$element.attr("data-file-url").substring(36,68));const ext=$element.attr("data-file-ext");let score;$element.attr("data-score")?score=parseInt($element.attr("data-score")):0!==$element.find(".post-score-score").length&&(score=parseInt($element.find(".post-score-score").first().html().substring(1)));const flagString=$element.attr("data-flags");return{error:"",id:parseInt($element.attr("data-id")),change_seq:-1,comment_count:-1,created_at:"",description:"",fav_count:-1,file:{ext:ext,height:-1,width:-1,md5:md5,size:-1,url:$element.attr("data-file-url")?$element.attr("data-file-url"):getFileName(md5)},flags:{deleted:flagString.includes("deleted"),flagged:flagString.includes("flagged"),note_locked:!1,pending:flagString.includes("pending"),rating_locked:!1,status_locked:!1},locked_tags:[],pools:[],preview:{height:-1,width:-1,url:$element.attr("data-preview-file-url")?$element.attr("data-preview-file-url"):getFileName(md5,"preview")},rating:PostRating.fromValue($element.attr("data-rating")),relationships:{children:[],has_active_children:!1,has_children:!1},sample:{has:!0,height:-1,width:-1,url:$element.attr("data-large-file-url")?$element.attr("data-large-file-url"):getFileName(md5,"sample")},score:{down:0,total:score,up:0},sources:[],tags:{artist:[],character:[],copyright:[],general:$element.attr("data-tags").split(" "),invalid:[],lore:[],meta:[],species:[]},updated_at:"",uploader_id:parseInt($element.attr("data-uploader-id"))};function getFileName(md5,prefix){return void 0===md5?"/images/deleted-preview.png":prefix?`https://static1.e621.net/data/${prefix}/${md5.substring(0,2)}/${md5.substring(2,4)}/${md5}.jpg`:`https://static1.e621.net/data/${md5.substring(0,2)}/${md5.substring(2,4)}/${md5}.jpg`}}}(exports.APIPost||(exports.APIPost={}))},{}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AvoidPosting=void 0;const E621_1=require("../api/E621"),Util_1=require("../utility/Util");class AvoidPosting{static getCache(){return void 0===AvoidPosting.cache&&(AvoidPosting.cache=new Set(JSON.parse(window.localStorage.getItem("re621.dnpcache.data")||"[]"))),AvoidPosting.cache}static save(){window.localStorage.setItem("re621.dnpcache.data",JSON.stringify(Array.from(AvoidPosting.getCache())))}static clear(){AvoidPosting.cache=new Set,AvoidPosting.save()}static size(){return AvoidPosting.getCache().size}static has(tag){return AvoidPosting.getCache().has(tag)}static add(tag){AvoidPosting.getCache().add(tag),AvoidPosting.save()}static async update(status){status||(status=$("<span>")),AvoidPosting.clear();let result=[],page=0;do{page++,status.html(`<i class="fas fa-circle-notch fa-spin"></i> Processing tags: batch ${page} / ?`),result=await E621_1.E621.TagImplications.get({search:{consequent_name:["avoid_posting","conditional_dnp"]},page:page,limit:1e3},500);for(const entry of result)AvoidPosting.add(entry.antecedent_name)}while(320==result.length);return status.html(`<i class="far fa-check-circle"></i> Cache reloaded: ${AvoidPosting.size()} entries`),window.localStorage.setItem("re621.dnpcache.update",Util_1.Util.Time.now()+""),Promise.resolve(AvoidPosting.size())}static getUpdateTime(){return parseInt(window.localStorage.getItem("re621.dnpcache.update"))||0}static isUpdateRequired(){return AvoidPosting.getUpdateTime()+Util_1.Util.Time.DAY<Util_1.Util.Time.now()||0==AvoidPosting.size()}}exports.AvoidPosting=AvoidPosting},{"../api/E621":5,"../utility/Util":33}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TagCache=void 0;const Debug_1=require("../utility/Debug"),Util_1=require("../utility/Util");class TagCache{static getCache(){return null==TagCache.cache&&TagCache.load(),TagCache.cache}static load(){TagCache.cache=new Map(JSON.parse(Util_1.Util.LS.getItem("re621.tagcache")||"[]"));const now=Util_1.Util.Time.now();let pruned=0;for(const[name,data]of TagCache.cache)data.expires<now&&(TagCache.cache.delete(name),pruned++);Debug_1.Debug.log(`TagCache loaded, ${TagCache.cache.size}, ${pruned} pruned`)}static save(){Util_1.Util.LS.setItem("re621.tagcache",JSON.stringify(Array.from(TagCache.getCache().entries()))),Debug_1.Debug.log("TagCache saved, "+TagCache.cache.size)}static clear(){TagCache.getCache().clear(),TagCache.save()}static has(tag){return TagCache.getCache().has(tag)}static get(tag){return TagCache.getCache().has(tag)?TagCache.getCache().get(tag):null}static add(tag,count,category){TagCache.getCache().set(tag,{count:count,category:category,expires:Util_1.Util.Time.now()+(count>1e5?Util_1.Util.Time.WEEK:Util_1.Util.Time.DAY)})}}exports.TagCache=TagCache},{"../utility/Debug":30,"../utility/Util":33}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Blacklist=void 0;const BlacklistEnhancer_1=require("../../modules/search/BlacklistEnhancer"),ModuleController_1=require("../ModuleController"),Post_1=require("../post/Post"),PostFilter_1=require("../post/PostFilter"),Util_1=require("../utility/Util"),User_1=require("./User");class Blacklist{constructor(){this.blacklist=new Map;const filters=$("head meta[name=blacklisted-tags]").attr("content"),blacklistEnabled="1"!==Util_1.Util.LS.getItem("dab");if(void 0!==filters)for(const filter of JSON.parse(filters))this.createFilter(filter,blacklistEnabled)}static getInstance(){return null==this.instance&&(this.instance=new Blacklist),this.instance}static get(){return this.getInstance().blacklist}static getActiveFilters(){const result=new Map;for(const[tags,filter]of this.getInstance().blacklist)filter.getMatchesCount()>0&&result.set(tags,filter);return result}static addPost(...posts){let count=0;for(const filter of Blacklist.get().values())filter.update(posts)&&count++;return count}static updatePost(...posts){return Blacklist.addPost(...posts)}static checkPost(post,ignoreDisabled=!1){"number"!=typeof post&&(post=post.id);for(const filter of Blacklist.get().values())if(filter.matchesID(post,ignoreDisabled))return!0;return!1}static enableAll(){for(const filter of Blacklist.get().values())filter.setEnabled(!0)}static disableAll(){for(const filter of Blacklist.get().values())filter.setEnabled(!1)}createFilter(filter,enabled=!0){let postFilter=this.blacklist.get(filter);void 0===postFilter&&(postFilter=new PostFilter_1.PostFilter(filter,enabled),this.blacklist.set(filter,postFilter))}static createFilter(filter,enabled=!0){return this.getInstance().createFilter(filter,enabled)}deleteFilter(filter){this.blacklist.delete(filter)}static deleteFilter(filter){return this.getInstance().deleteFilter(filter)}static async toggleBlacklistTag(tagName){let currentBlacklist=(await User_1.User.getCurrentSettings()).blacklisted_tags.split("\n");return-1===currentBlacklist.indexOf(tagName)?(currentBlacklist.push(tagName),Blacklist.createFilter(tagName),Danbooru.notice(`Adding ${getTagLink(tagName)} to blacklist`)):(currentBlacklist=currentBlacklist.filter(e=>e!==tagName),Blacklist.deleteFilter(tagName),Danbooru.notice(`Removing ${getTagLink(tagName)} from blacklist`)),await User_1.User.setSettings({blacklisted_tags:currentBlacklist.join("\n")}),ModuleController_1.ModuleController.get(BlacklistEnhancer_1.BlacklistEnhancer).isInitialized()&&BlacklistEnhancer_1.BlacklistEnhancer.update(),Post_1.Post.find("all").each(post=>{post.updateVisibility()}),Promise.resolve();function getTagLink(tagName){return tagName.startsWith("id:")?`<a href="/posts/${tagName.substr(3)}" target="_blank">${tagName}</a>`:`<a href="/wiki_pages/show_or_new?title=${tagName}">${tagName}</a>`}}}exports.Blacklist=Blacklist},{"../../modules/search/BlacklistEnhancer":56,"../ModuleController":1,"../post/Post":19,"../post/PostFilter":21,"../utility/Util":33,"./User":18}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KeybindManager=void 0;const Debug_1=require("../utility/Debug");class KeybindManager{static register(keybind){if(Array.isArray(keybind))for(const entry of keybind)this.register(entry);else{this.refreshListener(keybind.keys);for(const key of keybind.keys)0!=key.length&&(this.executors.get(key)[keybind.bindMeta]=keybind)}}static unregister(bindMeta){Array.isArray(bindMeta)||(bindMeta=[bindMeta]);for(const executor of this.executors.values())for(const key of Object.keys(executor))bindMeta.includes(key)&&delete executor[key]}static record(callback){this.listening=!0,Mousetrap.record(sequence=>{this.listening=!1,callback(sequence)})}static count(sequence){return this.executors.has(sequence)?Object.keys(this.executors.get(sequence)).length:0}static refreshListener(keys){for(const key of keys)this.listeners.has(key)||(this.listeners.set(key,()=>{if(KeybindManager.listening)return;const listenerExecutor=this.executors.get(key);Debug_1.Debug.log("["+key+"]: triggered "+Object.entries(listenerExecutor).length+" executors");for(const[bindMeta,keyObj]of Object.entries(listenerExecutor))keyObj.enabled&&keyObj.fnct(bindMeta)}),Mousetrap.bind(key,()=>{this.listeners.get(key)()},"keyup")),this.executors.has(key)||this.executors.set(key,{})}static getData(){console.log(this.listeners),console.log(this.executors)}}exports.KeybindManager=KeybindManager,KeybindManager.listeners=new Map,KeybindManager.executors=new Map,KeybindManager.listening=!1},{"../utility/Debug":30}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PageDefintion=exports.Page=void 0;class Page{constructor(){this.url=new URL(window.location.toString())}static matches(filter){filter instanceof RegExp&&(filter=[filter]);const pathname=this.getInstance().url.pathname.replace(/[\/?]$/g,"");let result=!1;return filter.forEach((function(constraint){result=result||constraint.test(pathname)})),result}static getURL(){return this.getInstance().url}static getQueryParameter(key){return this.getInstance().url.searchParams.get(key)}static setQueryParameter(key,value){this.getInstance().url.searchParams.set(key,value),this.refreshCurrentUrl()}static removeQueryParameter(key){this.getInstance().url.searchParams.delete(key),this.refreshCurrentUrl()}static refreshCurrentUrl(){const url=this.getInstance().url,searchPrefix=0===url.searchParams.toString().length?"":"?";history.replaceState({},"",url.origin+url.pathname+searchPrefix+url.searchParams.toString())}static getSiteName(){return this.getInstance().url.hostname.replace(/\.net/g,"")}static getPageID(){return this.getInstance().url.pathname.split("/")[2]}static getInstance(){return void 0===this.instance&&(this.instance=new Page),this.instance}}exports.Page=Page,exports.PageDefintion={title:/^(\/)?$/,search:/^\/posts\/?$/,post:/^\/posts\/\d+\/?(show_seq)?$/,upload:/\/uploads\/new\/?/,forum:/^\/forum_topics\/?.*/,forumPost:/^\/forum_topics\/\d+.*/,pool:/^\/pools\/.+/,set:/^\/post_sets\/.+/,popular:/^\/explore\/posts\/popular.?/,favorites:/^\/favorites\/?.*/,wiki:/^\/wiki_pages\/[0-9]+/,wikiNA:/^\/wiki_pages\/show_or_new.*/,artist:/^\/artists\/[0-9]+/,comments:/^\/comments\??.*/g,settings:/^\/users\/\d+\/edit$/g}},{}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tag=exports.TagTypes=void 0,function(TagTypes){TagTypes.Artist="artist",TagTypes.Character="character",TagTypes.Copyright="copyright",TagTypes.Species="species",TagTypes.General="general",TagTypes.Meta="meta",TagTypes.Lore="lore"}(exports.TagTypes||(exports.TagTypes={}));class Tag{static isArist(tag){return-1===Tag.nonArtistTags.indexOf(tag)}static escapeSearchToRegex(string){return new RegExp(string.replace(/[-\/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,"[\\S]*?"))}}exports.Tag=Tag,Tag.nonArtistTags=["unknown_artist","unknown_artist_signature","unknown_colorist","anonymous_artist","avoid_posting","conditional_dnp","sound_warning","epilepsy_warning"]},{}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.User=void 0;const E621_1=require("../api/E621");exports.User=class{constructor(){const $ref=$("body");this.loggedin="false"==$ref.attr("data-user-is-anonymous"),this.username=$ref.attr("data-user-name")||"Anonymous",this.userid=parseInt($ref.attr("data-user-id"))||0,this.level=$ref.attr("data-user-level-string")||"Guest"}static isLoggedIn(){return this.getInstance().loggedin}static getUsername(){return this.getInstance().username}static getUserID(){return this.getInstance().userid}static getLevel(){return this.getInstance().level}static async getCurrentSettings(){return E621_1.E621.User.id(this.getUserID()).first()}static async setSettings(data){await E621_1.E621.User.id(this.getUserID()).post({user:data,_method:"patch"})}static getInstance(){return null==this.instance&&(this.instance=new this),this.instance}}},{"../api/E621":5}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LoadedFileType=exports.PostData=exports.Post=void 0;const BetterSearch_1=require("../../modules/search/BetterSearch"),CustomFlagger_1=require("../../modules/search/CustomFlagger"),APIPost_1=require("../api/responses/APIPost"),Blacklist_1=require("../data/Blacklist"),Tag_1=require("../data/Tag"),ModuleController_1=require("../ModuleController"),Debug_1=require("../utility/Debug"),Util_1=require("../utility/Util"),PostParts_1=require("./PostParts"),PostSet_1=require("./PostSet");class Post{constructor(data,$ref){for(const[key,value]of Object.entries(data))this[key]=value;this.$ref=$ref,this.$ref.data("post",this),this.updateFilters()}update(data){for(const[key,value]of Object.entries(PostData.fromAPI(data)))this[key]=value;return this.updateFilters(),this}isRendered(){return"true"==this.$ref.attr("rendered")}isBlacklisted(){return"true"==this.$ref.attr("blacklisted")}render(){const conf=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings(["imageRatioChange","clickAction","imageLoadMethod","autoPlayGIFs","hoverTags","ribbonsFlag","ribbonsRel","buttonsVote","buttonsFav"]);return this.$ref.attr({fav:1==this.is_favorited?"true":void 0,rendered:!0}).removeAttr("style").html(""),this.$ref.append(PostParts_1.PostParts.renderImage(this,conf)).append(PostParts_1.PostParts.renderRibbons(this,conf)).append(PostParts_1.PostParts.renderButtons(this,conf)).append(PostParts_1.PostParts.renderFlags(this)).append(PostParts_1.PostParts.renderInfo(this)),conf.imageRatioChange||this.$ref.css("--img-ratio",this.img.ratio),this.updateVisibility(),this}reset(){return this.$ref.attr({rendered:!1,loading:!1}).html(this.id+"").children().remove(),this.$ref.off("re621:update"),this}updateFilters(){return CustomFlagger_1.CustomFlagger.addPost(this),Blacklist_1.Blacklist.addPost(this),this}updateVisibility(){return Blacklist_1.Blacklist.checkPost(this.id)?(this.$ref.attr("blacklisted","true"),this.isRendered()&&this.reset()):this.$ref.removeAttr("blacklisted"),this}static get(post){return"number"==typeof post&&0==(post=$("#entry_"+post).first()).length?null:post.data("post")}static getViewingPost(){const container=$("#image-container");return void 0!==container.data("post")?Post.get(container):new Post(PostData.fromDOM(),container)}static find(type){const result=new PostSet_1.PostSet;switch(type){case"hovering":case"blacklisted":case"rendered":for(const elem of $(`post[${type}=true]`).get())result.push(Post.get($(elem)));break;case"all":for(const elem of $("post").get())result.push(Post.get($(elem)))}return result}static make(data,page,imageRatioChange){const tags=APIPost_1.APIPost.getTagSet(data),flags=APIPost_1.PostFlag.get(data),animated=tags.has("animated")||"webm"==data.file.ext||"gif"==data.file.ext||"swf"==data.file.ext;null==imageRatioChange&&(imageRatioChange=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings("imageRatioChange"));const $article=$("<post>").attr({id:"entry_"+data.id,fav:1==data.is_favorited||void 0,vote:void 0,animated:animated?"true":void 0,filetype:data.file.ext,deleted:!!flags.has(APIPost_1.PostFlag.Deleted)||void 0,rendered:!1,page:page}).data({id:data.id,"large-file-url":data.sample.url,"file-ext":data.file.ext}).html(data.id+"");imageRatioChange||$article.css("--img-ratio",data.file.height/data.file.width+"");const result=new Post(PostData.fromAPI(data,page),$article);return result.file.original||result.flags.has(APIPost_1.PostFlag.Deleted)?(result.updateFilters(),result.updateVisibility(),result):(Debug_1.Debug.log(`Post #${result.id} skipped: no file`),null)}}var PostData;exports.Post=Post,function(PostData){PostData.fromAPI=function(data,page){const tags=APIPost_1.APIPost.getTagSet(data),flags=APIPost_1.PostFlag.get(data);return{id:data.id,flags:flags,score:data.score.total,user_score:void 0,favorites:data.fav_count,is_favorited:1==data.is_favorited,comments:data.comment_count,rating:APIPost_1.PostRating.fromValue(data.rating),uploader:data.uploader_id,page:page,date:{raw:null==data.created_at?data.updated_at:data.created_at,ago:Util_1.Util.Time.ago(null==data.created_at?data.updated_at:data.created_at)},tagString:[...tags].sort().join(" "),tags:{all:tags,artist:new Set(data.tags.artist),real_artist:new Set(data.tags.artist.filter(tag=>Tag_1.Tag.isArist(tag))),copyright:new Set(data.tags.copyright),species:new Set(data.tags.species),character:new Set(data.tags.character),general:new Set(data.tags.general),invalid:new Set(data.tags.invalid),meta:new Set(data.tags.meta),lore:new Set(data.tags.lore)},file:{ext:data.file.ext,md5:data.file.md5,original:data.file.url,sample:data.sample.url,preview:data.preview.url,size:data.file.size},loaded:void 0,img:{width:data.file.width,height:data.file.height,ratio:data.file.height/data.file.width},has:{file:null!==data.file.url,children:data.relationships.has_active_children,parent:void 0!==data.relationships.parent_id&&null!==data.relationships.parent_id},rel:{children:new Set(data.relationships.children),parent:data.relationships.parent_id}}},PostData.fromDOM=function(){const $article=$("#image-container"),id=parseInt($article.attr("data-id"))||0,timeEl=$("#post-information").find("time"),time=0!=timeEl.length?timeEl.attr("title"):"0",children=new Set;for(const post of $("div#has-children-relationship-preview").find("article").get())children.add(parseInt($(post).attr("data-id")));const tagString=$article.attr("data-tags")||"",artistTags=getTags("artist");let md5;$article.attr("data-md5")?md5=$article.attr("data-md5"):$article.attr("data-file-url")&&(md5=$article.attr("data-file-url").substring(36,68));let score=0;$article.attr("data-score")?score=parseInt($article.attr("data-score")):0!==$article.find(".post-score-score").length&&(score=parseInt($article.find(".post-score-score").first().html().substring(1)));let userScore=0;$(".post-vote-up-"+id).first().hasClass("score-positive")?userScore=1:$(".post-vote-down-"+id).first().hasClass("score-negative")&&(userScore=-1);const width=parseInt($article.attr("data-width")),height=parseInt($article.attr("data-height"));return{id:id,flags:APIPost_1.PostFlag.fromString($article.attr("data-flags")||""),score:score,user_score:userScore,favorites:parseInt($article.attr("data-fav-count"))||0,is_favorited:"true"==$article.attr("data-is-favorited"),comments:-1,rating:APIPost_1.PostRating.fromValue($article.attr("data-rating")),uploader:parseInt($article.attr("data-uploader-id"))||0,page:"-1",date:{raw:time,ago:Util_1.Util.Time.ago(time)},tagString:tagString,tags:{all:new Set(tagString.split(" ")),artist:artistTags,real_artist:new Set([...artistTags].filter(tag=>Tag_1.Tag.isArist(tag))),copyright:getTags("copyright"),species:getTags("species"),character:getTags("character"),general:getTags("general"),invalid:getTags("invalid"),meta:getTags("meta"),lore:getTags("lore")},file:{ext:$article.attr("data-file-ext"),md5:md5,original:$article.attr("data-file-url")||null,sample:$article.attr("data-large-file-url")||null,preview:$article.attr("data-preview-file-url")||null,size:0},loaded:void 0,img:{width:width,height:height,ratio:height/width},has:{file:void 0!==$article.attr("data-file-url"),children:"true"==$article.attr("data-has-active-children"),parent:void 0!==$article.attr("data-parent-id")},rel:{children:children,parent:parseInt($article.attr("data-parent-id"))||null}};function getTags(group){const result=new Set;for(const element of $(`#tag-list .${group}-tag-list`).children())result.add($(element).find(".search-tag").text().replace(/ /g,"_"));return result}},PostData.fromThumbnail=function($article){const id=parseInt($article.attr("data-id"))||0,children=new Set,tagString=$article.attr("data-tags")||"",width=parseInt($article.attr("data-width")),height=parseInt($article.attr("data-height")),extension=$article.attr("data-file-ext");let md5,urls={};$article.hasClass("post-preview")?($article.attr("data-md5")?md5=$article.attr("data-md5"):$article.attr("data-file-url")&&(md5=$article.attr("data-file-url").substr(36,32)),urls={preview:$article.attr("data-preview-file-url")||null,sample:$article.attr("data-large-file-url")||null,original:$article.attr("data-file-url")||null}):($article.attr("data-md5")?md5=$article.attr("data-md5"):$article.attr("data-preview-url")&&(md5=$article.attr("data-preview-url").substr(44,32)),urls=null==md5?{preview:"/images/deleted-preview.png",sample:"/images/deleted-preview.png",original:"/images/deleted-preview.png"}:{preview:$article.attr("data-preview-url")||null,sample:width<850||height<850?`https://static1.e621.net/data/${md5.substr(0,2)}/${md5.substr(2,2)}/${md5}.${extension}`:`https://static1.e621.net/data/sample/${md5.substr(0,2)}/${md5.substr(2,2)}/${md5}.jpg`,original:`https://static1.e621.net/data/${md5.substr(0,2)}/${md5.substr(2,2)}/${md5}.${extension}`});const rawDate=$article.attr("data-created-at")||"0";return{id:id,flags:APIPost_1.PostFlag.fromString($article.attr("data-flags")||""),score:parseInt($article.attr("data-score")||"0"),user_score:0,favorites:parseInt($article.attr("data-fav-count"))||0,is_favorited:"true"==$article.attr("data-is-favorited"),comments:-1,rating:APIPost_1.PostRating.fromValue($article.attr("data-rating")),uploader:parseInt($article.attr("data-uploader-id"))||0,page:"-1",date:{raw:rawDate,ago:Util_1.Util.Time.ago(rawDate)},tagString:tagString,tags:{all:new Set(tagString.split(" ")),artist:new Set,real_artist:new Set,copyright:new Set,species:new Set,character:new Set,general:new Set,invalid:new Set,meta:new Set,lore:new Set},file:{ext:extension,md5:md5,original:urls.original,sample:urls.sample,preview:urls.preview,size:0},loaded:void 0,img:{width:width,height:height,ratio:height/width},has:{file:void 0!==$article.attr("data-file-url"),children:"true"==$article.attr("data-has-active-children"),parent:void 0!==$article.attr("data-parent-id")},rel:{children:children,parent:parseInt($article.attr("data-parent-id"))||null}}},PostData.createPreviewUrlFromMd5=function(md5){return""==md5?"https://static1.e621.net/images/download-preview.png":`https://static1.e621.net/data/preview/${md5.substring(0,2)}/${md5.substring(2,4)}/${md5}.jpg`}}(PostData=exports.PostData||(exports.PostData={})),function(LoadedFileType){LoadedFileType.PREVIEW="preview",LoadedFileType.SAMPLE="sample",LoadedFileType.ORIGINAL="original"}(exports.LoadedFileType||(exports.LoadedFileType={}))},{"../../modules/search/BetterSearch":55,"../../modules/search/CustomFlagger":57,"../ModuleController":1,"../api/responses/APIPost":11,"../data/Blacklist":14,"../data/Tag":17,"../utility/Debug":30,"../utility/Util":33,"./PostParts":22,"./PostSet":23}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostActions=void 0;const E621_1=require("../api/E621"),Debug_1=require("../utility/Debug");class PostActions{static async toggleSet(setID,postID){const setData=await E621_1.E621.Set.id(setID).first({},500);if(null==setData)return Danbooru.error("Error: active set moved or deleted"),Promise.resolve(!1);setData.post_ids.includes(postID)?PostActions.removeSet(setID,postID):PostActions.addSet(setID,postID)}static addSet(setID,postID){return E621_1.E621.SetAddPost.id(setID).post({"post_ids[]":[postID]},500).then(response=>201==response[1]?(Danbooru.notice(`<a href="/post_sets/${setID}">${response[0].name}</a>: post <a href="/posts/${postID}">#${postID}</a> added (${response[0].post_count} total)`),Promise.resolve(!0)):(Danbooru.error("Error occured while adding the post to set: "+response[1]),Promise.resolve(!1)),response=>(Danbooru.error("Error occured while adding the post to set: "+response[1]),Promise.resolve(!1)))}static removeSet(setID,postID){return E621_1.E621.SetRemovePost.id(setID).post({"post_ids[]":[postID]},500).then(response=>201==response[1]?(Danbooru.notice(`<a href="/post_sets/${setID}">${response[0].name}</a>: post <a href="/posts/${postID}">#${postID}</a> removed (${response[0].post_count} total)`),Promise.resolve(!0)):(Danbooru.error("Error occured while removing the post from set: "+response[1]),Promise.resolve(!1)),response=>(Danbooru.error("Error occured while removing the post from set: "+response[1]),Promise.resolve(!1)))}static vote(postID,score,preventUnvote=!1){return new Promise(resolve=>{E621_1.E621.PostVotes.id(postID).post({score:score,no_unvote:preventUnvote}).then(success=>{Debug_1.Debug.log(success),resolve({success:!0,action:success[0].our_score,score:success[0].score,up:success[0].up,down:success[0].down})},error=>{console.log(error),resolve({success:!1})})})}static addFavorite(postID){return new Promise(resolve=>{E621_1.E621.Favorites.post({post_id:postID}).then(response=>{Debug_1.Debug.log(response),resolve(!0)},error=>{console.log(error),resolve(!1)})})}static removeFavorite(postID){return new Promise(resolve=>{E621_1.E621.Favorite.id(postID).delete().then(response=>{Debug_1.Debug.log(response),resolve(!0)},error=>{console.log(error),resolve(!1)})})}}exports.PostActions=PostActions},{"../api/E621":5,"../utility/Debug":30}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostFilter=void 0;const APIPost_1=require("../api/responses/APIPost"),Tag_1=require("../data/Tag");exports.PostFilter=class{constructor(input,enabled=!0){this.input=input.toLowerCase().trim(),this.entries=[],this.enabled=enabled,this.matchIDs=new Set,this.optionals=0;for(let filter of new Set(this.input.split(" ").filter(e=>""!=e))){const optional=filter.startsWith("~");optional&&(filter=filter.substring(1),this.optionals++);const inverse=filter.startsWith("-");inverse&&(filter=filter.substring(1));const filterType=FilterType.test(filter);filterType!==FilterType.Tag&&(filter=filter.substring(filterType.length));const comparison=ComparisonType.test(filter);comparison!==ComparisonType.Equals&&(filter=filter.substring(comparison.length)),this.entries.push({type:filterType,value:filter,inverted:inverse,optional:optional,comparison:comparison})}}getName(){return this.input}update(post,shouldDecrement=!0){if(Array.isArray(post)){let result=!0;for(const entry of post)result=!!this.update(entry)&&result;return result}let result=!0,optionalHits=0;for(const filter of this.entries){const value=filter.value;switch(filter.type){case FilterType.Flag:result=post.flags.has(APIPost_1.PostFlag.fromSingle(value));break;case FilterType.Id:result=PostFilterUtils.compareNumbers(post.id,parseInt(value),filter.comparison);break;case FilterType.Rating:result=post.rating===APIPost_1.PostRating.fromValue(value);break;case FilterType.Score:result=PostFilterUtils.compareNumbers(post.score,parseInt(value),filter.comparison);break;case FilterType.Tag:result=PostFilterUtils.tagsMatchesFilter(post,value);break;case FilterType.Uploader:result=post.uploader===parseInt(value);break;case FilterType.Fav:result=post.is_favorited}if(filter.inverted&&(result=!result),filter.optional)optionalHits+=result?1:0;else if(!result)break}return result=result&&(0==this.optionals||optionalHits>0),!0===result?this.matchIDs.add(post.id):!1===result&&shouldDecrement&&this.matchIDs.delete(post.id),result}matches(post,ignoreDisabled=!1){return this.matchesID(post.id,ignoreDisabled)}matchesID(id,ignoreDisabled=!1){return(this.enabled||ignoreDisabled)&&this.matchIDs.has(id)}getMatches(){return this.matchIDs}getMatchesCount(){return this.matchIDs.size}toggleEnabled(){this.enabled=!this.enabled}setEnabled(enabled){this.enabled=enabled}isEnabled(){return this.enabled}};class PostFilterUtils{static compareNumbers(a,b,mode){switch(mode){case ComparisonType.Equals:return a===b;case ComparisonType.Smaller:return a<b;case ComparisonType.EqualsSmaller:return a<=b;case ComparisonType.Larger:return a>b;case ComparisonType.EqualsLarger:return a>=b}}static tagsMatchesFilter(post,filter){if(filter.includes("*")){return Tag_1.Tag.escapeSearchToRegex(filter).test(post.tagString)}return post.tags.all.has(filter)}}var FilterType,ComparisonType;!function(FilterType){FilterType.Tag="tag:",FilterType.Id="id:",FilterType.Score="score:",FilterType.Rating="rating:",FilterType.Uploader="uplaoder:",FilterType.Flag="status:",FilterType.Fav="fav:"}(FilterType||(FilterType={})),function(FilterType){FilterType.test=function(input){input=input.toLowerCase();for(const key of Object.keys(FilterType))if(input.startsWith(FilterType[key]))return FilterType[key];return FilterType.Tag}}(FilterType||(FilterType={})),function(ComparisonType){ComparisonType.EqualsSmaller="<=",ComparisonType.EqualsLarger=">=",ComparisonType.Equals="=",ComparisonType.Smaller="<",ComparisonType.Larger=">"}(ComparisonType||(ComparisonType={})),function(ComparisonType){ComparisonType.test=function(input){input=input.toLowerCase();for(const key of Object.keys(ComparisonType))if(input.startsWith(ComparisonType[key]))return ComparisonType[key];return ComparisonType.Equals}}(ComparisonType||(ComparisonType={}))},{"../api/responses/APIPost":11,"../data/Tag":17}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostParts=void 0;const BetterSearch_1=require("../../modules/search/BetterSearch"),CustomFlagger_1=require("../../modules/search/CustomFlagger"),Danbooru_1=require("../api/Danbooru"),APIPost_1=require("../api/responses/APIPost"),XM_1=require("../api/XM"),Blacklist_1=require("../data/Blacklist"),Page_1=require("../data/Page"),DomUtilities_1=require("../structure/DomUtilities"),Util_1=require("../utility/Util"),Post_1=require("./Post"),PostActions_1=require("./PostActions");class PostParts{static renderImage(post,conf){const query=Page_1.Page.getQueryParameter("tags"),$link=$("<a>").attr({href:"/posts/"+post.id+(null!==query?"?q="+query:"")}).append(PostParts.renderImageElement(post,conf)).append($("<post-loading>"));return conf.clickAction!==BetterSearch_1.ImageClickAction.Disabled&&PostParts.handleDoubleClick($link,post,conf),$link}static handleDoubleClick($link,post,conf){let dbclickTimer,prevent=!1;$link.on("click.re621.dblextra",event=>{if(!(0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||BetterSearch_1.BetterSearch.isPaused()||"view"!==$("#mode-box-mode").val()))return event.preventDefault(),dbclickTimer=window.setTimeout(()=>{prevent||($link.off("click.re621.dblextra"),$link[0].click()),prevent=!1},200),!1}),$link.on("dblclick.re621.dblextra",event=>{if(!(0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||BetterSearch_1.BetterSearch.isPaused()||"view"!==$("#mode-box-mode").val()))switch(event.preventDefault(),window.clearTimeout(dbclickTimer),prevent=!0,post.$ref.addClass("highlight"),window.setTimeout(()=>post.$ref.removeClass("highlight"),250),conf.clickAction){case BetterSearch_1.ImageClickAction.NewTab:XM_1.XM.Util.openInTab(window.location.origin+$link.attr("href"),!1);break;case BetterSearch_1.ImageClickAction.CopyID:XM_1.XM.Util.setClipboard(post.id+"","text"),Danbooru_1.Danbooru.notice(`Copied post ID to clipboard: <a href="/posts/${post.id}" target="_blank">#${post.id}</a>`);break;case BetterSearch_1.ImageClickAction.Blacklist:Blacklist_1.Blacklist.toggleBlacklistTag("id:"+post.id);break;case BetterSearch_1.ImageClickAction.AddToSet:{const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.addSet(lastSet,post.id):Danbooru_1.Danbooru.error("Error: no set selected");break}case BetterSearch_1.ImageClickAction.ToggleSet:{const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.toggleSet(lastSet,post.id):Danbooru_1.Danbooru.error("Error: no set selected");break}default:$link.off("click.re621.dblextra"),$link[0].click()}})}static renderImageElement(post,conf){post.$ref.attr("loading","true");const $image=$("<img>").attr("src",DomUtilities_1.DomUtilities.getPlaceholderImage()).one("load",()=>{post.$ref.removeAttr("loading")});if(conf.hoverTags&&$image.attr("title",PostParts.formatHoverText(post)),post.flags.has(APIPost_1.PostFlag.Deleted))post.img.ratio=1,post.loaded=Post_1.LoadedFileType.ORIGINAL;else if("swf"===post.file.ext)post.img.ratio=1,post.loaded=Post_1.LoadedFileType.ORIGINAL;else if("gif"!==post.file.ext||conf.imageLoadMethod!=BetterSearch_1.ImageLoadMethod.Always||conf.autoPlayGIFs){const size=function(cur,req){if(!cur)return req==BetterSearch_1.ImageLoadMethod.Always?Post_1.LoadedFileType.SAMPLE:Post_1.LoadedFileType.PREVIEW;if(req==BetterSearch_1.ImageLoadMethod.Always)return Post_1.LoadedFileType.SAMPLE;if(req==BetterSearch_1.ImageLoadMethod.Disabled)return Post_1.LoadedFileType.PREVIEW;return cur}(post.loaded,conf.imageLoadMethod);size==Post_1.LoadedFileType.SAMPLE?$image.attr("src",post.file.sample):$image.attr("src",post.file.preview),post.loaded=size}else if(post.loaded==Post_1.LoadedFileType.SAMPLE)$image.attr("src",post.file.sample);else{let timer;$image.attr("src",post.file.preview),post.loaded=Post_1.LoadedFileType.PREVIEW,$image.on("mouseenter.re621.upscale",()=>{timer=window.setTimeout(()=>{post.$ref.attr("loading","true"),post.loaded=Post_1.LoadedFileType.SAMPLE,$image.attr("src",post.file.sample).on("load",()=>{post.$ref.removeAttr("loading"),$image.off("mouseenter.re621.upscale").off("mouseleave.re621.upscale")})},200)}),$image.on("mouseleave.re621.upscale",()=>{window.clearTimeout(timer)})}if(conf.imageLoadMethod==BetterSearch_1.ImageLoadMethod.Hover&&post.loaded==Post_1.LoadedFileType.PREVIEW){let timer;$image.on("mouseenter.re621.upscale",()=>{timer=window.setTimeout(()=>{post.$ref.attr("loading","true"),post.loaded=Post_1.LoadedFileType.SAMPLE,$image.attr("src",post.file.sample).one("load",()=>{post.$ref.removeAttr("loading"),$image.off("mouseenter.re621.upscale").off("mouseleave.re621.upscale")})},200)}),$image.on("mouseleave.re621.upscale",()=>{window.clearTimeout(timer)})}return $image}static renderRibbons(post,conf){const $ribbons=$("<img-ribbons>");if(conf.ribbonsRel){const relRibbon=$("<ribbon>").addClass("left").html("<span></span>").appendTo($ribbons),relRibbonText=[];post.has.children&&(relRibbon.addClass("has-children"),relRibbonText.push("Child posts")),post.has.parent&&(relRibbon.addClass("has-parent"),relRibbonText.push("Parent posts")),relRibbonText.length>0?relRibbon.attr("title",relRibbonText.join("\n")):relRibbon.remove()}if(conf.ribbonsFlag){const flagRibbon=$("<ribbon>").addClass("right").html("<span></span>").appendTo($ribbons),flagRibbonText=[];post.flags.has(APIPost_1.PostFlag.Flagged)&&(flagRibbon.addClass("is-flagged"),flagRibbonText.push("Flagged")),post.flags.has(APIPost_1.PostFlag.Pending)&&(flagRibbon.addClass("is-pending"),flagRibbonText.push("Pending")),flagRibbonText.length>0?flagRibbon.attr("title",flagRibbonText.join("\n")):flagRibbon.remove()}if(0!=$ribbons.children().length)return $ribbons}static renderButtons(post,conf){const $voteBox=$("<post-voting>");if(conf.buttonsVote&&($("<button>").addClass("button voteButton vote score-neutral").attr("action","up").appendTo($voteBox).on("click",event=>{event.preventDefault();const firstVote=null==post.$ref.attr("vote");PostActions_1.PostActions.vote(post.id,1,firstVote).then(response=>{0==response.action?firstVote?post.$ref.attr("vote","1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)})}),$("<button>").addClass("button voteButton vote score-neutral").attr("action","down").appendTo($voteBox).on("click",event=>{event.preventDefault();const firstVote=null==parseInt(post.$ref.attr("vote"));PostActions_1.PostActions.vote(post.id,-1,firstVote).then(response=>{0==response.action?firstVote?post.$ref.attr("vote","-1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)})})),conf.buttonsFav){let favBlock=!1;const $btn=$("<button>").addClass("button voteButton fav score-neutral").appendTo($voteBox).on("click",async event=>{event.preventDefault(),favBlock||(favBlock=!0,post.is_favorited?(await PostActions_1.PostActions.removeFavorite(post.id),post.is_favorited=!1,post.$ref.removeAttr("fav"),$btn.removeClass("score-favorite")):(await PostActions_1.PostActions.addFavorite(post.id),post.is_favorited=!0,post.$ref.attr("fav","true"),$btn.addClass("score-favorite")),favBlock=!1)})}return $voteBox}static renderFlags(post){const $flagBox=$("<post-flags>");for(const flag of CustomFlagger_1.CustomFlagger.getFlags(post))$("<span>").addClass("custom-flag-thumb").css("--flag-color",flag.color).attr("title",flag.tags).html(flag.name).appendTo($flagBox);if(0!=$flagBox.children().length)return $flagBox}static renderInfo(post){const $infoBlock=$("<post-info>");return post.$ref.on("re621:update",()=>{$infoBlock.html(getPostInfo(post))}),$infoBlock.html(getPostInfo(post)),$infoBlock;function getPostInfo(post){return`\n <span class="post-info-score score-${post.score>0?"positive":post.score<0?"negative":"neutral"}">${post.score}</span>\n <span class="post-info-favorites">${post.favorites}</span>\n <span class="post-info-comments">${post.comments}</span>\n <span class="post-info-rating rating-${post.rating}">${post.rating}</span>\n `}}static formatHoverText(post,compact=!1,html=!1){const br=html?"<br>\n":"\n";return compact?[...post.tags.artist,...post.tags.copyright].join(" ")+" "+[...post.tags.character,...post.tags.species].join(" ")+" "+[...post.tags.general,...post.tags.invalid,...post.tags.lore,...post.tags.meta].join(" "):`Post #${post.id}, posted on: ${Util_1.Util.Time.format(post.date.raw)} (${post.date.ago})${br}${[...post.tags.artist,...post.tags.copyright].join(" ")}${br}${[...post.tags.character,...post.tags.species].join(" ")}${br}${[...post.tags.general,...post.tags.invalid,...post.tags.lore,...post.tags.meta].join(" ")}${br}`}}exports.PostParts=PostParts},{"../../modules/search/BetterSearch":55,"../../modules/search/CustomFlagger":57,"../api/Danbooru":3,"../api/XM":6,"../api/responses/APIPost":11,"../data/Blacklist":14,"../data/Page":16,"../structure/DomUtilities":25,"../utility/Util":33,"./Post":19,"./PostActions":20}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostSortType=exports.PostSet=void 0;class PostSet{constructor(posts){this.posts=posts||[]}push(post){this.posts.push(post)}pop(){return this.posts.pop()}size(){return this.posts.length}reverse(){return new PostSet(this.posts.reverse())}values(){return this.posts.values()}each(fn){for(const entry of this.posts)fn(entry)}sort(type){switch(type||(type=PostSortType.ID),type){case PostSortType.Size:return this.sort(PostSortType.Size).reverse();case PostSortType.SizeAsc:return new PostSet([...this.posts.sort((a,b)=>a.file.size-b.file.size)]);case PostSortType.ID:return this.sort(PostSortType.ID).reverse();case PostSortType.IDAsc:return new PostSet([...this.posts.sort((a,b)=>a.id-b.id)])}}}var PostSortType;exports.PostSet=PostSet,function(PostSortType){PostSortType.ID="id",PostSortType.IDAsc="id_asc",PostSortType.Size="size",PostSortType.SizeAsc="size_asc"}(PostSortType=exports.PostSortType||(exports.PostSortType={}))},{}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CleanSlate=void 0;const XM_1=require("../api/XM"),Page_1=require("../data/Page"),ErrorHandler_1=require("../utility/ErrorHandler"),Util_1=require("../utility/Util"),DomUtilities_1=require("./DomUtilities");exports.CleanSlate=class{static async run(){const actions=[];return actions.push({selector:"head",action:async()=>{try{const css=await XM_1.XM.Connect.getResourceText("re621_css"),stylesheet=DomUtilities_1.DomUtilities.addStyle(css);return $(()=>{stylesheet.appendTo("head")}),Promise.resolve(stylesheet)}catch(error){ErrorHandler_1.ErrorHandler.error("DOM",error.stack,"styles")}"undefined"==typeof GM&&$("<script>").attr("src",XM_1.XM.Chrome.getResourceURL("injector.js")).appendTo("head")}}),actions.push({selector:"body",action:()=>{$("body").attr({"data-th-main":window.localStorage.getItem("theme"),"data-th-extra":window.localStorage.getItem("theme-extra"),"data-th-nav":window.localStorage.getItem("theme-nav")})}}),actions.push({selector:"#page",action:()=>{$("<div>").attr("id","modal-container").prependTo("div#page")}}),actions.push({selector:"#nav",action:()=>{const $menuContainer=$("nav#nav"),$menuMain=$("menu.main");$("#nav").find("menu").length<2&&$menuContainer.append("<menu>");const titlePageRouting=Util_1.Util.LS.getItem("re621.mainpage")||"default";$("<menu>").addClass("logo desktop-only").html(`<a href="${"default"==titlePageRouting?"/":"/"+titlePageRouting}" data-ytta-id="-">`+Page_1.Page.getSiteName()+"</a>").prependTo($menuContainer),$menuMain.find("a[href='/']").remove(),$("<menu>").addClass("extra").insertAfter($menuMain),$menuContainer.addClass("grid")}}),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites])&&"true"===Util_1.Util.LS.getItem("re621.bs.enabled")&&actions.push({selector:"div.paginator menu",action:()=>{$("div.paginator menu").css("display","none").attr("id","paginator-old").appendTo("body"),$("#content").html("")}}),this.elementsReady(actions)}static async elementsReady(actions){const processed=new Map;for(const action of actions)processed.set(action.selector,action.action);let iterations=0;return new Promise(resolve=>{new MutationObserver((function(){for(const[selector,action]of processed.entries())0!=$(selector).length&&(processed.delete(selector),action());iterations++,0==processed.size?(this.disconnect(),resolve(!0)):iterations>100&&(this.disconnect(),resolve(!1))})).observe(document,{childList:!0,subtree:!0})})}static async awaitFocus(){return new Promise(resolve=>{document.hasFocus()||"visible"==document.visibilityState?resolve(!0):$(window).one("focus",()=>{resolve(!0)})})}}},{"../api/XM":6,"../data/Page":16,"../utility/ErrorHandler":31,"../utility/Util":33,"./DomUtilities":25}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DomUtilities=void 0;const Page_1=require("../data/Page"),Util_1=require("../utility/Util");exports.DomUtilities=class{static createSearchbox(){if(Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites])&&$("aside#sidebar").length>0){const $searchContainer=$("<div>").attr("id","re621-search").prependTo("aside#sidebar");$("aside#sidebar section#search-box").appendTo($searchContainer),$("aside#sidebar section#mode-box").appendTo($searchContainer);new IntersectionObserver(([event])=>{$(event.target).toggleClass("re621-search-sticky bg-foreground",event.intersectionRatio<1)},{threshold:[1]}).observe($searchContainer[0])}}static createTagList(){$("#tag-box > ul > li, #tag-list > ul > li").each((index,element)=>{const $container=$(element),$tagLink=$container.find("a.search-tag").first();$("<span>").addClass("tag-wrap").insertAfter($tagLink).append($tagLink);const $actionsBox=$("<div>").addClass("tag-actions").attr("data-tag",$container.find("a.search-tag").text().replace(/ /g,"_")).appendTo($container);$("<span>").addClass("tag-action-blacklist").appendTo($actionsBox);const $countBox=$container.find(".post-count").first();$countBox.addClass("re621-post-count").attr("data-count-short",$countBox.text()).insertAfter($tagLink),$("<span>").addClass("tag-action-subscribe").appendTo($actionsBox)})}static addSettingsButton(config){void 0===config.name&&(config.name="T"),void 0===config.href&&(config.href=""),void 0===config.title&&(config.title=""),void 0===config.tabClass&&(config.tabClass=""),void 0===config.linkClass&&(config.linkClass=""),void 0===config.attr&&(config.attr={});const $tab=$("<li>").appendTo("menu.extra"),$link=$("<a>").html(config.name).attr({title:config.title,id:config.id}).appendTo($tab);return config.href&&$link.attr("href",config.href),config.tabClass&&$tab.addClass(config.tabClass),config.linkClass&&$link.addClass(config.linkClass),config.attr&&$link.attr(config.attr),$link}static addStyle(css){return $("<style>").attr({id:Util_1.Util.ID.make(),type:"text/css"}).html(css).appendTo("head")}static getPlaceholderImage(){return"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="}}},{"../data/Page":16,"../utility/Util":33}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FormElement=exports.Form=void 0;const XM_1=require("../api/XM"),Keybinds_1=require("../data/Keybinds"),Util_1=require("../utility/Util");class Form{constructor(options,content,onSubmit){options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),this.element=$("<form>").addClass("form-section"+(options.wrapper?" "+options.wrapper:"")).attr({id:options.name,columns:1!==options.columns?options.columns:null,formspan:1!==options.width?options.width:null}).on("submit",event=>{event.preventDefault();const values={};this.inputList.forEach((input,name)=>{"checkbox"==input.attr("type")?values[name]=input.is(":checked"):values[name]=input.val().toString()}),onSubmit(values,this)}),this.content=content,this.inputList=new Map}render(force=!1){if(this.created&&!force)return this.element;this.element[0].innerHTML="";const formID=this.element.attr("id");for(const entry of this.content)for(const childElem of entry.build(formID,force))childElem.appendTo(this.element);for(const entry of this.content)for(const input of entry.getInputs()){const name=input.attr("name");void 0!==name&&this.inputList.set(name,input)}return this.created=!0,this.element}reset(){this.inputList.forEach(input=>{const defval=input.attr("defval");void 0!==defval&&("checkbox"==input.attr("type")?input.prop("checked","true"==defval):input.val(defval))})}getInputList(...names){if(0==names.length)return this.inputList;const results=new Map;return this.inputList.forEach((input,name)=>{names.includes(name)&&results.set(name,input)}),results}static placeholder(width=1){return new Form({columns:width,width:width},[Form.spacer(width)]).render()}static section(options,content){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=$("<form-section>").toggleClass(options.wrapper,options.wrapper).attr({id:options.name,labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null});return new FormElement($element,void 0,$label,content)}static accordion(options,content){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=$("<form-accordion>").toggleClass(options.wrapper,options.wrapper).attr({id:options.name,labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null});return new FormElement($element,void 0,$label,content,void 0,postElement=>{postElement.accordion({active:options.active,animate:!1,collapsible:!0===options.collapsible,header:"form-header"}),postElement.find("form-section[aria-hidden=false]").css("display","")})}static accordionTab(options,content){options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns);const $label=$("<form-header>").attr("for",options.name).html(options.label||"TITLE_ERROR");options.subheader&&$("<span>").addClass("form-collapse-subheader").append(options.subheader).appendTo($label),options.badge&&$("<span>").addClass("form-collapse-badge").append(options.badge).appendTo($label);const $element=$("<form-section>").addClass("collapse-content").attr({id:options.name,labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null});return new FormElement($element,void 0,$label,content)}static collapse(options,content){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=$("<form-collapse>").attr({id:options.name,colspan:options.width||1}),header=$("<h3>").addClass("collapse-header").html(options.title||"Details").appendTo($element);options.badge&&$("<span>").addClass("form-collapse-badge").append(options.badge).appendTo(header);const container=$("<form-section>").addClass("collapse-content").attr({labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null}).appendTo($element);return $element.accordion({active:!options.collapsed,animate:!1,collapsible:!0,header:"h3"}),new FormElement($element,void 0,$label,content,container)}static input(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<input>").attr({type:"text",id:options.name,name:options.name}).addClass("bg-section color-text").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==options.value&&null!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}if(options.title&&$input.attr("title",options.title),options.pattern&&$input.attr("pattern",options.pattern),options.required&&$input.attr("required",""),void 0!==changed){let timer;$input.on("input",()=>{timer&&clearTimeout(timer),timer=window.setTimeout(()=>{changed($input.val().toString(),$input)},Form.inputTimeout)})}return new FormElement($element,$input,$label)}static copy(options){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("copybox"),$input=$("<input>").attr({type:"text",id:options.name,readonly:""}).addClass("bg-section color-text").appendTo($element);if(void 0!==options.value&&null!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}const $copybutton=$("<button>").attr({type:"button",id:options.name+"-copy"}).addClass("button btn-neutral border-highlight border-left").html('<i class="far fa-copy"></i>').appendTo($element);let copyTimer;return options.title&&($input.attr("title",options.title),$copybutton.attr("title",options.title)),$($copybutton).click((function(){XM_1.XM.Util.setClipboard($input.val()),window.clearTimeout(copyTimer),$input.addClass("highlight"),copyTimer=window.setTimeout(()=>$input.removeClass("highlight"),250)})),new FormElement($element,$input,$label)}static key(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("keyinput"),$input=$("<input>").attr({type:"text",id:options.name,readonly:""}).addClass("bg-section color-text").appendTo($element);if(void 0!==options.value&&null!==options.value){switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}$input.attr("key",$input.val()+"")}const $warning=$("<span>").addClass("keyinput-warning").attr("title","Duplicate Keybinding").appendTo($element);Keybinds_1.KeybindManager.count($input.val()+"")<=1&&$warning.addClass("display-none");const $recordbutton=$("<button>").attr({type:"button",id:options.name+"-key"}).addClass("button btn-neutral border-highlight border-left").html('<i class="far fa-keyboard"></i>').appendTo($element);options.title&&($input.attr("title",options.title),$recordbutton.attr("title",options.title));let occupied=!1;return $($recordbutton).click((function(){if(occupied)return;occupied=!0;const duplicates=$(`.keyinput input[key="${$input.val()}"]`);duplicates.length>2?$warning.addClass("display-none"):duplicates.parent().find("span.keyinput-warning").addClass("display-none"),$input.addClass("input-info").val("Recording"),Keybinds_1.KeybindManager.record(sequence=>{if(sequence.includes("esc"))$input.removeClass("input-info").val("").attr("key",""),void 0!==changed&&changed("",$input),occupied=!1;else{const newVal=(input=(input=sequence).join("+").split("+"),(input=[...new Set(input)]).join("+"));$input.removeClass("input-info").val(newVal).attr("key",newVal);const duplicates=$(`.keyinput input[key="${newVal}"]`);duplicates.length>1&&duplicates.parent().find("span.keyinput-warning").removeClass("display-none"),void 0!==changed&&changed(newVal,$input),occupied=!1}var input})})),new FormElement($element,$input,$label)}static file(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("fileinput"),$input=$("<input>").attr({type:"file",accept:options.accept,id:options.name}).addClass("bg-section color-text").prop("disabled",1==options.disabled).appendTo($element);return options.title&&$input.attr("title",options.title),void 0!==changed&&$input.on("change",()=>{changed($input.prop("files"),$input)}),new FormElement($element,$input,$label)}static icon(options,content,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<input>").attr({type:"text",id:options.name,name:options.name}).css("display","none").appendTo($element);if(void 0!==options.value&&null!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}const $selectContainer=$("<div>").addClass("icon-picker").appendTo($element);for(const key in content)$("<a>").attr("href","#").attr("data-value",key).html(content[key]).appendTo($selectContainer);return $selectContainer.find("a").click(event=>{event.preventDefault(),$selectContainer.find("a").removeClass("active");const $target=$(event.target);$input.val($target.attr("data-value")),$target.addClass("active"),changed&&changed($input.val().toString(),$input)}),options.value?$selectContainer.find("a[data-value='"+options.value+"']").first().click():$selectContainer.find("a").first().click(),$input.on("re621:form:update",()=>{""==$input.val()?$selectContainer.find("a").first().click():$selectContainer.find("a[data-value='"+$input.val()+"']").first().click()}),new FormElement($element,$input,$label)}static button(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<button>").attr({id:options.name,type:options.type?options.type:"button"}).addClass("button btn-neutral").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==options.value&&null!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.append(options.value);break;case"number":case"boolean":options.value=options.value+"";default:$input.html(options.value).attr("defval",options.value)}return options.title&&$input.attr("title",options.title),void 0!==changed&&$input.on("click",event=>{event.preventDefault(),changed(!0,$input)}),new FormElement($element,$input,$label)}static checkbox(options,changed){options.name||(options.name=Util_1.Util.ID.make());const $element=FormUtils.makeInputWrapper(void 0,options.wrapper,options.width).addClass("checkbox-switch"),$input=$("<input>").attr({id:options.name,name:options.name,type:"checkbox"}).addClass("switch").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==options.value&&null!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":break;default:$input.prop("checked",options.value).attr("defval",options.value+"")}return $("<label>").attr("for",options.name).addClass("switch").appendTo($element),options.label&&$("<label>").attr("for",options.name).html(options.label).appendTo($element),void 0!==changed&&$input.on("change",()=>{changed($input.is(":checked"),$input)}),new FormElement($element,$input)}static select(options,content,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<select>").attr({id:options.name,name:options.name}).addClass("button btn-neutral").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==content){"function"==typeof content&&(content=content());for(const key in content)$("<option>").val(key).text(content[key]).appendTo($input)}if(void 0!==options.value&&null!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}return options.title&&$input.attr("title",options.title),void 0!==changed&&$input.on("change",()=>{changed($input.val().toString(),$input)}),new FormElement($element,$input,$label)}static header(text,width){const $element=FormUtils.makeInputWrapper(void 0,void 0,width);return $("<h3>").attr("id",Util_1.Util.ID.make()).addClass("color-text").html(text).appendTo($element),new FormElement($element)}static div(options){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("text-div").attr("id",options.name);if(void 0!==options.value&&null!==options.value)switch(typeof options.value){case"function":options.value($element);break;case"object":$element.append(options.value);break;case"number":case"boolean":options.value=options.value+"";default:$element.html(options.value)}return new FormElement($element,void 0,$label)}static text(text,width=1,wrapper){return Form.div({value:text,width:width,wrapper:wrapper})}static subheader(header,subheader,width=1,name,wrapper){return Form.div({value:`<b>${header}</b><br />${subheader}`,width:width,wrapper:"subheader"+(wrapper?" "+wrapper:""),name:name})}static hr(width){const $element=FormUtils.makeInputWrapper(void 0,void 0,width);return $("<hr>").attr("id",Util_1.Util.ID.make()).addClass("color-text-muted").appendTo($element),new FormElement($element)}static spacer(width,unmargin=!1){const $element=FormUtils.makeInputWrapper(void 0,void 0,width);return $("<spacer>").attr("id",Util_1.Util.ID.make()).toggleClass("unmargin",unmargin).appendTo($element),new FormElement($element)}}exports.Form=Form,Form.inputTimeout=500;class FormUtils{static makeLabel(name,text){return $("<label>").attr("for",name).html(text)}static makeInputWrapper(label,wrapper,width=1){return $("<form-input>").addClass(wrapper?" "+wrapper:"").attr({labeled:void 0!==label?"":null,colspan:1!==width?width:null})}}class FormElement{constructor(wrapper,input,label,content,container,postProcessing){this.wrapper=wrapper,this.input=input,this.label=label,this.content=content||[],this.container=container||wrapper,this.postProcessing=postProcessing||(()=>{})}getInput(){return this.input}getInputs(){const result=[];this.input&&result.push(this.input);for(const entry of this.content)result.push(...entry.getInputs());return result}build(parentID,force=!1){if(force||!this.created){for(const entry of this.content)for(const childElem of entry.build(parentID+"-"+this.wrapper.attr("id"),force))childElem.appendTo(this.container);switch(void 0!==this.label&&this.label.attr("for",parentID+"-"+this.label.attr("for")),void 0!==this.input&&this.input.attr("id",parentID+"-"+this.input.attr("id")),this.wrapper.prop("tagName")){case"FORM-INPUT":this.wrapper.attr("id")&&this.wrapper.attr("id",parentID+"-"+this.wrapper.attr("id"));for(const label of this.wrapper.find("> label")){const $subLabel=$(label);$subLabel.attr("for",parentID+"-"+$subLabel.attr("for"))}break;case"FORM-SECTION":case"FORM-ACCORDION":this.wrapper.attr("id",parentID+"-"+this.wrapper.attr("id"))}this.postProcessing(this.wrapper),this.created=!0}return this.label?[this.label,this.wrapper]:[this.wrapper]}}exports.FormElement=FormElement},{"../api/XM":6,"../data/Keybinds":15,"../utility/Util":33}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Modal=void 0;const Util_1=require("../utility/Util");exports.Modal=class{constructor(config){if(this.triggers=[],this.id=Util_1.Util.ID.make(),this.config=this.validateConfig(config),this.$modal=$("<div>").addClass(config.wrapperClass).attr("title",config.title).append(this.config.content).appendTo("div#modal-container").dialog({autoOpen:!1,appendTo:"#modal-container",closeOnEscape:config.escapable,draggable:config.draggable,resizable:config.resizable,width:"auto",minWidth:config.minWidth,minHeight:config.minHeight,position:{my:config.position.my,at:config.position.at,of:$("#modal-container"),within:$("#modal-container"),collision:"none"},classes:{"ui-dialog":"bg-foreground border-section color-text","ui-dialog-titlebar":"color-text","ui-dialog-titlebar-close":"border-foreground"}}),this.$modal.dialog("widget").addClass("re621-ui-dialog").removeClass("ui-dialog ui-widget ui-widget-content").toggleClass("modal-reserve-height",config.reserveHeight).draggable({disabled:!config.draggable,containment:"parent"}).resizable({disabled:!config.resizable,containment:"parent"}),config.structure){let modalOpened=!1;this.$modal.on("dialogopen",()=>{modalOpened||(modalOpened=!0,this.$modal.html(""),this.$modal.append(config.structure.render()))})}if(config.fixed){const widget=this.$modal.dialog("widget");widget.addClass("modal-fixed"),this.$modal.dialog("option","position",{my:config.position.my,at:config.position.at,of:window,within:"div#modal-container",collision:"none"}),widget.draggable("option","containment","window"),widget.resizable("option","containment","window");let timer=0,left=widget.css("left"),top=widget.css("top");const style=$("<style>").attr({id:"style-"+this.id,type:"text/css"}).html(`\n .modal-fixed-${this.id} {\n left: ${left} !important;\n top: ${top} !important;\n }\n `).appendTo("head");$(window).scroll(()=>{timer?clearTimeout(timer):(left=widget.css("left"),top=widget.css("top"),style.html(`\n .modal-fixed-${this.id} {\n left: ${left} !important;\n top: ${top} !important;\n }\n `),widget.addClass("modal-fixed-"+this.id)),timer=window.setTimeout(()=>{timer=0,widget.removeClass("modal-fixed-"+this.id),widget.css("left",left),widget.css("top",top)},500)})}for(const trigger of config.triggers)this.registerTrigger(trigger)}validateConfig(config){return void 0===config.title&&(config.title="Dialog"),void 0===config.content&&(config.content=$("")),void 0===config.triggers&&(config.triggers=[]),void 0===config.triggerMulti&&(config.triggerMulti=!1),void 0===config.escapable&&(config.escapable=!0),void 0===config.draggable&&(config.draggable=!0),void 0===config.resizable&&(config.resizable=!1),void 0===config.minWidth&&(config.minWidth=150),void 0===config.minHeight&&(config.minHeight=150),void 0===config.fixed&&(config.fixed=!1),void 0===config.reserveHeight&&(config.reserveHeight=!1),void 0===config.wrapperClass&&(config.wrapperClass=""),void 0===config.disabled&&(config.disabled=!1),void 0===config.position&&(config.position={my:"center",at:"center"}),config}addContent($content){this.$modal.append($content)}setContent($content){this.$modal.html(""),this.$modal.append($content)}registerTrigger(trigger){void 0===trigger.event&&(trigger.event="click"),0==this.triggers.length&&(this.$activeTrigger=trigger.element),this.triggers.push(trigger),trigger.element.on(trigger.event,event=>{if(this.isDisabled())return;const $target=$(event.currentTarget);return this.config.triggerMulti&&!this.$activeTrigger.is($target)&&this.isOpen()&&this.toggle(),this.$activeTrigger=$target,event.preventDefault(),this.toggle(),!1})}getElement(){return this.$modal}toggle(){this.isOpen()?this.close():this.open()}isOpen(){return this.$modal.dialog("isOpen")}open(){return this.$modal.dialog("open")}close(){return this.$modal.dialog("close")}isDisabled(){return this.config.disabled}enable(){this.config.disabled=!1}disable(){this.config.disabled=!0}destroy(){this.$modal.dialog("destroy"),this.$modal.remove()}getActiveTrigger(){return this.$activeTrigger}}},{"../utility/Util":33}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Prompt=void 0;const Modal_1=require("./Modal");class Prompt extends Modal_1.Modal{constructor(title="Prompt"){super({title:title,fixed:!0,minHeight:50}),this.createForm(),this.addContent(this.$form),this.open(),this.$input.focus(),this.promise=new Promise((resolve,reject)=>{this.$form.submit(event=>{event.preventDefault(),this.destroy(),resolve(this.$input.val()),reject()})})}createForm(){this.$form=$("<form>").addClass("prompt-input"),this.$input=$("<input>").attr("id","text").appendTo(this.$form),$("<button>").attr("type","submit").html("Submit").appendTo(this.$form)}getPromise(){return this.promise}}exports.Prompt=Prompt},{"./Modal":27}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tabbed=void 0;const Util_1=require("../utility/Util");exports.Tabbed=class{constructor(config){this.id=Util_1.Util.ID.make(),this.config=config}render(clearCache=!1){if(void 0!==this.$container&&!clearCache)return this.$container;this.$container=$("<div>");const $tabList=$("<ul>").appendTo(this.$container);return this.config.content.forEach((entry,index)=>{let $tab;$tab="string"==typeof entry.name?$("<a>").html(entry.name):entry.name,$tab.attr("href","#"+this.id+"-fragment-"+index),$("<li>").appendTo($tabList).append($tab);const elem=$("<div>").attr("id",this.id+"-fragment-"+index).appendTo(this.$container);entry.content&&elem.append(entry.content),entry.structure&&elem.append(entry.structure.render())}),this.$container.tabs({classes:{"ui-tabs":"color-text","ui-tabs-tab":"color-text"}}),this.$container.tabs("widget").find(".ui-tabs-nav li").off("keydown"),this.$container}replace(index,$element){this.$container.find("#"+this.id+"-fragment-"+index).children().replaceWith($element)}}},{"../utility/Util":33}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Debug=void 0;const XM_1=require("../api/XM");class Debug{static async init(){return Debug.enabled=await XM_1.XM.Storage.getValue("re621.debug.enabled",!1),Debug.connect=await XM_1.XM.Storage.getValue("re621.debug.connect",!1),Debug.perform=await XM_1.XM.Storage.getValue("re621.debug.perform",!1),Promise.resolve(!0)}static getState(type){return Debug[type]}static setState(type,enabled){Debug[type]=enabled,enabled?XM_1.XM.Storage.setValue("re621.debug."+type,enabled):XM_1.XM.Storage.deleteValue("re621.debug."+type)}static log(...data){Debug.enabled&&console.log(...data)}static connectLog(...data){Debug.connect&&console.log("CONNECT",...data)}static perfStart(input){Debug.perform&&console.time(input)}static perfEnd(input){Debug.perform&&console.timeEnd(input)}}exports.Debug=Debug},{"../api/XM":6}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ErrorHandler=void 0;const XM_1=require("../api/XM"),Modal_1=require("../structure/Modal"),Patcher_1=require("./Patcher");class ErrorHandler{constructor(){const $contentWrapper=$("<div>").html(`\n <p>RE621 has encountered an error during script execution.</p>\n <p>Please, report this message, including the error log below, through the <a href="${window.re621.links.issues}">issue tracker</a>, or in the <a href="${window.re621.links.forum}">forum thread</a>.</p>\n `);this.feedback=$("<textarea>").addClass("error-feedback bg-section color-text").val(`${window.re621.name} v.${window.re621.version}-${window.re621.build}-${Patcher_1.Patcher.version} for ${XM_1.XM.info().scriptHandler} v.${XM_1.XM.info().version}\n`+window.navigator.userAgent+"\n").prop("readonly",!0).appendTo($contentWrapper),this.trigger=$("<a>"),this.modal=new Modal_1.Modal({title:"An error has occurred",content:$contentWrapper,triggers:[{element:this.trigger}],fixed:!0}),this.modal.getElement().dialog("open")}static getInstance(){return void 0===this.instance&&(this.instance=new ErrorHandler),this.instance}static log(module,message,context){const instance=this.getInstance();"string"!=typeof module&&(module=module.getSettingsTag()),void 0!==context&&(module+="/"+context),instance.feedback.val((index,value)=>{const entry=""===value?module+"\n"+message+"\n":value+"\n"+module+"\n"+message+"\n";return console.log(entry),entry})}static error(module,message,context){const instance=this.getInstance();instance.modal.isOpen()||instance.trigger.get(0).click(),this.log(module,message,context)}}exports.ErrorHandler=ErrorHandler},{"../api/XM":6,"../structure/Modal":27,"./Patcher":32}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Patcher=void 0;const HoverZoom_1=require("../../modules/search/HoverZoom"),XM_1=require("../api/XM"),Debug_1=require("./Debug");class Patcher{static async run(){let counter=0;switch(Patcher.version=await XM_1.XM.Storage.getValue("re621.patchVersion",0),Patcher.version){case 0:for(const type of["Comment","Forum","Pool","Tag"]){const entry=await XM_1.XM.Storage.getValue("re621."+type+"Subscriptions",void 0);void 0!==entry&&(void 0!==entry.cache&&(await XM_1.XM.Storage.setValue("re621."+type+"Tracker.cache",entry.cache),delete entry.cache,counter++),await XM_1.XM.Storage.setValue("re621."+type+"Tracker",entry),await XM_1.XM.Storage.deleteValue("re621."+type+"Subscriptions"),counter++)}Patcher.version=1;case 1:{const miscSettings=await XM_1.XM.Storage.getValue("re621.Miscellaneous",{}),searchUtilities=await XM_1.XM.Storage.getValue("re621.SearchUtilities",{});for(const property of["improveTagCount","shortenTagNames","collapseCategories","hotkeyFocusSearch","hotkeyRandomPost"])miscSettings.hasOwnProperty(property)&&(searchUtilities[property]=miscSettings[property],delete miscSettings[property],counter++);for(const property of["removeSearchQueryString","categoryData"])miscSettings.hasOwnProperty(property)&&(delete miscSettings[property],counter++);await XM_1.XM.Storage.setValue("re621.Miscellaneous",miscSettings),await XM_1.XM.Storage.setValue("re621.SearchUtilities",searchUtilities),Patcher.version=2}case 2:void 0!==await XM_1.XM.Storage.getValue("re621.report",void 0)&&(await XM_1.XM.Storage.deleteValue("re621.report"),counter++),Patcher.version=3;case 3:window.localStorage.removeItem("re621.favorites"),window.localStorage.removeItem("re621.dnp.cache"),counter+=2,Patcher.version=4;case 4:{const taConf=await XM_1.XM.Storage.getValue("re621.TinyAlias",void 0);if(void 0!==taConf&&void 0!==taConf.data){let output="";for(const[key,value]of Object.entries(taConf.data))output+=`${key} -> ${value}\n`,counter++;const saConf=await XM_1.XM.Storage.getValue("re621.SmartAlias",{data:""});saConf.data=saConf.data+(""==saConf.data?"":"\n\n")+"# Imported from TinyAlias\n"+output,await XM_1.XM.Storage.setValue("re621.SmartAlias",saConf),await XM_1.XM.Storage.deleteValue("re621.TinyAlias")}Patcher.version=5}case 5:{const thumbEnhancer=await XM_1.XM.Storage.getValue("re621.ThumbnailEnhancer",void 0),infiniteScroll=await XM_1.XM.Storage.getValue("re621.InfiniteScroll",void 0),betterSearch=await XM_1.XM.Storage.getValue("re621.BetterSearch",{});thumbEnhancer&&(betterSearch.imageLoadMethod=thumbEnhancer.upscale,betterSearch.autoPlayGIFs=thumbEnhancer.autoPlayGIFs,betterSearch.hoverTags=thumbEnhancer.preserveHoverText,"onshift"==thumbEnhancer.zoom?betterSearch.zoomMode=HoverZoom_1.ImageZoomMode.OnShift:"true"==thumbEnhancer.zoom?betterSearch.zoomMode=HoverZoom_1.ImageZoomMode.Hover:betterSearch.zoomMode=HoverZoom_1.ImageZoomMode.Disabled,betterSearch.imageSizeChange=thumbEnhancer.crop,betterSearch.imageWidth=thumbEnhancer.cropSize.replace(/px/g,""),betterSearch.imageRatioChange=!thumbEnhancer.cropPreserveRatio,betterSearch.imageRatio=thumbEnhancer.cropRatio,betterSearch.ribbonsFlag=thumbEnhancer.ribbons,betterSearch.ribbonsRel=thumbEnhancer.relRibbons,betterSearch.buttonsVote=thumbEnhancer.vote,betterSearch.buttonsFav=thumbEnhancer.fav,counter+=12,await XM_1.XM.Storage.setValue("re621.BetterSearch",betterSearch),await XM_1.XM.Storage.deleteValue("re621.ThumbnailEnhancer")),infiniteScroll&&(betterSearch.infiniteScroll=infiniteScroll.enabled,betterSearch.loadPrevPages=infiniteScroll.keepHistory,counter+=2,await XM_1.XM.Storage.setValue("re621.BetterSearch",betterSearch),await XM_1.XM.Storage.deleteValue("re621.InfiniteScroll")),window.localStorage.removeItem("re621.favcache.data"),window.localStorage.removeItem("re621.favcache.invalid"),window.localStorage.removeItem("re621.favcache.update"),counter+=3,Patcher.version=6}case 6:case 7:await XM_1.XM.Storage.deleteValue("re621.sync"),counter++,Patcher.version=8;case 8:{const betterSearch=await XM_1.XM.Storage.getValue("re621.BetterSearch",{}),hoverZoom=await XM_1.XM.Storage.getValue("re621.HoverZoom",{});void 0!==betterSearch.zoomMode&&(hoverZoom.mode=betterSearch.zoomMode,delete betterSearch.zoomMode,counter++),void 0!==betterSearch.zoomTags&&(hoverZoom.tags=betterSearch.zoomTags,delete betterSearch.zoomTags,counter++);for(const deletedEntry of["zoomFull","zoomScale","zoomContextual"])delete betterSearch[deletedEntry],counter++;await XM_1.XM.Storage.setValue("re621.BetterSearch",betterSearch),await XM_1.XM.Storage.setValue("re621.HoverZoom",hoverZoom),Patcher.version=9}}Debug_1.Debug.log(`Patcher: ${counter} records changed`),await XM_1.XM.Storage.setValue("re621.patchVersion",Patcher.version)}}exports.Patcher=Patcher},{"../../modules/search/HoverZoom":58,"../api/XM":6,"./Debug":30}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Util=void 0;const UtilID_1=require("./UtilID"),UtilMath_1=require("./UtilMath"),UtilTime_1=require("./UtilTime");class Util{static downloadAsJSON(data,file){$("<a>").attr({download:file+".json",href:"data:application/json,"+encodeURIComponent(JSON.stringify(data,null,4))}).appendTo("body").click((function(){$(this).remove()}))[0].click()}static async sleep(time){return new Promise(resolve=>{setTimeout(()=>{resolve()},time)})}static chunkArray(input,size,altMode=!1){Array.isArray(input)||(input=Array.from(input));const result=[];if(altMode)result[0]=input.slice(0,size),result[1]=input.slice(size);else for(let i=0;i<input.length;i+=size)result.push(input.slice(i,i+size));return result}static getArrayIndexes(input,value){const indexes=[];let i=0;for(;i<input.length;i++)input[i]===value&&indexes.push(i);return indexes}static quickParseMarkdown(input){return void 0===input?"":input.replace(/\*\*(.*?)\*\*/gm,"<strong>$1</strong>").replace(/\_(.*?\S)\_/gm,"<em>$1</em>").replace(/\[(.+)\]\((.*)\)/gm,'<a href="$2">$1</a>').replace(/^[-]+(.*)?/gim,"<ul><li>$1</li></ul>").replace(/\<\/ul\>\r\n\<ul\>/gm,"").replace(/\n(?!<)/gm,"<br />")}static parseDText(input,removeSections=!0){return removeSections&&(input=input.replace(/\[quote\][\s\S]*\[\/quote\]/g,"").replace(/\[code\][\s\S]*\[\/code\]/g,"").replace(/\\[section[\s\S]*\[\/section\]/g,"")),input=input.replace(/\[b\]([\s\S]*)\[\/b\]/g,"<b>$1</b>").replace(/\[i\]([\s\S]*)\[\/i\]/g,"<i>$1</i>").replace(/\[u\]([\s\S]*)\[\/u\]/g,"<u>$1</u>").replace(/\[o\]([\s\S]*)\[\/o\]/g,"<o>$1</o>").replace(/\[s\]([\s\S]*)\[\/s\]/g,"<s>$1</s>").replace(/\[sup\]([\s\S]*)\[\/sup\]/g,"<sup>$1</sup>").replace(/\[sub\]([\s\S]*)\[\/sub\]/g,"<sub>$1</sub>").replace(/\[spoiler\]([\s\S]*)\[\/spoiler\]/g,"<span>$1</span>").replace(/\[color\]([\s\S]*)\[\/color\]/g,"<span>$1</span>")}static formatBytes(bytes,decimals=2){if(0===bytes)return"0 B";const dm=decimals<0?0:decimals,i=Math.floor(Math.log(bytes)/Math.log(1024));return parseFloat((bytes/Math.pow(1024,i)).toFixed(dm))+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][i]}static formatK(num){return Math.abs(num)>999?(Math.sign(num)*(Math.abs(num)/1e3)).toFixed(1)+"k":Math.sign(num)*Math.abs(num)+""}static formatRatio(width,height){const d=function gcd(u,v){if(u===v)return u;if(0===u)return v;if(0===v)return u;if(1&~u)return 1&v?gcd(u>>1,v):gcd(u>>1,v>>1)<<1;return 1&~v?gcd(u,v>>1):u>v?gcd(u-v>>1,v):gcd(v-u>>1,u)}(width,height);return[width/d,height/d]}static getTagString(input){return input.val().toString().trim().toLowerCase().replace(/\r?\n|\r/g," ").replace(/(?:\s){2,}/g," ")}static getTags(input){return("string"==typeof input?input:Util.getTagString(input)).split(" ").filter(el=>null!=el&&""!=el)}static versionCompare(v1,v2,options){const lexicographical=options&&options.lexicographical,zeroExtend=options&&options.zeroExtend;let v1parts=v1.split("."),v2parts=v2.split(".");function isValidPart(x){return(lexicographical?/^\d+[A-Za-z]*$/:/^\d+$/).test(x)}if(!v1parts.every(isValidPart)||!v2parts.every(isValidPart))return NaN;if(zeroExtend){for(;v1parts.length<v2parts.length;)v1parts.push("0");for(;v2parts.length<v1parts.length;)v2parts.push("0")}lexicographical||(v1parts=v1parts.map(Number),v2parts=v2parts.map(Number));for(let i=0;i<v1parts.length;++i){if(v2parts.length==i)return 1;if(v1parts[i]!=v2parts[i])return v1parts[i]>v2parts[i]?1:-1}return v1parts.length!=v2parts.length?-1:0}}exports.Util=Util,Util.Time=UtilTime_1.UtilTime,Util.ID=UtilID_1.UtilID,Util.Math=UtilMath_1.UtilMath,Util.LS=window.localStorage,Util.SS=window.sessionStorage},{"./UtilID":34,"./UtilMath":35,"./UtilTime":36}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UtilID=void 0;class UtilID{static make(length=8,unique=!0){if(!unique)return getRandomString(length);let uniqueID;do{uniqueID=getRandomString(length)}while(UtilID.uniqueIDs.has(uniqueID));return UtilID.uniqueIDs.add(uniqueID),uniqueID;function getRandomString(length){let result="";const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",charLength=chars.length;for(let i=0;i<length;i++)result+=chars.charAt(Math.floor(Math.random()*charLength));return result}}static has(id){return UtilID.uniqueIDs.has(id)}static remove(id){return!!UtilID.has(id)&&(UtilID.uniqueIDs.delete(id),!0)}}exports.UtilID=UtilID,UtilID.uniqueIDs=new Set},{}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UtilMath=void 0;exports.UtilMath=class{static clamp(value,min,max){return Math.min(Math.max(value,min),max)}static between(value,min,max){return min<=value&&max>=value}}},{}],36:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UtilTime=void 0,function(UtilTime){UtilTime[UtilTime.SECOND=1e3]="SECOND",UtilTime[UtilTime.MINUTE=6e4]="MINUTE",UtilTime[UtilTime.HOUR=36e5]="HOUR",UtilTime[UtilTime.DAY=864e5]="DAY",UtilTime[UtilTime.WEEK=6048e5]="WEEK"}(exports.UtilTime||(exports.UtilTime={})),function(UtilTime){UtilTime.now=function(){return(new Date).getTime()},UtilTime.ago=function(time){switch(typeof time){case"string":time=+new Date(time);break;case"object":time=time.getTime()}const timeFormats=[[60,"seconds",1],[120,"1 minute ago","1 minute from now"],[3600,"minutes",60],[7200,"1 hour ago","1 hour from now"],[86400,"hours",3600],[172800,"Yesterday","Tomorrow"],[604800,"days",86400],[1209600,"Last week","Next week"],[2419200,"weeks",604800],[4838400,"Last month","Next month"],[29030400,"months",2419200],[58060800,"Last year","Next year"],[290304e4,"years",29030400],[580608e4,"Last century","Next century"],[580608e5,"centuries",290304e4]];let seconds=(+new Date-time)/1e3,token="ago",listChoice=1;if(seconds>=0&&seconds<2)return"Just now";seconds<0&&(seconds=Math.abs(seconds),token="from now",listChoice=2);let format,i=0;for(;format=timeFormats[i++];)if(seconds<format[0])return"string"==typeof format[2]?format[listChoice]:Math.floor(seconds/format[2])+" "+format[1]+" "+token;return time+""},UtilTime.format=function(date=new Date){"number"!=typeof date&&"string"!=typeof date||(date=new Date(date));const parts={year:""+date.getFullYear(),month:""+(date.getMonth()+1),day:""+date.getDate(),hours:""+date.getHours(),minutes:""+date.getMinutes(),seconds:""+date.getSeconds()};for(const id in parts)parts[id].length<2&&(parts[id]="0"+parts[id]);return parts.year+"-"+parts.month+"-"+parts.day+" "+parts.hours+":"+parts.minutes+":"+parts.seconds},UtilTime.getDatetimeShort=function(){function twoDigit(n){return(n<10?"0":"")+n}const date=new Date;return(date.getFullYear()+"").substring(2)+twoDigit(date.getMonth()+1)+twoDigit(date.getDate())+"-"+twoDigit(date.getHours())+twoDigit(date.getMinutes())}}(exports.UtilTime||(exports.UtilTime={}))},{}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.VersionChecker=void 0;const XM_1=require("../api/XM"),Debug_1=require("./Debug"),Util_1=require("./Util");class VersionChecker{static async init(){const emVersion=Util_1.Util.LS.getItem("re621.version");VersionChecker.scriptBuild=emVersion||window.re621.version;const settings=await XM_1.XM.Storage.getValue("re621.VersionChecker",{});if(void 0!==settings.latestBuild&&(VersionChecker.latestBuild=settings.latestBuild),void 0!==settings.cachedBuild&&(VersionChecker.cachedBuild=settings.cachedBuild),VersionChecker.cachedBuild!==VersionChecker.scriptBuild&&(VersionChecker.wasUpdated=!0),Util_1.Util.versionCompare(VersionChecker.cachedBuild,VersionChecker.latestBuild)<0&&(VersionChecker.hasUpdate=!0),void 0!==settings.lastUpdated&&(VersionChecker.lastUpdated=settings.lastUpdated),void 0!==settings.changesText&&(VersionChecker.changesText=settings.changesText),VersionChecker.scriptBuild.includes("dev"))VersionChecker.wasUpdated=!1,VersionChecker.hasUpdate=!1;else if(VersionChecker.wasUpdated||VersionChecker.lastUpdated+Util_1.Util.Time.HOUR<Util_1.Util.Time.now()){const latestRelease=await VersionChecker.getGithubData("latest");VersionChecker.latestBuild=latestRelease.name,VersionChecker.cachedBuild=VersionChecker.scriptBuild,VersionChecker.hasUpdate=Util_1.Util.versionCompare(VersionChecker.scriptBuild,VersionChecker.latestBuild)<0,VersionChecker.lastUpdated=Util_1.Util.Time.now(),VersionChecker.changesText=latestRelease.body}VersionChecker.changesHTML=Util_1.Util.quickParseMarkdown(VersionChecker.changesText),Debug_1.Debug.log("VersionChecker",{scriptBuild:VersionChecker.scriptBuild,latestBuild:VersionChecker.latestBuild,cachedBuild:VersionChecker.cachedBuild,wasUpdated:VersionChecker.wasUpdated,hasUpdate:VersionChecker.hasUpdate,lastUpdated:VersionChecker.lastUpdated,changesText:VersionChecker.changesText,changesHTML:VersionChecker.changesHTML}),await XM_1.XM.Storage.setValue("re621.VersionChecker",{latestBuild:VersionChecker.latestBuild,cachedBuild:VersionChecker.cachedBuild,lastUpdated:VersionChecker.lastUpdated,changesText:VersionChecker.changesText})}static async getGithubData(node){return XM_1.XM.Connect.xmlHttpPromise({url:"https://api.github.com/repos/re621/re621/releases/"+node,method:"GET"}).then(response=>Promise.resolve(JSON.parse(response.responseText)),()=>{throw Error("Failed to fetch Github release data")})}}exports.VersionChecker=VersionChecker,VersionChecker.scriptBuild="0.0.1",VersionChecker.latestBuild="0.0.1",VersionChecker.cachedBuild="0.0.1",VersionChecker.wasUpdated=!1,VersionChecker.hasUpdate=!1,VersionChecker.lastUpdated=0,VersionChecker.changesText="_~ Changelog not available ~_",VersionChecker.changesHTML=""},{"../api/XM":6,"./Debug":30,"./Util":33}],38:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const Danbooru_1=require("./components/api/Danbooru"),Page_1=require("./components/data/Page"),ModuleController_1=require("./components/ModuleController"),CleanSlate_1=require("./components/structure/CleanSlate"),DomUtilities_1=require("./components/structure/DomUtilities"),Debug_1=require("./components/utility/Debug"),Patcher_1=require("./components/utility/Patcher"),Util_1=require("./components/utility/Util"),VersionChecker_1=require("./components/utility/VersionChecker"),FavDownloader_1=require("./modules/downloader/FavDownloader"),MassDownloader_1=require("./modules/downloader/MassDownloader"),PoolDownloader_1=require("./modules/downloader/PoolDownloader"),FormattingHelper_1=require("./modules/general/FormattingHelper"),HeaderCustomizer_1=require("./modules/general/HeaderCustomizer"),Miscellaneous_1=require("./modules/general/Miscellaneous"),SettingsController_1=require("./modules/general/SettingsController"),ThemeCustomizer_1=require("./modules/general/ThemeCustomizer"),SmartAlias_1=require("./modules/misc/SmartAlias"),UploadUtilities_1=require("./modules/misc/UploadUtilities"),WikiEnhancer_1=require("./modules/misc/WikiEnhancer"),DownloadCustomizer_1=require("./modules/post/DownloadCustomizer"),ImageScaler_1=require("./modules/post/ImageScaler"),PoolNavigator_1=require("./modules/post/PoolNavigator"),PostViewer_1=require("./modules/post/PostViewer"),TitleCustomizer_1=require("./modules/post/TitleCustomizer"),BetterSearch_1=require("./modules/search/BetterSearch"),BlacklistEnhancer_1=require("./modules/search/BlacklistEnhancer"),CustomFlagger_1=require("./modules/search/CustomFlagger"),HoverZoom_1=require("./modules/search/HoverZoom"),InstantSearch_1=require("./modules/search/InstantSearch"),PostSuggester_1=require("./modules/search/PostSuggester"),SearchUtilities_1=require("./modules/search/SearchUtilities"),ThumbnailTweaks_1=require("./modules/search/ThumbnailTweaks"),CommentTracker_1=require("./modules/subscriptions/CommentTracker"),ForumTracker_1=require("./modules/subscriptions/ForumTracker"),PoolTracker_1=require("./modules/subscriptions/PoolTracker"),SubscriptionManager_1=require("./modules/subscriptions/SubscriptionManager"),TagTracker_1=require("./modules/subscriptions/TagTracker"),loadOrder=[FormattingHelper_1.FormattingManager,HeaderCustomizer_1.HeaderCustomizer,ThemeCustomizer_1.ThemeCustomizer,DownloadCustomizer_1.DownloadCustomizer,ImageScaler_1.ImageScaler,PoolNavigator_1.PoolNavigator,PostViewer_1.PostViewer,TitleCustomizer_1.TitleCustomizer,BlacklistEnhancer_1.BlacklistEnhancer,CustomFlagger_1.CustomFlagger,InstantSearch_1.InstantSearch,ThumbnailTweaks_1.ThumbnailTweaks,BetterSearch_1.BetterSearch,HoverZoom_1.HoverZoom,PostSuggester_1.PostSuggester,SearchUtilities_1.SearchUtilities,Miscellaneous_1.Miscellaneous,SmartAlias_1.SmartAlias,WikiEnhancer_1.WikiEnhancer,UploadUtilities_1.UploadUtilities,FavDownloader_1.FavDownloader,PoolDownloader_1.PoolDownloader,MassDownloader_1.MassDownloader,SubscriptionManager_1.SubscriptionManager,SettingsController_1.SettingsController],subscriptions=[TagTracker_1.TagTracker,PoolTracker_1.PoolTracker,ForumTracker_1.ForumTracker,CommentTracker_1.CommentTracker];if(console.log(`${window.re621.name} v.${window.re621.version} build ${window.re621.build}`),Page_1.Page.matches(Page_1.PageDefintion.title)){const page=Util_1.Util.LS.getItem("re621.mainpage");page&&"default"!==page&&window.location.replace("/"+page)}Danbooru_1.Danbooru.Utility.disableShortcuts(!0),CleanSlate_1.CleanSlate.run().then(async()=>{DomUtilities_1.DomUtilities.createSearchbox(),DomUtilities_1.DomUtilities.createTagList(),await Debug_1.Debug.init(),await Patcher_1.Patcher.run(),await VersionChecker_1.VersionChecker.init(),await CleanSlate_1.CleanSlate.awaitFocus(),await ModuleController_1.ModuleController.register(subscriptions),await SubscriptionManager_1.SubscriptionManager.register(subscriptions),await ModuleController_1.ModuleController.register(loadOrder)})},{"./components/ModuleController":1,"./components/api/Danbooru":3,"./components/data/Page":16,"./components/structure/CleanSlate":24,"./components/structure/DomUtilities":25,"./components/utility/Debug":30,"./components/utility/Patcher":32,"./components/utility/Util":33,"./components/utility/VersionChecker":37,"./modules/downloader/FavDownloader":39,"./modules/downloader/MassDownloader":40,"./modules/downloader/PoolDownloader":41,"./modules/general/FormattingHelper":42,"./modules/general/HeaderCustomizer":43,"./modules/general/Miscellaneous":44,"./modules/general/SettingsController":45,"./modules/general/ThemeCustomizer":46,"./modules/misc/SmartAlias":47,"./modules/misc/UploadUtilities":48,"./modules/misc/WikiEnhancer":49,"./modules/post/DownloadCustomizer":50,"./modules/post/ImageScaler":51,"./modules/post/PoolNavigator":52,"./modules/post/PostViewer":53,"./modules/post/TitleCustomizer":54,"./modules/search/BetterSearch":55,"./modules/search/BlacklistEnhancer":56,"./modules/search/CustomFlagger":57,"./modules/search/HoverZoom":58,"./modules/search/InstantSearch":59,"./modules/search/PostSuggester":60,"./modules/search/SearchUtilities":61,"./modules/search/ThumbnailTweaks":62,"./modules/subscriptions/CommentTracker":63,"./modules/subscriptions/ForumTracker":64,"./modules/subscriptions/PoolTracker":65,"./modules/subscriptions/SubscriptionManager":66,"./modules/subscriptions/TagTracker":68}],39:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FavDownloader=void 0;const DownloadQueue_1=require("../../components/api/DownloadQueue"),E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("../search/BetterSearch"),MassDownloader_1=require("./MassDownloader");class FavDownloader extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.favorites),this.processing=!1,this.downloadOverSize=!1,this.batchOverSize=!0,this.posts=[],this.fileTimestamp=Util_1.Util.Time.getDatetimeShort(),this.downloadIndex=1}getDefaultSettings(){return{enabled:!0,template:"%artist%/%postid%-%copyright%-%character%-%species%",autoDownloadArchive:!0}}create(){super.create(),this.userID=parseInt(Page_1.Page.getQueryParameter("user_id")||$("meta[name=current-user-id]").attr("content")),NaN!=this.userID&&(this.section=$("<section>").attr({id:"fav-downloader-box","data-fixed":this.fetchSettings("fixedSection")+""}).html("<h1>Download</h1>").appendTo("aside#sidebar"),$("#sidebar").on("re621:reflow",()=>{this.section.css("top",$("#re621-search").outerHeight()+"px")}),$("#sidebar").trigger("re621:reflow"),this.actButton=$("<a>").html("Download All").addClass("pool-download-button button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.processFiles()}),this.infoText=$("<div>").addClass("download-info").appendTo(this.section),this.infoFile=$("<div>").addClass("download-file").appendTo(this.section))}destroy(){super.destroy()}toggleFixedSection(){"true"===this.section.attr("data-fixed")?this.section.attr("data-fixed","false"):this.section.attr("data-fixed","true")}async processFiles(){if(this.processing)return;this.processing=!0,this.actButton.attr("disabled","disabled"),$("search-content").attr("data-downloading","true"),BetterSearch_1.BetterSearch.setPaused(!0),this.infoText.attr("data-state","loading").html("Indexing favorites . . ."),0==this.posts.length&&(this.infoText.attr("data-state","loading").html("Fetching API data . . ."),this.posts=(await async function recursiveLookup(output,info,userID,index=1){return info.html(" request "+index+" ["+output.length+"]"),E621_1.E621.Favorites.get({user_id:userID,page:index,limit:320}).then(data=>(output.push(...data),320==data.length?recursiveLookup(output,info,userID,++index):Promise.resolve(output)))}([],this.infoFile,this.userID)).reverse());const downloadQueue=new DownloadQueue_1.DownloadQueue,threadInfo=[];this.infoFile.html("");for(let i=0;i<downloadQueue.getThreadCount();i++)threadInfo.push($("<span>").appendTo(this.infoFile));let queuedPost,totalFileSize=0,queueSize=0;for(this.batchOverSize=!1;queuedPost=this.posts.pop();){const post=Post_1.PostData.fromAPI(queuedPost);if(post.has.file){if(totalFileSize+=post.file.size,Debug_1.Debug.log(`adding #${post.id} (${Util_1.Util.formatBytes(post.file.size)}) to the queue: ${Util_1.Util.formatBytes(totalFileSize)} total`),totalFileSize>FavDownloader.maxBlobSize){this.batchOverSize=!0,this.downloadOverSize=!0;break}$("#entry_"+post.id).addClass("download-item").attr("data-state","preparing"),downloadQueue.add({name:this.createFilename(post),path:post.file.original,file:post.file.original.match(/.{32}\..*$/g)[0],unid:post.id,date:new Date(post.date.raw),tags:post.tagString},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("#entry_"+post.id).attr("data-state","loading")},onFinish:()=>{$("#entry_"+post.id).attr("data-state","done")},onError:()=>{$("#entry_"+post.id).attr("data-state","error")},onLoadProgress:(item,thread,event)=>{event.lengthComputable&&threadInfo[thread].css("--progress",Math.round(event.loaded/event.total*100)+"%")},onWorkerFinish:(item,thread)=>{threadInfo[thread].remove()}})}}queueSize=downloadQueue.getQueueLength(),this.infoText.html("Processing . . . ");const zipData=await downloadQueue.run(metadata=>{this.infoText.html("Compressing . . . "+metadata.percent.toFixed(2)+"%"),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")});let filename=this.userID+"-fav-"+this.fileTimestamp;filename+=this.downloadOverSize?"-part"+this.downloadIndex+".zip":".zip",this.infoText.attr("data-state","done").html("Done! "),this.infoFile.html("");const $downloadLink=$("<a>").attr({href:URL.createObjectURL(zipData),download:filename}).html("Download Archive").appendTo(this.infoText);this.fetchSettings("autoDownloadArchive")&&$downloadLink.get(0).click(),this.downloadIndex++,this.actButton.removeAttr("disabled"),this.processing=!1,this.batchOverSize?this.fetchSettings("autoDownloadArchive")?this.actButton.get(0).click():$("<div>").addClass("download-notice").html("Download has exceeded the maximum file size.<br /><br />Click the download button again for the next part.").appendTo(this.infoText):BetterSearch_1.BetterSearch.setPaused(!1)}createFilename(post){return MassDownloader_1.MassDownloader.createFilenameBase(this.fetchSettings("template"),post).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+post.file.ext}}exports.FavDownloader=FavDownloader,FavDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/utility/Debug":30,"../../components/utility/Util":33,"../search/BetterSearch":55,"./MassDownloader":40}],40:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MassDownloader=void 0;const DownloadQueue_1=require("../../components/api/DownloadQueue"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),PostSet_1=require("../../components/post/PostSet"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("../search/BetterSearch");class MassDownloader extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.search),this.showInterface=!1,this.processing=!1,this.downloadOverSize=!1,this.fileTimestamp=Util_1.Util.Time.getDatetimeShort(),this.downloadIndex=0}getDefaultSettings(){return{enabled:!0,template:"%artist%/%postid%-%copyright%-%character%-%species%",autoDownloadArchive:!0}}create(){super.create(),this.section=$("<section>").attr({id:"downloader-box","data-fixed":this.fetchSettings("fixedSection")+""}).html("<h1>Download</h1>").appendTo("aside#sidebar"),$("#sidebar").on("re621:reflow",()=>{this.section.css("top",$("#re621-search").outerHeight()+"px")}),$("#sidebar").trigger("re621:reflow"),this.selectButton=$("<a>").html("Select").attr("id","download-select").addClass("button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.toggleInterface()}),this.actButton=$("<a>").html("Download").attr("id","download-act").addClass("button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.processFiles()}),this.infoText=$("<div>").addClass("download-info").appendTo(this.section),this.infoFile=$("<div>").addClass("download-file").appendTo(this.section),this.container=$("search-content")}destroy(){super.destroy(),BetterSearch_1.BetterSearch.off("pageload.MassDownloader")}toggleInterface(){this.showInterface=!this.showInterface,BetterSearch_1.BetterSearch.setPaused(this.showInterface),this.showInterface?(this.selectButton.html("Cancel"),this.section.attr("data-interface","true"),this.infoText.html('Click on thumbnails to select them, then press "Download"'),this.container.attr("data-downloading","true").selectable({autoRefresh:!1,filter:"post",selected:function(event,ui){$(ui.selected).toggleClass("download-item").attr("data-state","ready")}}),BetterSearch_1.BetterSearch.on("pageload.MassDownloader",()=>{this.container.selectable("refresh")})):(this.selectButton.html("Select"),this.section.attr("data-interface","false"),this.container.attr("data-downloading","false").selectable("destroy"),BetterSearch_1.BetterSearch.off("pageload.MassDownloader"))}toggleFixedSection(){"true"===this.section.attr("data-fixed")?this.section.attr("data-fixed","false"):this.section.attr("data-fixed","true")}setProcessing(state){this.processing=state,BetterSearch_1.BetterSearch.setPaused(state),state?this.actButton.attr("disabled","disabled"):this.actButton.removeAttr("disabled")}async processFiles(){if(this.processing)return;this.setProcessing(!0),this.infoText.attr("data-state","loading").html("Indexing selected files . . .");const postList=new PostSet_1.PostSet;if($("post.download-item[data-state=ready]").each((index,element)=>{postList.push(Post_1.Post.get($(element)))}),0===postList.size())return this.infoText.attr("data-state","error").html("Error: No files selected!"),void this.setProcessing(!1);console.log(`downloading ${postList.size()} files`),console.log(postList);const downloadQueue=new DownloadQueue_1.DownloadQueue,threadInfo=[];this.infoFile.html("");for(let i=0;i<downloadQueue.getThreadCount();i++)threadInfo.push($("<span>").appendTo(this.infoFile));let totalFileSize=0,queueSize=0;this.downloadOverSize=!1;for(const post of postList.sort(PostSet_1.PostSortType.SizeAsc).values())if(post.has.file){if(totalFileSize+=post.file.size,Debug_1.Debug.log(`adding #${post.id} (${Util_1.Util.formatBytes(post.file.size)}) to the queue: ${Util_1.Util.formatBytes(totalFileSize)} total`),totalFileSize>MassDownloader.maxBlobSize){this.downloadOverSize=!0,Debug_1.Debug.log("over filesize limit, aborting");break}post.$ref.attr("data-state","preparing"),downloadQueue.add({name:this.createFilename(post),path:post.file.original,file:post.file.original.match(/.{32}\..*$/g)[0],unid:post.id,date:new Date(post.date.raw),tags:post.tagString},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("#entry_"+item.unid).attr("data-state","loading")},onFinish:item=>{$("#entry_"+item.unid).attr("data-state","done")},onError:item=>{$("#entry_"+item.unid).attr("data-state","error")},onLoadProgress:(item,thread,event)=>{event.lengthComputable&&threadInfo[thread].css("--progress",Math.round(event.loaded/event.total*100)+"%")},onWorkerFinish:(item,thread)=>{threadInfo[thread].remove()}})}queueSize=downloadQueue.getQueueLength(),this.infoText.html("Processing . . . ");const zipData=await downloadQueue.run(metadata=>{this.infoText.html(`Compressing . . . ${metadata.percent.toFixed(2)}%`),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")});this.infoText.attr("data-state","done").html("Done! "),this.infoFile.html(""),this.downloadIndex++;const filename=`e621-${this.fileTimestamp}-${this.downloadIndex}.zip`,$downloadLink=$("<a>").attr({href:URL.createObjectURL(zipData),download:filename}).html("Download Archive").appendTo(this.infoText);if(this.fetchSettings("autoDownloadArchive")){if($downloadLink.get(0).click(),this.downloadOverSize)return this.setProcessing(!1),void this.actButton.get(0).click()}else this.downloadOverSize&&$("<div>").addClass("download-notice").html("Download has exceeded the maximum file size.<br /><br />Click the download button again for the next part.").appendTo(this.infoText);this.setProcessing(!1)}createFilename(post){return MassDownloader.createFilenameBase(this.fetchSettings("template"),post).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+post.file.ext}static createFilenameBase(template,post){return template.replace(/%postid%/g,post.id+"").replace(/%artist%/g,[...post.tags.artist].join("-")).replace(/%copyright%/g,[...post.tags.copyright].join("-")).replace(/%character%/g,[...post.tags.character].join("-")).replace(/%species%/g,[...post.tags.species].join("-")).replace(/%meta%/g,[...post.tags.meta].join("-")).replace(/%md5%/g,post.file.md5)}}exports.MassDownloader=MassDownloader,MassDownloader.chunkSize=100,MassDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostSet":23,"../../components/utility/Debug":30,"../../components/utility/Util":33,"../search/BetterSearch":55}],41:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PoolDownloader=void 0;const DownloadQueue_1=require("../../components/api/DownloadQueue"),E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),MassDownloader_1=require("./MassDownloader");class PoolDownloader extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.pool,Page_1.PageDefintion.set]),this.processing=!1,this.downloadOverSize=!1,this.batchOverSize=!0,this.fileTimestamp=Util_1.Util.Time.getDatetimeShort(),this.downloadIndex=1,this.poolName="",this.poolFiles=[],this.poolDownloaded=[]}getDefaultSettings(){return{enabled:!0,template:"%pool%/%index%-%postid%-%artist%-%copyright%-%character%-%species%",autoDownloadArchive:!0}}create(){super.create();const base=Page_1.Page.matches(Page_1.PageDefintion.pool)?"div#c-pools":"div#c-sets",container=$(base).addClass("pool-container"),overview=$("#a-show").addClass("pool-overview");this.actButton=$("<button>").addClass("pool-download-button").addClass("button btn-neutral").html("Download").prependTo(overview).on("click",event=>{event.preventDefault(),container.attr("data-interface","true"),this.processFiles()});const sidebar=$("<aside>").addClass("pool-sidebar").appendTo(container);this.section=$("<section>").attr("id","pool-downloader-box").html("<h1>Download</h1>").appendTo(sidebar),this.infoText=$("<div>").addClass("download-info").appendTo(this.section),this.infoFile=$("<div>").addClass("download-file").appendTo(this.section)}processFiles(){if(this.processing)return;let source;this.processing=!0,this.actButton.attr("disabled","disabled"),this.infoText.attr("data-state","loading").html("Indexing pool files . . .");let poolName="UnknownPostGroup";source=Page_1.Page.matches(Page_1.PageDefintion.pool)?E621_1.E621.Pools.get({"search[id]":Page_1.Page.getPageID()}):E621_1.E621.Sets.get({"search[id]":Page_1.Page.getPageID()}),source.then(poolData=>{if(poolData.length<1)return Promise.reject("Pool not found");const pool=poolData[0],imageList=pool.post_ids.filter(n=>!this.poolDownloaded.includes(n));if(this.poolFiles=pool.post_ids,poolName=pool.name,0===imageList.length)return this.infoText.attr("data-state","error").html("Error: Pool is empty!"),Promise.reject("Pool is empty");this.poolName=pool.name,this.infoText.attr("data-state","loading").html("Fetching API data . . .");const dataQueue=[],resultPages=Math.ceil(imageList.length/320);this.infoFile.html(" request 1 / "+resultPages);for(let i=1;i<=resultPages;i++)dataQueue.push(new Promise(async resolve=>{const result=await E621_1.E621.Posts.get({tags:(Page_1.Page.matches(Page_1.PageDefintion.pool)?"pool:":"set:")+pool.id,page:i,limit:320},500);this.infoFile.html(" request "+(i+1)+" / "+resultPages),resolve(result)}));return Promise.all(dataQueue)}).then(dataChunks=>{const downloadQueue=new DownloadQueue_1.DownloadQueue,threadInfo=[];this.infoFile.html("");for(let i=0;i<downloadQueue.getThreadCount();i++)threadInfo.push($("<span>").appendTo(this.infoFile));let totalFileSize=0,queueSize=0;return this.batchOverSize=!1,dataChunks.forEach(chunk=>{this.batchOverSize||chunk.forEach(queuedPost=>{const post=Post_1.PostData.fromAPI(queuedPost);if(post.has.file){if(totalFileSize+=post.file.size,Debug_1.Debug.log(`adding #${post.id} (${Util_1.Util.formatBytes(post.file.size)}) to the queue: ${Util_1.Util.formatBytes(totalFileSize)} total`),totalFileSize>PoolDownloader.maxBlobSize)return this.batchOverSize=!0,void(this.downloadOverSize=!0);$("article.post-preview#post_"+post.id).attr("data-state","preparing"),downloadQueue.add({name:this.createFilename(post),path:post.file.original,file:post.file.original.match(/.{32}\..*$/g)[0],unid:post.id,date:new Date(post.date.raw),tags:post.tagString},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("article.post-preview#post_"+post.id).attr("data-state","loading")},onFinish:()=>{$("article.post-preview#post_"+post.id).attr("data-state","done")},onError:()=>{$("article.post-preview#post_"+post.id).attr("data-state","error")},onLoadProgress:(item,thread,event)=>{event.lengthComputable&&threadInfo[thread].css("--progress",Math.round(event.loaded/event.total*100)+"%")},onWorkerFinish:(item,thread)=>{threadInfo[thread].remove()}}),this.poolDownloaded.push(post.id)}})}),queueSize=downloadQueue.getQueueLength(),this.infoText.html("Processing . . . "),downloadQueue.run(metadata=>{this.infoText.html("Compressing . . . "+metadata.percent.toFixed(2)+"%"),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")})}).then(zipData=>{let filename=this.createPoolFilename(poolName)+"-"+this.fileTimestamp;filename+=this.downloadOverSize?"-part"+this.downloadIndex+".zip":".zip",this.infoText.attr("data-state","done").html("Done! "),this.infoFile.html("");const $downloadLink=$("<a>").attr({href:URL.createObjectURL(zipData),download:filename}).html("Download Archive").appendTo(this.infoText);this.fetchSettings("autoDownloadArchive")&&$downloadLink.get(0).click(),this.downloadIndex++,this.actButton.removeAttr("disabled"),this.processing=!1,this.batchOverSize&&(this.fetchSettings("autoDownloadArchive")?this.actButton.get(0).click():$("<div>").addClass("download-notice").html("Download has exceeded the maximum file size.<br /><br />Click the download button again for the next part.").appendTo(this.infoText))})}createFilename(post){return MassDownloader_1.MassDownloader.createFilenameBase(this.fetchSettings("template"),post).replace(/%pool%/g,this.poolName).replace(/%index%/g,""+(this.poolFiles.indexOf(post.id)+1)).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+post.file.ext}createPoolFilename(name){return name.slice(0,64).replace(/\s/g,"_").replace(/_{2,}/g,"_").replace(/-{2,}/g,"-").replace(/-*$/g,"")}}exports.PoolDownloader=PoolDownloader,PoolDownloader.chunkSize=100,PoolDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/utility/Debug":30,"../../components/utility/Util":33,"./MassDownloader":40}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FormattingManager=void 0;const Danbooru_1=require("../../components/api/Danbooru"),E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal"),Prompt_1=require("../../components/structure/Prompt"),iconDefinitions={spacer:" ",bold:"",italic:"",strikethrough:"",underscore:"",superscript:"",subscript:"",spoiler:"",color:"",code:"",heading:"",quote:"",section:"",tag:"",wiki:"",keyboard:"",link:"",unlink:"",link_prompt:"",lemon:"",pepper:"",drumstick:"",magic:"",clipboard:"",paperclip:"",fountainpen:"",comment:"",bell:"",bullhorn:"",heart:"","plus-square":"","minus-square":"",baby:"",scales:"","chart-pie":"",dice:"",hotdog:"",leaf:"","paper-plane":"",anchor:"",crown:"",crow:""};class FormattingManager extends RE6Module_1.RE6Module{constructor(){super([],!0),this.formatters=[],this.index=0}getDefaultSettings(){return{enabled:!0,buttonsActive:[{name:"Bold",icon:"bold",text:"[b]%selection%[/b]"},{name:"Italic",icon:"italic",text:"[i]%selection%[/i]"},{name:"Strikethrough",icon:"strikethrough",text:"[s]%selection%[/s]"},{name:"Underscore",icon:"underscore",text:"[u]%selection%[/u]"},{name:"Spacer",icon:"spacer",text:""},{name:"Heading",icon:"heading",text:"h2.%selection%"},{name:"Spoiler",icon:"spoiler",text:"[spoiler]%selection%[/spoiler]"},{name:"Code",icon:"code",text:"`%selection%`"},{name:"Quote",icon:"quote",text:"[quote]%selection%[/quote]"},{name:"Section",icon:"section",text:"[section=Title]%selection%[/section]"},{name:"Tag",icon:"tag",text:"{{%selection%}}"},{name:"Link",icon:"link",text:'"%selection%":'}],buttonInactive:[{name:"Superscript",icon:"superscript",text:"[sup]%selection%[/sup]"},{name:"Color",icon:"color",text:"[color=]%selection%[/color]"},{name:"Wiki",icon:"wiki",text:"[[%selection%]]"},{name:"Link (Prompted)",icon:"link_prompt",text:'"%selection%":%prompt:Address%'}]}}create(){if(super.create(),Page_1.Page.matches(Page_1.PageDefintion.upload)||Page_1.Page.matches(Page_1.PageDefintion.post)){const $textarea=$("textarea#post_description");$("<div>").addClass("dtext-previewable").append($('<div class="dtext-preview">')).insertBefore($textarea).append($textarea)}$("div.dtext-previewable:has(textarea)").each((i,element)=>{const $container=$(element),newFormatter=new FormattingHelper($container,this,this.index);this.formatters.push(newFormatter),$container.on("re621:formatter:update",()=>{this.formatters.forEach(element=>{element.getContainer().is(newFormatter.getContainer())||element.loadButtons()})}),this.index++})}destroy(){this.formatters.forEach(entry=>{entry.destroy()}),this.formatters=[]}}exports.FormattingManager=FormattingManager;class FormattingHelper{constructor($targetContainer,parent,id){this.parent=parent,this.id=id,this.$container=$targetContainer,this.createDOM()}getContainer(){return this.$container}createDOM(){this.$container.attr("data-editing","true"),this.$container.attr("data-drawer","false"),this.$form=this.$container.parents("form.simple_form").first(),this.$textarea=this.$container.find("textarea"),this.$preview=this.$container.find("div.dtext-preview"),this.createToolbar(),this.createButtonDrawer(),this.createCharacterCounter(),this.$form.find("input.dtext-preview-button").css("display","none"),this.$form.find("input[type=submit]").addClass("dtext-submit"),this.$form.addClass("formatting-helper"),this.$textarea.attr({rows:"0",cols:"0"}).addClass("border-foreground"),this.$preview.addClass("border-foreground color-text"),this.$formatButtons.sortable({helper:"clone",forceHelperSize:!0,cursor:"grabbing",containment:this.$container,connectWith:this.$formatButtonsDrawer,disabled:!0,update:()=>{this.saveButtons()}}),this.$formatButtonsDrawer.sortable({helper:"clone",forceHelperSize:!0,cursor:"grabbing",containment:this.$container,connectWith:this.$formatButtons,disabled:!0});const $editButtonsForm=new Form_1.Form({name:"dtext-edit-button-"+this.id,columns:2,width:2},[Form_1.Form.input({name:"name",label:"Name",width:2}),Form_1.Form.icon({name:"icon",label:"Icon",width:2},iconDefinitions),Form_1.Form.input({name:"text",label:"Content",width:2}),Form_1.Form.button({name:"delete",value:"Delete"},async()=>{this.deleteButton(this.$editButtonsModal.getActiveTrigger().parent()),this.$editButtonsModal.close()}),Form_1.Form.button({name:"update",value:"Update",type:"submit"}),Form_1.Form.hr(2),Form_1.Form.div({value:"Available variables:",width:2}),Form_1.Form.copy({label:"Selection",value:"%selection%",width:2}),Form_1.Form.copy({label:"Prompt",value:"%prompt%",width:2})],async values=>{this.updateButton(this.$editButtonsModal.getActiveTrigger().parent(),{name:values.name,icon:values.icon,text:values.text}),this.$editButtonsModal.close()});this.$editButtonsModal=new Modal_1.Modal({title:"Edit Button",content:Form_1.Form.placeholder(),structure:$editButtonsForm,triggers:[],triggerMulti:!0,fixed:!0,disabled:!0}),this.$editButtonsModal.getElement().on("dialogopen",()=>{const $button=this.$editButtonsModal.getActiveTrigger().parent(),$updateTabInputs=$editButtonsForm.getInputList();$updateTabInputs.get("name").val($button.attr("data-name")),$updateTabInputs.get("icon").val($button.attr("data-icon")).trigger("re621:form:update"),$updateTabInputs.get("text").val($button.attr("data-text"))}),this.loadButtons()}destroy(){this.$container.find(".comment-header, .dtext-button-drawer-title, .dtext-button-drawer, .dtext-character-counter-box").remove(),this.$form.find("input.dtext-preview-button").css("display","")}createToolbar(){const $bar=$("<div>").addClass("comment-header").addClass("border-foreground").prependTo(this.$container);this.$toggleTabs=$("<div>").addClass("comment-tabs").html('\n <a class="toggle-editing active">Write</a>\n <a class="toggle-preview">Preview</a>\n ').appendTo($bar),this.$toggleTabs.find("a").click(e=>{e.preventDefault(),this.toggleEditing()}),this.$formatButtons=$("<div>").addClass("comment-buttons").appendTo($bar);const $drawerButtonBox=$("<li>").appendTo($("<div>").addClass("settings-buttons").appendTo($bar));$("<a>").html("").attr("title","Settings").appendTo($drawerButtonBox).click(event=>{event.preventDefault(),this.toggleButtonDrawer()})}createButtonDrawer(){const $newFormatButton=$("<a>").html("Add Button");$("<div>").addClass("dtext-button-drawer-title").addClass("border-foreground color-text").append($newFormatButton).appendTo(this.$container);const newFormatForm=new Form_1.Form({name:"dtext-custom-button-"+this.id,columns:2,width:2},[Form_1.Form.input({name:"name",label:"Name",width:2}),Form_1.Form.icon({name:"icon",label:"Icon",width:2},iconDefinitions),Form_1.Form.input({name:"text",label:"Content",width:2}),Form_1.Form.spacer(),Form_1.Form.button({name:"submit",value:"Create",type:"submit"}),Form_1.Form.hr(2),Form_1.Form.div({value:"Available variables:",width:2}),Form_1.Form.copy({label:"Selection",value:"%selection%",width:2}),Form_1.Form.copy({label:"Prompt",value:"%prompt%",width:2})],values=>{this.createButton({name:values.name,icon:values.icon,text:values.text}).box.appendTo(this.$formatButtonsDrawer),newFormatForm.reset(),newFormatModal.close(),this.saveButtons()}),newFormatModal=new Modal_1.Modal({title:"New Custom Button",content:Form_1.Form.placeholder(),structure:newFormatForm,triggers:[{element:$newFormatButton}],fixed:!0});this.$formatButtonsDrawer=$("<div>").addClass("dtext-button-drawer").addClass("border-foreground color-text").appendTo(this.$container)}createCharacterCounter(){const charCounter=$("<span>").addClass("char-counter").html((this.$textarea.val()+"").length+" / 50000");$("<div>").addClass("dtext-character-counter-box").append(charCounter).appendTo(this.$container),this.$textarea.keyup(()=>{charCounter.html((this.$textarea.val()+"").length+" / 50000")})}loadButtons(){this.$formatButtons.empty(),this.parent.fetchSettings("buttonsActive",!0).then(response=>{response.forEach(data=>{const buttonElement=this.createButton(data);buttonElement.box.appendTo(this.$formatButtons),""===buttonElement.box.attr("data-text")&&(buttonElement.button.addClass("disabled"),buttonElement.button.removeAttr("title"))})}),this.$formatButtonsDrawer.empty(),this.parent.fetchSettings("buttonInactive",!0).then(response=>{response.forEach(data=>{this.createButton(data).box.appendTo(this.$formatButtonsDrawer)})})}async saveButtons(){let buttonData=[];function fetchData(element){const $button=$(element);return{name:$button.attr("data-name"),icon:$button.attr("data-icon"),text:$button.attr("data-text")}}this.$formatButtons.find("li").each((function(i,element){buttonData.push(fetchData(element))})),await this.parent.pushSettings("buttonsActive",buttonData),buttonData=[],this.$formatButtonsDrawer.find("li").each((function(i,element){buttonData.push(fetchData(element))})),await this.parent.pushSettings("buttonInactive",buttonData),this.$container.trigger("re621:formatter:update",[this])}parseButtonConfig(config){return void 0===config.name&&(config.name="New Button"),void 0===config.icon&&(config.icon="#"),void 0===config.text&&(config.text=""),config}createButton(config){config=this.parseButtonConfig(config);const box=$("<li>").attr({"data-name":config.name,"data-icon":config.icon,"data-text":config.text}).appendTo(this.$formatButtons),button=$("<a>").html(this.getIcon(config.icon)).addClass("format-button").attr("title",config.name).appendTo(box);return this.$editButtonsModal.registerTrigger({element:button}),button.click(event=>{event.preventDefault(),"false"===this.$container.attr("data-drawer")&&this.processFormattingTag(box.attr("data-text"))}),{button:button,box:box}}updateButton($element,config){config=this.parseButtonConfig(config),$element.attr("data-name",config.name).attr("data-icon",config.icon).attr("data-text",config.text),$element.find("a").first().html(this.getIcon(config.icon)).attr("title",config.name),this.saveButtons()}deleteButton($element){$element.remove(),this.saveButtons()}toggleEditing(){"true"===this.$container.attr("data-editing")?(this.$container.attr("data-editing","false"),this.$toggleTabs.find("a").toggleClass("active"),E621_1.E621.DTextPreview.post({body:this.$textarea.val()}).then(response=>{this.$preview.html(response[0].html),Danbooru_1.Danbooru.E621.addDeferredPosts(response[0].posts),Danbooru_1.Danbooru.Thumbnails.initialize()})):(this.$container.attr("data-editing","true"),this.$toggleTabs.find("a").toggleClass("active"))}toggleButtonDrawer(){"true"===this.$container.attr("data-drawer")?(this.$container.attr("data-drawer","false"),this.$formatButtons.sortable("disable"),this.$formatButtonsDrawer.sortable("disable"),this.$editButtonsModal.disable()):(this.$container.attr("data-drawer","true"),this.$formatButtons.sortable("enable"),this.$formatButtonsDrawer.sortable("enable"),this.$editButtonsModal.enable())}getIcon(name){return iconDefinitions[name]||""}processFormattingTag(content){const promises=[],lookup=content.match(/%prompt[:]?[^%]*?(%|$)/g),replacedTags=[];null!==lookup&&lookup.forEach((function(element){const title=element.replace(/(%$)|(^%prompt[:]?)/g,"");replacedTags.push(element),promises.push(new Prompt_1.Prompt(title).getPromise())})),Promise.all(promises).then(data=>{replacedTags.forEach((function(tag,index){content=content.replace(tag,data[index])}));const currentText=this.$textarea.val()+"",position={start:this.$textarea.prop("selectionStart"),end:this.$textarea.prop("selectionEnd")};content=content.replace(/%selection%/g,currentText.substring(position.start,position.end)),this.$textarea.focus(),document.execCommand("insertText",!1,content)||this.$textarea.val(currentText.substring(0,position.start)+content+currentText.substring(position.end,currentText.length)),this.$textarea.prop("selectionStart",position.start),this.$textarea.prop("selectionEnd",position.start+content.length),this.$textarea.keyup()})}}},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/structure/Form":26,"../../components/structure/Modal":27,"../../components/structure/Prompt":28}],43:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.HeaderCustomizer=void 0;const Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal");class HeaderCustomizer extends RE6Module_1.RE6Module{constructor(){super(),this.registerHotkeys({keys:"hotkeyTab1",fnct:()=>{HeaderCustomizer.openTabNum(0)}},{keys:"hotkeyTab2",fnct:()=>{HeaderCustomizer.openTabNum(1)}},{keys:"hotkeyTab3",fnct:()=>{HeaderCustomizer.openTabNum(2)}},{keys:"hotkeyTab4",fnct:()=>{HeaderCustomizer.openTabNum(3)}},{keys:"hotkeyTab5",fnct:()=>{HeaderCustomizer.openTabNum(4)}},{keys:"hotkeyTab6",fnct:()=>{HeaderCustomizer.openTabNum(5)}},{keys:"hotkeyTab7",fnct:()=>{HeaderCustomizer.openTabNum(6)}},{keys:"hotkeyTab8",fnct:()=>{HeaderCustomizer.openTabNum(7)}},{keys:"hotkeyTab9",fnct:()=>{HeaderCustomizer.openTabNum(8)}})}getDefaultSettings(){return{enabled:!0,hotkeyTab1:"1",hotkeyTab2:"2",hotkeyTab3:"3",hotkeyTab4:"4",hotkeyTab5:"5",hotkeyTab6:"6",hotkeyTab7:"7",hotkeyTab8:"8",hotkeyTab9:"9",tabs:[{name:"Account",href:"/users/home"},{name:"Posts",href:"/posts"},{name:"Comments",href:"/comments?group_by=post"},{name:"Artists",href:"/artists"},{name:"Tags",href:"/tags"},{name:"Blips",href:"/blips"},{name:"Pools",href:"/pools"},{name:"Sets",href:"/post_sets"},{name:"Wiki",href:"/wiki_pages?title=help%3Ahome"},{name:"Forum",href:"/forum_topics"},{name:"Discord",href:"/static/discord"},{name:"Help",href:"/help"},{name:"More »",href:"/static/site_map"}],forumUpdateDot:!0}}create(){super.create(),this.hasForumUpdates=$("li#nav-forum").hasClass("forum-updated"),this.$menu=$("menu.main"),this.$oldMenu=$("<div>").css("display","none").appendTo("body"),this.$menu.children().appendTo(this.$oldMenu),this.$menu.addClass("custom");for(const value of this.fetchSettings("tabs"))this.createTabElement(value);this.reloadTabMargins(),this.$menu.sortable({axis:"x",containment:"parent",helper:"clone",forceHelperSize:!0,opacity:.75,cursor:"grabbing",disabled:!0,update:()=>{this.reloadTabMargins(),this.saveNavbarSettings()}}),this.createConfigInterface(),this.toggleForumDot(this.fetchSettings("forumUpdateDot")),this.addTabModal.getElement().on("dialogopen",()=>{this.enableEditingMode()}),this.addTabModal.getElement().on("dialogclose",()=>{this.disableEditingMode()})}destroy(){this.isInitialized()&&(super.destroy(),this.$menu.removeClass("custom").empty(),this.$menu.sortable("destroy"),this.addTabButton.remove(),this.addTabModal.destroy(),this.updateTabModal.destroy(),this.$oldMenu.children().appendTo(this.$menu),this.$oldMenu.remove())}createConfigInterface(){this.addTabButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-customizer",name:'<i class="fas fa-tasks"></i>',title:"Edit Header Tabs",tabClass:"float-left"});const newTabForm=new Form_1.Form({name:"header-customizer-new"},[Form_1.Form.input({label:"Name",name:"name",value:"",required:!0,pattern:"[\\S ]+"}),Form_1.Form.input({label:"Hover",value:"",name:"title"}),Form_1.Form.input({label:"Link",value:"",name:"href"}),Form_1.Form.checkbox({label:"Attach to the right side",value:!1,name:"right"}),Form_1.Form.button({value:"Submit",type:"submit"}),Form_1.Form.hr(),Form_1.Form.div({value:"Available variables:"}),Form_1.Form.copy({label:"Unique ID",value:"%userid%"}),Form_1.Form.copy({label:"Username",value:"%username%"}),Form_1.Form.hr(),Form_1.Form.div({value:"Drag-and-drop tabs to re-arrange.<br />Click on a tab to edit it."})],(values,form)=>{this.addTab({name:values.name,title:values.title,href:values.href,right:values.right}),form.reset(),this.reloadTabMargins()});this.addTabModal=new Modal_1.Modal({title:"Add Tab",triggers:[{element:this.addTabButton}],content:Form_1.Form.placeholder(),structure:newTabForm,position:{my:"right top",at:"right top"}}),this.updateTabForm=new Form_1.Form({name:"header-customizer-update"},[Form_1.Form.input({label:"Name",name:"name",value:"",required:!0,pattern:"[\\S ]+"}),Form_1.Form.input({label:"Hover",value:"",name:"title"}),Form_1.Form.input({label:"Link",value:"",name:"href"}),Form_1.Form.checkbox({label:"Attach to the right side",value:!1,name:"right"}),Form_1.Form.button({value:"Delete",type:"button"},()=>{this.deleteTab(this.updateTabModal.getActiveTrigger().parent()),this.updateTabModal.close()}),Form_1.Form.button({value:"Update",type:"submit"})],(values,form)=>{this.updateTab(this.updateTabModal.getActiveTrigger().parent(),{name:values.name,title:values.title,href:values.href,right:values.right}),this.updateTabModal.close(),form.reset(),this.reloadTabMargins()}),this.updateTabModal=new Modal_1.Modal({title:"Update Tab",triggers:[{element:$("menu.main li a")}],content:Form_1.Form.placeholder(),structure:this.updateTabForm,position:{my:"center top",at:"center top"},triggerMulti:!0,disabled:!0})}enableEditingMode(){this.$menu.attr("data-editing","true"),this.$menu.sortable("enable"),this.updateTabModal.enable(),this.updateTabModal.getElement().on("dialogopen",()=>{const $tab=this.updateTabModal.getActiveTrigger().parent(),$updateTabInputs=this.updateTabForm.getInputList();$updateTabInputs.get("name").val($tab.data("tab.name")),$updateTabInputs.get("title").val($tab.data("tab.title")),$updateTabInputs.get("href").val($tab.data("tab.href")),$updateTabInputs.get("right").prop("checked",$tab.data("tab.right"))})}disableEditingMode(){this.$menu.attr("data-editing","false"),this.$menu.sortable("disable"),this.updateTabModal.close(),this.updateTabModal.disable()}toggleForumDot(state){this.$menu.attr("data-forumdot",""+state)}createTabElement(config,triggerUpdate=!1){config=this.parseHeaderTabConfig(config);const $tab=$("<li>").data({"tab.name":config.name,"tab.title":config.title,"tab.href":config.href,"tab.right":config.right}).attr("align",config.right?"true":void 0).appendTo(this.$menu),$link=$("<a>").html(this.processTabVariables(config.name)).appendTo($tab);return""!==config.title&&$link.attr("title",this.processTabVariables(config.title)),""!==config.href&&$link.attr("href",this.processTabVariables(config.href)),"/forum_topics"===config.href&&this.hasForumUpdates&&$link.addClass("tab-has-updates"),triggerUpdate&&this.saveNavbarSettings(),""!==config.href.trim()&&Page_1.Page.getURL().pathname.includes(this.processTabVariables(config.href).split("?")[0])&&$tab.addClass("bg-foreground"),{tab:$tab,link:$link}}parseHeaderTabConfig(config){return void 0===config.name&&(config.name="New Tab"),void 0===config.href&&(config.href=""),void 0===config.title&&(config.title=""),void 0===config.right&&(config.right=!1),config}addTab(config){config=this.parseHeaderTabConfig(config);const newTab=this.createTabElement(config,!0);this.updateTabModal.registerTrigger({element:newTab.link})}updateTab($element,config){config=this.parseHeaderTabConfig(config),$element.data({"tab.name":config.name,"tab.title":config.title,"tab.href":config.href,"tab.right":config.right}).removeAttr("align").attr("align",config.right?"true":void 0),$element.find("a").first().html(this.processTabVariables(config.name)).attr("title",this.processTabVariables(config.title)).attr("href",this.processTabVariables(config.href)),this.saveNavbarSettings()}deleteTab($element){$element.remove(),this.saveNavbarSettings()}processTabVariables(text){return text.replace(/%userid%/g,User_1.User.getUserID()+"").replace(/%username%/g,User_1.User.getUsername())}async saveNavbarSettings(){const tabData=[];function formatVal(value){if(value)return value}this.$menu.find("li").each((function(i,element){const $tab=$(element);tabData.push({name:formatVal($tab.data("tab.name")),title:formatVal($tab.data("tab.title")),href:formatVal($tab.data("tab.href")),right:!!$tab.data("tab.right")||void 0})})),await this.pushSettings("tabs",tabData)}static openTabNum(num){const tabs=ModuleController_1.ModuleController.get(HeaderCustomizer).$menu.find("li > a");num>tabs.length||tabs[num].click()}reloadTabMargins(){this.$menu.children("li").removeClass("margined"),this.$menu.find("li[align=true]").first().addClass("margined")}}exports.HeaderCustomizer=HeaderCustomizer},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/data/User":18,"../../components/structure/DomUtilities":25,"../../components/structure/Form":26,"../../components/structure/Modal":27}],44:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Miscellaneous=void 0;const E621_1=require("../../components/api/E621"),XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),BetterSearch_1=require("../search/BetterSearch");class Miscellaneous extends RE6Module_1.RE6Module{constructor(){super(),this.registerHotkeys({keys:"hotkeyNewComment",fnct:this.openNewComment},{keys:"hotkeyEditPost",fnct:this.openEditTab},{keys:"hotkeyToggleBlacklist",fnct:this.toggleBlacklist})}getDefaultSettings(){return{enabled:!0,hotkeyNewComment:"n",hotkeyEditPost:"e",hotkeyToggleBlacklist:"",hotkeySubmit:"alt+return",stickySearchbox:!0,stickyHeader:!1,stickyEditBox:!0,avatarClick:!0,fixForumTitle:!0}}create(){if(super.create(),Page_1.Page.matches([Page_1.PageDefintion.post,Page_1.PageDefintion.forum])&&this.handleQuoteButton(),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites])&&this.createStickySearchbox(this.fetchSettings("stickySearchbox")),this.createStickyHeader(this.fetchSettings("stickyHeader")),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites])&&this.createStickyEditBox(this.fetchSettings("stickyEditBox")),this.handleAvatarClick(this.fetchSettings("avatarClick")),this.fetchSettings("fixForumTitle")&&Page_1.Page.matches(Page_1.PageDefintion.forum)){const title=/^(?:Forum - )(.+)(?: - (e621|e926))$/g.exec(document.title);title&&(document.title=`${title[1]} - Forum - ${title[2]}`)}Page_1.Page.matches(Page_1.PageDefintion.settings)&&this.modifyBlacklistForm(),DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-dmail",name:'<i class="fas fa-envelope"></i>',href:"/dmails",title:"DMail"})}openNewComment(){Page_1.Page.matches(Page_1.PageDefintion.post)?($("menu#post-sections > li > a[href$=comments]")[0].click(),$("a.expand-comment-response")[0].click()):Page_1.Page.matches(Page_1.PageDefintion.forum)&&$("a#new-response-link")[0].click()}openEditTab(){Page_1.Page.matches(Page_1.PageDefintion.post)&&window.setTimeout(()=>{$("#post-edit-link")[0].click()},100)}createStickySearchbox(state=!0){$("body").attr("data-sticky",state+"")}createStickyHeader(state=!0){$("body").attr("data-sticky-header",state+"")}createStickyEditBox(state=!0){$("body").attr("data-sticky-editbox",state+"")}handleQuoteButton(){Page_1.Page.matches(Page_1.PageDefintion.forum)?($(".forum-post-reply-link").each((function(index,element){const $newLink=$("<a>").attr("href","#").addClass("re621-forum-post-reply").html("Respond");$(element).after($newLink).remove()})),$(".re621-forum-post-reply").on("click",event=>{event.preventDefault();const $parent=$(event.target).parents("article.forum-post");this.quote($parent,"forum",$parent.data("forum-post-id"),$("#forum_post_body"),$("a#new-response-link"))})):Page_1.Page.matches(Page_1.PageDefintion.post)&&($(".comment-reply-link").each((function(index,element){const $newLink=$("<a>").attr("href","#").addClass("re621-comment-reply").html("Respond");$(element).after($newLink).remove()})),$(".re621-comment-reply").on("click",event=>{event.preventDefault();const $parent=$(event.target).parents("article.comment");this.quote($parent,"comment",$parent.data("comment-id"),$("#comment_body_for_"),$("a.expand-comment-response"))}))}async quote($parent,endpoint,id,$textarea,$responseButton){let strippedBody="";const selection=window.getSelection().toString();if(""===selection){strippedBody=("forum"===endpoint?await E621_1.E621.ForumPost.id(id).first():await E621_1.E621.Comment.id(id).first()).body.replace(/\[quote\](?:.|\n|\r)+?\[\/quote\][\n\r]*/gm,""),strippedBody='[quote]"'+$parent.data("creator")+'":/user/show/'+$parent.data("creator-id")+" said:\n"+strippedBody+"\n[/quote]"}else strippedBody='[quote]"'+$parent.data("creator")+'":/user/show/'+$parent.data("creator-id")+" said:\n"+selection+"\n[/quote]";($textarea.val()+"").length>0&&(strippedBody="\n\n"+strippedBody),$responseButton[0].click(),$textarea.scrollTop($textarea[0].scrollHeight);const newVal=$textarea.val()+strippedBody;$textarea.focus().val("").val(newVal)}handleAvatarClick(state=!0){if($("div.avatar > div.active > a").off("click.re621.thumbnail").off("dblclick.re621.thumbnail"),!state)return;const clickAction=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings("clickAction"),avatars=$("div.avatar > div > a").get();for(const element of avatars){const $link=$(element);let dbclickTimer,prevent=!1;$link.on("click.re621.thumbnail",event=>{0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||(event.preventDefault(),dbclickTimer=window.setTimeout(()=>{prevent||($link.off("click.re621.thumbnail"),$link[0].click()),prevent=!1},200))}).on("dblclick.re621.thumbnail",event=>{0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||(event.preventDefault(),window.clearTimeout(dbclickTimer),prevent=!0,clickAction===BetterSearch_1.ImageClickAction.NewTab?XM_1.XM.Util.openInTab(window.location.origin+$link.attr("href"),!1):($link.off("click.re621.thumbnail"),$link[0].click()))})}}handleSubmitForm(event){$(event.target).parents("form").submit()}modifyBlacklistForm(){const $textarea=$("textarea#user_blacklisted_tags"),$container=$("div.user_blacklisted_tags"),charCounter=$("<span>").addClass("char-counter").html(($textarea.val()+"").length+" / 50000");$("<div>").addClass("blacklist-character-counter-box").append(charCounter).appendTo($container),$textarea.keyup(()=>{charCounter.html(($textarea.val()+"").length+" / 50000")})}toggleBlacklist(){$("a#disable-all-blacklists:visible, a#re-enable-all-blacklists:visible").first()[0].click()}}exports.Miscellaneous=Miscellaneous},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":6,"../../components/data/Page":16,"../../components/structure/DomUtilities":25,"../search/BetterSearch":55}],45:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SettingsController=void 0;const E621_1=require("../../components/api/E621"),XM_1=require("../../components/api/XM"),AvoidPosting_1=require("../../components/cache/AvoidPosting"),TagCache_1=require("../../components/cache/TagCache"),User_1=require("../../components/data/User"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal"),Tabbed_1=require("../../components/structure/Tabbed"),Debug_1=require("../../components/utility/Debug"),Patcher_1=require("../../components/utility/Patcher"),Util_1=require("../../components/utility/Util"),VersionChecker_1=require("../../components/utility/VersionChecker"),FavDownloader_1=require("../downloader/FavDownloader"),MassDownloader_1=require("../downloader/MassDownloader"),PoolDownloader_1=require("../downloader/PoolDownloader"),SmartAlias_1=require("../misc/SmartAlias"),UploadUtilities_1=require("../misc/UploadUtilities"),DownloadCustomizer_1=require("../post/DownloadCustomizer"),ImageScaler_1=require("../post/ImageScaler"),PoolNavigator_1=require("../post/PoolNavigator"),PostViewer_1=require("../post/PostViewer"),TitleCustomizer_1=require("../post/TitleCustomizer"),BetterSearch_1=require("../search/BetterSearch"),CustomFlagger_1=require("../search/CustomFlagger"),HoverZoom_1=require("../search/HoverZoom"),SearchUtilities_1=require("../search/SearchUtilities"),ForumTracker_1=require("../subscriptions/ForumTracker"),PoolTracker_1=require("../subscriptions/PoolTracker"),SubscriptionManager_1=require("../subscriptions/SubscriptionManager"),HeaderCustomizer_1=require("./HeaderCustomizer"),Miscellaneous_1=require("./Miscellaneous");class SettingsController extends RE6Module_1.RE6Module{constructor(){super(),this.registerHotkeys({keys:"hotkeyOpenSettings",fnct:this.openSettings})}getDefaultSettings(){return{enabled:!0,hotkeyOpenSettings:""}}create(){this.openSettingsButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-settings",name:'<i class="fas fa-wrench"></i>',title:"Settings",tabClass:"float-right",attr:{"data-loading":"false","data-updates":"0"},linkClass:"update-notification"});const $settings=new Tabbed_1.Tabbed({name:"settings-tabs",content:[{name:"General",structure:this.createGeneralTab()},{name:"Downloads",structure:this.createDownloadsTab()},{name:"Custom Flags",structure:this.createFlagsTab()},{name:"Smart Alias",structure:this.createUploadsTab()},{name:"Hotkeys",structure:this.createHotkeysTab()},{name:"Features",structure:this.createFeaturesTab()},{name:this.utilTabButton=$("<a>").attr({"data-loading":"false","data-updates":"0",id:"conf-tab-util"}).addClass("update-notification").html("Utilities"),structure:this.createMiscTab()},{name:this.aboutTabButton=$("<a>").attr({"data-loading":"false","data-updates":"0",id:"conf-tab-about"}).addClass("update-notification").html("About"),structure:this.createAboutTab()}]});new Modal_1.Modal({title:"Settings",triggers:[{element:this.openSettingsButton}],escapable:!1,fixed:!0,reserveHeight:!0,content:Form_1.Form.placeholder(3),structure:$settings,position:{my:"center",at:"center"}})}pushNotificationsCount(tab,count=0){this.openSettingsButton.attr("data-updates",(parseInt(this.openSettingsButton.attr("data-updates"))||0)+count);("util"==tab?this.utilTabButton:this.aboutTabButton).attr("data-updates",(parseInt(this.utilTabButton.attr("data-updates"))||0)+count)}createGeneralTab(){const titleCustomizer=ModuleController_1.ModuleController.get(TitleCustomizer_1.TitleCustomizer),miscellaneous=ModuleController_1.ModuleController.get(Miscellaneous_1.Miscellaneous),postViewer=ModuleController_1.ModuleController.get(PostViewer_1.PostViewer),imageScaler=ModuleController_1.ModuleController.get(ImageScaler_1.ImageScaler),headerCustomizer=ModuleController_1.ModuleController.get(HeaderCustomizer_1.HeaderCustomizer),searchUtilities=ModuleController_1.ModuleController.get(SearchUtilities_1.SearchUtilities),betterSearch=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch),hoverZoom=ModuleController_1.ModuleController.get(HoverZoom_1.HoverZoom);return new Form_1.Form({name:"optgeneral",columns:3,width:3},[Form_1.Form.accordion({name:"gencollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"layout",label:"Layout",columns:3,width:3},[Form_1.Form.div({value:"<b>Main Page</b><br />Reroute the title page to the one specified",width:2}),Form_1.Form.select({value:Util_1.Util.LS.getItem("re621.mainpage")||"default"},{default:"Default",posts:"Posts",forum_topics:"Forums",blips:"Blips"},value=>{Util_1.Util.LS.setItem("re621.mainpage",value)}),Form_1.Form.spacer(3,!0),Form_1.Form.input({name:"template",value:titleCustomizer.fetchSettings("template"),label:"<b>Page Title</b>",width:3},async data=>{await titleCustomizer.pushSettings("template",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.section({columns:3,width:3},[Form_1.Form.div({value:'<div class="notice unmargin">The following variables can be used:</div>',width:3}),Form_1.Form.copy({value:"%postid%",label:"Post ID"}),Form_1.Form.copy({value:"%artist%",label:"Artist"}),Form_1.Form.copy({value:"%copyright%",label:"Copyright"}),Form_1.Form.copy({value:"%character%",label:"Characters"}),Form_1.Form.copy({value:"%species%",label:"Species"}),Form_1.Form.copy({value:"%meta%",label:"Meta"})]),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:titleCustomizer.fetchSettings("symbolsEnabled"),label:"<b>Title Icons</b>",width:3},async data=>{await titleCustomizer.pushSettings("symbolsEnabled",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.input({value:titleCustomizer.fetchSettings("symbolFav"),label:"Favorite"},async data=>{await titleCustomizer.pushSettings("symbolFav",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.input({value:titleCustomizer.fetchSettings("symbolVoteUp"),label:"Upvoted"},async data=>{await titleCustomizer.pushSettings("symbolVoteUp",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.input({value:titleCustomizer.fetchSettings("symbolVoteDown"),label:"Downvoted"},async data=>{await titleCustomizer.pushSettings("symbolVoteDown",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.hr(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("improveTagCount"),label:"<b>Expanded Tag Count</b><br />Replace the rounded tag count in the sidebar with the precise one",width:3},async data=>{await searchUtilities.pushSettings("improveTagCount",data),searchUtilities.isInitialized()&&searchUtilities.improveTagCount(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("shortenTagNames"),label:"<b>Shorten Tag Names</b><br />Cut off long tag names to make them fit on one line",width:3},async data=>{await searchUtilities.pushSettings("shortenTagNames",data),searchUtilities.isInitialized()&&searchUtilities.shortenTagNames(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("hidePlusMinusIcons"),label:"<b>Hide + and - Icons</b><br />Remove these icons from view",width:3},async data=>{await searchUtilities.pushSettings("hidePlusMinusIcons",data),searchUtilities.isInitialized()&&searchUtilities.hidePlusMinusIcons(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:postViewer.fetchSettings("moveChildThumbs"),label:"<b>Move Related Thumbnails</b><br />Moves the parent / child thumbnails to the sidebar",width:2},async data=>{await postViewer.pushSettings("moveChildThumbs",data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>',1,"align-middle"),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:postViewer.fetchSettings("boldenTags"),label:"<b>Boldened Tags</b><br />Restore the classic boldened look on the sidebar tags",width:3},async data=>{await postViewer.pushSettings("boldenTags",data),postViewer.toggleBoldenedTags(data)}),Form_1.Form.hr(3),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("stickyHeader"),label:"<b>Fixed Header</b><br />Make the page header stick to the top when scrolling",width:3},async data=>{await miscellaneous.pushSettings("stickyHeader",data),miscellaneous.createStickyHeader(data),$("#sidebar").trigger("re621:reflow")}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("stickySearchbox"),label:"<b>Fixed Sidebar</b><br />Leave the sidebar controls on the screen while scrolling",width:3},async data=>{await miscellaneous.pushSettings("stickySearchbox",data),miscellaneous.createStickySearchbox(data),$("#sidebar").trigger("re621:reflow")}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("stickyEditBox"),label:"<b>Fixed Edit Form</b><br />Make the quick tags form stick to the top when scrolling",width:3},async data=>{await miscellaneous.pushSettings("stickyEditBox",data),miscellaneous.createStickyEditBox(data)})]),Form_1.Form.accordionTab({name:"thumb",label:"Thumbnails",columns:3,width:3},[Form_1.Form.subheader("Hi-Res Thumbnails","Replace 150x150 thumbnails with high-resolution ones",2),Form_1.Form.select({value:betterSearch.fetchSettings("imageLoadMethod")},{disabled:"Disabled",hover:"On Hover",always:"Always"},async data=>{await betterSearch.pushSettings("imageLoadMethod",data),betterSearch.isInitialized()&&(betterSearch.reloadEventListeners(),betterSearch.reloadRenderedPosts())}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("autoPlayGIFs"),label:"<b>Auto-Play GIFs</b><br />If disabled, animated GIFs will only play on hover",width:3},async data=>{await betterSearch.pushSettings("autoPlayGIFs",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Double-Click Action","Action taken when a thumbnail is double-clicked",2),Form_1.Form.select({value:betterSearch.fetchSettings("clickAction")},{disabled:"Disabled",newtab:"Open New Tab",copyid:"Copy Post ID",blacklist:"Add to Blacklist",addtoset:"Add to Current Set ",toggleset:"Toggle Current Set "},async data=>{await betterSearch.pushSettings("clickAction",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("hoverTags"),label:"<b>Preserve Hover Text</b><br />Restores text displayed when hovering over the thumbnail",width:3},async data=>{await betterSearch.pushSettings("hoverTags",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.collapse({name:"scalingconf",columns:3,width:3,title:"Scaling Options",collapsed:!0},[Form_1.Form.checkbox({value:betterSearch.fetchSettings("imageSizeChange"),label:"<b>Thumbnail Rescaling</b><br />Resize thumbnail images according to settings below",width:3},async data=>{await betterSearch.pushSettings("imageSizeChange",data),betterSearch.isInitialized()&&betterSearch.updateContentHeader(),$("#optgeneral-gencollapse-thumb-scalingconf-thumbsize-desc").toggleClass("input-disabled",!data),$("#optgeneral-gencollapse-thumb-scalingconf-thumbsize").prop("disabled",!data).parent().toggleClass("input-disabled",!data)}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Thumbnail Size","Thumbnail card width, in pixels",2,"thumbsize-desc",betterSearch.fetchSettings("imageSizeChange")?void 0:"input-disabled"),Form_1.Form.input({name:"thumbsize",value:betterSearch.fetchSettings("imageWidth"),title:"Number between 150 and 999",required:!0,pattern:"^(1[5-9][0-9]|[2-9][0-9][0-9])$",wrapper:betterSearch.fetchSettings("imageSizeChange")?void 0:"input-disabled",disabled:!betterSearch.fetchSettings("imageSizeChange")},async(data,input)=>{""!=input.val()&&input.get()[0].checkValidity()&&(await betterSearch.pushSettings("imageWidth",parseInt(data)),betterSearch.isInitialized()&&betterSearch.updateContentHeader())}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"cropimages",value:betterSearch.fetchSettings("imageRatioChange"),label:"<b>Crop Images</b><br />Restrict image size to the specified ratio",width:3},async data=>{await betterSearch.pushSettings("imageRatioChange",data),betterSearch.isInitialized()&&(betterSearch.updateContentHeader(),betterSearch.reloadRenderedPosts()),$("#optgeneral-gencollapse-thumb-scalingconf-cropratio-desc").toggleClass("input-disabled",!data),$("#optgeneral-gencollapse-thumb-scalingconf-cropratio").prop("disabled",!data).parent().toggleClass("input-disabled",!data)}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Image Ratio","Height to width ratio of the image",2,"cropratio-desc",betterSearch.fetchSettings("imageRatioChange")?void 0:"input-disabled"),Form_1.Form.input({name:"cropratio",value:betterSearch.fetchSettings("imageRatio"),title:"Number between 0.1 and 1.9",required:!0,pattern:"^([01]\\.[1-9]|1\\.0)$",wrapper:betterSearch.fetchSettings("imageRatioChange")?void 0:"input-disabled",disabled:!betterSearch.fetchSettings("imageRatioChange")},async(data,input)=>{""!=input.val()&&input.get()[0].checkValidity()&&(await betterSearch.pushSettings("imageRatio",parseFloat(data)),betterSearch.isInitialized()&&(betterSearch.updateContentHeader(),betterSearch.reloadRenderedPosts()))}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"compactMode",value:betterSearch.fetchSettings("compactMode"),label:"<b>Compact Mode</b><br />Limit the image height to the same value as the width",width:3},async data=>{await betterSearch.pushSettings("compactMode",data),betterSearch.isInitialized()&&(betterSearch.updateContentHeader(),betterSearch.reloadRenderedPosts())}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Minimum Image Width","Images narrower than this percent value will be cropped to fit",2),Form_1.Form.input({value:betterSearch.fetchSettings("imageMinWidth"),required:!0,pattern:"^([1-9][0-9]|100)$",title:"Number between 10 and 100"},async(data,input)=>{""!=input.val()&&input.get()[0].checkValidity()&&(await betterSearch.pushSettings("imageMinWidth",parseInt(data)),betterSearch.isInitialized()&&betterSearch.updateContentHeader())}),Form_1.Form.spacer(3,!0)]),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"votebutton",value:betterSearch.fetchSettings("buttonsVote"),label:"<b>Voting Buttons</b><br />Adds voting buttons when hovering over a thumbnail",width:3},async data=>{await betterSearch.pushSettings("buttonsVote",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"favbutton",value:betterSearch.fetchSettings("buttonsFav"),label:"<b>Favorite Button</b><br />Adds a +favorite button when hovering over a thumbnail",width:3},async data=>{await betterSearch.pushSettings("buttonsFav",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("ribbonsRel"),label:"<b>Relations Ribbons</b><br />Display ribbons for parent/child relationships",width:3},async data=>{await betterSearch.pushSettings("ribbonsRel",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("ribbonsFlag"),label:"<b>Status Ribbons</b><br />Display post status as a colored ribbon on the post",width:3},async data=>{await betterSearch.pushSettings("ribbonsFlag",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("ribbonsAlt"),label:"<b>Alternative Ribbons</b><br />Place the ribbons on the bottom of the thumbnail",width:3},async data=>{await betterSearch.pushSettings("ribbonsAlt",data),betterSearch.isInitialized()&&betterSearch.updateContentHeader()})]),Form_1.Form.accordionTab({name:"infscroll",label:"Scrolling and Zoom",columns:3,width:3},[Form_1.Form.header("Infinite Scroll",3),Form_1.Form.checkbox({value:betterSearch.fetchSettings("infiniteScroll"),label:"<b>Enable Infinite Scroll</b><br />Append the next page of posts below the current one",width:3},async data=>{await betterSearch.pushSettings("infiniteScroll",data),betterSearch.isInitialized()&&(betterSearch.reloadEventListeners(),betterSearch.reloadPaginator())}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("loadAutomatically"),label:"<b>Auto-Load Posts</b><br />Load posts automatically as you scroll, not by clicking a button",width:3},async data=>{await betterSearch.pushSettings("loadAutomatically",data),betterSearch.isInitialized()&&betterSearch.reloadEventListeners()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("loadPrevPages"),label:"<b>Preserve Scroll History</b><br />When opening a specific result page, load several previous pages as well",width:3},async data=>{await betterSearch.pushSettings("loadPrevPages",data)}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("hidePageBreaks"),label:"<b>Hide Page Separators</b><br />Display posts as one continuous section, instead of being separated by page",width:3},async data=>{await betterSearch.pushSettings("hidePageBreaks",data),betterSearch.isInitialized()&&betterSearch.updateContentHeader()}),Form_1.Form.hr(3),Form_1.Form.header("Hover Zoom",3),Form_1.Form.div({value:"<b>Zoom Mode</b><br />Increases the size of the thumbnail when hovering over it",width:2}),Form_1.Form.select({name:"hoverzoom",value:hoverZoom.fetchSettings("mode")},{disabled:"Disabled",hover:"On Hover",onshift:"Holding Shift"},async data=>{console.log("setting",data,hoverZoom.isInitialized()),await hoverZoom.pushSettings("mode",data),hoverZoom.isInitialized()&&hoverZoom.reloadEventListeners()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:hoverZoom.fetchSettings("tags"),label:"<b>Show Tags</b><br />Display the list of posts's tags under the zoom-in image",width:3},async data=>{await hoverZoom.pushSettings("tags",data)}),Form_1.Form.spacer(3,!0)]),Form_1.Form.accordionTab({name:"misc",label:"Other",columns:3,width:3},[Form_1.Form.hr(3),Form_1.Form.text("<b>Persistent Tags</b>"),Form_1.Form.input({value:searchUtilities.fetchSettings("persistentTags"),width:2},async data=>{await searchUtilities.pushSettings("persistentTags",data)}),Form_1.Form.text("Tags added to every search, used to emulate server-side blacklisting",2),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>',1,"align-middle"),Form_1.Form.hr(3),Form_1.Form.checkbox({value:postViewer.fetchSettings("upvoteOnFavorite"),label:"<b>Auto-Upvote Favorites</b><br />Automatically upvote a post when adding it to the favorites",width:3},async data=>{await postViewer.pushSettings("upvoteOnFavorite",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:imageScaler.fetchSettings("clickScale"),label:"<b>Quick Rescale</b><br />Click on a post image to cycle through scaling options",width:3},async data=>{await imageScaler.pushSettings("clickScale",data),imageScaler.toggleClickScale(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("collapseCategories"),label:"<b>Remember Collapsed Tag Categories</b><br />Preserve the minimized state of the tag categories in the sidebar",width:3},async data=>{await searchUtilities.pushSettings("collapseCategories",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("quickBlacklist"),label:"<b>Quick Blacklist</b><br />Click X next to the tag in the sidebar to add it to the blacklist",width:3},async data=>{await searchUtilities.pushSettings("quickBlacklist",data),searchUtilities.initQuickBlacklist(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:headerCustomizer.fetchSettings("forumUpdateDot"),label:"<b>Forum Notifications</b><br />Red dot on the Forum tab in the header if there are new posts",width:3},async data=>{headerCustomizer.toggleForumDot(data),await headerCustomizer.pushSettings("forumUpdateDot",data)}),Form_1.Form.spacer(3)])])])}createDownloadsTab(){const downloadCustomizer=ModuleController_1.ModuleController.get(DownloadCustomizer_1.DownloadCustomizer),massDownloader=ModuleController_1.ModuleController.get(MassDownloader_1.MassDownloader),poolDownloader=ModuleController_1.ModuleController.get(PoolDownloader_1.PoolDownloader),favDownloader=ModuleController_1.ModuleController.get(FavDownloader_1.FavDownloader);return new Form_1.Form({name:"optdownload",columns:3,width:3},[Form_1.Form.section({name:"customizer",columns:3,width:3},[Form_1.Form.header("Download Customizer"),Form_1.Form.div({value:'<div class="notice float-right">Download individual files</div>',width:2}),Form_1.Form.text("<b>File name</b>"),Form_1.Form.input({value:downloadCustomizer.fetchSettings("template"),width:2},async data=>{await downloadCustomizer.pushSettings("template",data),downloadCustomizer.isInitialized()&&downloadCustomizer.refreshDownloadLink()}),Form_1.Form.section({columns:3,width:3},[Form_1.Form.div({value:'<div class="notice unmargin">The following variables can be used:</div>',width:3}),Form_1.Form.copy({value:"%postid%",label:"Post ID"}),Form_1.Form.copy({value:"%artist%",label:"Artist"}),Form_1.Form.copy({value:"%copyright%",label:"Copyright"}),Form_1.Form.copy({value:"%character%",label:"Characters"}),Form_1.Form.copy({value:"%species%",label:"Species"}),Form_1.Form.copy({value:"%meta%",label:"Meta"}),Form_1.Form.copy({value:"%md5%",label:"MD5"})])]),Form_1.Form.spacer(3),Form_1.Form.accordion({name:"downcollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"mass",label:"Mass Downloader",subheader:"Download files from the search page",columns:3,width:3},[Form_1.Form.text("<b>Archive name</b>"),Form_1.Form.input({value:massDownloader.fetchSettings("template"),width:2},async data=>{await massDownloader.pushSettings("template",data)}),Form_1.Form.div({value:'<div class="notice unmargin">The same variables as above can be used. Add a forward slash ( / ) to signify a folder.</div>',width:3}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:massDownloader.fetchSettings("autoDownloadArchive"),label:"<b>Auto Download</b><br />The archive will be downloaded automatically after being created",width:3},async data=>{await massDownloader.pushSettings("autoDownloadArchive",data)})]),Form_1.Form.accordionTab({name:"fav",label:"Favorites Downloader",subheader:"Download all favorites at once",columns:3,width:3},[Form_1.Form.text("<b>Archive name</b>"),Form_1.Form.input({value:favDownloader.fetchSettings("template"),width:2},async data=>{await favDownloader.pushSettings("template",data)}),Form_1.Form.div({value:'<div class="notice unmargin">The same variables as above can be used. Add a forward slash ( / ) to signify a folder.</div>',width:3}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:favDownloader.fetchSettings("autoDownloadArchive"),label:"<b>Auto Download</b><br />The archive will be downloaded automatically after being created",width:3},async data=>{await favDownloader.pushSettings("autoDownloadArchive",data)})]),Form_1.Form.accordionTab({name:"pool",label:"Pool Downloader",subheader:"Download image pools or sets",columns:3,width:3},[Form_1.Form.text("<b>Archive name</b>"),Form_1.Form.input({value:poolDownloader.fetchSettings("template"),width:2},async data=>{await poolDownloader.pushSettings("template",data)}),Form_1.Form.section({name:"template-vars-pool",columns:3,width:3},[Form_1.Form.div({value:'<div class="notice unmargin">The same variables as above can be used. Add a forward slash ( / ) to signify a folder.</div>',width:3}),Form_1.Form.div({value:'<div class="notice unmargin">The following variables can also be used:</div>',width:3}),Form_1.Form.copy({value:"%pool%",label:"Pool Name"}),Form_1.Form.copy({value:"%index%",label:"Index"})]),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:poolDownloader.fetchSettings("autoDownloadArchive"),label:"<b>Auto Download</b><br />The archive will be downloaded automatically after being created",width:3},async data=>{await poolDownloader.pushSettings("autoDownloadArchive",data)})])])])}createFlagsTab(){const customFlagger=ModuleController_1.ModuleController.get(CustomFlagger_1.CustomFlagger),defsContainer=$("<div>").attr("id","flag-defs-container");return customFlagger.fetchSettings("flags").forEach(flag=>{makeDefInput(flag).appendTo(defsContainer)}),new Form_1.Form({name:"optflags",columns:3,width:3},[Form_1.Form.header("Flag Definitions",2),Form_1.Form.button({value:"New Flag"},async()=>{makeDefInput({name:"",color:"#"+Math.floor(16777215*Math.random()).toString(16),tags:""}).appendTo(defsContainer)}),Form_1.Form.div({value:defsContainer,width:3}),Form_1.Form.button({value:"Save"},async()=>{const confirmBox=$("span#defs-confirm").html("Saving . . ."),defData=[],defInputs=$(defsContainer).find("div.flag-defs-inputs").get();for(const inputContainer of defInputs){const inputs=$(inputContainer).find("input").get(),name=$(inputs[0]),color=$(inputs[1]),tags=$(inputs[2]);0==name.val().length&&name.val("FLAG"),color.val().match(/^#(?:[0-9a-f]{3}){1,2}$/i)||color.val("#800000"),0!=tags.val().length&&defData.push({name:name.val(),color:color.val(),tags:tags.val()})}await customFlagger.pushSettings("flags",defData),confirmBox.html("Settings Saved"),window.setTimeout(()=>{confirmBox.html("")},1e3)}),Form_1.Form.div({value:'<span id="defs-confirm"></span>'}),Form_1.Form.div({value:"\n <b>Custom Flags</b> allow you to automatically highlight posts that match specified tags. For example:<br />\n <pre>-solo -duo -group -zero_pictured</pre>: posts that do not include character count tags.<br />\n <pre>tagcount:<5</pre>: posts with less than 5 tags<br />\n Flag names must be unique. Duplicate tag strings are allowed, but their corresponding flag may not display.",width:3})]);function makeDefInput(flag){const flagContainer=$("<div>").addClass("flag-defs-inputs");return $("<input>").attr({type:"text",placeholder:"name"}).val(void 0===flag?"":flag.name).appendTo(flagContainer),$("<input>").attr({type:"text",placeholder:"color"}).val(void 0===flag?"":flag.color).css("border-left-color",void 0===flag?"transparent":flag.color).appendTo(flagContainer).keyup(event=>{const $target=$(event.target);($target.val()+"").match(/^#(?:[0-9a-f]{3}){1,2}$/i)&&$target.css("border-left-color",$target.val()+"")}),$("<input>").attr({type:"text",placeholder:"tags"}).val(void 0===flag?"":flag.tags).appendTo(flagContainer),$("<button>").html('<i class="far fa-trash-alt"></i>').appendTo(flagContainer).click(()=>{flagContainer.remove()}),flagContainer}}createUploadsTab(){const smartAlias=ModuleController_1.ModuleController.get(SmartAlias_1.SmartAlias),uploadUtilities=ModuleController_1.ModuleController.get(UploadUtilities_1.UploadUtilities),aliasContainer=$("<textarea>").attr("id","alias-list-container").val(smartAlias.fetchSettings("data"));return new Form_1.Form({name:"optalias",columns:3,width:3},[Form_1.Form.accordion({name:"aliascollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"validatior",label:"Validation Configuration",columns:3,width:3},[Form_1.Form.checkbox({value:uploadUtilities.fetchSettings("checkDuplicates"),label:"<b>Check Duplicates</b><br />Search for visually similar images on e621 when uploading",width:2},async data=>{await uploadUtilities.pushSettings("checkDuplicates",data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>'),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:uploadUtilities.fetchSettings("addSourceLinks"),label:"<b>Source Link Buttons</b><br />Add utility buttons to the upload source inputs",width:2},async data=>{await uploadUtilities.pushSettings("addSourceLinks",data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>'),Form_1.Form.hr(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("autoLoad"),label:"<b>Run Automatically</b><br />Either validate tag input as you type, or by pressing a button",width:3},async data=>{await smartAlias.pushSettings("autoLoad",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("replaceAliasedTags"),label:"<b>Replace Aliases</b><br />Automatically replace aliased tag names with their consequent version",width:3},data=>{smartAlias.pushSettings("replaceAliasedTags",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("fixCommonTypos"),label:"<b>Fix Common Typos</b><br />Correct several common typos in the tag fields",width:3,wrapper:"display-none"},data=>{smartAlias.pushSettings("fixCommonTypos",data)}),Form_1.Form.subheader("Tag Display Order","How the tags should be arranged in the display box",2),Form_1.Form.select({value:smartAlias.fetchSettings("tagOrder")},{default:"Original",alphabetical:"Alphabetical",grouped:"Grouped by Category"},data=>{smartAlias.pushSettings("tagOrder",data)}),Form_1.Form.spacer(3),Form_1.Form.subheader("Minimum Posts Warning","Highlight tags that have less than the specified number of posts",2),Form_1.Form.input({value:smartAlias.fetchSettings("minPostsWarning"),width:1,pattern:"\\d+"},(data,input)=>{input.get()[0].checkValidity()&&smartAlias.pushSettings("minPostsWarning",data)}),Form_1.Form.spacer(3),Form_1.Form.subheader("Cache Post Minimum","Tags with this amount of posts will be cached to speed up lookups",2),Form_1.Form.input({value:smartAlias.fetchSettings("minCachedTags"),width:1,pattern:"\\d{2,}"},(data,input)=>{input.get()[0].checkValidity()&&smartAlias.pushSettings("minCachedTags",data)}),Form_1.Form.hr(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("compactOutput"),label:"<b>Compact Display</b><br />Limit the tag information section to a set height",width:3},async data=>{await smartAlias.pushSettings("compactOutput",data),smartAlias.setCompactOutput(data)})]),Form_1.Form.accordionTab({name:"aliasref",label:"Validated Inputs",columns:3,width:3},[Form_1.Form.checkbox({value:smartAlias.fetchSettings("quickTagsForm"),label:"<b>Quick Tags</b><br />SmartAlias validation on the search page editing mode form",width:3},async data=>{await smartAlias.pushSettings("quickTagsForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("editTagsForm"),label:"<b>Post Editing</b><br />SmartAlias validation on the individual post editing form",width:3},async data=>{await smartAlias.pushSettings("editTagsForm",data),await smartAlias.reload()}),Form_1.Form.hr(3),Form_1.Form.header("Upload Page"),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadCharactersForm"),label:"<b>Artist Tags</b>",width:3},async data=>{await smartAlias.pushSettings("uploadCharactersForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadSexesForm"),label:"<b>Characters</b>",width:3},async data=>{await smartAlias.pushSettings("uploadSexesForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadBodyTypesForm"),label:"<b>Species</b>",width:3},async data=>{await smartAlias.pushSettings("uploadBodyTypesForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadThemesForm"),label:"<b>Themes</b>",width:3},async data=>{await smartAlias.pushSettings("uploadThemesForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadTagsForm"),label:"<b>Other Tags</b>",width:3},async data=>{await smartAlias.pushSettings("uploadTagsForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3)]),Form_1.Form.accordionTab({name:"aliasdef",label:"Alias Definitions",columns:3,width:3},[Form_1.Form.div({value:aliasContainer,width:3}),Form_1.Form.button({value:"Save"},async()=>{const confirmBox=$("span#defs-confirm").html("Saving . . .");await smartAlias.pushSettings("data",$("#alias-list-container").val().toString().trim()),confirmBox.html("Settings Saved"),window.setTimeout(()=>{confirmBox.html("")},1e3)}),Form_1.Form.div({value:'<span id="defs-confirm"></span>'}),Form_1.Form.div({value:'<div class="float-right">[ <a href="https://github.com/re621/re621/wiki/SmartAlias">syntax help</a> ]</div>'})])])])}createHotkeysTab(){const postViewer=ModuleController_1.ModuleController.get(PostViewer_1.PostViewer),poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator_1.PoolNavigator),imageScaler=ModuleController_1.ModuleController.get(ImageScaler_1.ImageScaler),miscellaneous=ModuleController_1.ModuleController.get(Miscellaneous_1.Miscellaneous),headerCustomizer=ModuleController_1.ModuleController.get(HeaderCustomizer_1.HeaderCustomizer),subscriptionManager=ModuleController_1.ModuleController.get(SubscriptionManager_1.SubscriptionManager),searchUtilities=ModuleController_1.ModuleController.get(SearchUtilities_1.SearchUtilities);function createInputs(module,label,settingsKey){const values=module.fetchSettings(settingsKey).split("|"),bindings=[void 0===values[0]?"":values[0],void 0===values[1]?"":values[1]];return[Form_1.Form.div({value:label}),Form_1.Form.key({value:bindings[0]},async data=>{await handleRebinding(data,0)}),Form_1.Form.key({value:bindings[1]},async data=>{await handleRebinding(data,1)})];async function handleRebinding(data,index){bindings[index]=data,await module.pushSettings(settingsKey,bindings.join("|")),await module.resetHotkeys()}}function createCustomInputs(module,label,dataLabel,settingsKey,pattern){const values=module.fetchSettings(settingsKey).split("|"),dataVal=module.fetchSettings(settingsKey+"_data"),bindings=[void 0===values[0]?"":values[0],void 0===values[1]?"":values[1]];return[Form_1.Form.div({value:label}),Form_1.Form.key({value:bindings[0]},async data=>{await async function(data,index){bindings[index]=data,await module.pushSettings(settingsKey,bindings.join("|")),await module.resetHotkeys()}(data,0)}),Form_1.Form.input({value:dataVal,label:dataLabel,pattern:pattern},async(data,input)=>{input.get()[0].checkValidity()&&await module.pushSettings(settingsKey+"_data",data)})]}return new Form_1.Form({name:"opthotkeys",columns:3,width:3},[Form_1.Form.header("Listing",3),...createInputs(searchUtilities,"Search","hotkeyFocusSearch"),...createInputs(searchUtilities,"Random Post","hotkeyRandomPost"),Form_1.Form.hr(3),Form_1.Form.header("Posts",3),...createInputs(postViewer,"Upvote Post","hotkeyUpvoteNU"),...createInputs(postViewer,"Toggle Upvote","hotkeyUpvote"),...createInputs(postViewer,"Downvote Post","hotkeyDownvoteNU"),...createInputs(postViewer,"Toggle Downvote","hotkeyDownvote"),...createInputs(postViewer,"Toggle Favorite","hotkeyFavorite"),...createInputs(postViewer,"Add to Favorites","hotkeyAddFavorite"),...createInputs(postViewer,"Remove From Favorites","hotkeyRemoveFavorite"),...createInputs(imageScaler,"Fullscreen Mode","hotkeyFullscreen"),Form_1.Form.spacer(3,!0),...createInputs(poolNavigator,"Previous Post","hotkeyPrev"),...createInputs(poolNavigator,"Next Post","hotkeyNext"),...createInputs(poolNavigator,"Cycle Navigation","hotkeyCycle"),...createInputs(imageScaler,"Change Scale","hotkeyScale"),Form_1.Form.spacer(3,!0),...createInputs(postViewer,"Open `Add to Set` Dialog","hotkeyAddSet"),...createInputs(postViewer,"Open `Add to Pool` Dialog","hotkeyAddPool"),...createInputs(postViewer,"Toggle Current Set","hotkeyToggleSetLatest"),...createInputs(postViewer,"Add to Current Set","hotkeyAddSetLatest"),...createInputs(postViewer,"Remove from Current Set","hotkeyRemoveSetLatest"),Form_1.Form.spacer(3,!0),...createCustomInputs(postViewer,"Add to Set","Set ID","hotkeyAddSetCustom1","\\d+"),...createCustomInputs(postViewer,"Add to Set","Set ID","hotkeyAddSetCustom2","\\d+"),...createCustomInputs(postViewer,"Add to Set","Set ID","hotkeyAddSetCustom3","\\d+"),Form_1.Form.hr(3),Form_1.Form.header("Actions",3),...createInputs(miscellaneous,"New Comment","hotkeyNewComment"),...createInputs(miscellaneous,"Edit Post","hotkeyEditPost"),...createInputs(postViewer,"Toggle Notes","hotkeyHideNotes"),...createInputs(postViewer,"Edit Notes","hotkeyNewNote"),...createInputs(miscellaneous,"Toggle Blacklist","hotkeyToggleBlacklist"),Form_1.Form.hr(3),Form_1.Form.header("Search Modes",3),...createInputs(searchUtilities,"View","hotkeySwitchModeView"),...createInputs(searchUtilities,"Edit","hotkeySwitchModeEdit"),...createInputs(searchUtilities,"Add Favorite","hotkeySwitchModeAddFav"),...createInputs(searchUtilities,"Remove Favorite","hotkeySwitchModeRemFav"),...createInputs(searchUtilities,"Add to Set","hotkeySwitchModeAddSet"),...createInputs(searchUtilities,"Remove from Set","hotkeySwitchModeRemSet"),Form_1.Form.hr(3),Form_1.Form.header("Header Tabs",3),...createInputs(headerCustomizer,"Tab #1","hotkeyTab1"),...createInputs(headerCustomizer,"Tab #2","hotkeyTab2"),...createInputs(headerCustomizer,"Tab #3","hotkeyTab3"),...createInputs(headerCustomizer,"Tab #4","hotkeyTab4"),...createInputs(headerCustomizer,"Tab #5","hotkeyTab5"),...createInputs(headerCustomizer,"Tab #6","hotkeyTab6"),...createInputs(headerCustomizer,"Tab #7","hotkeyTab7"),...createInputs(headerCustomizer,"Tab #8","hotkeyTab8"),...createInputs(headerCustomizer,"Tab #9","hotkeyTab9"),...createInputs(this,"Open Settings","hotkeyOpenSettings"),...createInputs(subscriptionManager,"Open Notifications","hotkeyOpenNotifications")])}createFeaturesTab(){const modules=ModuleController_1.ModuleController.getAll();function createInput(moduleName,label,description){const module=modules.get(moduleName);return[Form_1.Form.checkbox({name:moduleName+"-enabled",value:module.fetchSettings("enabled"),label:`<b>${label}</b><br />${description}`,width:3},data=>{module.pushSettings("enabled",data),module.setEnabled(data),!0===data?module.canInitialize()&&module.create():module.destroy()}),Form_1.Form.spacer(3)]}return new Form_1.Form({name:"settings-modules",columns:3,width:3},[Form_1.Form.header("Features",3),...createInput("BetterSearch","Improved Thumbnails","Massively overhauled thumbnail system. Many features will not work with this module disabled."),...createInput("HeaderCustomizer","Header Customizer","Add, delete, and customize header links to your heart's content."),...createInput("InstantSearch","Instant Filters","Quickly add filters to your current search."),...createInput("FormattingManager","Formatting Helper","Fully customizable toolbar for easy DText formatting."),...createInput("SmartAlias","Smart Alias","A more intelligent way to quickly fill out post tags.")])}createMiscTab(){const modules=ModuleController_1.ModuleController.getAll(),moduleSelector={none:"------"};modules.forEach(module=>{moduleSelector[module.getSettingsTag()]=module.getSettingsTag()});let selectedModule="none",dnpcacheUpdated=!0;return new Form_1.Form({name:"optmisc",columns:3,width:3},[Form_1.Form.header("Miscellaneous",3),Form_1.Form.accordion({name:"misccollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"cache",label:"Cache",columns:3,width:3},[Form_1.Form.section({name:"tagcache",columns:3,width:3},[Form_1.Form.div({value:"<b>Tag Cache</b><br />Used to speed up SmartAlias tag checking",width:2}),Form_1.Form.button({name:"reset",value:"Clear"},async(data,input)=>{TagCache_1.TagCache.clear(),input.html("Done!"),window.setTimeout(()=>{input.html("Clear")},1e3)})]),Form_1.Form.spacer(3),Form_1.Form.section({name:"dnpcache",columns:3,width:3},[Form_1.Form.div({value:"<b>Avoid Posting Cache</b><br />Used to validate the artist tags against the DNP list",width:2}),Form_1.Form.button({name:"reset",value:"Reset"},async(data,input)=>{input.prop("disabled","true"),await AvoidPosting_1.AvoidPosting.update($("#dnpcache-status")),input.prop("disabled","false"),dnpcacheUpdated||(dnpcacheUpdated=!1,this.pushNotificationsCount("util",-1))}),Form_1.Form.div({value:async element=>{const $status=$("<div>").attr("id","dnpcache-status").html('<i class="fas fa-circle-notch fa-spin"></i> Initializing . . .').appendTo(element);0==AvoidPosting_1.AvoidPosting.getUpdateTime()&&await AvoidPosting_1.AvoidPosting.update(),0==AvoidPosting_1.AvoidPosting.size()?($status.html('\n <i class="far fa-times-circle"></i> \n <span style="color:gold">Reset required</span>: Cache integrity failure\n '),this.pushNotificationsCount("util",1),dnpcacheUpdated=!0):$status.html('<i class="far fa-check-circle"></i> Cache integrity verified')},width:2}),Form_1.Form.div({value:element=>{const lastUpdate=AvoidPosting_1.AvoidPosting.getUpdateTime();lastUpdate?element.html(Util_1.Util.Time.format(lastUpdate)):element.html("")},wrapper:"text-center input-disabled"})])]),Form_1.Form.accordionTab({name:"export",label:"Import / Export",columns:3,width:3},[Form_1.Form.section({name:"file",columns:3,width:3},[Form_1.Form.header("Import / Export from file"),Form_1.Form.div({value:'<div class="notice float-right">Import subscription data from file</div>',width:2}),Form_1.Form.text("Export to File"),Form_1.Form.button({value:"Export",width:2},()=>{!function(){const promises=[];ModuleController_1.ModuleController.getAll().forEach(module=>{promises.push(module.getSavedSettings())}),Promise.all(promises).then(response=>{Debug_1.Debug.log(response);const storedData={meta:"re621/1.0"};response.forEach(data=>{storedData[data.name]=data.data,storedData[data.name].cache&&(storedData[data.name].cache={})}),Util_1.Util.downloadAsJSON(storedData,"re621-"+User_1.User.getUsername()+"-userdata")})}()}),Form_1.Form.text("Import from File"),Form_1.Form.file({accept:"json",width:2},data=>{!function(data){if(!data)return;const $info=$("#file-import-status").html("Loading . . ."),reader=new FileReader;reader.readAsText(data[0],"UTF-8"),reader.onload=function(event){const parsedData=JSON.parse(event.target.result.toString());parsedData.meta&&"re621/1.0"===parsedData.meta?(delete parsedData.meta,Object.keys(parsedData).forEach(key=>{$info.html("Importing "+key),XM_1.XM.Storage.setValue(key,parsedData[key])}),$info.html("Settings imported!")):$info.html("Invalid file format")},reader.onerror=function(){$info.html("Error loading file")}}(data)}),Form_1.Form.spacer(),Form_1.Form.div({value:'<div id="file-import-status" class="unmargin"></div>',label:" ",width:3})]),Form_1.Form.section({name:"esix",columns:3,width:3,wrapper:Debug_1.Debug.getState("enabled")?void 0:"display-none"},[Form_1.Form.header("eSix Extended"),Form_1.Form.div({value:'<div class="notice float-right">Import the settings from eSix Extended (Legacy)</div>',width:2}),Form_1.Form.text("Select File"),Form_1.Form.file({accept:"json",width:2},data=>{!function(data){if(!data)return;const $info=$("#file-esix-status").html("Loading . . ."),reader=new FileReader;reader.readAsText(data,"UTF-8"),reader.onload=async event=>{const parsedData=event.target.result.toString().split("\n");"eSixExtend User Prefs"===parsedData[0]?(parsedData.forEach((value,index)=>{0!==index&&(parsedData[index]=JSON.parse(atob(value).replace(/^\d+\|/,"")))}),await async function(settings,$info){$info.html("Processing pools . . .");const poolSubs=PoolTracker_1.PoolTracker.getInstance(),poolData=poolSubs.fetchSettings("data");for(const entry of settings)poolData[entry.id]={md5:entry.thumb.url.substr(6,32),lastID:entry.last};poolSubs.pushSettings("data",poolData)}(parsedData[2],$info),await async function(settings,$info){$info.html("Processing forums . . .");const forumSubs=ForumTracker_1.ForumTracker.getInstance(),forumData=forumSubs.fetchSettings("data"),postIDs=[];for(const entry of settings)postIDs.push(entry.id);(await E621_1.E621.ForumPosts.get({"search[id]":postIDs.join(",")})).forEach(postData=>{forumData[postData.topic_id]={}}),forumSubs.pushSettings("data",forumData)}(parsedData[3],$info),$info.html("Settings imported!")):$info.html("Invalid file format")},reader.onerror=function(){$info.html("Error loading file")}}(data)}),Form_1.Form.spacer(),Form_1.Form.div({value:'<div id="file-esix-status" class="unmargin"></div>',label:" ",width:3}),Form_1.Form.text("From LocalStorage"),Form_1.Form.button({value:"Load",width:2},()=>{!async function(){const $info=$("#localstorage-esix-status").html("Loading . . .");null!==localStorage.getItem("poolSubscriptions")&&await this.importPoolData(JSON.parse(localStorage.getItem("poolSubscriptions")),$info);null!==localStorage.getItem("forumSubscriptions")&&await this.importForumData(JSON.parse(localStorage.getItem("forumSubscriptions")),$info);$info.html("Settings imported!")}()}),Form_1.Form.spacer(),Form_1.Form.div({value:'<div id="localstorage-esix-status" class="unmargin"></div>',label:" ",width:3})])]),Form_1.Form.accordionTab({name:"reset",label:"Reset Modules",columns:3,width:3},[Form_1.Form.text("<b>Everything</b><br />Delete settings for all modules. <b>This cannot be undone.</b>",2),Form_1.Form.button({value:"Clear"},()=>{confirm("Are you absolutely sure?")&&(ModuleController_1.ModuleController.getAll().forEach(module=>{module.clearSettings()}),location.reload())}),Form_1.Form.spacer(3),Form_1.Form.text("<b>Module</b><br />Reset a specific module",2),Form_1.Form.select({value:selectedModule},moduleSelector,data=>{selectedModule=data}),Form_1.Form.text('<div class="text-bold">Requires a page reload</div>',2),Form_1.Form.button({value:"Reset"},()=>{"none"!==selectedModule&&ModuleController_1.ModuleController.get(selectedModule).clearSettings()}),Form_1.Form.spacer(3)]),Form_1.Form.accordionTab({name:"debug",label:"Debugging Tools",columns:3,width:3},[Form_1.Form.checkbox({value:Debug_1.Debug.getState("enabled"),label:"<b>Debug Mode</b><br />Enable debug messages in the console log",width:3},data=>{Debug_1.Debug.setState("enabled",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:Debug_1.Debug.getState("connect"),label:"<b>Connections Log</b><br />Logs all outbound connections in the console",width:3},data=>{Debug_1.Debug.setState("connect",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:Debug_1.Debug.getState("perform"),label:"<b>Performance Metrics</b><br />Write script performance analysis into the console log",width:3},data=>{Debug_1.Debug.setState("perform",data)}),Form_1.Form.spacer(3)])])])}createAboutTab(){return VersionChecker_1.VersionChecker.hasUpdate&&this.pushNotificationsCount("about",1),new Form_1.Form({name:"optabout",columns:3,width:3},[Form_1.Form.div({value:`<h3 class="display-inline"><a href="${window.re621.links.website}" target="_blank">${window.re621.name} v.${VersionChecker_1.VersionChecker.scriptBuild}</a></h3> <span class="display-inline">build ${window.re621.build}:${Patcher_1.Patcher.version}</span>`,width:2}),Form_1.Form.div({value:`<span class="float-right" id="project-update-button" data-available="${VersionChecker_1.VersionChecker.hasUpdate}">\n <a href="${window.re621.links.releases}" target="_blank">Update Available</a>\n </span>`}),Form_1.Form.div({value:`<b>${window.re621.name}</b> is a comprehensive set of tools designed to enhance the website for both casual and power users. It is created and maintained by unpaid volunteers, with the hope that it will be useful for the community.`,width:3}),Form_1.Form.div({value:`Keeping the script - and the website - fully functional is our highest priority. If you are experiencing bugs or issues, do not hesitate to create a new ticket on <a href="${window.re621.links.issues}">github</a>, or leave us a message in the <a href="${window.re621.links.forum}">forum thread</a>. Feature requests, comments, and overall feedback are also appreciated.`,width:3}),Form_1.Form.div({value:"Thank you for downloading and using this script. We hope that you enjoy the experience.",width:3}),Form_1.Form.spacer(3),Form_1.Form.header(`<a href="${window.re621.links.releases}" target="_blank" class="unmargin">What's new?</a>`,3),Form_1.Form.div({value:`<div id="changelog-list"><h5>Version ${VersionChecker_1.VersionChecker.latestBuild}</h5>${VersionChecker_1.VersionChecker.changesHTML}</div>`,width:3})])}openSettings(){$("a#header-button-settings")[0].click()}}exports.SettingsController=SettingsController},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":6,"../../components/cache/AvoidPosting":12,"../../components/cache/TagCache":13,"../../components/data/User":18,"../../components/structure/DomUtilities":25,"../../components/structure/Form":26,"../../components/structure/Modal":27,"../../components/structure/Tabbed":29,"../../components/utility/Debug":30,"../../components/utility/Patcher":32,"../../components/utility/Util":33,"../../components/utility/VersionChecker":37,"../downloader/FavDownloader":39,"../downloader/MassDownloader":40,"../downloader/PoolDownloader":41,"../misc/SmartAlias":47,"../misc/UploadUtilities":48,"../post/DownloadCustomizer":50,"../post/ImageScaler":51,"../post/PoolNavigator":52,"../post/PostViewer":53,"../post/TitleCustomizer":54,"../search/BetterSearch":55,"../search/CustomFlagger":57,"../search/HoverZoom":58,"../search/SearchUtilities":61,"../subscriptions/ForumTracker":64,"../subscriptions/PoolTracker":65,"../subscriptions/SubscriptionManager":66,"./HeaderCustomizer":43,"./Miscellaneous":44}],46:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ThemeCustomizer=void 0;const RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal");class ThemeCustomizer extends RE6Module_1.RE6Module{getDefaultSettings(){return{enabled:!0}}create(){super.create();const openCustomizerButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-theme",name:'<i class="fas fa-paint-brush"></i>',title:"Change Theme"}),form=new Form_1.Form({name:"theme-customizer"},[Form_1.Form.select({label:"Theme",value:window.localStorage.getItem("theme")||"hexagon"},{hexagon:"Hexagon",pony:"Pony",bloodlust:"Bloodlust",serpent:"Serpent",hotdog:"Hotdog"},data=>{window.localStorage.setItem("theme",data),$("body").attr("data-th-main",data)}),Form_1.Form.select({label:"Extras",value:window.localStorage.getItem("theme-extra")||"hexagons"},{none:"None",autumn:"Autumn",winter:"Winter",spring:"Spring",aurora:"Aurora",hexagons:"Hexagons",space:"Space",stars:"Stars"},data=>{window.localStorage.setItem("theme-extra",data),$("body").attr("data-th-extra",data)}),Form_1.Form.select({label:"Post Navbar",value:window.localStorage.getItem("theme-nav")||"top"},{top:"Top",bottom:"Bottom",none:"None"},data=>{window.localStorage.setItem("theme-nav",data),$("body").attr("data-th-nav",data)})]);new Modal_1.Modal({title:"Themes",triggers:[{element:openCustomizerButton}],content:Form_1.Form.placeholder(),structure:form,position:{my:"right top",at:"right top"}})}}exports.ThemeCustomizer=ThemeCustomizer},{"../../components/RE6Module":2,"../../components/structure/DomUtilities":25,"../../components/structure/Form":26,"../../components/structure/Modal":27}],47:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SmartAlias=void 0;const E621_1=require("../../components/api/E621"),AvoidPosting_1=require("../../components/cache/AvoidPosting"),TagCache_1=require("../../components/cache/TagCache"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util");class SmartAlias extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.upload,Page_1.PageDefintion.post,Page_1.PageDefintion.search,Page_1.PageDefintion.favorites],!0)}getDefaultSettings(){return{enabled:!0,autoLoad:!0,tagOrder:TagOrder.Default,quickTagsForm:!0,editTagsForm:!0,uploadCharactersForm:!0,uploadSexesForm:!0,uploadBodyTypesForm:!0,uploadThemesForm:!0,uploadTagsForm:!0,replaceAliasedTags:!0,fixCommonTypos:!1,minPostsWarning:20,compactOutput:!1,minCachedTags:1e3,data:""}}async prepare(){await super.prepare(),Page_1.Page.matches(Page_1.PageDefintion.post)&&($("#post_tag_string").is(":visible")||(SmartAlias.postPageLockout=!0,$("body").one("click.re621","#post-edit-link",()=>{SmartAlias.postPageLockout=!1,this.reload()})))}async reload(){return this.destroy(),new Promise(resolve=>{setTimeout(()=>{this.create(),resolve()},100)})}destroy(){if(this.isInitialized()){super.destroy();for(const inputElement of $("#post_tags, #post_tag_string").get())$(inputElement).off("focus.re621.smart-alias").off("focusout.re621.smart-alias");$("smart-alias").remove(),$("smart-tag-counter").remove(),$("button.smart-alias-validate").remove()}}create(){if(super.create(),!this.fetchSettings("quickTagsForm")&&Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites]))return;if(!this.fetchSettings("editTagsForm")&&Page_1.Page.matches(Page_1.PageDefintion.post))return;if(this.setCompactOutput(this.fetchSettings("compactOutput")),SmartAlias.postPageLockout)return;if(void 0===SmartAlias.aliasCache){const cacheData=this.fetchSettings("data");SmartAlias.aliasCache=SmartAlias.getAliasData(cacheData),SmartAlias.aliasCacheLength=cacheData.length}$(".the_secret_switch").one("click",()=>{this.reload()});const inputs=new Set(Array.from(SmartAlias.inputSelector)),enabledInputs=this.fetchSettings(["uploadCharactersForm","uploadSexesForm","uploadBodyTypesForm","uploadThemesForm","uploadTagsForm"]);enabledInputs.uploadCharactersForm||inputs.delete("#post_characters"),enabledInputs.uploadSexesForm||inputs.delete("#post_sexes"),enabledInputs.uploadBodyTypesForm||inputs.delete("#post_bodyTypes"),enabledInputs.uploadThemesForm||inputs.delete("#post_themes"),enabledInputs.uploadTagsForm||inputs.delete("#post_tags");const mode=this.fetchSettings("autoLoad");for(const inputElement of $([...inputs].join(", ")).get()){const $textarea=$(inputElement),$container=$("<smart-alias>").attr("ready","true").insertAfter($textarea),$counter=$("<smart-tag-counter>").insertAfter($textarea);let updateTimeout;mode?this.manageAutoLoad($textarea,$container):this.manageManualLoad($textarea,$container),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites])&&$("article.post-preview").on("click.danbooru",()=>{mode?this.handleTagInput($textarea,$container,!1):$container.html("")}),$textarea.on("input",()=>{updateTimeout||(updateTimeout=window.setTimeout(()=>{updateTimeout=0},500),$counter.html(SmartAlias.getInputTags($textarea).length+""))})}}static getInputString(input){return input.val().toString().trim().toLowerCase().replace(/\r?\n|\r/g," ").replace(/(?:\s){2,}/g," ")}static getInputTags(input){return("string"==typeof input?input:SmartAlias.getInputString(input)).split(" ").filter(el=>null!=el&&""!=el)}manageAutoLoad($textarea,$container){let typingTimeout;$textarea.on("input",()=>{"true"!==$textarea.data("vue-event")?(window.clearInterval(typingTimeout),typingTimeout=window.setInterval(()=>{"true"===$container.attr("ready")&&(window.clearInterval(typingTimeout),this.handleTagInput($textarea,$container))},1e3)):$textarea.data("vue-event","false")}),$textarea.on("re621:input",()=>{this.handleTagInput($textarea,$container)}),this.handleTagInput($textarea,$container,!1)}manageManualLoad($textarea,$container){$("<button>").html("Validate").addClass("smart-alias-validate").insertBefore($container).on("click",()=>{this.handleTagInput($textarea,$container,!1)})}async handleTagInput($textarea,$container,scrollToBottom=!0){if("true"!==$container.attr("ready"))return;$container.attr("ready","false"),AvoidPosting_1.AvoidPosting.isUpdateRequired()&&await AvoidPosting_1.AvoidPosting.update();const inputString=SmartAlias.getInputString($textarea);let tags=SmartAlias.getInputTags(inputString);if(0==tags.length)return $container.html(""),void $container.attr("ready","true");const minPostsWarning=this.fetchSettings("minPostsWarning"),tagOrder=this.fetchSettings("tagOrder"),aliasCacheRaw=await this.fetchSettings("data",!0);aliasCacheRaw.length!==SmartAlias.aliasCacheLength&&(SmartAlias.aliasCache=SmartAlias.getAliasData(aliasCacheRaw),SmartAlias.aliasCacheLength=aliasCacheRaw.length),SmartAlias.aliasCache.length>0&&($textarea.val((index,currentValue)=>{let changes=0,iterations=0;do{changes=0;for(const aliasDef of SmartAlias.aliasCache)currentValue=currentValue.replace(getTagRegex(aliasDef.lookup),(...args)=>{changes++;let output=aliasDef.output;for(let i=3;i<args.length-3;i++)output=output.replace(new RegExp("\\$"+(i-2),"gi"),args[i]);const result=new Set;for(const part of output.split(" "))getTagRegex(part).test(currentValue)||result.add(part);return 0==result.size?" ":args[1]+[...result].join(" ")+args[args.length-3]});iterations++}while(0!=changes&&iterations<SmartAlias.ITERATIONS_LIMIT);return currentValue}),triggerUpdateEvent($textarea),tags=SmartAlias.getInputTags($textarea));const lookup=new Set;for(const tagName of tags)void 0===SmartAlias.tagData[tagName]&&lookup.add(tagName);redrawContainerContents($container,tags,minPostsWarning,tagOrder,lookup);const invalidTags=new Set,ambiguousTags=new Set;for(const batch of Util_1.Util.chunkArray([...lookup].filter(value=>null==SmartAlias.tagAliases[value]),40))for(const result of await E621_1.E621.TagAliases.get({"search[antecedent_name]":batch,limit:1e3},500)){if("active"!==result.status)continue;const currentName=result.antecedent_name,trueName=result.consequent_name;"invalid_tag"!=trueName&&"invalid_color"!=trueName?trueName.endsWith("_(disambiguation)")?ambiguousTags.add(currentName):(lookup.delete(currentName),null==SmartAlias.tagData[trueName]&&lookup.add(trueName),SmartAlias.tagAliases[currentName]=trueName):invalidTags.add(currentName)}this.fetchSettings("replaceAliasedTags")&&($textarea.val((index,currentValue)=>{for(const[antecedent,consequent]of Object.entries(SmartAlias.tagAliases))currentValue=currentValue.replace(getTagRegex(antecedent),"$1"+consequent+"$3");return currentValue}),triggerUpdateEvent($textarea),tags=SmartAlias.getInputTags($textarea)),TagCache_1.TagCache.load();for(const tag of lookup){const data=TagCache_1.TagCache.get(tag);null!=data&&(SmartAlias.tagData[tag]={count:data.count,category:data.category,ambiguous:!1,invalid:!1,dnp:AvoidPosting_1.AvoidPosting.has(tag),cached:!0},lookup.delete(tag))}if(lookup.size>0){for(const batch of Util_1.Util.chunkArray(lookup,100))for(const result of await E621_1.E621.Tags.get({search:{name:batch.join(","),hide_empty:!1},limit:100},500))SmartAlias.tagData[result.name]={count:result.post_count,category:result.category,ambiguous:ambiguousTags.has(result.name),invalid:invalidTags.has(result.name),dnp:AvoidPosting_1.AvoidPosting.has(result.name),cached:!1},lookup.delete(result.name);for(const tagName of lookup)SmartAlias.tagData[tagName]={count:-1,category:-1,ambiguous:!1,invalid:!0,dnp:AvoidPosting_1.AvoidPosting.has(tagName),cached:!1}}const minCachedTags=this.fetchSettings("minCachedTags");if(minCachedTags>0){for(const[name,data]of Object.entries(SmartAlias.tagData))TagCache_1.TagCache.has(name)||data.count<minCachedTags||TagCache_1.TagCache.add(name,data.count,data.category);TagCache_1.TagCache.save()}function triggerUpdateEvent($textarea){const e=document.createEvent("HTMLEvents");e.initEvent("input",!0,!0),$textarea.data("vue-event","true"),$textarea[0].dispatchEvent(e)}function getTagRegex(input){input="string"==typeof input?[input]:[...input];for(let i=0;i<input.length;i++)input[i]=input[i].replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"(\\S*)");return new RegExp("(^|\n| )("+input.join("|")+")( |\n|$)","gi")}function redrawContainerContents($container,tags,minPostsWarning,tagOrder,loading=new Set){$container.html("").toggleClass("grouped",tagOrder==TagOrder.Grouped),tagOrder!==TagOrder.Default&&(tags=tags.sort());for(let tagName of tags){let displayName=tagName;null!=SmartAlias.tagAliases[tagName]&&(tagName=SmartAlias.tagAliases[tagName]);const data=SmartAlias.tagData[tagName],isLoading=loading.has(tagName);if(null==data&&!isLoading)continue;let symbol,color,text,title;isLoading?(symbol="loading",color="success",text=""):data.dnp?(symbol="error",color="error",text="avoid posting"):Util_1.Util.getArrayIndexes(tags,tagName).length>1?(symbol="info",color="info",text="duplicate"):data.invalid?(symbol="error",color="error",text="invalid"):data.ambiguous||tagName.endsWith("_(disambiguation)")?(symbol="info",color="warning",text="ambiguous",displayName=displayName.replace("_(disambiguation)","")):0==data.count?(symbol="error",color="error",text="empty"):data.count<minPostsWarning?(symbol="error",color="error",text=data.count+""):(symbol="success",color="success",text=data.cached?"~"+Util_1.Util.formatK(data.count):data.count+"",title=data.cached?"cached value":void 0),displayName=displayName.replace(/_/g,"_​"),$("<smart-tag>").addClass(isLoading?"":"category-"+data.category).attr({name:tagName,symbol:symbol,color:color,title:title}).html(`<a href="/wiki_pages/show_or_new?title=${tagName}" target="_blank">${displayName}</a> ${text}`).appendTo($container)}}redrawContainerContents($container,tags,minPostsWarning,tagOrder),scrollToBottom&&$container.scrollTop($container[0].scrollHeight-$container[0].clientHeight),$container.attr("ready","true")}static getAliasData(rawData){const data=rawData.split("\n").reverse(),result=[],aliasList=new Set;for(const line of data){const parts=line.split("#")[0].trim().split("->");if(2!==parts.length)continue;const def={lookup:new Set,output:(input=parts[1],input.trim().replace(/\s{2,}/g," "))};for(const part of formatLookup(parts[0]))aliasList.has(part)||(aliasList.add(part),def.lookup.add(part));0!=def.lookup.size&&result.push(def)}var input;return result;function formatLookup(input){return new Set(input.split(" ").filter(e=>""!=e))}}setCompactOutput(state=!1){$("#page").attr("data-smartalias-compact",state+"")}}var TagOrder;exports.SmartAlias=SmartAlias,SmartAlias.ITERATIONS_LIMIT=10,SmartAlias.inputSelector=new Set(["#post_tag_string","#re621_qedit_tags","#post_characters","#post_sexes","#post_bodyTypes","#post_themes","#post_tags"]),SmartAlias.tagData={},SmartAlias.tagAliases={},SmartAlias.postPageLockout=!1,function(TagOrder){TagOrder.Default="default",TagOrder.Alphabetical="alphabetical",TagOrder.Grouped="grouped"}(TagOrder||(TagOrder={})),function(TagOrder){TagOrder.fromString=function(input){for(const value of Object.values(TagOrder))if(value==input)return value;return TagOrder.Default}}(TagOrder||(TagOrder={}))},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/cache/AvoidPosting":12,"../../components/cache/TagCache":13,"../../components/data/Page":16,"../../components/utility/Util":33}],48:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UploadUtilities=void 0;const E621_1=require("../../components/api/E621"),XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util");class UploadUtilities extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.upload],!0)}getDefaultSettings(){return{enabled:!0,checkDuplicates:!0,addSourceLinks:!0}}create(){super.create(),this.fetchSettings("checkDuplicates")&&this.handleDuplicateCheck(),this.fetchSettings("addSourceLinks")&&this.handleSourceEnhancements()}static findSection(label,id){return $("label[for="+label+"]").parent().parent().attr("id",id)}handleDuplicateCheck(){const fileContainer=UploadUtilities.findSection("post_file","section-file").find("div.col2").first().attr("id","file-container"),dupesContainer=$("<div>").attr("id","dupes-container").appendTo(fileContainer),risContainer=$("<div>").attr("id","ris-container").html("").appendTo("div.upload_preview_container");let working=!1;function makePostThumbnail(entry){const postData=entry.post.posts,article=$("<div>"),link=$("<a>").attr({href:"/posts/"+postData.id,target:"_blank"}).appendTo(article);return $("<img>").attr({src:postData.is_deleted?"/images/deleted-preview.png":postData.preview_file_url,title:`${postData.image_width}x${postData.image_height} ${Util_1.Util.formatBytes(postData.file_size)} ${Math.round(entry.score)}% match\n${postData.tag_string_artist}\n${postData.tag_string_copyright}\n${postData.tag_string_character}\n${postData.tag_string_species}`}).appendTo(link),$("<loading>").css("--progress",Math.round(entry.score)+"%").appendTo(link),$("<span>").html(`${postData.image_width}x${postData.image_height} ${Util_1.Util.formatBytes(postData.file_size)}`).appendTo(article),article}$(fileContainer).on("input","input",event=>{if(working)return;const value=$(event.target).val()+"";return""==value?(dupesContainer.html(""),void risContainer.html("")):/^https?:\/\//.test(value)?(working=!0,dupesContainer.html('<span class="fullspan">Checking for duplicates . . .</span>'),E621_1.E621.IQDBQueries.get({url:value}).then(response=>{if(console.log(response),dupesContainer.html(""),0==response.length||void 0!==response[0]&&null==response[0].post_id)working=!1;else{$("<h3>").html(`<a href="/iqdb_queries?url=${encodeURI(value)}" target="_blank">Duplicates Found:</a> ${response.length}`).appendTo(dupesContainer);for(const entry of response)makePostThumbnail(entry).appendTo(dupesContainer);working=!1}},error=>{console.log(error),dupesContainer.html(`"<span class="fullspan error">IQDB server responded with: Internal Error ${error}</span>`),working=!1}),void risContainer.html(`\n <a href="/iqdb_queries?url=${encodeURI(value)}" target="_blank">e621</a>\n <a href="https://www.google.com/searchbyimage?image_url=${encodeURI(value)}" target="_blank">Google</a>\n <a href="https://saucenao.com/search.php?url=${encodeURI(value)}" target="_blank">SauceNAO</a>\n <a href="https://derpibooru.org/search/reverse?url=${encodeURI(value)}" target="_blank">Derpibooru</a>\n <a href="https://kheina.com/?url=${encodeURI(value)}" target="_blank">Kheina</a>\n `)):(dupesContainer.html('<span class="fullspan">Unable to parse image path. <a href="/iqdb_queries" target="_blank">Check manually</a>?</span>'),void risContainer.html(""))}),fileContainer.find("input[type=text").trigger("input")}handleSourceEnhancements(){const sourceContainer=UploadUtilities.findSection("post_sources","section-sources").find("div.col2").children("div").eq(1).attr("id","source-container");$(sourceContainer).on("input","input.upload-source-input",event=>{const $input=$(event.target),$parent=$input.parent();$parent.find("button.source-copy").remove(),$parent.find("button.source-link").remove(),""!=$input.val()&&($("<button>").addClass("source-copy").html("copy").appendTo($parent).on("click",()=>{XM_1.XM.Util.setClipboard($input.val())}),$("<button>").addClass("source-link").html("open").appendTo($parent).on("click",()=>{window.open($input.val()+"","_blank")}))}),$("input.upload-source-input").trigger("input")}}exports.UploadUtilities=UploadUtilities},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":6,"../../components/data/Page":16,"../../components/utility/Util":33}],49:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WikiEnhancer=void 0;const XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module");class WikiEnhancer extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.wiki,Page_1.PageDefintion.wikiNA,Page_1.PageDefintion.artist])}getDefaultSettings(){return{enabled:!0}}create(){super.create();const $title=Page_1.Page.matches(Page_1.PageDefintion.artist)?$("#a-show h1").first():$("#wiki-page-title"),tagName=$title.text().trim().replace(/^((Species|Character|Copyright|Artist|Lore|Meta): )/g,"").replace(/ /g,"_");$("<button>").attr("id","wiki-page-copy-tag").addClass("button btn-neutral border-highlight border-left").html('<i class="far fa-copy"></i>').appendTo($title).on("click",()=>{XM_1.XM.Util.setClipboard(tagName)})}destroy(){this.isInitialized()&&(super.destroy(),$("#wiki-page-copy-tag").remove())}}exports.WikiEnhancer=WikiEnhancer},{"../../components/RE6Module":2,"../../components/api/XM":6,"../../components/data/Page":16}],50:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DownloadCustomizer=void 0;const XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),PostParts_1=require("../../components/post/PostParts"),RE6Module_1=require("../../components/RE6Module");class DownloadCustomizer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0)}getDefaultSettings(){return{enabled:!0,template:"%postid%-%artist%-%copyright%-%character%"}}create(){super.create(),this.post=Post_1.Post.getViewingPost();const downloadContainer=$("<div>").attr("id","image-custdownload-links").appendTo("#image-extra-controls"),link=$("<a>").attr({id:"image-custdownload-file",href:this.post.file.original,download:this.parseTemplate()}).html("Download").addClass("button btn-neutral").appendTo(downloadContainer).on("click",event=>{event.preventDefault(),event.stopImmediatePropagation(),link.attr("loading","true"),XM_1.XM.Connect.download({url:link.attr("href"),name:link.attr("download"),onload:()=>{link.removeAttr("loading")}})}),tags=$("<a>").attr({id:"image-custdownload-tags",href:this.getTagsBlock(),download:this.parseTemplate("txt")}).html("Tags").addClass("button btn-neutral").appendTo(downloadContainer).on("click",()=>{tags.attr("loading","true"),tags.attr({loading:"false",href:this.getTagsBlock()})})}refreshDownloadLink(){$("#image-custdownload-file").attr("download",this.parseTemplate())}getTagsBlock(){return URL.createObjectURL(new Blob([PostParts_1.PostParts.formatHoverText(this.post)],{type:"text/plain"}))}parseTemplate(ext){return this.fetchSettings("template").replace(/%postid%/g,this.post.id).replace(/%artist%/g,tagSetToString(this.post.tags.real_artist)).replace(/%copyright%/g,tagSetToString(this.post.tags.copyright)).replace(/%species%/g,tagSetToString(this.post.tags.species)).replace(/%character%/g,tagSetToString(this.post.tags.character)).replace(/%meta%/g,tagSetToString(this.post.tags.meta)).replace(/%md5%/g,this.post.file.md5).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+(ext||this.post.file.ext);function tagSetToString(tags){return[...tags].join("-")}}}exports.DownloadCustomizer=DownloadCustomizer},{"../../components/RE6Module":2,"../../components/api/XM":6,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostParts":22}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageScaler=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module");class ImageScaler extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0),this.registerHotkeys({keys:"hotkeyScale",fnct:()=>{this.setScale()}},{keys:"hotkeyFullscreen",fnct:this.openFullscreen})}getDefaultSettings(){return{enabled:!0,hotkeyScale:"v|0",hotkeyFullscreen:"",clickScale:!0,size:ImageSize.Fill}}create(){super.create(),this.post=Post_1.Post.getViewingPost(),this.image=$("img#image");const resizeButtonContainer=$("#image-resize-cycle").empty();this.setImageSize(this.fetchSettings("size")),this.resizeSelector=$("<select>").html(`\n <option value="${ImageSize.Sample}">Sample</option>\n <option value="${ImageSize.Fill}">Fill Screen</option>\n <option value="${ImageSize.Fit}">Fit Horizontally</option>\n <option value="${ImageSize.Original}">Original</option>\n `).val(this.fetchSettings("size")).addClass("button btn-neutral").appendTo(resizeButtonContainer).change(async(event,save)=>{const size=$(event.target).val()+"";if(this.setImageSize(size),!1!==save)switch(await this.pushSettings("size",size),size){case ImageSize.Sample:await User_1.User.setSettings({default_image_size:"large"});break;case ImageSize.Fill:case ImageSize.Fit:await User_1.User.setSettings({default_image_size:"fit"});break;case ImageSize.Original:await User_1.User.setSettings({default_image_size:"original"})}}),$("#image-download-link a").html("Fullscreen"),this.image.click(async()=>{this.fetchSettings("clickScale")&&!await Danbooru_1.Danbooru.Note.TranslationMode.active()&&this.setScale("",!1)}),this.toggleClickScale(this.fetchSettings("clickScale"))}setScale(size="",save=!0){const selector=ModuleController_1.ModuleController.get(ImageScaler).resizeSelector;if(""===size){const $next=selector.find("option:selected").next();size=$next.length>0?$next.val()+"":selector.find("option").first().val()+""}selector.val(size).trigger("change",save)}setImageSize(size){switch(this.image.removeClass(),this.image.parent().addClass("loading"),this.image.on("load",()=>{Danbooru_1.Danbooru.Note.Box.scale_all(),this.image.parent().removeClass("loading")}),size){case ImageSize.Sample:this.image.attr("src",this.post.file.sample);break;case ImageSize.Fill:this.image.addClass("re621-fit-vertical"),this.image.attr("src")!==this.post.file.original?this.image.attr("src",this.post.file.original):this.image.parent().removeClass("loading");break;case ImageSize.Fit:this.image.addClass("re621-fit-horizontal"),this.image.attr("src")!==this.post.file.original?this.image.attr("src",this.post.file.original):this.image.parent().removeClass("loading");break;case ImageSize.Original:this.image.attr("src")!==this.post.file.original?this.image.attr("src",this.post.file.original):this.image.parent().removeClass("loading")}Danbooru_1.Danbooru.Note.Box.scale_all()}openFullscreen(){$("#image-download-link a")[0].click()}toggleClickScale(state=!0){$("#image-container").toggleClass("click-scale",state)}}var ImageSize;exports.ImageScaler=ImageScaler,function(ImageSize){ImageSize.Sample="sample",ImageSize.Fill="fit-vertical",ImageSize.Fit="fit-horizontal",ImageSize.Original="original"}(ImageSize||(ImageSize={}))},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Page":16,"../../components/data/User":18,"../../components/post/Post":19}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PoolNavigator=void 0;const Page_1=require("../../components/data/Page"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module");class PoolNavigator extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post),this.activeNav=0,this.navbars=[],this.registerHotkeys({keys:"hotkeyCycle",fnct:this.cycleNavbars},{keys:"hotkeyNext",fnct:this.triggerNextPost},{keys:"hotkeyPrev",fnct:this.triggerPrevPost})}getDefaultSettings(){return{enabled:!0,hotkeyCycle:"x|.",hotkeyPrev:"a|left",hotkeyNext:"d|right"}}create(){super.create(),this.buildDOM(),$("input[type='radio'].post-nav-switch").change(event=>{this.activeNav=parseInt($(event.target).val()+"")})}cycleNavbars(){const poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator),navbars=poolNavigator.navbars,active=poolNavigator.activeNav;0!=navbars.length&&(active+1>=navbars.length?navbars[0].checkbox.click():navbars[active+1].checkbox.click())}triggerNextPost(){const poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator),navbars=poolNavigator.navbars,active=poolNavigator.activeNav;if(0==navbars.length)return;const button=navbars[active].element.find("a.next").first()[0];void 0!==button&&button.click()}triggerPrevPost(){const poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator),navbars=poolNavigator.navbars,active=poolNavigator.activeNav;if(0==navbars.length)return;const button=navbars[active].element.find("a.prev").first()[0];void 0!==button&&button.click()}buildDOM(){$("#search-seq-nav").length&&this.navbars.push({type:"search",element:$("#search-seq-nav > ul > li").first(),checkbox:void 0});for(const element of $("#pool-nav").find("ul > li").get())this.navbars.push({type:"pool",element:$(element),checkbox:void 0});for(const element of $("#set-nav").find("ul > li").get())this.navbars.push({type:"set",element:$(element),checkbox:void 0});this.navbars.forEach((nav,index)=>{nav.element.addClass("post-nav");const $radioBox=$("<div>").addClass("post-nav-switch-box").prependTo(nav.element);$("<div>").addClass("post-nav-spacer").appendTo(nav.element),nav.checkbox=$("<input>").attr("type","radio").attr("id","post-nav-switch-"+index).attr("name","nav").val(index).addClass("post-nav-switch").appendTo($radioBox),index===this.activeNav&&nav.checkbox.attr("checked",""),$("<label>").attr("for","post-nav-switch-"+index).appendTo($radioBox)}),1==this.navbars.length&&this.navbars[0].checkbox.parent().addClass("vis-hidden"),$("#nav-links").find(".first").each((index,element)=>{$(element).html("«")}),$("#nav-links").find(".last").each((index,element)=>{$(element).html("»")})}}exports.PoolNavigator=PoolNavigator},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/data/Page":16}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostViewer=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Page_1=require("../../components/data/Page"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),PostActions_1=require("../../components/post/PostActions"),RE6Module_1=require("../../components/RE6Module");class PostViewer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0),this.registerHotkeys({keys:"hotkeyUpvote",fnct:this.triggerUpvote},{keys:"hotkeyUpvoteNU",fnct:this.triggerUpvoteNU},{keys:"hotkeyDownvote",fnct:this.triggerDownvote},{keys:"hotkeyDownvoteNU",fnct:this.triggerDownvoteNU},{keys:"hotkeyFavorite",fnct:this.toggleFavorite},{keys:"hotkeyAddFavorite",fnct:this.addFavorite},{keys:"hotkeyRemoveFavorite",fnct:this.removeFavorite},{keys:"hotkeyHideNotes",fnct:this.toggleNotes},{keys:"hotkeyNewNote",fnct:this.switchNewNote},{keys:"hotkeyAddSet",fnct:this.addSet},{keys:"hotkeyAddPool",fnct:this.addPool},{keys:"hotkeyToggleSetLatest",fnct:this.toggleSetLatest},{keys:"hotkeyAddSetLatest",fnct:this.addSetLatest},{keys:"hotkeyRemoveSetLatest",fnct:this.removeSetLatest},{keys:"hotkeyAddSetCustom1",fnct:()=>{this.addSetCustom("hotkeyAddSetCustom1_data")}},{keys:"hotkeyAddSetCustom2",fnct:()=>{this.addSetCustom("hotkeyAddSetCustom2_data")}},{keys:"hotkeyAddSetCustom3",fnct:()=>{this.addSetCustom("hotkeyAddSetCustom3_data")}})}getDefaultSettings(){return{enabled:!0,hotkeyUpvote:"w",hotkeyUpvoteNU:"",hotkeyDownvote:"s",hotkeyDownvoteNU:"",hotkeyFavorite:"f",hotkeyAddFavorite:"",hotkeyRemoveFavorite:"",hotkeyHideNotes:"o",hotkeyNewNote:"p",hotkeyAddSet:"",hotkeyAddPool:"",hotkeyToggleSetLatest:"",hotkeyAddSetLatest:"",hotkeyRemoveSetLatest:"",hotkeyAddSetCustom1:"",hotkeyAddSetCustom1_data:"0",hotkeyAddSetCustom2:"",hotkeyAddSetCustom2_data:"0",hotkeyAddSetCustom3:"",hotkeyAddSetCustom3_data:"0",upvoteOnFavorite:!0,hideNotes:!1,moveChildThumbs:!0,boldenTags:!0}}create(){super.create(),this.post=Post_1.Post.getViewingPost();const $addToContainer=$("<div>").attr("id","image-add-links").insertAfter("div#image-download-link");$("li#add-to-set-list > a").addClass("image-add-set").addClass("button btn-neutral").html("+ Set").appendTo($addToContainer),$("li#add-to-pool-list > a").addClass("image-add-pool").addClass("button btn-neutral").html("+ Pool").appendTo($addToContainer);const $noteToggleCountainer=$("<div>").attr("id","image-toggle-notes").insertAfter("div#image-add-links");$("<a>").attr({id:"image-note-button",href:"#"}).addClass("button btn-neutral").html(this.fetchSettings("hideNotes")?"Notes: Off":"Notes: On").appendTo($noteToggleCountainer).on("click",event=>{event.preventDefault(),this.toggleNotes()}),$("#note-container").css("display","").attr("data-hidden",this.fetchSettings("hideNotes")),this.fetchSettings("moveChildThumbs")&&$(".parent-children").addClass("children-moved").insertAfter($("#search-box")),this.toggleBoldenedTags(this.fetchSettings("boldenTags")),$("#add-fav-button, #add-to-favorites").on("click",()=>{this.fetchSettings("upvoteOnFavorite")&&Danbooru_1.Danbooru.Post.vote(this.post.id,1,!0)})}toggleBoldenedTags(state=!0){$("#tag-list").toggleClass("tags-boldened",state)}triggerUpvote(){Danbooru_1.Danbooru.Post.vote(Post_1.Post.getViewingPost().id,1)}triggerUpvoteNU(){const id=Post_1.Post.getViewingPost().id;PostActions_1.PostActions.vote(id,1,!0).then(response=>{response.success?($("span.post-vote-up-"+id).removeClass("score-neutral").addClass("score-positive"),$("span.post-vote-down-"+id).removeClass("score-negative").addClass("score-neutral"),$("span.post-score-"+id).removeClass("score-positive score-negative score-neutral").addClass(PostViewer.getScoreClass(response.score)).attr("title",response.up+" up / "+response.down+" down").html(response.score+""),response.score>0&&Danbooru_1.Danbooru.notice("Post Score Updated")):Danbooru_1.Danbooru.error("An error occurred while processing votes")})}triggerDownvote(){Danbooru_1.Danbooru.Post.vote(Post_1.Post.getViewingPost().id,-1)}triggerDownvoteNU(){const id=Post_1.Post.getViewingPost().id;PostActions_1.PostActions.vote(id,-1,!0).then(response=>{response.success?($("span.post-vote-down-"+id).addClass("score-negative").removeClass("score-neutral"),$("span.post-vote-up-"+id).removeClass("score-positive").addClass("score-neutral"),$("span.post-score-"+id).removeClass("score-positive score-negative score-neutral").addClass(PostViewer.getScoreClass(response.score)).attr("title",response.up+" up / "+response.down+" down").html(response.score+""),response.score<0&&Danbooru_1.Danbooru.notice("Post Score Updated")):Danbooru_1.Danbooru.error("An error occurred while processing votes")})}static getScoreClass(score){return score>0?"score-positive":score<0?"score-negative":"score-neutral"}toggleFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")?$("#add-fav-button")[0].click():$("#remove-fav-button")[0].click()}addFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")&&$("#add-fav-button")[0].click()}removeFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")||$("#remove-fav-button")[0].click()}async toggleNotes(){const module=ModuleController_1.ModuleController.get(PostViewer),hideNotes=module.fetchSettings("hideNotes");hideNotes?($("#note-container").attr("data-hidden","false"),$("a#image-note-button").html("Notes: ON")):($("#note-container").attr("data-hidden","true"),$("a#image-note-button").html("Notes: OFF")),await module.pushSettings("hideNotes",!hideNotes)}async switchNewNote(){$("#note-container").attr("data-hidden","false"),$("a#image-note-button").html("Notes: ON"),await ModuleController_1.ModuleController.get(PostViewer).pushSettings("hideNotes",!1),Danbooru_1.Danbooru.Note.TranslationMode.toggle()}addSet(){$("a#set")[0].click()}toggleSetLatest(){const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.toggleSet(lastSet,Post_1.Post.getViewingPost().id):Danbooru_1.Danbooru.error("Error: no set selected")}addSetLatest(){const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.addSet(lastSet,Post_1.Post.getViewingPost().id):Danbooru_1.Danbooru.error("Error: no set selected")}removeSetLatest(){const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.removeSet(lastSet,Post_1.Post.getViewingPost().id):Danbooru_1.Danbooru.error("Error: no set selected")}addSetCustom(dataKey){PostActions_1.PostActions.addSet(this.fetchSettings(dataKey),Post_1.Post.getViewingPost().id)}addPool(){$("a#pool")[0].click()}}exports.PostViewer=PostViewer},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostActions":20}],54:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TitleCustomizer=void 0;const Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module");class TitleCustomizer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0)}getDefaultSettings(){return{enabled:!0,template:"#%postid% by %artist% (%copyright%) - %character%",symbolsEnabled:!0,symbolFav:"♥",symbolVoteUp:"↑",symbolVoteDown:"↓"}}create(){super.create(),this.post=Post_1.Post.getViewingPost(),this.refreshPageTitle()}refreshPageTitle(){document.title=this.parseTemplate()}parseTemplate(){let prefix="";return this.fetchSettings("symbolsEnabled")&&(this.post.is_favorited&&(prefix+=this.fetchSettings("symbolFav")),this.post.user_score>0?prefix+=this.fetchSettings("symbolVoteUp"):this.post.user_score<0&&(prefix+=this.fetchSettings("symbolVoteDown")),prefix&&(prefix+=" ")),prefix+this.fetchSettings("template").replace(/%postid%/g,this.post.id).replace(/%artist%/g,tagSetToString(this.post.tags.real_artist)).replace(/%copyright%/g,tagSetToString(this.post.tags.copyright)).replace(/%character%/g,tagSetToString(this.post.tags.character)).replace(/%species%/g,tagSetToString(this.post.tags.species)).replace(/%meta%/g,tagSetToString(this.post.tags.meta)).replace(/[ ]{2,}/g," ").replace(/\(\)|( - )$/g,"").replace(/^ | $/g,"")+" - "+Page_1.Page.getSiteName();function tagSetToString(tags){return[...tags].join(", ")}}}exports.TitleCustomizer=TitleCustomizer},{"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/post/Post":19}],55:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageClickAction=exports.ImageLoadMethod=exports.BetterSearch=void 0;const jquery_1=require("jquery"),Danbooru_1=require("../../components/api/Danbooru"),E621_1=require("../../components/api/E621"),APIPost_1=require("../../components/api/responses/APIPost"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),Post_1=require("../../components/post/Post"),PostActions_1=require("../../components/post/PostActions"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),BlacklistEnhancer_1=require("./BlacklistEnhancer");class BetterSearch extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites],!0,[BlacklistEnhancer_1.BlacklistEnhancer])}getDefaultSettings(){return{enabled:!0,imageLoadMethod:ImageLoadMethod.Disabled,autoPlayGIFs:!0,imageSizeChange:!0,imageWidth:150,imageRatioChange:!0,imageRatio:.9,imageMinWidth:50,compactMode:!0,hoverTags:!1,ribbonsRel:!0,ribbonsFlag:!0,ribbonsAlt:!1,buttonsVote:!0,buttonsFav:!0,clickAction:ImageClickAction.NewTab,infiniteScroll:!0,loadAutomatically:!0,loadPrevPages:!1,hidePageBreaks:!0}}async prepare(){await super.prepare();const enabled=this.fetchSettings("enabled");Util_1.Util.LS.setItem("re621.bs.enabled",enabled+""),enabled&&this.pageMatchesFilter()&&(this.queryPage=Page_1.Page.getQueryParameter("page")||"1",this.queryTags=(Page_1.Page.getQueryParameter("tags")||"").split(" ").filter(el=>""!=el),this.queryLimit=parseInt(Page_1.Page.getQueryParameter("limit"))||void 0,this.pageResult=this.fetchPosts(),$("#content").attr("loading","true"))}create(){super.create();const paginator=$("#paginator-old, div.paginator menu").first(),curPage=parseInt(paginator.find(".current-page").text())||-1,lastPage=parseInt(paginator.find(".numbered-page").last().text())||-1;if(paginator.remove(),this.lastPage=Math.max(curPage,lastPage),jquery_1.isNumeric(this.queryPage)){const currentPage=Util_1.Util.Math.clamp(parseInt(this.queryPage),1,750);this.queryPage=currentPage+"",this.lastPage<currentPage&&(this.lastPage=currentPage),this.hasMorePages=750==currentPage||currentPage<this.lastPage}else this.queryPage.match(/(?:a|b)\d+/g)?this.hasMorePages=!0:(this.queryPage="-1",this.hasMorePages=!1);this.createStructure(),this.updateContentHeader(),this.updatePageTitle(this.queryPage);const preloadEnabled=this.fetchSettings("loadPrevPages")&&"true"!==Page_1.Page.getQueryParameter("nopreload");let timer;Page_1.Page.removeQueryParameter("nopreload"),$(window).on("scroll.re621.gen resize.re621.gen",()=>{timer||(null==timer&&BetterSearch.trigger("scroll"),timer=window.setTimeout(()=>{timer=void 0,BetterSearch.trigger("scroll")},250))}),this.$content.on("re621:render","post",event=>{Post_1.Post.get($(event.currentTarget)).render()}).on("re621:reset","post",event=>{Post_1.Post.get($(event.currentTarget)).reset()}).on("re621:filters","post",event=>{Post_1.Post.get($(event.currentTarget)).updateFilters()}).on("re621:visibility","post",event=>{Post_1.Post.get($(event.currentTarget)).updateVisibility()}),BetterSearch.on("postcount",()=>{this.updatePostCount()}),BetterSearch.on("paginator",()=>{this.reloadPaginator()});const intersecting=new Set;let selectedPage=this.queryPage;this.observer=new IntersectionObserver(entries=>{entries.forEach(value=>{const post=Post_1.Post.get($(value.target)),has=intersecting.has(post.id);has&&!value.isIntersecting&&(intersecting.delete(post.id),post.reset()),!has&&value.isIntersecting&&(intersecting.add(post.id),window.setTimeout(()=>{intersecting.has(post.id)&&(post.render(),post.page!=selectedPage&&(selectedPage=post.page,Page_1.Page.setQueryParameter("page",selectedPage+""),this.updatePageTitle(selectedPage)))},100))})},{root:null,rootMargin:"100% 50% 100% 50%",threshold:.5}),new Promise(async resolve=>{let pagesLoaded=0;const pageResult=await this.pageResult;if(pageResult.length>0){const imageRatioChange=this.fetchSettings("imageRatioChange");if(jquery_1.isNumeric(this.queryPage)){const currentPage=parseInt(this.queryPage);let result=[];for(let i=preloadEnabled?Math.max(currentPage-BetterSearch.PAGES_PRELOAD,1):currentPage;i<currentPage;i++){result=await this.fetchPosts(i);for(const post of result){const postData=Post_1.Post.make(post,i+"",imageRatioChange);null!==postData&&(this.$content.append(postData.$ref),this.observer.observe(postData.$ref[0]))}$("<post-break>").attr("id","page-"+(i+1)).html("Page "+(i+1)).appendTo(this.$content),pagesLoaded++}}for(const post of pageResult){const postData=Post_1.Post.make(post,this.queryPage,imageRatioChange);null!==postData&&(this.$content.append(postData.$ref),this.observer.observe(postData.$ref[0]))}pagesLoaded++}this.$wrapper.removeAttr("loading").attr("infscroll","ready"),resolve(pagesLoaded)}).then(pagesLoaded=>{this.reloadPaginator(),this.reloadEventListeners();const scrollTo=$(`[page=${this.queryPage}]:visible:first`);preloadEnabled&&pagesLoaded>1&&0!==scrollTo.length&&$([document.documentElement,document.body]).animate({scrollTop:scrollTo.offset().top-30},200),BlacklistEnhancer_1.BlacklistEnhancer.update(),this.updatePostCount()})}static isPaused(){return BetterSearch.paused}static setPaused(state){BetterSearch.paused=state,BetterSearch.trigger("paginator")}updatePageTitle(page){document.title=(0==this.queryTags.length?"Posts":this.queryTags.join(" ").replace(/_/g," "))+("1"!=page?" - Page "+page:"")+" - "+Page_1.Page.getSiteName()}createStructure(){this.$wrapper=$("#content").attr("loading","true"),$("<search-loading>").html('<span><div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div></span>').appendTo(this.$wrapper),this.$quickEdit=$("<form>").attr({id:"re621-quick-tags",postid:"invalid"}).addClass("simple_form").html('<input type="hidden" name="_method" value="put"><div class="quick-tags-container"> <textarea name="post[tag_string]" id="re621_qedit_tags" data-autocomplete="tag-edit" class="ui-autocomplete-input" autocomplete="off"></textarea></div><div class="quick-tags-toolbar"> <input type="submit" name="submit" value="Submit"> <input type="button" name="cancel" value="Cancel"> <input type="text" name="reason" placeholder="Edit Reason" title="Edit Reason" id="re621_qedit_reason"> <input type="text" name="parent" placeholder="Parent ID" title="Parent ID" id="re621_qedit_parent"> <select name="post[rating]" title="Rating" id="re621_qedit_rating">\n <option value="s">Safe</option>\n <option value="q">Questionable</option>\n <option value="e">Explicit</option>\n </select><div class="quick-tags-info"> <span id="re621-qedit-dimensions"></span> <span id="re621-qedit-flags" class="display-none-important"></span> <a id="re621-qedit-history" href="404">history</a></div></div>').appendTo(this.$wrapper).hide(),this.$quickEdit.data({token:$("#re621_qedit_token"),info:$("#re621-qedit-dimensions"),flags:$("#re621-qedit-flags"),history:$("#re621-qedit-history"),tags:$("#re621_qedit_tags"),reason:$("#re621_qedit_reason"),parent:$("#re621_qedit_parent"),rating:$("#re621_qedit_rating")}),this.$quickEdit.find("input[name=cancel]").on("click",()=>{this.$quickEdit.hide("fast")}),Danbooru_1.Danbooru.Autocomplete.initialize_all(),this.$quickEdit.on("submit",event=>{event.preventDefault();const postID=parseInt(this.$quickEdit.attr("postid"));E621_1.E621.Post.id(postID).put({post:{tag_string:this.$quickEdit.data("tags").val()+"",edit_reason:this.$quickEdit.data("reason").val()+"",parent_id:this.$quickEdit.data("parent").val()+"",rating:APIPost_1.PostRating.fromValue(this.$quickEdit.data("rating").val()+"")}}).then(response=>{Debug_1.Debug.log(response),Post_1.Post.get(postID).update(response[0].post).render(),Danbooru_1.Danbooru.notice(`Post <a href="/posts/${postID}" target="_blank">#${postID}</a> updated (<a href="/post_versions?search[post_id]=${postID}">history</a>)`),this.$quickEdit.hide("fast")},error=>{Danbooru_1.Danbooru.error("An error occurred while updating a post"),console.log(error),this.$quickEdit.hide("fast")})}),this.$content=$("<search-content>").appendTo(this.$wrapper);const infscroll=$("<paginator-container>").appendTo(this.$wrapper);$("<span>").addClass("paginator-loading").html('<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>').appendTo(infscroll),this.$paginator=$("<paginator>").html("").appendTo(infscroll)}updatePostCount(){this.$content.attr("posts",$("post:visible").length)}reloadRenderedPosts(){Post_1.Post.find("rendered").each(post=>post.render())}updateContentHeader(){const conf=this.fetchSettings(["imageSizeChange","imageWidth","imageRatioChange","imageRatio","imageMinWidth","compactMode","ribbonsAlt","hidePageBreaks"]);this.$content.removeAttr("style"),conf.imageSizeChange&&this.$content.css("--img-width",conf.imageWidth+"px"),conf.imageRatioChange?this.$content.css("--img-ratio",conf.imageRatio):this.$content.css("--img-fit",conf.imageMinWidth+"%"),conf.compactMode&&this.$content.css("--img-maxheight",(conf.imageSizeChange?conf.imageWidth:150)+"px"),conf.ribbonsAlt?this.$content.attr("ribbons-alt","true"):this.$content.removeAttr("ribbons-alt"),conf.hidePageBreaks?this.$content.attr("hide-page-breaks","true"):this.$content.removeAttr("hide-page-breaks")}reloadEventListeners(){this.reloadModeSwitchListener(),this.reloadInfScrollListeners()}reloadModeSwitchListener(){this.$content.on("click","post a",event=>{const mode=$("#mode-box-mode").val();if("view"==mode)return;event.preventDefault();const $article=$(event.currentTarget).parent(),post=Post_1.Post.get($article);switch(mode){case"rating-q":case"rating-s":case"rating-e":case"lock-rating":case"lock-note":case"delete":case"undelete":case"approve":case"remove-parent":case"tag-script":case"add-to-set":case"remove-from-set":case"fake-click":{const $farticle=$("<article>").addClass("post-preview display-none-important").attr({id:"post_"+post.id,"data-id":post.id,"data-tags":post.tagString}).appendTo("body");$("<a>").appendTo($farticle).one("click",event=>{Danbooru_1.Danbooru.PostModeMenu.click(event),window.setTimeout(()=>{$farticle.remove()},500)})[0].click();break}case"vote-up":{const firstVote=null==post.$ref.attr("vote");PostActions_1.PostActions.vote(post.id,1,firstVote).then(response=>{Debug_1.Debug.log(response),0==response.action?firstVote?post.$ref.attr("vote","1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)});break}case"vote-down":{const firstVote=null==post.$ref.attr("vote");PostActions_1.PostActions.vote(post.id,-1,!1).then(response=>{Debug_1.Debug.log(response),0==response.action?firstVote?post.$ref.attr("vote","1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)});break}case"add-fav":E621_1.E621.Favorites.post({post_id:post.id}),post.is_favorited=!0,post.$ref.attr("fav","true");break;case"remove-fav":E621_1.E621.Favorite.id(post.id).delete(),post.is_favorited=!1,post.$ref.removeAttr("fav");break;case"edit":{"true"==$("body").attr("data-sticky-header")?this.$quickEdit.css("top",$("#top").height()+"px"):this.$quickEdit.css("top",""),this.$quickEdit.show("fast"),this.$quickEdit.attr("postid",post.id);const ratio=Util_1.Util.formatRatio(post.img.width,post.img.height);this.$quickEdit.data("info").html(`${post.img.width} x ${post.img.height} (${ratio[0]}:${ratio[1]}), ${Util_1.Util.formatBytes(post.file.size)}`),this.$quickEdit.data("flags").toggleClass("display-none-important",0==post.flags.size).html(post.flags.size>0?[...post.flags].join(", "):""),this.$quickEdit.data("history").attr("href","https://e621.net/post_versions?search[post_id]="+post.id),this.$quickEdit.data("tags").val(post.tagString+" ").trigger("re621:input").focus(),this.$quickEdit.data("reason").val(""),this.$quickEdit.data("parent").val(post.rel.parent),this.$quickEdit.data("rating").val(post.rating);break}default:Danbooru_1.Danbooru.error("Unknown mode")}})}reloadInfScrollListeners(){const fullpage=$(document),viewport=$(window);BetterSearch.off("scroll.infscroll"),this.fetchSettings("infiniteScroll")&&this.fetchSettings("loadAutomatically")&&void 0===this.queryLimit&&BetterSearch.on("scroll.infscroll",()=>{if(!this.hasMorePages)return void BetterSearch.off("scroll.infscroll");if(BetterSearch.paused)return;if(this.loadingPosts)return;const pageHeight=fullpage.height(),viewHeight=viewport.height();viewport.scrollTop()+viewHeight<Math.max(pageHeight-viewHeight,.9*fullpage.height())||$("#infscroll-next")[0].click()})}async fetchPosts(page){if(Page_1.Page.matches(Page_1.PageDefintion.favorites)){const userID=Page_1.Page.getQueryParameter("user_id")||User_1.User.getUserID();return E621_1.E621.Favorites.get({user_id:userID,page:page||this.queryPage,limit:this.queryLimit},500)}const parsedTags=[];for(const tag of this.queryTags)parsedTags.push(decodeURIComponent(tag));return E621_1.E621.Posts.get({tags:parsedTags,page:page||this.queryPage,limit:this.queryLimit},500)}async loadNextPage(){this.queryPage=jquery_1.isNumeric(this.queryPage)?this.queryPage=parseInt(this.queryPage)+1+"":this.queryPage="b"+Post_1.Post.get($("post:last")).id;const search=await this.fetchPosts(this.queryPage);if(0==search.length)return Promise.resolve(!1);const imageRatioChange=this.fetchSettings("imageRatioChange");$("<post-break>").attr("id","page-"+this.queryPage).html("Page "+this.queryPage).appendTo(this.$content);for(const post of search){if(null!==Post_1.Post.get(post.id))continue;const postData=Post_1.Post.make(post,this.queryPage,imageRatioChange);null!==postData&&(this.$content.append(postData.$ref),this.observer.observe(postData.$ref[0]))}return Page_1.Page.setQueryParameter("page",this.queryPage+""),BetterSearch.trigger("tracker.update"),BlacklistEnhancer_1.BlacklistEnhancer.update(),this.updatePostCount(),BetterSearch.trigger("pageload"),jquery_1.isNumeric(this.queryPage)?Promise.resolve(parseInt(this.queryPage)<this.lastPage):Promise.resolve(!0)}reloadPaginator(){if(this.$paginator.html(""),"1"==this.queryPage?$("<span>").html('<i class="fas fa-angle-double-left"></i> Previous').addClass("paginator-prev").appendTo(this.$paginator):$("<a>").attr("href",function(page){if(jquery_1.isNumeric(page))return getPageURL(parseInt(page)-1);const lookup=$("post:first");return 0==lookup.length?null:getPageURL("a"+Post_1.Post.get(lookup).id)}(this.queryPage)).html('<i class="fas fa-angle-double-left"></i> Previous').addClass("paginator-prev").appendTo(this.$paginator),this.fetchSettings("infiniteScroll")){const loadMoreWrap=$("<span>").addClass("infscroll-next-wrap").appendTo(this.$paginator),loadMoreCont=$("<span>").addClass("infscroll-next-cont").appendTo(loadMoreWrap);this.hasMorePages?($("<a>").html("Load More").attr("id","infscroll-next").appendTo(loadMoreCont).one("click",event=>{event.preventDefault(),this.loadingPosts=!0,this.$wrapper.attr("infscroll","loading"),this.loadNextPage().then(result=>{this.hasMorePages=result,this.$wrapper.attr("infscroll","ready"),this.reloadPaginator(),this.loadingPosts=!1})}),$("<span>").addClass("infscroll-manual").html(BetterSearch.paused||!this.fetchSettings("loadAutomatically")?"Manual Mode":" ").appendTo(loadMoreCont)):$("<span>").html("No More Posts").attr("id","infscroll-next").appendTo(loadMoreCont)}else $("<span>").appendTo(this.$paginator);this.hasMorePages?$("<a>").attr("href",function(page){if(jquery_1.isNumeric(page)){if(parseInt(page)<750)return getPageURL(parseInt(page)+1)}const lookup=$("post:last");return 0==lookup.length?null:getPageURL("b"+Post_1.Post.get(lookup).id)}(this.queryPage)).html('Next <i class="fas fa-angle-double-right"></i>').addClass("paginator-next").appendTo(this.$paginator):$("<span>").html('Next <i class="fas fa-angle-double-right"></i>').addClass("paginator-next").appendTo(this.$paginator);const pages=$("<div>").addClass("paginator-numbers").appendTo(this.$paginator);if(jquery_1.isNumeric(this.queryPage)){const currentPage=parseInt(this.queryPage),pageNum=[];let count=0;for(let i=1;i<=this.lastPage;i++)Util_1.Util.Math.between(i,0,currentPage<5?5:3)||Util_1.Util.Math.between(i,currentPage-2,currentPage+2)||Util_1.Util.Math.between(i,currentPage<5?this.lastPage-5:this.lastPage-3,this.lastPage)?(pageNum.push(i),count++):null!==pageNum[count-1]&&(pageNum.push(null),count++);for(const page of pageNum)null==page?$("<span>").html(". . .").appendTo(pages):page==currentPage?$("<span>").html(`<b>${page}</b>`).appendTo(pages):$("<a>").attr("href",getPageURL(page)).html(""+page).appendTo(pages)}function getPageURL(page){const url=new URL(window.location.toString());return url.searchParams.set("page",page+""),url.searchParams.set("nopreload","true"),url.pathname+url.search}}}var ImageLoadMethod,ImageClickAction;exports.BetterSearch=BetterSearch,BetterSearch.PAGES_PRELOAD=3,BetterSearch.CLICK_DELAY=200,BetterSearch.paused=!1,function(ImageLoadMethod){ImageLoadMethod.Disabled="disabled",ImageLoadMethod.Hover="hover",ImageLoadMethod.Always="always"}(ImageLoadMethod=exports.ImageLoadMethod||(exports.ImageLoadMethod={})),function(ImageClickAction){ImageClickAction.Disabled="disabled",ImageClickAction.NewTab="newtab",ImageClickAction.CopyID="copyid",ImageClickAction.Blacklist="blacklist",ImageClickAction.AddToSet="addtoset",ImageClickAction.ToggleSet="toggleset"}(ImageClickAction=exports.ImageClickAction||(exports.ImageClickAction={}))},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/E621":5,"../../components/api/responses/APIPost":11,"../../components/data/Page":16,"../../components/data/User":18,"../../components/post/Post":19,"../../components/post/PostActions":20,"../../components/utility/Debug":30,"../../components/utility/Util":33,"./BlacklistEnhancer":56,jquery:69}],56:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlacklistEnhancer=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Blacklist_1=require("../../components/data/Blacklist"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("./BetterSearch");class BlacklistEnhancer extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites],!0,[BetterSearch_1.BetterSearch])}create(){super.create(),Danbooru_1.Danbooru.Blacklist.stub_vanilla_functions(),Danbooru_1.Danbooru.Blacklist.initialize_disable_all_blacklists(),$("#blacklisted-hider").remove(),BlacklistEnhancer.$wrapper=$("#blacklist-box").attr({id:"re621-blacklist",open:!1,count:0,discount:0,collapsed:"1"==Util_1.Util.LS.getItem("bc")}).removeAttr("style").removeAttr("class").appendTo("#re621-search").html(""),BlacklistEnhancer.$header=$("<blacklist-header>").html("Blacklisted").appendTo(BlacklistEnhancer.$wrapper).on("click.re621",()=>{const collapsed=!("true"==BlacklistEnhancer.$wrapper.attr("collapsed"));BlacklistEnhancer.$wrapper.attr("collapsed",collapsed+""),Util_1.Util.LS.setItem("bc",collapsed?"1":"0"),$("#sidebar").trigger("re621:reflow")}),BlacklistEnhancer.$content=$("<blacklist-content>").appendTo(BlacklistEnhancer.$wrapper),BlacklistEnhancer.$content.on("click.re621","a",event=>{event.preventDefault();const $target=$(event.currentTarget).parent(),enabled=!("true"==$target.attr("enabled")),filter=$target.data("filter");filter.setEnabled(enabled),$target.attr("enabled",enabled+""),BlacklistEnhancer.updateHeader(),BlacklistEnhancer.updateToggleSwitch();for(const match of filter.getMatches())$("#entry_"+match).trigger("re621:visibility");BetterSearch_1.BetterSearch.trigger("postcount")});const toggleContainer=$("<blacklist-toggle>").appendTo(BlacklistEnhancer.$wrapper);BlacklistEnhancer.$toggle=$("<a>").attr("id","disable-all-blacklists").html("Disable All Filters").appendTo(toggleContainer).on("click.re621",()=>{"re-enable-all-blacklists"==BlacklistEnhancer.$toggle.attr("id")?(Blacklist_1.Blacklist.enableAll(),BlacklistEnhancer.$toggle.attr("id","disable-all-blacklists"),Post_1.Post.find("all").each(post=>post.updateVisibility())):(Blacklist_1.Blacklist.disableAll(),Post_1.Post.find("blacklisted").each(post=>post.updateVisibility()),BlacklistEnhancer.$toggle.attr("id","re-enable-all-blacklists"),BlacklistEnhancer.$wrapper.attr("collapsed","false"),Util_1.Util.LS.setItem("bc","0"),$("#sidebar").trigger("re621:reflow")),BlacklistEnhancer.update(),BetterSearch_1.BetterSearch.trigger("postcount")})}static update(){BlacklistEnhancer.updateFilterList(),BlacklistEnhancer.updateHeader(),BlacklistEnhancer.updateToggleSwitch(),$("#sidebar").trigger("re621:reflow")}static updateHeader(){let enabled=0,disabled=0;for(const entry of BlacklistEnhancer.$content.find("filter")){const filter=$(entry);"true"==filter.attr("enabled")?enabled+=parseInt(filter.attr("count"))||0:disabled+=parseInt(filter.attr("count"))||0}BlacklistEnhancer.$header.html(`Blacklisted (${enabled})`),BlacklistEnhancer.$wrapper.attr({count:enabled,discount:disabled})}static updateFilterList(){BlacklistEnhancer.$content.html("");for(const[tags,filter]of Blacklist_1.Blacklist.getActiveFilters()){const count=filter.getMatchesCount(),entry=$("<filter>").attr({count:count,enabled:filter.isEnabled()}).data("filter",filter).appendTo(BlacklistEnhancer.$content);$("<a>").attr("href","/posts?tags="+tags.replace(" ","+")).html(tags.replace(/_/g,"​_")).appendTo(entry),$("<span>").html(count+"").appendTo(entry)}$("#sidebar").trigger("re621:reflow")}static updateToggleSwitch(){BlacklistEnhancer.$content.find("filter[enabled=false]").length>0?(BlacklistEnhancer.$toggle.html("Enable All Filters").attr("id","re-enable-all-blacklists"),Util_1.Util.LS.setItem("dab","1")):(BlacklistEnhancer.$toggle.html("Disable All Filters").attr("id","disable-all-blacklists"),Util_1.Util.LS.setItem("dab","0"))}}exports.BlacklistEnhancer=BlacklistEnhancer},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Blacklist":14,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/utility/Util":33,"./BetterSearch":55}],57:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomFlagger=void 0;const Page_1=require("../../components/data/Page"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),PostFilter_1=require("../../components/post/PostFilter"),RE6Module_1=require("../../components/RE6Module"),BetterSearch_1=require("./BetterSearch");class CustomFlagger extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.post,Page_1.PageDefintion.search,Page_1.PageDefintion.favorites,Page_1.PageDefintion.popular],!0,[BetterSearch_1.BetterSearch])}getDefaultSettings(){return{enabled:!1,flags:[]}}create(){Page_1.Page.matches(Page_1.PageDefintion.post)&&this.createPostPage()}static get(){if(null==CustomFlagger.filters){CustomFlagger.filters=new Map;for(const flag of ModuleController_1.ModuleController.get(CustomFlagger).fetchSettings("flags"))CustomFlagger.filters.get(flag.tags)||CustomFlagger.filters.set(flag.tags,{data:flag,filter:new PostFilter_1.PostFilter(flag.tags,!0)})}return CustomFlagger.filters}static addPost(...posts){let count=0;for(const filterPair of CustomFlagger.get().values())filterPair.filter.update(posts)&&count++;return count}static updatePost(...posts){return CustomFlagger.addPost(...posts)}static getFlags(post){"number"!=typeof post&&(post=post.id);const output=[];for(const filterPair of CustomFlagger.get().values())filterPair.filter.matchesID(post)&&output.push(filterPair.data);return output}createPostPage(){const post=Post_1.Post.getViewingPost();CustomFlagger.addPost(post);const flagContainer=$("<div>").insertAfter("div.input#tags-container");let activeFlags=0;for(const flag of CustomFlagger.getFlags(post))$("<div>").addClass("custom-flag").html(`<span class="custom-flag-title" style="--flag-color: ${flag.color}">${flag.name}</span> ${flag.tags}`).appendTo(flagContainer),activeFlags++;activeFlags>0&&$("<b>").html("Flags").addClass("display-block").prependTo(flagContainer)}}exports.CustomFlagger=CustomFlagger},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostFilter":21,"./BetterSearch":55}],58:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageZoomMode=exports.HoverZoom=void 0;const APIPost_1=require("../../components/api/responses/APIPost"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util");class HoverZoom extends RE6Module_1.RE6Module{constructor(){super([],!0),this.shiftPressed=!1}getDefaultSettings(){return{enabled:!0,mode:ImageZoomMode.OnShift,tags:!1}}create(){super.create(),this.createStructure(),this.reloadEventListeners(),this.initFunctionality()}createStructure(){this.$zoomBlock=$("<zoom-container>").attr("status","waiting").appendTo("body"),this.$zoomInfo=$("<div>").attr("id","zoom-info").appendTo(this.$zoomBlock),this.$zoomImage=$("<img>").attr("src",DomUtilities_1.DomUtilities.getPlaceholderImage()).addClass("display-none").appendTo(this.$zoomBlock),this.$zoomVideo=$("<video controls autoplay loop muted></video>").attr({poster:"",src:"",muted:"muted"}).addClass("display-none").appendTo(this.$zoomBlock),this.$zoomTags=$("<div>").attr("id","zoom-tags").appendTo(this.$zoomBlock)}reloadEventListeners(){const zoomMode=this.fetchSettings("mode");$(document).off("keydown.re621.zoom").off("keyup.re621.zoom"),$("#page").off("mouseenter.re621.zoom","post, .post-preview, div.post-thumbnail").off("mouseleave.re621.zoom","post, .post-preview, div.post-thumbnail"),zoomMode!=ImageZoomMode.Disabled&&($("#page").on("mouseenter.re621.zoom","post, .post-preview, div.post-thumbnail",event=>{const $ref=$(event.currentTarget);$ref.attr("hovering","true"),HoverZoom.trigger("zoom.start",{post:$ref.data("id"),pageX:event.pageX,pageY:event.pageY})}).on("mouseleave.re621.zoom","post, .post-preview, div.post-thumbnail",event=>{const $ref=$(event.currentTarget);$ref.removeAttr("hovering"),HoverZoom.trigger("zoom.stop",{post:$ref.data("id"),pageX:event.pageX,pageY:event.pageY})}),zoomMode===ImageZoomMode.OnShift&&$(document).on("keydown.re621.zoom",event=>{if(this.shiftPressed||"Shift"!==event.originalEvent.key)return;this.shiftPressed=!0;let count=0;for(const el of $("[hovering=true]"))$(el).trigger("mouseenter.re621.zoom"),count++;Debug_1.Debug.log("hovering total",count)}).on("keyup.re621.zoom",event=>{this.shiftPressed&&"Shift"===event.originalEvent.key&&(this.shiftPressed=!1)}))}initFunctionality(){let videoTimeout;const viewport=$(window);HoverZoom.on("zoom.start",(event,data)=>{if(HoverZoom.paused||this.fetchSettings("mode")==ImageZoomMode.OnShift&&!this.shiftPressed)return;const $ref=$(`#entry_${data.post}, #post_${data.post}, div.post-thumbnail[data-id=${data.post}]`).first(),post=$ref.is("post")?Post_1.Post.get($ref):Post_1.PostData.fromThumbnail($ref);if(post.flags.has(APIPost_1.PostFlag.Deleted)||"swf"==post.file.ext)return;const $img=$ref.find("img").first();$ref.data("stored-title",$img.attr("title")||""),$img.removeAttr("title"),this.$zoomBlock.attr("status","loading");let width=Math.min(post.img.width,.5*viewport.width()-50),height=width*post.img.ratio;height>.75*viewport.height()&&(height=.75*viewport.height(),width=height/post.img.ratio),this.$zoomImage.css({width:width+"px",height:height+"px"}),"webm"==post.file.ext?(this.$zoomVideo.removeClass("display-none").css("background-image",`url("${post.file.sample}")`).attr({src:post.file.original,poster:post.file.sample}),videoTimeout=window.setTimeout(()=>{this.$zoomVideo.attr("muted","false")},500),this.$zoomBlock.attr("status","ready")):this.$zoomImage.removeClass("display-none").css("background-image",`url("${post.file.preview}")`).attr("src",post.file.sample).one("load",()=>{this.$zoomBlock.attr("status","ready")}),this.$zoomInfo.html(`${post.img.width} x ${post.img.height}`+(post.file.size>0?", "+Util_1.Util.formatBytes(post.file.size):"")+` | <span class="post-info-rating rating-${post.rating}">${post.rating}</span>`+("0"!==post.date.raw?" | "+post.date.ago:"")),this.fetchSettings("tags")&&this.$zoomTags.html(post.tagString).css({"max-width":width+"px"});let throttled=!1;$(document).on("mousemove.re621.zoom",event=>{if(throttled)return;throttled=!0,window.setTimeout(()=>{throttled=!1},25);const imgHeight=this.$zoomBlock.height(),imgWidth=this.$zoomBlock.width(),cursorX=event.pageX,cursorY=event.pageY-viewport.scrollTop(),left=cursorX<viewport.width()/2?cursorX+50:cursorX-imgWidth-50,top=Util_1.Util.Math.clamp(cursorY-imgHeight/2,10,viewport.height()-imgHeight-10);this.$zoomBlock.css({left:left+"px",top:top+"px"})});const offset=$ref.offset(),e=$.Event("mousemove.re621.zoom"),centerX=offset.left+$ref.width()/2,centerY=offset.top+$ref.height()/2;e.pageX=data.pageX?data.pageX:centerX,e.pageY=data.pageY?data.pageY:centerY,$(document).trigger(e)}),HoverZoom.on("zoom.stop",(event,data)=>{$(document).off("mousemove.re621.zoom");const $ref=$(`#entry_${data.post}, #post_${data.post}, div.post-thumbnail[data-id=${data.post}]`).first(),$img=$ref.find("img").first();$ref.data("stored-title")&&$img.attr("title",$ref.data("stored-title")),this.$zoomBlock.attr("status","waiting").css({left:0,top:"100vh"}),this.$zoomInfo.html(""),this.$zoomImage.addClass("display-none").removeAttr("style").attr("src",DomUtilities_1.DomUtilities.getPlaceholderImage()),this.$zoomVideo.addClass("display-none").attr({muted:""}),""!==this.$zoomVideo.attr("src")&&this.$zoomVideo.attr({poster:"",src:""}),window.clearTimeout(videoTimeout),this.$zoomTags.removeAttr("style").html("")})}}var ImageZoomMode;exports.HoverZoom=HoverZoom,HoverZoom.paused=!1,function(ImageZoomMode){ImageZoomMode.Disabled="disabled",ImageZoomMode.Hover="hover",ImageZoomMode.OnShift="onshift"}(ImageZoomMode=exports.ImageZoomMode||(exports.ImageZoomMode={}))},{"../../components/RE6Module":2,"../../components/api/responses/APIPost":11,"../../components/post/Post":19,"../../components/structure/DomUtilities":25,"../../components/utility/Debug":30,"../../components/utility/Util":33}],59:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InstantSearch=void 0;const Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),PostFilter_1=require("../../components/post/PostFilter"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("./BetterSearch");class InstantSearch extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites],!0,[BetterSearch_1.BetterSearch])}getDefaultSettings(){return{enabled:!1}}create(){super.create(),$("search-content").on("re621:insearch","post",event=>{const $article=$(event.currentTarget),post=Post_1.Post.get($article);null==InstantSearch.filter?$article.removeAttr("filtered"):(InstantSearch.filter.update(post),InstantSearch.filter.matches(post)?$article.removeAttr("filtered"):$article.attr("filtered","true"))});const $section=$("<section>").attr("id","re621-insearch").html("<h1>Filter</h1>").insertAfter("#search-box"),$searchForm=$("<form>").appendTo($section);let typingTimeout;this.$searchbox=$("<input>").attr("id","re621-insearch-input").attr("type","text").val(Util_1.Util.SS.getItem("re621.insearch")||"").appendTo($searchForm).on("input",()=>{clearTimeout(typingTimeout),typingTimeout=window.setTimeout(()=>{this.applyFilter()},500)}),this.$searchbox.trigger("input"),$("<button>").attr("type","submit").html('<i class="fas fa-search"></i>').appendTo($searchForm),$("#sidebar").trigger("re621:reflow")}destroy(){super.destroy(),this.$searchbox.val(""),this.applyFilter(),$("#re621-insearch").remove(),$("search-content").off("re621:insearch","post"),$("#sidebar").trigger("re621:reflow")}static get(){return InstantSearch.filter}static addPost(...posts){const filter=InstantSearch.get();return!!filter&&filter.update(posts)}applyFilter(){const filterText=this.$searchbox.val().toString().trim();0==filterText.length?(InstantSearch.filter=void 0,Util_1.Util.SS.removeItem("re621.insearch")):(InstantSearch.filter=new PostFilter_1.PostFilter(filterText),Util_1.Util.SS.setItem("re621.insearch",filterText)),$("post").trigger("re621:insearch")}}exports.InstantSearch=InstantSearch},{"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostFilter":21,"../../components/utility/Util":33,"./BetterSearch":55}],60:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostSuggester=void 0;const E621_1=require("../../components/api/E621"),APIPost_1=require("../../components/api/responses/APIPost"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),RE6Module_1=require("../../components/RE6Module"),Modal_1=require("../../components/structure/Modal");class PostSuggester extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.search)}getDefaultSettings(){return{enabled:!0}}create(){if(super.create(),!User_1.User.isLoggedIn())return;const listItem=$("<li>").appendTo("ul#related-list"),button=$("<a>").html("Recommended").appendTo(listItem),modalContent=$("<div>").addClass("post-suggester");this.status=$("<div>").addClass("post-suggester-status").appendTo(modalContent),this.content=$("<div>").addClass("post-suggester-content").appendTo(modalContent);const modal=new Modal_1.Modal({title:"Post Recommendations",triggers:[{element:button}],fixed:!0,content:modalContent,position:{my:"center",at:"center"}});let triggered=!1;modal.getElement().on("dialogopen",()=>{triggered||(triggered=!0,this.handleRecommendation())})}async handleRecommendation(){this.status.html("Compiling favorites data");const data={};let result;for(let i=1;i<=PostSuggester.maxPages&&(this.status.html(`Analyzing favorites [ ${i} / ${PostSuggester.maxPages} ]`),result=await E621_1.E621.Posts.get({tags:"fav:"+User_1.User.getUsername(),page:i,limit:320},500),result.forEach(post=>{APIPost_1.APIPost.getTags(post).forEach(tag=>{data[tag]?data[tag]=data[tag]+1:data[tag]=1})}),320===result.length);i++);this.status.html("Lookup complete");let processedData=[];for(const tag in data)processedData.push([tag,data[tag]]);processedData=processedData.sort((a,b)=>b[1]-a[1]);for(let year=1973;year<=(new Date).getFullYear();year++)PostSuggester.removedTags.push(year+"");processedData=processedData.filter(entry=>!PostSuggester.removedTags.includes(entry[0])&&entry[1]>PostSuggester.minTagCount),processedData.length>100&&(processedData.length=100),this.content[0].innerHTML="";let checkedNum=0,shouldCheck=!0;for(const[tag,count]of processedData){const container=$("<span>").appendTo(this.content);shouldCheck=checkedNum<10&&!PostSuggester.ignoredTags.includes(tag),shouldCheck&&checkedNum++,$("<input>").attr({type:"checkbox",name:"post-suggester-selector",value:tag,id:"tag-"+tag,"data-tag":tag,"data-count":count}).prop("checked",shouldCheck).appendTo(container),$("<label>").attr({for:"tag-"+tag}).html(tag.replace(/_/g," ")).appendTo(container),$("<a>").attr("href","/posts?tags="+tag).html("?").appendTo(container),$("<span>").addClass("tag-count").html(""+count).appendTo(container)}return this.status[0].innerHTML="",$("<a>").html("Search").addClass("button btn-neutral post-suggester-search").appendTo(this.status).click(event=>{event.preventDefault();const checkedEls=$("input[name=post-suggester-selector]:checked").get(),query=[];for(const checkedEl of checkedEls)query.push("~"+encodeURIComponent($(checkedEl).attr("data-tag")));query.push(encodeURIComponent("order:random")),query.push(encodeURIComponent("score:>10")),window.location.href="/posts?tags="+query.join("+")}),Promise.resolve(!0)}}exports.PostSuggester=PostSuggester,PostSuggester.maxPages=5,PostSuggester.minTagCount=10,PostSuggester.removedTags=["hi_res","absurd_res","digital_media_(artwork)","solo","duo","group","simple_background","detailed_background","text","english_text"],PostSuggester.ignoredTags=["male","female","intersex","mammal","scalie","biped","anthro","feral","genitals","penis","balls","animal_genitalia","humanoid_penis","erection","pussy","butt","anus","breasts","nipples","non-mammal_breasts","genital_fluids","bodily_fluids","cum","wings","membrane_(anatomy)","membranous_wings","claws","horn","scales","teeth","smile","tongue","feathers","toes","hair","fur","clothing","clothed","nude","sex","penetration","male_penetrating"]},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/responses/APIPost":11,"../../components/data/Page":16,"../../components/data/User":18,"../../components/structure/Modal":27}],61:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SearchUtilities=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Blacklist_1=require("../../components/data/Blacklist"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module");class SearchUtilities extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites]),this.registerHotkeys({keys:"hotkeyFocusSearch",fnct:this.focusSearchbar},{keys:"hotkeyRandomPost",fnct:this.randomPost},{keys:"hotkeySwitchModeView",fnct:this.switchModeView},{keys:"hotkeySwitchModeEdit",fnct:this.switchModeEdit},{keys:"hotkeySwitchModeAddFav",fnct:this.switchModeAddFav},{keys:"hotkeySwitchModeRemFav",fnct:this.switchModeRemFav},{keys:"hotkeySwitchModeAddSet",fnct:this.switchModeAddSet},{keys:"hotkeySwitchModeRemSet",fnct:this.switchModeRemSet})}getDefaultSettings(){return{enabled:!0,improveTagCount:!0,shortenTagNames:!0,hidePlusMinusIcons:!1,collapseCategories:!0,categoryData:[],persistentTags:"",quickBlacklist:!0,hotkeyFocusSearch:"q",hotkeyRandomPost:"r",hotkeySwitchModeView:"",hotkeySwitchModeEdit:"",hotkeySwitchModeAddFav:"",hotkeySwitchModeRemFav:"",hotkeySwitchModeAddSet:"",hotkeySwitchModeRemSet:""}}create(){if(super.create(),Page_1.Page.matches(Page_1.PageDefintion.search)){const searchbox=$("section#search-box input");""==searchbox.val()&&searchbox.focus()}Page_1.Page.matches(Page_1.PageDefintion.post)&&Page_1.Page.removeQueryParameter("q"),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post])&&(this.improveTagCount(this.fetchSettings("improveTagCount")),this.shortenTagNames(this.fetchSettings("shortenTagNames")),this.hidePlusMinusIcons(this.fetchSettings("hidePlusMinusIcons"))),!0===this.fetchSettings("collapseCategories")&&Page_1.Page.matches(Page_1.PageDefintion.post)&&this.collapseTagCategories();const persistentTags=this.fetchSettings("persistentTags").trim().toLowerCase();if(""!==persistentTags&&Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites])){const $tagInput=$("input#tags");$tagInput.val(($tagInput.val()+"").replace(persistentTags,"")),$("section#search-box form").on("submit",()=>($tagInput.val($tagInput.val()+" "+persistentTags),!0))}this.initQuickBlacklist(this.fetchSettings("quickBlacklist"))}async improveTagCount(state=!0){const source=state?"data-count":"data-count-short";$("span.re621-post-count").each((function(index,element){const tag=$(element);tag.text(tag.attr(source))}))}shortenTagNames(state=!0){$("section#tag-box, section#tag-list").attr("data-shorten-tagnames",state+"")}hidePlusMinusIcons(state=!0){$("section#tag-box, section#tag-list").attr("data-hide-plusminus",state+"")}async collapseTagCategories(){let storedCats=new Set(await this.fetchSettings("categoryData",!0));for(const element of $("section#tag-list .tag-list-header").get()){const $header=$(element),cat=$header.attr("data-category");storedCats.has(cat)&&$header.get(0).click(),$header.on("click.danbooru",async()=>{storedCats=new Set(await this.fetchSettings("categoryData",!0)),$header.hasClass("hidden-category")?storedCats.add(cat):storedCats.delete(cat),await this.pushSettings("categoryData",Array.from(storedCats))})}}focusSearchbar(event){event.preventDefault(),$("section#search-box input").focus()}randomPost(){location.pathname="/posts/random"}switchModeView(){SearchUtilities.switchMode("view")}switchModeEdit(){SearchUtilities.switchMode("edit")}switchModeAddFav(){SearchUtilities.switchMode("add-fav")}switchModeRemFav(){SearchUtilities.switchMode("remove-fav")}switchModeAddSet(){SearchUtilities.switchMode("add-to-set"),$("#set-id").focus()}switchModeRemSet(){SearchUtilities.switchMode("remove-from-set"),$("#set-id").focus()}static switchMode(mode){$("select#mode-box-mode").val(mode),Danbooru_1.Danbooru.PostModeMenu.change()}initQuickBlacklist(state=!0){if(state)for(const element of $("div.tag-actions span.tag-action-blacklist").get()){const $container=$(element);$("<a>").attr({href:"#",title:"Blacklist Tag"}).addClass("blacklist-tag-toggle").html('<i class="fas fa-times"></i>').prependTo($container).click(event=>{event.preventDefault(),Blacklist_1.Blacklist.toggleBlacklistTag($container.parent().attr("data-tag"))})}else $("div.tag-actions span.tag-action-blacklist").html("")}}exports.SearchUtilities=SearchUtilities},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Blacklist":14,"../../components/data/Page":16}],62:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ThumbnailTweaks=void 0;const ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),BetterSearch_1=require("./BetterSearch");class ThumbnailTweaks extends RE6Module_1.RE6Module{constructor(){super()}getDefaultSettings(){return{enabled:!0}}create(){super.create();const conf=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings(["ribbonsRel","ribbonsFlag"]);for(const element of $(".post-preview").get())ThumbnailTweaks.modify($(element),conf.ribbonsRel,conf.ribbonsFlag)}static modify($article,ribbonsRel,ribbonsFlag){let $picture=$article.find("picture");if(0==$picture.length){const $img=$article.find("img");$picture=$("<picture>").insertAfter($img).append($img)}$picture.addClass("picture-container");const $ribbons=$("<img-ribbons>").appendTo($picture);if(ribbonsRel){const relRibbon=$("<ribbon>").addClass("left").html("<span></span>").appendTo($ribbons),relRibbonText=[];"true"==$article.attr("data-has-children")&&(relRibbon.addClass("has-children"),relRibbonText.push("Child posts")),void 0!==$article.attr("data-parent-id")&&(relRibbon.addClass("has-parent"),relRibbonText.push("Parent posts")),relRibbonText.length>0?relRibbon.attr("title",relRibbonText.join("\n")):relRibbon.remove()}if(ribbonsFlag){const flags=new Set(($article.attr("data-flags")||"").split(" ")),flagRibbon=$("<ribbon>").addClass("right").html("<span></span>").appendTo($ribbons),flagRibbonText=[];flags.has("flagged")&&(flagRibbon.addClass("is-flagged"),flagRibbonText.push("Flagged")),flags.has("pending")&&(flagRibbon.addClass("is-pending"),flagRibbonText.push("Pending")),flagRibbonText.length>0?flagRibbon.attr("title",flagRibbonText.join("\n")):flagRibbon.remove()}0==$ribbons.children().length&&$ribbons.remove()}}exports.ThumbnailTweaks=ThumbnailTweaks},{"../../components/ModuleController":1,"../../components/RE6Module":2,"./BetterSearch":55}],63:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CommentTracker=void 0;const E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),SubscriptionTracker_1=require("./SubscriptionTracker");class CommentTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:data=>Post_1.PostData.createPreviewUrlFromMd5(data.md5),imageHref:data=>"/posts/"+data.extra.parent,imageRemoveOnError:!0,updateHref:data=>"/users/"+data.extra.author,updateText:data=>data.name,sourceHref:data=>`/posts/${data.extra.parent}#comment-${data.id}`,sourceText:()=>"Reply"},this.subBatchSize=100,this.maxSubscriptions=500,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Comments"}makeSubscribeButton(){return $("<button>").addClass("large-subscribe-button subscribe").addClass("button btn-success").html("Subscribe")}makeUnsubscribeButton(){return $("<button>").addClass("large-subscribe-button unsubscribe").addClass("button btn-danger").html("Unsubscribe")}getButtonAttachment(){return Page_1.Page.matches(Page_1.PageDefintion.post)?$("menu#post-sections").first():$()}insertButton($element,$button){$element.append($button)}getSubscriberId(){return Page_1.Page.getPageID()}getSubscriberName(){return"#"+$("section#image-container").attr("data-id")}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>"),status.append("<div> fetching posts</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),postsJSON=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div> - processing batch #${index}</div>`),postsJSON.push(...await E621_1.E621.Posts.get({tags:"id:"+chunk.join(",")},500));status.append("<div> fetching comments</div>");const commentsJSON=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div> - processing batch #${index}</div>`),commentsJSON.push(...await E621_1.E621.Comments.get({group_by:"comment","search[post_id]":chunk.join(",")},500));status.append("<div>. . . processing data</div>");const posts=new Map;postsJSON.forEach(post=>{posts.set(post.id,post)});const data=new Map;commentsJSON.forEach(value=>{(void 0===data.get(value.post_id)||data.get(value.post_id).created_at<value.created_at)&&data.set(value.post_id,value)}),status.append("<div>. . . formatting output</div>");for(const comment of data.values())new Date(comment.created_at).getTime()>lastUpdate&&comment.updater_id!==User_1.User.getUserID()&&(results[new Date(comment.created_at).getTime()]=await this.formatCommentUpdate(comment,posts.get(comment.post_id))),storedSubs[comment.post_id].name="#"+comment.post_id;return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatCommentUpdate(value,post){const body=Util_1.Util.parseDText(value.body);return{id:value.id,name:value.creator_name,nameExtra:body.length>256?body.substr(0,255)+"…":body,md5:"swf"===post.file.ext?"":post.file.md5,extra:{parent:post.id,author:value.creator_id},new:!0}}}exports.CommentTracker=CommentTracker},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/data/User":18,"../../components/post/Post":19,"../../components/utility/Util":33,"./SubscriptionTracker":67}],64:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ForumTracker=void 0;const E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),SubscriptionTracker_1=require("./SubscriptionTracker");class ForumTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:()=>"",updateHref:data=>`/forum_topics/${data.id}?page=${Math.ceil(data.extra.count/75)}`,updateText:data=>data.name,sourceHref:data=>"/forum_topics/"+data.id,sourceText:()=>"First Page"},this.subBatchSize=100,this.maxSubscriptions=500,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Forums"}makeSubscribeButton(){return $("<button>").addClass("large-subscribe-button subscribe").addClass("button btn-success").html("Subscribe")}makeUnsubscribeButton(){return $("<button>").addClass("large-subscribe-button unsubscribe").addClass("button btn-danger").html("Unsubscribe")}getButtonAttachment(){return Page_1.Page.matches(Page_1.PageDefintion.forumPost)?$("#c-forum-topics").first():$()}insertButton($element,$button){$element.prepend($button)}getSubscriberId(){return Page_1.Page.getPageID()}getSubscriberName(){return $("div#c-forum-topics div#a-show h1").first().text().trim().replace("Topic: ","")}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),apiData=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div> - processing batch #${index}</div>`),apiData.push(...await E621_1.E621.ForumTopics.get({"search[id]":chunk.join(",")},500));status.append("<div>. . . formatting output</div>");for(const forumJson of apiData)new Date(forumJson.updated_at).getTime()>lastUpdate&&forumJson.updater_id!==User_1.User.getUserID()&&(results[new Date(forumJson.updated_at).getTime()]=await this.formatForumUpdate(forumJson)),storedSubs[forumJson.id].name=forumJson.title.replace(/_/g," ");return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatForumUpdate(value){return{id:value.id,name:value.title,md5:"",extra:{count:value.response_count},new:!0}}}exports.ForumTracker=ForumTracker},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/data/User":18,"../../components/utility/Util":33,"./SubscriptionTracker":67}],65:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PoolTracker=void 0;const E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),SubscriptionTracker_1=require("./SubscriptionTracker");class PoolTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:data=>Post_1.PostData.createPreviewUrlFromMd5(data.md5),imageHref:data=>"/pools/"+data.id,updateHref:data=>`/posts/${data.extra.last}?pool_id=${data.id}`,updateText:data=>data.name,sourceHref:data=>"/pools/"+data.id,sourceText:()=>"All Posts"},this.subBatchSize=100,this.maxSubscriptions=500,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Pools"}makeSubscribeButton(){return $("<button>").addClass("large-subscribe-button subscribe").addClass("button btn-success").html("Subscribe")}makeUnsubscribeButton(){return $("<button>").addClass("large-subscribe-button unsubscribe").addClass("button btn-danger").html("Unsubscribe")}getButtonAttachment(){return $("div#c-pools > div#a-show").first()}insertButton($element,$button){$element.prepend($button)}getSubscriberId(){return Page_1.Page.getPageID()}getSubscriberName(){return $("div#c-pools div#a-show h2 a").first().text().trim()}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),apiData=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div> - processing batch #${index}</div>`),apiData.push(...await E621_1.E621.Pools.get({"search[id]":chunk.join(",")},500));status.append("<div>. . . formatting output</div>");for(const poolJson of apiData){void 0!==storedSubs[poolJson.id].lastId&&poolJson.post_ids.includes(storedSubs[poolJson.id].lastId)||(storedSubs[poolJson.id].lastId=poolJson.post_ids[poolJson.post_ids.length-1]);const previousStop=poolJson.post_ids.indexOf(storedSubs[poolJson.id].lastId);new Date(poolJson.updated_at).getTime()>lastUpdate&&poolJson.post_ids.length>previousStop&&(results[new Date(poolJson.updated_at).getTime()]=await this.formatPoolUpdate(poolJson,storedSubs)),storedSubs[poolJson.id].lastId=poolJson.post_ids[poolJson.post_ids.length-1],storedSubs[poolJson.id].name=poolJson.name.replace(/_/g," ")}return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatPoolUpdate(value,subSettings){const poolInfo=subSettings[value.id];if(void 0===poolInfo.md5){const lookup=await E621_1.E621.Post.id(value.post_ids[0]).get();0==lookup.length?poolInfo.md5="":poolInfo.md5="swf"===lookup[0].file.ext?"":lookup[0].file.md5}return{id:value.id,name:value.name.replace(/_/g," "),md5:poolInfo.md5,extra:{last:value.post_ids[value.post_ids.length-1]},new:!0}}}exports.PoolTracker=PoolTracker},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/utility/Util":33,"./SubscriptionTracker":67}],66:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0;const Danbooru_1=require("../../components/api/Danbooru"),XM_1=require("../../components/api/XM"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal"),Tabbed_1=require("../../components/structure/Tabbed"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("../search/BetterSearch");class SubscriptionManager extends RE6Module_1.RE6Module{constructor(){super(),this.trackers=new Map,this.notificationsAlreadyOpened=!1,this.registerHotkeys({keys:"hotkeyOpenNotifications",fnct:this.openNotifications})}getDefaultSettings(){return{enabled:!0,lastUpdate:0,updateStarted:0,cacheSize:60,updateInterval:36e5,cacheMaxAge:0,hotkeyOpenNotifications:""}}static async register(moduleList){Array.isArray(moduleList)||(moduleList=[moduleList]);const trackers=this.getInstance().trackers;for(const moduleClass of moduleList)trackers.set(moduleClass.prototype.constructor.name,{instance:ModuleController_1.ModuleController.get(moduleClass)});return Promise.resolve(moduleList.length)}getTracker(id){if("string"==typeof id)return this.trackers.get(id);for(const value of this.trackers.values())if(value.tabIndex===id)return value}async create(){super.create();const settings=this.fetchSettings(["lastUpdate","cacheVersion"]),cacheInvalid=void 0===settings.cacheVersion||settings.cacheVersion<SubscriptionManager.cacheVersion;cacheInvalid&&this.pushSettings("cacheVersion",SubscriptionManager.cacheVersion),this.$openSubsButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-notifications",name:'<i class="fas fa-bell"></i>',title:"Notifications",attr:{"data-loading":"false","data-updates":"0"},linkClass:"update-notification"});const content=[];let tabIndex=0;this.trackers.forEach((data,name)=>{data.tabElement=$("<a>").attr({"data-loading":"false","data-updates":"0"}).addClass("update-notification").html(data.instance.getName()),data.tabIndex=tabIndex,data.content=$("<div>").addClass("subscriptions-list subscription-"+data.instance.getName()).attr({"data-subscription-class":name,"data-updates":"0"}),$("<div>").addClass("subscription-load-status").html("Initializing . . .").appendTo(data.content),cacheInvalid?data.instance.getCache().clear():data.instance.getCache().load(),this.addSubscribeButtons(data.instance),content.push({name:data.tabElement,content:data.content}),tabIndex++}),content.push({name:"Info",content:this.buildInfoPage().render()}),this.tabs=new Tabbed_1.Tabbed({name:"notifications-tabs",content:content}).render(),this.modal=new Modal_1.Modal({title:"Subscriptions",triggers:[{element:this.$openSubsButton}],escapable:!1,reserveHeight:!0,content:this.tabs,position:{my:"right top",at:"right top"}}),SubscriptionManager.on("update.main",()=>{this.executeUpdateEvent()}),SubscriptionManager.on("timerRefresh.main",()=>{this.executeTimerRefreshEvent()}),this.trackers.forEach(trackerData=>{XM_1.XM.Storage.addListener("re621."+trackerData.instance.getSettingsTag()+".cache",(name,oldValue,newValue,remote)=>{remote&&(Debug_1.Debug.log(`SubM${trackerData.tabIndex}: Cache updated`),this.executeReloadEvent(trackerData))})}),this.modal.getElement().on("dialogopen.onUpdate",()=>{if(!SubscriptionManager.updateInProgress){if(!this.notificationsAlreadyOpened){this.notificationsAlreadyOpened=!0;let index=0;for(const sub of this.trackers){if(parseInt(sub[1].tabElement.attr("data-updates"))>0){this.tabs.tabs("option","active",index);break}index++}}this.clearTabNotification(this.tabs.tabs("option","active")),window.setTimeout(()=>{this.clearTabNotification(this.tabs.tabs("option","active"))},1e3)}}),this.tabs.on("tabsactivate.onUpdate",(event,tabProperties)=>{SubscriptionManager.updateInProgress||this.clearTabNotification(tabProperties.newTab.index())}),SubscriptionManager.trigger("timerRefresh"),this.updateRequired().then(updateRequired=>{updateRequired?this.executeUpdateEvent():this.trackers.forEach(trackerData=>{this.executeReloadEvent(trackerData)})}),setInterval(async()=>{SubscriptionManager.updateInProgress||(await this.updateRequired()?SubscriptionManager.trigger("update"):SubscriptionManager.trigger("timerRefresh"))},Util_1.Util.Time.MINUTE)}buildInfoPage(){let updateInterval=this.fetchSettings("updateInterval");return(updateInterval>24*Util_1.Util.Time.HOUR||updateInterval<Util_1.Util.Time.HOUR&&-1!=updateInterval)&&(updateInterval=Util_1.Util.Time.HOUR,this.pushSettings("updateInterval",updateInterval)),-1!==updateInterval&&(updateInterval/=Util_1.Util.Time.HOUR),new Form_1.Form({name:"subscriptions-controls",columns:2,width:2},[Form_1.Form.header("Subscriptions"),makeSubSection(this.getTracker("TagTracker").instance,2),makeSubSection(this.getTracker("PoolTracker").instance,1),makeSubSection(this.getTracker("ForumTracker").instance,1),makeSubSection(this.getTracker("CommentTracker").instance,2),Form_1.Form.hr(2),Form_1.Form.header("Settings"),Form_1.Form.section({name:"settings",columns:2,width:2},[Form_1.Form.div({value:"Cache Size"}),Form_1.Form.input({value:this.fetchSettings("cacheSize"),pattern:"^([1-9][0-9]|[12][0-9]{2}|3[01][0-9]|320)$"},async(data,input)=>{input.get()[0].checkValidity()&&await this.pushSettings("cacheSize",parseInt(data))}),Form_1.Form.div({value:'<div class="unmargin">Number of items kept in the update cache. Must be at least 10, but no more than 320. Large values may lead to performance drops.</div>',width:2}),Form_1.Form.spacer(2),Form_1.Form.div({value:"Update Interval"}),Form_1.Form.select({value:updateInterval+""},{"-1":"Manually",1:"1 hour",6:"6 hours",12:"12 hours",24:"24 hours"},async data=>{(data=Math.max(parseFloat(data)*Util_1.Util.Time.HOUR,-1))<Util_1.Util.Time.HOUR&&-1!=data&&(data=Util_1.Util.Time.HOUR),await this.pushSettings("updateInterval",data),SubscriptionManager.trigger("timerRefresh")}),Form_1.Form.div({value:'<div class="unmargin">How often should the subscriptions be checked for updates.</div>',width:2}),Form_1.Form.spacer(2),Form_1.Form.div({value:"Cache Expiration"}),Form_1.Form.select({value:this.fetchSettings("cacheMaxAge")/Util_1.Util.Time.WEEK},{0:"Never",7:"1 week",2:"2 weeks",4:"1 month",24:"6 months"},async data=>{await this.pushSettings("cacheMaxAge",parseInt(data)*Util_1.Util.Time.WEEK),SubscriptionManager.trigger("timerRefresh")}),Form_1.Form.div({value:'<div class="unmargin">Updates older than this are removed automatically</div>',width:2})]),Form_1.Form.hr(2),Form_1.Form.section({name:"status",columns:2},[Form_1.Form.header("Other",2),Form_1.Form.div({value:"Last Update"}),Form_1.Form.div({value:$("<span>").attr("id","subscriptions-lastupdate").html("Initializing . . .")}),Form_1.Form.div({value:"Next Update"}),Form_1.Form.div({value:$("<span>").attr("id","subscriptions-nextupdate").html("Initializing . . .")}),Form_1.Form.button({value:'<i class="fas fa-sync-alt fa-xs fa-spin" id="subscription-action-update"></i> Manual Update'},()=>{SubscriptionManager.updateInProgress?Danbooru_1.Danbooru.notice("Update is already in progress"):SubscriptionManager.trigger("update")}),Form_1.Form.button({value:"Clear Cache"},()=>{this.trackers.forEach(async subscription=>{await subscription.instance.getCache().clear(),subscription.content[0].innerHTML=""})})])]);function makeSubSection(instance,columns){const $subsSection=$("<div>").addClass("subscriptions-manage-list col-"+columns),$badge=$("<span>");return executeSubUpdateEvent(),XM_1.XM.Storage.addListener("re621."+instance.getSettingsTag(),()=>{Debug_1.Debug.log("SubM: Subscriptions updated"),executeSubUpdateEvent()}),Form_1.Form.collapse({title:instance.getName(),columns:2,width:2,badge:$badge},[Form_1.Form.div({value:$subsSection,width:2})]);async function executeSubUpdateEvent(){const subData=await instance.fetchSettings("data",!0);var unordered;$subsSection.html(""),(unordered=subData,Object.keys(unordered).sort((a,b)=>{const aName=unordered[a].name?unordered[a].name.toLowerCase():"zzz_undefined",bName=unordered[b].name?unordered[b].name.toLowerCase():"zzz_undefined";return aName==bName?0:aName<bName?-1:1})).forEach(key=>{(function(instance,key,entry){const output=$("<item>");let currentlySubbed=!0;const heart=$("<i>").addClass("fas fa-heart");$("<a>").addClass("sub-manage-unsub").append(heart).appendTo(output).on("click",async event=>{event.preventDefault();const subData=await instance.fetchSettings("data",!0);currentlySubbed?(delete subData[key],Danbooru_1.Danbooru.notice("Successfully unsubscribed")):(subData[key]=entry,Danbooru_1.Danbooru.notice("Successfully subscribed")),instance.pushSettings("data",subData),currentlySubbed=!currentlySubbed,heart.toggleClass("fas far")});const link=$("<a>").html(entry.name?entry.name:key).appendTo(output);switch(instance.getName()){case"Pools":link.attr("href","/pools/"+key);break;case"Forums":link.attr("href","/forum_topics/"+key);break;case"Tags":link.attr("href","/posts?tags="+key);break;case"Comments":link.attr("href","/posts/"+key)}return output})(instance,key,subData[key]).appendTo($subsSection)}),$badge.html(Object.keys(subData).length+"")}}}async updateRequired(){const time=await this.fetchSettings(["lastUpdate","updateStarted","now","updateInterval"],!0);return void 0===time.now&&(time.now=Util_1.Util.Time.now()),Promise.resolve(!SubscriptionManager.updateInProgress&&-1!==time.updateInterval&&(time.now-time.lastUpdate>=time.updateInterval||0!==time.updateStarted&&time.now-time.updateStarted>=SubscriptionManager.updateTimeout))}async executeUpdateEvent(){SubscriptionManager.updateInProgress=!0;const now=Util_1.Util.Time.now(),prevUpdate=await this.fetchSettings("lastUpdate",!0);if(await this.pushSettings("updateStarted",now),SubscriptionManager.trigger("timerRefresh"),!navigator.onLine)return SubscriptionManager.updateInProgress=!1,void SubscriptionManager.trigger("timerRefresh");this.$openSubsButton.attr({"data-loading":"true","data-updates":"0"});const updateThreads=[];for(const trackerData of this.trackers.values())updateThreads.push(new Promise(async resolve=>{Debug_1.Debug.log("SubM: redrawing [update]"),trackerData.tabElement.attr("data-updates","0"),trackerData.tabElement.attr("data-loading","true"),trackerData.content[0].innerHTML="";const status=$("<div>").addClass("subscription-load-status").html("Loading . . .").appendTo(trackerData.content),cache=trackerData.instance.getCache();await cache.load(),await cache.update(prevUpdate,status),trackerData.tabElement.attr("data-loading","false"),await this.executeReloadEvent(trackerData),resolve()}));if(await Promise.all(updateThreads),SubscriptionManager.updateInProgress=!1,await this.pushSettings({lastUpdate:now,updateStarted:0}),SubscriptionManager.trigger("timerRefresh"),this.$openSubsButton.attr("data-loading","false"),this.refreshHeaderNotifications(),this.modal.isOpen()){const activeTab=this.tabs.tabs("option","active");window.setTimeout(()=>{this.clearTabNotification(activeTab)},1e3)}}async executeReloadEvent(trackerData){const cache=trackerData.instance.getCache();await cache.load(),Debug_1.Debug.log(`SubM${trackerData.tabIndex}: drawing ${cache.getSize()} items`),trackerData.content[0].innerHTML="",cache.getSize()>0&&trackerData.content.append(this.createCacheDivider());const clickAction=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings("clickAction");if(cache.forEach((content,timestamp)=>{trackerData.content.append(this.createUpdateEntry(timestamp,content,trackerData,clickAction))}),this.refreshTabNotifications(trackerData),this.refreshHeaderNotifications(),this.modal.isOpen()){const activeTab=this.tabs.tabs("option","active");window.setTimeout(()=>{this.clearTabNotification(activeTab)},1e3)}}async executeTimerRefreshEvent(){this.refreshSettings();const time=await this.fetchSettings(["lastUpdate","updateInterval","updateStarted"],!0);var lastUpdate,updateStarted,updateInterval;$("span#subscriptions-lastupdate").attr("title",(lastUpdate=time.lastUpdate,updateStarted=time.updateStarted,updateInterval=time.updateInterval,SubscriptionManager.updateInProgress?"":-1==updateInterval?"Never":0!==updateStarted?Util_1.Util.Time.format(updateStarted):0===lastUpdate?"":Util_1.Util.Time.format(lastUpdate))).html(function(lastUpdate,updateStarted,updateInterval){return SubscriptionManager.updateInProgress?"In progress . . .":-1==updateInterval?"Never":0!==updateStarted?Util_1.Util.Time.ago(updateStarted)+" (interrupted)":0===lastUpdate?"Never":Util_1.Util.Time.ago(lastUpdate)}(time.lastUpdate,time.updateStarted,time.updateInterval)),$("span#subscriptions-nextupdate").attr("title",function(lastUpdate,updateInterval,updateStarted){const now=Util_1.Util.Time.now();return SubscriptionManager.updateInProgress?"":-1==updateInterval?"Never":0!==updateStarted?Util_1.Util.Time.format(updateStarted+SubscriptionManager.updateTimeout):0===lastUpdate?Util_1.Util.Time.format(now+updateInterval):lastUpdate+updateInterval<now?"":Util_1.Util.Time.format(lastUpdate+updateInterval)}(time.lastUpdate,time.updateInterval,time.updateStarted)).html(function(lastUpdate,updateInterval,updateStarted){const now=Util_1.Util.Time.now();return SubscriptionManager.updateInProgress?"In progress . . .":-1==updateInterval?"Never":0!==updateStarted?Util_1.Util.Time.ago(updateStarted+SubscriptionManager.updateTimeout+Util_1.Util.Time.MINUTE):0===lastUpdate?Util_1.Util.Time.ago(now+updateInterval):lastUpdate+updateInterval<now?"Less than a minute":Util_1.Util.Time.ago(lastUpdate+updateInterval+Util_1.Util.Time.MINUTE)}(time.lastUpdate,time.updateInterval,time.updateStarted)),$("i#subscription-action-update").toggleClass("fa-spin",SubscriptionManager.updateInProgress)}refreshHeaderNotifications(){let totalCount=0;return this.trackers.forEach(subscription=>{totalCount+=parseInt(subscription.tabElement.attr("data-updates"))}),this.$openSubsButton.attr("data-updates",totalCount),totalCount}refreshTabNotifications(subscription){const curCount=subscription.content.find(".new").length;return subscription.content.attr("data-updates",curCount),subscription.tabElement.attr("data-updates",curCount),curCount}async clearTabNotification(tabIndex){const subscription=this.getTracker(tabIndex);if(void 0===subscription)return;const newItems=subscription.content.find(".new").get();for(const item of newItems)$(item).removeClass("new").addClass("new-viewed");this.refreshTabNotifications(subscription),this.refreshHeaderNotifications();const cache=subscription.instance.getCache();let cleared=0;cache.forEach(entry=>(entry.new&&cleared++,delete entry.new,entry)),cleared>0&&await cache.save()}addSubscribeButtons(instance){let subscriptionData=instance.fetchSettings("data");const elements=instance.getButtonAttachment().get();for(const element of elements){const $element=$(element);if($element.find("button.subscribe, a.subscribe").length>0)continue;const id=instance.getSubscriberId($element),$subscribeButton=instance.makeSubscribeButton(),$unsubscribeButton=instance.makeUnsubscribeButton();void 0===subscriptionData[id]?$unsubscribeButton.addClass("display-none"):$subscribeButton.addClass("display-none"),instance.insertButton($element,$subscribeButton),instance.insertButton($element,$unsubscribeButton);let processing=!1;$subscribeButton.click(async event=>{event.preventDefault(),processing||(processing=!0,execSubscribe(id,$subscribeButton,$unsubscribeButton,$element).then(()=>{processing=!1}))}),$unsubscribeButton.click(async event=>{event.preventDefault(),processing||(processing=!0,execUnsubscribe(id,$subscribeButton,$unsubscribeButton).then(()=>{processing=!1}))})}async function execSubscribe(id,$subscribeButton,$unsubscribeButton,$element){return subscriptionData=await instance.fetchSettings("data",!0),Object.keys(subscriptionData).length>=instance.maxSubscriptions?(Danbooru_1.Danbooru.error(`Error: Maximum number of subscriptions reached (${instance.maxSubscriptions})`),Promise.resolve(!1)):(subscriptionData[id]={name:instance.getSubscriberName($element)},subscriptionData=sortSubscriptions(subscriptionData),$subscribeButton.addClass("display-none"),$unsubscribeButton.removeClass("display-none"),instance.pushSettings("data",subscriptionData))}async function execUnsubscribe(id,$subscribeButton,$unsubscribeButton){return subscriptionData=await instance.fetchSettings("data",!0),delete subscriptionData[id],subscriptionData=sortSubscriptions(subscriptionData),$subscribeButton.removeClass("display-none"),$unsubscribeButton.addClass("display-none"),instance.pushSettings("data",subscriptionData)}function sortSubscriptions(unordered){const ordered={};return Object.keys(unordered).sort().forEach((function(key){ordered[key]=unordered[key]})),ordered}}createCacheDivider(){return $("<div>").addClass("subscription-update notice notice-cached").html('<div class="subscription-update-title">Older Updates</div>')}createUpdateEntry(timestamp,data,subscription,clickAction){const actions=subscription.instance.updateActions,cache=subscription.instance.getCache(),$content=$("<div>").addClass("subscription-update"+(data.new?" new":"")),timeAgo=Util_1.Util.Time.ago(timestamp),timeString=new Date(timestamp).toLocaleString(),$imageDiv=$("<div>").addClass("subscription-update-preview").appendTo($content),$image=$("<img>").attr({src:DomUtilities_1.DomUtilities.getPlaceholderImage(),"data-src":actions.imageSrc(data),title:actions.updateText(data)+"\n"+timeAgo+"\n"+timeString}).addClass("lazyload").on("error",()=>{actions.imageRemoveOnError&&($content.remove(),cache.deleteItem(timestamp),cache.save())});if(void 0===actions.imageHref)$image.appendTo($imageDiv);else{const $link=$("<a>").addClass("subscription-update-thumbnail").attr("href",actions.imageHref(data)).appendTo($imageDiv).append($image);let dbclickTimer,prevent=!1;$link.on("click.re621.thumbnail",event=>{0===event.button&&(event.preventDefault(),dbclickTimer=window.setTimeout(()=>{prevent||($link.off("click.re621.thumbnail"),$link[0].click()),prevent=!1},200))}).on("dblclick.re621.thumbnail",event=>{0===event.button&&(event.preventDefault(),window.clearTimeout(dbclickTimer),prevent=!0,clickAction===BetterSearch_1.ImageClickAction.NewTab?XM_1.XM.Util.openInTab(window.location.origin+$link.attr("href"),!1):($link.off("click.re621.thumbnail"),$link[0].click()))})}const $title=$("<div>").addClass("subscription-update-title").appendTo($content);void 0===actions.updateHref?$("<div>").html(actions.updateText(data)).attr("data-id",data.id).appendTo($title):$("<a>").html(actions.updateText(data)).attr({href:actions.updateHref(data),"data-id":data.id}).appendTo($title),data.nameExtra&&$("<span>").addClass("subscriptions-update-title-extra").html(data.nameExtra).appendTo($title);const $remove=$("<div>").addClass("subscription-update-remove").appendTo($content);$("<a>").addClass("sub-"+subscription.tabIndex+"-remove").attr("title","Remove").html('<i class="fas fa-times"></i>').appendTo($remove).click(async event=>{event.preventDefault();const $buttons=$("a.sub-"+subscription.tabIndex+"-remove");$buttons.css("visibility","hidden"),cache.deleteItem(timestamp),await cache.save(),$buttons.css("visibility",""),$content.css("display","none")});const $full=$("<div>").addClass("subscription-update-full").appendTo($content);void 0===actions.sourceHref?$("<div>").html(actions.sourceText(data)).appendTo($full):$("<a>").attr("href",actions.sourceHref(data)).html(actions.sourceText(data)).appendTo($full);const $date=$("<div>").addClass("subscription-update-date").appendTo($content);return $("<span>").html(timeAgo).attr("title",timeString).appendTo($date),$content}openNotifications(){$("a#header-button-notifications")[0].click()}}exports.SubscriptionManager=SubscriptionManager,SubscriptionManager.cacheVersion=1,SubscriptionManager.updateInProgress=!1,SubscriptionManager.updateTimeout=5*Util_1.Util.Time.MINUTE},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/XM":6,"../../components/structure/DomUtilities":25,"../../components/structure/Form":26,"../../components/structure/Modal":27,"../../components/structure/Tabbed":29,"../../components/utility/Debug":30,"../../components/utility/Util":33,"../search/BetterSearch":55}],67:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UpdateCache=void 0;const XM_1=require("../../components/api/XM"),ModuleController_1=require("../../components/ModuleController"),Util_1=require("../../components/utility/Util"),SubscriptionManager_1=require("./SubscriptionManager");exports.UpdateCache=class{constructor(instance){this.instance=instance,this.data={},this.updateIndex()}getStorageTag(){return"re621."+this.instance.getSettingsTag()+".cache"}async load(){return this.data=await XM_1.XM.Storage.getValue(this.getStorageTag(),{}),this.updateIndex(),Promise.resolve(!0)}async update(lastUpdate,status){const updates=await this.instance.getUpdatedEntries(lastUpdate,status);return Object.keys(updates).length>0?(this.push(updates),this.save()):Promise.resolve(!1)}async save(){return XM_1.XM.Storage.setValue(this.getStorageTag(),this.data)}async clear(){return this.data={},this.updateIndex(),this.save()}getIndex(){return this.index}getSize(){return this.index.length}getItem(timestamp){return this.data[timestamp]}deleteItem(timestamp){const el=this.index.indexOf(timestamp);-1!==el&&(this.index.splice(el,1),delete this.data[timestamp])}push(newData){Object.keys(newData).forEach(key=>{this.data[key]=newData[key]}),this.updateIndex(),this.trim()}updateIndex(){this.index=Object.keys(this.data).map(x=>parseInt(x)).sort((a,b)=>b-a)}trim(){const params=ModuleController_1.ModuleController.get(SubscriptionManager_1.SubscriptionManager).fetchSettings(["cacheMaxAge","cacheSize"]),ageLimit=0===params.cacheMaxAge?0:Util_1.Util.Time.now()-params.cacheMaxAge,uniqueKeys=[];this.index.forEach(timestamp=>{const update=this.data[timestamp];timestamp<ageLimit&&!update.new?delete this.data[timestamp]:-1===uniqueKeys.indexOf(update.id)?uniqueKeys.push(update.id):delete this.data[timestamp]}),this.updateIndex();const chunks=Util_1.Util.chunkArray(this.index,params.cacheSize,!0);this.index=chunks[0],chunks[1].forEach(entry=>{delete this.data[entry]})}forEach(fn){this.index.forEach(timestamp=>{const result=fn(this.data[timestamp],timestamp);void 0!==result&&(this.data[timestamp]=result)})}}},{"../../components/ModuleController":1,"../../components/api/XM":6,"../../components/utility/Util":33,"./SubscriptionManager":66}],68:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TagTracker=void 0;const E621_1=require("../../components/api/E621"),Blacklist_1=require("../../components/data/Blacklist"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),SubscriptionManager_1=require("./SubscriptionManager"),SubscriptionTracker_1=require("./SubscriptionTracker");class TagTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:data=>Post_1.PostData.createPreviewUrlFromMd5(data.md5),imageHref:data=>"/posts/"+data.id,imageRemoveOnError:!0,updateText:data=>data.name,sourceHref:data=>"/posts?tags="+encodeURIComponent(data.name.replace(/ /g,"_")),sourceText:()=>"View Tag"},this.subBatchSize=40,this.maxSubscriptions=1200,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Tags"}makeSubscribeButton(){return $("<a>").attr({href:"#",title:"Subscribe"}).addClass("tag-subscription-button subscribe").html('<i class="far fa-heart"></i>')}makeUnsubscribeButton(){return $("<a>").attr({href:"#",title:"Unsubscribe"}).addClass("tag-subscription-button unsubscribe").html('<i class="fas fa-heart"></i>')}getButtonAttachment(){return $("#tag-box li span.tag-action-subscribe, #tag-list li span.tag-action-subscribe")}insertButton($element,$button){$element.append($button)}getSubscriberId($element){return $element.parent().attr("data-tag")}getSubscriberName($element){return $element.parent().attr("data-tag").replace(/_/g," ")}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),apiResult={};for(const[index,chunk]of storedSubChunks.entries()){storedSubChunks.length>1&&status.append(`<div> - processing batch #${index}</div>`),10==index&&status.append('<div><span style="color:gold">warning</span> connection throttled</div>');for(const post of await E621_1.E621.Posts.get({tags:chunk.map(el=>"~"+el),limit:320},index<10?500:1e3)){const timestamp=new Date(post.created_at).getTime();if(timestamp<lastUpdate)break;apiResult[timestamp]=post}}Debug_1.Debug.log(apiResult),status.append("<div>. . . formatting output</div>");const postLimit=ModuleController_1.ModuleController.get(SubscriptionManager_1.SubscriptionManager).fetchSettings("cacheSize");for(const key of Object.keys(apiResult).sort()){if(Object.keys(results).length>postLimit){Debug_1.Debug.log("TgT: postlimit");break}const post=Post_1.PostData.fromAPI(apiResult[key]);Debug_1.Debug.log(`TgT: ${post.id} ${Util_1.Util.Time.format(new Date(post.date.raw))}`),Blacklist_1.Blacklist.addPost(post),Blacklist_1.Blacklist.checkPost(post.id,!0)?Debug_1.Debug.log("TgT: blacklist"):results[new Date(post.date.raw).getTime()]=await this.formatPostUpdate(post)}return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatPostUpdate(value){return{id:value.id,name:"post #"+value.id,md5:"swf"===value.file.ext?"":value.file.md5,new:!0}}}exports.TagTracker=TagTracker},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Blacklist":14,"../../components/post/Post":19,"../../components/utility/Debug":30,"../../components/utility/Util":33,"./SubscriptionManager":66,"./SubscriptionTracker":67}],69:[function(require,module,exports){
/*!
* jQuery JavaScript Library v3.5.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2020-05-04T22:49Z
*/
!function(global,factory){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=global.document?factory(global,!0):function(w){if(!w.document)throw new Error("jQuery requires a window with a document");return factory(w)}:factory(global)}("undefined"!=typeof window?window:this,(function(window,noGlobal){"use strict";var arr=[],getProto=Object.getPrototypeOf,slice=arr.slice,flat=arr.flat?function(array){return arr.flat.call(array)}:function(array){return arr.concat.apply([],array)},push=arr.push,indexOf=arr.indexOf,class2type={},toString=class2type.toString,hasOwn=class2type.hasOwnProperty,fnToString=hasOwn.toString,ObjectFunctionString=fnToString.call(Object),support={},isFunction=function(obj){return"function"==typeof obj&&"number"!=typeof obj.nodeType},isWindow=function(obj){return null!=obj&&obj===obj.window},document=window.document,preservedScriptAttributes={type:!0,src:!0,nonce:!0,noModule:!0};function DOMEval(code,node,doc){var i,val,script=(doc=doc||document).createElement("script");if(script.text=code,node)for(i in preservedScriptAttributes)(val=node[i]||node.getAttribute&&node.getAttribute(i))&&script.setAttribute(i,val);doc.head.appendChild(script).parentNode.removeChild(script)}function toType(obj){return null==obj?obj+"":"object"==typeof obj||"function"==typeof obj?class2type[toString.call(obj)]||"object":typeof obj}var jQuery=function(selector,context){return new jQuery.fn.init(selector,context)};function isArrayLike(obj){var length=!!obj&&"length"in obj&&obj.length,type=toType(obj);return!isFunction(obj)&&!isWindow(obj)&&("array"===type||0===length||"number"==typeof length&&length>0&&length-1 in obj)}jQuery.fn=jQuery.prototype={jquery:"3.5.1",constructor:jQuery,length:0,toArray:function(){return slice.call(this)},get:function(num){return null==num?slice.call(this):num<0?this[num+this.length]:this[num]},pushStack:function(elems){var ret=jQuery.merge(this.constructor(),elems);return ret.prevObject=this,ret},each:function(callback){return jQuery.each(this,callback)},map:function(callback){return this.pushStack(jQuery.map(this,(function(elem,i){return callback.call(elem,i,elem)})))},slice:function(){return this.pushStack(slice.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(jQuery.grep(this,(function(_elem,i){return(i+1)%2})))},odd:function(){return this.pushStack(jQuery.grep(this,(function(_elem,i){return i%2})))},eq:function(i){var len=this.length,j=+i+(i<0?len:0);return this.pushStack(j>=0&&j<len?[this[j]]:[])},end:function(){return this.prevObject||this.constructor()},push:push,sort:arr.sort,splice:arr.splice},jQuery.extend=jQuery.fn.extend=function(){var options,name,src,copy,copyIsArray,clone,target=arguments[0]||{},i=1,length=arguments.length,deep=!1;for("boolean"==typeof target&&(deep=target,target=arguments[i]||{},i++),"object"==typeof target||isFunction(target)||(target={}),i===length&&(target=this,i--);i<length;i++)if(null!=(options=arguments[i]))for(name in options)copy=options[name],"__proto__"!==name&&target!==copy&&(deep&©&&(jQuery.isPlainObject(copy)||(copyIsArray=Array.isArray(copy)))?(src=target[name],clone=copyIsArray&&!Array.isArray(src)?[]:copyIsArray||jQuery.isPlainObject(src)?src:{},copyIsArray=!1,target[name]=jQuery.extend(deep,clone,copy)):void 0!==copy&&(target[name]=copy));return target},jQuery.extend({expando:"jQuery"+("3.5.1"+Math.random()).replace(/\D/g,""),isReady:!0,error:function(msg){throw new Error(msg)},noop:function(){},isPlainObject:function(obj){var proto,Ctor;return!(!obj||"[object Object]"!==toString.call(obj))&&(!(proto=getProto(obj))||"function"==typeof(Ctor=hasOwn.call(proto,"constructor")&&proto.constructor)&&fnToString.call(Ctor)===ObjectFunctionString)},isEmptyObject:function(obj){var name;for(name in obj)return!1;return!0},globalEval:function(code,options,doc){DOMEval(code,{nonce:options&&options.nonce},doc)},each:function(obj,callback){var length,i=0;if(isArrayLike(obj))for(length=obj.length;i<length&&!1!==callback.call(obj[i],i,obj[i]);i++);else for(i in obj)if(!1===callback.call(obj[i],i,obj[i]))break;return obj},makeArray:function(arr,results){var ret=results||[];return null!=arr&&(isArrayLike(Object(arr))?jQuery.merge(ret,"string"==typeof arr?[arr]:arr):push.call(ret,arr)),ret},inArray:function(elem,arr,i){return null==arr?-1:indexOf.call(arr,elem,i)},merge:function(first,second){for(var len=+second.length,j=0,i=first.length;j<len;j++)first[i++]=second[j];return first.length=i,first},grep:function(elems,callback,invert){for(var matches=[],i=0,length=elems.length,callbackExpect=!invert;i<length;i++)!callback(elems[i],i)!==callbackExpect&&matches.push(elems[i]);return matches},map:function(elems,callback,arg){var length,value,i=0,ret=[];if(isArrayLike(elems))for(length=elems.length;i<length;i++)null!=(value=callback(elems[i],i,arg))&&ret.push(value);else for(i in elems)null!=(value=callback(elems[i],i,arg))&&ret.push(value);return flat(ret)},guid:1,support:support}),"function"==typeof Symbol&&(jQuery.fn[Symbol.iterator]=arr[Symbol.iterator]),jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),(function(_i,name){class2type["[object "+name+"]"]=name.toLowerCase()}));var Sizzle=
/*!
* Sizzle CSS Selector Engine v2.3.5
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://js.foundation/
*
* Date: 2020-03-14
*/
function(window){var i,support,Expr,getText,isXML,tokenize,compile,select,outermostContext,sortInput,hasDuplicate,setDocument,document,docElem,documentIsHTML,rbuggyQSA,rbuggyMatches,matches,contains,expando="sizzle"+1*new Date,preferredDoc=window.document,dirruns=0,done=0,classCache=createCache(),tokenCache=createCache(),compilerCache=createCache(),nonnativeSelectorCache=createCache(),sortOrder=function(a,b){return a===b&&(hasDuplicate=!0),0},hasOwn={}.hasOwnProperty,arr=[],pop=arr.pop,pushNative=arr.push,push=arr.push,slice=arr.slice,indexOf=function(list,elem){for(var i=0,len=list.length;i<len;i++)if(list[i]===elem)return i;return-1},booleans="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",whitespace="[\\x20\\t\\r\\n\\f]",identifier="(?:\\\\[\\da-fA-F]{1,6}"+whitespace+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",attributes="\\["+whitespace+"*("+identifier+")(?:"+whitespace+"*([*^$|!~]?=)"+whitespace+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+identifier+"))|)"+whitespace+"*\\]",pseudos=":("+identifier+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+attributes+")*)|.*)\\)|)",rwhitespace=new RegExp(whitespace+"+","g"),rtrim=new RegExp("^"+whitespace+"+|((?:^|[^\\\\])(?:\\\\.)*)"+whitespace+"+$","g"),rcomma=new RegExp("^"+whitespace+"*,"+whitespace+"*"),rcombinators=new RegExp("^"+whitespace+"*([>+~]|"+whitespace+")"+whitespace+"*"),rdescend=new RegExp(whitespace+"|>"),rpseudo=new RegExp(pseudos),ridentifier=new RegExp("^"+identifier+"$"),matchExpr={ID:new RegExp("^#("+identifier+")"),CLASS:new RegExp("^\\.("+identifier+")"),TAG:new RegExp("^("+identifier+"|[*])"),ATTR:new RegExp("^"+attributes),PSEUDO:new RegExp("^"+pseudos),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+whitespace+"*(even|odd|(([+-]|)(\\d*)n|)"+whitespace+"*(?:([+-]|)"+whitespace+"*(\\d+)|))"+whitespace+"*\\)|)","i"),bool:new RegExp("^(?:"+booleans+")$","i"),needsContext:new RegExp("^"+whitespace+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+whitespace+"*((?:-\\d)?\\d*)"+whitespace+"*\\)|)(?=[^-]|$)","i")},rhtml=/HTML$/i,rinputs=/^(?:input|select|textarea|button)$/i,rheader=/^h\d$/i,rnative=/^[^{]+\{\s*\[native \w/,rquickExpr=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,rsibling=/[+~]/,runescape=new RegExp("\\\\[\\da-fA-F]{1,6}"+whitespace+"?|\\\\([^\\r\\n\\f])","g"),funescape=function(escape,nonHex){var high="0x"+escape.slice(1)-65536;return nonHex||(high<0?String.fromCharCode(high+65536):String.fromCharCode(high>>10|55296,1023&high|56320))},rcssescape=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,fcssescape=function(ch,asCodePoint){return asCodePoint?"\0"===ch?"�":ch.slice(0,-1)+"\\"+ch.charCodeAt(ch.length-1).toString(16)+" ":"\\"+ch},unloadHandler=function(){setDocument()},inDisabledFieldset=addCombinator((function(elem){return!0===elem.disabled&&"fieldset"===elem.nodeName.toLowerCase()}),{dir:"parentNode",next:"legend"});try{push.apply(arr=slice.call(preferredDoc.childNodes),preferredDoc.childNodes),arr[preferredDoc.childNodes.length].nodeType}catch(e){push={apply:arr.length?function(target,els){pushNative.apply(target,slice.call(els))}:function(target,els){for(var j=target.length,i=0;target[j++]=els[i++];);target.length=j-1}}}function Sizzle(selector,context,results,seed){var m,i,elem,nid,match,groups,newSelector,newContext=context&&context.ownerDocument,nodeType=context?context.nodeType:9;if(results=results||[],"string"!=typeof selector||!selector||1!==nodeType&&9!==nodeType&&11!==nodeType)return results;if(!seed&&(setDocument(context),context=context||document,documentIsHTML)){if(11!==nodeType&&(match=rquickExpr.exec(selector)))if(m=match[1]){if(9===nodeType){if(!(elem=context.getElementById(m)))return results;if(elem.id===m)return results.push(elem),results}else if(newContext&&(elem=newContext.getElementById(m))&&contains(context,elem)&&elem.id===m)return results.push(elem),results}else{if(match[2])return push.apply(results,context.getElementsByTagName(selector)),results;if((m=match[3])&&support.getElementsByClassName&&context.getElementsByClassName)return push.apply(results,context.getElementsByClassName(m)),results}if(support.qsa&&!nonnativeSelectorCache[selector+" "]&&(!rbuggyQSA||!rbuggyQSA.test(selector))&&(1!==nodeType||"object"!==context.nodeName.toLowerCase())){if(newSelector=selector,newContext=context,1===nodeType&&(rdescend.test(selector)||rcombinators.test(selector))){for((newContext=rsibling.test(selector)&&testContext(context.parentNode)||context)===context&&support.scope||((nid=context.getAttribute("id"))?nid=nid.replace(rcssescape,fcssescape):context.setAttribute("id",nid=expando)),i=(groups=tokenize(selector)).length;i--;)groups[i]=(nid?"#"+nid:":scope")+" "+toSelector(groups[i]);newSelector=groups.join(",")}try{return push.apply(results,newContext.querySelectorAll(newSelector)),results}catch(qsaError){nonnativeSelectorCache(selector,!0)}finally{nid===expando&&context.removeAttribute("id")}}}return select(selector.replace(rtrim,"$1"),context,results,seed)}function createCache(){var keys=[];return function cache(key,value){return keys.push(key+" ")>Expr.cacheLength&&delete cache[keys.shift()],cache[key+" "]=value}}function markFunction(fn){return fn[expando]=!0,fn}function assert(fn){var el=document.createElement("fieldset");try{return!!fn(el)}catch(e){return!1}finally{el.parentNode&&el.parentNode.removeChild(el),el=null}}function addHandle(attrs,handler){for(var arr=attrs.split("|"),i=arr.length;i--;)Expr.attrHandle[arr[i]]=handler}function siblingCheck(a,b){var cur=b&&a,diff=cur&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(diff)return diff;if(cur)for(;cur=cur.nextSibling;)if(cur===b)return-1;return a?1:-1}function createInputPseudo(type){return function(elem){return"input"===elem.nodeName.toLowerCase()&&elem.type===type}}function createButtonPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return("input"===name||"button"===name)&&elem.type===type}}function createDisabledPseudo(disabled){return function(elem){return"form"in elem?elem.parentNode&&!1===elem.disabled?"label"in elem?"label"in elem.parentNode?elem.parentNode.disabled===disabled:elem.disabled===disabled:elem.isDisabled===disabled||elem.isDisabled!==!disabled&&inDisabledFieldset(elem)===disabled:elem.disabled===disabled:"label"in elem&&elem.disabled===disabled}}function createPositionalPseudo(fn){return markFunction((function(argument){return argument=+argument,markFunction((function(seed,matches){for(var j,matchIndexes=fn([],seed.length,argument),i=matchIndexes.length;i--;)seed[j=matchIndexes[i]]&&(seed[j]=!(matches[j]=seed[j]))}))}))}function testContext(context){return context&&void 0!==context.getElementsByTagName&&context}for(i in support=Sizzle.support={},isXML=Sizzle.isXML=function(elem){var namespace=elem.namespaceURI,docElem=(elem.ownerDocument||elem).documentElement;return!rhtml.test(namespace||docElem&&docElem.nodeName||"HTML")},setDocument=Sizzle.setDocument=function(node){var hasCompare,subWindow,doc=node?node.ownerDocument||node:preferredDoc;return doc!=document&&9===doc.nodeType&&doc.documentElement?(docElem=(document=doc).documentElement,documentIsHTML=!isXML(document),preferredDoc!=document&&(subWindow=document.defaultView)&&subWindow.top!==subWindow&&(subWindow.addEventListener?subWindow.addEventListener("unload",unloadHandler,!1):subWindow.attachEvent&&subWindow.attachEvent("onunload",unloadHandler)),support.scope=assert((function(el){return docElem.appendChild(el).appendChild(document.createElement("div")),void 0!==el.querySelectorAll&&!el.querySelectorAll(":scope fieldset div").length})),support.attributes=assert((function(el){return el.className="i",!el.getAttribute("className")})),support.getElementsByTagName=assert((function(el){return el.appendChild(document.createComment("")),!el.getElementsByTagName("*").length})),support.getElementsByClassName=rnative.test(document.getElementsByClassName),support.getById=assert((function(el){return docElem.appendChild(el).id=expando,!document.getElementsByName||!document.getElementsByName(expando).length})),support.getById?(Expr.filter.ID=function(id){var attrId=id.replace(runescape,funescape);return function(elem){return elem.getAttribute("id")===attrId}},Expr.find.ID=function(id,context){if(void 0!==context.getElementById&&documentIsHTML){var elem=context.getElementById(id);return elem?[elem]:[]}}):(Expr.filter.ID=function(id){var attrId=id.replace(runescape,funescape);return function(elem){var node=void 0!==elem.getAttributeNode&&elem.getAttributeNode("id");return node&&node.value===attrId}},Expr.find.ID=function(id,context){if(void 0!==context.getElementById&&documentIsHTML){var node,i,elems,elem=context.getElementById(id);if(elem){if((node=elem.getAttributeNode("id"))&&node.value===id)return[elem];for(elems=context.getElementsByName(id),i=0;elem=elems[i++];)if((node=elem.getAttributeNode("id"))&&node.value===id)return[elem]}return[]}}),Expr.find.TAG=support.getElementsByTagName?function(tag,context){return void 0!==context.getElementsByTagName?context.getElementsByTagName(tag):support.qsa?context.querySelectorAll(tag):void 0}:function(tag,context){var elem,tmp=[],i=0,results=context.getElementsByTagName(tag);if("*"===tag){for(;elem=results[i++];)1===elem.nodeType&&tmp.push(elem);return tmp}return results},Expr.find.CLASS=support.getElementsByClassName&&function(className,context){if(void 0!==context.getElementsByClassName&&documentIsHTML)return context.getElementsByClassName(className)},rbuggyMatches=[],rbuggyQSA=[],(support.qsa=rnative.test(document.querySelectorAll))&&(assert((function(el){var input;docElem.appendChild(el).innerHTML="<a id='"+expando+"'></a><select id='"+expando+"-\r\\' msallowcapture=''><option selected=''></option></select>",el.querySelectorAll("[msallowcapture^='']").length&&rbuggyQSA.push("[*^$]="+whitespace+"*(?:''|\"\")"),el.querySelectorAll("[selected]").length||rbuggyQSA.push("\\["+whitespace+"*(?:value|"+booleans+")"),el.querySelectorAll("[id~="+expando+"-]").length||rbuggyQSA.push("~="),(input=document.createElement("input")).setAttribute("name",""),el.appendChild(input),el.querySelectorAll("[name='']").length||rbuggyQSA.push("\\["+whitespace+"*name"+whitespace+"*="+whitespace+"*(?:''|\"\")"),el.querySelectorAll(":checked").length||rbuggyQSA.push(":checked"),el.querySelectorAll("a#"+expando+"+*").length||rbuggyQSA.push(".#.+[+~]"),el.querySelectorAll("\\\f"),rbuggyQSA.push("[\\r\\n\\f]")})),assert((function(el){el.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var input=document.createElement("input");input.setAttribute("type","hidden"),el.appendChild(input).setAttribute("name","D"),el.querySelectorAll("[name=d]").length&&rbuggyQSA.push("name"+whitespace+"*[*^$|!~]?="),2!==el.querySelectorAll(":enabled").length&&rbuggyQSA.push(":enabled",":disabled"),docElem.appendChild(el).disabled=!0,2!==el.querySelectorAll(":disabled").length&&rbuggyQSA.push(":enabled",":disabled"),el.querySelectorAll("*,:x"),rbuggyQSA.push(",.*:")}))),(support.matchesSelector=rnative.test(matches=docElem.matches||docElem.webkitMatchesSelector||docElem.mozMatchesSelector||docElem.oMatchesSelector||docElem.msMatchesSelector))&&assert((function(el){support.disconnectedMatch=matches.call(el,"*"),matches.call(el,"[s!='']:x"),rbuggyMatches.push("!=",pseudos)})),rbuggyQSA=rbuggyQSA.length&&new RegExp(rbuggyQSA.join("|")),rbuggyMatches=rbuggyMatches.length&&new RegExp(rbuggyMatches.join("|")),hasCompare=rnative.test(docElem.compareDocumentPosition),contains=hasCompare||rnative.test(docElem.contains)?function(a,b){var adown=9===a.nodeType?a.documentElement:a,bup=b&&b.parentNode;return a===bup||!(!bup||1!==bup.nodeType||!(adown.contains?adown.contains(bup):a.compareDocumentPosition&&16&a.compareDocumentPosition(bup)))}:function(a,b){if(b)for(;b=b.parentNode;)if(b===a)return!0;return!1},sortOrder=hasCompare?function(a,b){if(a===b)return hasDuplicate=!0,0;var compare=!a.compareDocumentPosition-!b.compareDocumentPosition;return compare||(1&(compare=(a.ownerDocument||a)==(b.ownerDocument||b)?a.compareDocumentPosition(b):1)||!support.sortDetached&&b.compareDocumentPosition(a)===compare?a==document||a.ownerDocument==preferredDoc&&contains(preferredDoc,a)?-1:b==document||b.ownerDocument==preferredDoc&&contains(preferredDoc,b)?1:sortInput?indexOf(sortInput,a)-indexOf(sortInput,b):0:4&compare?-1:1)}:function(a,b){if(a===b)return hasDuplicate=!0,0;var cur,i=0,aup=a.parentNode,bup=b.parentNode,ap=[a],bp=[b];if(!aup||!bup)return a==document?-1:b==document?1:aup?-1:bup?1:sortInput?indexOf(sortInput,a)-indexOf(sortInput,b):0;if(aup===bup)return siblingCheck(a,b);for(cur=a;cur=cur.parentNode;)ap.unshift(cur);for(cur=b;cur=cur.parentNode;)bp.unshift(cur);for(;ap[i]===bp[i];)i++;return i?siblingCheck(ap[i],bp[i]):ap[i]==preferredDoc?-1:bp[i]==preferredDoc?1:0},document):document},Sizzle.matches=function(expr,elements){return Sizzle(expr,null,null,elements)},Sizzle.matchesSelector=function(elem,expr){if(setDocument(elem),support.matchesSelector&&documentIsHTML&&!nonnativeSelectorCache[expr+" "]&&(!rbuggyMatches||!rbuggyMatches.test(expr))&&(!rbuggyQSA||!rbuggyQSA.test(expr)))try{var ret=matches.call(elem,expr);if(ret||support.disconnectedMatch||elem.document&&11!==elem.document.nodeType)return ret}catch(e){nonnativeSelectorCache(expr,!0)}return Sizzle(expr,document,null,[elem]).length>0},Sizzle.contains=function(context,elem){return(context.ownerDocument||context)!=document&&setDocument(context),contains(context,elem)},Sizzle.attr=function(elem,name){(elem.ownerDocument||elem)!=document&&setDocument(elem);var fn=Expr.attrHandle[name.toLowerCase()],val=fn&&hasOwn.call(Expr.attrHandle,name.toLowerCase())?fn(elem,name,!documentIsHTML):void 0;return void 0!==val?val:support.attributes||!documentIsHTML?elem.getAttribute(name):(val=elem.getAttributeNode(name))&&val.specified?val.value:null},Sizzle.escape=function(sel){return(sel+"").replace(rcssescape,fcssescape)},Sizzle.error=function(msg){throw new Error("Syntax error, unrecognized expression: "+msg)},Sizzle.uniqueSort=function(results){var elem,duplicates=[],j=0,i=0;if(hasDuplicate=!support.detectDuplicates,sortInput=!support.sortStable&&results.slice(0),results.sort(sortOrder),hasDuplicate){for(;elem=results[i++];)elem===results[i]&&(j=duplicates.push(i));for(;j--;)results.splice(duplicates[j],1)}return sortInput=null,results},getText=Sizzle.getText=function(elem){var node,ret="",i=0,nodeType=elem.nodeType;if(nodeType){if(1===nodeType||9===nodeType||11===nodeType){if("string"==typeof elem.textContent)return elem.textContent;for(elem=elem.firstChild;elem;elem=elem.nextSibling)ret+=getText(elem)}else if(3===nodeType||4===nodeType)return elem.nodeValue}else for(;node=elem[i++];)ret+=getText(node);return ret},(Expr=Sizzle.selectors={cacheLength:50,createPseudo:markFunction,match:matchExpr,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(match){return match[1]=match[1].replace(runescape,funescape),match[3]=(match[3]||match[4]||match[5]||"").replace(runescape,funescape),"~="===match[2]&&(match[3]=" "+match[3]+" "),match.slice(0,4)},CHILD:function(match){return match[1]=match[1].toLowerCase(),"nth"===match[1].slice(0,3)?(match[3]||Sizzle.error(match[0]),match[4]=+(match[4]?match[5]+(match[6]||1):2*("even"===match[3]||"odd"===match[3])),match[5]=+(match[7]+match[8]||"odd"===match[3])):match[3]&&Sizzle.error(match[0]),match},PSEUDO:function(match){var excess,unquoted=!match[6]&&match[2];return matchExpr.CHILD.test(match[0])?null:(match[3]?match[2]=match[4]||match[5]||"":unquoted&&rpseudo.test(unquoted)&&(excess=tokenize(unquoted,!0))&&(excess=unquoted.indexOf(")",unquoted.length-excess)-unquoted.length)&&(match[0]=match[0].slice(0,excess),match[2]=unquoted.slice(0,excess)),match.slice(0,3))}},filter:{TAG:function(nodeNameSelector){var nodeName=nodeNameSelector.replace(runescape,funescape).toLowerCase();return"*"===nodeNameSelector?function(){return!0}:function(elem){return elem.nodeName&&elem.nodeName.toLowerCase()===nodeName}},CLASS:function(className){var pattern=classCache[className+" "];return pattern||(pattern=new RegExp("(^|"+whitespace+")"+className+"("+whitespace+"|$)"))&&classCache(className,(function(elem){return pattern.test("string"==typeof elem.className&&elem.className||void 0!==elem.getAttribute&&elem.getAttribute("class")||"")}))},ATTR:function(name,operator,check){return function(elem){var result=Sizzle.attr(elem,name);return null==result?"!="===operator:!operator||(result+="","="===operator?result===check:"!="===operator?result!==check:"^="===operator?check&&0===result.indexOf(check):"*="===operator?check&&result.indexOf(check)>-1:"$="===operator?check&&result.slice(-check.length)===check:"~="===operator?(" "+result.replace(rwhitespace," ")+" ").indexOf(check)>-1:"|="===operator&&(result===check||result.slice(0,check.length+1)===check+"-"))}},CHILD:function(type,what,_argument,first,last){var simple="nth"!==type.slice(0,3),forward="last"!==type.slice(-4),ofType="of-type"===what;return 1===first&&0===last?function(elem){return!!elem.parentNode}:function(elem,_context,xml){var cache,uniqueCache,outerCache,node,nodeIndex,start,dir=simple!==forward?"nextSibling":"previousSibling",parent=elem.parentNode,name=ofType&&elem.nodeName.toLowerCase(),useCache=!xml&&!ofType,diff=!1;if(parent){if(simple){for(;dir;){for(node=elem;node=node[dir];)if(ofType?node.nodeName.toLowerCase()===name:1===node.nodeType)return!1;start=dir="only"===type&&!start&&"nextSibling"}return!0}if(start=[forward?parent.firstChild:parent.lastChild],forward&&useCache){for(diff=(nodeIndex=(cache=(uniqueCache=(outerCache=(node=parent)[expando]||(node[expando]={}))[node.uniqueID]||(outerCache[node.uniqueID]={}))[type]||[])[0]===dirruns&&cache[1])&&cache[2],node=nodeIndex&&parent.childNodes[nodeIndex];node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop();)if(1===node.nodeType&&++diff&&node===elem){uniqueCache[type]=[dirruns,nodeIndex,diff];break}}else if(useCache&&(diff=nodeIndex=(cache=(uniqueCache=(outerCache=(node=elem)[expando]||(node[expando]={}))[node.uniqueID]||(outerCache[node.uniqueID]={}))[type]||[])[0]===dirruns&&cache[1]),!1===diff)for(;(node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop())&&((ofType?node.nodeName.toLowerCase()!==name:1!==node.nodeType)||!++diff||(useCache&&((uniqueCache=(outerCache=node[expando]||(node[expando]={}))[node.uniqueID]||(outerCache[node.uniqueID]={}))[type]=[dirruns,diff]),node!==elem)););return(diff-=last)===first||diff%first==0&&diff/first>=0}}},PSEUDO:function(pseudo,argument){var args,fn=Expr.pseudos[pseudo]||Expr.setFilters[pseudo.toLowerCase()]||Sizzle.error("unsupported pseudo: "+pseudo);return fn[expando]?fn(argument):fn.length>1?(args=[pseudo,pseudo,"",argument],Expr.setFilters.hasOwnProperty(pseudo.toLowerCase())?markFunction((function(seed,matches){for(var idx,matched=fn(seed,argument),i=matched.length;i--;)seed[idx=indexOf(seed,matched[i])]=!(matches[idx]=matched[i])})):function(elem){return fn(elem,0,args)}):fn}},pseudos:{not:markFunction((function(selector){var input=[],results=[],matcher=compile(selector.replace(rtrim,"$1"));return matcher[expando]?markFunction((function(seed,matches,_context,xml){for(var elem,unmatched=matcher(seed,null,xml,[]),i=seed.length;i--;)(elem=unmatched[i])&&(seed[i]=!(matches[i]=elem))})):function(elem,_context,xml){return input[0]=elem,matcher(input,null,xml,results),input[0]=null,!results.pop()}})),has:markFunction((function(selector){return function(elem){return Sizzle(selector,elem).length>0}})),contains:markFunction((function(text){return text=text.replace(runescape,funescape),function(elem){return(elem.textContent||getText(elem)).indexOf(text)>-1}})),lang:markFunction((function(lang){return ridentifier.test(lang||"")||Sizzle.error("unsupported lang: "+lang),lang=lang.replace(runescape,funescape).toLowerCase(),function(elem){var elemLang;do{if(elemLang=documentIsHTML?elem.lang:elem.getAttribute("xml:lang")||elem.getAttribute("lang"))return(elemLang=elemLang.toLowerCase())===lang||0===elemLang.indexOf(lang+"-")}while((elem=elem.parentNode)&&1===elem.nodeType);return!1}})),target:function(elem){var hash=window.location&&window.location.hash;return hash&&hash.slice(1)===elem.id},root:function(elem){return elem===docElem},focus:function(elem){return elem===document.activeElement&&(!document.hasFocus||document.hasFocus())&&!!(elem.type||elem.href||~elem.tabIndex)},enabled:createDisabledPseudo(!1),disabled:createDisabledPseudo(!0),checked:function(elem){var nodeName=elem.nodeName.toLowerCase();return"input"===nodeName&&!!elem.checked||"option"===nodeName&&!!elem.selected},selected:function(elem){return elem.parentNode&&elem.parentNode.selectedIndex,!0===elem.selected},empty:function(elem){for(elem=elem.firstChild;elem;elem=elem.nextSibling)if(elem.nodeType<6)return!1;return!0},parent:function(elem){return!Expr.pseudos.empty(elem)},header:function(elem){return rheader.test(elem.nodeName)},input:function(elem){return rinputs.test(elem.nodeName)},button:function(elem){var name=elem.nodeName.toLowerCase();return"input"===name&&"button"===elem.type||"button"===name},text:function(elem){var attr;return"input"===elem.nodeName.toLowerCase()&&"text"===elem.type&&(null==(attr=elem.getAttribute("type"))||"text"===attr.toLowerCase())},first:createPositionalPseudo((function(){return[0]})),last:createPositionalPseudo((function(_matchIndexes,length){return[length-1]})),eq:createPositionalPseudo((function(_matchIndexes,length,argument){return[argument<0?argument+length:argument]})),even:createPositionalPseudo((function(matchIndexes,length){for(var i=0;i<length;i+=2)matchIndexes.push(i);return matchIndexes})),odd:createPositionalPseudo((function(matchIndexes,length){for(var i=1;i<length;i+=2)matchIndexes.push(i);return matchIndexes})),lt:createPositionalPseudo((function(matchIndexes,length,argument){for(var i=argument<0?argument+length:argument>length?length:argument;--i>=0;)matchIndexes.push(i);return matchIndexes})),gt:createPositionalPseudo((function(matchIndexes,length,argument){for(var i=argument<0?argument+length:argument;++i<length;)matchIndexes.push(i);return matchIndexes}))}}).pseudos.nth=Expr.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})Expr.pseudos[i]=createInputPseudo(i);for(i in{submit:!0,reset:!0})Expr.pseudos[i]=createButtonPseudo(i);function setFilters(){}function toSelector(tokens){for(var i=0,len=tokens.length,selector="";i<len;i++)selector+=tokens[i].value;return selector}function addCombinator(matcher,combinator,base){var dir=combinator.dir,skip=combinator.next,key=skip||dir,checkNonElements=base&&"parentNode"===key,doneName=done++;return combinator.first?function(elem,context,xml){for(;elem=elem[dir];)if(1===elem.nodeType||checkNonElements)return matcher(elem,context,xml);return!1}:function(elem,context,xml){var oldCache,uniqueCache,outerCache,newCache=[dirruns,doneName];if(xml){for(;elem=elem[dir];)if((1===elem.nodeType||checkNonElements)&&matcher(elem,context,xml))return!0}else for(;elem=elem[dir];)if(1===elem.nodeType||checkNonElements)if(uniqueCache=(outerCache=elem[expando]||(elem[expando]={}))[elem.uniqueID]||(outerCache[elem.uniqueID]={}),skip&&skip===elem.nodeName.toLowerCase())elem=elem[dir]||elem;else{if((oldCache=uniqueCache[key])&&oldCache[0]===dirruns&&oldCache[1]===doneName)return newCache[2]=oldCache[2];if(uniqueCache[key]=newCache,newCache[2]=matcher(elem,context,xml))return!0}return!1}}function elementMatcher(matchers){return matchers.length>1?function(elem,context,xml){for(var i=matchers.length;i--;)if(!matchers[i](elem,context,xml))return!1;return!0}:matchers[0]}function condense(unmatched,map,filter,context,xml){for(var elem,newUnmatched=[],i=0,len=unmatched.length,mapped=null!=map;i<len;i++)(elem=unmatched[i])&&(filter&&!filter(elem,context,xml)||(newUnmatched.push(elem),mapped&&map.push(i)));return newUnmatched}function setMatcher(preFilter,selector,matcher,postFilter,postFinder,postSelector){return postFilter&&!postFilter[expando]&&(postFilter=setMatcher(postFilter)),postFinder&&!postFinder[expando]&&(postFinder=setMatcher(postFinder,postSelector)),markFunction((function(seed,results,context,xml){var temp,i,elem,preMap=[],postMap=[],preexisting=results.length,elems=seed||function(selector,contexts,results){for(var i=0,len=contexts.length;i<len;i++)Sizzle(selector,contexts[i],results);return results}(selector||"*",context.nodeType?[context]:context,[]),matcherIn=!preFilter||!seed&&selector?elems:condense(elems,preMap,preFilter,context,xml),matcherOut=matcher?postFinder||(seed?preFilter:preexisting||postFilter)?[]:results:matcherIn;if(matcher&&matcher(matcherIn,matcherOut,context,xml),postFilter)for(temp=condense(matcherOut,postMap),postFilter(temp,[],context,xml),i=temp.length;i--;)(elem=temp[i])&&(matcherOut[postMap[i]]=!(matcherIn[postMap[i]]=elem));if(seed){if(postFinder||preFilter){if(postFinder){for(temp=[],i=matcherOut.length;i--;)(elem=matcherOut[i])&&temp.push(matcherIn[i]=elem);postFinder(null,matcherOut=[],temp,xml)}for(i=matcherOut.length;i--;)(elem=matcherOut[i])&&(temp=postFinder?indexOf(seed,elem):preMap[i])>-1&&(seed[temp]=!(results[temp]=elem))}}else matcherOut=condense(matcherOut===results?matcherOut.splice(preexisting,matcherOut.length):matcherOut),postFinder?postFinder(null,results,matcherOut,xml):push.apply(results,matcherOut)}))}function matcherFromTokens(tokens){for(var checkContext,matcher,j,len=tokens.length,leadingRelative=Expr.relative[tokens[0].type],implicitRelative=leadingRelative||Expr.relative[" "],i=leadingRelative?1:0,matchContext=addCombinator((function(elem){return elem===checkContext}),implicitRelative,!0),matchAnyContext=addCombinator((function(elem){return indexOf(checkContext,elem)>-1}),implicitRelative,!0),matchers=[function(elem,context,xml){var ret=!leadingRelative&&(xml||context!==outermostContext)||((checkContext=context).nodeType?matchContext(elem,context,xml):matchAnyContext(elem,context,xml));return checkContext=null,ret}];i<len;i++)if(matcher=Expr.relative[tokens[i].type])matchers=[addCombinator(elementMatcher(matchers),matcher)];else{if((matcher=Expr.filter[tokens[i].type].apply(null,tokens[i].matches))[expando]){for(j=++i;j<len&&!Expr.relative[tokens[j].type];j++);return setMatcher(i>1&&elementMatcher(matchers),i>1&&toSelector(tokens.slice(0,i-1).concat({value:" "===tokens[i-2].type?"*":""})).replace(rtrim,"$1"),matcher,i<j&&matcherFromTokens(tokens.slice(i,j)),j<len&&matcherFromTokens(tokens=tokens.slice(j)),j<len&&toSelector(tokens))}matchers.push(matcher)}return elementMatcher(matchers)}return setFilters.prototype=Expr.filters=Expr.pseudos,Expr.setFilters=new setFilters,tokenize=Sizzle.tokenize=function(selector,parseOnly){var matched,match,tokens,type,soFar,groups,preFilters,cached=tokenCache[selector+" "];if(cached)return parseOnly?0:cached.slice(0);for(soFar=selector,groups=[],preFilters=Expr.preFilter;soFar;){for(type in matched&&!(match=rcomma.exec(soFar))||(match&&(soFar=soFar.slice(match[0].length)||soFar),groups.push(tokens=[])),matched=!1,(match=rcombinators.exec(soFar))&&(matched=match.shift(),tokens.push({value:matched,type:match[0].replace(rtrim," ")}),soFar=soFar.slice(matched.length)),Expr.filter)!(match=matchExpr[type].exec(soFar))||preFilters[type]&&!(match=preFilters[type](match))||(matched=match.shift(),tokens.push({value:matched,type:type,matches:match}),soFar=soFar.slice(matched.length));if(!matched)break}return parseOnly?soFar.length:soFar?Sizzle.error(selector):tokenCache(selector,groups).slice(0)},compile=Sizzle.compile=function(selector,match){var i,setMatchers=[],elementMatchers=[],cached=compilerCache[selector+" "];if(!cached){for(match||(match=tokenize(selector)),i=match.length;i--;)(cached=matcherFromTokens(match[i]))[expando]?setMatchers.push(cached):elementMatchers.push(cached);(cached=compilerCache(selector,function(elementMatchers,setMatchers){var bySet=setMatchers.length>0,byElement=elementMatchers.length>0,superMatcher=function(seed,context,xml,results,outermost){var elem,j,matcher,matchedCount=0,i="0",unmatched=seed&&[],setMatched=[],contextBackup=outermostContext,elems=seed||byElement&&Expr.find.TAG("*",outermost),dirrunsUnique=dirruns+=null==contextBackup?1:Math.random()||.1,len=elems.length;for(outermost&&(outermostContext=context==document||context||outermost);i!==len&&null!=(elem=elems[i]);i++){if(byElement&&elem){for(j=0,context||elem.ownerDocument==document||(setDocument(elem),xml=!documentIsHTML);matcher=elementMatchers[j++];)if(matcher(elem,context||document,xml)){results.push(elem);break}outermost&&(dirruns=dirrunsUnique)}bySet&&((elem=!matcher&&elem)&&matchedCount--,seed&&unmatched.push(elem))}if(matchedCount+=i,bySet&&i!==matchedCount){for(j=0;matcher=setMatchers[j++];)matcher(unmatched,setMatched,context,xml);if(seed){if(matchedCount>0)for(;i--;)unmatched[i]||setMatched[i]||(setMatched[i]=pop.call(results));setMatched=condense(setMatched)}push.apply(results,setMatched),outermost&&!seed&&setMatched.length>0&&matchedCount+setMatchers.length>1&&Sizzle.uniqueSort(results)}return outermost&&(dirruns=dirrunsUnique,outermostContext=contextBackup),unmatched};return bySet?markFunction(superMatcher):superMatcher}(elementMatchers,setMatchers))).selector=selector}return cached},select=Sizzle.select=function(selector,context,results,seed){var i,tokens,token,type,find,compiled="function"==typeof selector&&selector,match=!seed&&tokenize(selector=compiled.selector||selector);if(results=results||[],1===match.length){if((tokens=match[0]=match[0].slice(0)).length>2&&"ID"===(token=tokens[0]).type&&9===context.nodeType&&documentIsHTML&&Expr.relative[tokens[1].type]){if(!(context=(Expr.find.ID(token.matches[0].replace(runescape,funescape),context)||[])[0]))return results;compiled&&(context=context.parentNode),selector=selector.slice(tokens.shift().value.length)}for(i=matchExpr.needsContext.test(selector)?0:tokens.length;i--&&(token=tokens[i],!Expr.relative[type=token.type]);)if((find=Expr.find[type])&&(seed=find(token.matches[0].replace(runescape,funescape),rsibling.test(tokens[0].type)&&testContext(context.parentNode)||context))){if(tokens.splice(i,1),!(selector=seed.length&&toSelector(tokens)))return push.apply(results,seed),results;break}}return(compiled||compile(selector,match))(seed,context,!documentIsHTML,results,!context||rsibling.test(selector)&&testContext(context.parentNode)||context),results},support.sortStable=expando.split("").sort(sortOrder).join("")===expando,support.detectDuplicates=!!hasDuplicate,setDocument(),support.sortDetached=assert((function(el){return 1&el.compareDocumentPosition(document.createElement("fieldset"))})),assert((function(el){return el.innerHTML="<a href='#'></a>","#"===el.firstChild.getAttribute("href")}))||addHandle("type|href|height|width",(function(elem,name,isXML){if(!isXML)return elem.getAttribute(name,"type"===name.toLowerCase()?1:2)})),support.attributes&&assert((function(el){return el.innerHTML="<input/>",el.firstChild.setAttribute("value",""),""===el.firstChild.getAttribute("value")}))||addHandle("value",(function(elem,_name,isXML){if(!isXML&&"input"===elem.nodeName.toLowerCase())return elem.defaultValue})),assert((function(el){return null==el.getAttribute("disabled")}))||addHandle(booleans,(function(elem,name,isXML){var val;if(!isXML)return!0===elem[name]?name.toLowerCase():(val=elem.getAttributeNode(name))&&val.specified?val.value:null})),Sizzle}(window);jQuery.find=Sizzle,jQuery.expr=Sizzle.selectors,jQuery.expr[":"]=jQuery.expr.pseudos,jQuery.uniqueSort=jQuery.unique=Sizzle.uniqueSort,jQuery.text=Sizzle.getText,jQuery.isXMLDoc=Sizzle.isXML,jQuery.contains=Sizzle.contains,jQuery.escapeSelector=Sizzle.escape;var dir=function(elem,dir,until){for(var matched=[],truncate=void 0!==until;(elem=elem[dir])&&9!==elem.nodeType;)if(1===elem.nodeType){if(truncate&&jQuery(elem).is(until))break;matched.push(elem)}return matched},siblings=function(n,elem){for(var matched=[];n;n=n.nextSibling)1===n.nodeType&&n!==elem&&matched.push(n);return matched},rneedsContext=jQuery.expr.match.needsContext;function nodeName(elem,name){return elem.nodeName&&elem.nodeName.toLowerCase()===name.toLowerCase()}var rsingleTag=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function winnow(elements,qualifier,not){return isFunction(qualifier)?jQuery.grep(elements,(function(elem,i){return!!qualifier.call(elem,i,elem)!==not})):qualifier.nodeType?jQuery.grep(elements,(function(elem){return elem===qualifier!==not})):"string"!=typeof qualifier?jQuery.grep(elements,(function(elem){return indexOf.call(qualifier,elem)>-1!==not})):jQuery.filter(qualifier,elements,not)}jQuery.filter=function(expr,elems,not){var elem=elems[0];return not&&(expr=":not("+expr+")"),1===elems.length&&1===elem.nodeType?jQuery.find.matchesSelector(elem,expr)?[elem]:[]:jQuery.find.matches(expr,jQuery.grep(elems,(function(elem){return 1===elem.nodeType})))},jQuery.fn.extend({find:function(selector){var i,ret,len=this.length,self=this;if("string"!=typeof selector)return this.pushStack(jQuery(selector).filter((function(){for(i=0;i<len;i++)if(jQuery.contains(self[i],this))return!0})));for(ret=this.pushStack([]),i=0;i<len;i++)jQuery.find(selector,self[i],ret);return len>1?jQuery.uniqueSort(ret):ret},filter:function(selector){return this.pushStack(winnow(this,selector||[],!1))},not:function(selector){return this.pushStack(winnow(this,selector||[],!0))},is:function(selector){return!!winnow(this,"string"==typeof selector&&rneedsContext.test(selector)?jQuery(selector):selector||[],!1).length}});var rootjQuery,rquickExpr=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(jQuery.fn.init=function(selector,context,root){var match,elem;if(!selector)return this;if(root=root||rootjQuery,"string"==typeof selector){if(!(match="<"===selector[0]&&">"===selector[selector.length-1]&&selector.length>=3?[null,selector,null]:rquickExpr.exec(selector))||!match[1]&&context)return!context||context.jquery?(context||root).find(selector):this.constructor(context).find(selector);if(match[1]){if(context=context instanceof jQuery?context[0]:context,jQuery.merge(this,jQuery.parseHTML(match[1],context&&context.nodeType?context.ownerDocument||context:document,!0)),rsingleTag.test(match[1])&&jQuery.isPlainObject(context))for(match in context)isFunction(this[match])?this[match](context[match]):this.attr(match,context[match]);return this}return(elem=document.getElementById(match[2]))&&(this[0]=elem,this.length=1),this}return selector.nodeType?(this[0]=selector,this.length=1,this):isFunction(selector)?void 0!==root.ready?root.ready(selector):selector(jQuery):jQuery.makeArray(selector,this)}).prototype=jQuery.fn,rootjQuery=jQuery(document);var rparentsprev=/^(?:parents|prev(?:Until|All))/,guaranteedUnique={children:!0,contents:!0,next:!0,prev:!0};function sibling(cur,dir){for(;(cur=cur[dir])&&1!==cur.nodeType;);return cur}jQuery.fn.extend({has:function(target){var targets=jQuery(target,this),l=targets.length;return this.filter((function(){for(var i=0;i<l;i++)if(jQuery.contains(this,targets[i]))return!0}))},closest:function(selectors,context){var cur,i=0,l=this.length,matched=[],targets="string"!=typeof selectors&&jQuery(selectors);if(!rneedsContext.test(selectors))for(;i<l;i++)for(cur=this[i];cur&&cur!==context;cur=cur.parentNode)if(cur.nodeType<11&&(targets?targets.index(cur)>-1:1===cur.nodeType&&jQuery.find.matchesSelector(cur,selectors))){matched.push(cur);break}return this.pushStack(matched.length>1?jQuery.uniqueSort(matched):matched)},index:function(elem){return elem?"string"==typeof elem?indexOf.call(jQuery(elem),this[0]):indexOf.call(this,elem.jquery?elem[0]:elem):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(selector,context){return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(),jQuery(selector,context))))},addBack:function(selector){return this.add(null==selector?this.prevObject:this.prevObject.filter(selector))}}),jQuery.each({parent:function(elem){var parent=elem.parentNode;return parent&&11!==parent.nodeType?parent:null},parents:function(elem){return dir(elem,"parentNode")},parentsUntil:function(elem,_i,until){return dir(elem,"parentNode",until)},next:function(elem){return sibling(elem,"nextSibling")},prev:function(elem){return sibling(elem,"previousSibling")},nextAll:function(elem){return dir(elem,"nextSibling")},prevAll:function(elem){return dir(elem,"previousSibling")},nextUntil:function(elem,_i,until){return dir(elem,"nextSibling",until)},prevUntil:function(elem,_i,until){return dir(elem,"previousSibling",until)},siblings:function(elem){return siblings((elem.parentNode||{}).firstChild,elem)},children:function(elem){return siblings(elem.firstChild)},contents:function(elem){return null!=elem.contentDocument&&getProto(elem.contentDocument)?elem.contentDocument:(nodeName(elem,"template")&&(elem=elem.content||elem),jQuery.merge([],elem.childNodes))}},(function(name,fn){jQuery.fn[name]=function(until,selector){var matched=jQuery.map(this,fn,until);return"Until"!==name.slice(-5)&&(selector=until),selector&&"string"==typeof selector&&(matched=jQuery.filter(selector,matched)),this.length>1&&(guaranteedUnique[name]||jQuery.uniqueSort(matched),rparentsprev.test(name)&&matched.reverse()),this.pushStack(matched)}}));var rnothtmlwhite=/[^\x20\t\r\n\f]+/g;function Identity(v){return v}function Thrower(ex){throw ex}function adoptValue(value,resolve,reject,noValue){var method;try{value&&isFunction(method=value.promise)?method.call(value).done(resolve).fail(reject):value&&isFunction(method=value.then)?method.call(value,resolve,reject):resolve.apply(void 0,[value].slice(noValue))}catch(value){reject.apply(void 0,[value])}}jQuery.Callbacks=function(options){options="string"==typeof options?function(options){var object={};return jQuery.each(options.match(rnothtmlwhite)||[],(function(_,flag){object[flag]=!0})),object}(options):jQuery.extend({},options);var firing,memory,fired,locked,list=[],queue=[],firingIndex=-1,fire=function(){for(locked=locked||options.once,fired=firing=!0;queue.length;firingIndex=-1)for(memory=queue.shift();++firingIndex<list.length;)!1===list[firingIndex].apply(memory[0],memory[1])&&options.stopOnFalse&&(firingIndex=list.length,memory=!1);options.memory||(memory=!1),firing=!1,locked&&(list=memory?[]:"")},self={add:function(){return list&&(memory&&!firing&&(firingIndex=list.length-1,queue.push(memory)),function add(args){jQuery.each(args,(function(_,arg){isFunction(arg)?options.unique&&self.has(arg)||list.push(arg):arg&&arg.length&&"string"!==toType(arg)&&add(arg)}))}(arguments),memory&&!firing&&fire()),this},remove:function(){return jQuery.each(arguments,(function(_,arg){for(var index;(index=jQuery.inArray(arg,list,index))>-1;)list.splice(index,1),index<=firingIndex&&firingIndex--})),this},has:function(fn){return fn?jQuery.inArray(fn,list)>-1:list.length>0},empty:function(){return list&&(list=[]),this},disable:function(){return locked=queue=[],list=memory="",this},disabled:function(){return!list},lock:function(){return locked=queue=[],memory||firing||(list=memory=""),this},locked:function(){return!!locked},fireWith:function(context,args){return locked||(args=[context,(args=args||[]).slice?args.slice():args],queue.push(args),firing||fire()),this},fire:function(){return self.fireWith(this,arguments),this},fired:function(){return!!fired}};return self},jQuery.extend({Deferred:function(func){var tuples=[["notify","progress",jQuery.Callbacks("memory"),jQuery.Callbacks("memory"),2],["resolve","done",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),0,"resolved"],["reject","fail",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),1,"rejected"]],state="pending",promise={state:function(){return state},always:function(){return deferred.done(arguments).fail(arguments),this},catch:function(fn){return promise.then(null,fn)},pipe:function(){var fns=arguments;return jQuery.Deferred((function(newDefer){jQuery.each(tuples,(function(_i,tuple){var fn=isFunction(fns[tuple[4]])&&fns[tuple[4]];deferred[tuple[1]]((function(){var returned=fn&&fn.apply(this,arguments);returned&&isFunction(returned.promise)?returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject):newDefer[tuple[0]+"With"](this,fn?[returned]:arguments)}))})),fns=null})).promise()},then:function(onFulfilled,onRejected,onProgress){var maxDepth=0;function resolve(depth,deferred,handler,special){return function(){var that=this,args=arguments,mightThrow=function(){var returned,then;if(!(depth<maxDepth)){if((returned=handler.apply(that,args))===deferred.promise())throw new TypeError("Thenable self-resolution");then=returned&&("object"==typeof returned||"function"==typeof returned)&&returned.then,isFunction(then)?special?then.call(returned,resolve(maxDepth,deferred,Identity,special),resolve(maxDepth,deferred,Thrower,special)):(maxDepth++,then.call(returned,resolve(maxDepth,deferred,Identity,special),resolve(maxDepth,deferred,Thrower,special),resolve(maxDepth,deferred,Identity,deferred.notifyWith))):(handler!==Identity&&(that=void 0,args=[returned]),(special||deferred.resolveWith)(that,args))}},process=special?mightThrow:function(){try{mightThrow()}catch(e){jQuery.Deferred.exceptionHook&&jQuery.Deferred.exceptionHook(e,process.stackTrace),depth+1>=maxDepth&&(handler!==Thrower&&(that=void 0,args=[e]),deferred.rejectWith(that,args))}};depth?process():(jQuery.Deferred.getStackHook&&(process.stackTrace=jQuery.Deferred.getStackHook()),window.setTimeout(process))}}return jQuery.Deferred((function(newDefer){tuples[0][3].add(resolve(0,newDefer,isFunction(onProgress)?onProgress:Identity,newDefer.notifyWith)),tuples[1][3].add(resolve(0,newDefer,isFunction(onFulfilled)?onFulfilled:Identity)),tuples[2][3].add(resolve(0,newDefer,isFunction(onRejected)?onRejected:Thrower))})).promise()},promise:function(obj){return null!=obj?jQuery.extend(obj,promise):promise}},deferred={};return jQuery.each(tuples,(function(i,tuple){var list=tuple[2],stateString=tuple[5];promise[tuple[1]]=list.add,stateString&&list.add((function(){state=stateString}),tuples[3-i][2].disable,tuples[3-i][3].disable,tuples[0][2].lock,tuples[0][3].lock),list.add(tuple[3].fire),deferred[tuple[0]]=function(){return deferred[tuple[0]+"With"](this===deferred?void 0:this,arguments),this},deferred[tuple[0]+"With"]=list.fireWith})),promise.promise(deferred),func&&func.call(deferred,deferred),deferred},when:function(singleValue){var remaining=arguments.length,i=remaining,resolveContexts=Array(i),resolveValues=slice.call(arguments),master=jQuery.Deferred(),updateFunc=function(i){return function(value){resolveContexts[i]=this,resolveValues[i]=arguments.length>1?slice.call(arguments):value,--remaining||master.resolveWith(resolveContexts,resolveValues)}};if(remaining<=1&&(adoptValue(singleValue,master.done(updateFunc(i)).resolve,master.reject,!remaining),"pending"===master.state()||isFunction(resolveValues[i]&&resolveValues[i].then)))return master.then();for(;i--;)adoptValue(resolveValues[i],updateFunc(i),master.reject);return master.promise()}});var rerrorNames=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;jQuery.Deferred.exceptionHook=function(error,stack){window.console&&window.console.warn&&error&&rerrorNames.test(error.name)&&window.console.warn("jQuery.Deferred exception: "+error.message,error.stack,stack)},jQuery.readyException=function(error){window.setTimeout((function(){throw error}))};var readyList=jQuery.Deferred();function completed(){document.removeEventListener("DOMContentLoaded",completed),window.removeEventListener("load",completed),jQuery.ready()}jQuery.fn.ready=function(fn){return readyList.then(fn).catch((function(error){jQuery.readyException(error)})),this},jQuery.extend({isReady:!1,readyWait:1,ready:function(wait){(!0===wait?--jQuery.readyWait:jQuery.isReady)||(jQuery.isReady=!0,!0!==wait&&--jQuery.readyWait>0||readyList.resolveWith(document,[jQuery]))}}),jQuery.ready.then=readyList.then,"complete"===document.readyState||"loading"!==document.readyState&&!document.documentElement.doScroll?window.setTimeout(jQuery.ready):(document.addEventListener("DOMContentLoaded",completed),window.addEventListener("load",completed));var access=function(elems,fn,key,value,chainable,emptyGet,raw){var i=0,len=elems.length,bulk=null==key;if("object"===toType(key))for(i in chainable=!0,key)access(elems,fn,i,key[i],!0,emptyGet,raw);else if(void 0!==value&&(chainable=!0,isFunction(value)||(raw=!0),bulk&&(raw?(fn.call(elems,value),fn=null):(bulk=fn,fn=function(elem,_key,value){return bulk.call(jQuery(elem),value)})),fn))for(;i<len;i++)fn(elems[i],key,raw?value:value.call(elems[i],i,fn(elems[i],key)));return chainable?elems:bulk?fn.call(elems):len?fn(elems[0],key):emptyGet},rmsPrefix=/^-ms-/,rdashAlpha=/-([a-z])/g;function fcamelCase(_all,letter){return letter.toUpperCase()}function camelCase(string){return string.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase)}var acceptData=function(owner){return 1===owner.nodeType||9===owner.nodeType||!+owner.nodeType};function Data(){this.expando=jQuery.expando+Data.uid++}Data.uid=1,Data.prototype={cache:function(owner){var value=owner[this.expando];return value||(value={},acceptData(owner)&&(owner.nodeType?owner[this.expando]=value:Object.defineProperty(owner,this.expando,{value:value,configurable:!0}))),value},set:function(owner,data,value){var prop,cache=this.cache(owner);if("string"==typeof data)cache[camelCase(data)]=value;else for(prop in data)cache[camelCase(prop)]=data[prop];return cache},get:function(owner,key){return void 0===key?this.cache(owner):owner[this.expando]&&owner[this.expando][camelCase(key)]},access:function(owner,key,value){return void 0===key||key&&"string"==typeof key&&void 0===value?this.get(owner,key):(this.set(owner,key,value),void 0!==value?value:key)},remove:function(owner,key){var i,cache=owner[this.expando];if(void 0!==cache){if(void 0!==key){i=(key=Array.isArray(key)?key.map(camelCase):(key=camelCase(key))in cache?[key]:key.match(rnothtmlwhite)||[]).length;for(;i--;)delete cache[key[i]]}(void 0===key||jQuery.isEmptyObject(cache))&&(owner.nodeType?owner[this.expando]=void 0:delete owner[this.expando])}},hasData:function(owner){var cache=owner[this.expando];return void 0!==cache&&!jQuery.isEmptyObject(cache)}};var dataPriv=new Data,dataUser=new Data,rbrace=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,rmultiDash=/[A-Z]/g;function dataAttr(elem,key,data){var name;if(void 0===data&&1===elem.nodeType)if(name="data-"+key.replace(rmultiDash,"-$&").toLowerCase(),"string"==typeof(data=elem.getAttribute(name))){try{data=function(data){return"true"===data||"false"!==data&&("null"===data?null:data===+data+""?+data:rbrace.test(data)?JSON.parse(data):data)}(data)}catch(e){}dataUser.set(elem,key,data)}else data=void 0;return data}jQuery.extend({hasData:function(elem){return dataUser.hasData(elem)||dataPriv.hasData(elem)},data:function(elem,name,data){return dataUser.access(elem,name,data)},removeData:function(elem,name){dataUser.remove(elem,name)},_data:function(elem,name,data){return dataPriv.access(elem,name,data)},_removeData:function(elem,name){dataPriv.remove(elem,name)}}),jQuery.fn.extend({data:function(key,value){var i,name,data,elem=this[0],attrs=elem&&elem.attributes;if(void 0===key){if(this.length&&(data=dataUser.get(elem),1===elem.nodeType&&!dataPriv.get(elem,"hasDataAttrs"))){for(i=attrs.length;i--;)attrs[i]&&0===(name=attrs[i].name).indexOf("data-")&&(name=camelCase(name.slice(5)),dataAttr(elem,name,data[name]));dataPriv.set(elem,"hasDataAttrs",!0)}return data}return"object"==typeof key?this.each((function(){dataUser.set(this,key)})):access(this,(function(value){var data;if(elem&&void 0===value)return void 0!==(data=dataUser.get(elem,key))||void 0!==(data=dataAttr(elem,key))?data:void 0;this.each((function(){dataUser.set(this,key,value)}))}),null,value,arguments.length>1,null,!0)},removeData:function(key){return this.each((function(){dataUser.remove(this,key)}))}}),jQuery.extend({queue:function(elem,type,data){var queue;if(elem)return type=(type||"fx")+"queue",queue=dataPriv.get(elem,type),data&&(!queue||Array.isArray(data)?queue=dataPriv.access(elem,type,jQuery.makeArray(data)):queue.push(data)),queue||[]},dequeue:function(elem,type){type=type||"fx";var queue=jQuery.queue(elem,type),startLength=queue.length,fn=queue.shift(),hooks=jQuery._queueHooks(elem,type);"inprogress"===fn&&(fn=queue.shift(),startLength--),fn&&("fx"===type&&queue.unshift("inprogress"),delete hooks.stop,fn.call(elem,(function(){jQuery.dequeue(elem,type)}),hooks)),!startLength&&hooks&&hooks.empty.fire()},_queueHooks:function(elem,type){var key=type+"queueHooks";return dataPriv.get(elem,key)||dataPriv.access(elem,key,{empty:jQuery.Callbacks("once memory").add((function(){dataPriv.remove(elem,[type+"queue",key])}))})}}),jQuery.fn.extend({queue:function(type,data){var setter=2;return"string"!=typeof type&&(data=type,type="fx",setter--),arguments.length<setter?jQuery.queue(this[0],type):void 0===data?this:this.each((function(){var queue=jQuery.queue(this,type,data);jQuery._queueHooks(this,type),"fx"===type&&"inprogress"!==queue[0]&&jQuery.dequeue(this,type)}))},dequeue:function(type){return this.each((function(){jQuery.dequeue(this,type)}))},clearQueue:function(type){return this.queue(type||"fx",[])},promise:function(type,obj){var tmp,count=1,defer=jQuery.Deferred(),elements=this,i=this.length,resolve=function(){--count||defer.resolveWith(elements,[elements])};for("string"!=typeof type&&(obj=type,type=void 0),type=type||"fx";i--;)(tmp=dataPriv.get(elements[i],type+"queueHooks"))&&tmp.empty&&(count++,tmp.empty.add(resolve));return resolve(),defer.promise(obj)}});var pnum=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,rcssNum=new RegExp("^(?:([+-])=|)("+pnum+")([a-z%]*)$","i"),cssExpand=["Top","Right","Bottom","Left"],documentElement=document.documentElement,isAttached=function(elem){return jQuery.contains(elem.ownerDocument,elem)},composed={composed:!0};documentElement.getRootNode&&(isAttached=function(elem){return jQuery.contains(elem.ownerDocument,elem)||elem.getRootNode(composed)===elem.ownerDocument});var isHiddenWithinTree=function(elem,el){return"none"===(elem=el||elem).style.display||""===elem.style.display&&isAttached(elem)&&"none"===jQuery.css(elem,"display")};function adjustCSS(elem,prop,valueParts,tween){var adjusted,scale,maxIterations=20,currentValue=tween?function(){return tween.cur()}:function(){return jQuery.css(elem,prop,"")},initial=currentValue(),unit=valueParts&&valueParts[3]||(jQuery.cssNumber[prop]?"":"px"),initialInUnit=elem.nodeType&&(jQuery.cssNumber[prop]||"px"!==unit&&+initial)&&rcssNum.exec(jQuery.css(elem,prop));if(initialInUnit&&initialInUnit[3]!==unit){for(initial/=2,unit=unit||initialInUnit[3],initialInUnit=+initial||1;maxIterations--;)jQuery.style(elem,prop,initialInUnit+unit),(1-scale)*(1-(scale=currentValue()/initial||.5))<=0&&(maxIterations=0),initialInUnit/=scale;initialInUnit*=2,jQuery.style(elem,prop,initialInUnit+unit),valueParts=valueParts||[]}return valueParts&&(initialInUnit=+initialInUnit||+initial||0,adjusted=valueParts[1]?initialInUnit+(valueParts[1]+1)*valueParts[2]:+valueParts[2],tween&&(tween.unit=unit,tween.start=initialInUnit,tween.end=adjusted)),adjusted}var defaultDisplayMap={};function getDefaultDisplay(elem){var temp,doc=elem.ownerDocument,nodeName=elem.nodeName,display=defaultDisplayMap[nodeName];return display||(temp=doc.body.appendChild(doc.createElement(nodeName)),display=jQuery.css(temp,"display"),temp.parentNode.removeChild(temp),"none"===display&&(display="block"),defaultDisplayMap[nodeName]=display,display)}function showHide(elements,show){for(var display,elem,values=[],index=0,length=elements.length;index<length;index++)(elem=elements[index]).style&&(display=elem.style.display,show?("none"===display&&(values[index]=dataPriv.get(elem,"display")||null,values[index]||(elem.style.display="")),""===elem.style.display&&isHiddenWithinTree(elem)&&(values[index]=getDefaultDisplay(elem))):"none"!==display&&(values[index]="none",dataPriv.set(elem,"display",display)));for(index=0;index<length;index++)null!=values[index]&&(elements[index].style.display=values[index]);return elements}jQuery.fn.extend({show:function(){return showHide(this,!0)},hide:function(){return showHide(this)},toggle:function(state){return"boolean"==typeof state?state?this.show():this.hide():this.each((function(){isHiddenWithinTree(this)?jQuery(this).show():jQuery(this).hide()}))}});var div,input,rcheckableType=/^(?:checkbox|radio)$/i,rtagName=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,rscriptType=/^$|^module$|\/(?:java|ecma)script/i;div=document.createDocumentFragment().appendChild(document.createElement("div")),(input=document.createElement("input")).setAttribute("type","radio"),input.setAttribute("checked","checked"),input.setAttribute("name","t"),div.appendChild(input),support.checkClone=div.cloneNode(!0).cloneNode(!0).lastChild.checked,div.innerHTML="<textarea>x</textarea>",support.noCloneChecked=!!div.cloneNode(!0).lastChild.defaultValue,div.innerHTML="<option></option>",support.option=!!div.lastChild;var wrapMap={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};function getAll(context,tag){var ret;return ret=void 0!==context.getElementsByTagName?context.getElementsByTagName(tag||"*"):void 0!==context.querySelectorAll?context.querySelectorAll(tag||"*"):[],void 0===tag||tag&&nodeName(context,tag)?jQuery.merge([context],ret):ret}function setGlobalEval(elems,refElements){for(var i=0,l=elems.length;i<l;i++)dataPriv.set(elems[i],"globalEval",!refElements||dataPriv.get(refElements[i],"globalEval"))}wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead,wrapMap.th=wrapMap.td,support.option||(wrapMap.optgroup=wrapMap.option=[1,"<select multiple='multiple'>","</select>"]);var rhtml=/<|&#?\w+;/;function buildFragment(elems,context,scripts,selection,ignored){for(var elem,tmp,tag,wrap,attached,j,fragment=context.createDocumentFragment(),nodes=[],i=0,l=elems.length;i<l;i++)if((elem=elems[i])||0===elem)if("object"===toType(elem))jQuery.merge(nodes,elem.nodeType?[elem]:elem);else if(rhtml.test(elem)){for(tmp=tmp||fragment.appendChild(context.createElement("div")),tag=(rtagName.exec(elem)||["",""])[1].toLowerCase(),wrap=wrapMap[tag]||wrapMap._default,tmp.innerHTML=wrap[1]+jQuery.htmlPrefilter(elem)+wrap[2],j=wrap[0];j--;)tmp=tmp.lastChild;jQuery.merge(nodes,tmp.childNodes),(tmp=fragment.firstChild).textContent=""}else nodes.push(context.createTextNode(elem));for(fragment.textContent="",i=0;elem=nodes[i++];)if(selection&&jQuery.inArray(elem,selection)>-1)ignored&&ignored.push(elem);else if(attached=isAttached(elem),tmp=getAll(fragment.appendChild(elem),"script"),attached&&setGlobalEval(tmp),scripts)for(j=0;elem=tmp[j++];)rscriptType.test(elem.type||"")&&scripts.push(elem);return fragment}var rkeyEvent=/^key/,rmouseEvent=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,rtypenamespace=/^([^.]*)(?:\.(.+)|)/;function returnTrue(){return!0}function returnFalse(){return!1}function expectSync(elem,type){return elem===function(){try{return document.activeElement}catch(err){}}()==("focus"===type)}function on(elem,types,selector,data,fn,one){var origFn,type;if("object"==typeof types){for(type in"string"!=typeof selector&&(data=data||selector,selector=void 0),types)on(elem,type,selector,data,types[type],one);return elem}if(null==data&&null==fn?(fn=selector,data=selector=void 0):null==fn&&("string"==typeof selector?(fn=data,data=void 0):(fn=data,data=selector,selector=void 0)),!1===fn)fn=returnFalse;else if(!fn)return elem;return 1===one&&(origFn=fn,(fn=function(event){return jQuery().off(event),origFn.apply(this,arguments)}).guid=origFn.guid||(origFn.guid=jQuery.guid++)),elem.each((function(){jQuery.event.add(this,types,fn,data,selector)}))}function leverageNative(el,type,expectSync){expectSync?(dataPriv.set(el,type,!1),jQuery.event.add(el,type,{namespace:!1,handler:function(event){var notAsync,result,saved=dataPriv.get(this,type);if(1&event.isTrigger&&this[type]){if(saved.length)(jQuery.event.special[type]||{}).delegateType&&event.stopPropagation();else if(saved=slice.call(arguments),dataPriv.set(this,type,saved),notAsync=expectSync(this,type),this[type](),saved!==(result=dataPriv.get(this,type))||notAsync?dataPriv.set(this,type,!1):result={},saved!==result)return event.stopImmediatePropagation(),event.preventDefault(),result.value}else saved.length&&(dataPriv.set(this,type,{value:jQuery.event.trigger(jQuery.extend(saved[0],jQuery.Event.prototype),saved.slice(1),this)}),event.stopImmediatePropagation())}})):void 0===dataPriv.get(el,type)&&jQuery.event.add(el,type,returnTrue)}jQuery.event={global:{},add:function(elem,types,handler,data,selector){var handleObjIn,eventHandle,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.get(elem);if(acceptData(elem))for(handler.handler&&(handler=(handleObjIn=handler).handler,selector=handleObjIn.selector),selector&&jQuery.find.matchesSelector(documentElement,selector),handler.guid||(handler.guid=jQuery.guid++),(events=elemData.events)||(events=elemData.events=Object.create(null)),(eventHandle=elemData.handle)||(eventHandle=elemData.handle=function(e){return void 0!==jQuery&&jQuery.event.triggered!==e.type?jQuery.event.dispatch.apply(elem,arguments):void 0}),t=(types=(types||"").match(rnothtmlwhite)||[""]).length;t--;)type=origType=(tmp=rtypenamespace.exec(types[t])||[])[1],namespaces=(tmp[2]||"").split(".").sort(),type&&(special=jQuery.event.special[type]||{},type=(selector?special.delegateType:special.bindType)||type,special=jQuery.event.special[type]||{},handleObj=jQuery.extend({type:type,origType:origType,data:data,handler:handler,guid:handler.guid,selector:selector,needsContext:selector&&jQuery.expr.match.needsContext.test(selector),namespace:namespaces.join(".")},handleObjIn),(handlers=events[type])||((handlers=events[type]=[]).delegateCount=0,special.setup&&!1!==special.setup.call(elem,data,namespaces,eventHandle)||elem.addEventListener&&elem.addEventListener(type,eventHandle)),special.add&&(special.add.call(elem,handleObj),handleObj.handler.guid||(handleObj.handler.guid=handler.guid)),selector?handlers.splice(handlers.delegateCount++,0,handleObj):handlers.push(handleObj),jQuery.event.global[type]=!0)},remove:function(elem,types,handler,selector,mappedTypes){var j,origCount,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.hasData(elem)&&dataPriv.get(elem);if(elemData&&(events=elemData.events)){for(t=(types=(types||"").match(rnothtmlwhite)||[""]).length;t--;)if(type=origType=(tmp=rtypenamespace.exec(types[t])||[])[1],namespaces=(tmp[2]||"").split(".").sort(),type){for(special=jQuery.event.special[type]||{},handlers=events[type=(selector?special.delegateType:special.bindType)||type]||[],tmp=tmp[2]&&new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)"),origCount=j=handlers.length;j--;)handleObj=handlers[j],!mappedTypes&&origType!==handleObj.origType||handler&&handler.guid!==handleObj.guid||tmp&&!tmp.test(handleObj.namespace)||selector&&selector!==handleObj.selector&&("**"!==selector||!handleObj.selector)||(handlers.splice(j,1),handleObj.selector&&handlers.delegateCount--,special.remove&&special.remove.call(elem,handleObj));origCount&&!handlers.length&&(special.teardown&&!1!==special.teardown.call(elem,namespaces,elemData.handle)||jQuery.removeEvent(elem,type,elemData.handle),delete events[type])}else for(type in events)jQuery.event.remove(elem,type+types[t],handler,selector,!0);jQuery.isEmptyObject(events)&&dataPriv.remove(elem,"handle events")}},dispatch:function(nativeEvent){var i,j,ret,matched,handleObj,handlerQueue,args=new Array(arguments.length),event=jQuery.event.fix(nativeEvent),handlers=(dataPriv.get(this,"events")||Object.create(null))[event.type]||[],special=jQuery.event.special[event.type]||{};for(args[0]=event,i=1;i<arguments.length;i++)args[i]=arguments[i];if(event.delegateTarget=this,!special.preDispatch||!1!==special.preDispatch.call(this,event)){for(handlerQueue=jQuery.event.handlers.call(this,event,handlers),i=0;(matched=handlerQueue[i++])&&!event.isPropagationStopped();)for(event.currentTarget=matched.elem,j=0;(handleObj=matched.handlers[j++])&&!event.isImmediatePropagationStopped();)event.rnamespace&&!1!==handleObj.namespace&&!event.rnamespace.test(handleObj.namespace)||(event.handleObj=handleObj,event.data=handleObj.data,void 0!==(ret=((jQuery.event.special[handleObj.origType]||{}).handle||handleObj.handler).apply(matched.elem,args))&&!1===(event.result=ret)&&(event.preventDefault(),event.stopPropagation()));return special.postDispatch&&special.postDispatch.call(this,event),event.result}},handlers:function(event,handlers){var i,handleObj,sel,matchedHandlers,matchedSelectors,handlerQueue=[],delegateCount=handlers.delegateCount,cur=event.target;if(delegateCount&&cur.nodeType&&!("click"===event.type&&event.button>=1))for(;cur!==this;cur=cur.parentNode||this)if(1===cur.nodeType&&("click"!==event.type||!0!==cur.disabled)){for(matchedHandlers=[],matchedSelectors={},i=0;i<delegateCount;i++)void 0===matchedSelectors[sel=(handleObj=handlers[i]).selector+" "]&&(matchedSelectors[sel]=handleObj.needsContext?jQuery(sel,this).index(cur)>-1:jQuery.find(sel,this,null,[cur]).length),matchedSelectors[sel]&&matchedHandlers.push(handleObj);matchedHandlers.length&&handlerQueue.push({elem:cur,handlers:matchedHandlers})}return cur=this,delegateCount<handlers.length&&handlerQueue.push({elem:cur,handlers:handlers.slice(delegateCount)}),handlerQueue},addProp:function(name,hook){Object.defineProperty(jQuery.Event.prototype,name,{enumerable:!0,configurable:!0,get:isFunction(hook)?function(){if(this.originalEvent)return hook(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[name]},set:function(value){Object.defineProperty(this,name,{enumerable:!0,configurable:!0,writable:!0,value:value})}})},fix:function(originalEvent){return originalEvent[jQuery.expando]?originalEvent:new jQuery.Event(originalEvent)},special:{load:{noBubble:!0},click:{setup:function(data){var el=this||data;return rcheckableType.test(el.type)&&el.click&&nodeName(el,"input")&&leverageNative(el,"click",returnTrue),!1},trigger:function(data){var el=this||data;return rcheckableType.test(el.type)&&el.click&&nodeName(el,"input")&&leverageNative(el,"click"),!0},_default:function(event){var target=event.target;return rcheckableType.test(target.type)&&target.click&&nodeName(target,"input")&&dataPriv.get(target,"click")||nodeName(target,"a")}},beforeunload:{postDispatch:function(event){void 0!==event.result&&event.originalEvent&&(event.originalEvent.returnValue=event.result)}}}},jQuery.removeEvent=function(elem,type,handle){elem.removeEventListener&&elem.removeEventListener(type,handle)},jQuery.Event=function(src,props){if(!(this instanceof jQuery.Event))return new jQuery.Event(src,props);src&&src.type?(this.originalEvent=src,this.type=src.type,this.isDefaultPrevented=src.defaultPrevented||void 0===src.defaultPrevented&&!1===src.returnValue?returnTrue:returnFalse,this.target=src.target&&3===src.target.nodeType?src.target.parentNode:src.target,this.currentTarget=src.currentTarget,this.relatedTarget=src.relatedTarget):this.type=src,props&&jQuery.extend(this,props),this.timeStamp=src&&src.timeStamp||Date.now(),this[jQuery.expando]=!0},jQuery.Event.prototype={constructor:jQuery.Event,isDefaultPrevented:returnFalse,isPropagationStopped:returnFalse,isImmediatePropagationStopped:returnFalse,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=returnTrue,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=returnTrue,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=returnTrue,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},jQuery.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,char:!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(event){var button=event.button;return null==event.which&&rkeyEvent.test(event.type)?null!=event.charCode?event.charCode:event.keyCode:!event.which&&void 0!==button&&rmouseEvent.test(event.type)?1&button?1:2&button?3:4&button?2:0:event.which}},jQuery.event.addProp),jQuery.each({focus:"focusin",blur:"focusout"},(function(type,delegateType){jQuery.event.special[type]={setup:function(){return leverageNative(this,type,expectSync),!1},trigger:function(){return leverageNative(this,type),!0},delegateType:delegateType}})),jQuery.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},(function(orig,fix){jQuery.event.special[orig]={delegateType:fix,bindType:fix,handle:function(event){var ret,target=this,related=event.relatedTarget,handleObj=event.handleObj;return related&&(related===target||jQuery.contains(target,related))||(event.type=handleObj.origType,ret=handleObj.handler.apply(this,arguments),event.type=fix),ret}}})),jQuery.fn.extend({on:function(types,selector,data,fn){return on(this,types,selector,data,fn)},one:function(types,selector,data,fn){return on(this,types,selector,data,fn,1)},off:function(types,selector,fn){var handleObj,type;if(types&&types.preventDefault&&types.handleObj)return handleObj=types.handleObj,jQuery(types.delegateTarget).off(handleObj.namespace?handleObj.origType+"."+handleObj.namespace:handleObj.origType,handleObj.selector,handleObj.handler),this;if("object"==typeof types){for(type in types)this.off(type,selector,types[type]);return this}return!1!==selector&&"function"!=typeof selector||(fn=selector,selector=void 0),!1===fn&&(fn=returnFalse),this.each((function(){jQuery.event.remove(this,types,fn,selector)}))}});var rnoInnerhtml=/<script|<style|<link/i,rchecked=/checked\s*(?:[^=]|=\s*.checked.)/i,rcleanScript=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function manipulationTarget(elem,content){return nodeName(elem,"table")&&nodeName(11!==content.nodeType?content:content.firstChild,"tr")&&jQuery(elem).children("tbody")[0]||elem}function disableScript(elem){return elem.type=(null!==elem.getAttribute("type"))+"/"+elem.type,elem}function restoreScript(elem){return"true/"===(elem.type||"").slice(0,5)?elem.type=elem.type.slice(5):elem.removeAttribute("type"),elem}function cloneCopyEvent(src,dest){var i,l,type,udataOld,udataCur,events;if(1===dest.nodeType){if(dataPriv.hasData(src)&&(events=dataPriv.get(src).events))for(type in dataPriv.remove(dest,"handle events"),events)for(i=0,l=events[type].length;i<l;i++)jQuery.event.add(dest,type,events[type][i]);dataUser.hasData(src)&&(udataOld=dataUser.access(src),udataCur=jQuery.extend({},udataOld),dataUser.set(dest,udataCur))}}function fixInput(src,dest){var nodeName=dest.nodeName.toLowerCase();"input"===nodeName&&rcheckableType.test(src.type)?dest.checked=src.checked:"input"!==nodeName&&"textarea"!==nodeName||(dest.defaultValue=src.defaultValue)}function domManip(collection,args,callback,ignored){args=flat(args);var fragment,first,scripts,hasScripts,node,doc,i=0,l=collection.length,iNoClone=l-1,value=args[0],valueIsFunction=isFunction(value);if(valueIsFunction||l>1&&"string"==typeof value&&!support.checkClone&&rchecked.test(value))return collection.each((function(index){var self=collection.eq(index);valueIsFunction&&(args[0]=value.call(this,index,self.html())),domManip(self,args,callback,ignored)}));if(l&&(first=(fragment=buildFragment(args,collection[0].ownerDocument,!1,collection,ignored)).firstChild,1===fragment.childNodes.length&&(fragment=first),first||ignored)){for(hasScripts=(scripts=jQuery.map(getAll(fragment,"script"),disableScript)).length;i<l;i++)node=fragment,i!==iNoClone&&(node=jQuery.clone(node,!0,!0),hasScripts&&jQuery.merge(scripts,getAll(node,"script"))),callback.call(collection[i],node,i);if(hasScripts)for(doc=scripts[scripts.length-1].ownerDocument,jQuery.map(scripts,restoreScript),i=0;i<hasScripts;i++)node=scripts[i],rscriptType.test(node.type||"")&&!dataPriv.access(node,"globalEval")&&jQuery.contains(doc,node)&&(node.src&&"module"!==(node.type||"").toLowerCase()?jQuery._evalUrl&&!node.noModule&&jQuery._evalUrl(node.src,{nonce:node.nonce||node.getAttribute("nonce")},doc):DOMEval(node.textContent.replace(rcleanScript,""),node,doc))}return collection}function remove(elem,selector,keepData){for(var node,nodes=selector?jQuery.filter(selector,elem):elem,i=0;null!=(node=nodes[i]);i++)keepData||1!==node.nodeType||jQuery.cleanData(getAll(node)),node.parentNode&&(keepData&&isAttached(node)&&setGlobalEval(getAll(node,"script")),node.parentNode.removeChild(node));return elem}jQuery.extend({htmlPrefilter:function(html){return html},clone:function(elem,dataAndEvents,deepDataAndEvents){var i,l,srcElements,destElements,clone=elem.cloneNode(!0),inPage=isAttached(elem);if(!(support.noCloneChecked||1!==elem.nodeType&&11!==elem.nodeType||jQuery.isXMLDoc(elem)))for(destElements=getAll(clone),i=0,l=(srcElements=getAll(elem)).length;i<l;i++)fixInput(srcElements[i],destElements[i]);if(dataAndEvents)if(deepDataAndEvents)for(srcElements=srcElements||getAll(elem),destElements=destElements||getAll(clone),i=0,l=srcElements.length;i<l;i++)cloneCopyEvent(srcElements[i],destElements[i]);else cloneCopyEvent(elem,clone);return(destElements=getAll(clone,"script")).length>0&&setGlobalEval(destElements,!inPage&&getAll(elem,"script")),clone},cleanData:function(elems){for(var data,elem,type,special=jQuery.event.special,i=0;void 0!==(elem=elems[i]);i++)if(acceptData(elem)){if(data=elem[dataPriv.expando]){if(data.events)for(type in data.events)special[type]?jQuery.event.remove(elem,type):jQuery.removeEvent(elem,type,data.handle);elem[dataPriv.expando]=void 0}elem[dataUser.expando]&&(elem[dataUser.expando]=void 0)}}}),jQuery.fn.extend({detach:function(selector){return remove(this,selector,!0)},remove:function(selector){return remove(this,selector)},text:function(value){return access(this,(function(value){return void 0===value?jQuery.text(this):this.empty().each((function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=value)}))}),null,value,arguments.length)},append:function(){return domManip(this,arguments,(function(elem){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||manipulationTarget(this,elem).appendChild(elem)}))},prepend:function(){return domManip(this,arguments,(function(elem){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var target=manipulationTarget(this,elem);target.insertBefore(elem,target.firstChild)}}))},before:function(){return domManip(this,arguments,(function(elem){this.parentNode&&this.parentNode.insertBefore(elem,this)}))},after:function(){return domManip(this,arguments,(function(elem){this.parentNode&&this.parentNode.insertBefore(elem,this.nextSibling)}))},empty:function(){for(var elem,i=0;null!=(elem=this[i]);i++)1===elem.nodeType&&(jQuery.cleanData(getAll(elem,!1)),elem.textContent="");return this},clone:function(dataAndEvents,deepDataAndEvents){return dataAndEvents=null!=dataAndEvents&&dataAndEvents,deepDataAndEvents=null==deepDataAndEvents?dataAndEvents:deepDataAndEvents,this.map((function(){return jQuery.clone(this,dataAndEvents,deepDataAndEvents)}))},html:function(value){return access(this,(function(value){var elem=this[0]||{},i=0,l=this.length;if(void 0===value&&1===elem.nodeType)return elem.innerHTML;if("string"==typeof value&&!rnoInnerhtml.test(value)&&!wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]){value=jQuery.htmlPrefilter(value);try{for(;i<l;i++)1===(elem=this[i]||{}).nodeType&&(jQuery.cleanData(getAll(elem,!1)),elem.innerHTML=value);elem=0}catch(e){}}elem&&this.empty().append(value)}),null,value,arguments.length)},replaceWith:function(){var ignored=[];return domManip(this,arguments,(function(elem){var parent=this.parentNode;jQuery.inArray(this,ignored)<0&&(jQuery.cleanData(getAll(this)),parent&&parent.replaceChild(elem,this))}),ignored)}}),jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},(function(name,original){jQuery.fn[name]=function(selector){for(var elems,ret=[],insert=jQuery(selector),last=insert.length-1,i=0;i<=last;i++)elems=i===last?this:this.clone(!0),jQuery(insert[i])[original](elems),push.apply(ret,elems.get());return this.pushStack(ret)}}));var rnumnonpx=new RegExp("^("+pnum+")(?!px)[a-z%]+$","i"),getStyles=function(elem){var view=elem.ownerDocument.defaultView;return view&&view.opener||(view=window),view.getComputedStyle(elem)},swap=function(elem,options,callback){var ret,name,old={};for(name in options)old[name]=elem.style[name],elem.style[name]=options[name];for(name in ret=callback.call(elem),options)elem.style[name]=old[name];return ret},rboxStyle=new RegExp(cssExpand.join("|"),"i");function curCSS(elem,name,computed){var width,minWidth,maxWidth,ret,style=elem.style;return(computed=computed||getStyles(elem))&&(""!==(ret=computed.getPropertyValue(name)||computed[name])||isAttached(elem)||(ret=jQuery.style(elem,name)),!support.pixelBoxStyles()&&rnumnonpx.test(ret)&&rboxStyle.test(name)&&(width=style.width,minWidth=style.minWidth,maxWidth=style.maxWidth,style.minWidth=style.maxWidth=style.width=ret,ret=computed.width,style.width=width,style.minWidth=minWidth,style.maxWidth=maxWidth)),void 0!==ret?ret+"":ret}function addGetHookIf(conditionFn,hookFn){return{get:function(){if(!conditionFn())return(this.get=hookFn).apply(this,arguments);delete this.get}}}!function(){function computeStyleTests(){if(div){container.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",div.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",documentElement.appendChild(container).appendChild(div);var divStyle=window.getComputedStyle(div);pixelPositionVal="1%"!==divStyle.top,reliableMarginLeftVal=12===roundPixelMeasures(divStyle.marginLeft),div.style.right="60%",pixelBoxStylesVal=36===roundPixelMeasures(divStyle.right),boxSizingReliableVal=36===roundPixelMeasures(divStyle.width),div.style.position="absolute",scrollboxSizeVal=12===roundPixelMeasures(div.offsetWidth/3),documentElement.removeChild(container),div=null}}function roundPixelMeasures(measure){return Math.round(parseFloat(measure))}var pixelPositionVal,boxSizingReliableVal,scrollboxSizeVal,pixelBoxStylesVal,reliableTrDimensionsVal,reliableMarginLeftVal,container=document.createElement("div"),div=document.createElement("div");div.style&&(div.style.backgroundClip="content-box",div.cloneNode(!0).style.backgroundClip="",support.clearCloneStyle="content-box"===div.style.backgroundClip,jQuery.extend(support,{boxSizingReliable:function(){return computeStyleTests(),boxSizingReliableVal},pixelBoxStyles:function(){return computeStyleTests(),pixelBoxStylesVal},pixelPosition:function(){return computeStyleTests(),pixelPositionVal},reliableMarginLeft:function(){return computeStyleTests(),reliableMarginLeftVal},scrollboxSize:function(){return computeStyleTests(),scrollboxSizeVal},reliableTrDimensions:function(){var table,tr,trChild,trStyle;return null==reliableTrDimensionsVal&&(table=document.createElement("table"),tr=document.createElement("tr"),trChild=document.createElement("div"),table.style.cssText="position:absolute;left:-11111px",tr.style.height="1px",trChild.style.height="9px",documentElement.appendChild(table).appendChild(tr).appendChild(trChild),trStyle=window.getComputedStyle(tr),reliableTrDimensionsVal=parseInt(trStyle.height)>3,documentElement.removeChild(table)),reliableTrDimensionsVal}}))}();var cssPrefixes=["Webkit","Moz","ms"],emptyStyle=document.createElement("div").style,vendorProps={};function finalPropName(name){var final=jQuery.cssProps[name]||vendorProps[name];return final||(name in emptyStyle?name:vendorProps[name]=function(name){for(var capName=name[0].toUpperCase()+name.slice(1),i=cssPrefixes.length;i--;)if((name=cssPrefixes[i]+capName)in emptyStyle)return name}(name)||name)}var rdisplayswap=/^(none|table(?!-c[ea]).+)/,rcustomProp=/^--/,cssShow={position:"absolute",visibility:"hidden",display:"block"},cssNormalTransform={letterSpacing:"0",fontWeight:"400"};function setPositiveNumber(_elem,value,subtract){var matches=rcssNum.exec(value);return matches?Math.max(0,matches[2]-(subtract||0))+(matches[3]||"px"):value}function boxModelAdjustment(elem,dimension,box,isBorderBox,styles,computedVal){var i="width"===dimension?1:0,extra=0,delta=0;if(box===(isBorderBox?"border":"content"))return 0;for(;i<4;i+=2)"margin"===box&&(delta+=jQuery.css(elem,box+cssExpand[i],!0,styles)),isBorderBox?("content"===box&&(delta-=jQuery.css(elem,"padding"+cssExpand[i],!0,styles)),"margin"!==box&&(delta-=jQuery.css(elem,"border"+cssExpand[i]+"Width",!0,styles))):(delta+=jQuery.css(elem,"padding"+cssExpand[i],!0,styles),"padding"!==box?delta+=jQuery.css(elem,"border"+cssExpand[i]+"Width",!0,styles):extra+=jQuery.css(elem,"border"+cssExpand[i]+"Width",!0,styles));return!isBorderBox&&computedVal>=0&&(delta+=Math.max(0,Math.ceil(elem["offset"+dimension[0].toUpperCase()+dimension.slice(1)]-computedVal-delta-extra-.5))||0),delta}function getWidthOrHeight(elem,dimension,extra){var styles=getStyles(elem),isBorderBox=(!support.boxSizingReliable()||extra)&&"border-box"===jQuery.css(elem,"boxSizing",!1,styles),valueIsBorderBox=isBorderBox,val=curCSS(elem,dimension,styles),offsetProp="offset"+dimension[0].toUpperCase()+dimension.slice(1);if(rnumnonpx.test(val)){if(!extra)return val;val="auto"}return(!support.boxSizingReliable()&&isBorderBox||!support.reliableTrDimensions()&&nodeName(elem,"tr")||"auto"===val||!parseFloat(val)&&"inline"===jQuery.css(elem,"display",!1,styles))&&elem.getClientRects().length&&(isBorderBox="border-box"===jQuery.css(elem,"boxSizing",!1,styles),(valueIsBorderBox=offsetProp in elem)&&(val=elem[offsetProp])),(val=parseFloat(val)||0)+boxModelAdjustment(elem,dimension,extra||(isBorderBox?"border":"content"),valueIsBorderBox,styles,val)+"px"}function Tween(elem,options,prop,end,easing){return new Tween.prototype.init(elem,options,prop,end,easing)}jQuery.extend({cssHooks:{opacity:{get:function(elem,computed){if(computed){var ret=curCSS(elem,"opacity");return""===ret?"1":ret}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(elem,name,value,extra){if(elem&&3!==elem.nodeType&&8!==elem.nodeType&&elem.style){var ret,type,hooks,origName=camelCase(name),isCustomProp=rcustomProp.test(name),style=elem.style;if(isCustomProp||(name=finalPropName(origName)),hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName],void 0===value)return hooks&&"get"in hooks&&void 0!==(ret=hooks.get(elem,!1,extra))?ret:style[name];"string"===(type=typeof value)&&(ret=rcssNum.exec(value))&&ret[1]&&(value=adjustCSS(elem,name,ret),type="number"),null!=value&&value==value&&("number"!==type||isCustomProp||(value+=ret&&ret[3]||(jQuery.cssNumber[origName]?"":"px")),support.clearCloneStyle||""!==value||0!==name.indexOf("background")||(style[name]="inherit"),hooks&&"set"in hooks&&void 0===(value=hooks.set(elem,value,extra))||(isCustomProp?style.setProperty(name,value):style[name]=value))}},css:function(elem,name,extra,styles){var val,num,hooks,origName=camelCase(name);return rcustomProp.test(name)||(name=finalPropName(origName)),(hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName])&&"get"in hooks&&(val=hooks.get(elem,!0,extra)),void 0===val&&(val=curCSS(elem,name,styles)),"normal"===val&&name in cssNormalTransform&&(val=cssNormalTransform[name]),""===extra||extra?(num=parseFloat(val),!0===extra||isFinite(num)?num||0:val):val}}),jQuery.each(["height","width"],(function(_i,dimension){jQuery.cssHooks[dimension]={get:function(elem,computed,extra){if(computed)return!rdisplayswap.test(jQuery.css(elem,"display"))||elem.getClientRects().length&&elem.getBoundingClientRect().width?getWidthOrHeight(elem,dimension,extra):swap(elem,cssShow,(function(){return getWidthOrHeight(elem,dimension,extra)}))},set:function(elem,value,extra){var matches,styles=getStyles(elem),scrollboxSizeBuggy=!support.scrollboxSize()&&"absolute"===styles.position,isBorderBox=(scrollboxSizeBuggy||extra)&&"border-box"===jQuery.css(elem,"boxSizing",!1,styles),subtract=extra?boxModelAdjustment(elem,dimension,extra,isBorderBox,styles):0;return isBorderBox&&scrollboxSizeBuggy&&(subtract-=Math.ceil(elem["offset"+dimension[0].toUpperCase()+dimension.slice(1)]-parseFloat(styles[dimension])-boxModelAdjustment(elem,dimension,"border",!1,styles)-.5)),subtract&&(matches=rcssNum.exec(value))&&"px"!==(matches[3]||"px")&&(elem.style[dimension]=value,value=jQuery.css(elem,dimension)),setPositiveNumber(0,value,subtract)}}})),jQuery.cssHooks.marginLeft=addGetHookIf(support.reliableMarginLeft,(function(elem,computed){if(computed)return(parseFloat(curCSS(elem,"marginLeft"))||elem.getBoundingClientRect().left-swap(elem,{marginLeft:0},(function(){return elem.getBoundingClientRect().left})))+"px"})),jQuery.each({margin:"",padding:"",border:"Width"},(function(prefix,suffix){jQuery.cssHooks[prefix+suffix]={expand:function(value){for(var i=0,expanded={},parts="string"==typeof value?value.split(" "):[value];i<4;i++)expanded[prefix+cssExpand[i]+suffix]=parts[i]||parts[i-2]||parts[0];return expanded}},"margin"!==prefix&&(jQuery.cssHooks[prefix+suffix].set=setPositiveNumber)})),jQuery.fn.extend({css:function(name,value){return access(this,(function(elem,name,value){var styles,len,map={},i=0;if(Array.isArray(name)){for(styles=getStyles(elem),len=name.length;i<len;i++)map[name[i]]=jQuery.css(elem,name[i],!1,styles);return map}return void 0!==value?jQuery.style(elem,name,value):jQuery.css(elem,name)}),name,value,arguments.length>1)}}),jQuery.Tween=Tween,Tween.prototype={constructor:Tween,init:function(elem,options,prop,end,easing,unit){this.elem=elem,this.prop=prop,this.easing=easing||jQuery.easing._default,this.options=options,this.start=this.now=this.cur(),this.end=end,this.unit=unit||(jQuery.cssNumber[prop]?"":"px")},cur:function(){var hooks=Tween.propHooks[this.prop];return hooks&&hooks.get?hooks.get(this):Tween.propHooks._default.get(this)},run:function(percent){var eased,hooks=Tween.propHooks[this.prop];return this.options.duration?this.pos=eased=jQuery.easing[this.easing](percent,this.options.duration*percent,0,1,this.options.duration):this.pos=eased=percent,this.now=(this.end-this.start)*eased+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),hooks&&hooks.set?hooks.set(this):Tween.propHooks._default.set(this),this}},Tween.prototype.init.prototype=Tween.prototype,Tween.propHooks={_default:{get:function(tween){var result;return 1!==tween.elem.nodeType||null!=tween.elem[tween.prop]&&null==tween.elem.style[tween.prop]?tween.elem[tween.prop]:(result=jQuery.css(tween.elem,tween.prop,""))&&"auto"!==result?result:0},set:function(tween){jQuery.fx.step[tween.prop]?jQuery.fx.step[tween.prop](tween):1!==tween.elem.nodeType||!jQuery.cssHooks[tween.prop]&&null==tween.elem.style[finalPropName(tween.prop)]?tween.elem[tween.prop]=tween.now:jQuery.style(tween.elem,tween.prop,tween.now+tween.unit)}}},Tween.propHooks.scrollTop=Tween.propHooks.scrollLeft={set:function(tween){tween.elem.nodeType&&tween.elem.parentNode&&(tween.elem[tween.prop]=tween.now)}},jQuery.easing={linear:function(p){return p},swing:function(p){return.5-Math.cos(p*Math.PI)/2},_default:"swing"},jQuery.fx=Tween.prototype.init,jQuery.fx.step={};var fxNow,inProgress,rfxtypes=/^(?:toggle|show|hide)$/,rrun=/queueHooks$/;function schedule(){inProgress&&(!1===document.hidden&&window.requestAnimationFrame?window.requestAnimationFrame(schedule):window.setTimeout(schedule,jQuery.fx.interval),jQuery.fx.tick())}function createFxNow(){return window.setTimeout((function(){fxNow=void 0})),fxNow=Date.now()}function genFx(type,includeWidth){var which,i=0,attrs={height:type};for(includeWidth=includeWidth?1:0;i<4;i+=2-includeWidth)attrs["margin"+(which=cssExpand[i])]=attrs["padding"+which]=type;return includeWidth&&(attrs.opacity=attrs.width=type),attrs}function createTween(value,prop,animation){for(var tween,collection=(Animation.tweeners[prop]||[]).concat(Animation.tweeners["*"]),index=0,length=collection.length;index<length;index++)if(tween=collection[index].call(animation,prop,value))return tween}function Animation(elem,properties,options){var result,stopped,index=0,length=Animation.prefilters.length,deferred=jQuery.Deferred().always((function(){delete tick.elem})),tick=function(){if(stopped)return!1;for(var currentTime=fxNow||createFxNow(),remaining=Math.max(0,animation.startTime+animation.duration-currentTime),percent=1-(remaining/animation.duration||0),index=0,length=animation.tweens.length;index<length;index++)animation.tweens[index].run(percent);return deferred.notifyWith(elem,[animation,percent,remaining]),percent<1&&length?remaining:(length||deferred.notifyWith(elem,[animation,1,0]),deferred.resolveWith(elem,[animation]),!1)},animation=deferred.promise({elem:elem,props:jQuery.extend({},properties),opts:jQuery.extend(!0,{specialEasing:{},easing:jQuery.easing._default},options),originalProperties:properties,originalOptions:options,startTime:fxNow||createFxNow(),duration:options.duration,tweens:[],createTween:function(prop,end){var tween=jQuery.Tween(elem,animation.opts,prop,end,animation.opts.specialEasing[prop]||animation.opts.easing);return animation.tweens.push(tween),tween},stop:function(gotoEnd){var index=0,length=gotoEnd?animation.tweens.length:0;if(stopped)return this;for(stopped=!0;index<length;index++)animation.tweens[index].run(1);return gotoEnd?(deferred.notifyWith(elem,[animation,1,0]),deferred.resolveWith(elem,[animation,gotoEnd])):deferred.rejectWith(elem,[animation,gotoEnd]),this}}),props=animation.props;for(!function(props,specialEasing){var index,name,easing,value,hooks;for(index in props)if(easing=specialEasing[name=camelCase(index)],value=props[index],Array.isArray(value)&&(easing=value[1],value=props[index]=value[0]),index!==name&&(props[name]=value,delete props[index]),(hooks=jQuery.cssHooks[name])&&"expand"in hooks)for(index in value=hooks.expand(value),delete props[name],value)index in props||(props[index]=value[index],specialEasing[index]=easing);else specialEasing[name]=easing}(props,animation.opts.specialEasing);index<length;index++)if(result=Animation.prefilters[index].call(animation,elem,props,animation.opts))return isFunction(result.stop)&&(jQuery._queueHooks(animation.elem,animation.opts.queue).stop=result.stop.bind(result)),result;return jQuery.map(props,createTween,animation),isFunction(animation.opts.start)&&animation.opts.start.call(elem,animation),animation.progress(animation.opts.progress).done(animation.opts.done,animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always),jQuery.fx.timer(jQuery.extend(tick,{elem:elem,anim:animation,queue:animation.opts.queue})),animation}jQuery.Animation=jQuery.extend(Animation,{tweeners:{"*":[function(prop,value){var tween=this.createTween(prop,value);return adjustCSS(tween.elem,prop,rcssNum.exec(value),tween),tween}]},tweener:function(props,callback){isFunction(props)?(callback=props,props=["*"]):props=props.match(rnothtmlwhite);for(var prop,index=0,length=props.length;index<length;index++)prop=props[index],Animation.tweeners[prop]=Animation.tweeners[prop]||[],Animation.tweeners[prop].unshift(callback)},prefilters:[function(elem,props,opts){var prop,value,toggle,hooks,oldfire,propTween,restoreDisplay,display,isBox="width"in props||"height"in props,anim=this,orig={},style=elem.style,hidden=elem.nodeType&&isHiddenWithinTree(elem),dataShow=dataPriv.get(elem,"fxshow");for(prop in opts.queue||(null==(hooks=jQuery._queueHooks(elem,"fx")).unqueued&&(hooks.unqueued=0,oldfire=hooks.empty.fire,hooks.empty.fire=function(){hooks.unqueued||oldfire()}),hooks.unqueued++,anim.always((function(){anim.always((function(){hooks.unqueued--,jQuery.queue(elem,"fx").length||hooks.empty.fire()}))}))),props)if(value=props[prop],rfxtypes.test(value)){if(delete props[prop],toggle=toggle||"toggle"===value,value===(hidden?"hide":"show")){if("show"!==value||!dataShow||void 0===dataShow[prop])continue;hidden=!0}orig[prop]=dataShow&&dataShow[prop]||jQuery.style(elem,prop)}if((propTween=!jQuery.isEmptyObject(props))||!jQuery.isEmptyObject(orig))for(prop in isBox&&1===elem.nodeType&&(opts.overflow=[style.overflow,style.overflowX,style.overflowY],null==(restoreDisplay=dataShow&&dataShow.display)&&(restoreDisplay=dataPriv.get(elem,"display")),"none"===(display=jQuery.css(elem,"display"))&&(restoreDisplay?display=restoreDisplay:(showHide([elem],!0),restoreDisplay=elem.style.display||restoreDisplay,display=jQuery.css(elem,"display"),showHide([elem]))),("inline"===display||"inline-block"===display&&null!=restoreDisplay)&&"none"===jQuery.css(elem,"float")&&(propTween||(anim.done((function(){style.display=restoreDisplay})),null==restoreDisplay&&(display=style.display,restoreDisplay="none"===display?"":display)),style.display="inline-block")),opts.overflow&&(style.overflow="hidden",anim.always((function(){style.overflow=opts.overflow[0],style.overflowX=opts.overflow[1],style.overflowY=opts.overflow[2]}))),propTween=!1,orig)propTween||(dataShow?"hidden"in dataShow&&(hidden=dataShow.hidden):dataShow=dataPriv.access(elem,"fxshow",{display:restoreDisplay}),toggle&&(dataShow.hidden=!hidden),hidden&&showHide([elem],!0),anim.done((function(){for(prop in hidden||showHide([elem]),dataPriv.remove(elem,"fxshow"),orig)jQuery.style(elem,prop,orig[prop])}))),propTween=createTween(hidden?dataShow[prop]:0,prop,anim),prop in dataShow||(dataShow[prop]=propTween.start,hidden&&(propTween.end=propTween.start,propTween.start=0))}],prefilter:function(callback,prepend){prepend?Animation.prefilters.unshift(callback):Animation.prefilters.push(callback)}}),jQuery.speed=function(speed,easing,fn){var opt=speed&&"object"==typeof speed?jQuery.extend({},speed):{complete:fn||!fn&&easing||isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&!isFunction(easing)&&easing};return jQuery.fx.off?opt.duration=0:"number"!=typeof opt.duration&&(opt.duration in jQuery.fx.speeds?opt.duration=jQuery.fx.speeds[opt.duration]:opt.duration=jQuery.fx.speeds._default),null!=opt.queue&&!0!==opt.queue||(opt.queue="fx"),opt.old=opt.complete,opt.complete=function(){isFunction(opt.old)&&opt.old.call(this),opt.queue&&jQuery.dequeue(this,opt.queue)},opt},jQuery.fn.extend({fadeTo:function(speed,to,easing,callback){return this.filter(isHiddenWithinTree).css("opacity",0).show().end().animate({opacity:to},speed,easing,callback)},animate:function(prop,speed,easing,callback){var empty=jQuery.isEmptyObject(prop),optall=jQuery.speed(speed,easing,callback),doAnimation=function(){var anim=Animation(this,jQuery.extend({},prop),optall);(empty||dataPriv.get(this,"finish"))&&anim.stop(!0)};return doAnimation.finish=doAnimation,empty||!1===optall.queue?this.each(doAnimation):this.queue(optall.queue,doAnimation)},stop:function(type,clearQueue,gotoEnd){var stopQueue=function(hooks){var stop=hooks.stop;delete hooks.stop,stop(gotoEnd)};return"string"!=typeof type&&(gotoEnd=clearQueue,clearQueue=type,type=void 0),clearQueue&&this.queue(type||"fx",[]),this.each((function(){var dequeue=!0,index=null!=type&&type+"queueHooks",timers=jQuery.timers,data=dataPriv.get(this);if(index)data[index]&&data[index].stop&&stopQueue(data[index]);else for(index in data)data[index]&&data[index].stop&&rrun.test(index)&&stopQueue(data[index]);for(index=timers.length;index--;)timers[index].elem!==this||null!=type&&timers[index].queue!==type||(timers[index].anim.stop(gotoEnd),dequeue=!1,timers.splice(index,1));!dequeue&&gotoEnd||jQuery.dequeue(this,type)}))},finish:function(type){return!1!==type&&(type=type||"fx"),this.each((function(){var index,data=dataPriv.get(this),queue=data[type+"queue"],hooks=data[type+"queueHooks"],timers=jQuery.timers,length=queue?queue.length:0;for(data.finish=!0,jQuery.queue(this,type,[]),hooks&&hooks.stop&&hooks.stop.call(this,!0),index=timers.length;index--;)timers[index].elem===this&&timers[index].queue===type&&(timers[index].anim.stop(!0),timers.splice(index,1));for(index=0;index<length;index++)queue[index]&&queue[index].finish&&queue[index].finish.call(this);delete data.finish}))}}),jQuery.each(["toggle","show","hide"],(function(_i,name){var cssFn=jQuery.fn[name];jQuery.fn[name]=function(speed,easing,callback){return null==speed||"boolean"==typeof speed?cssFn.apply(this,arguments):this.animate(genFx(name,!0),speed,easing,callback)}})),jQuery.each({slideDown:genFx("show"),slideUp:genFx("hide"),slideToggle:genFx("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},(function(name,props){jQuery.fn[name]=function(speed,easing,callback){return this.animate(props,speed,easing,callback)}})),jQuery.timers=[],jQuery.fx.tick=function(){var timer,i=0,timers=jQuery.timers;for(fxNow=Date.now();i<timers.length;i++)(timer=timers[i])()||timers[i]!==timer||timers.splice(i--,1);timers.length||jQuery.fx.stop(),fxNow=void 0},jQuery.fx.timer=function(timer){jQuery.timers.push(timer),jQuery.fx.start()},jQuery.fx.interval=13,jQuery.fx.start=function(){inProgress||(inProgress=!0,schedule())},jQuery.fx.stop=function(){inProgress=null},jQuery.fx.speeds={slow:600,fast:200,_default:400},jQuery.fn.delay=function(time,type){return time=jQuery.fx&&jQuery.fx.speeds[time]||time,type=type||"fx",this.queue(type,(function(next,hooks){var timeout=window.setTimeout(next,time);hooks.stop=function(){window.clearTimeout(timeout)}}))},function(){var input=document.createElement("input"),opt=document.createElement("select").appendChild(document.createElement("option"));input.type="checkbox",support.checkOn=""!==input.value,support.optSelected=opt.selected,(input=document.createElement("input")).value="t",input.type="radio",support.radioValue="t"===input.value}();var boolHook,attrHandle=jQuery.expr.attrHandle;jQuery.fn.extend({attr:function(name,value){return access(this,jQuery.attr,name,value,arguments.length>1)},removeAttr:function(name){return this.each((function(){jQuery.removeAttr(this,name)}))}}),jQuery.extend({attr:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(3!==nType&&8!==nType&&2!==nType)return void 0===elem.getAttribute?jQuery.prop(elem,name,value):(1===nType&&jQuery.isXMLDoc(elem)||(hooks=jQuery.attrHooks[name.toLowerCase()]||(jQuery.expr.match.bool.test(name)?boolHook:void 0)),void 0!==value?null===value?void jQuery.removeAttr(elem,name):hooks&&"set"in hooks&&void 0!==(ret=hooks.set(elem,value,name))?ret:(elem.setAttribute(name,value+""),value):hooks&&"get"in hooks&&null!==(ret=hooks.get(elem,name))?ret:null==(ret=jQuery.find.attr(elem,name))?void 0:ret)},attrHooks:{type:{set:function(elem,value){if(!support.radioValue&&"radio"===value&&nodeName(elem,"input")){var val=elem.value;return elem.setAttribute("type",value),val&&(elem.value=val),value}}}},removeAttr:function(elem,value){var name,i=0,attrNames=value&&value.match(rnothtmlwhite);if(attrNames&&1===elem.nodeType)for(;name=attrNames[i++];)elem.removeAttribute(name)}}),boolHook={set:function(elem,value,name){return!1===value?jQuery.removeAttr(elem,name):elem.setAttribute(name,name),name}},jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g),(function(_i,name){var getter=attrHandle[name]||jQuery.find.attr;attrHandle[name]=function(elem,name,isXML){var ret,handle,lowercaseName=name.toLowerCase();return isXML||(handle=attrHandle[lowercaseName],attrHandle[lowercaseName]=ret,ret=null!=getter(elem,name,isXML)?lowercaseName:null,attrHandle[lowercaseName]=handle),ret}}));var rfocusable=/^(?:input|select|textarea|button)$/i,rclickable=/^(?:a|area)$/i;function stripAndCollapse(value){return(value.match(rnothtmlwhite)||[]).join(" ")}function getClass(elem){return elem.getAttribute&&elem.getAttribute("class")||""}function classesToArray(value){return Array.isArray(value)?value:"string"==typeof value&&value.match(rnothtmlwhite)||[]}jQuery.fn.extend({prop:function(name,value){return access(this,jQuery.prop,name,value,arguments.length>1)},removeProp:function(name){return this.each((function(){delete this[jQuery.propFix[name]||name]}))}}),jQuery.extend({prop:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(3!==nType&&8!==nType&&2!==nType)return 1===nType&&jQuery.isXMLDoc(elem)||(name=jQuery.propFix[name]||name,hooks=jQuery.propHooks[name]),void 0!==value?hooks&&"set"in hooks&&void 0!==(ret=hooks.set(elem,value,name))?ret:elem[name]=value:hooks&&"get"in hooks&&null!==(ret=hooks.get(elem,name))?ret:elem[name]},propHooks:{tabIndex:{get:function(elem){var tabindex=jQuery.find.attr(elem,"tabindex");return tabindex?parseInt(tabindex,10):rfocusable.test(elem.nodeName)||rclickable.test(elem.nodeName)&&elem.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),support.optSelected||(jQuery.propHooks.selected={get:function(elem){var parent=elem.parentNode;return parent&&parent.parentNode&&parent.parentNode.selectedIndex,null},set:function(elem){var parent=elem.parentNode;parent&&(parent.selectedIndex,parent.parentNode&&parent.parentNode.selectedIndex)}}),jQuery.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],(function(){jQuery.propFix[this.toLowerCase()]=this})),jQuery.fn.extend({addClass:function(value){var classes,elem,cur,curValue,clazz,j,finalValue,i=0;if(isFunction(value))return this.each((function(j){jQuery(this).addClass(value.call(this,j,getClass(this)))}));if((classes=classesToArray(value)).length)for(;elem=this[i++];)if(curValue=getClass(elem),cur=1===elem.nodeType&&" "+stripAndCollapse(curValue)+" "){for(j=0;clazz=classes[j++];)cur.indexOf(" "+clazz+" ")<0&&(cur+=clazz+" ");curValue!==(finalValue=stripAndCollapse(cur))&&elem.setAttribute("class",finalValue)}return this},removeClass:function(value){var classes,elem,cur,curValue,clazz,j,finalValue,i=0;if(isFunction(value))return this.each((function(j){jQuery(this).removeClass(value.call(this,j,getClass(this)))}));if(!arguments.length)return this.attr("class","");if((classes=classesToArray(value)).length)for(;elem=this[i++];)if(curValue=getClass(elem),cur=1===elem.nodeType&&" "+stripAndCollapse(curValue)+" "){for(j=0;clazz=classes[j++];)for(;cur.indexOf(" "+clazz+" ")>-1;)cur=cur.replace(" "+clazz+" "," ");curValue!==(finalValue=stripAndCollapse(cur))&&elem.setAttribute("class",finalValue)}return this},toggleClass:function(value,stateVal){var type=typeof value,isValidValue="string"===type||Array.isArray(value);return"boolean"==typeof stateVal&&isValidValue?stateVal?this.addClass(value):this.removeClass(value):isFunction(value)?this.each((function(i){jQuery(this).toggleClass(value.call(this,i,getClass(this),stateVal),stateVal)})):this.each((function(){var className,i,self,classNames;if(isValidValue)for(i=0,self=jQuery(this),classNames=classesToArray(value);className=classNames[i++];)self.hasClass(className)?self.removeClass(className):self.addClass(className);else void 0!==value&&"boolean"!==type||((className=getClass(this))&&dataPriv.set(this,"__className__",className),this.setAttribute&&this.setAttribute("class",className||!1===value?"":dataPriv.get(this,"__className__")||""))}))},hasClass:function(selector){var className,elem,i=0;for(className=" "+selector+" ";elem=this[i++];)if(1===elem.nodeType&&(" "+stripAndCollapse(getClass(elem))+" ").indexOf(className)>-1)return!0;return!1}});var rreturn=/\r/g;jQuery.fn.extend({val:function(value){var hooks,ret,valueIsFunction,elem=this[0];return arguments.length?(valueIsFunction=isFunction(value),this.each((function(i){var val;1===this.nodeType&&(null==(val=valueIsFunction?value.call(this,i,jQuery(this).val()):value)?val="":"number"==typeof val?val+="":Array.isArray(val)&&(val=jQuery.map(val,(function(value){return null==value?"":value+""}))),(hooks=jQuery.valHooks[this.type]||jQuery.valHooks[this.nodeName.toLowerCase()])&&"set"in hooks&&void 0!==hooks.set(this,val,"value")||(this.value=val))}))):elem?(hooks=jQuery.valHooks[elem.type]||jQuery.valHooks[elem.nodeName.toLowerCase()])&&"get"in hooks&&void 0!==(ret=hooks.get(elem,"value"))?ret:"string"==typeof(ret=elem.value)?ret.replace(rreturn,""):null==ret?"":ret:void 0}}),jQuery.extend({valHooks:{option:{get:function(elem){var val=jQuery.find.attr(elem,"value");return null!=val?val:stripAndCollapse(jQuery.text(elem))}},select:{get:function(elem){var value,option,i,options=elem.options,index=elem.selectedIndex,one="select-one"===elem.type,values=one?null:[],max=one?index+1:options.length;for(i=index<0?max:one?index:0;i<max;i++)if(((option=options[i]).selected||i===index)&&!option.disabled&&(!option.parentNode.disabled||!nodeName(option.parentNode,"optgroup"))){if(value=jQuery(option).val(),one)return value;values.push(value)}return values},set:function(elem,value){for(var optionSet,option,options=elem.options,values=jQuery.makeArray(value),i=options.length;i--;)((option=options[i]).selected=jQuery.inArray(jQuery.valHooks.option.get(option),values)>-1)&&(optionSet=!0);return optionSet||(elem.selectedIndex=-1),values}}}}),jQuery.each(["radio","checkbox"],(function(){jQuery.valHooks[this]={set:function(elem,value){if(Array.isArray(value))return elem.checked=jQuery.inArray(jQuery(elem).val(),value)>-1}},support.checkOn||(jQuery.valHooks[this].get=function(elem){return null===elem.getAttribute("value")?"on":elem.value})})),support.focusin="onfocusin"in window;var rfocusMorph=/^(?:focusinfocus|focusoutblur)$/,stopPropagationCallback=function(e){e.stopPropagation()};jQuery.extend(jQuery.event,{trigger:function(event,data,elem,onlyHandlers){var i,cur,tmp,bubbleType,ontype,handle,special,lastElement,eventPath=[elem||document],type=hasOwn.call(event,"type")?event.type:event,namespaces=hasOwn.call(event,"namespace")?event.namespace.split("."):[];if(cur=lastElement=tmp=elem=elem||document,3!==elem.nodeType&&8!==elem.nodeType&&!rfocusMorph.test(type+jQuery.event.triggered)&&(type.indexOf(".")>-1&&(namespaces=type.split("."),type=namespaces.shift(),namespaces.sort()),ontype=type.indexOf(":")<0&&"on"+type,(event=event[jQuery.expando]?event:new jQuery.Event(type,"object"==typeof event&&event)).isTrigger=onlyHandlers?2:3,event.namespace=namespaces.join("."),event.rnamespace=event.namespace?new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,event.result=void 0,event.target||(event.target=elem),data=null==data?[event]:jQuery.makeArray(data,[event]),special=jQuery.event.special[type]||{},onlyHandlers||!special.trigger||!1!==special.trigger.apply(elem,data))){if(!onlyHandlers&&!special.noBubble&&!isWindow(elem)){for(bubbleType=special.delegateType||type,rfocusMorph.test(bubbleType+type)||(cur=cur.parentNode);cur;cur=cur.parentNode)eventPath.push(cur),tmp=cur;tmp===(elem.ownerDocument||document)&&eventPath.push(tmp.defaultView||tmp.parentWindow||window)}for(i=0;(cur=eventPath[i++])&&!event.isPropagationStopped();)lastElement=cur,event.type=i>1?bubbleType:special.bindType||type,(handle=(dataPriv.get(cur,"events")||Object.create(null))[event.type]&&dataPriv.get(cur,"handle"))&&handle.apply(cur,data),(handle=ontype&&cur[ontype])&&handle.apply&&acceptData(cur)&&(event.result=handle.apply(cur,data),!1===event.result&&event.preventDefault());return event.type=type,onlyHandlers||event.isDefaultPrevented()||special._default&&!1!==special._default.apply(eventPath.pop(),data)||!acceptData(elem)||ontype&&isFunction(elem[type])&&!isWindow(elem)&&((tmp=elem[ontype])&&(elem[ontype]=null),jQuery.event.triggered=type,event.isPropagationStopped()&&lastElement.addEventListener(type,stopPropagationCallback),elem[type](),event.isPropagationStopped()&&lastElement.removeEventListener(type,stopPropagationCallback),jQuery.event.triggered=void 0,tmp&&(elem[ontype]=tmp)),event.result}},simulate:function(type,elem,event){var e=jQuery.extend(new jQuery.Event,event,{type:type,isSimulated:!0});jQuery.event.trigger(e,null,elem)}}),jQuery.fn.extend({trigger:function(type,data){return this.each((function(){jQuery.event.trigger(type,data,this)}))},triggerHandler:function(type,data){var elem=this[0];if(elem)return jQuery.event.trigger(type,data,elem,!0)}}),support.focusin||jQuery.each({focus:"focusin",blur:"focusout"},(function(orig,fix){var handler=function(event){jQuery.event.simulate(fix,event.target,jQuery.event.fix(event))};jQuery.event.special[fix]={setup:function(){var doc=this.ownerDocument||this.document||this,attaches=dataPriv.access(doc,fix);attaches||doc.addEventListener(orig,handler,!0),dataPriv.access(doc,fix,(attaches||0)+1)},teardown:function(){var doc=this.ownerDocument||this.document||this,attaches=dataPriv.access(doc,fix)-1;attaches?dataPriv.access(doc,fix,attaches):(doc.removeEventListener(orig,handler,!0),dataPriv.remove(doc,fix))}}}));var location=window.location,nonce={guid:Date.now()},rquery=/\?/;jQuery.parseXML=function(data){var xml;if(!data||"string"!=typeof data)return null;try{xml=(new window.DOMParser).parseFromString(data,"text/xml")}catch(e){xml=void 0}return xml&&!xml.getElementsByTagName("parsererror").length||jQuery.error("Invalid XML: "+data),xml};var rbracket=/\[\]$/,rCRLF=/\r?\n/g,rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i,rsubmittable=/^(?:input|select|textarea|keygen)/i;function buildParams(prefix,obj,traditional,add){var name;if(Array.isArray(obj))jQuery.each(obj,(function(i,v){traditional||rbracket.test(prefix)?add(prefix,v):buildParams(prefix+"["+("object"==typeof v&&null!=v?i:"")+"]",v,traditional,add)}));else if(traditional||"object"!==toType(obj))add(prefix,obj);else for(name in obj)buildParams(prefix+"["+name+"]",obj[name],traditional,add)}jQuery.param=function(a,traditional){var prefix,s=[],add=function(key,valueOrFunction){var value=isFunction(valueOrFunction)?valueOrFunction():valueOrFunction;s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(null==value?"":value)};if(null==a)return"";if(Array.isArray(a)||a.jquery&&!jQuery.isPlainObject(a))jQuery.each(a,(function(){add(this.name,this.value)}));else for(prefix in a)buildParams(prefix,a[prefix],traditional,add);return s.join("&")},jQuery.fn.extend({serialize:function(){return jQuery.param(this.serializeArray())},serializeArray:function(){return this.map((function(){var elements=jQuery.prop(this,"elements");return elements?jQuery.makeArray(elements):this})).filter((function(){var type=this.type;return this.name&&!jQuery(this).is(":disabled")&&rsubmittable.test(this.nodeName)&&!rsubmitterTypes.test(type)&&(this.checked||!rcheckableType.test(type))})).map((function(_i,elem){var val=jQuery(this).val();return null==val?null:Array.isArray(val)?jQuery.map(val,(function(val){return{name:elem.name,value:val.replace(rCRLF,"\r\n")}})):{name:elem.name,value:val.replace(rCRLF,"\r\n")}})).get()}});var r20=/%20/g,rhash=/#.*$/,rantiCache=/([?&])_=[^&]*/,rheaders=/^(.*?):[ \t]*([^\r\n]*)$/gm,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,prefilters={},transports={},allTypes="*/".concat("*"),originAnchor=document.createElement("a");function addToPrefiltersOrTransports(structure){return function(dataTypeExpression,func){"string"!=typeof dataTypeExpression&&(func=dataTypeExpression,dataTypeExpression="*");var dataType,i=0,dataTypes=dataTypeExpression.toLowerCase().match(rnothtmlwhite)||[];if(isFunction(func))for(;dataType=dataTypes[i++];)"+"===dataType[0]?(dataType=dataType.slice(1)||"*",(structure[dataType]=structure[dataType]||[]).unshift(func)):(structure[dataType]=structure[dataType]||[]).push(func)}}function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR){var inspected={},seekingTransport=structure===transports;function inspect(dataType){var selected;return inspected[dataType]=!0,jQuery.each(structure[dataType]||[],(function(_,prefilterOrFactory){var dataTypeOrTransport=prefilterOrFactory(options,originalOptions,jqXHR);return"string"!=typeof dataTypeOrTransport||seekingTransport||inspected[dataTypeOrTransport]?seekingTransport?!(selected=dataTypeOrTransport):void 0:(options.dataTypes.unshift(dataTypeOrTransport),inspect(dataTypeOrTransport),!1)})),selected}return inspect(options.dataTypes[0])||!inspected["*"]&&inspect("*")}function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src)void 0!==src[key]&&((flatOptions[key]?target:deep||(deep={}))[key]=src[key]);return deep&&jQuery.extend(!0,target,deep),target}originAnchor.href=location.href,jQuery.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:location.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(location.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":allTypes,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":jQuery.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(target,settings){return settings?ajaxExtend(ajaxExtend(target,jQuery.ajaxSettings),settings):ajaxExtend(jQuery.ajaxSettings,target)},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(url,options){"object"==typeof url&&(options=url,url=void 0),options=options||{};var transport,cacheURL,responseHeadersString,responseHeaders,timeoutTimer,urlAnchor,completed,fireGlobals,i,uncached,s=jQuery.ajaxSetup({},options),callbackContext=s.context||s,globalEventContext=s.context&&(callbackContext.nodeType||callbackContext.jquery)?jQuery(callbackContext):jQuery.event,deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),statusCode=s.statusCode||{},requestHeaders={},requestHeadersNames={},strAbort="canceled",jqXHR={readyState:0,getResponseHeader:function(key){var match;if(completed){if(!responseHeaders)for(responseHeaders={};match=rheaders.exec(responseHeadersString);)responseHeaders[match[1].toLowerCase()+" "]=(responseHeaders[match[1].toLowerCase()+" "]||[]).concat(match[2]);match=responseHeaders[key.toLowerCase()+" "]}return null==match?null:match.join(", ")},getAllResponseHeaders:function(){return completed?responseHeadersString:null},setRequestHeader:function(name,value){return null==completed&&(name=requestHeadersNames[name.toLowerCase()]=requestHeadersNames[name.toLowerCase()]||name,requestHeaders[name]=value),this},overrideMimeType:function(type){return null==completed&&(s.mimeType=type),this},statusCode:function(map){var code;if(map)if(completed)jqXHR.always(map[jqXHR.status]);else for(code in map)statusCode[code]=[statusCode[code],map[code]];return this},abort:function(statusText){var finalText=statusText||strAbort;return transport&&transport.abort(finalText),done(0,finalText),this}};if(deferred.promise(jqXHR),s.url=((url||s.url||location.href)+"").replace(rprotocol,location.protocol+"//"),s.type=options.method||options.type||s.method||s.type,s.dataTypes=(s.dataType||"*").toLowerCase().match(rnothtmlwhite)||[""],null==s.crossDomain){urlAnchor=document.createElement("a");try{urlAnchor.href=s.url,urlAnchor.href=urlAnchor.href,s.crossDomain=originAnchor.protocol+"//"+originAnchor.host!=urlAnchor.protocol+"//"+urlAnchor.host}catch(e){s.crossDomain=!0}}if(s.data&&s.processData&&"string"!=typeof s.data&&(s.data=jQuery.param(s.data,s.traditional)),inspectPrefiltersOrTransports(prefilters,s,options,jqXHR),completed)return jqXHR;for(i in(fireGlobals=jQuery.event&&s.global)&&0==jQuery.active++&&jQuery.event.trigger("ajaxStart"),s.type=s.type.toUpperCase(),s.hasContent=!rnoContent.test(s.type),cacheURL=s.url.replace(rhash,""),s.hasContent?s.data&&s.processData&&0===(s.contentType||"").indexOf("application/x-www-form-urlencoded")&&(s.data=s.data.replace(r20,"+")):(uncached=s.url.slice(cacheURL.length),s.data&&(s.processData||"string"==typeof s.data)&&(cacheURL+=(rquery.test(cacheURL)?"&":"?")+s.data,delete s.data),!1===s.cache&&(cacheURL=cacheURL.replace(rantiCache,"$1"),uncached=(rquery.test(cacheURL)?"&":"?")+"_="+nonce.guid+++uncached),s.url=cacheURL+uncached),s.ifModified&&(jQuery.lastModified[cacheURL]&&jqXHR.setRequestHeader("If-Modified-Since",jQuery.lastModified[cacheURL]),jQuery.etag[cacheURL]&&jqXHR.setRequestHeader("If-None-Match",jQuery.etag[cacheURL])),(s.data&&s.hasContent&&!1!==s.contentType||options.contentType)&&jqXHR.setRequestHeader("Content-Type",s.contentType),jqXHR.setRequestHeader("Accept",s.dataTypes[0]&&s.accepts[s.dataTypes[0]]?s.accepts[s.dataTypes[0]]+("*"!==s.dataTypes[0]?", "+allTypes+"; q=0.01":""):s.accepts["*"]),s.headers)jqXHR.setRequestHeader(i,s.headers[i]);if(s.beforeSend&&(!1===s.beforeSend.call(callbackContext,jqXHR,s)||completed))return jqXHR.abort();if(strAbort="abort",completeDeferred.add(s.complete),jqXHR.done(s.success),jqXHR.fail(s.error),transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR)){if(jqXHR.readyState=1,fireGlobals&&globalEventContext.trigger("ajaxSend",[jqXHR,s]),completed)return jqXHR;s.async&&s.timeout>0&&(timeoutTimer=window.setTimeout((function(){jqXHR.abort("timeout")}),s.timeout));try{completed=!1,transport.send(requestHeaders,done)}catch(e){if(completed)throw e;done(-1,e)}}else done(-1,"No Transport");function done(status,nativeStatusText,responses,headers){var isSuccess,success,error,response,modified,statusText=nativeStatusText;completed||(completed=!0,timeoutTimer&&window.clearTimeout(timeoutTimer),transport=void 0,responseHeadersString=headers||"",jqXHR.readyState=status>0?4:0,isSuccess=status>=200&&status<300||304===status,responses&&(response=function(s,jqXHR,responses){for(var ct,type,finalDataType,firstDataType,contents=s.contents,dataTypes=s.dataTypes;"*"===dataTypes[0];)dataTypes.shift(),void 0===ct&&(ct=s.mimeType||jqXHR.getResponseHeader("Content-Type"));if(ct)for(type in contents)if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break}if(dataTypes[0]in responses)finalDataType=dataTypes[0];else{for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break}firstDataType||(firstDataType=type)}finalDataType=finalDataType||firstDataType}if(finalDataType)return finalDataType!==dataTypes[0]&&dataTypes.unshift(finalDataType),responses[finalDataType]}(s,jqXHR,responses)),!isSuccess&&jQuery.inArray("script",s.dataTypes)>-1&&(s.converters["text script"]=function(){}),response=function(s,response,jqXHR,isSuccess){var conv2,current,conv,tmp,prev,converters={},dataTypes=s.dataTypes.slice();if(dataTypes[1])for(conv in s.converters)converters[conv.toLowerCase()]=s.converters[conv];for(current=dataTypes.shift();current;)if(s.responseFields[current]&&(jqXHR[s.responseFields[current]]=response),!prev&&isSuccess&&s.dataFilter&&(response=s.dataFilter(response,s.dataType)),prev=current,current=dataTypes.shift())if("*"===current)current=prev;else if("*"!==prev&&prev!==current){if(!(conv=converters[prev+" "+current]||converters["* "+current]))for(conv2 in converters)if((tmp=conv2.split(" "))[1]===current&&(conv=converters[prev+" "+tmp[0]]||converters["* "+tmp[0]])){!0===conv?conv=converters[conv2]:!0!==converters[conv2]&&(current=tmp[0],dataTypes.unshift(tmp[1]));break}if(!0!==conv)if(conv&&s.throws)response=conv(response);else try{response=conv(response)}catch(e){return{state:"parsererror",error:conv?e:"No conversion from "+prev+" to "+current}}}return{state:"success",data:response}}(s,response,jqXHR,isSuccess),isSuccess?(s.ifModified&&((modified=jqXHR.getResponseHeader("Last-Modified"))&&(jQuery.lastModified[cacheURL]=modified),(modified=jqXHR.getResponseHeader("etag"))&&(jQuery.etag[cacheURL]=modified)),204===status||"HEAD"===s.type?statusText="nocontent":304===status?statusText="notmodified":(statusText=response.state,success=response.data,isSuccess=!(error=response.error))):(error=statusText,!status&&statusText||(statusText="error",status<0&&(status=0))),jqXHR.status=status,jqXHR.statusText=(nativeStatusText||statusText)+"",isSuccess?deferred.resolveWith(callbackContext,[success,statusText,jqXHR]):deferred.rejectWith(callbackContext,[jqXHR,statusText,error]),jqXHR.statusCode(statusCode),statusCode=void 0,fireGlobals&&globalEventContext.trigger(isSuccess?"ajaxSuccess":"ajaxError",[jqXHR,s,isSuccess?success:error]),completeDeferred.fireWith(callbackContext,[jqXHR,statusText]),fireGlobals&&(globalEventContext.trigger("ajaxComplete",[jqXHR,s]),--jQuery.active||jQuery.event.trigger("ajaxStop")))}return jqXHR},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json")},getScript:function(url,callback){return jQuery.get(url,void 0,callback,"script")}}),jQuery.each(["get","post"],(function(_i,method){jQuery[method]=function(url,data,callback,type){return isFunction(data)&&(type=type||callback,callback=data,data=void 0),jQuery.ajax(jQuery.extend({url:url,type:method,dataType:type,data:data,success:callback},jQuery.isPlainObject(url)&&url))}})),jQuery.ajaxPrefilter((function(s){var i;for(i in s.headers)"content-type"===i.toLowerCase()&&(s.contentType=s.headers[i]||"")})),jQuery._evalUrl=function(url,options,doc){return jQuery.ajax({url:url,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(response){jQuery.globalEval(response,options,doc)}})},jQuery.fn.extend({wrapAll:function(html){var wrap;return this[0]&&(isFunction(html)&&(html=html.call(this[0])),wrap=jQuery(html,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&wrap.insertBefore(this[0]),wrap.map((function(){for(var elem=this;elem.firstElementChild;)elem=elem.firstElementChild;return elem})).append(this)),this},wrapInner:function(html){return isFunction(html)?this.each((function(i){jQuery(this).wrapInner(html.call(this,i))})):this.each((function(){var self=jQuery(this),contents=self.contents();contents.length?contents.wrapAll(html):self.append(html)}))},wrap:function(html){var htmlIsFunction=isFunction(html);return this.each((function(i){jQuery(this).wrapAll(htmlIsFunction?html.call(this,i):html)}))},unwrap:function(selector){return this.parent(selector).not("body").each((function(){jQuery(this).replaceWith(this.childNodes)})),this}}),jQuery.expr.pseudos.hidden=function(elem){return!jQuery.expr.pseudos.visible(elem)},jQuery.expr.pseudos.visible=function(elem){return!!(elem.offsetWidth||elem.offsetHeight||elem.getClientRects().length)},jQuery.ajaxSettings.xhr=function(){try{return new window.XMLHttpRequest}catch(e){}};var xhrSuccessStatus={0:200,1223:204},xhrSupported=jQuery.ajaxSettings.xhr();support.cors=!!xhrSupported&&"withCredentials"in xhrSupported,support.ajax=xhrSupported=!!xhrSupported,jQuery.ajaxTransport((function(options){var callback,errorCallback;if(support.cors||xhrSupported&&!options.crossDomain)return{send:function(headers,complete){var i,xhr=options.xhr();if(xhr.open(options.type,options.url,options.async,options.username,options.password),options.xhrFields)for(i in options.xhrFields)xhr[i]=options.xhrFields[i];for(i in options.mimeType&&xhr.overrideMimeType&&xhr.overrideMimeType(options.mimeType),options.crossDomain||headers["X-Requested-With"]||(headers["X-Requested-With"]="XMLHttpRequest"),headers)xhr.setRequestHeader(i,headers[i]);callback=function(type){return function(){callback&&(callback=errorCallback=xhr.onload=xhr.onerror=xhr.onabort=xhr.ontimeout=xhr.onreadystatechange=null,"abort"===type?xhr.abort():"error"===type?"number"!=typeof xhr.status?complete(0,"error"):complete(xhr.status,xhr.statusText):complete(xhrSuccessStatus[xhr.status]||xhr.status,xhr.statusText,"text"!==(xhr.responseType||"text")||"string"!=typeof xhr.responseText?{binary:xhr.response}:{text:xhr.responseText},xhr.getAllResponseHeaders()))}},xhr.onload=callback(),errorCallback=xhr.onerror=xhr.ontimeout=callback("error"),void 0!==xhr.onabort?xhr.onabort=errorCallback:xhr.onreadystatechange=function(){4===xhr.readyState&&window.setTimeout((function(){callback&&errorCallback()}))},callback=callback("abort");try{xhr.send(options.hasContent&&options.data||null)}catch(e){if(callback)throw e}},abort:function(){callback&&callback()}}})),jQuery.ajaxPrefilter((function(s){s.crossDomain&&(s.contents.script=!1)})),jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(text){return jQuery.globalEval(text),text}}}),jQuery.ajaxPrefilter("script",(function(s){void 0===s.cache&&(s.cache=!1),s.crossDomain&&(s.type="GET")})),jQuery.ajaxTransport("script",(function(s){var script,callback;if(s.crossDomain||s.scriptAttrs)return{send:function(_,complete){script=jQuery("<script>").attr(s.scriptAttrs||{}).prop({charset:s.scriptCharset,src:s.url}).on("load error",callback=function(evt){script.remove(),callback=null,evt&&complete("error"===evt.type?404:200,evt.type)}),document.head.appendChild(script[0])},abort:function(){callback&&callback()}}}));var body,oldCallbacks=[],rjsonp=/(=)\?(?=&|$)|\?\?/;jQuery.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var callback=oldCallbacks.pop()||jQuery.expando+"_"+nonce.guid++;return this[callback]=!0,callback}}),jQuery.ajaxPrefilter("json jsonp",(function(s,originalSettings,jqXHR){var callbackName,overwritten,responseContainer,jsonProp=!1!==s.jsonp&&(rjsonp.test(s.url)?"url":"string"==typeof s.data&&0===(s.contentType||"").indexOf("application/x-www-form-urlencoded")&&rjsonp.test(s.data)&&"data");if(jsonProp||"jsonp"===s.dataTypes[0])return callbackName=s.jsonpCallback=isFunction(s.jsonpCallback)?s.jsonpCallback():s.jsonpCallback,jsonProp?s[jsonProp]=s[jsonProp].replace(rjsonp,"$1"+callbackName):!1!==s.jsonp&&(s.url+=(rquery.test(s.url)?"&":"?")+s.jsonp+"="+callbackName),s.converters["script json"]=function(){return responseContainer||jQuery.error(callbackName+" was not called"),responseContainer[0]},s.dataTypes[0]="json",overwritten=window[callbackName],window[callbackName]=function(){responseContainer=arguments},jqXHR.always((function(){void 0===overwritten?jQuery(window).removeProp(callbackName):window[callbackName]=overwritten,s[callbackName]&&(s.jsonpCallback=originalSettings.jsonpCallback,oldCallbacks.push(callbackName)),responseContainer&&isFunction(overwritten)&&overwritten(responseContainer[0]),responseContainer=overwritten=void 0})),"script"})),support.createHTMLDocument=((body=document.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===body.childNodes.length),jQuery.parseHTML=function(data,context,keepScripts){return"string"!=typeof data?[]:("boolean"==typeof context&&(keepScripts=context,context=!1),context||(support.createHTMLDocument?((base=(context=document.implementation.createHTMLDocument("")).createElement("base")).href=document.location.href,context.head.appendChild(base)):context=document),scripts=!keepScripts&&[],(parsed=rsingleTag.exec(data))?[context.createElement(parsed[1])]:(parsed=buildFragment([data],context,scripts),scripts&&scripts.length&&jQuery(scripts).remove(),jQuery.merge([],parsed.childNodes)));var base,parsed,scripts},jQuery.fn.load=function(url,params,callback){var selector,type,response,self=this,off=url.indexOf(" ");return off>-1&&(selector=stripAndCollapse(url.slice(off)),url=url.slice(0,off)),isFunction(params)?(callback=params,params=void 0):params&&"object"==typeof params&&(type="POST"),self.length>0&&jQuery.ajax({url:url,type:type||"GET",dataType:"html",data:params}).done((function(responseText){response=arguments,self.html(selector?jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector):responseText)})).always(callback&&function(jqXHR,status){self.each((function(){callback.apply(this,response||[jqXHR.responseText,status,jqXHR])}))}),this},jQuery.expr.pseudos.animated=function(elem){return jQuery.grep(jQuery.timers,(function(fn){return elem===fn.elem})).length},jQuery.offset={setOffset:function(elem,options,i){var curPosition,curLeft,curCSSTop,curTop,curOffset,curCSSLeft,position=jQuery.css(elem,"position"),curElem=jQuery(elem),props={};"static"===position&&(elem.style.position="relative"),curOffset=curElem.offset(),curCSSTop=jQuery.css(elem,"top"),curCSSLeft=jQuery.css(elem,"left"),("absolute"===position||"fixed"===position)&&(curCSSTop+curCSSLeft).indexOf("auto")>-1?(curTop=(curPosition=curElem.position()).top,curLeft=curPosition.left):(curTop=parseFloat(curCSSTop)||0,curLeft=parseFloat(curCSSLeft)||0),isFunction(options)&&(options=options.call(elem,i,jQuery.extend({},curOffset))),null!=options.top&&(props.top=options.top-curOffset.top+curTop),null!=options.left&&(props.left=options.left-curOffset.left+curLeft),"using"in options?options.using.call(elem,props):("number"==typeof props.top&&(props.top+="px"),"number"==typeof props.left&&(props.left+="px"),curElem.css(props))}},jQuery.fn.extend({offset:function(options){if(arguments.length)return void 0===options?this:this.each((function(i){jQuery.offset.setOffset(this,options,i)}));var rect,win,elem=this[0];return elem?elem.getClientRects().length?(rect=elem.getBoundingClientRect(),win=elem.ownerDocument.defaultView,{top:rect.top+win.pageYOffset,left:rect.left+win.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var offsetParent,offset,doc,elem=this[0],parentOffset={top:0,left:0};if("fixed"===jQuery.css(elem,"position"))offset=elem.getBoundingClientRect();else{for(offset=this.offset(),doc=elem.ownerDocument,offsetParent=elem.offsetParent||doc.documentElement;offsetParent&&(offsetParent===doc.body||offsetParent===doc.documentElement)&&"static"===jQuery.css(offsetParent,"position");)offsetParent=offsetParent.parentNode;offsetParent&&offsetParent!==elem&&1===offsetParent.nodeType&&((parentOffset=jQuery(offsetParent).offset()).top+=jQuery.css(offsetParent,"borderTopWidth",!0),parentOffset.left+=jQuery.css(offsetParent,"borderLeftWidth",!0))}return{top:offset.top-parentOffset.top-jQuery.css(elem,"marginTop",!0),left:offset.left-parentOffset.left-jQuery.css(elem,"marginLeft",!0)}}},offsetParent:function(){return this.map((function(){for(var offsetParent=this.offsetParent;offsetParent&&"static"===jQuery.css(offsetParent,"position");)offsetParent=offsetParent.offsetParent;return offsetParent||documentElement}))}}),jQuery.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},(function(method,prop){var top="pageYOffset"===prop;jQuery.fn[method]=function(val){return access(this,(function(elem,method,val){var win;if(isWindow(elem)?win=elem:9===elem.nodeType&&(win=elem.defaultView),void 0===val)return win?win[prop]:elem[method];win?win.scrollTo(top?win.pageXOffset:val,top?val:win.pageYOffset):elem[method]=val}),method,val,arguments.length)}})),jQuery.each(["top","left"],(function(_i,prop){jQuery.cssHooks[prop]=addGetHookIf(support.pixelPosition,(function(elem,computed){if(computed)return computed=curCSS(elem,prop),rnumnonpx.test(computed)?jQuery(elem).position()[prop]+"px":computed}))})),jQuery.each({Height:"height",Width:"width"},(function(name,type){jQuery.each({padding:"inner"+name,content:type,"":"outer"+name},(function(defaultExtra,funcName){jQuery.fn[funcName]=function(margin,value){var chainable=arguments.length&&(defaultExtra||"boolean"!=typeof margin),extra=defaultExtra||(!0===margin||!0===value?"margin":"border");return access(this,(function(elem,type,value){var doc;return isWindow(elem)?0===funcName.indexOf("outer")?elem["inner"+name]:elem.document.documentElement["client"+name]:9===elem.nodeType?(doc=elem.documentElement,Math.max(elem.body["scroll"+name],doc["scroll"+name],elem.body["offset"+name],doc["offset"+name],doc["client"+name])):void 0===value?jQuery.css(elem,type,extra):jQuery.style(elem,type,value,extra)}),type,chainable?margin:void 0,chainable)}}))})),jQuery.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],(function(_i,type){jQuery.fn[type]=function(fn){return this.on(type,fn)}})),jQuery.fn.extend({bind:function(types,data,fn){return this.on(types,null,data,fn)},unbind:function(types,fn){return this.off(types,null,fn)},delegate:function(selector,types,data,fn){return this.on(types,selector,data,fn)},undelegate:function(selector,types,fn){return 1===arguments.length?this.off(selector,"**"):this.off(types,selector||"**",fn)},hover:function(fnOver,fnOut){return this.mouseenter(fnOver).mouseleave(fnOut||fnOver)}}),jQuery.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),(function(_i,name){jQuery.fn[name]=function(data,fn){return arguments.length>0?this.on(name,null,data,fn):this.trigger(name)}}));var rtrim=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;jQuery.proxy=function(fn,context){var tmp,args,proxy;if("string"==typeof context&&(tmp=fn[context],context=fn,fn=tmp),isFunction(fn))return args=slice.call(arguments,2),(proxy=function(){return fn.apply(context||this,args.concat(slice.call(arguments)))}).guid=fn.guid=fn.guid||jQuery.guid++,proxy},jQuery.holdReady=function(hold){hold?jQuery.readyWait++:jQuery.ready(!0)},jQuery.isArray=Array.isArray,jQuery.parseJSON=JSON.parse,jQuery.nodeName=nodeName,jQuery.isFunction=isFunction,jQuery.isWindow=isWindow,jQuery.camelCase=camelCase,jQuery.type=toType,jQuery.now=Date.now,jQuery.isNumeric=function(obj){var type=jQuery.type(obj);return("number"===type||"string"===type)&&!isNaN(obj-parseFloat(obj))},jQuery.trim=function(text){return null==text?"":(text+"").replace(rtrim,"")},"function"==typeof define&&define.amd&&define("jquery",[],(function(){return jQuery}));var _jQuery=window.jQuery,_$=window.$;return jQuery.noConflict=function(deep){return window.$===jQuery&&(window.$=_$),deep&&window.jQuery===jQuery&&(window.jQuery=_jQuery),jQuery},void 0===noGlobal&&(window.jQuery=window.$=jQuery),jQuery}))},{}]},{},[38]);