diff --git a/bundle/modules/dsa5.js b/bundle/modules/dsa5.js index aa0294d7..d9afa057 100644 --- a/bundle/modules/dsa5.js +++ b/bundle/modules/dsa5.js @@ -1,4 +1,4 @@ -var vi=Object.defineProperty;var Fi=(l,e,t)=>e in l?vi(l,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[e]=t;var u=(l,e)=>vi(l,"name",{value:e,configurable:!0});var L=(l,e,t)=>(Fi(l,typeof e!="symbol"?e+"":e,t),t),Ti=(l,e,t)=>{if(!e.has(l))throw TypeError("Cannot "+t)};var ve=(l,e,t)=>(Ti(l,e,"read from private field"),t?t.call(l):e.get(l)),aa=(l,e,t)=>{if(e.has(l))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(l):e.set(l,t)},sa=(l,e,t,a)=>(Ti(l,e,"write to private field"),a?a.call(l,t):e.set(l,t),t);var M={};M.statusEffects=[{icon:"icons/svg/skull.svg",id:"dead",name:"CONDITION.defeated",label:"CONDITION.defeated",description:"CONDITIONDESCRIPTION.defeated",flags:{dsa5:{}}},{id:"inpain",name:"CONDITION.inpain",icon:"icons/svg/blood.svg",description:"CONDITIONDESCRIPTION.inpain",changes:[{key:"system.condition.inpain",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"prone",name:"CONDITION.prone",icon:"icons/svg/falling.svg",description:"CONDITIONDESCRIPTION.prone",flags:{dsa5:{}}},{id:"unconscious",name:"CONDITION.unconscious",icon:"icons/svg/unconscious.svg",description:"CONDITIONDESCRIPTION.unconscious",flags:{dsa5:{}}},{id:"rooted",name:"CONDITION.rooted",icon:"icons/svg/net.svg",description:"CONDITIONDESCRIPTION.rooted",flags:{dsa5:{}}},{id:"fixated",name:"CONDITION.fixated",icon:"icons/svg/padlock.svg",description:"CONDITIONDESCRIPTION.fixated",flags:{dsa5:{}}},{id:"surprised",name:"CONDITION.surprised",icon:"icons/svg/hazard.svg",description:"CONDITIONDESCRIPTION.surprised",flags:{dsa5:{}}},{id:"blind",name:"CONDITION.blind",icon:"icons/svg/blind.svg",description:"CONDITIONDESCRIPTION.blind",flags:{dsa5:{}}},{id:"poisoned",name:"CONDITION.poisoned",icon:"icons/svg/poison.svg",description:"CONDITIONDESCRIPTION.poisoned",flags:{dsa5:{}}},{id:"sick",name:"CONDITION.sick",icon:"icons/svg/biohazard.svg",description:"CONDITIONDESCRIPTION.sick",flags:{dsa5:{}}},{id:"deaf",name:"CONDITION.deaf",icon:"icons/svg/deaf.svg",description:"CONDITIONDESCRIPTION.deaf",flags:{dsa5:{}}},{id:"burning",name:"CONDITION.burning",icon:"icons/svg/fire.svg",description:"CONDITIONDESCRIPTION.burning",flags:{dsa5:{value:1,max:3}}},{id:"invisible",name:"CONDITION.invisible",icon:"icons/svg/circle.svg",description:"CONDITIONDESCRIPTION.invisible",flags:{dsa5:{}}},{id:"constricted",name:"CONDITION.constricted",icon:"icons/svg/cave.svg",description:"CONDITIONDESCRIPTION.constricted",flags:{dsa5:{}}},{id:"bloodrush",name:"CONDITION.bloodrush",icon:"icons/svg/bones.svg",description:"CONDITIONDESCRIPTION.bloodrush",changes:[{key:"system.skillModifiers.step",mode:0,value:"Kraftakt 2;Feat of Strength 2"}],flags:{dsa5:{}}},{id:"mute",name:"CONDITION.mute",icon:"icons/svg/silenced.svg",description:"CONDITIONDESCRIPTION.mute",flags:{dsa5:{}}},{id:"incapacitated",name:"CONDITION.incapacitated",icon:"icons/svg/sleep.svg",description:"CONDITIONDESCRIPTION.incapacitated",flags:{dsa5:{}}},{id:"encumbered",name:"CONDITION.encumbered",icon:"icons/svg/anchor.svg",changes:[{key:"system.condition.encumbered",mode:2,value:1}],description:"CONDITIONDESCRIPTION.encumbered",flags:{dsa5:{value:1,max:4}}},{id:"stunned",name:"CONDITION.stunned",icon:"icons/svg/daze.svg",changes:[{key:"system.condition.stunned",mode:2,value:1}],description:"CONDITIONDESCRIPTION.stunned",flags:{dsa5:{value:1,max:4}}},{id:"raptured",name:"CONDITION.raptured",icon:"icons/svg/ice-aura.svg",changes:[{key:"system.condition.raptured",mode:2,value:1}],description:"CONDITIONDESCRIPTION.raptured",flags:{dsa5:{value:1,max:4}}},{id:"feared",name:"CONDITION.feared",icon:"icons/svg/terror.svg",description:"CONDITIONDESCRIPTION.feared",changes:[{key:"system.condition.feared",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"paralysed",name:"CONDITION.paralysed",icon:"icons/svg/paralysis.svg",description:"CONDITIONDESCRIPTION.paralysed",changes:[{key:"system.condition.paralysed",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"confused",name:"CONDITION.confused",icon:"icons/svg/stoned.svg",description:"CONDITIONDESCRIPTION.confused",changes:[{key:"system.condition.confused",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"minorSpirits",name:"CONDITION.minorSpirits",icon:"icons/svg/terror.svg",description:"CONDITIONDESCRIPTION.minorSpirits",changes:[{key:"system.skillModifiers.global",mode:0,value:-1}],duration:{seconds:600},flags:{dsa5:{}}},{id:"services",name:"PLAYER.services",icon:"icons/svg/aura.svg",description:"CONDITIONDESCRIPTION.services",flags:{dsa5:{value:1,max:500,hideOnToken:!0}}}];M.armorSubcategories={0:4,1:5,2:6,3:8,4:9,5:13,6:12,7:11,8:10};M.weaponStabilities={Blowpipes:10,Bows:4,Brawling:12,"Chain Weapons":10,Crossbows:6,Daggers:14,Discuses:12,Fans:13,"Fencing Weapons":8,"Impact Weapons":12,Lances:6,Pikes:12,Polearms:12,Shields:10,Slingshots:4,Swords:13,"Throwing Weapons":10,"Two-Handed Impact Weapons":11,"Two-Handed Swords":12,Whips:4};M.journalFontSizes=[8,10,12,14,16,18,20,24,28,32];M.styles={"dsa5-immersive":"dsaStyle.immersive","dsa5-immersive dsa5-legacy":"dsaStyle.legacy","dsa5-naked":"dsaStyle.naked"};M.fallingConditions={normal:0,soft1:-1,soft2:-2,soft3:-3,soft4:-4,rough1:1,rough2:2,rough3:3,rough4:4},M.combatSkillSubCategories={0:"COMBATSKILLCATEGORY.0",1:"COMBATSKILLCATEGORY.1",2:"COMBATSKILLCATEGORY.2",3:"COMBATSKILLCATEGORY.3",4:"COMBATSKILLCATEGORY.4",5:"COMBATSKILLCATEGORY.5"};M.effectTextStyle=CONFIG.canvasTextStyle.clone();M.effectTextStyle.fontSize="30";M.effectTextStyle.fontFamily="GentiumBasic";M.knownShortcuts={};M.gearModifyableCalculatedAttributes=["fatePoints","initiative","speed","astralenergy","karmaenergy","wounds","dodge","soulpower","toughness"];M.defaultWeapon={name:"default",type:"meleeweapon",effects:[],system:{type:"meleeweapon",crit:1,botch:20,reach:{value:"short"},damage:{value:"1d6"},atmod:{value:0,offHandMod:0},pamod:{value:0,offHandMod:0},guidevalue:{value:"ge/kk"},damageThreshold:{value:"5000"},worn:{offhand:!1}}};M.asyncHooks={postProcessDSARoll:[]};M.characteristics={mu:"CHAR.MU",kl:"CHAR.KL",in:"CHAR.IN",ch:"CHAR.CH",ff:"CHAR.FF",ge:"CHAR.GE",ko:"CHAR.KO",kk:"CHAR.KK"};M.equipmentTypes={misc:"Equipment.misc",clothes:"Equipment.clothes",tools:"Equipment.tools",light:"Equipment.light",healing:"Equipment.healing",bags:"Equipment.bags",wealth:"Equipment.wealth",writing:"Equipment.writing",alchemy:"Equipment.alchemy",service:"Equipment.service",luxus:"Equipment.luxus",blessed:"Equipment.blessed",food:"Equipment.food"};M.equipmentCategories=new Set(["meleeweapon","rangeweapon","equipment","ammunition","armor","poison","consumable","plant"]);M.systemTables=[{name:"Defense",attrs:'data-weaponless="false"',roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"dsa5",key:"defenseBotchTableEnabled"}},{name:"Melee",attrs:'data-weaponless="false"',roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"dsa5",key:"meleeBotchTableEnabled"}},{name:"Range",attrs:'data-weaponless="false"',roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"dsa5",key:"rangeBotchTableEnabled"}},{name:"Liturgy",attrs:"",roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"",key:""}},{name:"Spell",attrs:"",roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"",key:""}}];M.morePackages={packages:{},names:{de:[],en:[]}};M.narrowSpaceModifiers={weaponshort:{attack:0,parry:0,label:"NarrowSpaceModifiers.weapon.short"},weaponmedium:{attack:-4,parry:-4,label:"NarrowSpaceModifiers.weapon.medium"},weaponlong:{attack:-8,parry:-8,label:"NarrowSpaceModifiers.weapon.long"},shieldshort:{attack:-2,parry:-2,label:"NarrowSpaceModifiers.shield.short"},shieldmedium:{attack:-4,parry:-3,label:"NarrowSpaceModifiers.shield.medium"},shieldlong:{attack:-6,parry:-4,label:"NarrowSpaceModifiers.shield.long"}};M.traditionArtifacts={Animistenwaffe:15,Bannschwert:15,Druidendolch:15,Druidensichel:12,Zauberkleidung:15,Magierkugel:12,Zauberinstrument:15,Narrenkappe:15,Hexenkessel:15,Krallenkette:12,Lebensring:12,Alchimistenschale:15,"Scharlatanische Zauberkugel":15,Sippenchronik:15,Schelmenspielzeug:12,Zauberstecken:0,Magierstab:18,Trinkhorn:12,Schuppenbeutel:18,"Kristallomantische Kristallkugel":15,Echsenhaube:12};M.moneyNames={D:"Money-D",S:"Money-S",H:"Money-H",K:"Money-K"};M.areaTargetTypes={cube:"rect",line:"ray",sphere:"circle",cone:"cone"};M.rangeMods={short:{damage:1,attack:2},medium:{damage:0,attack:0},long:{damage:-1,attack:-2},rangesense:{damage:-1,attack:-1},extreme:{damage:-2,attack:-4}};M.regnerationCampLocations={0:"regnerationCampLocations.normal","-1":"regnerationCampLocations.bad",1:"regnerationCampLocations.good"};M.regenerationInterruptOptions={0:"regenerationInterruptOptions.none","-1":"regenerationInterruptOptions.small","-2":"regenerationInterruptOptions.big"};M.targetMomevementOptions={0:"rangeMovementOptions.SLOW","-2":"rangeMovementOptions.FAST",2:"rangeMovementOptions.STATIONARY"};M.allowedforeignfields=["system.details.notes.value"];M.shooterMovementOptions={0:"rangeMovementOptions.SHOOTERSTATIONARY","-2":"rangeMovementOptions.SHOOTERMOVING","-4":"rangeMovementOptions.SHOOTERRUNNING"};M.mountedRangeOptionsSpecAb={STATIONARY:"0",SCHRITT:"0",TROT:"-5000",GALOPP:"-4"};M.mountedRangeOptions={STATIONARY:"0",SCHRITT:"-4",TROT:"-5000",GALOPP:"-8"};M.drivingArcherOptions={STATIONARY:"0",SCHRITT:"-2",GALOPP:"-4"};M.aimOptions={0:"aimOptions.0",2:"aimOptions.1",4:"aimOptions.2"};M.traitCategories={meleeAttack:"closeCombatAttacks",rangeAttack:"rangeCombatAttacks",armor:"armor",general:"general",familiar:"familiar",trick:"trick",training:"training",entity:"entityAbility",summoning:"summoningPackage"};M.ritualLocationModifiers={0:"-",1:"RITUALMODIFIER.holysite","-3":"RITUALMODIFIER.wrongsite"};M.ritualTimeModifiers={0:"-",1:"RITUALMODIFIER.matchingConstellation","-1":"RITUALMODIFIER.wrongConstellation"};M.ceremonyLocationModifiers={0:"-",2:"CEREMONYMODIFIER.holysite",1:"CEREMONYMODIFIER.temple","-1":"CEREMONYMODIFIER.otherTemple","-2":"CEREMONYMODIFIER.enemyGod","-3":"CEREMONYMODIFIER.archDemon","-4":"CEREMONYMODIFIER.nameless","-5":"CEREMONYMODIFIER.nemesis"};M.advancementCosts={A:[1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14],B:[2,2,2,2,2,2,2,2,2,2,2,2,2,4,6,8,10,12,14,16,18,20,22,24,26,28],C:[3,3,3,3,3,3,3,3,3,3,3,3,3,6,9,12,15,18,21,24,27,30,33,36,39,42],D:[4,4,4,4,4,4,4,4,4,4,4,4,4,8,12,16,20,24,28,32,36,40,44,48,52,56],E:[15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,30,45,60,75,90,105,120,135,150,165,180]};M.hooks={};M.startXP={900:"EXP.inexperienced",1e3:"EXP.average",1100:"EXP.experienced",1200:"EXP.competent",1400:"EXP.masterful",1700:"EXP.brillant",2100:"EXP.legendary"};M.helpContent=[{name:"pay",command:"/pay [0-9]+",example:"/pay 5.03"},{name:"getPaid",command:"/getPaid [0-9]+",example:"/getPaid 5.03"},{name:"quickAbility",command:"/sk [a-z]*, /sp [a-z]*, /li [a-z]*, /at [a-z]*, /pa [a-z]*",example:"/sk bet\xF6ren"},{name:"conditions",command:"/conditions",example:"/conditions"},{name:"tables",command:"/tables",example:"/tables"},{name:"request",command:"/rq",example:"/rq bet\xF6ren"},{name:"threeD20Check",command:"/ch",example:"/ch"},{name:"groupcheck",command:"/gc",example:"/gc"}];M.ceremonyTimeModifiers={0:"-",1:"CEREMONYMODIFIER.monthGod",2:"CEREMONYMODIFIER.celebration","-5":"CEREMONYMODIFIER.namelessDays"};M.mageLevels={mundane:"mundane",clerical:"clerical",magical:"magical"};M.specialAbilityCategories={Combat:"SpecCategory.Combat",command:"SpecCategory.command",general:"SpecCategory.general",generalStyle:"SpecCategory.generalStyle",extGeneral:"SpecCategory.extGeneral",animal:"SpecCategory.animal",fatePoints:"SpecCategory.fatePoints",vampire:"SpecCategory.vampire",lykanthrop:"SpecCategory.lykanthrop",language:"SpecCategory.language",secret:"SpecCategory.secret",clerical:"SpecCategory.clerical",clericalStyle:"SpecCategory.clericalStyle",extClericalStyle:"SpecCategory.extClericalStyle",ceremonial:"SpecCategory.ceremonial",vision:"SpecCategory.vision",prayer:"SpecCategory.prayer",magical:"SpecCategory.magical",magicalStyle:"SpecCategory.magicalStyle",extMagical:"SpecCategory.extMagical",staff:"SpecCategory.staff",pact:"SpecCategory.pact",homunculus:"SpecCategory.homunculus"};M.sortedSpecs={combat:new Set(["Combat","command"]),magical:new Set(["magical","magicalStyle","extMagical","pact","homunculus"]),clerical:new Set(["clerical","clericalStyle","extClericalStyle","ceremonial","vision","prayer"]),unUsed:new Set(["staff"])};M.sortedSpecs.general=new Set(Object.keys(M.specialAbilityCategories).filter(l=>!Object.keys(M.sortedSpecs).some(e=>M.sortedSpecs[e].has(l))));M.addvantageRules={};M.removevantageRules={};M.vantagesNeedingAdaption={};M.addAbilityRules={};M.removeAbilityRules={};M.AbilitiesNeedingAdaption={};M.addTraitRules={};M.rangeWeaponModifiers={short:"RangeMod.short",medium:"RangeMod.medium",long:"RangeMod.long",rangesense:"RangeMod.rangesense",extreme:"RangeMod.extreme"};M.meleeRangesArray=["short","medium","long"];M.meleeRanges={short:"Range-short",medium:"Range-medium",long:"Range-long"};M.weapontypes={melee:"meleeweapon",range:"rangeweapon"};M.ammunitiongroups={"-":"-",arrow:"arrow",bolt:"bolt",bullet:"bullet",stone:"stone",dart:"dart",mag:"mag",infinite:"infinite"};M.combatskillsGuidevalues={ff:"CHAR.FF",ge:"CHAR.GE",kk:"CHAR.KK","ge/kk":"CHAR.GEKK"};M.skillDifficultyModifiers={eeasy:5,veasy:3,easy:1,challenging:0,difficult:-1,hard:-3,vhard:-5};M.magicResistanceModifiers={"-":"-",SK:"soulpower",ZK:"toughness"};M.sizeCategories={tiny:"SIZE.tiny",small:"SIZE.small",average:"SIZE.average",big:"SIZE.big",giant:"SIZE.giant"};M.tokenSizeCategories={tiny:.5,small:.8,average:1,big:2,giant:4};M.rangeSizeCategories={tiny:"RANGESIZE.tiny",small:"RANGESIZE.small",average:"RANGESIZE.average",big:"RANGESIZE.big",giant:"RANGESIZE.giant"},M.meleeSizeCategories={tiny:"MELEESIZE.tiny",small:"MELEESIZE.small",average:"MELEESIZE.average",big:"MELEESIZE.big",giant:"MELEESIZE.giant"};M.shieldSizes={short:"SIZE.small",medium:"SIZE.average",long:"SIZE.big"};M.rangeSizeModifier={tiny:-8,small:-4,average:0,big:4,giant:8};M.meleeSizeModifier={tiny:-4,small:0,average:0,big:0,giant:0};M.rangeVision={0:"VisionDisruption.step0","-2":"VisionDisruption.step1","-4":"VisionDisruption.step2","-6":"VisionDisruption.step3","-5000":"VisionDisruption.step4"};M.meleeRangeVision=l=>({"+0":"meleeVisionDisruption.0","-1":"meleeVisionDisruption.1","-2":"meleeVisionDisruption.2","-3":"meleeVisionDisruption.3",[l=="attack"?"*0,5":"-5000"]:"meleeVisionDisruption.4"});M.attributeDifficultyModifiers={eeasy:6,veasy:4,easy:2,challenging:0,difficult:-2,hard:-4,vhard:-6};M.skillDifficultyLabels={eeasy:"Skill-eeasy",veasy:"Skill-veasy",easy:"Skill-easy",challenging:"Skill-challenging",difficult:"Skill-difficult",hard:"Skill-hard",vhard:"Skill-vhard"};M.attributeDifficultyLabels={eeasy:"Attribute-eeasy",veasy:"Attribute-veasy",easy:"Attribute-easy",challenging:"Attribute-challenging",difficult:"Attribute-difficult",hard:"Attribute-hard",vhard:"Attribute-vhard"};M.skillGroups={body:"SKILL.body",social:"SKILL.social",knowledge:"SKILL.knowledge",trade:"SKILL.trade",nature:"SKILL.nature"};M.features=["Object","Spheres","Influence","Clairvoyance","Healing","Transformation","Telekinesis","Elemental","Illusion","Anti-Magic","Demonic","Temporal"];M.skillBurdens={yes:"yes",no:"no",maybe:"maybe"};M.StFs={A:"A",B:"B",C:"C",D:"D"};M.noteIcons={"Griffin Shield":"systems/dsa5/icons/thirdparty/griffinshield.svg","At Sea":"systems/dsa5/icons/thirdparty/at-sea.svg","Medieval Gate":"systems/dsa5/icons/thirdparty/medieval-gate.svg","Position Marker":"systems/dsa5/icons/thirdparty/position-marker.svg",River:"systems/dsa5/icons/thirdparty/river.svg",Trail:"systems/dsa5/icons/thirdparty/trail.svg"};CONFIG.time.roundTime=5;CONFIG.time.turnTime=0;var b=M;function Si(l,e=320,t=40){l.attr({width:e*.8,viewBox:`0 0 ${e} ${t}`});let a=l.find("text"),s=a.get(0).getBBox(),i=e/s.width,r=t/s.height,n=isetTimeout(e,l))}u(ra,"delay");async function Ge(l,e,t=!0){let a,s;l.type=="Actor"?(a=await Actor.implementation.fromDropData(l),s=e===a.id):(a=await Item.implementation.fromDropData(l),s=e===a.parent?.uuid);let i=a?.type;return t&&(a=a.toObject()),l.amount&&(a.system.quantity.value=Number(l.amount)),{item:a,typeClass:i,selfTarget:s}}u(Ge,"itemFromDrop");function na(l,e,t,a="div"){if(e=l.find(e)[0],!e)return;e.classList.add("slist");let s=e.querySelectorAll(a),i=null;for(let r of s)r.draggable=!0,r.addEventListener("dragstart",function(n){i=this}),r.addEventListener("dragover",function(n){n.preventDefault()}),r.addEventListener("drop",async function(n){if(n.preventDefault(),this!=i){let o=0,c=0;for(let m=0;m'),e=$(".tinyNotifications"));let t=$(`
  • ${l}
  • `);e.prepend(t),setTimeout(function(){t.remove()},1500)}u(de,"tinyNotification");function ia(l,e,t,a){let s=Math.ceil(e.scrollLeft),i=e.scrollWidth-e.clientWidth;t.style.display=s>0?"block":"none",a.style.display=i>s?"block":"none",Hi(l)}u(ia,"IconVisibility");async function yt(l){let e=$(l.currentTarget).closest(".searchableAbility")[0].dataset.category.split(" "),t=l.currentTarget.text.replace(/\d+$/,"").trim();for(let a of e){let i=(await game.dsa5.itemLibrary.findCompendiumItem(t,a)).find(r=>r.name==t);if(i){i.sheet.render(!0);return}}if(/\(/.test(t)){t=t.split("(")[0].trim()+" ()";for(let a of e){let i=(await game.dsa5.itemLibrary.findCompendiumItem(t,a)).find(r=>r.name==t);if(i){i.sheet.render(!0);return}}}}u(yt,"clickableAbility");function Hi(l){let e=l.width(),t=Number(getComputedStyle(document.body).getPropertyValue("--minColumnWidth").replace("px","")),a=Number(getComputedStyle(document.body).getPropertyValue("--minColumnWidth60").replace("px","")),s=6;e>=t*2+s?l.removeClass("singleColumnLayout"):l.addClass("singleColumnLayout"),e<=a?l.addClass("minimumColumnLayout"):l.removeClass("minimumColumnLayout")}u(Hi,"columnLayout");function oe(l){let e=l.find(".navWrapper");for(let t of e){let a=t.querySelector(".left-btn"),s=t.querySelector(".right-btn"),i=t.querySelector(".sheet-tabs"),r=!1;s.addEventListener("click",()=>{i.scrollLeft+=150,setTimeout(()=>ia(l,i,a,s),500)}),a.addEventListener("click",()=>{i.scrollLeft-=150,setTimeout(()=>ia(l,i,a,s),500)}),new ResizeObserver(()=>ia(l,i,a,s)).observe(t),i.addEventListener("mousemove",n=>{!r||(i.scrollLeft-=n.movementX,setTimeout(()=>ia(l,i,a,s),500))}),i.addEventListener("mousedown",()=>{r=!0,i.classList.add("dragging"),document.addEventListener("mouseup",()=>{r=!1,i.classList.remove("dragging")},{once:!0})})}}u(oe,"tabSlider");var Ci=u(()=>{document.documentElement.style.setProperty("--app-height",`${window.innerHeight}px`)},"appHeight");window.addEventListener("resize",Ci);Ci();async function ji(){if(!game.settings.get("dsa5","defaultConfigFinished")){console.log("Configuring default token settings");let l=game.settings.get("core","defaultToken");l.displayName=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,l.displayBars=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,l.disposition=CONST.TOKEN_DISPOSITIONS.NEUTRAL,l.bar1={attribute:"status.wounds"},await game.settings.set("core","defaultToken",l),await game.settings.set("core","leftClickRelease",!0),await game.settings.set("dsa5","defaultConfigFinished",!0)}}u(ji,"setupDefaulTokenConfig");async function Gi(l,e){await Gt(),l<24&&await Bi(),await game.settings.set("dsa5","migrationVersion",e)}u(Gi,"migrateDSA");async function Bi(){for(let l of game.actors){let e=l.effects.filter(t=>["inpain","encumbered"].includes(t.getFlag("core","statusId")));e.length&&await l.deleteEmbeddedDocuments("ActiveEffect",e.map(t=>t.id))}}u(Bi,"migratTo24");async function Gt(){let e=await(await fetch("systems/dsa5/lazy/updatenotes.json")).json();new oa(e).render(!0)}u(Gt,"showPatchViewer");function Xs(){Hooks.once("ready",async function(){if(!game.user.isGM)return;await ji();let l=await game.settings.get("dsa5","migrationVersion"),e=26;lthis.showMore(e))}async showMore(e){let t=[this.json.notes[this.json.notes.length-this.versionIndex]];if(t[0].version=="2.3.0"){e.find(".showMore").hide();return}let a=await this.fetchVersions(t);e.find(".changelogsection").append(a.changelog[0]),e.find(".newssection").append(a.news[0]),this.versionIndex+=1}async fetchVersions(e){let t=game.i18n.lang,a=await Promise.all(e.map(async i=>await renderTemplate(`systems/dsa5/lazy/patchhtml/changelog_${t}_${i.version}.html`))),s=await Promise.all(e.map(async i=>await renderTemplate(`systems/dsa5/lazy/patchhtml/news_${t}_${i.version}.html`)));return{changelog:a,news:s}}async getData(){let e=this.json.notes[this.json.notes.length-1],t=this.json.default.replace(/VERSION/g,e.version),a=`

    CHANGELOG

    ${t}.
    Important updates: ${e.text}

    For details or proposals visit our wiki page at Github or show the Full Changelog in Foundry. Have fun.

    `;await ChatMessage.create(f.chatDataSetup(a,"roll"));let s=game.i18n.lang,i=await this.fetchVersions([e]),r=[this.json.notes[this.json.notes.length-2]],n=await this.fetchVersions(r),o=await renderTemplate(`systems/dsa5/lazy/patchhtml/modules_${s}.html`);return{patchName:t,changelog:i.changelog[0],news:i.news[0],prevVersions:r,prevChangeLogs:n.changelog,prevNews:n.news,modules:o}}};u(oa,"PatchViewer");var Zs=class{static getTalentBonus(e,t,a){let s=[],i=game.settings.get("dsa5","talentModifierEnabled");for(let r of e.items.filter(n=>a.includes(n.type)&&n.system.effect.value.includes(t)))for(let n of r.system.effect.value.split(/;|,/))if(n.includes(t)){let o=f.parseAbilityString(n.trim());o.name==t&&s.push({name:r.name,value:o.step*(r.system.step?r.system.step.value:1),type:o.type,selected:i,source:r.name})}return s}static async stepXPCost(e,t){let a=e.system.APValue.value;return/;/.test(a)&&(a=a.split(";").map(i=>Number(i.trim()))[t]),Number(a)}static calcAPCostSum(e){let t=Number(e.system.APValue.value)*(Number(e.system.step.value)||1);if(/;/.test(e.system.APValue.value)){let a=e.system.APValue.value.split(";").map(s=>Number(s.trim()));t=0;for(let s=0;si[t.name].items.includes(n.type)&&n.name==t.special);r&&(a.system.APValue.value=a.system.APValue.value?a.system.APValue.value.split("/")[r.system.StF.value.charCodeAt(0)-65]:0,Zs.simpleAdoption(a,r,t.name,i));break}return a}static hasItem(e,t,a){return e.items.find(s=>a.includes(s.type)&&s.name==t)!=null}static itemStep(e,t,a){let s=e.items.find(i=>a.includes(i.type)&&i.name==t);return s?Number(s.system.step.value):0}static itemAsModifier(e,t,a,s,i=!1,r=!1){let n=[],o=i?new RegExp(`^${f.escapeRegex(`${t} (`)}`):new RegExp(`^${f.escapeRegex(t)}$`),c=e.items.find(m=>s.includes(m.type)&&o.test(m.name));return c&&n.push({name:c.name,value:Number(c.system.step.value)*a,selected:r,source:c.name}),n}},te=Zs;u(te,"ItemRulesDSA5"),L(te,"children",{});var Be=class extends Dialog{activateListeners(e){super.activateListeners(e),e.find(".select2").select2()}};u(Be,"Select2Dialog");var _=class{static async track(e,t,a){if(game.settings.get("dsa5","enableAPTracking")&&e.hasPlayerOwner){let s=game.journal.find(i=>i.flags.dsa5?.apTrackerId==e.id);if(game.user.isGM||s?.isOwner){s||(s=await _.createJournal(e));let i=await _.getPage(s);await _.addEntry(i,e,t,a)}else{let i={actorId:e.id,apCost:a};t.item?.uuid&&(i.uuid=t.item.uuid,delete t.item),i.description=t,game.socket.emit("system.dsa5",{type:"apTracker",payload:i})}}}static async receiveSocketEvent(e){let t=game.actors.get(e.payload.actorId),a=e.payload.description;e.payload.uuid&&(a.item=await fromUuid(e.payload.uuid)),_.track(t,a,e.payload.apCost)}static async addEntry(e,t,a,s){let i=_.getRow(this.buildDescription(a),this.buildChange(a),s,`${t.system.details.experience.spent}/${t.system.details.experience.total}`),r=$(e.text.content);r.find(".adventurePoints").append(i),await e.update({"text.content":r.prop("outerHTML")})}static buildChange(e){if(e.state)return e.state>0?"":"";let t=e.next>e.previous?"angles-up":"angles-down";return`${e.previous} ${e.next}`}static buildDescription(e){switch(e.type){case"attribute":return game.i18n.localize(`CHAR.${e.attr.toUpperCase()}`);case"permanentLoss":return`${game.i18n.localize(e.attr)} (${game.i18n.localize("permanentCost")})`;case"point":return game.i18n.localize(e.attr);case"item":return e.item.toAnchor?e.item.toAnchor().outerHTML:`${game.i18n.localize("TYPES.Item."+e.item.type)}: ${e.item.name}`;case"sum":return game.i18n.localize("MASTER.awardXP")}}static getRow(e,t,a,s,i=""){return`
    +var vi=Object.defineProperty;var Fi=(l,e,t)=>e in l?vi(l,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[e]=t;var u=(l,e)=>vi(l,"name",{value:e,configurable:!0});var L=(l,e,t)=>(Fi(l,typeof e!="symbol"?e+"":e,t),t),Ti=(l,e,t)=>{if(!e.has(l))throw TypeError("Cannot "+t)};var ve=(l,e,t)=>(Ti(l,e,"read from private field"),t?t.call(l):e.get(l)),aa=(l,e,t)=>{if(e.has(l))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(l):e.set(l,t)},sa=(l,e,t,a)=>(Ti(l,e,"write to private field"),a?a.call(l,t):e.set(l,t),t);var M={};M.statusEffects=[{icon:"icons/svg/skull.svg",id:"dead",name:"CONDITION.defeated",label:"CONDITION.defeated",description:"CONDITIONDESCRIPTION.defeated",flags:{dsa5:{}}},{id:"inpain",name:"CONDITION.inpain",icon:"icons/svg/blood.svg",description:"CONDITIONDESCRIPTION.inpain",changes:[{key:"system.condition.inpain",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"prone",name:"CONDITION.prone",icon:"icons/svg/falling.svg",description:"CONDITIONDESCRIPTION.prone",flags:{dsa5:{}}},{id:"unconscious",name:"CONDITION.unconscious",icon:"icons/svg/unconscious.svg",description:"CONDITIONDESCRIPTION.unconscious",flags:{dsa5:{}}},{id:"rooted",name:"CONDITION.rooted",icon:"icons/svg/net.svg",description:"CONDITIONDESCRIPTION.rooted",flags:{dsa5:{}}},{id:"fixated",name:"CONDITION.fixated",icon:"icons/svg/padlock.svg",description:"CONDITIONDESCRIPTION.fixated",flags:{dsa5:{}}},{id:"surprised",name:"CONDITION.surprised",icon:"icons/svg/hazard.svg",description:"CONDITIONDESCRIPTION.surprised",flags:{dsa5:{}}},{id:"blind",name:"CONDITION.blind",icon:"icons/svg/blind.svg",description:"CONDITIONDESCRIPTION.blind",flags:{dsa5:{}}},{id:"poisoned",name:"CONDITION.poisoned",icon:"icons/svg/poison.svg",description:"CONDITIONDESCRIPTION.poisoned",flags:{dsa5:{}}},{id:"sick",name:"CONDITION.sick",icon:"icons/svg/biohazard.svg",description:"CONDITIONDESCRIPTION.sick",flags:{dsa5:{}}},{id:"deaf",name:"CONDITION.deaf",icon:"icons/svg/deaf.svg",description:"CONDITIONDESCRIPTION.deaf",flags:{dsa5:{}}},{id:"burning",name:"CONDITION.burning",icon:"icons/svg/fire.svg",description:"CONDITIONDESCRIPTION.burning",flags:{dsa5:{value:1,max:3}}},{id:"invisible",name:"CONDITION.invisible",icon:"icons/svg/circle.svg",description:"CONDITIONDESCRIPTION.invisible",flags:{dsa5:{}}},{id:"constricted",name:"CONDITION.constricted",icon:"icons/svg/cave.svg",description:"CONDITIONDESCRIPTION.constricted",flags:{dsa5:{}}},{id:"bloodrush",name:"CONDITION.bloodrush",icon:"icons/svg/bones.svg",description:"CONDITIONDESCRIPTION.bloodrush",changes:[{key:"system.skillModifiers.step",mode:0,value:"Kraftakt 2;Feat of Strength 2"}],flags:{dsa5:{}}},{id:"mute",name:"CONDITION.mute",icon:"icons/svg/silenced.svg",description:"CONDITIONDESCRIPTION.mute",flags:{dsa5:{}}},{id:"incapacitated",name:"CONDITION.incapacitated",icon:"icons/svg/sleep.svg",description:"CONDITIONDESCRIPTION.incapacitated",flags:{dsa5:{}}},{id:"encumbered",name:"CONDITION.encumbered",icon:"icons/svg/anchor.svg",changes:[{key:"system.condition.encumbered",mode:2,value:1}],description:"CONDITIONDESCRIPTION.encumbered",flags:{dsa5:{value:1,max:4}}},{id:"stunned",name:"CONDITION.stunned",icon:"icons/svg/daze.svg",changes:[{key:"system.condition.stunned",mode:2,value:1}],description:"CONDITIONDESCRIPTION.stunned",flags:{dsa5:{value:1,max:4}}},{id:"raptured",name:"CONDITION.raptured",icon:"icons/svg/ice-aura.svg",changes:[{key:"system.condition.raptured",mode:2,value:1}],description:"CONDITIONDESCRIPTION.raptured",flags:{dsa5:{value:1,max:4}}},{id:"feared",name:"CONDITION.feared",icon:"icons/svg/terror.svg",description:"CONDITIONDESCRIPTION.feared",changes:[{key:"system.condition.feared",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"paralysed",name:"CONDITION.paralysed",icon:"icons/svg/paralysis.svg",description:"CONDITIONDESCRIPTION.paralysed",changes:[{key:"system.condition.paralysed",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"confused",name:"CONDITION.confused",icon:"icons/svg/stoned.svg",description:"CONDITIONDESCRIPTION.confused",changes:[{key:"system.condition.confused",mode:2,value:1}],flags:{dsa5:{value:1,max:4}}},{id:"minorSpirits",name:"CONDITION.minorSpirits",icon:"icons/svg/terror.svg",description:"CONDITIONDESCRIPTION.minorSpirits",changes:[{key:"system.skillModifiers.global",mode:0,value:-1}],duration:{seconds:600},flags:{dsa5:{}}},{id:"services",name:"PLAYER.services",icon:"icons/svg/aura.svg",description:"CONDITIONDESCRIPTION.services",flags:{dsa5:{value:1,max:500,hideOnToken:!0}}}];M.armorSubcategories={0:4,1:5,2:6,3:8,4:9,5:13,6:12,7:11,8:10};M.weaponStabilities={Blowpipes:10,Bows:4,Brawling:12,"Chain Weapons":10,Crossbows:6,Daggers:14,Discuses:12,Fans:13,"Fencing Weapons":8,"Impact Weapons":12,Lances:6,Pikes:12,Polearms:12,Shields:10,Slingshots:4,Swords:13,"Throwing Weapons":10,"Two-Handed Impact Weapons":11,"Two-Handed Swords":12,Whips:4};M.journalFontSizes=[8,10,12,14,16,18,20,24,28,32];M.styles={"dsa5-immersive":"dsaStyle.immersive","dsa5-immersive dsa5-legacy":"dsaStyle.legacy","dsa5-naked":"dsaStyle.naked"};M.fallingConditions={normal:0,soft1:-1,soft2:-2,soft3:-3,soft4:-4,rough1:1,rough2:2,rough3:3,rough4:4},M.combatSkillSubCategories={0:"COMBATSKILLCATEGORY.0",1:"COMBATSKILLCATEGORY.1",2:"COMBATSKILLCATEGORY.2",3:"COMBATSKILLCATEGORY.3",4:"COMBATSKILLCATEGORY.4",5:"COMBATSKILLCATEGORY.5"};M.effectTextStyle=CONFIG.canvasTextStyle.clone();M.effectTextStyle.fontSize="30";M.effectTextStyle.fontFamily="GentiumBasic";M.knownShortcuts={};M.gearModifyableCalculatedAttributes=["fatePoints","initiative","speed","astralenergy","karmaenergy","wounds","dodge","soulpower","toughness"];M.defaultWeapon={name:"default",type:"meleeweapon",effects:[],system:{type:"meleeweapon",crit:1,botch:20,reach:{value:"short"},damage:{value:"1d6"},atmod:{value:0,offHandMod:0},pamod:{value:0,offHandMod:0},guidevalue:{value:"ge/kk"},damageThreshold:{value:"5000"},worn:{offhand:!1}}};M.asyncHooks={postProcessDSARoll:[]};M.characteristics={mu:"CHAR.MU",kl:"CHAR.KL",in:"CHAR.IN",ch:"CHAR.CH",ff:"CHAR.FF",ge:"CHAR.GE",ko:"CHAR.KO",kk:"CHAR.KK"};M.equipmentTypes={misc:"Equipment.misc",clothes:"Equipment.clothes",tools:"Equipment.tools",light:"Equipment.light",healing:"Equipment.healing",bags:"Equipment.bags",wealth:"Equipment.wealth",writing:"Equipment.writing",alchemy:"Equipment.alchemy",service:"Equipment.service",luxus:"Equipment.luxus",blessed:"Equipment.blessed",food:"Equipment.food"};M.equipmentCategories=new Set(["meleeweapon","rangeweapon","equipment","ammunition","armor","poison","consumable","plant"]);M.systemTables=[{name:"Defense",attrs:'data-weaponless="false"',roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"dsa5",key:"defenseBotchTableEnabled"}},{name:"Melee",attrs:'data-weaponless="false"',roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"dsa5",key:"meleeBotchTableEnabled"}},{name:"Range",attrs:'data-weaponless="false"',roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"dsa5",key:"rangeBotchTableEnabled"}},{name:"Liturgy",attrs:"",roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"",key:""}},{name:"Spell",attrs:"",roll:"botch-roll",pack:{de:"dsa5.patzer",en:"dsa5.botch"},setting:{module:"",key:""}}];M.morePackages={packages:{},names:{de:[],en:[]}};M.narrowSpaceModifiers={weaponshort:{attack:0,parry:0,label:"NarrowSpaceModifiers.weapon.short"},weaponmedium:{attack:-4,parry:-4,label:"NarrowSpaceModifiers.weapon.medium"},weaponlong:{attack:-8,parry:-8,label:"NarrowSpaceModifiers.weapon.long"},shieldshort:{attack:-2,parry:-2,label:"NarrowSpaceModifiers.shield.short"},shieldmedium:{attack:-4,parry:-3,label:"NarrowSpaceModifiers.shield.medium"},shieldlong:{attack:-6,parry:-4,label:"NarrowSpaceModifiers.shield.long"}};M.traditionArtifacts={Animistenwaffe:15,Bannschwert:15,Druidendolch:15,Druidensichel:12,Zauberkleidung:15,Magierkugel:12,Zauberinstrument:15,Narrenkappe:15,Hexenkessel:15,Krallenkette:12,Lebensring:12,Alchimistenschale:15,"Scharlatanische Zauberkugel":15,Sippenchronik:15,Schelmenspielzeug:12,Zauberstecken:0,Magierstab:18,Trinkhorn:12,Schuppenbeutel:18,"Kristallomantische Kristallkugel":15,Echsenhaube:12};M.moneyNames={D:"Money-D",S:"Money-S",H:"Money-H",K:"Money-K"};M.areaTargetTypes={cube:"rect",line:"ray",sphere:"circle",cone:"cone"};M.rangeMods={short:{damage:1,attack:2},medium:{damage:0,attack:0},long:{damage:-1,attack:-2},rangesense:{damage:-1,attack:-1},extreme:{damage:-2,attack:-4}};M.regnerationCampLocations={0:"regnerationCampLocations.normal","-1":"regnerationCampLocations.bad",1:"regnerationCampLocations.good"};M.regenerationInterruptOptions={0:"regenerationInterruptOptions.none","-1":"regenerationInterruptOptions.small","-2":"regenerationInterruptOptions.big"};M.targetMomevementOptions={0:"rangeMovementOptions.SLOW","-2":"rangeMovementOptions.FAST",2:"rangeMovementOptions.STATIONARY"};M.allowedforeignfields=["system.details.notes.value"];M.shooterMovementOptions={0:"rangeMovementOptions.SHOOTERSTATIONARY","-2":"rangeMovementOptions.SHOOTERMOVING","-4":"rangeMovementOptions.SHOOTERRUNNING"};M.mountedRangeOptionsSpecAb={STATIONARY:"0",SCHRITT:"0",TROT:"-5000",GALOPP:"-4"};M.mountedRangeOptions={STATIONARY:"0",SCHRITT:"-4",TROT:"-5000",GALOPP:"-8"};M.drivingArcherOptions={STATIONARY:"0",SCHRITT:"-2",GALOPP:"-4"};M.aimOptions={0:"aimOptions.0",2:"aimOptions.1",4:"aimOptions.2"};M.traitCategories={meleeAttack:"closeCombatAttacks",rangeAttack:"rangeCombatAttacks",armor:"armor",general:"general",familiar:"familiar",trick:"trick",training:"training",entity:"entityAbility",summoning:"summoningPackage"};M.ritualLocationModifiers={0:"-",1:"RITUALMODIFIER.holysite","-3":"RITUALMODIFIER.wrongsite"};M.ritualTimeModifiers={0:"-",1:"RITUALMODIFIER.matchingConstellation","-1":"RITUALMODIFIER.wrongConstellation"};M.ceremonyLocationModifiers={0:"-",2:"CEREMONYMODIFIER.holysite",1:"CEREMONYMODIFIER.temple","-1":"CEREMONYMODIFIER.otherTemple","-2":"CEREMONYMODIFIER.enemyGod","-3":"CEREMONYMODIFIER.archDemon","-4":"CEREMONYMODIFIER.nameless","-5":"CEREMONYMODIFIER.nemesis"};M.advancementCosts={A:[1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14],B:[2,2,2,2,2,2,2,2,2,2,2,2,2,4,6,8,10,12,14,16,18,20,22,24,26,28],C:[3,3,3,3,3,3,3,3,3,3,3,3,3,6,9,12,15,18,21,24,27,30,33,36,39,42],D:[4,4,4,4,4,4,4,4,4,4,4,4,4,8,12,16,20,24,28,32,36,40,44,48,52,56],E:[15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,30,45,60,75,90,105,120,135,150,165,180]};M.hooks={};M.startXP={900:"EXP.inexperienced",1e3:"EXP.average",1100:"EXP.experienced",1200:"EXP.competent",1400:"EXP.masterful",1700:"EXP.brillant",2100:"EXP.legendary"};M.helpContent=[{name:"pay",command:"/pay [0-9]+",example:"/pay 5.03"},{name:"getPaid",command:"/getPaid [0-9]+",example:"/getPaid 5.03"},{name:"quickAbility",command:"/sk [a-z]*, /sp [a-z]*, /li [a-z]*, /at [a-z]*, /pa [a-z]*",example:"/sk bet\xF6ren"},{name:"conditions",command:"/conditions",example:"/conditions"},{name:"tables",command:"/tables",example:"/tables"},{name:"request",command:"/rq",example:"/rq bet\xF6ren"},{name:"threeD20Check",command:"/ch",example:"/ch"},{name:"groupcheck",command:"/gc",example:"/gc"}];M.ceremonyTimeModifiers={0:"-",1:"CEREMONYMODIFIER.monthGod",2:"CEREMONYMODIFIER.celebration","-5":"CEREMONYMODIFIER.namelessDays"};M.mageLevels={mundane:"mundane",clerical:"clerical",magical:"magical"};M.specialAbilityCategories={Combat:"SpecCategory.Combat",command:"SpecCategory.command",general:"SpecCategory.general",generalStyle:"SpecCategory.generalStyle",extGeneral:"SpecCategory.extGeneral",animal:"SpecCategory.animal",fatePoints:"SpecCategory.fatePoints",vampire:"SpecCategory.vampire",lykanthrop:"SpecCategory.lykanthrop",language:"SpecCategory.language",secret:"SpecCategory.secret",clerical:"SpecCategory.clerical",clericalStyle:"SpecCategory.clericalStyle",extClericalStyle:"SpecCategory.extClericalStyle",ceremonial:"SpecCategory.ceremonial",vision:"SpecCategory.vision",prayer:"SpecCategory.prayer",magical:"SpecCategory.magical",magicalStyle:"SpecCategory.magicalStyle",extMagical:"SpecCategory.extMagical",staff:"SpecCategory.staff",pact:"SpecCategory.pact",homunculus:"SpecCategory.homunculus"};M.sortedSpecs={combat:new Set(["Combat","command"]),magical:new Set(["magical","magicalStyle","extMagical","pact","homunculus"]),clerical:new Set(["clerical","clericalStyle","extClericalStyle","ceremonial","vision","prayer"]),unUsed:new Set(["staff"])};M.sortedSpecs.general=new Set(Object.keys(M.specialAbilityCategories).filter(l=>!Object.keys(M.sortedSpecs).some(e=>M.sortedSpecs[e].has(l))));M.addvantageRules={};M.removevantageRules={};M.vantagesNeedingAdaption={};M.addAbilityRules={};M.removeAbilityRules={};M.AbilitiesNeedingAdaption={};M.addTraitRules={};M.rangeWeaponModifiers={short:"RangeMod.short",medium:"RangeMod.medium",long:"RangeMod.long",rangesense:"RangeMod.rangesense",extreme:"RangeMod.extreme"};M.meleeRangesArray=["short","medium","long"];M.meleeRanges={short:"Range-short",medium:"Range-medium",long:"Range-long"};M.weapontypes={melee:"meleeweapon",range:"rangeweapon"};M.ammunitiongroups={"-":"-",arrow:"arrow",bolt:"bolt",bullet:"bullet",stone:"stone",dart:"dart",mag:"mag",infinite:"infinite"};M.combatskillsGuidevalues={ff:"CHAR.FF",ge:"CHAR.GE",kk:"CHAR.KK","ge/kk":"CHAR.GEKK"};M.skillDifficultyModifiers={eeasy:5,veasy:3,easy:1,challenging:0,difficult:-1,hard:-3,vhard:-5};M.magicResistanceModifiers={"-":"-",SK:"soulpower",ZK:"toughness"};M.sizeCategories={tiny:"SIZE.tiny",small:"SIZE.small",average:"SIZE.average",big:"SIZE.big",giant:"SIZE.giant"};M.tokenSizeCategories={tiny:.5,small:.8,average:1,big:2,giant:4};M.rangeSizeCategories={tiny:"RANGESIZE.tiny",small:"RANGESIZE.small",average:"RANGESIZE.average",big:"RANGESIZE.big",giant:"RANGESIZE.giant"},M.meleeSizeCategories={tiny:"MELEESIZE.tiny",small:"MELEESIZE.small",average:"MELEESIZE.average",big:"MELEESIZE.big",giant:"MELEESIZE.giant"};M.shieldSizes={short:"SIZE.small",medium:"SIZE.average",long:"SIZE.big"};M.rangeSizeModifier={tiny:-8,small:-4,average:0,big:4,giant:8};M.meleeSizeModifier={tiny:-4,small:0,average:0,big:0,giant:0};M.rangeVision={0:"VisionDisruption.step0","-2":"VisionDisruption.step1","-4":"VisionDisruption.step2","-6":"VisionDisruption.step3","-5000":"VisionDisruption.step4"};M.meleeRangeVision=l=>({"+0":"meleeVisionDisruption.0","-1":"meleeVisionDisruption.1","-2":"meleeVisionDisruption.2","-3":"meleeVisionDisruption.3",[l=="attack"?"*0,5":"-5000"]:"meleeVisionDisruption.4"});M.attributeDifficultyModifiers={eeasy:6,veasy:4,easy:2,challenging:0,difficult:-2,hard:-4,vhard:-6};M.skillDifficultyLabels={eeasy:"Skill-eeasy",veasy:"Skill-veasy",easy:"Skill-easy",challenging:"Skill-challenging",difficult:"Skill-difficult",hard:"Skill-hard",vhard:"Skill-vhard"};M.attributeDifficultyLabels={eeasy:"Attribute-eeasy",veasy:"Attribute-veasy",easy:"Attribute-easy",challenging:"Attribute-challenging",difficult:"Attribute-difficult",hard:"Attribute-hard",vhard:"Attribute-vhard"};M.skillGroups={body:"SKILL.body",social:"SKILL.social",knowledge:"SKILL.knowledge",trade:"SKILL.trade",nature:"SKILL.nature"};M.features=["Object","Spheres","Influence","Clairvoyance","Healing","Transformation","Telekinesis","Elemental","Illusion","Anti-Magic","Demonic","Temporal"];M.skillBurdens={yes:"yes",no:"no",maybe:"maybe"};M.StFs={A:"A",B:"B",C:"C",D:"D"};M.noteIcons={"Griffin Shield":"systems/dsa5/icons/thirdparty/griffinshield.svg","At Sea":"systems/dsa5/icons/thirdparty/at-sea.svg","Medieval Gate":"systems/dsa5/icons/thirdparty/medieval-gate.svg","Position Marker":"systems/dsa5/icons/thirdparty/position-marker.svg",River:"systems/dsa5/icons/thirdparty/river.svg",Trail:"systems/dsa5/icons/thirdparty/trail.svg"};CONFIG.time.roundTime=5;CONFIG.time.turnTime=0;var b=M;function Si(l,e=320,t=40){l.attr({width:e*.8,viewBox:`0 0 ${e} ${t}`});let a=l.find("text"),s=a.get(0).getBBox(),i=e/s.width,n=t/s.height,r=isetTimeout(e,l))}u(na,"delay");async function Ge(l,e,t=!0){let a,s;l.type=="Actor"?(a=await Actor.implementation.fromDropData(l),s=e===a.id):(a=await Item.implementation.fromDropData(l),s=e===a.parent?.uuid);let i=a?.type;return t&&(a=a.toObject()),l.amount&&(a.system.quantity.value=Number(l.amount)),{item:a,typeClass:i,selfTarget:s}}u(Ge,"itemFromDrop");function ra(l,e,t,a="div"){if(e=l.find(e)[0],!e)return;e.classList.add("slist");let s=e.querySelectorAll(a),i=null;for(let n of s)n.draggable=!0,n.addEventListener("dragstart",function(r){i=this}),n.addEventListener("dragover",function(r){r.preventDefault()}),n.addEventListener("drop",async function(r){if(r.preventDefault(),this!=i){let o=0,c=0;for(let m=0;m'),e=$(".tinyNotifications"));let t=$(`
  • ${l}
  • `);e.prepend(t),setTimeout(function(){t.remove()},1500)}u(de,"tinyNotification");function ia(l,e,t,a){let s=Math.ceil(e.scrollLeft),i=e.scrollWidth-e.clientWidth;t.style.display=s>0?"block":"none",a.style.display=i>s?"block":"none",Hi(l)}u(ia,"IconVisibility");async function yt(l){let e=$(l.currentTarget).closest(".searchableAbility")[0].dataset.category.split(" "),t=l.currentTarget.text.replace(/\d+$/,"").trim();for(let a of e){let i=(await game.dsa5.itemLibrary.findCompendiumItem(t,a)).find(n=>n.name==t);if(i){i.sheet.render(!0);return}}if(/\(/.test(t)){t=t.split("(")[0].trim()+" ()";for(let a of e){let i=(await game.dsa5.itemLibrary.findCompendiumItem(t,a)).find(n=>n.name==t);if(i){i.sheet.render(!0);return}}}}u(yt,"clickableAbility");function Hi(l){let e=l.width(),t=Number(getComputedStyle(document.body).getPropertyValue("--minColumnWidth").replace("px","")),a=Number(getComputedStyle(document.body).getPropertyValue("--minColumnWidth60").replace("px","")),s=6;e>=t*2+s?l.removeClass("singleColumnLayout"):l.addClass("singleColumnLayout"),e<=a?l.addClass("minimumColumnLayout"):l.removeClass("minimumColumnLayout")}u(Hi,"columnLayout");function oe(l){let e=l.find(".navWrapper");for(let t of e){let a=t.querySelector(".left-btn"),s=t.querySelector(".right-btn"),i=t.querySelector(".sheet-tabs"),n=!1;s.addEventListener("click",()=>{i.scrollLeft+=150,setTimeout(()=>ia(l,i,a,s),500)}),a.addEventListener("click",()=>{i.scrollLeft-=150,setTimeout(()=>ia(l,i,a,s),500)}),new ResizeObserver(()=>ia(l,i,a,s)).observe(t),i.addEventListener("mousemove",r=>{!n||(i.scrollLeft-=r.movementX,setTimeout(()=>ia(l,i,a,s),500))}),i.addEventListener("mousedown",()=>{n=!0,i.classList.add("dragging"),document.addEventListener("mouseup",()=>{n=!1,i.classList.remove("dragging")},{once:!0})})}}u(oe,"tabSlider");var Ci=u(()=>{document.documentElement.style.setProperty("--app-height",`${window.innerHeight}px`)},"appHeight");window.addEventListener("resize",Ci);Ci();async function ji(){if(!game.settings.get("dsa5","defaultConfigFinished")){console.log("Configuring default token settings");let l=game.settings.get("core","defaultToken");l.displayName=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,l.displayBars=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,l.disposition=CONST.TOKEN_DISPOSITIONS.NEUTRAL,l.bar1={attribute:"status.wounds"},await game.settings.set("core","defaultToken",l),await game.settings.set("core","leftClickRelease",!0),await game.settings.set("dsa5","defaultConfigFinished",!0)}}u(ji,"setupDefaulTokenConfig");async function Gi(l,e){await Gt(),l<24&&await Bi(),l<27&&await qi(),await game.settings.set("dsa5","migrationVersion",e)}u(Gi,"migrateDSA");async function Bi(){for(let l of game.actors){let e=l.effects.filter(t=>["inpain","encumbered"].includes(t.getFlag("core","statusId")));e.length&&await l.deleteEmbeddedDocuments("ActiveEffect",e.map(t=>t.id))}}u(Bi,"migratTo24");async function qi(){game.settings.set("dsa5","disableTokenhotbar",!0)}u(qi,"migrateTo26");async function Gt(){let e=await(await fetch("systems/dsa5/lazy/updatenotes.json")).json();new oa(e).render(!0)}u(Gt,"showPatchViewer");function Xs(){Hooks.once("ready",async function(){if(!game.user.isGM)return;await ji();let l=await game.settings.get("dsa5","migrationVersion"),e=27;lthis.showMore(e))}async showMore(e){let t=[this.json.notes[this.json.notes.length-this.versionIndex]];if(t[0].version=="2.3.0"){e.find(".showMore").hide();return}let a=await this.fetchVersions(t);e.find(".changelogsection").append(a.changelog[0]),e.find(".newssection").append(a.news[0]),this.versionIndex+=1}async fetchVersions(e){let t=game.i18n.lang,a=await Promise.all(e.map(async i=>await renderTemplate(`systems/dsa5/lazy/patchhtml/changelog_${t}_${i.version}.html`))),s=await Promise.all(e.map(async i=>await renderTemplate(`systems/dsa5/lazy/patchhtml/news_${t}_${i.version}.html`)));return{changelog:a,news:s}}async getData(){let e=this.json.notes[this.json.notes.length-1],t=this.json.default.replace(/VERSION/g,e.version),a=`

    CHANGELOG

    ${t}.
    Important updates: ${e.text}

    For details or proposals visit our wiki page at Github or show the Full Changelog in Foundry. Have fun.

    `;await ChatMessage.create(f.chatDataSetup(a,"roll"));let s=game.i18n.lang,i=await this.fetchVersions([e]),n=[this.json.notes[this.json.notes.length-2]],r=await this.fetchVersions(n),o=await renderTemplate(`systems/dsa5/lazy/patchhtml/modules_${s}.html`);return{patchName:t,changelog:i.changelog[0],news:i.news[0],prevVersions:n,prevChangeLogs:r.changelog,prevNews:r.news,modules:o}}};u(oa,"PatchViewer");var Zs=class{static getTalentBonus(e,t,a){let s=[],i=game.settings.get("dsa5","talentModifierEnabled");for(let n of e.items.filter(r=>a.includes(r.type)&&r.system.effect.value.includes(t)))for(let r of n.system.effect.value.split(/;|,/))if(r.includes(t)){let o=f.parseAbilityString(r.trim());o.name==t&&s.push({name:n.name,value:o.step*(n.system.step?n.system.step.value:1),type:o.type,selected:i,source:n.name})}return s}static async stepXPCost(e,t){let a=e.system.APValue.value;return/;/.test(a)&&(a=a.split(";").map(i=>Number(i.trim()))[t]),Number(a)}static calcAPCostSum(e){let t=Number(e.system.APValue.value)*(Number(e.system.step.value)||1);if(/;/.test(e.system.APValue.value)){let a=e.system.APValue.value.split(";").map(s=>Number(s.trim()));t=0;for(let s=0;si[t.name].items.includes(r.type)&&r.name==t.special);n&&(a.system.APValue.value=a.system.APValue.value?a.system.APValue.value.split("/")[n.system.StF.value.charCodeAt(0)-65]:0,Zs.simpleAdoption(a,n,t.name,i));break}return a}static hasItem(e,t,a){return e.items.find(s=>a.includes(s.type)&&s.name==t)!=null}static itemStep(e,t,a){let s=e.items.find(i=>a.includes(i.type)&&i.name==t);return s?Number(s.system.step.value):0}static itemAsModifier(e,t,a,s,i=!1,n=!1){let r=[],o=i?new RegExp(`^${f.escapeRegex(`${t} (`)}`):new RegExp(`^${f.escapeRegex(t)}$`),c=e.items.find(m=>s.includes(m.type)&&o.test(m.name));return c&&r.push({name:c.name,value:Number(c.system.step.value)*a,selected:n,source:c.name}),r}},te=Zs;u(te,"ItemRulesDSA5"),L(te,"children",{});var Be=class extends Dialog{activateListeners(e){super.activateListeners(e),e.find(".select2").select2()}};u(Be,"Select2Dialog");var _=class{static async track(e,t,a){if(game.settings.get("dsa5","enableAPTracking")&&e.hasPlayerOwner){let s=game.journal.find(i=>i.flags.dsa5?.apTrackerId==e.id);if(game.user.isGM||s?.isOwner){s||(s=await _.createJournal(e));let i=await _.getPage(s);await _.addEntry(i,e,t,a)}else{let i={actorId:e.id,apCost:a};t.item?.uuid&&(i.uuid=t.item.uuid,delete t.item),i.description=t,game.socket.emit("system.dsa5",{type:"apTracker",payload:i})}}}static async receiveSocketEvent(e){let t=game.actors.get(e.payload.actorId),a=e.payload.description;e.payload.uuid&&(a.item=await fromUuid(e.payload.uuid)),_.track(t,a,e.payload.apCost)}static async addEntry(e,t,a,s){let i=_.getRow(this.buildDescription(a),this.buildChange(a),s,`${t.system.details.experience.spent}/${t.system.details.experience.total}`),n=$(e.text.content);n.find(".adventurePoints").append(i),await e.update({"text.content":n.prop("outerHTML")})}static buildChange(e){if(e.state)return e.state>0?"":"";let t=e.next>e.previous?"angles-up":"angles-down";return`${e.previous} ${e.next}`}static buildDescription(e){switch(e.type){case"attribute":return game.i18n.localize(`CHAR.${e.attr.toUpperCase()}`);case"permanentLoss":return`${game.i18n.localize(e.attr)} (${game.i18n.localize("permanentCost")})`;case"point":return game.i18n.localize(e.attr);case"item":return e.item.toAnchor?e.item.toAnchor().outerHTML:`${game.i18n.localize("TYPES.Item."+e.item.type)}: ${e.item.name}`;case"sum":return game.i18n.localize("MASTER.awardXP")}}static getRow(e,t,a,s,i=""){return`
    ${e}
    @@ -13,74 +13,74 @@ var vi=Object.defineProperty;var Fi=(l,e,t)=>e in l?vi(l,e,{enumerable:!0,config
    `}static async getPage(e){let t=new Date().toLocaleDateString(game.i18n.lang),a=e.pages.find(s=>s.name==t);return a||(a=(await e.createEmbeddedDocuments("JournalEntryPage",[{name:t,type:"text",text:{format:1,content:`
    ${_.getRow(game.i18n.localize("Description"),game.i18n.localize("attributeChange"),game.i18n.localize("cost"),game.i18n.localize("Total"),"table-title")} -
    `}}]))[0]),a}static async createJournal(e){let t=await f.getFolderForType("JournalEntry",null,game.i18n.localize("TRACKER.adventurePoints")),a=game.journal.find(s=>s.flags.dsa5?.apTrackerId==e.id);return a||(a=await JournalEntry.create({name:e.name,folder:t.id,ownership:e.ownership,flags:{dsa5:{apTrackerId:e.id}}})),a}};u(_,"APTracker");var R=class extends te{static setupFunctions(){}static async abilityAdded(e,t){b.addAbilityRules[t.name]&&b.addAbilityRules[t.name](e,t)}static async abilityRemoved(e,t,a=!0){b.removeAbilityRules[t.name]&&b.removeAbilityRules[t.name](e,t);let s=R.calcAPCostSum(t);s=await R.refundFreelanguage(t,e,s,a)*-1,await e._updateAPs(s,{},{render:a}),await _.track(e,{type:"item",item:t,state:-1},s)}static async _specialabilityReturnFunction(e,t,a,s){if(t==null)return;if(t=duplicate(t),s!=null){if(/,/.test(t.system.APValue.value)){let r=`${t.name.replace(" ()","")} (${s.name}`;t.system.APValue.value=t.system.APValue.value.split(",")[e.items.filter(n=>n.type==t.type&&n.name.includes(r)).length].trim()}R.simpleAdoption(t,s,t.name,b.AbilitiesNeedingAdaption),t.name=`${t.name.replace(" ()","")} (${s.name}${s.customEntry?", "+s.customEntry:""})`,s.system&&s.system.StF?.value&&/\//.test(t.system.APValue.value)&&(t.system.APValue.value=t.system.APValue.value.split("/")[s.system.StF.value.charCodeAt(0)-65].trim())}let i=e.items.find(r=>r.type==a&&r.name==t.name);if(i){let r=duplicate(i),n=await R.isFreeLanguage(t,e,/;/.test(r.system.APValue.value)?r.system.APValue.value.split(";").map(o=>Number(o.trim()))[r.system.step.value]:r.system.APValue.value,!1);r.system.step.value+1<=r.system.maxRank.value&&await e.checkEnoughXP(n)&&(r.system.step.value+=1,await e._updateAPs(n,{},{render:!1}),await e.updateEmbeddedDocuments("Item",[r]),await R.abilityAdded(e,r),await _.track(e,{type:"item",item:i,previous:r.system.step.value-1,next:r.system.step.value},n))}else{let r=await R.isFreeLanguage(t,e,t.system.APValue.value.split(";").map(n=>n.trim())[0],!1);if(await e.checkEnoughXP(r)){await R.abilityAdded(e,t),await e._updateAPs(r,{},{render:!1});let n=(await e.createEmbeddedDocuments("Item",[t]))[0];await _.track(e,{type:"item",item:n,state:1},r)}}}static async refundFreelanguage(e,t,a,s=!0){if(e.system.category.value=="language"&&t.system.freeLanguagePoints){let i=Number(t.system.freeLanguagePoints.value),r=t.items.filter(c=>c.type=="specialability"&&c.system.category.value=="language").reduce((c,m)=>c+Number(m.system.step.value)*Number(m.system.APValue.value),0),n=Math.min(i,r-Number(a)),o=Math.max(0,i-n);await t.update({"system.freeLanguagePoints.used":Math.min(i,Number(n))},{render:s}),a=Math.max(0,a-o)}return a}static async isFreeLanguage(e,t,a,s=!0){if(e.system.category.value=="language"&&t.system.freeLanguagePoints){let i=Number(t.system.freeLanguagePoints.value),r=t.items.filter(c=>c.type=="specialability"&&c.system.category.value=="language").reduce((c,m)=>c+Number(m.system.step.value)*Number(m.system.APValue.value),0),n=Math.min(i,r),o=Math.max(0,i-n);await t.update({"system.freeLanguagePoints.used":Math.min(i,Number(n)+Number(a))},{render:s}),a=Math.max(0,a-o)}return a}static async needsAdoption(e,t,a){let s=b.AbilitiesNeedingAdaption[t.name];if(s){let i,r;if(s.items=="text")i=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-string-dialog.html",{original:t}),r=u(function(n){let o={name:n.find('[name="entryselection"]').val()};R._specialabilityReturnFunction(e,t,a,o)},"callback");else if(s.items=="array"){let n=s.elems.map(o=>({name:o}));i=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-dialog.html",{items:n,original:t,area:s.area}),r=u(function(o){let c=n.find(m=>m.name==o.find('[name="entryselection"]').val());R._specialabilityReturnFunction(e,t,a,c)},"callback")}else{let n=e.items.filter(o=>s.items.includes(o.type)).sort((o,c)=>o.name.localeCompare(c.name));i=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-dialog.html",{items:n,original:t,area:s.area}),r=u(function(o){let c=n.find(m=>m.name==o.find('[name="entryselection"]').val());c.customEntry=o.find('[name="custom"]').val(),R._specialabilityReturnFunction(e,t,a,c)},"callback")}await new Be({title:game.i18n.localize("DIALOG.ItemRequiresAdoption"),content:i,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:r},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}else R._specialabilityReturnFunction(e,t,a,null)}static hasAbility(e,t){return super.hasItem(e,t,["specialability"])}static abilityStep(e,t){return super.itemStep(e,t,["specialability"])}static abilityAsModifier(e,t,a=1,s=!1){return super.itemAsModifier(e,t,a,["specialability"],s)}};u(R,"SpecialabilityRulesDSA5");te.children.SpecialabilityRulesDSA5=R;var Bt=class{static multipleDefenseValue(e,t){let a=-3;return(t.type=="dodge"||getProperty(t,"system.combatskill.value")==game.i18n.localize("LocalizedIDs.wrestle"))&&R.hasAbility(e,game.i18n.localize("LocalizedIDs.masterfulDodge"))?a=-2:R.hasAbility(e,game.i18n.localize("LocalizedIDs.mightyMasterfulParry"))?a=-1:R.hasAbility(e,game.i18n.localize("LocalizedIDs.masterfulParry"))&&(a=-2),R.hasAbility(e,game.i18n.localize("LocalizedIDs.vinsaltStyle"))&&(a-=1),Math.min(0,a)}static async bleedingMessage(e){await ChatMessage.create(f.chatDataSetup(game.i18n.format("CHATNOTIFICATION.applyBleeding",{actor:e.name,actorId:e.id,tokenId:e.token?e.token.id:""})))}static isShield(e){return game.i18n.localize("LocalizedIDs.Shields")==getProperty(e,"system.combatskill.value")}static _getFunctionData(e){return{data:e.currentTarget.dataset,actor:f.getSpeaker({token:e.currentTarget.dataset.token,actor:e.currentTarget.dataset.actor,scene:canvas.scene?canvas.scene.id:null})}}static quantityClick(e){let t=e.currentTarget.dataset.quantityfocus,a=$(e.currentTarget);if(t&&!a.is(":focus")){setTimeout(function(){a.select()});return}let s={val:Number(a.val())};Bt.increment(e,s,"val"),a.val(s.val)}static getGroupSchips(){let e=game.settings.get("dsa5","groupschips").split("/").map(a=>Number(a)),t=[];for(let a=1;a<=e[1];a++)t.push({value:a,cssClass:a<=e[0]?"fullSchip":"emptySchip"});return t}static ensureNumber(e){e.system.AsPCost.value=Number(e.system.AsPCost.value)||e.system.AsPCost.value}static isYieldedTwohanded(e){let t=this.regex2h.test(e.name),a=e.system.worn.wrongGrip;return t&&!a||!t&&a}static obfuscateDropData(e,t){if(t)for(let a of t)mergeObject(e,{system:{obfuscation:{[a]:!0}}})}static _buildDuration(e){let t={duration:{startTime:game.time.worldTime,rounds:e,seconds:e*5}};return game.combat&&mergeObject(t,{duration:{combat:game.combat.id,startRound:game.combat.round,startTurn:game.combat.turn}}),t}static async calcBleeding(e){let{data:t,actor:a}=Bt._getFunctionData(e);if(!a)return;let s=a.items.find(i=>i.name==game.i18n.localize("LocalizedIDs.selfControl")&&i.type=="skill");a.setupSkill(s,{},t.token).then(async i=>{let r=await a.basicTest(i);if(r.result.successLevel<2){let n=r.result.qualityStep||0,o=7;r.result.successLevel==1?o-=Number(n):r.successLevel<1&&(o+=o);let c=a.hasCondition("bleeding"),m=Bt._buildDuration(o);if(c){let d=game.combat?(c.data.duration.startRound||1)+c.data.duration.rounds-game.combat.round:c.data.duration.rounds;o>d&&await c.update(m)}else{let d=duplicate(CONFIG.statusEffects.find(p=>p.id=="bleeding"));mergeObject(d,m),await E.addCondition(a,d,1,!1,!0),await ChatMessage.create(f.chatDataSetup(game.i18n.format("CHATNOTIFICATION.gotBleeding",{actor:a.name})))}}})}static increment(e,t,a,s=void 0){let i=e.ctrlKey?10:1,r=e.button==2?-1:1,n=getProperty(t,a)+i*r;return s!=null&&(n=Math.max(s,n)),setProperty(t,a,n),n}static magicalImprovement(e,t){for(let a of e.items)["ritual","spell"].includes(a.type)&&(a.system.talentValue.value+=4)}},P=Bt;u(P,"RuleChaos"),L(P,"regex2h",/\(2H/),L(P,"improvisedWeapon",/(\(|,)( )?i\)$/);function Ai(){Hooks.on("getImagePopoutHeaderButtons",(l,e)=>{e.unshift({class:"posttochat",icon:"fas fa-comment",onclick:async()=>Wi(l)})})}u(Ai,"initImagePopoutTochat");async function Wi(l){let e=l.object,t=await renderTemplate("systems/dsa5/templates/chat/imagetochat.html",{image:e});ChatMessage.create(f.chatDataSetup(t))}u(Wi,"postImage");function Di(l){let e=l.currentTarget.dataset;f.showArtwork(e,!1)}u(Di,"showPopout");var ae=class{static chatListeners(e){e.on("click",".openJournalBrowser",()=>game.dsa5.apps.journalBrowser.render(!0));let t=$('');t.click(()=>{ae.getHelp()}),$(e.find(".control-buttons")).prepend(t),e.on("click",".showPatchViewer",()=>Gt()),e.on("click",".functionswitch",a=>P[a.currentTarget.dataset.function](a)),e.on("click",".panToToken",a=>ae.panToToken(a)),e.on("click",".popoutImage",a=>Di(a))}static async panToToken(e){let t=await fromUuid(e.currentTarget.dataset.uuid);!t||(canvas.animatePan({x:t.x,y:t.y}),t.isOwner&&t.object.control({releaseOthers:!0}))}static postStatus(e){let t=CONFIG.statusEffects.find(s=>s.id==e),a=`

    ${game.i18n.localize(t.name)}

    ${game.i18n.localize(t.description)}

    `;ChatMessage.create(f.chatDataSetup(a,"roll"))}static getHelp(){let e=b.helpContent.map(t=>`

    ${game.i18n.localize(`HELP.${t.name}`)}

    + `}}]))[0]),a}static async createJournal(e){let t=await f.getFolderForType("JournalEntry",null,game.i18n.localize("TRACKER.adventurePoints")),a=game.journal.find(s=>s.flags.dsa5?.apTrackerId==e.id);return a||(a=await JournalEntry.create({name:e.name,folder:t.id,ownership:e.ownership,flags:{dsa5:{apTrackerId:e.id}}})),a}};u(_,"APTracker");var R=class extends te{static setupFunctions(){}static async abilityAdded(e,t){b.addAbilityRules[t.name]&&b.addAbilityRules[t.name](e,t)}static async abilityRemoved(e,t,a=!0){b.removeAbilityRules[t.name]&&b.removeAbilityRules[t.name](e,t);let s=R.calcAPCostSum(t);s=await R.refundFreelanguage(t,e,s,a)*-1,await e._updateAPs(s,{},{render:a}),await _.track(e,{type:"item",item:t,state:-1},s)}static async _specialabilityReturnFunction(e,t,a,s){if(t==null)return;if(t=duplicate(t),s!=null){if(/,/.test(t.system.APValue.value)){let n=`${t.name.replace(" ()","")} (${s.name}`;t.system.APValue.value=t.system.APValue.value.split(",")[e.items.filter(r=>r.type==t.type&&r.name.includes(n)).length].trim()}R.simpleAdoption(t,s,t.name,b.AbilitiesNeedingAdaption),t.name=`${t.name.replace(" ()","")} (${s.name}${s.customEntry?", "+s.customEntry:""})`,s.system&&s.system.StF?.value&&/\//.test(t.system.APValue.value)&&(t.system.APValue.value=t.system.APValue.value.split("/")[s.system.StF.value.charCodeAt(0)-65].trim())}let i=e.items.find(n=>n.type==a&&n.name==t.name);if(i){let n=duplicate(i),r=await R.isFreeLanguage(t,e,/;/.test(n.system.APValue.value)?n.system.APValue.value.split(";").map(o=>Number(o.trim()))[n.system.step.value]:n.system.APValue.value,!1);n.system.step.value+1<=n.system.maxRank.value&&await e.checkEnoughXP(r)&&(n.system.step.value+=1,await e._updateAPs(r,{},{render:!1}),await e.updateEmbeddedDocuments("Item",[n]),await R.abilityAdded(e,n),await _.track(e,{type:"item",item:i,previous:n.system.step.value-1,next:n.system.step.value},r))}else{let n=await R.isFreeLanguage(t,e,t.system.APValue.value.split(";").map(r=>r.trim())[0],!1);if(await e.checkEnoughXP(n)){await R.abilityAdded(e,t),await e._updateAPs(n,{},{render:!1});let r=(await e.createEmbeddedDocuments("Item",[t]))[0];await _.track(e,{type:"item",item:r,state:1},n)}}}static async refundFreelanguage(e,t,a,s=!0){if(e.system.category.value=="language"&&t.system.freeLanguagePoints){let i=Number(t.system.freeLanguagePoints.value),n=t.items.filter(c=>c.type=="specialability"&&c.system.category.value=="language").reduce((c,m)=>c+Number(m.system.step.value)*Number(m.system.APValue.value),0),r=Math.min(i,n-Number(a)),o=Math.max(0,i-r);await t.update({"system.freeLanguagePoints.used":Math.min(i,Number(r))},{render:s}),a=Math.max(0,a-o)}return a}static async isFreeLanguage(e,t,a,s=!0){if(e.system.category.value=="language"&&t.system.freeLanguagePoints){let i=Number(t.system.freeLanguagePoints.value),n=t.items.filter(c=>c.type=="specialability"&&c.system.category.value=="language").reduce((c,m)=>c+Number(m.system.step.value)*Number(m.system.APValue.value),0),r=Math.min(i,n),o=Math.max(0,i-r);await t.update({"system.freeLanguagePoints.used":Math.min(i,Number(r)+Number(a))},{render:s}),a=Math.max(0,a-o)}return a}static async needsAdoption(e,t,a){let s=b.AbilitiesNeedingAdaption[t.name];if(s){let i,n;if(s.items=="text")i=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-string-dialog.html",{original:t}),n=u(function(r){let o={name:r.find('[name="entryselection"]').val()};R._specialabilityReturnFunction(e,t,a,o)},"callback");else if(s.items=="array"){let r=s.elems.map(o=>({name:o}));i=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-dialog.html",{items:r,original:t,area:s.area}),n=u(function(o){let c=r.find(m=>m.name==o.find('[name="entryselection"]').val());R._specialabilityReturnFunction(e,t,a,c)},"callback")}else{let r=e.items.filter(o=>s.items.includes(o.type)).sort((o,c)=>o.name.localeCompare(c.name));i=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-dialog.html",{items:r,original:t,area:s.area}),n=u(function(o){let c=r.find(m=>m.name==o.find('[name="entryselection"]').val());c.customEntry=o.find('[name="custom"]').val(),R._specialabilityReturnFunction(e,t,a,c)},"callback")}await new Be({title:game.i18n.localize("DIALOG.ItemRequiresAdoption"),content:i,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:n},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}else R._specialabilityReturnFunction(e,t,a,null)}static hasAbility(e,t){return super.hasItem(e,t,["specialability"])}static abilityStep(e,t){return super.itemStep(e,t,["specialability"])}static abilityAsModifier(e,t,a=1,s=!1){return super.itemAsModifier(e,t,a,["specialability"],s)}};u(R,"SpecialabilityRulesDSA5");te.children.SpecialabilityRulesDSA5=R;var Bt=class{static multipleDefenseValue(e,t){let a=-3;return(t.type=="dodge"||getProperty(t,"system.combatskill.value")==game.i18n.localize("LocalizedIDs.wrestle"))&&R.hasAbility(e,game.i18n.localize("LocalizedIDs.masterfulDodge"))?a=-2:R.hasAbility(e,game.i18n.localize("LocalizedIDs.mightyMasterfulParry"))?a=-1:R.hasAbility(e,game.i18n.localize("LocalizedIDs.masterfulParry"))&&(a=-2),R.hasAbility(e,game.i18n.localize("LocalizedIDs.vinsaltStyle"))&&(a-=1),Math.min(0,a)}static async bleedingMessage(e){await ChatMessage.create(f.chatDataSetup(game.i18n.format("CHATNOTIFICATION.applyBleeding",{actor:e.name,actorId:e.id,tokenId:e.token?e.token.id:""})))}static isShield(e){return game.i18n.localize("LocalizedIDs.Shields")==getProperty(e,"system.combatskill.value")}static _getFunctionData(e){return{data:e.currentTarget.dataset,actor:f.getSpeaker({token:e.currentTarget.dataset.token,actor:e.currentTarget.dataset.actor,scene:canvas.scene?canvas.scene.id:null})}}static quantityClick(e){let t=e.currentTarget.dataset.quantityfocus,a=$(e.currentTarget);if(t&&!a.is(":focus")){setTimeout(function(){a.select()});return}let s={val:Number(a.val())};Bt.increment(e,s,"val"),a.val(s.val)}static getGroupSchips(){let e=game.settings.get("dsa5","groupschips").split("/").map(a=>Number(a)),t=[];for(let a=1;a<=e[1];a++)t.push({value:a,cssClass:a<=e[0]?"fullSchip":"emptySchip"});return t}static ensureNumber(e){e.system.AsPCost.value=Number(e.system.AsPCost.value)||e.system.AsPCost.value}static isYieldedTwohanded(e){let t=this.regex2h.test(e.name),a=e.system.worn.wrongGrip;return t&&!a||!t&&a}static obfuscateDropData(e,t){if(t)for(let a of t)mergeObject(e,{system:{obfuscation:{[a]:!0}}})}static _buildDuration(e){let t={duration:{startTime:game.time.worldTime,rounds:e,seconds:e*5}};return game.combat&&mergeObject(t,{duration:{combat:game.combat.id,startRound:game.combat.round,startTurn:game.combat.turn}}),t}static async calcBleeding(e){let{data:t,actor:a}=Bt._getFunctionData(e);if(!a)return;let s=a.items.find(i=>i.name==game.i18n.localize("LocalizedIDs.selfControl")&&i.type=="skill");a.setupSkill(s,{},t.token).then(async i=>{let n=await a.basicTest(i);if(n.result.successLevel<2){let r=n.result.qualityStep||0,o=7;n.result.successLevel==1?o-=Number(r):n.successLevel<1&&(o+=o);let c=a.hasCondition("bleeding"),m=Bt._buildDuration(o);if(c){let d=game.combat?(c.data.duration.startRound||1)+c.data.duration.rounds-game.combat.round:c.data.duration.rounds;o>d&&await c.update(m)}else{let d=duplicate(CONFIG.statusEffects.find(p=>p.id=="bleeding"));mergeObject(d,m),await E.addCondition(a,d,1,!1,!0),await ChatMessage.create(f.chatDataSetup(game.i18n.format("CHATNOTIFICATION.gotBleeding",{actor:a.name})))}}})}static increment(e,t,a,s=void 0){let i=e.ctrlKey?10:1,n=e.button==2?-1:1,r=getProperty(t,a)+i*n;return s!=null&&(r=Math.max(s,r)),setProperty(t,a,r),r}static magicalImprovement(e,t){for(let a of e.items)["ritual","spell"].includes(a.type)&&(a.system.talentValue.value+=4)}},P=Bt;u(P,"RuleChaos"),L(P,"regex2h",/\(2H/),L(P,"improvisedWeapon",/(\(|,)( )?i\)$/);function Ai(){Hooks.on("getImagePopoutHeaderButtons",(l,e)=>{e.unshift({class:"posttochat",icon:"fas fa-comment",onclick:async()=>Ui(l)})})}u(Ai,"initImagePopoutTochat");async function Ui(l){let e=l.object,t=await renderTemplate("systems/dsa5/templates/chat/imagetochat.html",{image:e});ChatMessage.create(f.chatDataSetup(t))}u(Ui,"postImage");function Di(l){let e=l.currentTarget.dataset;f.showArtwork(e,!1)}u(Di,"showPopout");var ae=class{static chatListeners(e){e.on("click",".openJournalBrowser",()=>game.dsa5.apps.journalBrowser.render(!0));let t=$('');t.click(()=>{ae.getHelp()}),$(e.find(".control-buttons")).prepend(t),e.on("click",".showPatchViewer",()=>Gt()),e.on("click",".functionswitch",a=>P[a.currentTarget.dataset.function](a)),e.on("click",".panToToken",a=>ae.panToToken(a)),e.on("click",".popoutImage",a=>Di(a))}static async panToToken(e){let t=await fromUuid(e.currentTarget.dataset.uuid);!t||(canvas.animatePan({x:t.x,y:t.y}),t.isOwner&&t.object.control({releaseOthers:!0}))}static postStatus(e){let t=CONFIG.statusEffects.find(s=>s.id==e),a=`

    ${game.i18n.localize(t.name)}

    ${game.i18n.localize(t.description)}

    `;ChatMessage.create(f.chatDataSetup(a,"roll"))}static getHelp(){let e=b.helpContent.map(t=>`

    ${game.i18n.localize(`HELP.${t.name}`)}

    ${game.i18n.localize("HELP.command")}: ${t.command}

    ${game.i18n.localize("HELP.example")}: ${t.example}

    ${game.i18n.localize("Description")}: ${game.i18n.localize(`HELP.descr${t.name}`)}`).join("")+`
    -

    ${game.i18n.localize("HELP.default")}

    `;ChatMessage.create(f.chatDataSetup(e,"roll"))}static showConditions(){let t=duplicate(CONFIG.statusEffects).map(a=>(a.name=game.i18n.localize(a.name),a)).sort((a,s)=>a.name.localeCompare(s.name)).map(a=>`${a.name}`).join(" ");ChatMessage.create(f.chatDataSetup(t,"roll"))}static async check3D20(e,t,a={}){let s=12;e?(e=e.get(0),t=await f.skillByName(e.textContent),e.dataset.attrs&&(s=e.dataset.attrs.split("|"))):t&&(t=await f.skillByName(t)),t&&(t=t.toObject()),t||(t={name:"3d20",type:"skill",system:{talentValue:{value:0},characteristic1:{value:"mu"},characteristic2:{value:"kl"},characteristic3:{value:"in"},RPr:{value:"no"},burden:{value:"no"}}});let i=await f.emptyActor(s);i.setupSkill(t,a,"emptyActor").then(r=>{i.basicTest(r)})}static async showTables(){let e=await renderTemplate("systems/dsa5/templates/tables/systemtables.html",{tables:b.systemTables});ChatMessage.create(f.chatDataSetup(e,"roll"))}};u(ae,"DSA5ChatListeners");Hooks.once("i18nInit",async()=>{if(!I.creatureData){let l=await fetch(`systems/dsa5/lazy/creaturetype/${game.i18n.lang}.json`);I.creatureData=await l.json(),I.magical=game.i18n.localize("WEAPON.magical"),I.clerical=game.i18n.localize("WEAPON.clerical"),I.silverPlated=game.i18n.localize("WEAPON.silverPlated"),game.dsa5.apps.CreatureType=I}});var Ui=u(l=>!(!l||l.length===0),"isNotEmpty"),me=class{constructor(e){this.creatureClass=e,this.spellImmunities=[],this.poisonImmunity=!1,this.diseaseImmunity=!1}static detectCreatureType(e){let t=e.type=="creature"?e.system.creatureClass.value:e.system.details.species.value;return Object.keys(me.creatureData.types).filter(s=>t.indexOf(s)>=0).map(s=>this.getClass(me.creatureData.types[s],t))}static getClass(e,t){let a={DemonType:ma,ChimeraType:la,DaimonidType:ca,DragonType:da,ElementalType:ua,FairyType:pa,GhostType:ga,GolemType:fa,HomunculiType:ha,IntelligentCreatureType:ya,PlantType:ba,AnimalType:ka,UndeadType:wa,SupernaturalType:va,MagicalConstructType:Ta,WerCreatureType:Sa,VampireType:Ca}[e];return new a(t)}getName(){return Object.keys(me.creatureData.types).find(e=>me.creatureData.types[e]==this.constructor.name)}static checkImmunity(e){let t=[];switch(e.preData.source.type){case"poison":case"disease":{let a=game.i18n.localize("LocalizedIDs.immuneTo")+" ("+e.preData.source.name+")";for(let s of game.user.targets){let i=s.actor,r=i.items.find(n=>n.name==a&&n.type=="advantage");if(r)t.push({name:r.name,uuid:r.uuid,target:i.name,condition:e.preData.source.name});else{let n=me.detectCreatureType(s.actor);for(let o of n)if(o[`${e.preData.source.type}Immunity`]){t.push({name:e.preData.source.name,target:`${i.name} (${o.getName()})`,condition:e.preData.source.name});break}}}break}case"spell":case"ritual":{for(let a of game.user.targets){let s=me.detectCreatureType(a.actor),i=e.preData.source.system.feature.split(",").map(n=>n.trim()),r=!1;for(let n of s){for(let o of i)if(n.spellImmunities.includes(o)){t.push({name:e.preData.source.name,target:`${a.actor.name} (${n.getName()})`,condition:`${game.i18n.localize("feature")} ${o}`}),r=!0;break}if(r)break}}break}}return t}static creatureTypeName(e){if(e.type=="creature"){let t=e.system.creatureClass.value;return Object.keys(me.creatureData.types).filter(a=>t.indexOf(a)>=0)[0]}else return e.system.details.species.value}static addCreatureTypeModifiers(e,t,a,s){let i=me.detectCreatureType(e),r=["spell","ceremony","liturgy","ritual"].includes(t.type);for(let n of i){let o=n.damageModifier(t);if(r)for(let c of o)c.armorPen=n.spellResistanceModifier(e);a.push(...o)}a.push(...this.creatureBonusDamage(e,s)),me.addVulnerabilitiesToSource(e,t,a)}static addVulnerabilitiesToSource(e,t,a){let s=getProperty(e,"system.vulnerabilities");s&&["meleeweapon","rangeweapon"].includes(t.type)&&getProperty(s,"combatskill").reduce((r,n)=>{if(n.target==t.system.combatskill.value){let c=(/\*/.test(n.value)?Number(n.value.replace("*",""))>1:Number(n.value)>0)?"WEAPON.vulnerableTo":"WEAPON.resistantTo";a.push(...me.buildDamageMod(`${game.i18n.format(c,{name:t.system.combatskill.value})} (${n.source})`,n.value))}},a)}ignoredCondition(e){return!1}damageModifier(e){return[]}static creatureBonusDamage(e,t){let a=[],s=e.type=="creature"?e.system.creatureClass.value:e.system.details.species.value,i=getProperty(t,"system.creatureBonus");for(let r of i)s.indexOf(r.target)>=0&&a.push(...this.buildDamageMod(r.source,r.value,!0));return a}spellImmunity(e){return this.spellImmunities.some(t=>e.includes(t))}spellArmorModifier(e){return 0}poisonImmunity(){return this.poisonImmunity}diseaseImmunity(){return this.diseaseImmunity}spellResistanceModifier(e){return 0}static buildDamageMod(e,t,a=!0){return[{name:e,value:t,selected:a,type:"dmg",source:game.i18n.localize("target")}]}weaponAttributes(e){return getProperty(e,"system.effect.attributes")||""}getTypeByClass(e){return Object.keys(me.creatureData.types).find(t=>me.creatureData.types[t]===e)}isAttackItem(e){return["meleeweapon","trait","rangeweapon"].includes(e.type)&&Ui(this.weaponAttributes(e))}attributesRegex(e){let t=this.weaponAttributes(e);return new RegExp(`(${t.split(",").map(a=>f.escapeRegex(a.split("(")[0].trim())).join("|")})`,"i")}},I=me;u(I,"CreatureType"),L(I,"creatureData"),L(I,"magical"),L(I,"clerical");var bt=class extends I{damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);for(let a of I.creatureData.godOfLife){let s=`${I.clerical} (${a})`;if(t.test(s))return I.buildDamageMod(s,"*2")}}return super.damageModifier(e)}};u(bt,"VulnerableToLifeGods");var la=class extends bt{};u(la,"ChimeraType");var ca=class extends I{constructor(e){super(e),this.spellImmunities=["Influence","Transformation"].map(t=>game.i18n.localize(`Features.${t}`))}damageModifier(e){return this.isAttackItem(e)&&this.attributesRegex(e).test(I.clerical)?I.buildDamageMod(I.clerical,"*2"):super.damageModifier(e)}};u(ca,"DaimonidType");var da=class extends I{};u(da,"DragonType");var ma=class extends I{constructor(e){super(e),this.spellImmunities=["Influence","Transformation","Healing","Illusion"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);if(t.test(I.clerical))return I.buildDamageMod(`${I.clerical} (${I.creatureData.opposingGod})`,"*2",!1);if(t.test(I.magical))return super.damageModifier(e)}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return super.damageModifier(e);return I.buildDamageMod(this.getTypeByClass("DemonType"),"*0.5")}spellArmorModifier(e){return Number(e.system.status.soulpower.max)}spellResistanceModifier(e){return Number(e.system.status.soulpower.max)}ignoredCondition(e){return!0}};u(ma,"DemonType");var ua=class extends I{constructor(e){super(e),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){if(this.attributesRegex(e).test(I.magical))return super.damageModifier(e)}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return I.buildDamageMod(this.getTypeByClass("ElementalType"),"*1");return I.buildDamageMod(this.getTypeByClass("ElementalType"),"*0.5")}spellArmorModifier(e){return Number(e.system.status.soulpower.max)}spellResistanceModifier(e){return Number(e.system.status.soulpower.max)}ignoredCondition(e){return!0}};u(ua,"ElementalType");var pa=class extends I{constructor(e){super(e),this.spellImmunities=["Illusion"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}};u(pa,"FairyType");var ga=class extends I{constructor(e){super(e),this.spellImmunities=["Illusion","Healing","Telekinesis","Transformation"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);for(let a of I.creatureData.godOfDeath){let s=`${I.clerical} (${a})`;if(t.test(s))return[]}if(t=this.attributesRegex(e),t.test(I.clerical))return I.buildDamageMod(I.clerical,"*0.5");if(t.test(I.magical))return I.buildDamageMod(I.magical,"*0.5")}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return I.buildDamageMod(I.magical,"*0.5");return I.buildDamageMod(this.getTypeByClass("GhostType"),"*0")}ignoredCondition(e){return!["feared","inpain","confused"].includes(e)}};u(ga,"GhostType");var fa=class extends bt{constructor(e){super(e),this.spellImmunities=["Transformation"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}ignoredCondition(e){return!["confused","paralysed"].includes(e)}};u(fa,"GolemType");var ha=class extends bt{constructor(e){super(e),this.spellImmunities=["Healing"].map(t=>game.i18n.localize(`Features.${t}`))}ignoredCondition(e){return!["inpain","encumbered","stunned","feared","paralysed","confused"].includes(e)}};u(ha,"HomunculiType");var ya=class extends I{};u(ya,"IntelligentCreatureType");var ba=class extends I{};u(ba,"PlantType");var ka=class extends I{};u(ka,"AnimalType");var wa=class extends I{constructor(e){super(e),this.spellImmunities=["Influence","Healing","Illusion"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);for(let a of I.creatureData.godOfDeath){let s=`${I.clerical} (${a})`;if(t.test(s))return I.buildDamageMod(s,"*2")}}return super.damageModifier(e)}ignoredCondition(e){return!["paralysed"].includes(e)}};u(wa,"UndeadType");var va=class extends I{};u(va,"SupernaturalType");var Ta=class extends I{constructor(e){super(e),this.spellImmunities=["Transformation"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}ignoredCondition(e){return!["stunned","feared","paralysed","confused"].includes(e)}};u(Ta,"MagicalConstructType");var Sa=class extends I{damageModifier(e){if(this.isAttackItem(e)){if(this.attributesRegex(e).test(I.silverPlated))return I.buildDamageMod(this.getTypeByClass("WerCreatureType"),"*2")}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return super.damageModifier(e);return I.buildDamageMod(this.getTypeByClass("WerCreatureType"),"*0.5")}};u(Sa,"WerCreatureType");var Ca=class extends I{damageModifier(e){return["spell","ceremony","liturgy","ritual"].includes(e.type)?super.damageModifier(e):I.buildDamageMod(this.getTypeByClass("VampireType"),"*0.5")}};u(Ca,"VampireType");var E=class{static bindButtons(e){e.find(".chat-condition").each(function(t,a){a.setAttribute("draggable",!0),a.addEventListener("dragstart",s=>{let i={data:{type:"condition",payload:{id:s.currentTarget.dataset.id}}};s.dataTransfer.setData("text/plain",JSON.stringify(i))})}),e.on("click",".chat-condition",t=>ae.postStatus(t.currentTarget.dataset.id))}static createCustomEffect(e,t="",a){a=a||game.i18n.localize("CONDITION.custom"),t==""&&(t=a),e.addCondition({name:a,icon:"icons/svg/aura.svg",origin:e.uuid,flags:{dsa5:{description:t}}})}static prepareActiveEffects(e,t){let a=duplicate(CONFIG.statusEffects),s=[];t.conditions=[],t.transferedConditions=[];let i;e.documentName=="Item"?i=e.effects:(i=Array.from(e.allApplicableEffects()),game.user.isGM||(i=i.filter(n=>!n.getFlag("dsa5","hidePlayers"))));for(let n of i){let o=n.toObject();o.boolean=n.getFlag("dsa5","value")==null;let c=[...n.statuses][0];c&&(o.value=n.getFlag("dsa5","value"),o.editable=n.getFlag("dsa5","max"),o.descriptor=c,o.manual=n.getFlag("dsa5","manual"),s.push(c)),e.documentName=="Item"||n.parent?.documentName!="Item"&&!n.notApplicable?t.conditions.push(o):n.notApplicable||(o.uuid=n.uuid,o.parent={uuid:n.parent?.uuid,name:n.parent?.name},t.transferedConditions.push(o))}t.manualConditions=a.filter(n=>!s.includes(n.id));let r=[];for(let n of Object.keys(e.system?.condition||{}))if(e.system.condition[n]){let o=b.statusEffects.find(c=>c.id==n);o&&r.push({icon:o.icon,id:n,name:game.i18n.localize(o.name),value:e.system.condition[n]})}t.cumulativeConditions=r}static async addCondition(e,t,a=1,s=!1,i=!0){if(!e.isOwner)return"Not owned";if(e.compendium)return"Can not add in compendium";if(s&&a<1)return this.removeCondition(e,t,a,i,s);if(typeof t=="string"&&(t=duplicate(CONFIG.statusEffects.find(n=>n.id==t))),!t)return"No Effect Found";let r=this.hasCondition(e,t.id);return r&&r.flags.dsa5.value==null?r:r?await E.updateEffect(e,r,a,s,i,t):await E.createEffect(e,t,a,i)}static hasCondition(e,t){return e!=null&&t&&e.effects?e.effects.find(a=>a.statuses.has(t)):!1}static async removeCondition(e,t,a=1,s=!0,i=!1){if(!e.isOwner)return"Not owned";if(typeof t=="string"&&(t=duplicate(CONFIG.statusEffects.find(n=>n.id==t))),!t)return"No Effect Found";let r=this.hasCondition(e,t.id);if(r&&r.flags.dsa5.value==null)return e.token&&(e=e.token.actor),await e.deleteEmbeddedDocuments("ActiveEffect",[r.id]);if(r)return await E.removeEffect(e,r,a,i,s)}static immuneToEffect(e,t,a=!0){if(!t.id||!hasProperty(t,"flags.dsa5.max"))return;let s=getProperty(e,"system.immunities")||[],i;if(s.includes(t.id)&&(i={name:e.name,condition:game.i18n.localize(`CONDITION.${t.id}`)}),!i&&e.documentName=="Actor"){let n=I.detectCreatureType(e);for(let o of n)if(o.ignoredCondition(t.id)){i={name:`${e.name} (${o.getName()})`,condition:game.i18n.localize(`CONDITION.${t.id}`)};break}}if(!i||!(ui.notifications&&!a))return;let r=game.i18n.format("DSAError.conditionInvalidToCreature",{name:i.name,condition:i.condition});ui.notifications.warn(r)}static resistantToEffect(e,t){let a=[...t.statuses][0];return a?(getProperty(e,"system.resistances.effects")||[]).reduce((i,r)=>(r.target==a&&(i+=Number(r.value)),i),0):0}static async createEffect(e,t,a,s){t.name=game.i18n.localize(t.name),this.immuneToEffect(e,t,!1),s?(t.flags.dsa5.auto=Math.min(t.flags.dsa5.max,a),t.flags.dsa5.manual=0):(t.flags.dsa5.manual=Math.min(t.flags.dsa5.max,a),t.flags.dsa5.auto=0),t.flags.dsa5.value=Math.min(4,t.flags.dsa5.manual+t.flags.dsa5.auto),t.id&&(t.statuses=[t.id]),t.id=="dead"&&(t["flags.core.overlay"]=!0);let i=duplicate(t);(game.dsa5.config.statusEffectClasses[t.id]||E).levelDependentEffects(t,i);let r=await e.createEmbeddedDocuments("ActiveEffect",[i]);return delete t.id,r}static async removeEffect(e,t,a,s,i){let r=i?s?a:Math.max(0,t.flags.dsa5.auto-a):t.flags.dsa5.auto,n=i?t.flags.dsa5.manual:s?a:t.flags.dsa5.manual-a,o={flags:{dsa5:{auto:r,manual:n,value:Math.max(0,Math.min(t.flags.dsa5.max,n+r))}}};return o.flags.dsa5.auto<1&&o.flags.dsa5.manual==0?await e.deleteEmbeddedDocuments("ActiveEffect",[t.id]):((game.dsa5.config.statusEffectClasses[[...t.statuses][0]]||E).levelDependentEffects(t,o),await t.update(o))}static async levelDependentEffects(e,t){}static async updateEffect(e,t,a,s,i,r=void 0){this.immuneToEffect(e,t,!0);let n,o,c;return i?(o=Math.min(t.flags.dsa5.max,s?a:t.flags.dsa5.auto+a),n=o-t.flags.dsa5.auto,c={flags:{dsa5:{auto:o,manual:t.flags.dsa5.manual}}}):(o=s?a:t.flags.dsa5.manual+a,n=o-t.flags.dsa5.manual,c={flags:{dsa5:{manual:o,auto:t.flags.dsa5.auto}}}),n==0||(c.flags.dsa5.value=Math.max(0,Math.min(t.flags.dsa5.max,c.flags.dsa5.manual+c.flags.dsa5.auto)),r.duration&&(c.duration=r.duration,c.duration.startTime=game.time.worldTime),(game.dsa5.config.statusEffectClasses[[...t.statuses][0]]||E).levelDependentEffects(t,c),await t.update(c)),t}static calculateRollModifier(e,t,a,s={}){return e.flags.dsa5.value==null||a.type=="regenerate"?0:E.clampedCondition(t,e)}static clampedCondition(e,t){let a=[...t.statuses][0];if(!a)return 0;let s=Number(t.flags.dsa5.max),i=Math.clamped(e.system.condition[a]||0,0,s)*-1,r=this.resistantToEffect(e,t);return Math.clamped(i+r,-1*s,0)}static ModifierIsSelected(e,t={},a){return t.mode!="damage"}static getDamageBonus(){return 0}static getRollModifiers(e,t,a={}){let s=game.i18n.localize("status")+"/"+game.i18n.localize("condition"),i=[],r=[];for(let c of e.effects){if(c.disabled)continue;let m=[...c.statuses][0],d=game.dsa5.config.statusEffectClasses[m]||E,p=d.calculateRollModifier(c,e,t,a);m&&r.push(m),p!=0&&i.push({name:c.name,value:p,selected:d.ModifierIsSelected(t,a,e),source:s})}for(let[c,m]of Object.entries(e.system.condition))if(m&&!r.includes(c)){let d=duplicate(b.statusEffects.find(y=>y.id==c));if(!d)continue;let p=game.dsa5.config.statusEffectClasses[c]||E;d.flags.dsa5.value=m,d.statuses=[c];let g=p.calculateRollModifier(d,e,t,a);g!=0&&i.push({name:d.name,value:g,selected:p.ModifierIsSelected(t,a,e),source:s})}let n=e.hasPlayerOwner,o=game.settings.get("dsa5","masterSettings").globalMods||{};for(let c of Object.keys(o)){let m=expandObject(o[c]);if(!(!m.enabled||!m.target||!m.target[t.type])){if(n){if(!m.victim?.player)continue}else if(!m.victim?.npc)continue;i.push({name:m.name,value:m.value,selected:!0,source:game.i18n.localize("MASTER.globalMods")})}}return i}};u(E,"DSA5StatusEffects");var Aa=class extends E{static ModifierIsSelected(e,t={},a){let s=e.type=="skill"&&e.system.burden.value=="yes",i=["rangeweapon"].includes(e.type)&&t.mode!="damage"&&game.settings.get("dsa5","encumbranceForRange"),r=!["skill","spell","ritual","ceremony","liturgy","rangeweapon"].includes(e.type)&&t.mode!="damage";return s||r||i}static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"||a.type=="skill"&&a.system.burden.value=="no"?0:super.calculateRollModifier(e,t,a,s)}};u(Aa,"EncumberedEffect");var Da=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="dodge"?-2:s.mode?s.mode=="attack"?-4:-2:0}};u(Da,"ProneEffect");var Ma=class extends E{static calculateRollModifier(e,t,a,s={}){let i=new RegExp(`${game.i18n.localize("combatskill")} `,"gi"),r=t.system.happyTalents.value.split(/;|,/).map(n=>n.replace(i,"").trim());return r.includes(a.name)&&["skill","combatskill"].includes(a.type)||["rangeweapon","meleeweapon"].includes(a.type)&&r.includes(a.system.combatskill.value)||["ceremony","liturgy"].includes(a.type)?this.clampedCondition(t,e)*-1-1:["ritual","spell","skill","combatskill"].includes(a.type)?this.clampedCondition(t,e):(a.type=="regenerate",0)}};u(Ma,"RaptureEffect");var Ia=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.perception")?-3:0}};u(Ia,"DeafEffect");var Ea=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"?a.name==game.i18n.localize("LocalizedIDs.featOfStrength")?2:0:s.mode=="attack"?4:0}};u(Ea,"BloodrushEffect");var $a=class extends E{static ModifierIsSelected(e,t={},a){return a.effects.find(s=>Array.from(s.statuses).includes("bloodrush"))==null}};u($a,"PainEffect");var Oa=class extends E{static calculateRollModifier(e,t,a,s={}){if(a.type=="regenerate")return 0;switch(Number(this.clampedCondition(t,e))){case-2:let i=new RegExp(`${game.i18n.localize("combatskill")} `,"gi"),r=t.system.happyTalents.value.split(/;|,/).map(n=>n.replace(i,"").trim());if(r.includes(a.name)&&["skill","combatskill"].includes(a.type)||["rangeweapon","meleeweapon"].includes(a.type)&&r.includes(a.system.combatskill.value)||["ceremony","liturgy"].includes(a.type))return-2;case-3:return-3}return 0}};u(Oa,"TranceEffect");var xa=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.gambling")?Math.clamped(this.clampedCondition(t,e),-3,0):0}};u(xa,"DrunkenEffect");var za=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.bodyControl")?Math.clamped(this.clampedCondition(t,e)+1,-2,0):0}};u(za,"BurningEffect");var Pa=class extends E{static calculateRollModifier(e,t,a,s={}){return 0}};u(Pa,"ArousalEffect");var Na=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.willpower")?(this.clampedCondition(t,e)+1)*2:a.type=="regenerate"?this.clampedCondition(t,e):0}};u(Na,"SikaryanlossEffect");var La=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.willpower")?Math.clamped(this.clampedCondition(t,e),-3,0):0}};u(La,"DesireEffect");var Ra=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?this.clampedCondition(t,e)*-1:0}};u(Ra,"TheriakEffect");var _a=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="skill"&&a.system.group.value=="body"?Math.clamped(this.clampedCondition(t,e)-1,3,0)*-1:0}};u(_a,"SunkenEffect");var Fa=class extends E{static calculateRollModifier(e,t,a,s={}){let i=Math.clamped(e.flags.dsa5.value,0,4);return a.type=="regenerate"?Math.pow(2,i-1)*-1:0}};u(Fa,"HungerEffect");var Ha=class extends E{static calculateRollModifier(e,t,a,s={}){return 0}static levelDependentEffects(e,t){t.changes={1:[],2:[{key:"system.condition.stunned",mode:2,value:1/2}],3:[{key:"system.condition.stunned",mode:2,value:2/3}],4:[{key:"system.condition.stunned",mode:2,value:3/4}]}[t.flags.dsa5.value]}};u(Ha,"ThirstEffect");var ja=class extends E{static levelDependentEffects(e,t){t.changes={1:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:1}],2:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:1/2}],3:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:2/3}],4:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:1/2}]}[t.flags.dsa5.value]}};u(ja,"HeatEffect");var Ga=class extends E{static levelDependentEffects(e,t){t.changes={1:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:1}],2:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:1/2}],3:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:2/3}],4:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:1/2}]}[t.flags.dsa5.value]}};u(Ga,"ColdEffect");var Ba=class extends E{static calculateRollModifier(e,t,a,s={}){return 0}};u(Ba,"NoModifierEffect");b.statusEffectClasses={inpain:$a,heat:ja,cold:Ga,encumbered:Aa,stunned:E,raptured:Ma,feared:E,paralysed:E,confused:E,prone:Da,deaf:Ia,bloodrush:Ea,trance:Oa,drunken:xa,arousal:Pa,burning:za,sikaryanloss:Na,desire:La,theriak:Ra,services:Ba,sunken:_a,hunger:Fa,thirst:Ha};var O=class extends te{static setupFunctions(){}static async vantageAdded(e,t){game.dsa5.config.addvantageRules[t.name]&&game.dsa5.config.addvantageRules[t.name](e,t)}static async vantageRemoved(e,t,a=!0){game.dsa5.config.removevantageRules[t.name]&&game.dsa5.config.removevantageRules[t.name](e,t);let s=O.calcAPCostSum(t);s=await O.removeSingularVantages(e,t,s)*-1,await e._updateAPs(s,{},{render:a}),await _.track(e,{type:"item",item:t,state:-1},s)}static async _vantageReturnFunction(e,t,a,s){if(t==null)return;if(t=duplicate(t),/,/.test(t.system.APValue.value)){let n=t.name.replace(" ()","");t.system.APValue.value=t.system.APValue.value.split(",")[e.items.filter(o=>o.type==t.type&&o.name.includes(n)).length].trim()}s!=null&&(O.simpleAdoption(t,s,t.name,b.vantagesNeedingAdaption),t.name=`${t.name.replace(" ()","")} (${s.name})`,s.system&&(t.system.APValue.value=t.system.APValue.value.split("/")[s.system.StF.value.charCodeAt(0)-65].trim()));let i=e.items.find(n=>n.type==a&&n.name==t.name),r;if(i){let n=duplicate(i);r=Number(/;/.test(n.system.APValue.value)?n.system.APValue.value.split(";").map(o=>Number(o.trim()))[n.system.step.value]:n.system.APValue.value),n.system.step.value+1<=n.system.max.value&&await e.checkEnoughXP(r)&&(n.system.step.value+=1,r=this.addSingularVantages(e,n,r),await e._updateAPs(r,{},{render:!1}),await e.updateEmbeddedDocuments("Item",[n]),await O.vantageAdded(e,n),await _.track(e,{type:"item",item:i,previous:n.system.step.value-1,next:n.system.step.value},r))}else if(await e.checkEnoughXP(r=Number(t.system.APValue.value.split(";").map(n=>n.trim())[0]))){await O.vantageAdded(e,t),r=this.addSingularVantages(e,t,r),await e._updateAPs(r,{},{render:!1});let n=(await e.createEmbeddedDocuments("Item",[t]))[0];await _.track(e,{type:"item",item:n,state:1},r)}}static async needsAdoption(e,t,a){if(b.vantagesNeedingAdaption[t.name]){let s,i;if(b.vantagesNeedingAdaption[t.name].items=="text")s=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-string-dialog.html",{original:t}),i=u(function(r){let n={name:r.find('[name="entryselection"]').val()};O._vantageReturnFunction(e,t,a,n)},"callback");else{let r=e.items.filter(n=>b.vantagesNeedingAdaption[t.name].items.includes(n.type));s=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-dialog.html",{items:r,original:t}),i=u(function(n){let o=r.find(c=>c.name==n.find('[name="entryselection"]').val());O._vantageReturnFunction(e,t,a,o)},"callback")}await new Be({title:game.i18n.localize("DIALOG.ItemRequiresAdoption"),content:s,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:i},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}else O._vantageReturnFunction(e,t,a,null)}static addSingularVantages(e,t,a){let s=u((i,r,n)=>i.type=="disadvantage"&&r.test(i.name),"filter");return O._calculateSingularVantages(t,e,a,s)}static removeSingularVantages(e,t,a){let s=u((i,r,n)=>i.type=="disadvantage"&&r.test(i.name)&&i.name!=n.name,"filter");return O._calculateSingularVantages(t,e,a,s)}static _calculateSingularVantages(e,t,a,s,i=(r,n)=>Math.min(0,r-n)){if(e.type!="disadvantage")return a;for(let r of["principles","obligations"]){let n=new RegExp(`^${game.i18n.localize("LocalizedIDs."+r)} \\(`);if(n.test(e.name)){let o=t.items.filter(d=>s(d,n,e)),c=Math.min(0,...o.map(d=>O.calcAPCostSum(d))),m=O.calcAPCostSum(e);a=i(m,c)}}return a}static reduceSingularVantages(e,t,a){let s=u((r,n,o)=>r.type=="disadvantage"&&n.test(r.name)&&r.name!=o.name,"filter"),i=u((r,n)=>r0,a=a||s.data.dim>0,t)break;continue}let i=J.rangeFinder(e,s.object).distanceSum,r=s.object.document.config||s.object.document.light,n=r.bright>=i,o=r.dim>=i;if(!(!n&&!o)&&((s.data.walls===!1||s.shape.contains(e.center.x,e.center.y))&&(t=n||t,a=o||a),t))break}return{bright:t,dim:a}}static get isEnabled(){let e=canvas?.scene?.getFlag("dsa5","enableDPS");return e?e=="2":game.settings.get("dsa5","enableDPS")}static lightLevel(e,t){if(canvas.scene&&game.settings.get("dsa5","sightAutomationEnabled")){let a=0,s=canvas.scene?.darkness||0,i=game.settings.get("dsa5","sightOptions").split("|").map(n=>Number(n));for(;i[a]<=s;)a+=1;if(e){let n=O.vantageStep(e,game.i18n.localize("LocalizedIDs.darksight")),o=Number(getProperty(e,"system.sightModifier.value"))||0,c=Number(getProperty(e,"system.sightModifier.maxLevel"))||3,m=Array.from(game.user.targets);if(m.length){m=m[0];let d=J.inLight(m),p=0;d.bright?p=-2:d.dim&&(p=-1),a=Math.max(a+p,0)}a<=c&&a>0&&(n>1?a=0:a=Math.clamped(a+o-n,0,4))}let r=t.find(`[name="vision"] option:nth-child(${a+1})`);r.length&&(r[0].selected=!0)}}static distanceModifier(e,t,a){if(!J.isEnabled||!e)return 1;let s={};for(let i of game.user.targets){let r=J.rangeFinder(e,i);(s.distanceSum||0)Number(o)*i),n=0;for(;n<2&&r[n]{let a=getProperty(l.object,"flags.dsa5.enableDPS"),s=`
    +

    ${game.i18n.localize("HELP.default")}

    `;ChatMessage.create(f.chatDataSetup(e,"roll"))}static showConditions(){let t=duplicate(CONFIG.statusEffects).map(a=>(a.name=game.i18n.localize(a.name),a)).sort((a,s)=>a.name.localeCompare(s.name)).map(a=>`${a.name}`).join(" ");ChatMessage.create(f.chatDataSetup(t,"roll"))}static async check3D20(e,t,a={}){let s=12;e?(e=e.get(0),t=await f.skillByName(e.textContent),e.dataset.attrs&&(s=e.dataset.attrs.split("|"))):t&&(t=await f.skillByName(t)),t&&(t=t.toObject()),t||(t={name:"3d20",type:"skill",system:{talentValue:{value:0},characteristic1:{value:"mu"},characteristic2:{value:"kl"},characteristic3:{value:"in"},RPr:{value:"no"},burden:{value:"no"}}});let i=await f.emptyActor(s);i.setupSkill(t,a,"emptyActor").then(n=>{i.basicTest(n)})}static async showTables(){let e=await renderTemplate("systems/dsa5/templates/tables/systemtables.html",{tables:b.systemTables});ChatMessage.create(f.chatDataSetup(e,"roll"))}};u(ae,"DSA5ChatListeners");Hooks.once("i18nInit",async()=>{if(!I.creatureData){let l=await fetch(`systems/dsa5/lazy/creaturetype/${game.i18n.lang}.json`);I.creatureData=await l.json(),I.magical=game.i18n.localize("WEAPON.magical"),I.clerical=game.i18n.localize("WEAPON.clerical"),I.silverPlated=game.i18n.localize("WEAPON.silverPlated"),game.dsa5.apps.CreatureType=I}});var Vi=u(l=>!(!l||l.length===0),"isNotEmpty"),me=class{constructor(e){this.creatureClass=e,this.spellImmunities=[],this.poisonImmunity=!1,this.diseaseImmunity=!1}static detectCreatureType(e){let t=e.type=="creature"?e.system.creatureClass.value:e.system.details.species.value;return Object.keys(me.creatureData.types).filter(s=>t.indexOf(s)>=0).map(s=>this.getClass(me.creatureData.types[s],t))}static getClass(e,t){let a={DemonType:ma,ChimeraType:la,DaimonidType:ca,DragonType:da,ElementalType:ua,FairyType:pa,GhostType:ga,GolemType:fa,HomunculiType:ha,IntelligentCreatureType:ya,PlantType:ba,AnimalType:ka,UndeadType:wa,SupernaturalType:va,MagicalConstructType:Ta,WerCreatureType:Sa,VampireType:Ca}[e];return new a(t)}getName(){return Object.keys(me.creatureData.types).find(e=>me.creatureData.types[e]==this.constructor.name)}static checkImmunity(e){let t=[];switch(e.preData.source.type){case"poison":case"disease":{let a=game.i18n.localize("LocalizedIDs.immuneTo")+" ("+e.preData.source.name+")";for(let s of game.user.targets){let i=s.actor,n=i.items.find(r=>r.name==a&&r.type=="advantage");if(n)t.push({name:n.name,uuid:n.uuid,target:i.name,condition:e.preData.source.name});else{let r=me.detectCreatureType(s.actor);for(let o of r)if(o[`${e.preData.source.type}Immunity`]){t.push({name:e.preData.source.name,target:`${i.name} (${o.getName()})`,condition:e.preData.source.name});break}}}break}case"spell":case"ritual":{for(let a of game.user.targets){let s=me.detectCreatureType(a.actor),i=e.preData.source.system.feature.split(",").map(r=>r.trim()),n=!1;for(let r of s){for(let o of i)if(r.spellImmunities.includes(o)){t.push({name:e.preData.source.name,target:`${a.actor.name} (${r.getName()})`,condition:`${game.i18n.localize("feature")} ${o}`}),n=!0;break}if(n)break}}break}}return t}static creatureTypeName(e){if(e.type=="creature"){let t=e.system.creatureClass.value;return Object.keys(me.creatureData.types).filter(a=>t.indexOf(a)>=0)[0]}else return e.system.details.species.value}static addCreatureTypeModifiers(e,t,a,s){let i=me.detectCreatureType(e),n=["spell","ceremony","liturgy","ritual"].includes(t.type);for(let r of i){let o=r.damageModifier(t);if(n)for(let c of o)c.armorPen=r.spellResistanceModifier(e);a.push(...o)}a.push(...this.creatureBonusDamage(e,s)),me.addVulnerabilitiesToSource(e,t,a)}static addVulnerabilitiesToSource(e,t,a){let s=getProperty(e,"system.vulnerabilities");s&&["meleeweapon","rangeweapon"].includes(t.type)&&getProperty(s,"combatskill").reduce((n,r)=>{if(r.target==t.system.combatskill.value){let c=(/\*/.test(r.value)?Number(r.value.replace("*",""))>1:Number(r.value)>0)?"WEAPON.vulnerableTo":"WEAPON.resistantTo";a.push(...me.buildDamageMod(`${game.i18n.format(c,{name:t.system.combatskill.value})} (${r.source})`,r.value))}},a)}ignoredCondition(e){return!1}damageModifier(e){return[]}static creatureBonusDamage(e,t){let a=[],s=e.type=="creature"?e.system.creatureClass.value:e.system.details.species.value,i=getProperty(t,"system.creatureBonus");for(let n of i)s.indexOf(n.target)>=0&&a.push(...this.buildDamageMod(n.source,n.value,!0));return a}spellImmunity(e){return this.spellImmunities.some(t=>e.includes(t))}spellArmorModifier(e){return 0}poisonImmunity(){return this.poisonImmunity}diseaseImmunity(){return this.diseaseImmunity}spellResistanceModifier(e){return 0}static buildDamageMod(e,t,a=!0){return[{name:e,value:t,selected:a,type:"dmg",source:game.i18n.localize("target")}]}weaponAttributes(e){return getProperty(e,"system.effect.attributes")||""}getTypeByClass(e){return Object.keys(me.creatureData.types).find(t=>me.creatureData.types[t]===e)}isAttackItem(e){return["meleeweapon","trait","rangeweapon"].includes(e.type)&&Vi(this.weaponAttributes(e))}attributesRegex(e){let t=this.weaponAttributes(e);return new RegExp(`(${t.split(",").map(a=>f.escapeRegex(a.split("(")[0].trim())).join("|")})`,"i")}},I=me;u(I,"CreatureType"),L(I,"creatureData"),L(I,"magical"),L(I,"clerical");var bt=class extends I{damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);for(let a of I.creatureData.godOfLife){let s=`${I.clerical} (${a})`;if(t.test(s))return I.buildDamageMod(s,"*2")}}return super.damageModifier(e)}};u(bt,"VulnerableToLifeGods");var la=class extends bt{};u(la,"ChimeraType");var ca=class extends I{constructor(e){super(e),this.spellImmunities=["Influence","Transformation"].map(t=>game.i18n.localize(`Features.${t}`))}damageModifier(e){return this.isAttackItem(e)&&this.attributesRegex(e).test(I.clerical)?I.buildDamageMod(I.clerical,"*2"):super.damageModifier(e)}};u(ca,"DaimonidType");var da=class extends I{};u(da,"DragonType");var ma=class extends I{constructor(e){super(e),this.spellImmunities=["Influence","Transformation","Healing","Illusion"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);if(t.test(I.clerical))return I.buildDamageMod(`${I.clerical} (${I.creatureData.opposingGod})`,"*2",!1);if(t.test(I.magical))return super.damageModifier(e)}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return super.damageModifier(e);return I.buildDamageMod(this.getTypeByClass("DemonType"),"*0.5")}spellArmorModifier(e){return Number(e.system.status.soulpower.max)}spellResistanceModifier(e){return Number(e.system.status.soulpower.max)}ignoredCondition(e){return!0}};u(ma,"DemonType");var ua=class extends I{constructor(e){super(e),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){if(this.attributesRegex(e).test(I.magical))return super.damageModifier(e)}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return I.buildDamageMod(this.getTypeByClass("ElementalType"),"*1");return I.buildDamageMod(this.getTypeByClass("ElementalType"),"*0.5")}spellArmorModifier(e){return Number(e.system.status.soulpower.max)}spellResistanceModifier(e){return Number(e.system.status.soulpower.max)}ignoredCondition(e){return!0}};u(ua,"ElementalType");var pa=class extends I{constructor(e){super(e),this.spellImmunities=["Illusion"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}};u(pa,"FairyType");var ga=class extends I{constructor(e){super(e),this.spellImmunities=["Illusion","Healing","Telekinesis","Transformation"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);for(let a of I.creatureData.godOfDeath){let s=`${I.clerical} (${a})`;if(t.test(s))return[]}if(t=this.attributesRegex(e),t.test(I.clerical))return I.buildDamageMod(I.clerical,"*0.5");if(t.test(I.magical))return I.buildDamageMod(I.magical,"*0.5")}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return I.buildDamageMod(I.magical,"*0.5");return I.buildDamageMod(this.getTypeByClass("GhostType"),"*0")}ignoredCondition(e){return!["feared","inpain","confused"].includes(e)}};u(ga,"GhostType");var fa=class extends bt{constructor(e){super(e),this.spellImmunities=["Transformation"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}ignoredCondition(e){return!["confused","paralysed"].includes(e)}};u(fa,"GolemType");var ha=class extends bt{constructor(e){super(e),this.spellImmunities=["Healing"].map(t=>game.i18n.localize(`Features.${t}`))}ignoredCondition(e){return!["inpain","encumbered","stunned","feared","paralysed","confused"].includes(e)}};u(ha,"HomunculiType");var ya=class extends I{};u(ya,"IntelligentCreatureType");var ba=class extends I{};u(ba,"PlantType");var ka=class extends I{};u(ka,"AnimalType");var wa=class extends I{constructor(e){super(e),this.spellImmunities=["Influence","Healing","Illusion"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}damageModifier(e){if(this.isAttackItem(e)){let t=this.attributesRegex(e);for(let a of I.creatureData.godOfDeath){let s=`${I.clerical} (${a})`;if(t.test(s))return I.buildDamageMod(s,"*2")}}return super.damageModifier(e)}ignoredCondition(e){return!["paralysed"].includes(e)}};u(wa,"UndeadType");var va=class extends I{};u(va,"SupernaturalType");var Ta=class extends I{constructor(e){super(e),this.spellImmunities=["Transformation"].map(t=>game.i18n.localize(`Features.${t}`)),this.poisonImmunity=!0,this.diseaseImmunity=!0}ignoredCondition(e){return!["stunned","feared","paralysed","confused"].includes(e)}};u(Ta,"MagicalConstructType");var Sa=class extends I{damageModifier(e){if(this.isAttackItem(e)){if(this.attributesRegex(e).test(I.silverPlated))return I.buildDamageMod(this.getTypeByClass("WerCreatureType"),"*2")}else if(["spell","ceremony","liturgy","ritual"].includes(e.type))return super.damageModifier(e);return I.buildDamageMod(this.getTypeByClass("WerCreatureType"),"*0.5")}};u(Sa,"WerCreatureType");var Ca=class extends I{damageModifier(e){return["spell","ceremony","liturgy","ritual"].includes(e.type)?super.damageModifier(e):I.buildDamageMod(this.getTypeByClass("VampireType"),"*0.5")}};u(Ca,"VampireType");var E=class{static bindButtons(e){e.find(".chat-condition").each(function(t,a){a.setAttribute("draggable",!0),a.addEventListener("dragstart",s=>{let i={data:{type:"condition",payload:{id:s.currentTarget.dataset.id}}};s.dataTransfer.setData("text/plain",JSON.stringify(i))})}),e.on("click",".chat-condition",t=>ae.postStatus(t.currentTarget.dataset.id))}static createCustomEffect(e,t="",a){a=a||game.i18n.localize("CONDITION.custom"),t==""&&(t=a),e.addCondition({name:a,icon:"icons/svg/aura.svg",origin:e.uuid,flags:{dsa5:{description:t}}})}static prepareActiveEffects(e,t){let a=duplicate(CONFIG.statusEffects),s=[];t.conditions=[],t.transferedConditions=[];let i;e.documentName=="Item"?i=e.effects:(i=Array.from(e.allApplicableEffects()),game.user.isGM||(i=i.filter(r=>!r.getFlag("dsa5","hidePlayers"))));for(let r of i){let o=r.toObject();o.boolean=r.getFlag("dsa5","value")==null;let c=[...r.statuses][0];c&&(o.value=r.getFlag("dsa5","value"),o.editable=r.getFlag("dsa5","max"),o.descriptor=c,o.manual=r.getFlag("dsa5","manual"),s.push(c)),e.documentName=="Item"||r.parent?.documentName!="Item"&&!r.notApplicable?t.conditions.push(o):r.notApplicable||(o.uuid=r.uuid,o.parent={uuid:r.parent?.uuid,name:r.parent?.name},t.transferedConditions.push(o))}t.manualConditions=a.filter(r=>!s.includes(r.id));let n=[];for(let r of Object.keys(e.system?.condition||{}))if(e.system.condition[r]){let o=b.statusEffects.find(c=>c.id==r);o&&n.push({icon:o.icon,id:r,name:game.i18n.localize(o.name),value:e.system.condition[r]})}t.cumulativeConditions=n}static async addCondition(e,t,a=1,s=!1,i=!0){if(!e.isOwner)return"Not owned";if(e.compendium)return"Can not add in compendium";if(s&&a<1)return this.removeCondition(e,t,a,i,s);if(typeof t=="string"&&(t=duplicate(CONFIG.statusEffects.find(r=>r.id==t))),!t)return"No Effect Found";let n=this.hasCondition(e,t.id);return n&&n.flags.dsa5.value==null?n:n?await E.updateEffect(e,n,a,s,i,t):await E.createEffect(e,t,a,i)}static hasCondition(e,t){return e!=null&&t&&e.effects?e.effects.find(a=>a.statuses.has(t)):!1}static async removeCondition(e,t,a=1,s=!0,i=!1){if(!e.isOwner)return"Not owned";if(typeof t=="string"&&(t=duplicate(CONFIG.statusEffects.find(r=>r.id==t))),!t)return"No Effect Found";let n=this.hasCondition(e,t.id);if(n&&n.flags.dsa5.value==null)return e.token&&(e=e.token.actor),await e.deleteEmbeddedDocuments("ActiveEffect",[n.id]);if(n)return await E.removeEffect(e,n,a,i,s)}static immuneToEffect(e,t,a=!0){if(!t.id||!hasProperty(t,"flags.dsa5.max"))return;let s=getProperty(e,"system.immunities")||[],i;if(s.includes(t.id)&&(i={name:e.name,condition:game.i18n.localize(`CONDITION.${t.id}`)}),!i&&e.documentName=="Actor"){let r=I.detectCreatureType(e);for(let o of r)if(o.ignoredCondition(t.id)){i={name:`${e.name} (${o.getName()})`,condition:game.i18n.localize(`CONDITION.${t.id}`)};break}}if(!i||!(ui.notifications&&!a))return;let n=game.i18n.format("DSAError.conditionInvalidToCreature",{name:i.name,condition:i.condition});ui.notifications.warn(n)}static resistantToEffect(e,t){let a=[...t.statuses][0];return a?(getProperty(e,"system.resistances.effects")||[]).reduce((i,n)=>(n.target==a&&(i+=Number(n.value)),i),0):0}static async createEffect(e,t,a,s){t.name=game.i18n.localize(t.name),this.immuneToEffect(e,t,!1),s?(t.flags.dsa5.auto=Math.min(t.flags.dsa5.max,a),t.flags.dsa5.manual=0):(t.flags.dsa5.manual=Math.min(t.flags.dsa5.max,a),t.flags.dsa5.auto=0),t.flags.dsa5.value=Math.min(4,t.flags.dsa5.manual+t.flags.dsa5.auto),t.id&&(t.statuses=[t.id]),t.id=="dead"&&(t["flags.core.overlay"]=!0);let i=duplicate(t);(game.dsa5.config.statusEffectClasses[t.id]||E).levelDependentEffects(t,i);let n=await e.createEmbeddedDocuments("ActiveEffect",[i]);return delete t.id,n}static async removeEffect(e,t,a,s,i){let n=i?s?a:Math.max(0,t.flags.dsa5.auto-a):t.flags.dsa5.auto,r=i?t.flags.dsa5.manual:s?a:t.flags.dsa5.manual-a,o={flags:{dsa5:{auto:n,manual:r,value:Math.max(0,Math.min(t.flags.dsa5.max,r+n))}}};return o.flags.dsa5.auto<1&&o.flags.dsa5.manual==0?await e.deleteEmbeddedDocuments("ActiveEffect",[t.id]):((game.dsa5.config.statusEffectClasses[[...t.statuses][0]]||E).levelDependentEffects(t,o),await t.update(o))}static async levelDependentEffects(e,t){}static async updateEffect(e,t,a,s,i,n=void 0){this.immuneToEffect(e,t,!0);let r,o,c;return i?(o=Math.min(t.flags.dsa5.max,s?a:t.flags.dsa5.auto+a),r=o-t.flags.dsa5.auto,c={flags:{dsa5:{auto:o,manual:t.flags.dsa5.manual}}}):(o=s?a:t.flags.dsa5.manual+a,r=o-t.flags.dsa5.manual,c={flags:{dsa5:{manual:o,auto:t.flags.dsa5.auto}}}),r==0||(c.flags.dsa5.value=Math.max(0,Math.min(t.flags.dsa5.max,c.flags.dsa5.manual+c.flags.dsa5.auto)),n.duration&&(c.duration=n.duration,c.duration.startTime=game.time.worldTime),(game.dsa5.config.statusEffectClasses[[...t.statuses][0]]||E).levelDependentEffects(t,c),await t.update(c)),t}static calculateRollModifier(e,t,a,s={}){return e.flags.dsa5.value==null||a.type=="regenerate"?0:E.clampedCondition(t,e)}static clampedCondition(e,t){let a=[...t.statuses][0];if(!a)return 0;let s=Number(t.flags.dsa5.max),i=Math.clamped(e.system.condition[a]||0,0,s)*-1,n=this.resistantToEffect(e,t);return Math.clamped(i+n,-1*s,0)}static ModifierIsSelected(e,t={},a){return t.mode!="damage"}static getDamageBonus(){return 0}static getRollModifiers(e,t,a={}){let s=game.i18n.localize("status")+"/"+game.i18n.localize("condition"),i=[],n=[];for(let c of e.effects){if(c.disabled)continue;let m=[...c.statuses][0],d=game.dsa5.config.statusEffectClasses[m]||E,p=d.calculateRollModifier(c,e,t,a);m&&n.push(m),p!=0&&i.push({name:c.name,value:p,selected:d.ModifierIsSelected(t,a,e),source:s})}for(let[c,m]of Object.entries(e.system.condition))if(m&&!n.includes(c)){let d=duplicate(b.statusEffects.find(y=>y.id==c));if(!d)continue;let p=game.dsa5.config.statusEffectClasses[c]||E;d.flags.dsa5.value=m,d.statuses=[c];let g=p.calculateRollModifier(d,e,t,a);g!=0&&i.push({name:d.name,value:g,selected:p.ModifierIsSelected(t,a,e),source:s})}let r=e.hasPlayerOwner,o=game.settings.get("dsa5","masterSettings").globalMods||{};for(let c of Object.keys(o)){let m=expandObject(o[c]);if(!(!m.enabled||!m.target||!m.target[t.type])){if(r){if(!m.victim?.player)continue}else if(!m.victim?.npc)continue;i.push({name:m.name,value:m.value,selected:!0,source:game.i18n.localize("MASTER.globalMods")})}}return i}};u(E,"DSA5StatusEffects");var Aa=class extends E{static ModifierIsSelected(e,t={},a){let s=e.type=="skill"&&e.system.burden.value=="yes",i=["rangeweapon"].includes(e.type)&&t.mode!="damage"&&game.settings.get("dsa5","encumbranceForRange"),n=!["skill","spell","ritual","ceremony","liturgy","rangeweapon"].includes(e.type)&&t.mode!="damage";return s||n||i}static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"||a.type=="skill"&&a.system.burden.value=="no"?0:super.calculateRollModifier(e,t,a,s)}};u(Aa,"EncumberedEffect");var Da=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="dodge"?-2:s.mode?s.mode=="attack"?-4:-2:0}};u(Da,"ProneEffect");var Ma=class extends E{static calculateRollModifier(e,t,a,s={}){let i=new RegExp(`${game.i18n.localize("combatskill")} `,"gi"),n=t.system.happyTalents.value.split(/;|,/).map(r=>r.replace(i,"").trim());return n.includes(a.name)&&["skill","combatskill"].includes(a.type)||["rangeweapon","meleeweapon"].includes(a.type)&&n.includes(a.system.combatskill.value)||["ceremony","liturgy"].includes(a.type)?this.clampedCondition(t,e)*-1-1:["ritual","spell","skill","combatskill"].includes(a.type)?this.clampedCondition(t,e):(a.type=="regenerate",0)}};u(Ma,"RaptureEffect");var Ia=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.perception")?-3:0}};u(Ia,"DeafEffect");var Ea=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"?a.name==game.i18n.localize("LocalizedIDs.featOfStrength")?2:0:s.mode=="attack"?4:0}};u(Ea,"BloodrushEffect");var $a=class extends E{static ModifierIsSelected(e,t={},a){return a.effects.find(s=>Array.from(s.statuses).includes("bloodrush"))==null}};u($a,"PainEffect");var Oa=class extends E{static calculateRollModifier(e,t,a,s={}){if(a.type=="regenerate")return 0;switch(Number(this.clampedCondition(t,e))){case-2:let i=new RegExp(`${game.i18n.localize("combatskill")} `,"gi"),n=t.system.happyTalents.value.split(/;|,/).map(r=>r.replace(i,"").trim());if(n.includes(a.name)&&["skill","combatskill"].includes(a.type)||["rangeweapon","meleeweapon"].includes(a.type)&&n.includes(a.system.combatskill.value)||["ceremony","liturgy"].includes(a.type))return-2;case-3:return-3}return 0}};u(Oa,"TranceEffect");var za=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.gambling")?Math.clamped(this.clampedCondition(t,e),-3,0):0}};u(za,"DrunkenEffect");var xa=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?0:a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.bodyControl")?Math.clamped(this.clampedCondition(t,e)+1,-2,0):0}};u(xa,"BurningEffect");var Pa=class extends E{static calculateRollModifier(e,t,a,s={}){return 0}};u(Pa,"ArousalEffect");var Na=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.willpower")?(this.clampedCondition(t,e)+1)*2:a.type=="regenerate"?this.clampedCondition(t,e):0}};u(Na,"SikaryanlossEffect");var La=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="skill"&&a.name==game.i18n.localize("LocalizedIDs.willpower")?Math.clamped(this.clampedCondition(t,e),-3,0):0}};u(La,"DesireEffect");var Ra=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="regenerate"?this.clampedCondition(t,e)*-1:0}};u(Ra,"TheriakEffect");var _a=class extends E{static calculateRollModifier(e,t,a,s={}){return a.type=="skill"&&a.system.group.value=="body"?Math.clamped(this.clampedCondition(t,e)-1,3,0)*-1:0}};u(_a,"SunkenEffect");var Fa=class extends E{static calculateRollModifier(e,t,a,s={}){let i=Math.clamped(e.flags.dsa5.value,0,4);return a.type=="regenerate"?Math.pow(2,i-1)*-1:0}};u(Fa,"HungerEffect");var Ha=class extends E{static calculateRollModifier(e,t,a,s={}){return 0}static levelDependentEffects(e,t){t.changes={1:[],2:[{key:"system.condition.stunned",mode:2,value:1/2}],3:[{key:"system.condition.stunned",mode:2,value:2/3}],4:[{key:"system.condition.stunned",mode:2,value:3/4}]}[t.flags.dsa5.value]}};u(Ha,"ThirstEffect");var ja=class extends E{static levelDependentEffects(e,t){t.changes={1:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:1}],2:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:1/2}],3:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:2/3}],4:[{key:"system.condition.stunned",mode:2,value:1},{key:"system.condition.confused",mode:2,value:1/2}]}[t.flags.dsa5.value]}};u(ja,"HeatEffect");var Ga=class extends E{static levelDependentEffects(e,t){t.changes={1:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:1}],2:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:1/2}],3:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:2/3}],4:[{key:"system.condition.confused",mode:2,value:1},{key:"system.condition.paralysed",mode:2,value:1/2}]}[t.flags.dsa5.value]}};u(Ga,"ColdEffect");var Ba=class extends E{static calculateRollModifier(e,t,a,s={}){return 0}};u(Ba,"NoModifierEffect");b.statusEffectClasses={inpain:$a,heat:ja,cold:Ga,encumbered:Aa,stunned:E,raptured:Ma,feared:E,paralysed:E,confused:E,prone:Da,deaf:Ia,bloodrush:Ea,trance:Oa,drunken:za,arousal:Pa,burning:xa,sikaryanloss:Na,desire:La,theriak:Ra,services:Ba,sunken:_a,hunger:Fa,thirst:Ha};var O=class extends te{static setupFunctions(){}static async vantageAdded(e,t){game.dsa5.config.addvantageRules[t.name]&&game.dsa5.config.addvantageRules[t.name](e,t)}static async vantageRemoved(e,t,a=!0){game.dsa5.config.removevantageRules[t.name]&&game.dsa5.config.removevantageRules[t.name](e,t);let s=O.calcAPCostSum(t);s=await O.removeSingularVantages(e,t,s)*-1,await e._updateAPs(s,{},{render:a}),await _.track(e,{type:"item",item:t,state:-1},s)}static async _vantageReturnFunction(e,t,a,s){if(t==null)return;if(t=duplicate(t),/,/.test(t.system.APValue.value)){let r=t.name.replace(" ()","");t.system.APValue.value=t.system.APValue.value.split(",")[e.items.filter(o=>o.type==t.type&&o.name.includes(r)).length].trim()}s!=null&&(O.simpleAdoption(t,s,t.name,b.vantagesNeedingAdaption),t.name=`${t.name.replace(" ()","")} (${s.name})`,s.system&&(t.system.APValue.value=t.system.APValue.value.split("/")[s.system.StF.value.charCodeAt(0)-65].trim()));let i=e.items.find(r=>r.type==a&&r.name==t.name),n;if(i){let r=duplicate(i);n=Number(/;/.test(r.system.APValue.value)?r.system.APValue.value.split(";").map(o=>Number(o.trim()))[r.system.step.value]:r.system.APValue.value),r.system.step.value+1<=r.system.max.value&&await e.checkEnoughXP(n)&&(r.system.step.value+=1,n=this.addSingularVantages(e,r,n),await e._updateAPs(n,{},{render:!1}),await e.updateEmbeddedDocuments("Item",[r]),await O.vantageAdded(e,r),await _.track(e,{type:"item",item:i,previous:r.system.step.value-1,next:r.system.step.value},n))}else if(await e.checkEnoughXP(n=Number(t.system.APValue.value.split(";").map(r=>r.trim())[0]))){await O.vantageAdded(e,t),n=this.addSingularVantages(e,t,n),await e._updateAPs(n,{},{render:!1});let r=(await e.createEmbeddedDocuments("Item",[t]))[0];await _.track(e,{type:"item",item:r,state:1},n)}}static async needsAdoption(e,t,a){if(b.vantagesNeedingAdaption[t.name]){let s,i;if(b.vantagesNeedingAdaption[t.name].items=="text")s=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-string-dialog.html",{original:t}),i=u(function(n){let r={name:n.find('[name="entryselection"]').val()};O._vantageReturnFunction(e,t,a,r)},"callback");else{let n=e.items.filter(r=>b.vantagesNeedingAdaption[t.name].items.includes(r.type));s=await renderTemplate("systems/dsa5/templates/dialog/requires-adoption-dialog.html",{items:n,original:t}),i=u(function(r){let o=n.find(c=>c.name==r.find('[name="entryselection"]').val());O._vantageReturnFunction(e,t,a,o)},"callback")}await new Be({title:game.i18n.localize("DIALOG.ItemRequiresAdoption"),content:s,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:i},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}else O._vantageReturnFunction(e,t,a,null)}static addSingularVantages(e,t,a){let s=u((i,n,r)=>i.type=="disadvantage"&&n.test(i.name),"filter");return O._calculateSingularVantages(t,e,a,s)}static removeSingularVantages(e,t,a){let s=u((i,n,r)=>i.type=="disadvantage"&&n.test(i.name)&&i.name!=r.name,"filter");return O._calculateSingularVantages(t,e,a,s)}static _calculateSingularVantages(e,t,a,s,i=(n,r)=>Math.min(0,n-r)){if(e.type!="disadvantage")return a;for(let n of["principles","obligations"]){let r=new RegExp(`^${game.i18n.localize("LocalizedIDs."+n)} \\(`);if(r.test(e.name)){let o=t.items.filter(d=>s(d,r,e)),c=Math.min(0,...o.map(d=>O.calcAPCostSum(d))),m=O.calcAPCostSum(e);a=i(m,c)}}return a}static reduceSingularVantages(e,t,a){let s=u((n,r,o)=>n.type=="disadvantage"&&r.test(n.name)&&n.name!=o.name,"filter"),i=u((n,r)=>n0,a=a||s.data.dim>0,t)break;continue}let i=J.rangeFinder(e,s.object).distanceSum,n=s.object.document.config||s.object.document.light,r=n.bright>=i,o=n.dim>=i;if(!(!r&&!o)&&((s.data.walls===!1||s.shape.contains(e.center.x,e.center.y))&&(t=r||t,a=o||a),t))break}return{bright:t,dim:a}}static get isEnabled(){let e=canvas?.scene?.getFlag("dsa5","enableDPS");return e?e=="2":game.settings.get("dsa5","enableDPS")}static lightLevel(e,t){if(canvas.scene&&game.settings.get("dsa5","sightAutomationEnabled")){let a=0,s=canvas.scene?.darkness||0,i=game.settings.get("dsa5","sightOptions").split("|").map(r=>Number(r));for(;i[a]<=s;)a+=1;if(e){let r=O.vantageStep(e,game.i18n.localize("LocalizedIDs.darksight")),o=Number(getProperty(e,"system.sightModifier.value"))||0,c=Number(getProperty(e,"system.sightModifier.maxLevel"))||3,m=Array.from(game.user.targets);if(m.length){m=m[0];let d=J.inLight(m),p=0;d.bright?p=-2:d.dim&&(p=-1),a=Math.max(a+p,0)}a<=c&&a>0&&(r>1?a=0:a=Math.clamped(a+o-r,0,4))}let n=t.find(`[name="vision"] option:nth-child(${a+1})`);n.length&&(n[0].selected=!0)}}static distanceModifier(e,t,a){if(!J.isEnabled||!e)return 1;let s={};for(let i of game.user.targets){let n=J.rangeFinder(e,i);(s.distanceSum||0)Number(o)*i),r=0;for(;r<2&&n[r]{let a=getProperty(l.object,"flags.dsa5.enableDPS"),s=`
    -
    `;e.find(".dpsSelector").remove(),e.find('.tab[data-tab="grid"]').append(s)});var ot=class extends Dialog{static async getDialog(e){let t=Array.from(game.user.targets).map(i=>i.id),a=[],s=canvas.scene?canvas.scene.tokens.get(e.token)?.object:void 0;return game.combat&&game.combat.combatants.forEach(i=>{if(!!i.visible){if(i.isSelected=t.includes(i.token.id),s&&i.token){let r=canvas.scene.tokens.get(i.token.id).object;i.distance=J.rangeFinder(s,r),i.distance.distanceSum=Number(i.distance.distanceSum.toFixed(1))}a.push(i)}}),new ot({title:game.i18n.localize("DIALOG.addTarget"),content:await renderTemplate("systems/dsa5/templates/dialog/addTarget-dialog.html",{selectables:a}),default:"yes",buttons:{}})}activateListeners(e){super.activateListeners(e);let t=e.find(".combatant");t.click(a=>this.setTargets(a)),t.hover(this._onCombatantHoverIn.bind(this),this._onCombatantHoverOut.bind(this)),t.mousedown(a=>this._onRightClick(a))}_onCombatantHoverOut(e){this._getCombatApp()._onCombatantHoverOut(e)}_onCombatantHoverIn(e){this._getCombatApp()._onCombatantHoverIn(e)}_onRightClick(e){if(e.button==2){let t=game.combat.combatants.get(e.currentTarget.dataset.combatantId);if(t.token)return canvas.animatePan({x:t.token.x,y:t.token.y})}}_getCombatApp(){return game.combats.apps[0]}async setTargets(e){let t=e.originalEvent.shiftKey;t||$(e.currentTarget).closest(".directory").find(".combatant").removeClass("selectedTarget"),$(e.currentTarget).addClass("selectedTarget");let a=e.currentTarget.dataset.combatantId;game.combat.combatants.get(a).token.object.setTarget(!0,{user:game.user,releaseOthers:!t,groupSelection:!0})}};u(ot,"AddTargetDialog");var De=class extends Dialog{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5Decent"])}),e}static async getDialog(){let e=game.users.filter(t=>t.active&&!t.isGM);return new De({title:game.i18n.localize("DIALOG.setTargetToUser"),content:await renderTemplate("systems/dsa5/templates/dialog/selectForUserDialog.html",{users:e}),default:"yes",buttons:{}})}static registerButtons(){Hooks.on("getSceneControlButtons",e=>{if(!game.user.isGM)return;let t={name:"targetUser",title:game.i18n.localize("CONTROLS.targetForUser"),icon:"fa fa-bullseye",button:!0,onClick:async()=>{(await De.getDialog()).render(!0)}};e[0].tools.splice(2,0,t)})}activateListeners(e){super.activateListeners(e),e.find(".combatant").click(t=>this.setTargetToUser(t))}setTargetToUser(e){let t=Array.from(game.user.targets).map(i=>i.id),a=e.currentTarget.dataset.userId;game.users.get(a).updateTokenTargets(t),game.socket.emit("userActivity",a,{targets:t}),this.close()}};u(De,"SelectUserDialog");var lt=class extends Dialog{static async getDialog(e){let t=game.users.filter(a=>a.active&&!a.isGM);new lt({title:game.i18n.localize("SHEET.PostItem"),content:await renderTemplate("systems/dsa5/templates/dialog/usermultipickdialog.html",{users:t}),default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:a=>{this.postContent(a,e)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}static async postContent(e,t){let a=f.chatDataSetup(t);if(!e.find("#sel_all").is(":checked")){let s=[];e.find(".usersel:checked").each(function(){s.push($(this).val())}),a.whisper=s}ChatMessage.create(a)}activateListeners(e){super.activateListeners(e),e.find('[name="sel_all"]').change(t=>{e.find(".usersel").prop("disabled",t.currentTarget.checked).prop("checked",t.currentTarget.checked)})}};u(lt,"UserMultipickDialog");var ei=class extends Dialog{recallSettings(e,t,a,s){return this.recallData=game.dsa5.memory.recall(e,t,a),this.dialogData={mode:a,speaker:e,source:t,renderData:s},this}async _render(e,t){await super._render(e,t),this.prepareFormRecall($(this._element))}setRollButtonWarning(){return this.dialogData.mode=="attack"?` ${game.i18n.localize("DIALOG.noTarget")}`:""}setMultipleTargetsWarning(){return this.dialogData.mode=="attack"?` ${game.i18n.localize("DIALOG.multipleTarget")}`:""}renderRollValueDie(){if(this.dialogData.rollValue&&this.dialogData.mode!="damage"){let e=this.dialogData.mode=="attack"||this.dialogData.counterAttack?"die-mu":"die-in",t=this.dialogData.modifier||0;return`${Math.clamped(this.dialogData.rollValue+t,1,20)}`}else return""}async updateRollButton(e){let t=this.renderRollValueDie()+game.i18n.localize("Roll");e.length>0?e.length>1&&(t+=this.setMultipleTargetsWarning()):t+=this.setRollButtonWarning(),$(this._element).find(".dialog-buttons .rollButton").html(t)}async updateTargets(e,t){let a=await renderTemplate("systems/dsa5/templates/dialog/parts/targets.html",{targets:t});e.find(".targets").html(a),this.updateRollButton(t)}removeTarget(e){let t=e.currentTarget.dataset.id;$(e.currentTarget).remove();let a=[];game.user.targets.forEach(s=>{t!=s.id&&a.push(s.id)}),game.user.updateTokenTargets(a)}readTargets(){let e=[];return game.user.targets.forEach(t=>{t.actor&&e.push({name:t.actor.name,img:t.actor.img,id:t.id})}),e}compareTargets(e,t){let a=this.readTargets();return JSON.stringify(t)!=JSON.stringify(a)&&(t=a,this.updateTargets(e,t)),t}activateListeners(e){super.activateListeners(e),e.find(".quantity-click").mousedown(t=>P.quantityClick(t)),e.find(".modifiers option").mousedown(t=>(t.preventDefault(),$(t.currentTarget).prop("selected",!$(t.currentTarget).prop("selected")),!1)),e.on("click",".rollTarget",t=>this.removeTarget(t)),e.on("click",".addTarget",t=>this.addTarget(t))}async addTarget(e){(await ot.getDialog(this.dialogData.speaker)).render(!0)}prepareFormRecall(e){if(this.recallData)for(let t in this.recallData)if(t=="specAbs")for(let a of this.recallData[t]){let s=e.find(`.specAbs[data-id="${a.id}"]`);s.addClass("active").attr("data-step",a.step),s.find(".step").text(ei.roman[a.step])}else{let a=e.find(`[name="${t}"]`);if(Array.isArray(this.recallData[t])){let s=a.find("option");for(let i of s){let r=this.recallData[t].find(n=>n.name==$(i).text().trim());r&&(i.selected=r.selected)}}else a.attr("type")=="checkbox"?a[0].checked=this.recallData[t]:a.val(this.recallData[t])}}},ie=ei;u(ie,"DialogShared"),L(ie,"roman",[""," I"," II"," III"," IV"," V"," VI"," VII"," VIII"," IX"," X"]);var qe=class extends ie{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,resizable:!0}),e}prepareFormRecall(e){super.prepareFormRecall(e),e.find(".spellModifier").trigger("change")}static getRollButtons(e,t,a,s){let i=ee.getRollButtons(e,t,a,s);if(["spell","liturgy"].includes(e.source.type)){let r=Number(e.source.system.castingTime.value),n=e.source.system.castingTime.progress,o=e.source.system.castingTime.modified;if(r&&e.extra.speaker.token!="emptyActor"){let c=o>0?` (${n}/${o})`:"";mergeObject(i,{reloadButton:{label:`${game.i18n.localize("SPELL.reload")}${c}`,callback:async m=>{let d=await f.getSpeaker(e.extra.speaker),p={_id:e.source._id,"system.castingTime.progress":n+1};o==0&&(o=Number(m.find(".castingTime").text())-1,p["system.castingTime.modified"]=o),await d.updateEmbeddedDocuments("Item",[p]);let g=game.i18n.format("SPELL.isReloading",{actor:d.token?.name||d.prototypeToken.name,item:e.source.name,status:`${n+1}/${o}`});await ChatMessage.create(f.chatDataSetup(g))}}})}}return i}async applyTransformations(e,t){let a=t.find('[name="situationalModifiers"]');a.find('option[data-extension="1"]').remove();let s=[],i=Object.keys(qe.rollModifiers).map(n=>`${n}.mod`);this.dialogData.renderData.rollModifiersPrepared=duplicate(this.dialogData.renderData.rollModifiers);for(let n of t.find(".specAbs.active")){let o=fromUuidSync(n.dataset.uuid);if(!!o)for(let c of o.effects)for(let m of c.changes)if(qe.rollChanges.includes(m.key)){let d=o.name.split(" - "),p=game.i18n.localize(`MODS.${m.key}`);d=`${d[1]||d[0]}`;let g=`${p}: ${m.value}
    ${game.i18n.localize("spellextension")}: ${d}`;s.push(``)}else m.key=="macro.transform"?await f.callItemTransformationMacro(m.value,e,c):i.includes(m.key)?c.apply(this.dialogData.renderData.rollModifiersPrepared,m):c.apply(e,m)}let r=this.dialogData.renderData.rollModifiersPrepared.extensionModifier.mod;if(r){let n=game.i18n.localize("ABBR.modifiers"),o=game.i18n.localize("spellextension"),c=`${n}: ${r}
    ${o}`;s.push(``)}a.append(s.join(""))}static setData(e,t){let a=duplicate(qe.rollModifiers),s=`${t}RollModifiers`;if(e.system[s])for(let i of Object.keys(e.system[s]))a[i].mod+=Number(e.system[s][i]?.mod??0);return a}async recalcSpellModifiers(e,t){let a=e,s=duplicate(this.dialogData.source);P.ensureNumber(s);let i=a.find(".castingTime"),r=a.find(".aspcost"),n=a.find(".reach"),o=a.find(".maintainCost"),c=a.find(".ritual").length>0;await this.applyTransformations(s,a);let m=a.find(".maxMods");if(a.find(".spellModifier:checked").length>Number(m.text())){t&&(t.currentTarget.checked=!1),m.addClass("emphasize"),setTimeout(function(){m.removeClass("emphasize")},600);return}for(let S of Object.keys(this.dialogData.renderData.rollModifiersPrepared)){let z=this.dialogData.renderData.rollModifiersPrepared[S].mod;e.find(`.${S}Label`).text(`(${z})`),e.find(`#${S}`).val(z)}let d=e.find(".canChangeCastingTime");s.system.canChangeCastingTime.value=="true"?d.is(":empty")&&(d.html(await renderTemplate("systems/dsa5/templates/dialog/parts/canChangeCastingTime.html",{rollModifiers:this.dialogData.renderData.rollModifiers})),this.setPosition({height:"auto"})):d.is(":empty")||(d.html(""),this.setPosition({height:"auto"}));let p=s.system.AsPCost.value,g=s.system.range.value,y=s.system.castingTime.value,h=p,w=s.system.maintainCost.value;a.find(".variableBaseCost")[s.system.variableBaseCost=="true"?"show":"hide"]();let x=0;a.find(".spellModifier[data-cost]:checked").each(function(S,z){if(h=h*(z.value<0?.5:2),w!=""&&w!=null){let F=String(w).split(" ");F[0]=Math.max(Number(F[0])*(z.value<0?.5:2)),w=F.join(" ")}x+=Number(z.value)}),h<1?t&&(t.currentTarget.checked=!1):(r.text(h),o.text(w),r.attr("data-mod",x)),x=0,h=y,a.find(".spellModifier[data-castingTime]:checked").each(function(S,z){if(c){let F=qe.bigTimes.indexOf(Number(h));if(F!=null){let N=F+(z.value>0?1:-1);N=0?h=qe.bigTimes[N]:ui.notifications.error(game.i18n.localize("DSAError.CastingTimeLimit"))}else ui.notifications.error(game.i18n.localize("DSAError.TimeCannotBeParsed"))}else h=h*(z.value>0?2:.5);x+=Number(z.value)}),h<1?t&&(t.currentTarget.checked=!1):(i.text(h),i.attr("data-mod",x)),x=0;let v=game.i18n.localize("ReverseSpellRanges."+g);n.text(g),a.find(".spellModifier[data-reach]:checked").each(function(S,z){if(v=="self")z.checked=!1;else if(v=="touch")n.text("4 "+game.i18n.localize("step")),x+=Number(z.value);else{let F=g.split(" ");v=Number(F[0]),isNaN(v)?(t&&(t.currentTarget.checked=!1),ui.notifications.error(game.i18n.localize("DSAError.RangeCannotBeParsed"))):(n.text(v*2+" "+game.i18n.localize("step")),x+=Number(z.value))}}),n.attr("data-mod",x),e.find(".reloadButton").prop("disabled",Number(e.find(".castingTime").text())<2)}activateListeners(e){super.activateListeners(e),e.find(".reloadButton").prop("disabled",Number(e.find(".castingTime").text())<2),e.find(".specAbs").mousedown(s=>{$(s.currentTarget).toggleClass("active"),this.recalcSpellModifiers(e)}),e.find(".variableBaseCost").change(s=>{let i=$(s.currentTarget).parents(".skill-test"),r=i.find(".aspcost").attr("data-base"),n=$(s.currentTarget).val();i.find(".aspcost").attr("data-base",n),i.find(".aspcost").text(Number(i.find(".aspcost").text())*n/r)}),e.on("change",".spellModifier",s=>this.recalcSpellModifiers(e,s));let t=this.readTargets();t.length==0&&this.setRollButtonWarning();let a=this;this.checkTargets=setInterval(function(){t=a.compareTargets(e,t)},500)}},le=qe;u(le,"DSA5SpellDialog"),L(le,"rollChanges",["defenseMalus"]),L(le,"rollModifiers",{forceSpell:{mod:1},reduceCostSpell:{mod:-1},increaseRangeSpell:{mod:-1},increaseCastingTime:{mod:1},decreaseCastingTime:{mod:-1},removeGesture:{mod:-2},removeFormula:{mod:-2},extensionModifier:{mod:0}}),L(le,"bigTimes",[5,30,120,480,960,1920]);function Mi(l,e={}){f.moduleEnabled("autoanimations")&&console.warn("Animations for on use effects not enabled yet")}u(Mi,"automatedAnimation");async function ti(l,e,t,a,s,i={}){let r={};if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else{let o=await game.packs.get(l)?.getDocuments({name:e});if(!o||!o.length){for(let c of game.packs.filter(m=>m.documentName=="Macro"&&/\(internal\)/.test(m.metadata.label)))if(o=await c.getDocuments({name:e}),o.length)break}if(o.length){let c=Object.getPrototypeOf(async function(){}).constructor,m=new c("actor","item","qs","automatedAnimation","args",o[0].command);try{i.result=r;let d=mergeObject({automatedAnimation:Mi},this);await m.call(d,t,a,s,Mi,i)}catch(d){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(d),r.error=!0}}else ui.notifications.error(game.i18n.format("DSAError.macroNotFound",{name:e}))}return r}u(ti,"callMacro");Hooks.once("i18nInit",()=>{Q.effectDurationRegexes=[{regEx:new RegExp(game.i18n.localize("DSAREGEX.combatRounds"),"i"),seconds:5},{regEx:new RegExp(game.i18n.localize("DSAREGEX.minutes"),"i"),seconds:60},{regEx:new RegExp(game.i18n.localize("DSAREGEX.hours"),"i"),seconds:3600},{regEx:new RegExp(game.i18n.localize("DSAREGEX.days"),"i"),seconds:3600*24},{regEx:new RegExp(game.i18n.localize("DSAREGEX.weeks"),"i"),seconds:3600*24*7},{regEx:new RegExp(game.i18n.localize("DSAREGEX.months"),"i"),seconds:3600*24*30},{regEx:new RegExp(game.i18n.localize("DSAREGEX.years"),"i"),seconds:3600*24*350}]});var Q=class extends ActiveEffectConfig{static get defaultOptions(){return mergeObject(super.defaultOptions,{resizable:!0})}static async callMacro(e,t,a,s,i,r={}){return await ti(e,t,a,s,i,r)}static async onEffectRemove(e,t){let a=getProperty(t,"flags.dsa5.onRemove");if(a)if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else try{let s=Object.getPrototypeOf(async function(){}).constructor;await new s("effect","actor",a).call(this,t,e)}catch(s){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(s),console.warn(s.stack)}}async checkTimesUpInstalled(){let e=f.moduleEnabled("times-up");return!e&&game.user.isGM&&ui.notifications.warn(game.i18n.localize("DSAError.shouldTimesUp")),e}async _render(e=!1,t={}){await super._render(e,t);let a=0,s=getProperty(this.object,"parent.type"),i=["meleeweapon","rangeweapon"].includes(s)||s=="trait"&&["meleeAttack","rangeAttack"].includes(getProperty(this.object,"parent.system.traitType.value")),r={hasSpellEffects:i||["spell","liturgy","ritual","skill","ceremony","consumable","poison","disease","ammunition"].includes(s)||["specialability"].includes(s)&&getProperty(this.object,"parent.system.category.value")=="Combat",hasDamageTransformation:["ammunition"].includes(s),hasTriggerEffects:["specialability"].includes(s)},n=[];if((r.hasSpellEffects||r.hasDamageTransformation||r.hasTriggerEffects)&&n.push({name:"ActiveEffects.advancedFunctions.none",index:0}),r.hasSpellEffects)for(let p of["systemEffect","macro","creature"])n.push({name:`ActiveEffects.advancedFunctions.${p}`,index:a+=1});r.hasDamageTransformation&&n.push({name:"ActiveEffects.advancedFunctions.armorPostprocess",index:4},{name:"ActiveEffects.advancedFunctions.damagePostprocess",index:5}),r.hasTriggerEffects&&n.push({name:"ActiveEffects.advancedFunctions.postRoll",index:6},{name:"ActiveEffects.advancedFunctions.postOpposed",index:7});let o={systemEffects:this.getStatusEffects(),canEditMacros:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro")},c=[2,6,7],m=$(this._element);m.find(".tabs").append(`${game.i18n.localize("advanced")}`);let d=await renderTemplate("systems/dsa5/templates/status/advanced_effect.html",{effect:this.object,advancedFunctions:n,effectConfigs:r,macroIndexes:c,config:o,isWeapon:i});m.find('.tab[data-tab="effects"]').after($(d)),m.find(".advancedSelector").on("change",p=>{let g=this.object;g.flags.dsa5.advancedFunction=$(p.currentTarget).val(),renderTemplate("systems/dsa5/templates/status/advanced_functions.html",{effect:g,config:o,macroIndexes:c}).then(y=>{m.find(".advancedFunctions").html(y)})}),this.object.statuses.size&&game.i18n.has(this.object.description)&&m.find('[data-tab="details"] .editor').replaceWith(`

    ${game.i18n.localize(this.object.description)}

    `),this.checkTimesUpInstalled()}getStatusEffects(){return CONFIG.statusEffects.map(e=>({id:e.id,name:game.i18n.localize(e.name)})).sort((e,t)=>e.name.localeCompare(t.name))}static applyRollTransformation(e,t,a){let s="",i=t.origin;for(let r of i.effects)try{if(Number(getProperty(r,"flags.dsa5.advancedFunction"))==a)if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else try{let n=Object.getPrototypeOf(function(){}).constructor;new n("ef","callMacro","actor","msg","source",getProperty(r,"flags.dsa5.args3")).call(this,r,ti,e,s,i)}catch(n){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(n),console.warn(n.stack)}}catch(n){console.warn("Unable to apply advanced effect",n,r)}return t.origin=i,{msg:s,options:t}}static async applyAdvancedFunction(e,t,a,s,i,r=!0){let n="",o=[],c=!1,m=[],d=new Set;for(let p of t){p.origin&&delete p.origin;let g=Number(getProperty(p,"flags.dsa5.specStep"))||0;try{let y=Number(getProperty(p,"flags.dsa5.advancedFunction")),h=Math.min(s.qualityStep||0,6),w=getProperty(p,"flags.dsa5.resistRoll");if(w&&!r){let x=w.split(" "),v=`${x.pop()}`;o.push({skill:x.join(" "),mod:Math.round(Roll.safeEval(`${v}`.replace(/q(l|s)/i,h).replace("step",g)))||0,effect:p,target:e,token:e.token?e.token.id:void 0})}else if(c=!0,d.has(p.name)||d.add(p.name),p.changes&&p.changes.length>0&&m.push(p),y)switch(y){case 1:{let v=duplicate(CONFIG.statusEffects.find(z=>z.id==getProperty(p,"flags.dsa5.args0"))),S=`${getProperty(p,"flags.dsa5.args1")}`||"1";v.duration=p.duration,/,/.test(S)?S=Number(S.split(",")[h-1]):S=Number(S.replace(game.i18n.localize("CHARAbbrev.QS"),h)),await e.addCondition(v,S,!1,!1)}break;case 2:if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else try{let v=Object.getPrototypeOf(async function(){}).constructor;await new v("effect","actor","callMacro","msg","source","actor","sourceActor","testData","qs",getProperty(p,"flags.dsa5.args3")).call(this,p,e,ti,n,a,e,i,s,h)}catch(v){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(v),console.warn(v.stack)}break;case 3:let x=(getProperty(p,"flags.dsa5.args4")||"").split(",").map(v=>`@Compendium[${v.trim().replace(/(@Compendium\[|\])/)}]`).join(" ");n+=`

    ${game.i18n.localize("ActiveEffects.advancedFunctions.creature")}:

    ${x}

    `;break}}catch(y){console.warn("Unable to apply advanced effect"),console.warn(y),console.warn(p)}}return await e.createEmbeddedDocuments("ActiveEffect",m),{msg:n,resistRolls:o,effectApplied:c,effectNames:Array.from(d)}}static async resistEffect(e){let t=e.currentTarget.dataset,a={token:t.token,actor:t.actor,scene:canvas.id},s=f.getSpeaker(a);if(s){let i=s.items.find(r=>r.type=="skill"&&r.name==t.skill);s.setupSkill(i,{modifier:t.mod},t.token).then(async r=>{r.testData.opposable=!1,((await s.basicTest(r)).result.qualityStep||0)<1&&await this.applyEffect(t.message,t.mode,[a],{effectIds:[t.effect],skipResistRolls:!0})})}else console.warn("Actor not found for resist roll.")}static async applyEffect(e,t,a,s={}){let i=game.messages.get(e),r=i.flags.data.preData.source,n=i.flags.data.postData,o=i.speaker;["poison","disease"].includes(r.type)&&(n.qualityStep=n.successLevel>0?2:1);let c=f.getSpeaker(o)||f.getSpeaker(getProperty(i.flags,"data.preData.extra.speaker"))||game.actors.get(getProperty(i.flags,"data.preData.extra.actor.id")),m=c,d=(await this._parseEffectDuration(r,n,i.flags.data.preData,c)).filter(g=>!getProperty(g,"flags.dsa5.applyToOwner"));s.effectIds&&(d=d.filter(g=>s.effectIds.includes(g._id)));let p=[];if(t=="self"?c&&p.push(c):a?p=a.map(g=>f.getSpeaker(g)):game.user.targets.size&&game.user.targets.forEach(g=>{g.actor&&p.push(g.actor)}),game.user.isGM)for(let g of p){let{msg:y,resistRolls:h,effectApplied:w,effectNames:x}=await Q.applyAdvancedFunction(g,d,r,n,m,s.skipResistRolls||!1);if(w){let S=`${game.i18n.format("ActiveEffects.appliedEffect",{target:g.token?.name||g.name,source:x.join(", ")})}${y||""}`;await ChatMessage.create(f.chatDataSetup(S))}h.length&&await this.createResistRollMessage(h,e,t)}else game.socket.emit("system.dsa5",{type:"addEffect",payload:{mode:t,id:e,actors:p.map(g=>({token:g.token?g.token.id:void 0,actor:g.id,scene:canvas.scene.id}))}})}static async createResistRollMessage(e,t,a){for(let s of e){let i=await renderTemplate("systems/dsa5/templates/chat/roll/resist-roll.html",{resist:s,id:t,mode:a});await ChatMessage.create(f.chatDataSetup(i))}}static async _parseEffectDuration(e,t,a,s){let i={};for(let m of a.situationalModifiers.filter(d=>d.specAbId))i[m.specAbId]=m.step;let r=Object.keys(i),n=s?s.items.filter(m=>r.includes(m.id)):[],o=e.effects?duplicate(e.effects):[];for(let m of n){let d=duplicate(m).effects;for(let p of d)setProperty(p,"flags.dsa5.specStep",i[m.id]);o.push(...d)}let c=getProperty(e,"system.duration.value")||"";c=c.replace(/ x /g," * ").replace(game.i18n.localize("CHARAbbrev.QS"),t.qualityStep);try{for(let m of Q.effectDurationRegexes)if(m.regEx.test(c)){let d=c.replace(m.regEx,"").trim(),p=await _DiceDSA5._stringToRoll(d);if(!isNaN(p))for(let g of o){let y=p*m.seconds,h=getProperty(g,"flags.dsa5.customDuration");if(h){let w=h.split(",")[t.qualityStep-1];w&&w!="-"&&(y=Number(w))}g.duration.seconds=y,g.duration.rounds=g.duration.seconds/5}break}}catch{console.error(`Could not parse duration '${c}' of '${e.name}'`)}return o}dropDownMenu(){let e=game.i18n.localize("MODS.FW"),t=game.i18n.localize("skill"),a=game.i18n.localize("regenerate"),s=game.i18n.localize("MODS.FP"),i=game.i18n.localize("stepValue"),r=game.i18n.localize("MODS.QS"),n=game.i18n.localize("MODS.partChecks"),o=`${game.i18n.localize("LocalizedIDs.perception")} 1`,c=`${game.i18n.localize("LocalizedIDs.wrestle")} 1`,m=game.i18n.localize("closeCombatAttacks"),d=game.i18n.localize("rangeCombatAttacks"),p=`${a} (${game.i18n.localize("CHARAbbrev.CR")})`,g=game.i18n.localize("AsPCost"),y=game.i18n.localize("KaPCost"),h=game.i18n.localize("permanentCost"),w=`${game.i18n.localize("Healing")} 1`,x=`${game.i18n.localize("Description")} 1`,v=`${game.i18n.localize("LocalizedIDs.miracle")}`,S=[{name:game.i18n.localize("protection"),val:"system.totalArmor",mode:2,ph:"1"},{name:game.i18n.localize("liturgyArmor"),val:"system.liturgyArmor",mode:2,ph:"1"},{name:`${game.i18n.localize("resistanceModifier")} (${game.i18n.localize("condition")})`,val:"system.resistances.effects",mode:0,ph:"inpain 1"},{name:game.i18n.localize("spellArmor"),val:"system.spellArmor",mode:2,ph:"1"},{name:game.i18n.localize("carrycapacity"),val:"system.carryModifier",mode:2,ph:"1"},{name:`${m} - ${game.i18n.localize("CHARAbbrev.AT")}`,val:"system.meleeStats.attack",mode:2,ph:"1"},{name:`${m} - ${game.i18n.localize("CHARAbbrev.PA")}`,val:"system.meleeStats.parry",mode:2,ph:"1"},{name:`${v} - ${game.i18n.localize("CHARAbbrev.AT")}`,val:"system.miracle.attack",mode:2,ph:"1"},{name:`${v} - ${game.i18n.localize("CHARAbbrev.PA")}`,val:"system.miracle.parry",mode:2,ph:"1"},{name:`${m} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.meleeStats.damage",mode:2,ph:"1d6"},{name:`${m} - ${game.i18n.localize("MODS.defenseMalus")}`,val:"system.meleeStats.defenseMalus",mode:2,ph:"1"},{name:game.i18n.localize("MODS.creatureBonus"),val:"system.creatureBonus",mode:0,ph:`${game.i18n.localize("CONJURATION.elemental")} 1`},{name:`${d} - ${game.i18n.localize("CHARAbbrev.AT")}`,val:"system.rangeStats.attack",mode:2,ph:"1"},{name:`${d} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.rangeStats.damage",mode:2,ph:"1d6"},{name:`${d} - ${game.i18n.localize("MODS.defenseMalus")}`,val:"system.rangeStats.defenseMalus",mode:2,ph:"1"},{name:`${game.i18n.localize("spell")} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.spellStats.damage",mode:2,ph:"1"},{name:`${game.i18n.localize("liturgy")} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.liturgyStats.damage",mode:2,ph:"1"},{name:y,val:"system.kapModifier",mode:2,ph:"1"},{name:g,val:"system.aspModifier",mode:2,ph:"1"},{name:`${h} ${game.i18n.localize("CHARAbbrev.AsP")}`,val:"system.status.astralenergy.permanentGear",mode:2,ph:"1"},{name:`${h} ${game.i18n.localize("CHARAbbrev.KaP")}`,val:"system.status.astralenergy.permanentGear",mode:2,ph:"1"},{name:`${t} - ${e}`,val:"system.skillModifiers.FW",mode:0,ph:o},{name:`${t} - ${s}`,val:"system.skillModifiers.FP",mode:0,ph:o},{name:`${t} - ${i}`,val:"system.skillModifiers.step",mode:0,ph:o},{name:`${t} - ${r}`,val:"system.skillModifiers.QL",mode:0,ph:o},{name:`${t} - ${n}`,val:"system.skillModifiers.TPM",mode:0,ph:o},{name:`${game.i18n.localize("vulnerability")} - ${game.i18n.localize("combatskill")}`,val:"system.vulnerabilities.combatskill",mode:0,ph:c},{name:`${t} - ${game.i18n.localize("MODS.global")}`,val:"system.skillModifiers.global",mode:0,ph:"1"},{name:`${p} - ${game.i18n.localize("wounds")}`,val:"system.repeatingEffects.startOfRound.wounds",mode:0,ph:"1d6"},{name:`${p} - ${game.i18n.localize("astralenergy")}`,val:"system.repeatingEffects.startOfRound.astralenergy",mode:0,ph:"1d6"},{name:`${p} - ${game.i18n.localize("karmaenergy")}`,val:"system.repeatingEffects.startOfRound.karmaenergy",mode:0,ph:"1d6"},{name:`${a} - ${game.i18n.localize("wounds")}`,val:"system.status.regeneration.LePgearmodifier",mode:2,ph:"1"},{name:`${a} - ${game.i18n.localize("astralenergy")}`,val:"system.status.regeneration.AsPgearmodifier",mode:2,ph:"1"},{name:`${a} - ${game.i18n.localize("karmaenergy")}`,val:"system.status.regeneration.KaPgearmodifier",mode:2,ph:"1"},{name:`${game.i18n.localize("feature")} - ${g}`,val:"system.skillModifiers.feature.AsPCost",mode:0,ph:w},{name:`${game.i18n.localize("advanced")} - ${g}`,val:"system.skillModifiers.conditional.AsPCost",mode:0,ph:x},{name:`${game.i18n.localize("feature")} - ${y}`,val:"system.skillModifiers.feature.KaPCost",mode:0,ph:w},{name:`${game.i18n.localize("advanced")} - ${y}`,val:"system.skillModifiers.conditional.KaPCost",mode:0,ph:x},{name:`${game.i18n.localize("MODS.sight")}`,val:"system.sightModifier.value",mode:2,ph:"-1"},{name:`${game.i18n.localize("MODS.sightMax")}`,val:"system.sightModifier.maxLevel",mode:5,ph:"4"},{name:`${game.i18n.localize("LocalizedIDs.immuneTo")} ${game.i18n.localize("condition")}`,val:"system.immunities",mode:2,ph:"feared"},{name:game.i18n.localize("temperature.heatProtection"),val:"system.temperature.heatProtection",mode:2,ph:"1"},{name:game.i18n.localize("temperature.coldProtection"),val:"system.temperature.coldProtection",mode:2,ph:"1"}],z=["liturgy","ceremony","spell","ritual","skill","feature"];for(let F of z){let N=F=="skill"?"skillglobal":F,D=game.i18n.localize(N);S.push({name:`${D} - ${e}`,val:`system.skillModifiers.${F}.FW`,mode:0,ph:o},{name:`${D} - ${s}`,val:`system.skillModifiers.${F}.FP`,mode:0,ph:o},{name:`${D} - ${i}`,val:`system.skillModifiers.${F}.step`,mode:0,ph:o},{name:`${D} - ${r}`,val:`system.skillModifiers.${F}.QL`,mode:0,ph:o},{name:`${D} - ${n}`,val:`system.skillModifiers.${F}.TPM`,mode:0,ph:o})}for(let F of CONFIG.statusEffects)getProperty(F,"flags.dsa5.max")&&S.push({name:game.i18n.localize(F.name),val:`system.condition.${F.id}`,mode:2,ph:1});for(let F of Object.keys(b.characteristics))S.push({name:game.i18n.localize(`CHAR.${F.toUpperCase()}`),val:`system.characteristics.${F}.gearmodifier`,mode:2,ph:"1"});for(let F of b.gearModifyableCalculatedAttributes)S.push({name:game.i18n.localize(F),val:`system.status.${F}.gearmodifier`,mode:2,ph:"1"});for(let F of["spell","liturgy","ceremony","ritual"]){let N=f.categoryLocalization(F);for(let D of["soulpower","toughness"])S.push({name:`${game.i18n.localize(D)} (${N})`,val:`system.status.${D}.${F}resist`,mode:2,ph:"1"});for(let D of Object.keys(le.rollModifiers))S.push({name:`${N} - ${game.i18n.localize(D.replace("Spell",""))}`,val:`system.${F}RollModifiers.${D}.mod`,mode:2,ph:"1"},{name:`${N} - ${game.i18n.localize(D.replace("Spell",""))} - ${game.i18n.localize("advanced")}`,val:`system.${F}RollModifiers.${D}.custom`,mode:0,ph:x})}S=S.sort((F,N)=>F.name.localeCompare(N.name));for(let F of S)(!F.ph||F.mode==null)&&console.warn(F);return S=S.map(F=>``).join(` -`),``}activateListeners(e){super.activateListeners(e);let t=this.dropDownMenu();e.find(".changes-list .effect-change .key").append(t),e.find(".selMenu").select2({width:"element"}).change(a=>{let s=$(a.currentTarget);s.siblings("input").val(s.val());let i=s.closest(".effect-change"),r=s.find("option:selected");i.find(".mode select").val(r.attr("data-mode")),i.find(".value input").attr("placeholder",r.attr("data-ph")),s.trigger("blur")}),e.find(".select2").each((a,s)=>{$(s)[0].style.removeProperty("width")})}};u(Q,"DSAActiveEffectConfig");var qa=class{static async createTokenHook(e,t,a){if(!f.isActiveGM())return;let s=e.parent;if(this.isRiding(e.actor)&&s.active){let i=this.getHorse(e.actor);if(!i)return;let r=await i.getTokenDocument();r.updateSource({x:e.x,y:e.y,hidden:e.hidden});let n=(await s.createEmbeddedDocuments("Token",[r]))[0],o={"flags.dsa5.horseTokenId":n.id,elevation:(n.elevation??0)+1};mergeObject(o,this.adaptTokenSize(e,n)),await e.update(o),n.actorLink||await e.actor.update({"system.horse.actorLink":!1,"system.horse.token":{scene:s.id,token:n.id}})}}static isRiding(e){return getProperty(e,"system.horse.isRiding")}static updateTokenHook(e,t,a){if(!f.isActiveGM())return;let s=getProperty(e,"flags.dsa5.horseTokenId"),i=e.parent;s&&i.active&&(t.x||t.y)&&this.isRiding(e.actor)&&i.updateEmbeddedDocuments("Token",[{_id:s,x:e.x,y:e.y}])}static rollLoyalty(e,t={}){let a=this.getHorse(e);if(!a)return;let s=this.getLoyaltyFromHorse(a);if(!s)return ui.notifications.warn(game.i18n.format("DSAError.notFound",{category:f.categoryLocalization("skill"),name:game.i18n.localize("LocalizedIDs.loyalty")}));a.setupSkill(s,t,a.token?.id).then(i=>{a.basicTest(i)})}static async updateRiderSpeed(e,t){if(!canvas?.tokens?.documentCollection)return;let a=e.getActiveTokens().map(s=>s.id);for(let s of Array.from(canvas.tokens.documentCollection))a.includes(s.getFlag("dsa5","horseTokenId"))&&t!=s.actor.system.status.speed.max&&(s.actor.prepareData(),s.actor.sheet.render())}static getLoyaltyFromHorse(e){return e.items.find(t=>t.type=="skill"&&t.name.startsWith(game.i18n.localize("LocalizedIDs.loyalty")))}static activateListeners(e,t){e.find(".riding-toggle").click(()=>this.toggleIsRiding(t)),e.find(".showHorse").click(()=>this.getHorse(t).sheet.render(!0)),e.find(".horse-delete").click(()=>this.clearMount(t)),e.find(".horse-loyalty").click(()=>this.rollLoyalty(t)),e.find('[name="horseSpeedSelector"]').change(async a=>{a.preventDefault();let s=qa.getHorse(t);qa.setSpeed(s,a.currentTarget.value)})}static async toggleIsRiding(e){await e.update({"system.horse.isRiding":!e.system.horse?.isRiding});let t=[];if(e.system.horse.isRiding){let a=this.getHorse(e),s;for(let i of a.getActiveTokens())t.push({_id:i.document.id,["flags.dsa5.-=horseTokenId"]:null}),s=i.document.id;for(let i of e.getActiveTokens())t.push({_id:i.document.id,elevation:Math.max(0,(i.elevation??0)+1),"flags.dsa5.horseTokenId":s});await this.addRidingCondition(e)}else{for(let a of e.getActiveTokens())t.push({_id:a.document.id,["flags.dsa5.-=horseTokenId"]:null,elevation:Math.max(0,(a.elevation??0)-1)});await this.removeRidingCondition(e)}await canvas.scene.updateEmbeddedDocuments("Token",t,{noHooks:!0})}static getRidingCondition(e){let t=game.i18n.localize("RIDING.riding");return e.effects.find(a=>a.name==t)}static async addRidingCondition(e){this.getRidingCondition(e)||await e.addCondition(this.ridingCondition())}static async removeRidingCondition(e){let t=this.getRidingCondition(e);t&&await e.deleteEmbeddedDocuments("ActiveEffect",[t.id])}static deleteTokenHook(){console.warn("delete riding token hook not implemented")}static getHorse(e,t=!1){let a;return e.system.horse&&(e.system.horse.token&&!e.system.horse.actorLink?a=f.getSpeaker(e.system.horse.token):a=game.actors.get(e.system.horse.actorId),!a&&t&&e.system.horse.isRiding&&(a={name:game.i18n.localize("unknown")})),a}static async unmountHorse(e,t){let a={["flags.dsa5.-=horseTokenId"]:null,elevation:Math.max(0,(t.elevation??0)-1)},s=t.getFlag("dsa5","horseResized");s&&mergeObject(a,{["flags.dsa5.-=horseResized"]:null,width:s.width,height:s.height}),await this.clearMount(e),await t.update(a)}static async clearMount(e){await e.update({system:{horse:{isRiding:!1,actorLink:!1,actorId:"","-=token":null}}}),await this.removeRidingCondition(e)}static ridingCondition(){return{name:game.i18n.localize("RIDING.riding"),icon:"systems/dsa5/icons/thirdparty/horse-head.svg",changes:[{key:"system.status.dodge.gearmodifier",mode:2,value:-2}],flags:{dsa5:{description:game.i18n.localize("RIDING.ridingDescription")}}}}static async setHorse(e,t){let a={system:{horse:{isRiding:!0,actorLink:t.prototypeToken.actorLink,actorId:t.id}}};!t.prototypeToken.actorLink&&t.token&&mergeObject(a,{system:{horse:{token:{scene:canvas.scene.id,token:t.token.id}}}}),await e.update(a),t.isToken&&await canvas.scene.updateEmbeddedDocuments("Token",e.getActiveTokens().map(s=>({_id:s.id,"flags.dsa5.horseTokenId":t.token.id,x:t.token.x,y:t.token.y})).concat({_id:t.token.id,["flags.dsa5.-=horseTokenId"]:null}),{noHooks:!0}),await this.addRidingCondition(e)}static adaptTokenSize(e,t){return e.width>=t.width?{width:.7*t.width,height:.7*t.height,"flags.dsa5.horseResized":{width:e.width,height:e.height}}:{}}static async mountHorse(e){let t=canvas.tokens.controlled.find(r=>r.document.id!=e.id),a=e.parent,s={system:{horse:{isRiding:!0,actorLink:t.actorLink,actorId:t.actor.id}}};t.actorLink||mergeObject(s,{system:{horse:{token:{scene:a.id,token:t.id}}}});let i={_id:e.id,"flags.dsa5.horseTokenId":t.id,x:t.x,y:t.y,elevation:(t.document.elevation??0)+1};mergeObject(i,this.adaptTokenSize(e.document,t.document)),await e.actor.update(s),await canvas.scene.updateEmbeddedDocuments("Token",[i,{_id:t.id,["flags.dsa5.-=horseTokenId"]:null}],{noHooks:!0}),await this.addRidingCondition(e.actor)}static getHorseSpeed(e){return e.effects.find(t=>getProperty(t,"flags.dsa5.horseSpeed"))?.flags.dsa5.horseSpeed||0}static horseSpeedModifier(e){let t=this.getHorseSpeed(e);return Object.keys(this.speedKeys).map(a=>Number(a)).indexOf(Number(t))}static increaseSpeed(e){let t=this.getHorseSpeed(e),a=Math.min(3,Object.keys(this.speedKeys).map(s=>Number(s)).indexOf(t)+1);this.setSpeed(e,Object.keys(this.speedKeys).map(s=>Number(s))[a])}static decreaseSpeed(e){let t=this.getHorseSpeed(e),a=Math.max(0,Object.keys(this.speedKeys).map(s=>Number(s)).indexOf(t)-1);this.setSpeed(e,Object.keys(this.speedKeys).map(s=>Number(s))[a])}static async setSpeed(e,t){await e.deleteEmbeddedDocuments("ActiveEffect",e.effects.filter(a=>hasProperty(a,"flags.dsa5.horseSpeed")).map(a=>a.id)),await e.addCondition({name:game.i18n.localize("speed")+": "+game.i18n.localize(`RIDING.speeds.${t}`),icon:"systems/dsa5/icons/thirdparty/horse-head.svg",changes:[this.speedKeys[t]],flags:{dsa5:{description:game.i18n.localize(`RIDING.speed.${t}`),horseSpeed:t}}})}static renderTokenHUD(e,t,a){let s=e.object.actor;if(canvas.tokens.controlled.length==2)t.find(".col.left").prepend(this.preRenderedMountHud),t.find('.control-icon[data-action="ride"]').click(()=>this.mountHorse(e.object));else if(this.isRiding(s)){t.find(".col.left").prepend(this.preRenderedUnmountHud);let i=t.find('.control-icon[data-action="ride"]');i.click(()=>{this.unmountHorse(s,e.object.document),i.remove()});let r=this.getHorse(s);t.find(".col.right").prepend(this.preRenderedSpeedHud),t.find('.control-icon[data-action="rideIncrease"]').click(()=>this.increaseSpeed(r)),t.find('.control-icon[data-action="rideDecrease"]').click(()=>this.decreaseSpeed(r))}}},H=qa;u(H,"Riding"),L(H,"preRenderedUnmountHud",` +
    `;e.find(".dpsSelector").remove(),e.find('.tab[data-tab="grid"]').append(s)});var ot=class extends Dialog{static async getDialog(e){let t=Array.from(game.user.targets).map(i=>i.id),a=[],s=canvas.scene?canvas.scene.tokens.get(e.token)?.object:void 0;return game.combat&&game.combat.combatants.forEach(i=>{if(!!i.visible){if(i.isSelected=t.includes(i.token.id),s&&i.token){let n=canvas.scene.tokens.get(i.token.id).object;i.distance=J.rangeFinder(s,n),i.distance.distanceSum=Number(i.distance.distanceSum.toFixed(1))}a.push(i)}}),new ot({title:game.i18n.localize("DIALOG.addTarget"),content:await renderTemplate("systems/dsa5/templates/dialog/addTarget-dialog.html",{selectables:a}),default:"yes",buttons:{}})}activateListeners(e){super.activateListeners(e);let t=e.find(".combatant");t.click(a=>this.setTargets(a)),t.hover(this._onCombatantHoverIn.bind(this),this._onCombatantHoverOut.bind(this)),t.mousedown(a=>this._onRightClick(a))}_onCombatantHoverOut(e){this._getCombatApp()._onCombatantHoverOut(e)}_onCombatantHoverIn(e){this._getCombatApp()._onCombatantHoverIn(e)}_onRightClick(e){if(e.button==2){let t=game.combat.combatants.get(e.currentTarget.dataset.combatantId);if(t.token)return canvas.animatePan({x:t.token.x,y:t.token.y})}}_getCombatApp(){return game.combats.apps[0]}async setTargets(e){let t=e.originalEvent.shiftKey;t||$(e.currentTarget).closest(".directory").find(".combatant").removeClass("selectedTarget"),$(e.currentTarget).addClass("selectedTarget");let a=e.currentTarget.dataset.combatantId;game.combat.combatants.get(a).token.object.setTarget(!0,{user:game.user,releaseOthers:!t,groupSelection:!0})}};u(ot,"AddTargetDialog");var De=class extends Dialog{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5Decent"])}),e}static async getDialog(){let e=game.users.filter(t=>t.active&&!t.isGM);return new De({title:game.i18n.localize("DIALOG.setTargetToUser"),content:await renderTemplate("systems/dsa5/templates/dialog/selectForUserDialog.html",{users:e}),default:"yes",buttons:{}})}static registerButtons(){Hooks.on("getSceneControlButtons",e=>{if(!game.user.isGM)return;let t={name:"targetUser",title:game.i18n.localize("CONTROLS.targetForUser"),icon:"fa fa-bullseye",button:!0,onClick:async()=>{(await De.getDialog()).render(!0)}};e[0].tools.splice(2,0,t)})}activateListeners(e){super.activateListeners(e),e.find(".combatant").click(t=>this.setTargetToUser(t))}setTargetToUser(e){let t=Array.from(game.user.targets).map(i=>i.id),a=e.currentTarget.dataset.userId;game.users.get(a).updateTokenTargets(t),game.socket.emit("userActivity",a,{targets:t}),this.close()}};u(De,"SelectUserDialog");var lt=class extends Dialog{static async getDialog(e){let t=game.users.filter(a=>a.active&&!a.isGM);new lt({title:game.i18n.localize("SHEET.PostItem"),content:await renderTemplate("systems/dsa5/templates/dialog/usermultipickdialog.html",{users:t}),default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:a=>{this.postContent(a,e)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}static async postContent(e,t){let a=f.chatDataSetup(t);if(!e.find("#sel_all").is(":checked")){let s=[];e.find(".usersel:checked").each(function(){s.push($(this).val())}),a.whisper=s}ChatMessage.create(a)}activateListeners(e){super.activateListeners(e),e.find('[name="sel_all"]').change(t=>{e.find(".usersel").prop("disabled",t.currentTarget.checked).prop("checked",t.currentTarget.checked)})}};u(lt,"UserMultipickDialog");var ei=class extends Dialog{recallSettings(e,t,a,s){return this.recallData=game.dsa5.memory.recall(e,t,a),this.dialogData={mode:a,speaker:e,source:t,renderData:s},this}async _render(e,t){await super._render(e,t),this.prepareFormRecall($(this._element))}setRollButtonWarning(){return this.dialogData.mode=="attack"?` ${game.i18n.localize("DIALOG.noTarget")}`:""}setMultipleTargetsWarning(){return this.dialogData.mode=="attack"?` ${game.i18n.localize("DIALOG.multipleTarget")}`:""}renderRollValueDie(){if(this.dialogData.rollValue&&this.dialogData.mode!="damage"){let e=this.dialogData.mode=="attack"||this.dialogData.counterAttack?"die-mu":"die-in",t=this.dialogData.modifier||0;return`${Math.clamped(this.dialogData.rollValue+t,1,20)}`}else return""}async updateRollButton(e){let t=this.renderRollValueDie()+game.i18n.localize("Roll");e.length>0?e.length>1&&(t+=this.setMultipleTargetsWarning()):t+=this.setRollButtonWarning(),$(this._element).find(".dialog-buttons .rollButton").html(t)}async updateTargets(e,t){let a=await renderTemplate("systems/dsa5/templates/dialog/parts/targets.html",{targets:t});e.find(".targets").html(a),this.updateRollButton(t)}removeTarget(e){let t=e.currentTarget.dataset.id;$(e.currentTarget).remove();let a=[];game.user.targets.forEach(s=>{t!=s.id&&a.push(s.id)}),game.user.updateTokenTargets(a)}readTargets(){let e=[];return game.user.targets.forEach(t=>{t.actor&&e.push({name:t.actor.name,img:t.actor.img,id:t.id})}),e}compareTargets(e,t){let a=this.readTargets();return JSON.stringify(t)!=JSON.stringify(a)&&(t=a,this.updateTargets(e,t)),t}activateListeners(e){super.activateListeners(e),e.find(".quantity-click").mousedown(t=>P.quantityClick(t)),e.find(".modifiers option").mousedown(t=>(t.preventDefault(),$(t.currentTarget).prop("selected",!$(t.currentTarget).prop("selected")),!1)),e.on("click",".rollTarget",t=>this.removeTarget(t)),e.on("click",".addTarget",t=>this.addTarget(t))}async addTarget(e){(await ot.getDialog(this.dialogData.speaker)).render(!0)}prepareFormRecall(e){if(this.recallData)for(let t in this.recallData)if(t=="specAbs")for(let a of this.recallData[t]){let s=e.find(`.specAbs[data-id="${a.id}"]`);s.addClass("active").attr("data-step",a.step),s.find(".step").text(ei.roman[a.step])}else{let a=e.find(`[name="${t}"]`);if(Array.isArray(this.recallData[t])){let s=a.find("option");for(let i of s){let n=this.recallData[t].find(r=>r.name==$(i).text().trim());n&&(i.selected=n.selected)}}else a.attr("type")=="checkbox"?a[0].checked=this.recallData[t]:a.val(this.recallData[t])}}},ie=ei;u(ie,"DialogShared"),L(ie,"roman",[""," I"," II"," III"," IV"," V"," VI"," VII"," VIII"," IX"," X"]);var qe=class extends ie{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,resizable:!0}),e}prepareFormRecall(e){super.prepareFormRecall(e),e.find(".spellModifier").trigger("change")}static getRollButtons(e,t,a,s){let i=ee.getRollButtons(e,t,a,s);if(["spell","liturgy"].includes(e.source.type)){let n=Number(e.source.system.castingTime.value),r=e.source.system.castingTime.progress,o=e.source.system.castingTime.modified;if(n&&e.extra.speaker.token!="emptyActor"){let c=o>0?` (${r}/${o})`:"";mergeObject(i,{reloadButton:{label:`${game.i18n.localize("SPELL.reload")}${c}`,callback:async m=>{let d=await f.getSpeaker(e.extra.speaker),p={_id:e.source._id,"system.castingTime.progress":r+1};o==0&&(o=Number(m.find(".castingTime").text())-1,p["system.castingTime.modified"]=o),await d.updateEmbeddedDocuments("Item",[p]);let g=game.i18n.format("SPELL.isReloading",{actor:d.token?.name||d.prototypeToken.name,item:e.source.name,status:`${r+1}/${o}`});await ChatMessage.create(f.chatDataSetup(g))}}})}}return i}async applyTransformations(e,t){let a=t.find('[name="situationalModifiers"]');a.find('option[data-extension="1"]').remove();let s=[],i=Object.keys(qe.rollModifiers).map(r=>`${r}.mod`);this.dialogData.renderData.rollModifiersPrepared=duplicate(this.dialogData.renderData.rollModifiers);for(let r of t.find(".specAbs.active")){let o=fromUuidSync(r.dataset.uuid);if(!!o)for(let c of o.effects)for(let m of c.changes)if(qe.rollChanges.includes(m.key)){let d=o.name.split(" - "),p=game.i18n.localize(`MODS.${m.key}`);d=`${d[1]||d[0]}`;let g=`${p}: ${m.value}
    ${game.i18n.localize("spellextension")}: ${d}`;s.push(``)}else m.key=="macro.transform"?await f.callItemTransformationMacro(m.value,e,c):i.includes(m.key)?c.apply(this.dialogData.renderData.rollModifiersPrepared,m):c.apply(e,m)}let n=this.dialogData.renderData.rollModifiersPrepared.extensionModifier.mod;if(n){let r=game.i18n.localize("ABBR.modifiers"),o=game.i18n.localize("spellextension"),c=`${r}: ${n}
    ${o}`;s.push(``)}a.append(s.join(""))}static setData(e,t){let a=duplicate(qe.rollModifiers),s=`${t}RollModifiers`;if(e.system[s])for(let i of Object.keys(e.system[s]))a[i].mod+=Number(e.system[s][i]?.mod??0);return a}async recalcSpellModifiers(e,t){let a=e,s=duplicate(this.dialogData.source);P.ensureNumber(s);let i=a.find(".castingTime"),n=a.find(".aspcost"),r=a.find(".reach"),o=a.find(".maintainCost"),c=a.find(".ritual").length>0;await this.applyTransformations(s,a);let m=a.find(".maxMods");if(a.find(".spellModifier:checked").length>Number(m.text())){t&&(t.currentTarget.checked=!1),m.addClass("emphasize"),setTimeout(function(){m.removeClass("emphasize")},600);return}for(let S of Object.keys(this.dialogData.renderData.rollModifiersPrepared)){let x=this.dialogData.renderData.rollModifiersPrepared[S].mod;e.find(`.${S}Label`).text(`(${x})`),e.find(`#${S}`).val(x)}let d=e.find(".canChangeCastingTime");s.system.canChangeCastingTime.value=="true"?d.is(":empty")&&(d.html(await renderTemplate("systems/dsa5/templates/dialog/parts/canChangeCastingTime.html",{rollModifiers:this.dialogData.renderData.rollModifiers})),this.setPosition({height:"auto"})):d.is(":empty")||(d.html(""),this.setPosition({height:"auto"}));let p=s.system.AsPCost.value,g=s.system.range.value,y=s.system.castingTime.value,h=p,w=s.system.maintainCost.value;a.find(".variableBaseCost")[s.system.variableBaseCost=="true"?"show":"hide"]();let z=0;a.find(".spellModifier[data-cost]:checked").each(function(S,x){if(h=h*(x.value<0?.5:2),w!=""&&w!=null){let F=String(w).split(" ");F[0]=Math.max(Number(F[0])*(x.value<0?.5:2)),w=F.join(" ")}z+=Number(x.value)}),h<1?t&&(t.currentTarget.checked=!1):(n.text(h),o.text(w),n.attr("data-mod",z)),z=0,h=y,a.find(".spellModifier[data-castingTime]:checked").each(function(S,x){if(c){let F=qe.bigTimes.indexOf(Number(h));if(F!=null){let N=F+(x.value>0?1:-1);N=0?h=qe.bigTimes[N]:ui.notifications.error(game.i18n.localize("DSAError.CastingTimeLimit"))}else ui.notifications.error(game.i18n.localize("DSAError.TimeCannotBeParsed"))}else h=h*(x.value>0?2:.5);z+=Number(x.value)}),h<1?t&&(t.currentTarget.checked=!1):(i.text(h),i.attr("data-mod",z)),z=0;let v=game.i18n.localize("ReverseSpellRanges."+g);r.text(g),a.find(".spellModifier[data-reach]:checked").each(function(S,x){if(v=="self")x.checked=!1;else if(v=="touch")r.text("4 "+game.i18n.localize("step")),z+=Number(x.value);else{let F=g.split(" ");v=Number(F[0]),isNaN(v)?(t&&(t.currentTarget.checked=!1),ui.notifications.error(game.i18n.localize("DSAError.RangeCannotBeParsed"))):(r.text(v*2+" "+game.i18n.localize("step")),z+=Number(x.value))}}),r.attr("data-mod",z),e.find(".reloadButton").prop("disabled",Number(e.find(".castingTime").text())<2)}activateListeners(e){super.activateListeners(e),e.find(".reloadButton").prop("disabled",Number(e.find(".castingTime").text())<2),e.find(".specAbs").mousedown(s=>{$(s.currentTarget).toggleClass("active"),this.recalcSpellModifiers(e)}),e.find(".variableBaseCost").change(s=>{let i=$(s.currentTarget).parents(".skill-test"),n=i.find(".aspcost").attr("data-base"),r=$(s.currentTarget).val();i.find(".aspcost").attr("data-base",r),i.find(".aspcost").text(Number(i.find(".aspcost").text())*r/n)}),e.on("change",".spellModifier",s=>this.recalcSpellModifiers(e,s));let t=this.readTargets();t.length==0&&this.setRollButtonWarning();let a=this;this.checkTargets=setInterval(function(){t=a.compareTargets(e,t)},500)}},le=qe;u(le,"DSA5SpellDialog"),L(le,"rollChanges",["defenseMalus"]),L(le,"rollModifiers",{forceSpell:{mod:1},reduceCostSpell:{mod:-1},increaseRangeSpell:{mod:-1},increaseCastingTime:{mod:1},decreaseCastingTime:{mod:-1},removeGesture:{mod:-2},removeFormula:{mod:-2},extensionModifier:{mod:0}}),L(le,"bigTimes",[5,30,120,480,960,1920]);function Mi(l,e={}){f.moduleEnabled("autoanimations")&&console.warn("Animations for on use effects not enabled yet")}u(Mi,"automatedAnimation");async function ti(l,e,t,a,s,i={}){let n={};if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else{let o=await game.packs.get(l)?.getDocuments({name:e});if(!o||!o.length){for(let c of game.packs.filter(m=>m.documentName=="Macro"&&/\(internal\)/.test(m.metadata.label)))if(o=await c.getDocuments({name:e}),o.length)break}if(o.length){let c=Object.getPrototypeOf(async function(){}).constructor,m=new c("actor","item","qs","automatedAnimation","args",o[0].command);try{i.result=n;let d=mergeObject({automatedAnimation:Mi},this);await m.call(d,t,a,s,Mi,i)}catch(d){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(d),n.error=!0}}else ui.notifications.error(game.i18n.format("DSAError.macroNotFound",{name:e}))}return n}u(ti,"callMacro");Hooks.once("i18nInit",()=>{Q.effectDurationRegexes=[{regEx:new RegExp(game.i18n.localize("DSAREGEX.combatRounds"),"i"),seconds:5},{regEx:new RegExp(game.i18n.localize("DSAREGEX.minutes"),"i"),seconds:60},{regEx:new RegExp(game.i18n.localize("DSAREGEX.hours"),"i"),seconds:3600},{regEx:new RegExp(game.i18n.localize("DSAREGEX.days"),"i"),seconds:3600*24},{regEx:new RegExp(game.i18n.localize("DSAREGEX.weeks"),"i"),seconds:3600*24*7},{regEx:new RegExp(game.i18n.localize("DSAREGEX.months"),"i"),seconds:3600*24*30},{regEx:new RegExp(game.i18n.localize("DSAREGEX.years"),"i"),seconds:3600*24*350}]});var Q=class extends ActiveEffectConfig{static get defaultOptions(){return mergeObject(super.defaultOptions,{resizable:!0})}static async callMacro(e,t,a,s,i,n={}){return await ti(e,t,a,s,i,n)}static async onEffectRemove(e,t){let a=getProperty(t,"flags.dsa5.onRemove");if(a)if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else try{let s=Object.getPrototypeOf(async function(){}).constructor;await new s("effect","actor",a).call(this,t,e)}catch(s){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(s),console.warn(s.stack)}}async checkTimesUpInstalled(){let e=f.moduleEnabled("times-up");return!e&&game.user.isGM&&ui.notifications.warn(game.i18n.localize("DSAError.shouldTimesUp")),e}async _render(e=!1,t={}){await super._render(e,t);let a=0,s=getProperty(this.object,"parent.type"),i=["meleeweapon","rangeweapon"].includes(s)||s=="trait"&&["meleeAttack","rangeAttack"].includes(getProperty(this.object,"parent.system.traitType.value")),n={hasSpellEffects:i||["spell","liturgy","ritual","skill","ceremony","consumable","poison","disease","ammunition"].includes(s)||["specialability"].includes(s)&&getProperty(this.object,"parent.system.category.value")=="Combat",hasDamageTransformation:["ammunition"].includes(s),hasTriggerEffects:["specialability"].includes(s)},r=[];if((n.hasSpellEffects||n.hasDamageTransformation||n.hasTriggerEffects)&&r.push({name:"ActiveEffects.advancedFunctions.none",index:0}),n.hasSpellEffects)for(let p of["systemEffect","macro","creature"])r.push({name:`ActiveEffects.advancedFunctions.${p}`,index:a+=1});n.hasDamageTransformation&&r.push({name:"ActiveEffects.advancedFunctions.armorPostprocess",index:4},{name:"ActiveEffects.advancedFunctions.damagePostprocess",index:5}),n.hasTriggerEffects&&r.push({name:"ActiveEffects.advancedFunctions.postRoll",index:6},{name:"ActiveEffects.advancedFunctions.postOpposed",index:7});let o={systemEffects:this.getStatusEffects(),canEditMacros:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro")},c=[2,6,7],m=$(this._element);m.find(".tabs").append(`${game.i18n.localize("advanced")}`);let d=await renderTemplate("systems/dsa5/templates/status/advanced_effect.html",{effect:this.object,advancedFunctions:r,effectConfigs:n,macroIndexes:c,config:o,isWeapon:i});m.find('.tab[data-tab="effects"]').after($(d)),m.find(".advancedSelector").on("change",p=>{let g=this.object;g.flags.dsa5.advancedFunction=$(p.currentTarget).val(),renderTemplate("systems/dsa5/templates/status/advanced_functions.html",{effect:g,config:o,macroIndexes:c}).then(y=>{m.find(".advancedFunctions").html(y)})}),this.object.statuses.size&&game.i18n.has(this.object.description)&&m.find('[data-tab="details"] .editor').replaceWith(`

    ${game.i18n.localize(this.object.description)}

    `),this.checkTimesUpInstalled()}getStatusEffects(){return CONFIG.statusEffects.map(e=>({id:e.id,name:game.i18n.localize(e.name)})).sort((e,t)=>e.name.localeCompare(t.name))}static applyRollTransformation(e,t,a){let s="",i=t.origin;for(let n of i.effects)try{if(Number(getProperty(n,"flags.dsa5.advancedFunction"))==a)if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else try{let r=Object.getPrototypeOf(function(){}).constructor;new r("ef","callMacro","actor","msg","source",getProperty(n,"flags.dsa5.args3")).call(this,n,ti,e,s,i)}catch(r){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(r),console.warn(r.stack)}}catch(r){console.warn("Unable to apply advanced effect",r,n)}return t.origin=i,{msg:s,options:t}}static async applyAdvancedFunction(e,t,a,s,i,n=!0){let r="",o=[],c=!1,m=[],d=new Set;for(let p of t){p.origin&&delete p.origin;let g=Number(getProperty(p,"flags.dsa5.specStep"))||0;try{let y=Number(getProperty(p,"flags.dsa5.advancedFunction")),h=Math.min(s.qualityStep||0,6),w=getProperty(p,"flags.dsa5.resistRoll");if(w&&!n){let z=w.split(" "),v=`${z.pop()}`;o.push({skill:z.join(" "),mod:Math.round(Roll.safeEval(`${v}`.replace(/q(l|s)/i,h).replace("step",g)))||0,effect:p,target:e,token:e.token?e.token.id:void 0})}else if(c=!0,d.has(p.name)||d.add(p.name),p.changes&&p.changes.length>0&&m.push(p),y)switch(y){case 1:{let v=duplicate(CONFIG.statusEffects.find(x=>x.id==getProperty(p,"flags.dsa5.args0"))),S=`${getProperty(p,"flags.dsa5.args1")}`||"1";v.duration=p.duration,/,/.test(S)?S=Number(S.split(",")[h-1]):S=Number(S.replace(game.i18n.localize("CHARAbbrev.QS"),h)),await e.addCondition(v,S,!1,!1)}break;case 2:if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else try{let v=Object.getPrototypeOf(async function(){}).constructor;await new v("effect","actor","callMacro","msg","source","actor","sourceActor","testData","qs",getProperty(p,"flags.dsa5.args3")).call(this,p,e,ti,r,a,e,i,s,h)}catch(v){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(v),console.warn(v.stack)}break;case 3:let z=(getProperty(p,"flags.dsa5.args4")||"").split(",").map(v=>`@Compendium[${v.trim().replace(/(@Compendium\[|\])/)}]`).join(" ");r+=`

    ${game.i18n.localize("ActiveEffects.advancedFunctions.creature")}:

    ${z}

    `;break}}catch(y){console.warn("Unable to apply advanced effect"),console.warn(y),console.warn(p)}}return await e.createEmbeddedDocuments("ActiveEffect",m),{msg:r,resistRolls:o,effectApplied:c,effectNames:Array.from(d)}}static async resistEffect(e){let t=e.currentTarget.dataset,a={token:t.token,actor:t.actor,scene:canvas.id},s=f.getSpeaker(a);if(s){let i=s.items.find(n=>n.type=="skill"&&n.name==t.skill);s.setupSkill(i,{modifier:t.mod},t.token).then(async n=>{n.testData.opposable=!1,((await s.basicTest(n)).result.qualityStep||0)<1&&await this.applyEffect(t.message,t.mode,[a],{effectIds:[t.effect],skipResistRolls:!0})})}else console.warn("Actor not found for resist roll.")}static async applyEffect(e,t,a,s={}){let i=game.messages.get(e),n=i.flags.data.preData.source,r=i.flags.data.postData,o=i.speaker;["poison","disease"].includes(n.type)&&(r.qualityStep=r.successLevel>0?2:1);let c=f.getSpeaker(o)||f.getSpeaker(getProperty(i.flags,"data.preData.extra.speaker"))||game.actors.get(getProperty(i.flags,"data.preData.extra.actor.id")),m=c,d=(await this._parseEffectDuration(n,r,i.flags.data.preData,c)).filter(g=>!getProperty(g,"flags.dsa5.applyToOwner"));s.effectIds&&(d=d.filter(g=>s.effectIds.includes(g._id)));let p=[];if(t=="self"?c&&p.push(c):a?p=a.map(g=>f.getSpeaker(g)):game.user.targets.size&&game.user.targets.forEach(g=>{g.actor&&p.push(g.actor)}),game.user.isGM)for(let g of p){let{msg:y,resistRolls:h,effectApplied:w,effectNames:z}=await Q.applyAdvancedFunction(g,d,n,r,m,s.skipResistRolls||!1);if(w){let S=`${game.i18n.format("ActiveEffects.appliedEffect",{target:g.token?.name||g.name,source:z.join(", ")})}${y||""}`;await ChatMessage.create(f.chatDataSetup(S))}h.length&&await this.createResistRollMessage(h,e,t)}else game.socket.emit("system.dsa5",{type:"addEffect",payload:{mode:t,id:e,actors:p.map(g=>({token:g.token?g.token.id:void 0,actor:g.id,scene:canvas.scene.id}))}})}static async createResistRollMessage(e,t,a){for(let s of e){let i=await renderTemplate("systems/dsa5/templates/chat/roll/resist-roll.html",{resist:s,id:t,mode:a});await ChatMessage.create(f.chatDataSetup(i))}}static async _parseEffectDuration(e,t,a,s){let i={};for(let m of a.situationalModifiers.filter(d=>d.specAbId))i[m.specAbId]=m.step;let n=Object.keys(i),r=s?s.items.filter(m=>n.includes(m.id)):[],o=e.effects?duplicate(e.effects):[];for(let m of r){let d=duplicate(m).effects;for(let p of d)setProperty(p,"flags.dsa5.specStep",i[m.id]);o.push(...d)}let c=getProperty(e,"system.duration.value")||"";c=c.replace(/ x /g," * ").replace(game.i18n.localize("CHARAbbrev.QS"),t.qualityStep);try{for(let m of Q.effectDurationRegexes)if(m.regEx.test(c)){let d=c.replace(m.regEx,"").trim(),p=await _DiceDSA5._stringToRoll(d);if(!isNaN(p))for(let g of o){let y=p*m.seconds,h=getProperty(g,"flags.dsa5.customDuration");if(h){let w=h.split(",")[t.qualityStep-1];w&&w!="-"&&(y=Number(w))}g.duration.seconds=y,g.duration.rounds=g.duration.seconds/5}break}}catch{console.error(`Could not parse duration '${c}' of '${e.name}'`)}return o}dropDownMenu(){let e=game.i18n.localize("MODS.FW"),t=game.i18n.localize("skill"),a=game.i18n.localize("regenerate"),s=game.i18n.localize("MODS.FP"),i=game.i18n.localize("stepValue"),n=game.i18n.localize("MODS.QS"),r=game.i18n.localize("MODS.partChecks"),o=`${game.i18n.localize("LocalizedIDs.perception")} 1`,c=`${game.i18n.localize("LocalizedIDs.wrestle")} 1`,m=game.i18n.localize("closeCombatAttacks"),d=game.i18n.localize("rangeCombatAttacks"),p=`${a} (${game.i18n.localize("CHARAbbrev.CR")})`,g=game.i18n.localize("AsPCost"),y=game.i18n.localize("KaPCost"),h=game.i18n.localize("permanentCost"),w=`${game.i18n.localize("Healing")} 1`,z=`${game.i18n.localize("Description")} 1`,v=`${game.i18n.localize("LocalizedIDs.miracle")}`,S=[{name:game.i18n.localize("protection"),val:"system.totalArmor",mode:2,ph:"1"},{name:game.i18n.localize("liturgyArmor"),val:"system.liturgyArmor",mode:2,ph:"1"},{name:`${game.i18n.localize("resistanceModifier")} (${game.i18n.localize("condition")})`,val:"system.resistances.effects",mode:0,ph:"inpain 1"},{name:game.i18n.localize("spellArmor"),val:"system.spellArmor",mode:2,ph:"1"},{name:game.i18n.localize("carrycapacity"),val:"system.carryModifier",mode:2,ph:"1"},{name:`${m} - ${game.i18n.localize("CHARAbbrev.AT")}`,val:"system.meleeStats.attack",mode:2,ph:"1"},{name:`${m} - ${game.i18n.localize("CHARAbbrev.PA")}`,val:"system.meleeStats.parry",mode:2,ph:"1"},{name:`${v} - ${game.i18n.localize("CHARAbbrev.AT")}`,val:"system.miracle.attack",mode:2,ph:"1"},{name:`${v} - ${game.i18n.localize("CHARAbbrev.PA")}`,val:"system.miracle.parry",mode:2,ph:"1"},{name:`${m} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.meleeStats.damage",mode:2,ph:"1d6"},{name:`${m} - ${game.i18n.localize("MODS.defenseMalus")}`,val:"system.meleeStats.defenseMalus",mode:2,ph:"1"},{name:game.i18n.localize("MODS.creatureBonus"),val:"system.creatureBonus",mode:0,ph:`${game.i18n.localize("CONJURATION.elemental")} 1`},{name:`${d} - ${game.i18n.localize("CHARAbbrev.AT")}`,val:"system.rangeStats.attack",mode:2,ph:"1"},{name:`${d} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.rangeStats.damage",mode:2,ph:"1d6"},{name:`${d} - ${game.i18n.localize("MODS.defenseMalus")}`,val:"system.rangeStats.defenseMalus",mode:2,ph:"1"},{name:`${game.i18n.localize("spell")} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.spellStats.damage",mode:2,ph:"1"},{name:`${game.i18n.localize("liturgy")} - ${game.i18n.localize("CHARAbbrev.damage")}`,val:"system.liturgyStats.damage",mode:2,ph:"1"},{name:y,val:"system.kapModifier",mode:2,ph:"1"},{name:g,val:"system.aspModifier",mode:2,ph:"1"},{name:`${h} ${game.i18n.localize("CHARAbbrev.AsP")}`,val:"system.status.astralenergy.permanentGear",mode:2,ph:"1"},{name:`${h} ${game.i18n.localize("CHARAbbrev.KaP")}`,val:"system.status.astralenergy.permanentGear",mode:2,ph:"1"},{name:`${t} - ${e}`,val:"system.skillModifiers.FW",mode:0,ph:o},{name:`${t} - ${s}`,val:"system.skillModifiers.FP",mode:0,ph:o},{name:`${t} - ${i}`,val:"system.skillModifiers.step",mode:0,ph:o},{name:`${t} - ${n}`,val:"system.skillModifiers.QL",mode:0,ph:o},{name:`${t} - ${r}`,val:"system.skillModifiers.TPM",mode:0,ph:o},{name:`${game.i18n.localize("vulnerability")} - ${game.i18n.localize("combatskill")}`,val:"system.vulnerabilities.combatskill",mode:0,ph:c},{name:`${t} - ${game.i18n.localize("MODS.global")}`,val:"system.skillModifiers.global",mode:0,ph:"1"},{name:`${p} - ${game.i18n.localize("wounds")}`,val:"system.repeatingEffects.startOfRound.wounds",mode:0,ph:"1d6"},{name:`${p} - ${game.i18n.localize("astralenergy")}`,val:"system.repeatingEffects.startOfRound.astralenergy",mode:0,ph:"1d6"},{name:`${p} - ${game.i18n.localize("karmaenergy")}`,val:"system.repeatingEffects.startOfRound.karmaenergy",mode:0,ph:"1d6"},{name:`${a} - ${game.i18n.localize("wounds")}`,val:"system.status.regeneration.LePgearmodifier",mode:2,ph:"1"},{name:`${a} - ${game.i18n.localize("astralenergy")}`,val:"system.status.regeneration.AsPgearmodifier",mode:2,ph:"1"},{name:`${a} - ${game.i18n.localize("karmaenergy")}`,val:"system.status.regeneration.KaPgearmodifier",mode:2,ph:"1"},{name:`${game.i18n.localize("feature")} - ${g}`,val:"system.skillModifiers.feature.AsPCost",mode:0,ph:w},{name:`${game.i18n.localize("advanced")} - ${g}`,val:"system.skillModifiers.conditional.AsPCost",mode:0,ph:z},{name:`${game.i18n.localize("feature")} - ${y}`,val:"system.skillModifiers.feature.KaPCost",mode:0,ph:w},{name:`${game.i18n.localize("advanced")} - ${y}`,val:"system.skillModifiers.conditional.KaPCost",mode:0,ph:z},{name:`${game.i18n.localize("MODS.sight")}`,val:"system.sightModifier.value",mode:2,ph:"-1"},{name:`${game.i18n.localize("MODS.sightMax")}`,val:"system.sightModifier.maxLevel",mode:5,ph:"4"},{name:`${game.i18n.localize("LocalizedIDs.immuneTo")} ${game.i18n.localize("condition")}`,val:"system.immunities",mode:2,ph:"feared"},{name:game.i18n.localize("temperature.heatProtection"),val:"system.temperature.heatProtection",mode:2,ph:"1"},{name:game.i18n.localize("temperature.coldProtection"),val:"system.temperature.coldProtection",mode:2,ph:"1"}],x=["liturgy","ceremony","spell","ritual","skill","feature"];for(let F of x){let N=F=="skill"?"skillglobal":F,D=game.i18n.localize(N);S.push({name:`${D} - ${e}`,val:`system.skillModifiers.${F}.FW`,mode:0,ph:o},{name:`${D} - ${s}`,val:`system.skillModifiers.${F}.FP`,mode:0,ph:o},{name:`${D} - ${i}`,val:`system.skillModifiers.${F}.step`,mode:0,ph:o},{name:`${D} - ${n}`,val:`system.skillModifiers.${F}.QL`,mode:0,ph:o},{name:`${D} - ${r}`,val:`system.skillModifiers.${F}.TPM`,mode:0,ph:o})}for(let F of CONFIG.statusEffects)getProperty(F,"flags.dsa5.max")&&S.push({name:game.i18n.localize(F.name),val:`system.condition.${F.id}`,mode:2,ph:1});for(let F of Object.keys(b.characteristics))S.push({name:game.i18n.localize(`CHAR.${F.toUpperCase()}`),val:`system.characteristics.${F}.gearmodifier`,mode:2,ph:"1"});for(let F of b.gearModifyableCalculatedAttributes)S.push({name:game.i18n.localize(F),val:`system.status.${F}.gearmodifier`,mode:2,ph:"1"});for(let F of["spell","liturgy","ceremony","ritual"]){let N=f.categoryLocalization(F);for(let D of["soulpower","toughness"])S.push({name:`${game.i18n.localize(D)} (${N})`,val:`system.status.${D}.${F}resist`,mode:2,ph:"1"});for(let D of Object.keys(le.rollModifiers))S.push({name:`${N} - ${game.i18n.localize(D.replace("Spell",""))}`,val:`system.${F}RollModifiers.${D}.mod`,mode:2,ph:"1"},{name:`${N} - ${game.i18n.localize(D.replace("Spell",""))} - ${game.i18n.localize("advanced")}`,val:`system.${F}RollModifiers.${D}.custom`,mode:0,ph:z})}S=S.sort((F,N)=>F.name.localeCompare(N.name));for(let F of S)(!F.ph||F.mode==null)&&console.warn(F);return S=S.map(F=>``).join(` +`),``}activateListeners(e){super.activateListeners(e);let t=this.dropDownMenu();e.find(".changes-list .effect-change .key").append(t),e.find(".selMenu").select2({width:"element"}).change(a=>{let s=$(a.currentTarget);s.siblings("input").val(s.val());let i=s.closest(".effect-change"),n=s.find("option:selected");i.find(".mode select").val(n.attr("data-mode")),i.find(".value input").attr("placeholder",n.attr("data-ph")),s.trigger("blur")}),e.find(".select2").each((a,s)=>{$(s)[0].style.removeProperty("width")})}};u(Q,"DSAActiveEffectConfig");var qa=class{static async createTokenHook(e,t,a){if(!f.isActiveGM())return;let s=e.parent;if(this.isRiding(e.actor)&&s.active){let i=this.getHorse(e.actor);if(!i)return;let n=await i.getTokenDocument();n.updateSource({x:e.x,y:e.y,hidden:e.hidden});let r=(await s.createEmbeddedDocuments("Token",[n]))[0],o={"flags.dsa5.horseTokenId":r.id,elevation:(r.elevation??0)+1};mergeObject(o,this.adaptTokenSize(e,r)),await e.update(o),r.actorLink||await e.actor.update({"system.horse.actorLink":!1,"system.horse.token":{scene:s.id,token:r.id}})}}static isRiding(e){return getProperty(e,"system.horse.isRiding")}static updateTokenHook(e,t,a){if(!f.isActiveGM())return;let s=getProperty(e,"flags.dsa5.horseTokenId"),i=e.parent;s&&i.active&&(t.x||t.y)&&this.isRiding(e.actor)&&i.updateEmbeddedDocuments("Token",[{_id:s,x:e.x,y:e.y}])}static rollLoyalty(e,t={}){let a=this.getHorse(e);if(!a)return;let s=this.getLoyaltyFromHorse(a);if(!s)return ui.notifications.warn(game.i18n.format("DSAError.notFound",{category:f.categoryLocalization("skill"),name:game.i18n.localize("LocalizedIDs.loyalty")}));a.setupSkill(s,t,a.token?.id).then(i=>{a.basicTest(i)})}static async updateRiderSpeed(e,t){if(!canvas?.tokens?.documentCollection)return;let a=e.getActiveTokens().map(s=>s.id);for(let s of Array.from(canvas.tokens.documentCollection))a.includes(s.getFlag("dsa5","horseTokenId"))&&t!=s.actor.system.status.speed.max&&(s.actor.prepareData(),s.actor.sheet.render())}static getLoyaltyFromHorse(e){return e.items.find(t=>t.type=="skill"&&t.name.startsWith(game.i18n.localize("LocalizedIDs.loyalty")))}static activateListeners(e,t){e.find(".riding-toggle").click(()=>this.toggleIsRiding(t)),e.find(".showHorse").click(()=>this.getHorse(t).sheet.render(!0)),e.find(".horse-delete").click(()=>this.clearMount(t)),e.find(".horse-loyalty").click(()=>this.rollLoyalty(t)),e.find('[name="horseSpeedSelector"]').change(async a=>{a.preventDefault();let s=qa.getHorse(t);qa.setSpeed(s,a.currentTarget.value)})}static async toggleIsRiding(e){await e.update({"system.horse.isRiding":!e.system.horse?.isRiding});let t=[];if(e.system.horse.isRiding){let a=this.getHorse(e),s;for(let i of a.getActiveTokens())t.push({_id:i.document.id,["flags.dsa5.-=horseTokenId"]:null}),s=i.document.id;for(let i of e.getActiveTokens())t.push({_id:i.document.id,elevation:Math.max(0,(i.elevation??0)+1),"flags.dsa5.horseTokenId":s});await this.addRidingCondition(e)}else{for(let a of e.getActiveTokens())t.push({_id:a.document.id,["flags.dsa5.-=horseTokenId"]:null,elevation:Math.max(0,(a.elevation??0)-1)});await this.removeRidingCondition(e)}await canvas.scene.updateEmbeddedDocuments("Token",t,{noHooks:!0})}static getRidingCondition(e){let t=game.i18n.localize("RIDING.riding");return e.effects.find(a=>a.name==t)}static async addRidingCondition(e){this.getRidingCondition(e)||await e.addCondition(this.ridingCondition())}static async removeRidingCondition(e){let t=this.getRidingCondition(e);t&&await e.deleteEmbeddedDocuments("ActiveEffect",[t.id])}static deleteTokenHook(){console.warn("delete riding token hook not implemented")}static getHorse(e,t=!1){let a;return e.system.horse&&(e.system.horse.token&&!e.system.horse.actorLink?a=f.getSpeaker(e.system.horse.token):a=game.actors.get(e.system.horse.actorId),!a&&t&&e.system.horse.isRiding&&(a={name:game.i18n.localize("unknown")})),a}static async unmountHorse(e,t){let a={["flags.dsa5.-=horseTokenId"]:null,elevation:Math.max(0,(t.elevation??0)-1)},s=t.getFlag("dsa5","horseResized");s&&mergeObject(a,{["flags.dsa5.-=horseResized"]:null,width:s.width,height:s.height}),await this.clearMount(e),await t.update(a)}static async clearMount(e){await e.update({system:{horse:{isRiding:!1,actorLink:!1,actorId:"","-=token":null}}}),await this.removeRidingCondition(e)}static ridingCondition(){return{name:game.i18n.localize("RIDING.riding"),icon:"systems/dsa5/icons/thirdparty/horse-head.svg",changes:[{key:"system.status.dodge.gearmodifier",mode:2,value:-2}],flags:{dsa5:{description:game.i18n.localize("RIDING.ridingDescription")}}}}static async setHorse(e,t){let a={system:{horse:{isRiding:!0,actorLink:t.prototypeToken.actorLink,actorId:t.id}}};!t.prototypeToken.actorLink&&t.token&&mergeObject(a,{system:{horse:{token:{scene:canvas.scene.id,token:t.token.id}}}}),await e.update(a),t.isToken&&await canvas.scene.updateEmbeddedDocuments("Token",e.getActiveTokens().map(s=>({_id:s.id,"flags.dsa5.horseTokenId":t.token.id,x:t.token.x,y:t.token.y})).concat({_id:t.token.id,["flags.dsa5.-=horseTokenId"]:null}),{noHooks:!0}),await this.addRidingCondition(e)}static adaptTokenSize(e,t){return e.width>=t.width?{width:.7*t.width,height:.7*t.height,"flags.dsa5.horseResized":{width:e.width,height:e.height}}:{}}static async mountHorse(e){let t=canvas.tokens.controlled.find(n=>n.document.id!=e.id),a=e.parent,s={system:{horse:{isRiding:!0,actorLink:t.actorLink,actorId:t.actor.id}}};t.actorLink||mergeObject(s,{system:{horse:{token:{scene:a.id,token:t.id}}}});let i={_id:e.id,"flags.dsa5.horseTokenId":t.id,x:t.x,y:t.y,elevation:(t.document.elevation??0)+1};mergeObject(i,this.adaptTokenSize(e.document,t.document)),await e.actor.update(s),await canvas.scene.updateEmbeddedDocuments("Token",[i,{_id:t.id,["flags.dsa5.-=horseTokenId"]:null}],{noHooks:!0}),await this.addRidingCondition(e.actor)}static getHorseSpeed(e){return e.effects.find(t=>getProperty(t,"flags.dsa5.horseSpeed"))?.flags.dsa5.horseSpeed||0}static horseSpeedModifier(e){let t=this.getHorseSpeed(e);return Object.keys(this.speedKeys).map(a=>Number(a)).indexOf(Number(t))}static increaseSpeed(e){let t=this.getHorseSpeed(e),a=Math.min(3,Object.keys(this.speedKeys).map(s=>Number(s)).indexOf(t)+1);this.setSpeed(e,Object.keys(this.speedKeys).map(s=>Number(s))[a])}static decreaseSpeed(e){let t=this.getHorseSpeed(e),a=Math.max(0,Object.keys(this.speedKeys).map(s=>Number(s)).indexOf(t)-1);this.setSpeed(e,Object.keys(this.speedKeys).map(s=>Number(s))[a])}static async setSpeed(e,t){await e.deleteEmbeddedDocuments("ActiveEffect",e.effects.filter(a=>hasProperty(a,"flags.dsa5.horseSpeed")).map(a=>a.id)),await e.addCondition({name:game.i18n.localize("speed")+": "+game.i18n.localize(`RIDING.speeds.${t}`),icon:"systems/dsa5/icons/thirdparty/horse-head.svg",changes:[this.speedKeys[t]],flags:{dsa5:{description:game.i18n.localize(`RIDING.speed.${t}`),horseSpeed:t}}})}static renderTokenHUD(e,t,a){let s=e.object.actor;if(canvas.tokens.controlled.length==2)t.find(".col.left").prepend(this.preRenderedMountHud),t.find('.control-icon[data-action="ride"]').click(()=>this.mountHorse(e.object));else if(this.isRiding(s)){t.find(".col.left").prepend(this.preRenderedUnmountHud);let i=t.find('.control-icon[data-action="ride"]');i.click(()=>{this.unmountHorse(s,e.object.document),i.remove()});let n=this.getHorse(s);t.find(".col.right").prepend(this.preRenderedSpeedHud),t.find('.control-icon[data-action="rideIncrease"]').click(()=>this.increaseSpeed(n)),t.find('.control-icon[data-action="rideDecrease"]').click(()=>this.decreaseSpeed(n))}}},H=qa;u(H,"Riding"),L(H,"preRenderedUnmountHud",`
    `),L(H,"preRenderedMountHud",'
    '),L(H,"preRenderedSpeedHud",`
    - `),L(H,"speedKeys",{0:{key:"system.status.speed.multiplier",mode:5,value:0},"-4":{key:"system.status.speed.initial",mode:5,value:4},"-5000":{key:"system.status.speed.multiplier",mode:5,value:.66},"-8":{key:"system.status.speed.multiplier",mode:5,value:1}});var he=class extends Item{static defaultIcon(e){(!e.img||e.img=="")&&(e.type in this.defaultImages?e.img=this.defaultImages[e.type]:e.img="systems/dsa5/icons/blank.webp")}static async create(e,t){return this.defaultIcon(e),await super.create(e,t)}static getSpecAbModifiers(e,t){let a=[];for(let s of e.find(".specAbs")){let i=Number($(s).attr("data-step"));if(i>0){let r=t=="attack"?$(s).attr("data-atbonus"):$(s).attr("data-pabonus"),n=r.split(",").reduce((o,c)=>o+Number(c),0);a.push({name:$(s).find("a").text(),value:isNaN(n)?Number(r.replace("*","")):Number(n)*i,damageBonus:$(s).attr("data-tpbonus"),dmmalus:$(s).attr("data-dmmalus")*i,step:i,specAbId:$(s).attr("data-id"),type:/^\*/.test(r)?"*":void 0})}}return a}static setupSubClasses(){game.dsa5.config.ItemSubclasses={ritual:os,spell:We,liturgy:Wt,ceremony:es,advantage:Ut,disadvantage:Ut,aggregatedTest:Ya,trait:us,blessing:Za,magictrick:qt,specialability:cs,disease:is,poison:ns,armor:Xa,rangeweapon:wt,meleeweapon:kt,ammunition:Ja,equipment:rs,combatskill:ts,skill:vt,application:ls,consumable:as,spellextension:ms,species:ds,effectwrapper:Qa,plant:Wa,magicalsign:Ua,patron:Ka,demonmark:Va,information:ss}}static buildSpeaker(e,t){return{token:t,actor:e?.id,scene:canvas.scene?.id}}static parseValueType(e,t){let a="";return/^\*/.test(t)&&(a="*",t=t.substring(1).replace(",",".")),{name:e,value:Number(t),type:a}}async addCondition(e,t=1,a=!1,s=!0){return await E.addCondition(this,e,t,a,s)}async removeCondition(e,t=1,a=!0,s=!1){return E.removeCondition(this,e,t,a,s)}hasCondition(e){return E.hasCondition(this,e)}static getMiracleModifiers(e,t,a,s){let i=new RegExp(`${game.i18n.localize("combatskill")} `,"gi"),r=(getProperty(e,"system.happyTalents.value")||"").split(/;|,/).map(o=>o.replace(i,"").trim()),n=[];if(r.includes(t.name)){let o=e.system.status.karmaenergy.value,c=getProperty(e,`system.miracle.${s}`)||0;if(o<4)return[];n.push({name:game.i18n.localize("LocalizedIDs.miracle"),value:2+c,type:a,selected:!1});let m=game.i18n.localize("LocalizedIDs.miracleMight");o>=6&&R.hasAbility(e,m)&&n.push({name:m,value:3+c,type:a,selected:!1})}return n}static getSkZkModifier(e,t){let a=[],s=[],i=["spell","liturgy","ceremony","ritual"].includes(t.type)&&t.system.effectFormula.value.trim()=="";game.user.targets.size&&game.user.targets.forEach(r=>{if(r.actor){let n=0;i&&(n=I.detectCreatureType(r.actor).reduce((d,p)=>d+p.spellResistanceModifier(r.actor),0));let o=getProperty(r.actor,`system.status.soulpower.${t.type}resist`)||0,c=getProperty(r.actor,`system.status.toughness.${t.type}resist`)||0;a.push((r.actor.system.status.soulpower.max+o)*-1-n),s.push((r.actor.system.status.toughness.max+c)*-1-n)}}),mergeObject(e,{SKModifier:a.length>0?Math.min(...a):0,ZKModifier:s.length>0?Math.min(...s):0})}static async _onCreateDocuments(e,t){for(let a of e)a.actor&&await T.postUpdateConditions(a.actor);return super._onCreateDocuments(e,t)}static async _onUpdateDocuments(e,t){for(let a of e)a.actor&&await T.postUpdateConditions(a.actor);return super._onUpdateDocuments(e,t)}static async _onDeleteDocuments(e,t){for(let a of e)a.actor&&await T.postUpdateConditions(a.actor);return super._onDeleteDocuments(e,t)}static parseEffect(e,t){let a={},s=new RegExp(game.i18n.localize("CHARAbbrev.GS"),"gi");for(let i of e.split(/,|;/).map(r=>r.trim())){let r=i.replace(/(\s+)/g," ").trim().split(" ");r[0]=r[0].replace(s,t.system.status.speed.max),r.length==2&&(!isNaN(r[0])||/(=)?[+-]\d([+-]\d)?/.test(r[0])||/(=)?\d[dDwW]\d/.test(r[0])||/=\d+/.test(r[0])||/\*\d(\.\d)*/.test(r[0]))&&(a[r[1].toLowerCase()]==null?a[r[1].toLowerCase()]=[r[0]]:a[r[1].toLowerCase()].push(r[0]))}return a}static getDefenseMalus(e,t){let a=!1;if(t.flags.oppose){let s=game.messages.get(t.flags.oppose.messageId),i=s.flags.data.preData;a=!(getProperty(i,"source.type")=="meleeweapon"||getProperty(i,"source.system.traitType.value")=="meleeAttack");let r=/ \[(-)?\d{1,}\]/;for(let n of i.situationalModifiers)n.dmmalus!=null&&n.dmmalus!=0?e.push({name:`${game.i18n.localize("MODS.defenseMalus")} - ${n.name.replace(r,"")}`,value:n.dmmalus,selected:!0}):n.type=="defenseMalus"&&n.value!=0&&e.push({name:n.name.replace(r,""),value:n.value,selected:!0});s.flags.data.postData.halfDefense&&e.push({name:`${game.i18n.localize("MODS.defenseMalus")} - ${game.i18n.localize("halfDefenseShort")}`,value:.5,type:"*",selected:!0})}return a}static changeChars(e,t,a,s){e.system.characteristic1.value=t,e.system.characteristic2.value=a,e.system.characteristic3.value=s}static attackSpecAbs(e,t,a="effect.value"){let s=game.i18n.localize("LocalizedAbilityModifiers.at"),i=game.i18n.localize("LocalizedAbilityModifiers.tp"),r=game.i18n.localize("LocalizedAbilityModifiers.dm"),n=[];for(let o of e){let c=he.parseEffect(getProperty(o.system,a),t),m=c[s]||0,d=c[i]||0,p=c[r]||0,g=["","2","3"].map(y=>getProperty(o,`system.effect.value${y}`)).filter(y=>y).length;if(m!=0||d!=0||p!=0||o.effects.size>0){let y=game.i18n.localize(b.combatSkillSubCategories[o.system.category.sub]);n.push({name:o.name,atbonus:m,tpbonus:d,dmmalus:p,label:`${s.toUpperCase()}: ${m}, ${i.toUpperCase()}: ${d}, ${r.toUpperCase()}: ${p}`,steps:o.system.step.value,category:{id:o.system.category.sub,css:`ab_${o.system.category.sub}`,name:y},id:o.id,actor:t.id,variantCount:g})}}return n}static defenseSpecAbs(e,t,a="effect.value"){let s=[],i=game.i18n.localize("LocalizedAbilityModifiers.pa");for(let r of e){let o=he.parseEffect(getProperty(r.system,a),t)[i]||0;if(o!=0){let c=game.i18n.localize(b.combatSkillSubCategories[r.system.category.sub]),m=["","2","3"].map(d=>getProperty(r,`system.effect.value${d}`)).filter(d=>d).length;s.push({name:r.name,pabonus:o,tpbonus:0,dmmalus:0,label:`${i}: ${o}`,steps:r.system.step.value,category:{id:r.system.category.sub,css:`ab_${r.system.category.sub}`,name:c},id:r.id,actor:t.id,variantCount:m})}}return s}static buildCombatSpecAbs(e,t,a,s){let i;a?(a.push(game.i18n.localize("LocalizedIDs.all")),a=a.map(o=>o.toLowerCase()),i=u((o,c)=>o.system.list.value.split(/;|,/).map(m=>m.trim().toLowerCase()).filter(m=>c.includes(m.replace(/ \([a-zA-Z äüöÄÖÜ]*\)/,""))).length>0,"searchFilter")):i=u(()=>!0,"searchFilter");let r=game.combat?.isBrawling?()=>!0:o=>Number(o.system.category.sub)!=5,n=e.items.filter(o=>o.type=="specialability"&&t.includes(o.system.category.value)&&o.system.effect.value!=""&&i(o,a)&&r(o));return s=="attack"?this.attackSpecAbs(n,e):this.defenseSpecAbs(n,e)}static getCombatSkillModifier(e,t,a){if(t.type=="trait")return;let s=e.items.find(i=>i.type=="combatskill"&&i.name==t.system.combatskill.value);for(let i of s.effects)for(let r of i.changes)switch(r.key){case"system.rangeStats.defenseMalus":case"system.meleeStats.defenseMalus":a.push({name:`${s.name} - ${game.i18n.localize("MODS.defenseMalus")}`,value:r.value*-1,type:"defenseMalus",selected:!0});break}}static attackStatEffect(e,t){t!=0&&(t=isNaN(t)?t:Number(t),e.push({name:game.i18n.localize("statuseffects"),value:t,selected:!0}))}static getTargetSizeAndModifier(e,t,a){let s="average";return game.user.targets.forEach(i=>{if(i.actor){let r=getProperty(i.actor,"system.status.size.value");r&&(s=r),I.addCreatureTypeModifiers(i.actor,t,a,e)}}),s}static prepareRangeAttack(e,t,a,s,i,r,n=void 0){e.push(...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.restrictedSenseSight"),-2)),this.getCombatSkillModifier(t,s,e);let o=this.getTargetSizeAndModifier(t,s,e),c=Number(t.system.rangeStats.defenseMalus)*-1;c!=0&&e.push({name:`${game.i18n.localize("statuseffects")} - ${game.i18n.localize("MODS.defenseMalus")}`,value:c,type:"defenseMalus",selected:!0});let m={...b.rangeWeaponModifiers};delete m[O.hasVantage(t,game.i18n.localize("LocalizedIDs.senseOfRange"))?"long":"rangesense"],R.hasAbility(t,game.i18n.localize("LocalizedIDs.extremeShot"))||delete m.extreme;let d=R.hasAbility(t,game.i18n.localize("LocalizedIDs.drivingArcher")),p=R.hasAbility(t,game.i18n.localize("LocalizedIDs.mountedArcher")),g;p&&H.isRiding(t)?g=duplicate(b.mountedRangeOptionsSpecAb):d?g=duplicate(b.drivingArcherOptions):g=duplicate(b.mountedRangeOptions),this.swarmModifiers(t,"attack",e),mergeObject(a,{rangeOptions:m,rangeDistance:Object.keys(m)[J.distanceModifier(game.canvas.tokens.get(i),s,n)],sizeOptions:b.rangeSizeCategories,visionOptions:b.rangeVision,mountedOptions:g,shooterMovementOptions:b.shooterMovementOptions,targetMovementOptions:b.targetMomevementOptions,targetSize:o,combatSpecAbs:r,aimOptions:b.aimOptions})}static swarmModifiers(e,t,a){e.system.swarm?.count>1&&(t=="attack"?a.push({name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("MODS.defenseMalus")}`,value:e.system.swarm.parry,type:"defenseMalus",selected:!0},{name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("CHARAbbrev.AT")}`,value:e.system.swarm.attack,selected:!0},{name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("CHARAbbrev.damage")}`,value:e.system.swarm.damage,type:"dmg",selected:!0}):a.push({name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("CHARAbbrev.PA")}`,value:e.system.swarm.parry,selected:!0}))}static prepareMeleeAttack(e,t,a,s,i,r){let n="short";game.user.targets.forEach(m=>{if(m.actor){for(let d of m.actor.items)if((d.type=="meleeweapon"&&d.system.worn.value||d.type=="trait"&&d.system.traitType.value=="meleeAttack"&&d.system.pa)&&(b.meleeRangesArray.indexOf(d.system.reach.value)>b.meleeRangesArray.indexOf(n)&&(n=d.system.reach.value),n=="long"))break}});let o=this.getTargetSizeAndModifier(t,s,e);this.getCombatSkillModifier(t,s,e);let c=Number(t.system.meleeStats.defenseMalus)*-1;c!=0&&e.push({name:`${game.i18n.localize("statuseffects")} - ${game.i18n.localize("MODS.defenseMalus")}`,value:c,type:"defenseMalus",selected:!0}),this.swarmModifiers(t,"attack",e),mergeObject(a,{visionOptions:b.meleeRangeVision(a.mode),weaponSizes:b.meleeRanges,melee:!0,showAttack:!0,targetWeaponSize:n,combatSpecAbs:i,meleeSizeOptions:b.meleeSizeCategories,targetSize:o,constricted:t.hasCondition("constricted"),wrongHandDisabled:r,offHand:!r&&getProperty(s,"system.worn.offHand")})}static prepareMeleeParry(e,t,a,s,i,r){let n=he.getDefenseMalus(e,t);this.swarmModifiers(t,"parry",e),mergeObject(a,{visionOptions:b.meleeRangeVision(a.mode),showDefense:!0,isRangeDefense:n,wrongHandDisabled:r&&getProperty(s,"system.worn.offHand"),offHand:!r&&getProperty(s,"system.worn.offHand")&&!P.isShield(s),melee:!0,combatSpecAbs:i,constricted:t.hasCondition("constricted")})}static _chatLineHelper(e,t){return`${game.i18n.localize(e)}: ${t||"-"}`}static setupDialog(e,t,a,s,i){return null}setupEffect(e,t={},a){return he.getSubClass(this.type).setupDialog(e,t,this,a)}static checkEquality(e,t){return t.type==e.type&&e.name==t.name&&e.system.description?.value==t.system.description?.value}static async combineItem(e,t,a){return e=duplicate(e),e.system.quantity.value+=t.system.quantity.value,await a.updateEmbeddedDocuments("Item",[e])}static areEquals(e,t){return e.type!=t.type||e.id==t.id?!1:he.getSubClass(e.type).checkEquality(e,t)}static async stackItems(e,t,a){return await he.getSubClass(e.type).combineItem(e,t,a)}_setupCardOptions(e,t,a){let s=ChatMessage.getSpeaker();return{speaker:{alias:s.alias,scene:s.scene},flags:{img:s.token?canvas.tokens.get(s.token).document.img:this.img},title:t,template:e}}async itemTest({testData:e,cardOptions:t},a={}){e=await _DiceDSA5.rollDices(e,t);let s=await _DiceDSA5.rollTest(e);if(s.postFunction="itemTest",game.user.targets.size){t.isOpposedTest=e.opposable;let i=` - ${game.i18n.localize("Opposed")}`;t.isOpposedTest&&t.title.match(i+"$")!=i&&(t.title+=i)}return a.suppressMessage||_DiceDSA5.renderRollCard(t,s,a.rerenderMessage),{result:s,cardOptions:t}}static chatData(e,t){return[]}static getSubClass(e){return game.dsa5.config.ItemSubclasses[e]||he}async postItem(){he.getSubClass(this.type)._postItem(this)}static async _postItem(e){let t=duplicate(e),a=getProperty(t,"system.obfuscation.details"),s=getProperty(t,"system.obfuscation.description");if(mergeObject(t,{properties:a?[]:he.getSubClass(e.type).chatData(duplicate(t.system),e.name),descriptionObfuscated:s}),t.hasPrice="price"in t.system&&!a,t.hasPrice){let n=t.system.price.value;t.system.QL&&(n=he.getSubClass(t.type).consumablePrice(t)),t.system.price.D=Math.floor(n/10),n-=t.system.price.D*10,t.system.price.S=Math.floor(n),n-=t.system.price.S,t.system.price.H=Math.floor(n/.1),n-=t.system.price.H*.1,t.system.price.K=Math.round(n/.01);let o=["D","S","H","K"].map(c=>`${t.system.price[c]}
    `).join(",");t.properties.push(`${game.i18n.localize("price")}: ${o}`)}e.pack&&(t.itemLink=e.link),t.img.includes("/blank.webp")&&(t.img=null);let i=await renderTemplate("systems/dsa5/templates/chat/post-item.html",t),r=f.chatDataSetup(i);ChatMessage.create(r)}},A=he;u(A,"Itemdsa5"),L(A,"defaultImages",{advantage:"systems/dsa5/icons/categories/Vorteil.webp",disadvantage:"systems/dsa5/icons/categories/Nachteil.webp",armor:"systems/dsa5/icons/categories/Armor.webp",meleeweapon:"systems/dsa5/icons/categories/Meleeweapon.webp",rangeweapon:"systems/dsa5/icons/categories/Rangeweapon.webp",equipment:"systems/dsa5/icons/categories/Equipment.webp",consumable:"systems/dsa5/icons/categories/consumable.webp",liturgy:"systems/dsa5/icons/categories/Liturgy.webp",spell:"systems/dsa5/icons/categories/Spell.webp",ammunition:"systems/dsa5/icons/categories/Munition.webp",career:"systems/dsa5/icons/categories/Career.webp",magictrick:"systems/dsa5/icons/categories/Spelltrick.webp",blessing:"systems/dsa5/icons/categories/Blessing.webp",combatskill:"systems/dsa5/icons/categories/Combat_Skill.webp",skill:"systems/dsa5/icons/categories/Skill.webp",Geweihte:"systems/dsa5/icons/categories/Geweihte.webp",Weltliche:"systems/dsa5/icons/categories/Weltliche.webp",Zauberer:"systems/dsa5/icons/categories/Zauberer.webp",ritual:"systems/dsa5/icons/categories/ritual.webp",ceremony:"systems/dsa5/icons/categories/ceremony.webp",abilityclerical:"systems/dsa5/icons/categories/ability_clerical.webp",abilityCombat:"systems/dsa5/icons/categories/ability_combat.webp",abilityfatePoints:"systems/dsa5/icons/categories/ability_fate_points.webp",abilitygeneral:"systems/dsa5/icons/categories/ability_general.webp",specialability:"systems/dsa5/icons/categories/ability_general.webp",abilitymagical:"systems/dsa5/icons/categories/ability_magical.webp",abilitylanguage:"systems/dsa5/icons/categories/Ability_Language.webp",abilitystaff:"systems/dsa5/icons/categories/ability_staff.webp",abilityceremonial:"systems/dsa5/icons/categories/ability_ceremonial.webp",abilityanimal:"systems/dsa5/icons/categories/ability_animal.webp",trait:"systems/dsa5/icons/categories/trait.webp",Tiere:"systems/dsa5/icons/categories/Tiere.webp",aggregatedTest:"systems/dsa5/icons/categories/aggregated_test.webp",poison:"systems/dsa5/icons/categories/poison.webp",disease:"systems/dsa5/icons/categories/disease.webp",spellextension:"systems/dsa5/icons/categories/Spellextension.webp",species:"icons/environment/people/group.webp",application:"systems/dsa5/icons/categories/Skill.webp",trick:"systems/dsa5/icons/categories/Tiere.webp",disadvantageanimal:"systems/dsa5/icons/categories/NachteilAnimal.webp",advantageanimal:"systems/dsa5/icons/categories/VorteilAnimal.webp",diseaseanimal:"systems/dsa5/icons/categories/diseaseAnimal.webp",effectwrapper:"icons/svg/aura.svg",liturgyTalisman:"systems/dsa5/icons/categories/LiturgieTalisman.webp",plant:"systems/dsa5/icons/categories/plant.webp",magicalsign:"systems/dsa5/icons/categories/magicalsign.webp",abilitypact:"systems/dsa5/icons/categories/ability_pact.webp",demonmark:"systems/dsa5/icons/categories/ability_pact.webp",patron:"systems/dsa5/icons/categories/ability_pact.webp",information:"systems/dsa5/icons/categories/DSA-Auge.webp",essence:"systems/dsa5/icons/categories/wesenszug.webp",imprint:"systems/dsa5/icons/categories/praegung.webp"});var Wa=class extends A{static chatData(e,t){return[this._chatLineHelper("effect",e.effect),this._chatLineHelper("PLANT.recipes",e.recipes),this._chatLineHelper("PLANT.usages",e.usages)]}};u(Wa,"PlantItemDSA5");var Ua=class extends A{static chatData(e,t){let a=[this._chatLineHelper("AsPCost",e.asp)];return e.category==2&&a.push(this._chatLineHelper("feature",e.feature)),a}};u(Ua,"MagicalSignItemDSA5");var Va=class extends A{static chatData(e,t){return[this._chatLineHelper("attributes",e.attribute),this._chatLineHelper("skills",e.skills),this._chatLineHelper("domains",e.domain)]}};u(Va,"DemonmarkItemDSA5");var Ka=class extends A{static chatData(e,t){return[this._chatLineHelper("skills",e.talents),this._chatLineHelper("culture",e.culture),this._chatLineHelper("Category",game.i18n.localize(`PATRON.${e.category}`))]}};u(Ka,"PatronItemDSA5");var Ya=class extends A{static async _postItem(e){let t="",a=game.i18n.localize("Ongoing");e.system.cummulatedQS.value>=10?(a=game.i18n.localize("Success"),t=`${await TextEditor.enrichHTML(e.system.partsuccess,{secrets:this.isOwner,async:!0})}${await TextEditor.enrichHTML(e.system.success,{secrets:this.isOwner,async:!0})}`):e.system.cummulatedQS.value>=6?(a=game.i18n.localize("PartSuccess"),t=`${await TextEditor.enrichHTML(e.system.partsuccess,{secrets:this.isOwner,async:!0})}`):e.system.allowedTestCount.value-e.system.usedTestCount.value<=0&&(a=game.i18n.localize("Failure"));let s=[this._chatLineHelper("cummulatedQS",`${e.system.cummulatedQS.value} / 10`),this._chatLineHelper("interval",e.system.interval.value),this._chatLineHelper("probes",`${e.system.usedTestCount.value} / ${e.system.allowedTestCount.value}`),this._chatLineHelper("result",a),t],i=getProperty(e,"system.obfuscation.description"),r=await renderTemplate("systems/dsa5/templates/chat/aggregatedTestResult.html",{descriptionObfuscated:i,item:e,properties:s}),n=f.chatDataSetup(r);ChatMessage.create(n)}};u(Ya,"aggregatedTestItemDSA5");var Ja=class extends A{static chatData(e,t){return[this._chatLineHelper("ammunitiongroup",game.i18n.localize(e.ammunitiongroup.value))]}};u(Ja,"AmmunitionItemDSA5");var Qa=class extends A{};u(Qa,"EffectWrapperItemDSA5");var Xa=class extends A{static chatData(e,t){let a=[this._chatLineHelper("protection",e.protection.value),this._chatLineHelper("encumbrance",e.encumbrance.value)];return e.effect.value!=""&&a.push(this._chatLineHelper("effect",e.effect.value)),a}};u(Xa,"ArmorItemDSA5");var qt=class extends A{static chatData(e,t){return[this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("targetCategory",e.targetCategory.value),this._chatLineHelper("feature",e.feature.value)]}};u(qt,"CantripItemDSA5");var Za=class extends qt{};u(Za,"BlessingItemDSA5");var We=class extends A{static chatData(e,t){return[this._chatLineHelper("castingTime",e.castingTime.value),this._chatLineHelper("AsPCost",e.AsPCost.value),this._chatLineHelper("distribution",e.distribution.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("reach",e.range.value),this._chatLineHelper("targetCategory",e.targetCategory.value),this._chatLineHelper("effect",f.replaceConditions(f.replaceDies(e.effect.value)))]}static async getCallbackData(e,t,a){e.testDifficulty=0,e.situationalModifiers=T._parseModifiers(t);let s=new FormDataExtended(t.find("form")[0]).object;e.calculatedSpellModifiers={castingTime:t.find(".castingTime").text(),cost:t.find(".aspcost").text(),reach:t.find(".reach").text(),maintainCost:t.find(".maintainCost").text()},e.situationalModifiers.push({name:game.i18n.localize("removeGesture"),value:Number(s.removeGesture)||0},{name:game.i18n.localize("removeFormula"),value:Number(s.removeFormula)||0},{name:game.i18n.localize("castingTime"),value:t.find(".castingTime").data("mod")},{name:game.i18n.localize("cost"),value:t.find(".aspcost").data("mod")},{name:game.i18n.localize("reach"),value:t.find(".reach").data("mod")},{name:game.i18n.localize("zkModifier"),value:s.zkModifier||0},{name:game.i18n.localize("skModifier"),value:s.skModifier||0},{name:game.i18n.localize("maintainedSpells"),value:s.maintainedSpells*-1}),e.extensions=We.getSpecAbModifiers(t),e.advancedModifiers={chars:[0,1,2].map(i=>s[`ch${i}`]),fws:s.fw,qls:s.qs},A.changeChars(e.source,...[0,1,2].map(i=>s[`characteristics${i}`])),await this.applyExtensions(e.source,e.extensions,a)}static async applyExtensions(e,t,a){P.ensureNumber(e);let s=Object.keys(le.rollModifiers).map(i=>`${i}.mod`);for(let i of t){let r=fromUuidSync(i.uuid);if(!!r)for(let n of r.effects)for(let o of n.changes)le.rollChanges.includes(o.key)||s.includes(o.key)||(o.key=="macro.transform"?await f.callItemTransformationMacro(o.value,e,n):n.apply(e,o))}}static getSpecAbModifiers(e){let t=[];for(let a of e.find(".specAbs.active"))t.push({name:a.dataset.name,title:a.getAttribute("title"),uuid:a.dataset.uuid});return t}static attackSpellMalus(e){let t=[];return e.system.effectFormula.value&&t.push({name:game.i18n.localize("MODS.defenseMalus"),value:-4,type:"defenseMalus",selected:!0,source:e.name}),t}static getPropertyModifiers(e,t){let a=["ceremony","liturgy"].includes(t.type),s=(getProperty(t,"system.feature")||"").replace(/\(a-z äöü\-\)/gi,"").split(",").map(c=>c.trim()),i=[],r=a?"KaPCost":"AsPCost",n=["FP","step","QL","TPM","FW",r];for(let c of n){let m=c=="step"?"":c,d=getProperty(e.system.skillModifiers,`feature.${c}`);i.push(...d.filter(p=>s.includes(p.target)).map(p=>({name:p.source,value:p.value,type:m,source:p.source})))}let o=getProperty(e.system.skillModifiers,`conditional.${r}`);return i.push(...o.map(c=>({name:c.target,value:c.value,type:r}))),i}static foreignSpellModifier(e,t,a,s){if(game.settings.get("dsa5","enableForeignSpellModifer")&&["npc","character"].includes(e.type)&&["spell","ritual"].includes(t.type)){let i=t.system.distribution.value.split(",").map(o=>o.trim().toLowerCase()),r=new RegExp(`(${game.i18n.localize("tradition")}|\\)|\\()`,"g"),n=e.system.tradition.magical.replace(r,"").split(",").map(o=>o.trim().toLowerCase());n.push(game.i18n.localize("general").toLowerCase()),s.isForeign=!i.some(o=>n.includes(o)),s.isForeign&&a.push({name:game.i18n.localize("DSASETTINGS.enableForeignSpellModifer"),value:-2,selected:!0})}}static getSituationalModifiers(e,t,a,s){e.push(...te.getTalentBonus(t,s.name,["advantage","disadvantage","specialability","equipment"]),...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.magicalAttunement"),1,!0),...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.magicalRestriction"),-1,!0),...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.boundToArtifact"),-1,!0),...this.getPropertyModifiers(t,s),...this.attackSpellMalus(s)),this.foreignSpellModifier(t,s,e,a),game.user.targets.size&&game.user.targets.forEach(i=>{i.actor&&I.addCreatureTypeModifiers(i.actor,s,e,t)}),e.push(...t.getSkillModifier(s.name,s.type));for(let i of t.system.skillModifiers.global)e.push({name:i.source,value:i.value});this.getSkZkModifier(a,s)}static setupDialog(e,t,a,s,i){let r="spell";(a.type=="ceremony"||a.type=="liturgy")&&(r="liturgy");let n=a.name+" "+game.i18n.localize(`${a.type}Test`)+(t.subtitle||""),o={opposable:a.system.effectFormula.value.length>0,source:a,extra:{actor:s.toObject(!1),options:t,speaker:A.buildSpeaker(s,i)},advancedModifiers:{chars:[0,0,0],fws:0,qls:0},calculatedSpellModifiers:{castingTime:0,cost:0,reach:0,maintainCost:0}},c={rollMode:t.rollMode,spellCost:a.system.AsPCost.value,maintainCost:a.system.maintainCost.value,spellCastingTime:a.system.castingTime.value,spellReach:a.system.range.value,canChangeCost:a.system.canChangeCost.value=="true",canChangeRange:a.system.canChangeRange.value=="true",canChangeCastingTime:a.system.canChangeCastingTime.value=="true",hasSKModifier:a.system.resistanceModifier.value=="SK",hasZKModifier:a.system.resistanceModifier.value=="ZK",maxMods:Math.floor(Number(a.system.talentValue.value)/4),extensions:this.prepareExtensions(s,a),variableBaseCost:a.system.variableBaseCost=="true",characteristics:[1,2,3].map(g=>a.system[`characteristic${g}`].value)},m=s?E.getRollModifiers(s,a):[];this.getSituationalModifiers(m,s,c,a),c.situationalModifiers=m;let d={title:n,template:`/systems/dsa5/templates/dialog/${r}-enhanced-dialog.html`,data:c,callback:async(g,y={})=>(p.rollMode=g.find('[name="rollMode"]').val(),await this.getCallbackData(o,g,s),mergeObject(o.extra.options,y),{testData:o,cardOptions:p})},p=s._setupCardOptions("systems/dsa5/templates/chat/roll/spell-card.html",n,i);return _DiceDSA5.setupDialog({dialogOptions:d,testData:o,cardOptions:p})}static prepareExtensions(e,t){return e.items.filter(a=>a.type=="spellextension"&&a.system.source==t.name&&a.system.category==t.type).map(a=>(a.shortName=a.name.split(" - ").length>1?a.name.split(" - ")[1]:a.name,a.descr=$(a.system.description.value).text()||"",a))}};u(We,"SpellItemDSA5");var Wt=class extends We{static chatData(e,t){return[this._chatLineHelper("castingTime",e.castingTime.value),this._chatLineHelper("KaPCost",e.AsPCost.value),this._chatLineHelper("distribution",e.distribution.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("reach",e.range.value),this._chatLineHelper("targetCategory",e.targetCategory.value),this._chatLineHelper("effect",f.replaceConditions(f.replaceDies(e.effect.value)))]}};u(Wt,"LiturgyItemDSA5");var es=class extends Wt{static getCallbackData(e,t,a){super.getCallbackData(e,t,a),e.situationalModifiers.push({name:game.i18n.localize("CEREMONYMODIFIER.artefact"),value:t.find('[name="artefactUsage"]').is(":checked")?1:0},{name:game.i18n.localize("place"),value:t.find('[name="placeModifier"]').val()},{name:game.i18n.localize("time"),value:t.find('[name="timeModifier"]').val()})}static getSituationalModifiers(e,t,a,s){super.getSituationalModifiers(e,t,a,s),mergeObject(a,{isCeremony:!0,locationModifiers:b.ceremonyLocationModifiers,timeModifiers:b.ceremonyTimeModifiers})}};u(es,"CeremonyItemDSA5");var ts=class extends A{static chatData(e,t){return[this._chatLineHelper("Description",game.i18n.localize(`Combatskilldescr.${t}`))]}static setupDialog(e,t,a,s,i){let r=t.mode,n=a.name+" "+game.i18n.localize(r+"test"),o={opposable:!0,source:a,mode:r,extra:{actor:s.toObject(!1),options:t,speaker:A.buildSpeaker(s,i)}},c={title:n,template:"systems/dsa5/templates/dialog/combatskill-dialog.html",data:{rollMode:t.rollMode},callback:(d,p={})=>(m.rollMode=d.find('[name="rollMode"]').val(),o.situationalModifiers=T._parseModifiers(d),mergeObject(o.extra.options,p),{testData:o,cardOptions:m})},m=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",n,i);return _DiceDSA5.setupDialog({dialogOptions:c,testData:o,cardOptions:m})}};u(ts,"CombatskillDSA5");var as=class extends A{static chatData(e,t){return[this._chatLineHelper("qualityStep",e.QL),this._chatLineHelper("effect",f.replaceDies(e.QLList.split(` -`)[e.QL-1])),this._chatLineHelper("charges",e.charges)]}static consumablePrice(e){let t=e.system.price.value;if(isNaN(t)){let a=t.split(";");return t=Number(a[e.system.QL-1]),isNaN(t)&&(t=Number(a.pop())||0),t}else return Number(t)*e.system.QL||0}static checkEquality(e,t){return e.type==t.type&&e.name==t.name&&e.system.description.value==t.system.description.value&&e.system.QL==t.system.QL}static async setupDialog(e,t,a,s){let i=game.i18n.format("CHATNOTIFICATION.usesItem",{actor:a.actor.name,item:a.name});if(!a.isOwned)return;if((a.system.quantity.value-1)*a.system.maxCharges+a.system.charges<=0){ui.notifications.error(game.i18n.localize("DSAError.NotEnoughCharges"));return}let n=a.system.charges<=1?a.system.maxCharges:a.system.charges-1,o=a.system.charges<=1?a.system.quantity.value-1:a.system.quantity.value,c=f.replaceDies(a.system.QLList.split(` -`)[a.system.QL-1],!1),m=`
    ${i}
    ${a.system.description.value}
    ${game.i18n.localize("effect")}: ${c}
    `;o==0?await a.actor.deleteEmbeddedDocuments("Item",[a.id]):await a.update({"system.quantity.value":o,"system.charges":n}),await ChatMessage.create(f.chatDataSetup(m)),await this._applyActiveEffect(a)}static async _applyActiveEffect(e){let t=e.effects.toObject();if(t.length>0){let{msg:a,resistRolls:s,effectNames:i}=await Q.applyAdvancedFunction(e.actor,t,e,{qualityStep:e.system.QL},e.actor),r=`${game.i18n.format("ActiveEffects.appliedEffect",{target:e.actor.token?.name||e.actor.name,source:i.join(", ")})} ${a||""}`;ChatMessage.create(f.chatDataSetup(r))}}static async combineItem(e,t,a){e=duplicate(e);let s=(e.system.quantity.value-1)*e.system.maxCharges+e.system.charges,i=(t.system.quantity.value-1)*t.system.maxCharges+t.system.charges,r=Math.floor((s+i)/e.system.maxCharges)+1,n=(s+i)%e.system.maxCharges;return n==0&&(r-=1,n=e.system.maxCharges),e.system.quantity.value=r,e.system.charges=n,await a.updateEmbeddedDocuments("Item",[e])}};u(as,"ConsumableItemDSA");var ss=class extends A{static async _postItem(e){let t=await renderTemplate("systems/dsa5/templates/chat/informationRequestRoll.html",{item:e}),a=f.chatDataSetup(t);ChatMessage.create(a)}};u(ss,"InformationItemDSA5");var is=class extends A{static chatData(e,t){return[this._chatLineHelper("stepValue",e.step.value),this._chatLineHelper("incubation",e.incubation.value),this._chatLineHelper("damage",f.replaceConditions(f.replaceDies(e.damage.value))),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("source",f.replaceDies(e.source.value)),this._chatLineHelper("treatment",e.treatment.value),this._chatLineHelper("antidot",e.antidot.value),this._chatLineHelper("resistanceModifier",e.resistance.value)]}static getSituationalModifiers(e,t,a,s){s=f.toObjectIfPossible(s),game.user.targets.size&&game.user.targets.forEach(i=>{i.actor&&e.push(...O.getVantageAsModifier(i.actor,game.i18n.localize("LocalizedIDs.ResistanttoDisease"),-1,!1,!0))}),this.getSkZkModifier(a,s),mergeObject(a,{hasSKModifier:s.system.resistance.value=="SK",hasZKModifier:s.system.resistance.value=="ZK"})}static setupDialog(e,t,a,s,i){let r=a.name+" "+game.i18n.localize(a.type)+" "+game.i18n.localize("Test"),n={opposable:!1,source:a,extra:{options:t,speaker:A.buildSpeaker(s,i)}},o={rollMode:t.rollMode},c=[];this.getSituationalModifiers(c,s,o,a),o.situationalModifiers=c,t.manualResistance&&mergeObject(o,t.manualResistance);let m={title:r,template:"/systems/dsa5/templates/dialog/poison-dialog.html",data:o,callback:(p,g={})=>(d.rollMode=p.find('[name="rollMode"]').val(),n.situationalModifiers=T._parseModifiers(p),n.situationalModifiers.push({name:game.i18n.localize("zkModifier"),value:p.find('[name="zkModifier"]').val()||0},{name:game.i18n.localize("skModifier"),value:p.find('[name="skModifier"]').val()||0}),mergeObject(n.extra.options,g),{testData:n,cardOptions:d})},d=a._setupCardOptions(`systems/dsa5/templates/chat/roll/${a.type}-card.html`,r,i);return _DiceDSA5.setupDialog({dialogOptions:m,testData:n,cardOptions:d})}};u(is,"DiseaseItemDSA5");var rs=class extends A{static chatData(e,t){return[this._chatLineHelper("equipmentType",game.i18n.localize(`Equipment.${e.equipmentType.value}`))]}};u(rs,"EquipmentItemDSA5");var kt=class extends A{static chatData(e,t){let a=[this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("atmod",e.atmod.value),this._chatLineHelper("pamod",e.pamod.value),this._chatLineHelper("reach",game.i18n.localize(`Range-${e.reach.value}`)),this._chatLineHelper("TYPES.Item.combatskill",e.combatskill.value)];return e.effect.value!=""&&a.push(this._chatLineHelper(f.replaceConditions("effect",e.effect.value))),a}static getSituationalModifiers(e,t,a,s){let i=O.hasVantage(t,game.i18n.localize("LocalizedIDs.ambidextrous"));s=f.toObjectIfPossible(s);let r=[s.system.combatskill.value],n=A.buildCombatSpecAbs(t,["Combat"],r,a.mode);a.mode=="attack"?this.prepareMeleeAttack(e,t,a,s,n,i):a.mode=="parry"&&this.prepareMeleeParry(e,t,a,s,n,i),this.attackStatEffect(e,t.system.meleeStats[a.mode]),["attack","parry"].includes(a.mode)&&e.push(...kt.getMiracleModifiers(t,{name:s.system.combatskill.value},"",a.mode))}static setupDialog(e,t,a,s,i){let r=t.mode,n=a.name+" "+game.i18n.localize(r+"test"),o={opposable:t.mode!="parry",source:a,mode:r,extra:{actor:s.toObject(!1),options:t,speaker:A.buildSpeaker(s,i)}},c=P.multipleDefenseValue(s,f.toObjectIfPossible(a)),m={rollMode:t.rollMode,mode:r,defenseCountString:game.i18n.format("defenseCount",{malus:c})},d=s?E.getRollModifiers(s,a,{mode:r}):[];this.getSituationalModifiers(d,s,m,a),m.situationalModifiers=d,t.situationalModifiers&&m.situationalModifiers.push(...t.situationalModifiers);let p={title:n,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:m,callback:(y,h={})=>(ge.resolveMeleeDialog(o,g,y,s,h,c,r),Hooks.call("callbackDialogCombatDSA5",o,s,y,a,i),o.isRangeDefense=m.isRangeDefense,{testData:o,cardOptions:g})},g=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",n,i);return _DiceDSA5.setupDialog({dialogOptions:p,testData:o,cardOptions:g})}};u(kt,"MeleeweaponDSA5");var ns=class extends A{static chatData(e,t){return[this._chatLineHelper("stepValue",e.step.value),this._chatLineHelper("poisonType",e.poisonType.value),this._chatLineHelper("start",e.start.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("resistanceModifier",e.resistance.value),this._chatLineHelper("effect",f.replaceConditions(f.replaceDies(e.effect.value)))]}static getSituationalModifiers(e,t,a,s){s=f.toObjectIfPossible(s),game.user.targets.size&&game.user.targets.forEach(i=>{i.actor&&e.push(...O.getVantageAsModifier(i.actor,game.i18n.localize("LocalizedIDs.poisonResistance"),-1,!1,!0))}),this.getSkZkModifier(a,s),mergeObject(a,{hasSKModifier:s.system.resistance.value=="SK",hasZKModifier:s.system.resistance.value=="ZK"})}static setupDialog(e,t,a,s,i){let r=a.name+" "+game.i18n.localize(a.type)+" "+game.i18n.localize("Test"),n={opposable:!1,source:a,extra:{options:t,speaker:A.buildSpeaker(s,i)}},o={rollMode:t.rollMode},c=[];this.getSituationalModifiers(c,s,o,a),o.situationalModifiers=c;let m={title:r,template:"/systems/dsa5/templates/dialog/poison-dialog.html",data:o,callback:(p,g={})=>(d.rollMode=p.find('[name="rollMode"]').val(),n.situationalModifiers=T._parseModifiers(p),n.situationalModifiers.push({name:game.i18n.localize("zkModifier"),value:p.find('[name="zkModifier"]').val()||0}),n.situationalModifiers.push({name:game.i18n.localize("skModifier"),value:p.find('[name="skModifier"]').val()||0}),mergeObject(n.extra.options,g),{testData:n,cardOptions:d})},d=a._setupCardOptions(`systems/dsa5/templates/chat/roll/${a.type}-card.html`,r,i);return _DiceDSA5.setupDialog({dialogOptions:m,testData:n,cardOptions:d})}};u(ns,"PoisonItemDSA5");var wt=class extends A{static chatData(e,t){let a=[this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("TYPES.Item.combatskill",e.combatskill.value),this._chatLineHelper("reach",e.reach.value)];return e.effect.value!=""&&a.push(this._chatLineHelper(f.replaceConditions("effect",e.effect.value))),a}static getSituationalModifiers(e,t,a,s,i){if(a.mode=="attack"){let r=f.toObjectIfPossible(s),n=[r.system.combatskill.value],o=A.buildCombatSpecAbs(t,["Combat"],n,a.mode),c=t.items.get(r.system.currentAmmo.value);if(c){c=c.toObject(!1),r.system.effect.attributes=(r.system.effect.attributes||"").split(",").concat((c.system.effect.attributes||"").split(",")).filter(d=>d!="").join(",");let m=getProperty(c.flags,"dsa5.poison");m&&mergeObject(s.flags,{dsa5:{poison:m}})}if(this.prepareRangeAttack(e,t,a,r,i,o,c),c){if(c.system.atmod&&e.push({name:`${c.name} - ${game.i18n.localize("atmod")}`,value:c.system.atmod,selected:!0,specAbId:r.system.currentAmmo.value}),c.system.damageMod||c.system.armorMod){let m={name:`${c.name} - ${game.i18n.localize("MODS.damage")}`,value:c.system.damageMod.replace(/wWD/g,"d")||0,type:"dmg",selected:!0,specAbId:r.system.currentAmmo.value};c.system.armorMod&&(m.armorPen=c.system.armorMod),e.push(m)}c.effects.length&&e.push({name:`${c.name} - ${game.i18n.localize("TYPES.Item.ammunition")}`,value:1,type:"effect",selected:!0,specAbId:r.system.currentAmmo.value})}e.push(...wt.getMiracleModifiers(t,{name:r.system.combatskill.value},"",a.mode))}this.attackStatEffect(e,t.system.rangeStats[a.mode])}static async checkAmmunitionState(e,t,a,s){let i=!0;if(s!="damage"){let r=e.system;if(r.ammunitiongroup.value!="infinite")if(r.ammunitiongroup.value=="-")t.extra.ammo=duplicate(e),i=t.extra.ammo.system.quantity.value>0;else{let n=a.items.get(r.currentAmmo.value);n?(t.extra.ammo=n.toObject(),r.ammunitiongroup.value=="mag"?i=t.extra.ammo.system.quantity.value>1||t.extra.ammo.system.mag.value>0&&t.extra.ammo.system.quantity.value>0:i=t.extra.ammo.system.quantity.value>0):i=!1}!i&&a.type=="creature"&&(i=!0)}return i||ui.notifications.error(game.i18n.localize("DSAError.NoAmmo")),i}static async setupDialog(e,t,a,s,i){let r=t.mode,n=a.name+" "+game.i18n.localize(r+"test"),o={opposable:t.mode!="parry",source:a,mode:r,extra:{actor:s.toObject(!1),options:t,speaker:A.buildSpeaker(s,i)}};if(!await this.checkAmmunitionState(a,o,s,r))return;let c={rollMode:t.rollMode,mode:r},m=s?E.getRollModifiers(s,a,{mode:r}):[];this.getSituationalModifiers(m,s,c,a,i),c.situationalModifiers=m,t.situationalModifiers&&c.situationalModifiers.push(...t.situationalModifiers);let d={title:n,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:c,callback:(g,y={})=>(ge.resolveRangeDialog(o,p,g,s,y),Hooks.call("callbackDialogCombatDSA5",o,s,g,a,i),{testData:o,cardOptions:p})},p=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",n,i);return _DiceDSA5.setupDialog({dialogOptions:d,testData:o,cardOptions:p})}};u(wt,"RangeweaponItemDSA5");var os=class extends We{static getCallbackData(e,t,a){super.getCallbackData(e,t,a),e.situationalModifiers.push({name:game.i18n.localize("RITUALMODIFIER.rightClothes"),value:t.find('[name="rightClothes"]').is(":checked")?1:0},{name:game.i18n.localize("RITUALMODIFIER.rightEquipment"),value:t.find('[name="rightEquipment"]').is(":checked")?1:0},{name:game.i18n.localize("place"),value:t.find('[name="placeModifier"]').val()},{name:game.i18n.localize("time"),value:t.find('[name="timeModifier"]').val()})}static getSituationalModifiers(e,t,a,s){super.getSituationalModifiers(e,t,a,s),mergeObject(a,{isRitual:!0,locationModifiers:b.ritualLocationModifiers,timeModifiers:b.ritualTimeModifiers})}};u(os,"RitualItemDSA5");var ls=class extends A{static chatData(e,t){let s=game.i18n.has(`APPLICATION.${e.skill} - ${t}`)?game.i18n.localize(`APPLICATION.${e.skill} - ${t}`):e.description.value;return[this._chatLineHelper("Description",s)]}};u(ls,"ApplicationItemDSA5");var vt=class extends A{static chatData(e,t){let s=game.i18n.has(`SKILLdescr.${t}`)?game.i18n.localize(`SKILLdescr.${t}`):e.description.value;return[this._chatLineHelper("Description",s)]}static getSituationalModifiers(e,t,a,s){e.push(...te.getTalentBonus(t,s.name,["advantage","disadvantage","specialability","equipment"]),...t.getSkillModifier(s.name,s.type),...vt.getMiracleModifiers(t,s,"FW","skill"));for(let i of t.system.skillModifiers.global)e.push({name:i.source,value:i.value})}static setupDialog(e,t,a,s,i){let r=a.name+" "+game.i18n.localize("Test")+(t.subtitle||""),n={opposable:!0,source:a,extra:{actor:s.toObject(!1),options:t,speaker:A.buildSpeaker(s,i)}},o={rollMode:t.rollMode,difficultyLabels:b.skillDifficultyLabels,modifier:t.modifier||0,characteristics:[1,2,3].map(d=>a.system[`characteristic${d}`].value),situationalModifiers:s?E.getRollModifiers(s,a):[]};t.situationalModifiers&&o.situationalModifiers.push(...t.situationalModifiers),this.getSituationalModifiers(o.situationalModifiers,s,o,a);let c={title:r,template:"/systems/dsa5/templates/dialog/skill-dialog.html",data:o,callback:(d,p={})=>(m.rollMode=d.find('[name="rollMode"]').val(),n.testDifficulty=b.skillDifficultyModifiers[d.find('[name="testDifficulty"]').val()],n.situationalModifiers=T._parseModifiers(d),n.advancedModifiers={chars:[0,1,2].map(g=>Number(d.find(`[name="ch${g}"]`).val())),fws:Number(d.find('[name="fw"]').val()),qls:Number(d.find('[name="qs"]').val())},A.changeChars(n.source,...[0,1,2].map(g=>d.find(`[name="characteristics${g}"]`).val())),mergeObject(n.extra.options,p),{testData:n,cardOptions:m})},m=s._setupCardOptions("systems/dsa5/templates/chat/roll/skill-card.html",r,i);return _DiceDSA5.setupDialog({dialogOptions:c,testData:n,cardOptions:m})}};u(vt,"SkillItemDSA5");var cs=class extends A{static chatData(e,t){return[this._chatLineHelper("rule",e.rule.value)]}};u(cs,"SpecialAbilityItemDSA5");var ds=class extends A{};u(ds,"SpeciesItemDSA5");var ms=class extends A{static chatData(e,t){return[this._chatLineHelper("source",e.source),this._chatLineHelper("Category",game.i18n.localize(e.category))]}};u(ms,"SpellextensionItemDSA5");var us=class extends A{static chatData(e,t){let a=[];switch(e.traitType.value){case"meleeAttack":a=[this._chatLineHelper("attack",e.at.value),this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("reach",e.reach.value)];break;case"rangeAttack":a=[this._chatLineHelper("attack",e.at.value),this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("reach",e.reach.value),this._chatLineHelper("reloadTime",e.reloadTime.value)];break;case"armor":a=[this._chatLineHelper("protection",e.damage.value)];break;case"general":a=[];break;case"familiar":a=[this._chatLineHelper("APValue",e.APValue.value),this._chatLineHelper("AsPCost",e.AsPCost.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("aspect",e.aspect.value)];break;case"trick":a=[this._chatLineHelper("APValue",e.APValue.value)];break;case"entity":a=[this._chatLineHelper("distribution",e.distribution),this._chatLineHelper("CHARAbbrev.QL",e.AsPCost.value)];break;case"summoning":a=[this._chatLineHelper("distribution",e.distribution),this._chatLineHelper("conjuringDifficulty",e.at.value)];break}return e.effect.value!=""&&a.push(this._chatLineHelper("effect",e.effect.value)),a}static getSituationalModifiers(e,t,a,s,i){s=f.toObjectIfPossible(s);let r=s.system.traitType.value,n=A.buildCombatSpecAbs(t,["Combat","animal"],void 0,a.mode);a.mode=="attack"&&r=="meleeAttack"?this.prepareMeleeAttack(e,t,a,s,n,!1):a.mode=="attack"&&r=="rangeAttack"?this.prepareRangeAttack(e,t,a,s,i,n):a.mode=="parry"&&this.prepareMeleeParry(e,t,a,s,n,!1),this.attackStatEffect(e,t.system[r=="meleeAttack"?"meleeStats":"rangeStats"][a.mode])}static setupDialog(e,t,a,s,i){let r=t.mode,n=a.name+" "+game.i18n.localize(r+"test"),o={opposable:t.mode!="parry",source:a,mode:r,extra:{actor:s.toObject(!1),options:t,speaker:A.buildSpeaker(s,i)}},c=P.multipleDefenseValue(s,a.toObject()),m={rollMode:t.rollMode,mode:r,defenseCountString:game.i18n.format("defenseCount",{malus:c})},d=getProperty(a,"system.traitType.value"),p=s?E.getRollModifiers(s,a,{mode:r}):[];this.getSituationalModifiers(p,s,m,a,i),m.situationalModifiers=p;let g={title:n,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:m,callback:(h,w={})=>(d=="meleeAttack"?ge.resolveMeleeDialog(o,y,h,s,w,c,r):ge.resolveRangeDialog(o,y,h,s,w),o.isRangeDefense=m.isRangeDefense,Hooks.call("callbackDialogCombatDSA5",o,s,h,a,i),{testData:o,cardOptions:y})},y=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",n,i);return _DiceDSA5.setupDialog({dialogOptions:g,testData:o,cardOptions:y})}};u(us,"TraitItemDSA5");var Ut=class extends A{static chatData(e,t){return[this._chatLineHelper("effect",e.effect.value)]}};u(Ut,"VantageItemDSA5");var Tt=class extends ie{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,resizable:!0}),e}static setData(e,t,a){let s=duplicate(Tt.rollModifiers);s.narrowSpace.mod=this.getNarrowSpaceModifier(a,a.mode);let i=`${t}RollModifiers`;if(e.system[i])for(let r of Object.keys(e.system[i]))s[r].mod+=Number(e.system[i][r]?.mod??0);return s}activateListeners(e){super.activateListeners(e);let t=e.find(".specAbs");t.mouseenter(i=>{if(i.currentTarget.getElementsByClassName("hovermenu").length==0){let r=document.createElement("div");r.classList.add("hovermenu");let n=document.createElement("i");n.classList.add("fas","fa-comment"),n.title=game.i18n.localize("SHEET.PostItem"),n.addEventListener("mousedown",this._postItem,!1),r.appendChild(n),i.currentTarget.appendChild(r)}}),t.mouseleave(i=>{let r=i.toElement||i.relatedTarget;r.parentNode==this||r==this||i.currentTarget.querySelectorAll(".hovermenu").forEach(n=>n.remove())}),e.find(".variantChange").mousedown(i=>this.changeSpecAbVariant(i)),e.on("mousedown",".specAbs",i=>{if(e.find(".opportunityAttack").is(":checked")){ui.notifications.error(game.i18n.localize("DSAError.opposedAttackNoSpecAbs"));return}let r=$(i.currentTarget),n=Number(r.attr("data-step")),o=Number(r.attr("data-maxStep")),c=Number(r.attr("data-category"));if(i.button==0){if(n=Math.min(o,n+1),[0,1].includes(c)&&game.settings.get("dsa5","limitCombatSpecAbs")){let m=r.siblings(`[data-category="${c}"]`);m.removeClass("active").attr("data-step",0),m.find(".step").text(ie.roman[0])}}else i.button==2&&(n=Math.clamped(o,0,n-1));r.attr("data-step",n),r.toggleClass("active",n>0),r.find(".step").text(ie.roman[n]),this.checkCounterAttack(i),this.calculateModifier()}),e.find(".opportunityAttack").change(i=>{if($(i.currentTarget).is(":checked"))for(let r of e.find(".specAbs"))$(r).removeClass("active").attr("data-step",0).find(".step").text("")}),e.on("change","input,select",i=>this.calculateModifier(i)),e.find(".modifiers option").mousedown(i=>{this.calculateModifier(i)}),e.find(".quantity-click").mousedown(i=>this.calculateModifier(i));let a=this.readTargets();this.calculateModifier();let s=this;this.checkTargets=setInterval(function(){a=s.compareTargets(e,a)},500)}checkCounterAttack(e){if(!this.dialogData.mode=="parry")return;let t=f.getSpeaker(this.dialogData.speaker);if(t&&t.items.get(e.currentTarget.dataset.id).name==game.i18n.localize("LocalizedIDs.counterAttack")){this.dialogData.counterAttack=e.button==0,this.prepareWeapon();let s=e.button==0?"attack":"parry",i=t.items.get(this.dialogData.source._id),r=E.getRollModifiers(t,i,{mode:s});A.getSubClass(i.type).getSituationalModifiers(r,t,{mode:s},i),s=="attack"&&(r=r.filter(o=>o.type!="defenseMalus"));let n=$(this._element).find("[name=situationalModifiers]");if(r.length>0){if(n.length==0){let c=`
    + `),L(H,"speedKeys",{0:{key:"system.status.speed.multiplier",mode:5,value:0},"-4":{key:"system.status.speed.initial",mode:5,value:4},"-5000":{key:"system.status.speed.multiplier",mode:5,value:.66},"-8":{key:"system.status.speed.multiplier",mode:5,value:1}});var he=class extends Item{static defaultIcon(e){(!e.img||e.img=="")&&(e.type in this.defaultImages?e.img=this.defaultImages[e.type]:e.img="systems/dsa5/icons/blank.webp")}static async create(e,t){return this.defaultIcon(e),await super.create(e,t)}static getSpecAbModifiers(e,t){let a=[];for(let s of e.find(".specAbs")){let i=Number($(s).attr("data-step"));if(i>0){let n=t=="attack"?$(s).attr("data-atbonus"):$(s).attr("data-pabonus"),r=n.split(",").reduce((o,c)=>o+Number(c),0);a.push({name:$(s).find("a").text(),value:isNaN(r)?Number(n.replace("*","")):Number(r)*i,damageBonus:$(s).attr("data-tpbonus"),dmmalus:$(s).attr("data-dmmalus")*i,step:i,specAbId:$(s).attr("data-id"),type:/^\*/.test(n)?"*":void 0})}}return a}static setupSubClasses(){game.dsa5.config.ItemSubclasses={ritual:os,spell:We,liturgy:Wt,ceremony:es,advantage:Ut,disadvantage:Ut,aggregatedTest:Ya,trait:us,blessing:Za,magictrick:qt,specialability:cs,disease:is,poison:rs,armor:Xa,rangeweapon:wt,meleeweapon:kt,ammunition:Ja,equipment:ns,combatskill:ts,skill:vt,application:ls,consumable:as,spellextension:ms,species:ds,effectwrapper:Qa,plant:Wa,magicalsign:Ua,patron:Ka,demonmark:Va,information:ss}}static buildSpeaker(e,t){return{token:t,actor:e?.id,scene:canvas.scene?.id}}static parseValueType(e,t){let a="";return/^\*/.test(t)&&(a="*",t=t.substring(1).replace(",",".")),{name:e,value:Number(t),type:a}}async addCondition(e,t=1,a=!1,s=!0){return await E.addCondition(this,e,t,a,s)}async removeCondition(e,t=1,a=!0,s=!1){return E.removeCondition(this,e,t,a,s)}hasCondition(e){return E.hasCondition(this,e)}static getMiracleModifiers(e,t,a,s){let i=new RegExp(`${game.i18n.localize("combatskill")} `,"gi"),n=(getProperty(e,"system.happyTalents.value")||"").split(/;|,/).map(o=>o.replace(i,"").trim()),r=[];if(n.includes(t.name)){let o=e.system.status.karmaenergy.value,c=getProperty(e,`system.miracle.${s}`)||0;if(o<4)return[];r.push({name:game.i18n.localize("LocalizedIDs.miracle"),value:2+c,type:a,selected:!1});let m=game.i18n.localize("LocalizedIDs.miracleMight");o>=6&&R.hasAbility(e,m)&&r.push({name:m,value:3+c,type:a,selected:!1})}return r}static getSkZkModifier(e,t){let a=[],s=[],i=["spell","liturgy","ceremony","ritual"].includes(t.type)&&t.system.effectFormula.value.trim()=="";game.user.targets.size&&game.user.targets.forEach(n=>{if(n.actor){let r=0;i&&(r=I.detectCreatureType(n.actor).reduce((d,p)=>d+p.spellResistanceModifier(n.actor),0));let o=getProperty(n.actor,`system.status.soulpower.${t.type}resist`)||0,c=getProperty(n.actor,`system.status.toughness.${t.type}resist`)||0;a.push((n.actor.system.status.soulpower.max+o)*-1-r),s.push((n.actor.system.status.toughness.max+c)*-1-r)}}),mergeObject(e,{SKModifier:a.length>0?Math.min(...a):0,ZKModifier:s.length>0?Math.min(...s):0})}static async _onCreateDocuments(e,t){for(let a of e)a.actor&&await T.postUpdateConditions(a.actor);return super._onCreateDocuments(e,t)}static async _onUpdateDocuments(e,t){for(let a of e)a.actor&&await T.postUpdateConditions(a.actor);return super._onUpdateDocuments(e,t)}static async _onDeleteDocuments(e,t){for(let a of e)a.actor&&await T.postUpdateConditions(a.actor);return super._onDeleteDocuments(e,t)}static parseEffect(e,t){let a={},s=new RegExp(game.i18n.localize("CHARAbbrev.GS"),"gi");for(let i of e.split(/,|;/).map(n=>n.trim())){let n=i.replace(/(\s+)/g," ").trim().split(" ");n[0]=n[0].replace(s,t.system.status.speed.max),n.length==2&&(!isNaN(n[0])||/(=)?[+-]\d([+-]\d)?/.test(n[0])||/(=)?\d[dDwW]\d/.test(n[0])||/=\d+/.test(n[0])||/\*\d(\.\d)*/.test(n[0]))&&(a[n[1].toLowerCase()]==null?a[n[1].toLowerCase()]=[n[0]]:a[n[1].toLowerCase()].push(n[0]))}return a}static getDefenseMalus(e,t){let a=!1;if(t.flags.oppose){let s=game.messages.get(t.flags.oppose.messageId),i=s.flags.data.preData;a=!(getProperty(i,"source.type")=="meleeweapon"||getProperty(i,"source.system.traitType.value")=="meleeAttack");let n=/ \[(-)?\d{1,}\]/;for(let r of i.situationalModifiers)r.dmmalus!=null&&r.dmmalus!=0?e.push({name:`${game.i18n.localize("MODS.defenseMalus")} - ${r.name.replace(n,"")}`,value:r.dmmalus,selected:!0}):r.type=="defenseMalus"&&r.value!=0&&e.push({name:r.name.replace(n,""),value:r.value,selected:!0});s.flags.data.postData.halfDefense&&e.push({name:`${game.i18n.localize("MODS.defenseMalus")} - ${game.i18n.localize("halfDefenseShort")}`,value:.5,type:"*",selected:!0})}return a}static changeChars(e,t,a,s){e.system.characteristic1.value=t,e.system.characteristic2.value=a,e.system.characteristic3.value=s}static attackSpecAbs(e,t,a="effect.value"){let s=game.i18n.localize("LocalizedAbilityModifiers.at"),i=game.i18n.localize("LocalizedAbilityModifiers.tp"),n=game.i18n.localize("LocalizedAbilityModifiers.dm"),r=[];for(let o of e){let c=he.parseEffect(getProperty(o.system,a),t),m=c[s]||0,d=c[i]||0,p=c[n]||0,g=["","2","3"].map(y=>getProperty(o,`system.effect.value${y}`)).filter(y=>y).length;if(m!=0||d!=0||p!=0||o.effects.size>0){let y=game.i18n.localize(b.combatSkillSubCategories[o.system.category.sub]);r.push({name:o.name,atbonus:m,tpbonus:d,dmmalus:p,label:`${s.toUpperCase()}: ${m}, ${i.toUpperCase()}: ${d}, ${n.toUpperCase()}: ${p}`,steps:o.system.step.value,category:{id:o.system.category.sub,css:`ab_${o.system.category.sub}`,name:y},id:o.id,actor:t.id,variantCount:g})}}return r}static defenseSpecAbs(e,t,a="effect.value"){let s=[],i=game.i18n.localize("LocalizedAbilityModifiers.pa");for(let n of e){let o=he.parseEffect(getProperty(n.system,a),t)[i]||0;if(o!=0){let c=game.i18n.localize(b.combatSkillSubCategories[n.system.category.sub]),m=["","2","3"].map(d=>getProperty(n,`system.effect.value${d}`)).filter(d=>d).length;s.push({name:n.name,pabonus:o,tpbonus:0,dmmalus:0,label:`${i}: ${o}`,steps:n.system.step.value,category:{id:n.system.category.sub,css:`ab_${n.system.category.sub}`,name:c},id:n.id,actor:t.id,variantCount:m})}}return s}static buildCombatSpecAbs(e,t,a,s){let i;a?(a.push(game.i18n.localize("LocalizedIDs.all")),a=a.map(o=>o.toLowerCase()),i=u((o,c)=>o.system.list.value.split(/;|,/).map(m=>m.trim().toLowerCase()).filter(m=>c.includes(m.replace(/ \([a-zA-Z äüöÄÖÜ]*\)/,""))).length>0,"searchFilter")):i=u(()=>!0,"searchFilter");let n=game.combat?.isBrawling?()=>!0:o=>Number(o.system.category.sub)!=5,r=e.items.filter(o=>o.type=="specialability"&&t.includes(o.system.category.value)&&o.system.effect.value!=""&&i(o,a)&&n(o));return s=="attack"?this.attackSpecAbs(r,e):this.defenseSpecAbs(r,e)}static getCombatSkillModifier(e,t,a){if(t.type=="trait")return;let s=e.items.find(i=>i.type=="combatskill"&&i.name==t.system.combatskill.value);for(let i of s.effects)for(let n of i.changes)switch(n.key){case"system.rangeStats.defenseMalus":case"system.meleeStats.defenseMalus":a.push({name:`${s.name} - ${game.i18n.localize("MODS.defenseMalus")}`,value:n.value*-1,type:"defenseMalus",selected:!0});break}}static attackStatEffect(e,t){t!=0&&(t=isNaN(t)?t:Number(t),e.push({name:game.i18n.localize("statuseffects"),value:t,selected:!0}))}static getTargetSizeAndModifier(e,t,a){let s="average";return game.user.targets.forEach(i=>{if(i.actor){let n=getProperty(i.actor,"system.status.size.value");n&&(s=n),I.addCreatureTypeModifiers(i.actor,t,a,e)}}),s}static prepareRangeAttack(e,t,a,s,i,n,r=void 0){e.push(...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.restrictedSenseSight"),-2)),this.getCombatSkillModifier(t,s,e);let o=this.getTargetSizeAndModifier(t,s,e),c=Number(t.system.rangeStats.defenseMalus)*-1;c!=0&&e.push({name:`${game.i18n.localize("statuseffects")} - ${game.i18n.localize("MODS.defenseMalus")}`,value:c,type:"defenseMalus",selected:!0});let m={...b.rangeWeaponModifiers};delete m[O.hasVantage(t,game.i18n.localize("LocalizedIDs.senseOfRange"))?"long":"rangesense"],R.hasAbility(t,game.i18n.localize("LocalizedIDs.extremeShot"))||delete m.extreme;let d=R.hasAbility(t,game.i18n.localize("LocalizedIDs.drivingArcher")),p=R.hasAbility(t,game.i18n.localize("LocalizedIDs.mountedArcher")),g;p&&H.isRiding(t)?g=duplicate(b.mountedRangeOptionsSpecAb):d?g=duplicate(b.drivingArcherOptions):g=duplicate(b.mountedRangeOptions),this.swarmModifiers(t,"attack",e),mergeObject(a,{rangeOptions:m,rangeDistance:Object.keys(m)[J.distanceModifier(game.canvas.tokens.get(i),s,r)],sizeOptions:b.rangeSizeCategories,visionOptions:b.rangeVision,mountedOptions:g,shooterMovementOptions:b.shooterMovementOptions,targetMovementOptions:b.targetMomevementOptions,targetSize:o,combatSpecAbs:n,aimOptions:b.aimOptions})}static swarmModifiers(e,t,a){e.system.swarm?.count>1&&(t=="attack"?a.push({name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("MODS.defenseMalus")}`,value:e.system.swarm.parry,type:"defenseMalus",selected:!0},{name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("CHARAbbrev.AT")}`,value:e.system.swarm.attack,selected:!0},{name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("CHARAbbrev.damage")}`,value:e.system.swarm.damage,type:"dmg",selected:!0}):a.push({name:`${game.i18n.localize("swarm.name")} - ${game.i18n.localize("CHARAbbrev.PA")}`,value:e.system.swarm.parry,selected:!0}))}static prepareMeleeAttack(e,t,a,s,i,n){let r="short";game.user.targets.forEach(m=>{if(m.actor){for(let d of m.actor.items)if((d.type=="meleeweapon"&&d.system.worn.value||d.type=="trait"&&d.system.traitType.value=="meleeAttack"&&d.system.pa)&&(b.meleeRangesArray.indexOf(d.system.reach.value)>b.meleeRangesArray.indexOf(r)&&(r=d.system.reach.value),r=="long"))break}});let o=this.getTargetSizeAndModifier(t,s,e);this.getCombatSkillModifier(t,s,e);let c=Number(t.system.meleeStats.defenseMalus)*-1;c!=0&&e.push({name:`${game.i18n.localize("statuseffects")} - ${game.i18n.localize("MODS.defenseMalus")}`,value:c,type:"defenseMalus",selected:!0}),this.swarmModifiers(t,"attack",e),mergeObject(a,{visionOptions:b.meleeRangeVision(a.mode),weaponSizes:b.meleeRanges,melee:!0,showAttack:!0,targetWeaponSize:r,combatSpecAbs:i,meleeSizeOptions:b.meleeSizeCategories,targetSize:o,constricted:t.hasCondition("constricted"),wrongHandDisabled:n,offHand:!n&&getProperty(s,"system.worn.offHand")})}static prepareMeleeParry(e,t,a,s,i,n){let r=he.getDefenseMalus(e,t);this.swarmModifiers(t,"parry",e),mergeObject(a,{visionOptions:b.meleeRangeVision(a.mode),showDefense:!0,isRangeDefense:r,wrongHandDisabled:n&&getProperty(s,"system.worn.offHand"),offHand:!n&&getProperty(s,"system.worn.offHand")&&!P.isShield(s),melee:!0,combatSpecAbs:i,constricted:t.hasCondition("constricted")})}static _chatLineHelper(e,t){return`${game.i18n.localize(e)}: ${t||"-"}`}static setupDialog(e,t,a,s,i){return null}setupEffect(e,t={},a){return he.getSubClass(this.type).setupDialog(e,t,this,a)}static checkEquality(e,t){return t.type==e.type&&e.name==t.name&&e.system.description?.value==t.system.description?.value}static async combineItem(e,t,a){return e=duplicate(e),e.system.quantity.value+=t.system.quantity.value,await a.updateEmbeddedDocuments("Item",[e])}static areEquals(e,t){return e.type!=t.type||e.id==t.id?!1:he.getSubClass(e.type).checkEquality(e,t)}static async stackItems(e,t,a){return await he.getSubClass(e.type).combineItem(e,t,a)}_setupCardOptions(e,t,a){let s=ChatMessage.getSpeaker();return{speaker:{alias:s.alias,scene:s.scene},flags:{img:s.token?canvas.tokens.get(s.token).document.img:this.img},title:t,template:e}}async itemTest({testData:e,cardOptions:t},a={}){e=await _DiceDSA5.rollDices(e,t);let s=await _DiceDSA5.rollTest(e);if(s.postFunction="itemTest",game.user.targets.size){t.isOpposedTest=e.opposable;let i=` - ${game.i18n.localize("Opposed")}`;t.isOpposedTest&&t.title.match(i+"$")!=i&&(t.title+=i)}return a.suppressMessage||_DiceDSA5.renderRollCard(t,s,a.rerenderMessage),{result:s,cardOptions:t}}static chatData(e,t){return[]}static getSubClass(e){return game.dsa5.config.ItemSubclasses[e]||he}async postItem(){he.getSubClass(this.type)._postItem(this)}static async _postItem(e){let t=duplicate(e),a=getProperty(t,"system.obfuscation.details"),s=getProperty(t,"system.obfuscation.description");if(mergeObject(t,{properties:a?[]:he.getSubClass(e.type).chatData(duplicate(t.system),e.name),descriptionObfuscated:s}),t.hasPrice="price"in t.system&&!a,t.hasPrice){let r=t.system.price.value;t.system.QL&&(r=he.getSubClass(t.type).consumablePrice(t)),t.system.price.D=Math.floor(r/10),r-=t.system.price.D*10,t.system.price.S=Math.floor(r),r-=t.system.price.S,t.system.price.H=Math.floor(r/.1),r-=t.system.price.H*.1,t.system.price.K=Math.round(r/.01);let o=["D","S","H","K"].map(c=>`${t.system.price[c]}
    `).join(",");t.properties.push(`${game.i18n.localize("price")}: ${o}`)}e.pack&&(t.itemLink=e.link),t.img.includes("/blank.webp")&&(t.img=null);let i=await renderTemplate("systems/dsa5/templates/chat/post-item.html",t),n=f.chatDataSetup(i);ChatMessage.create(n)}},C=he;u(C,"Itemdsa5"),L(C,"defaultImages",{advantage:"systems/dsa5/icons/categories/Vorteil.webp",disadvantage:"systems/dsa5/icons/categories/Nachteil.webp",armor:"systems/dsa5/icons/categories/Armor.webp",meleeweapon:"systems/dsa5/icons/categories/Meleeweapon.webp",rangeweapon:"systems/dsa5/icons/categories/Rangeweapon.webp",equipment:"systems/dsa5/icons/categories/Equipment.webp",consumable:"systems/dsa5/icons/categories/consumable.webp",liturgy:"systems/dsa5/icons/categories/Liturgy.webp",spell:"systems/dsa5/icons/categories/Spell.webp",ammunition:"systems/dsa5/icons/categories/Munition.webp",career:"systems/dsa5/icons/categories/Career.webp",magictrick:"systems/dsa5/icons/categories/Spelltrick.webp",blessing:"systems/dsa5/icons/categories/Blessing.webp",combatskill:"systems/dsa5/icons/categories/Combat_Skill.webp",skill:"systems/dsa5/icons/categories/Skill.webp",Geweihte:"systems/dsa5/icons/categories/Geweihte.webp",Weltliche:"systems/dsa5/icons/categories/Weltliche.webp",Zauberer:"systems/dsa5/icons/categories/Zauberer.webp",ritual:"systems/dsa5/icons/categories/ritual.webp",ceremony:"systems/dsa5/icons/categories/ceremony.webp",abilityclerical:"systems/dsa5/icons/categories/ability_clerical.webp",abilityCombat:"systems/dsa5/icons/categories/ability_combat.webp",abilityfatePoints:"systems/dsa5/icons/categories/ability_fate_points.webp",abilitygeneral:"systems/dsa5/icons/categories/ability_general.webp",specialability:"systems/dsa5/icons/categories/ability_general.webp",abilitymagical:"systems/dsa5/icons/categories/ability_magical.webp",abilitylanguage:"systems/dsa5/icons/categories/Ability_Language.webp",abilitystaff:"systems/dsa5/icons/categories/ability_staff.webp",abilityceremonial:"systems/dsa5/icons/categories/ability_ceremonial.webp",abilityanimal:"systems/dsa5/icons/categories/ability_animal.webp",trait:"systems/dsa5/icons/categories/trait.webp",Tiere:"systems/dsa5/icons/categories/Tiere.webp",aggregatedTest:"systems/dsa5/icons/categories/aggregated_test.webp",poison:"systems/dsa5/icons/categories/poison.webp",disease:"systems/dsa5/icons/categories/disease.webp",spellextension:"systems/dsa5/icons/categories/Spellextension.webp",species:"icons/environment/people/group.webp",application:"systems/dsa5/icons/categories/Skill.webp",trick:"systems/dsa5/icons/categories/Tiere.webp",disadvantageanimal:"systems/dsa5/icons/categories/NachteilAnimal.webp",advantageanimal:"systems/dsa5/icons/categories/VorteilAnimal.webp",diseaseanimal:"systems/dsa5/icons/categories/diseaseAnimal.webp",effectwrapper:"icons/svg/aura.svg",liturgyTalisman:"systems/dsa5/icons/categories/LiturgieTalisman.webp",plant:"systems/dsa5/icons/categories/plant.webp",magicalsign:"systems/dsa5/icons/categories/magicalsign.webp",abilitypact:"systems/dsa5/icons/categories/ability_pact.webp",demonmark:"systems/dsa5/icons/categories/ability_pact.webp",patron:"systems/dsa5/icons/categories/ability_pact.webp",information:"systems/dsa5/icons/categories/DSA-Auge.webp",essence:"systems/dsa5/icons/categories/wesenszug.webp",imprint:"systems/dsa5/icons/categories/praegung.webp"});var Wa=class extends C{static chatData(e,t){return[this._chatLineHelper("effect",e.effect),this._chatLineHelper("PLANT.recipes",e.recipes),this._chatLineHelper("PLANT.usages",e.usages)]}};u(Wa,"PlantItemDSA5");var Ua=class extends C{static chatData(e,t){let a=[this._chatLineHelper("AsPCost",e.asp)];return e.category==2&&a.push(this._chatLineHelper("feature",e.feature)),a}};u(Ua,"MagicalSignItemDSA5");var Va=class extends C{static chatData(e,t){return[this._chatLineHelper("attributes",e.attribute),this._chatLineHelper("skills",e.skills),this._chatLineHelper("domains",e.domain)]}};u(Va,"DemonmarkItemDSA5");var Ka=class extends C{static chatData(e,t){return[this._chatLineHelper("skills",e.talents),this._chatLineHelper("culture",e.culture),this._chatLineHelper("Category",game.i18n.localize(`PATRON.${e.category}`))]}};u(Ka,"PatronItemDSA5");var Ya=class extends C{static async _postItem(e){let t="",a=game.i18n.localize("Ongoing");e.system.cummulatedQS.value>=10?(a=game.i18n.localize("Success"),t=`${await TextEditor.enrichHTML(e.system.partsuccess,{secrets:this.isOwner,async:!0})}${await TextEditor.enrichHTML(e.system.success,{secrets:this.isOwner,async:!0})}`):e.system.cummulatedQS.value>=6?(a=game.i18n.localize("PartSuccess"),t=`${await TextEditor.enrichHTML(e.system.partsuccess,{secrets:this.isOwner,async:!0})}`):e.system.allowedTestCount.value-e.system.usedTestCount.value<=0&&(a=game.i18n.localize("Failure"));let s=[this._chatLineHelper("cummulatedQS",`${e.system.cummulatedQS.value} / 10`),this._chatLineHelper("interval",e.system.interval.value),this._chatLineHelper("probes",`${e.system.usedTestCount.value} / ${e.system.allowedTestCount.value}`),this._chatLineHelper("result",a),t],i=getProperty(e,"system.obfuscation.description"),n=await renderTemplate("systems/dsa5/templates/chat/aggregatedTestResult.html",{descriptionObfuscated:i,item:e,properties:s}),r=f.chatDataSetup(n);ChatMessage.create(r)}};u(Ya,"aggregatedTestItemDSA5");var Ja=class extends C{static chatData(e,t){return[this._chatLineHelper("ammunitiongroup",game.i18n.localize(e.ammunitiongroup.value))]}};u(Ja,"AmmunitionItemDSA5");var Qa=class extends C{};u(Qa,"EffectWrapperItemDSA5");var Xa=class extends C{static chatData(e,t){let a=[this._chatLineHelper("protection",e.protection.value),this._chatLineHelper("encumbrance",e.encumbrance.value)];return e.effect.value!=""&&a.push(this._chatLineHelper("effect",e.effect.value)),a}};u(Xa,"ArmorItemDSA5");var qt=class extends C{static chatData(e,t){return[this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("targetCategory",e.targetCategory.value),this._chatLineHelper("feature",e.feature.value)]}};u(qt,"CantripItemDSA5");var Za=class extends qt{};u(Za,"BlessingItemDSA5");var We=class extends C{static chatData(e,t){return[this._chatLineHelper("castingTime",e.castingTime.value),this._chatLineHelper("AsPCost",e.AsPCost.value),this._chatLineHelper("distribution",e.distribution.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("reach",e.range.value),this._chatLineHelper("targetCategory",e.targetCategory.value),this._chatLineHelper("effect",f.replaceConditions(f.replaceDies(e.effect.value)))]}static async getCallbackData(e,t,a){e.testDifficulty=0,e.situationalModifiers=T._parseModifiers(t);let s=new FormDataExtended(t.find("form")[0]).object;e.calculatedSpellModifiers={castingTime:t.find(".castingTime").text(),cost:t.find(".aspcost").text(),reach:t.find(".reach").text(),maintainCost:t.find(".maintainCost").text()},e.situationalModifiers.push({name:game.i18n.localize("removeGesture"),value:Number(s.removeGesture)||0},{name:game.i18n.localize("removeFormula"),value:Number(s.removeFormula)||0},{name:game.i18n.localize("castingTime"),value:t.find(".castingTime").data("mod")},{name:game.i18n.localize("cost"),value:t.find(".aspcost").data("mod")},{name:game.i18n.localize("reach"),value:t.find(".reach").data("mod")},{name:game.i18n.localize("zkModifier"),value:s.zkModifier||0},{name:game.i18n.localize("skModifier"),value:s.skModifier||0},{name:game.i18n.localize("maintainedSpells"),value:s.maintainedSpells*-1}),e.extensions=We.getSpecAbModifiers(t),e.advancedModifiers={chars:[0,1,2].map(i=>s[`ch${i}`]),fws:s.fw,qls:s.qs},C.changeChars(e.source,...[0,1,2].map(i=>s[`characteristics${i}`])),await this.applyExtensions(e.source,e.extensions,a)}static async applyExtensions(e,t,a){P.ensureNumber(e);let s=Object.keys(le.rollModifiers).map(i=>`${i}.mod`);for(let i of t){let n=fromUuidSync(i.uuid);if(!!n)for(let r of n.effects)for(let o of r.changes)le.rollChanges.includes(o.key)||s.includes(o.key)||(o.key=="macro.transform"?await f.callItemTransformationMacro(o.value,e,r):r.apply(e,o))}}static getSpecAbModifiers(e){let t=[];for(let a of e.find(".specAbs.active"))t.push({name:a.dataset.name,title:a.getAttribute("title"),uuid:a.dataset.uuid});return t}static attackSpellMalus(e){let t=[];return e.system.effectFormula.value&&t.push({name:game.i18n.localize("MODS.defenseMalus"),value:-4,type:"defenseMalus",selected:!0,source:e.name}),t}static getPropertyModifiers(e,t){let a=["ceremony","liturgy"].includes(t.type),s=(getProperty(t,"system.feature")||"").replace(/\(a-z äöü\-\)/gi,"").split(",").map(c=>c.trim()),i=[],n=a?"KaPCost":"AsPCost",r=["FP","step","QL","TPM","FW",n];for(let c of r){let m=c=="step"?"":c,d=getProperty(e.system.skillModifiers,`feature.${c}`);i.push(...d.filter(p=>s.includes(p.target)).map(p=>({name:p.source,value:p.value,type:m,source:p.source})))}let o=getProperty(e.system.skillModifiers,`conditional.${n}`);return i.push(...o.map(c=>({name:c.target,value:c.value,type:n}))),i}static foreignSpellModifier(e,t,a,s){if(game.settings.get("dsa5","enableForeignSpellModifer")&&["npc","character"].includes(e.type)&&["spell","ritual"].includes(t.type)){let i=t.system.distribution.value.split(",").map(o=>o.trim().toLowerCase()),n=new RegExp(`(${game.i18n.localize("tradition")}|\\)|\\()`,"g"),r=e.system.tradition.magical.replace(n,"").split(",").map(o=>o.trim().toLowerCase());r.push(game.i18n.localize("general").toLowerCase()),s.isForeign=!i.some(o=>r.includes(o)),s.isForeign&&a.push({name:game.i18n.localize("DSASETTINGS.enableForeignSpellModifer"),value:-2,selected:!0})}}static getSituationalModifiers(e,t,a,s){e.push(...te.getTalentBonus(t,s.name,["advantage","disadvantage","specialability","equipment"]),...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.magicalAttunement"),1,!0),...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.magicalRestriction"),-1,!0),...O.getVantageAsModifier(t,game.i18n.localize("LocalizedIDs.boundToArtifact"),-1,!0),...this.getPropertyModifiers(t,s),...this.attackSpellMalus(s)),this.foreignSpellModifier(t,s,e,a),game.user.targets.size&&game.user.targets.forEach(i=>{i.actor&&I.addCreatureTypeModifiers(i.actor,s,e,t)}),e.push(...t.getSkillModifier(s.name,s.type));for(let i of t.system.skillModifiers.global)e.push({name:i.source,value:i.value});this.getSkZkModifier(a,s)}static setupDialog(e,t,a,s,i){let n="spell";(a.type=="ceremony"||a.type=="liturgy")&&(n="liturgy");let r=a.name+" "+game.i18n.localize(`${a.type}Test`)+(t.subtitle||""),o={opposable:a.system.effectFormula.value.length>0,source:a,extra:{actor:s.toObject(!1),options:t,speaker:C.buildSpeaker(s,i)},advancedModifiers:{chars:[0,0,0],fws:0,qls:0},calculatedSpellModifiers:{castingTime:0,cost:0,reach:0,maintainCost:0}},c={rollMode:t.rollMode,spellCost:a.system.AsPCost.value,maintainCost:a.system.maintainCost.value,spellCastingTime:a.system.castingTime.value,spellReach:a.system.range.value,canChangeCost:a.system.canChangeCost.value=="true",canChangeRange:a.system.canChangeRange.value=="true",canChangeCastingTime:a.system.canChangeCastingTime.value=="true",hasSKModifier:a.system.resistanceModifier.value=="SK",hasZKModifier:a.system.resistanceModifier.value=="ZK",maxMods:Math.floor(Number(a.system.talentValue.value)/4),extensions:this.prepareExtensions(s,a),variableBaseCost:a.system.variableBaseCost=="true",characteristics:[1,2,3].map(g=>a.system[`characteristic${g}`].value)},m=s?E.getRollModifiers(s,a):[];this.getSituationalModifiers(m,s,c,a),c.situationalModifiers=m;let d={title:r,template:`/systems/dsa5/templates/dialog/${n}-enhanced-dialog.html`,data:c,callback:async(g,y={})=>(p.rollMode=g.find('[name="rollMode"]').val(),await this.getCallbackData(o,g,s),mergeObject(o.extra.options,y),{testData:o,cardOptions:p})},p=s._setupCardOptions("systems/dsa5/templates/chat/roll/spell-card.html",r,i);return _DiceDSA5.setupDialog({dialogOptions:d,testData:o,cardOptions:p})}static prepareExtensions(e,t){return e.items.filter(a=>a.type=="spellextension"&&a.system.source==t.name&&a.system.category==t.type).map(a=>(a.shortName=a.name.split(" - ").length>1?a.name.split(" - ")[1]:a.name,a.descr=$(a.system.description.value).text()||"",a))}};u(We,"SpellItemDSA5");var Wt=class extends We{static chatData(e,t){return[this._chatLineHelper("castingTime",e.castingTime.value),this._chatLineHelper("KaPCost",e.AsPCost.value),this._chatLineHelper("distribution",e.distribution.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("reach",e.range.value),this._chatLineHelper("targetCategory",e.targetCategory.value),this._chatLineHelper("effect",f.replaceConditions(f.replaceDies(e.effect.value)))]}};u(Wt,"LiturgyItemDSA5");var es=class extends Wt{static getCallbackData(e,t,a){super.getCallbackData(e,t,a),e.situationalModifiers.push({name:game.i18n.localize("CEREMONYMODIFIER.artefact"),value:t.find('[name="artefactUsage"]').is(":checked")?1:0},{name:game.i18n.localize("place"),value:t.find('[name="placeModifier"]').val()},{name:game.i18n.localize("time"),value:t.find('[name="timeModifier"]').val()})}static getSituationalModifiers(e,t,a,s){super.getSituationalModifiers(e,t,a,s),mergeObject(a,{isCeremony:!0,locationModifiers:b.ceremonyLocationModifiers,timeModifiers:b.ceremonyTimeModifiers})}};u(es,"CeremonyItemDSA5");var ts=class extends C{static chatData(e,t){return[this._chatLineHelper("Description",game.i18n.localize(`Combatskilldescr.${t}`))]}static setupDialog(e,t,a,s,i){let n=t.mode,r=a.name+" "+game.i18n.localize(n+"test"),o={opposable:!0,source:a,mode:n,extra:{actor:s.toObject(!1),options:t,speaker:C.buildSpeaker(s,i)}},c={title:r,template:"systems/dsa5/templates/dialog/combatskill-dialog.html",data:{rollMode:t.rollMode},callback:(d,p={})=>(m.rollMode=d.find('[name="rollMode"]').val(),o.situationalModifiers=T._parseModifiers(d),mergeObject(o.extra.options,p),{testData:o,cardOptions:m})},m=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",r,i);return _DiceDSA5.setupDialog({dialogOptions:c,testData:o,cardOptions:m})}};u(ts,"CombatskillDSA5");var as=class extends C{static chatData(e,t){return[this._chatLineHelper("qualityStep",e.QL),this._chatLineHelper("effect",f.replaceDies(e.QLList.split(` +`)[e.QL-1])),this._chatLineHelper("charges",e.charges)]}static consumablePrice(e){let t=e.system.price.value;if(isNaN(t)){let a=t.split(";");return t=Number(a[e.system.QL-1]),isNaN(t)&&(t=Number(a.pop())||0),t}else return Number(t)*e.system.QL||0}static checkEquality(e,t){return e.type==t.type&&e.name==t.name&&e.system.description.value==t.system.description.value&&e.system.QL==t.system.QL}static async setupDialog(e,t,a,s){let i=game.i18n.format("CHATNOTIFICATION.usesItem",{actor:a.actor.name,item:a.name});if(!a.isOwned)return;if((a.system.quantity.value-1)*a.system.maxCharges+a.system.charges<=0){ui.notifications.error(game.i18n.localize("DSAError.NotEnoughCharges"));return}let r=a.system.charges<=1?a.system.maxCharges:a.system.charges-1,o=a.system.charges<=1?a.system.quantity.value-1:a.system.quantity.value,c=f.replaceDies(a.system.QLList.split(` +`)[a.system.QL-1],!1),m=`
    ${i}
    ${a.system.description.value}
    ${game.i18n.localize("effect")}: ${c}
    `;o==0?await a.actor.deleteEmbeddedDocuments("Item",[a.id]):await a.update({"system.quantity.value":o,"system.charges":r}),await ChatMessage.create(f.chatDataSetup(m)),await this._applyActiveEffect(a)}static async _applyActiveEffect(e){let t=e.effects.toObject();if(t.length>0){let{msg:a,resistRolls:s,effectNames:i}=await Q.applyAdvancedFunction(e.actor,t,e,{qualityStep:e.system.QL},e.actor),n=`${game.i18n.format("ActiveEffects.appliedEffect",{target:e.actor.token?.name||e.actor.name,source:i.join(", ")})} ${a||""}`;ChatMessage.create(f.chatDataSetup(n))}}static async combineItem(e,t,a){e=duplicate(e);let s=(e.system.quantity.value-1)*e.system.maxCharges+e.system.charges,i=(t.system.quantity.value-1)*t.system.maxCharges+t.system.charges,n=Math.floor((s+i)/e.system.maxCharges)+1,r=(s+i)%e.system.maxCharges;return r==0&&(n-=1,r=e.system.maxCharges),e.system.quantity.value=n,e.system.charges=r,await a.updateEmbeddedDocuments("Item",[e])}};u(as,"ConsumableItemDSA");var ss=class extends C{static async _postItem(e){let t=await renderTemplate("systems/dsa5/templates/chat/informationRequestRoll.html",{item:e}),a=f.chatDataSetup(t);ChatMessage.create(a)}};u(ss,"InformationItemDSA5");var is=class extends C{static chatData(e,t){return[this._chatLineHelper("stepValue",e.step.value),this._chatLineHelper("incubation",e.incubation.value),this._chatLineHelper("damage",f.replaceConditions(f.replaceDies(e.damage.value))),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("source",f.replaceDies(e.source.value)),this._chatLineHelper("treatment",e.treatment.value),this._chatLineHelper("antidot",e.antidot.value),this._chatLineHelper("resistanceModifier",e.resistance.value)]}static getSituationalModifiers(e,t,a,s){s=f.toObjectIfPossible(s),game.user.targets.size&&game.user.targets.forEach(i=>{i.actor&&e.push(...O.getVantageAsModifier(i.actor,game.i18n.localize("LocalizedIDs.ResistanttoDisease"),-1,!1,!0))}),this.getSkZkModifier(a,s),mergeObject(a,{hasSKModifier:s.system.resistance.value=="SK",hasZKModifier:s.system.resistance.value=="ZK"})}static setupDialog(e,t,a,s,i){let n=a.name+" "+game.i18n.localize(a.type)+" "+game.i18n.localize("Test"),r={opposable:!1,source:a,extra:{options:t,speaker:C.buildSpeaker(s,i)}},o={rollMode:t.rollMode},c=[];this.getSituationalModifiers(c,s,o,a),o.situationalModifiers=c,t.manualResistance&&mergeObject(o,t.manualResistance);let m={title:n,template:"/systems/dsa5/templates/dialog/poison-dialog.html",data:o,callback:(p,g={})=>(d.rollMode=p.find('[name="rollMode"]').val(),r.situationalModifiers=T._parseModifiers(p),r.situationalModifiers.push({name:game.i18n.localize("zkModifier"),value:p.find('[name="zkModifier"]').val()||0},{name:game.i18n.localize("skModifier"),value:p.find('[name="skModifier"]').val()||0}),mergeObject(r.extra.options,g),{testData:r,cardOptions:d})},d=a._setupCardOptions(`systems/dsa5/templates/chat/roll/${a.type}-card.html`,n,i);return _DiceDSA5.setupDialog({dialogOptions:m,testData:r,cardOptions:d})}};u(is,"DiseaseItemDSA5");var ns=class extends C{static chatData(e,t){return[this._chatLineHelper("equipmentType",game.i18n.localize(`Equipment.${e.equipmentType.value}`))]}};u(ns,"EquipmentItemDSA5");var kt=class extends C{static chatData(e,t){let a=[this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("atmod",e.atmod.value),this._chatLineHelper("pamod",e.pamod.value),this._chatLineHelper("reach",game.i18n.localize(`Range-${e.reach.value}`)),this._chatLineHelper("TYPES.Item.combatskill",e.combatskill.value)];return e.effect.value!=""&&a.push(this._chatLineHelper(f.replaceConditions("effect",e.effect.value))),a}static getSituationalModifiers(e,t,a,s){let i=O.hasVantage(t,game.i18n.localize("LocalizedIDs.ambidextrous"));s=f.toObjectIfPossible(s);let n=[s.system.combatskill.value],r=C.buildCombatSpecAbs(t,["Combat"],n,a.mode);a.mode=="attack"?this.prepareMeleeAttack(e,t,a,s,r,i):a.mode=="parry"&&this.prepareMeleeParry(e,t,a,s,r,i),this.attackStatEffect(e,t.system.meleeStats[a.mode]),["attack","parry"].includes(a.mode)&&e.push(...kt.getMiracleModifiers(t,{name:s.system.combatskill.value},"",a.mode))}static setupDialog(e,t,a,s,i){let n=t.mode,r=a.name+" "+game.i18n.localize(n+"test"),o={opposable:t.mode!="parry",source:a,mode:n,extra:{actor:s.toObject(!1),options:t,speaker:C.buildSpeaker(s,i)}},c=P.multipleDefenseValue(s,f.toObjectIfPossible(a)),m={rollMode:t.rollMode,mode:n,defenseCountString:game.i18n.format("defenseCount",{malus:c})},d=s?E.getRollModifiers(s,a,{mode:n}):[];this.getSituationalModifiers(d,s,m,a),m.situationalModifiers=d,t.situationalModifiers&&m.situationalModifiers.push(...t.situationalModifiers);let p={title:r,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:m,callback:(y,h={})=>(ge.resolveMeleeDialog(o,g,y,s,h,c,n),Hooks.call("callbackDialogCombatDSA5",o,s,y,a,i),o.isRangeDefense=m.isRangeDefense,{testData:o,cardOptions:g})},g=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",r,i);return _DiceDSA5.setupDialog({dialogOptions:p,testData:o,cardOptions:g})}};u(kt,"MeleeweaponDSA5");var rs=class extends C{static chatData(e,t){return[this._chatLineHelper("stepValue",e.step.value),this._chatLineHelper("poisonType",e.poisonType.value),this._chatLineHelper("start",e.start.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("resistanceModifier",e.resistance.value),this._chatLineHelper("effect",f.replaceConditions(f.replaceDies(e.effect.value)))]}static getSituationalModifiers(e,t,a,s){s=f.toObjectIfPossible(s),game.user.targets.size&&game.user.targets.forEach(i=>{i.actor&&e.push(...O.getVantageAsModifier(i.actor,game.i18n.localize("LocalizedIDs.poisonResistance"),-1,!1,!0))}),this.getSkZkModifier(a,s),mergeObject(a,{hasSKModifier:s.system.resistance.value=="SK",hasZKModifier:s.system.resistance.value=="ZK"})}static setupDialog(e,t,a,s,i){let n=a.name+" "+game.i18n.localize(a.type)+" "+game.i18n.localize("Test"),r={opposable:!1,source:a,extra:{options:t,speaker:C.buildSpeaker(s,i)}},o={rollMode:t.rollMode},c=[];this.getSituationalModifiers(c,s,o,a),o.situationalModifiers=c;let m={title:n,template:"/systems/dsa5/templates/dialog/poison-dialog.html",data:o,callback:(p,g={})=>(d.rollMode=p.find('[name="rollMode"]').val(),r.situationalModifiers=T._parseModifiers(p),r.situationalModifiers.push({name:game.i18n.localize("zkModifier"),value:p.find('[name="zkModifier"]').val()||0}),r.situationalModifiers.push({name:game.i18n.localize("skModifier"),value:p.find('[name="skModifier"]').val()||0}),mergeObject(r.extra.options,g),{testData:r,cardOptions:d})},d=a._setupCardOptions(`systems/dsa5/templates/chat/roll/${a.type}-card.html`,n,i);return _DiceDSA5.setupDialog({dialogOptions:m,testData:r,cardOptions:d})}};u(rs,"PoisonItemDSA5");var wt=class extends C{static chatData(e,t){let a=[this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("TYPES.Item.combatskill",e.combatskill.value),this._chatLineHelper("reach",e.reach.value)];return e.effect.value!=""&&a.push(this._chatLineHelper(f.replaceConditions("effect",e.effect.value))),a}static getSituationalModifiers(e,t,a,s,i){if(a.mode=="attack"){let n=f.toObjectIfPossible(s),r=[n.system.combatskill.value],o=C.buildCombatSpecAbs(t,["Combat"],r,a.mode),c=t.items.get(n.system.currentAmmo.value);if(c){c=c.toObject(!1),n.system.effect.attributes=(n.system.effect.attributes||"").split(",").concat((c.system.effect.attributes||"").split(",")).filter(d=>d!="").join(",");let m=getProperty(c.flags,"dsa5.poison");m&&mergeObject(s.flags,{dsa5:{poison:m}})}if(this.prepareRangeAttack(e,t,a,n,i,o,c),c){if(c.system.atmod&&e.push({name:`${c.name} - ${game.i18n.localize("atmod")}`,value:c.system.atmod,selected:!0,specAbId:n.system.currentAmmo.value}),c.system.damageMod||c.system.armorMod){let m={name:`${c.name} - ${game.i18n.localize("MODS.damage")}`,value:c.system.damageMod.replace(/wWD/g,"d")||0,type:"dmg",selected:!0,specAbId:n.system.currentAmmo.value};c.system.armorMod&&(m.armorPen=c.system.armorMod),e.push(m)}c.effects.length&&e.push({name:`${c.name} - ${game.i18n.localize("TYPES.Item.ammunition")}`,value:1,type:"effect",selected:!0,specAbId:n.system.currentAmmo.value})}e.push(...wt.getMiracleModifiers(t,{name:n.system.combatskill.value},"",a.mode))}this.attackStatEffect(e,t.system.rangeStats[a.mode])}static async checkAmmunitionState(e,t,a,s){let i=!0;if(s!="damage"){let n=e.system;if(n.ammunitiongroup.value!="infinite")if(n.ammunitiongroup.value=="-")t.extra.ammo=duplicate(e),i=t.extra.ammo.system.quantity.value>0;else{let r=a.items.get(n.currentAmmo.value);r?(t.extra.ammo=r.toObject(),n.ammunitiongroup.value=="mag"?i=t.extra.ammo.system.quantity.value>1||t.extra.ammo.system.mag.value>0&&t.extra.ammo.system.quantity.value>0:i=t.extra.ammo.system.quantity.value>0):i=!1}!i&&a.type=="creature"&&(i=!0)}return i||ui.notifications.error(game.i18n.localize("DSAError.NoAmmo")),i}static async setupDialog(e,t,a,s,i){let n=t.mode,r=a.name+" "+game.i18n.localize(n+"test"),o={opposable:t.mode!="parry",source:a,mode:n,extra:{actor:s.toObject(!1),options:t,speaker:C.buildSpeaker(s,i)}};if(!await this.checkAmmunitionState(a,o,s,n))return;let c={rollMode:t.rollMode,mode:n},m=s?E.getRollModifiers(s,a,{mode:n}):[];this.getSituationalModifiers(m,s,c,a,i),c.situationalModifiers=m,t.situationalModifiers&&c.situationalModifiers.push(...t.situationalModifiers);let d={title:r,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:c,callback:(g,y={})=>(ge.resolveRangeDialog(o,p,g,s,y),Hooks.call("callbackDialogCombatDSA5",o,s,g,a,i),{testData:o,cardOptions:p})},p=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",r,i);return _DiceDSA5.setupDialog({dialogOptions:d,testData:o,cardOptions:p})}};u(wt,"RangeweaponItemDSA5");var os=class extends We{static getCallbackData(e,t,a){super.getCallbackData(e,t,a),e.situationalModifiers.push({name:game.i18n.localize("RITUALMODIFIER.rightClothes"),value:t.find('[name="rightClothes"]').is(":checked")?1:0},{name:game.i18n.localize("RITUALMODIFIER.rightEquipment"),value:t.find('[name="rightEquipment"]').is(":checked")?1:0},{name:game.i18n.localize("place"),value:t.find('[name="placeModifier"]').val()},{name:game.i18n.localize("time"),value:t.find('[name="timeModifier"]').val()})}static getSituationalModifiers(e,t,a,s){super.getSituationalModifiers(e,t,a,s),mergeObject(a,{isRitual:!0,locationModifiers:b.ritualLocationModifiers,timeModifiers:b.ritualTimeModifiers})}};u(os,"RitualItemDSA5");var ls=class extends C{static chatData(e,t){let s=game.i18n.has(`APPLICATION.${e.skill} - ${t}`)?game.i18n.localize(`APPLICATION.${e.skill} - ${t}`):e.description.value;return[this._chatLineHelper("Description",s)]}};u(ls,"ApplicationItemDSA5");var vt=class extends C{static chatData(e,t){let s=game.i18n.has(`SKILLdescr.${t}`)?game.i18n.localize(`SKILLdescr.${t}`):e.description.value;return[this._chatLineHelper("Description",s)]}static getSituationalModifiers(e,t,a,s){e.push(...te.getTalentBonus(t,s.name,["advantage","disadvantage","specialability","equipment"]),...t.getSkillModifier(s.name,s.type),...vt.getMiracleModifiers(t,s,"FW","skill"));for(let i of t.system.skillModifiers.global)e.push({name:i.source,value:i.value})}static setupDialog(e,t,a,s,i){let n=a.name+" "+game.i18n.localize("Test")+(t.subtitle||""),r={opposable:!0,source:a,extra:{actor:s.toObject(!1),options:t,speaker:C.buildSpeaker(s,i)}},o={rollMode:t.rollMode,difficultyLabels:b.skillDifficultyLabels,modifier:t.modifier||0,characteristics:[1,2,3].map(d=>a.system[`characteristic${d}`].value),situationalModifiers:s?E.getRollModifiers(s,a):[]};t.situationalModifiers&&o.situationalModifiers.push(...t.situationalModifiers),this.getSituationalModifiers(o.situationalModifiers,s,o,a);let c={title:n,template:"/systems/dsa5/templates/dialog/skill-dialog.html",data:o,callback:(d,p={})=>(m.rollMode=d.find('[name="rollMode"]').val(),r.testDifficulty=b.skillDifficultyModifiers[d.find('[name="testDifficulty"]').val()],r.situationalModifiers=T._parseModifiers(d),r.advancedModifiers={chars:[0,1,2].map(g=>Number(d.find(`[name="ch${g}"]`).val())),fws:Number(d.find('[name="fw"]').val()),qls:Number(d.find('[name="qs"]').val())},C.changeChars(r.source,...[0,1,2].map(g=>d.find(`[name="characteristics${g}"]`).val())),mergeObject(r.extra.options,p),{testData:r,cardOptions:m})},m=s._setupCardOptions("systems/dsa5/templates/chat/roll/skill-card.html",n,i);return _DiceDSA5.setupDialog({dialogOptions:c,testData:r,cardOptions:m})}};u(vt,"SkillItemDSA5");var cs=class extends C{static chatData(e,t){return[this._chatLineHelper("rule",e.rule.value)]}};u(cs,"SpecialAbilityItemDSA5");var ds=class extends C{};u(ds,"SpeciesItemDSA5");var ms=class extends C{static chatData(e,t){return[this._chatLineHelper("source",e.source),this._chatLineHelper("Category",game.i18n.localize(e.category))]}};u(ms,"SpellextensionItemDSA5");var us=class extends C{static chatData(e,t){let a=[];switch(e.traitType.value){case"meleeAttack":a=[this._chatLineHelper("attack",e.at.value),this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("reach",e.reach.value)];break;case"rangeAttack":a=[this._chatLineHelper("attack",e.at.value),this._chatLineHelper("damage",e.damage.value),this._chatLineHelper("reach",e.reach.value),this._chatLineHelper("reloadTime",e.reloadTime.value)];break;case"armor":a=[this._chatLineHelper("protection",e.damage.value)];break;case"general":a=[];break;case"familiar":a=[this._chatLineHelper("APValue",e.APValue.value),this._chatLineHelper("AsPCost",e.AsPCost.value),this._chatLineHelper("duration",e.duration.value),this._chatLineHelper("aspect",e.aspect.value)];break;case"trick":a=[this._chatLineHelper("APValue",e.APValue.value)];break;case"entity":a=[this._chatLineHelper("distribution",e.distribution),this._chatLineHelper("CHARAbbrev.QL",e.AsPCost.value)];break;case"summoning":a=[this._chatLineHelper("distribution",e.distribution),this._chatLineHelper("conjuringDifficulty",e.at.value)];break}return e.effect.value!=""&&a.push(this._chatLineHelper("effect",e.effect.value)),a}static getSituationalModifiers(e,t,a,s,i){s=f.toObjectIfPossible(s);let n=s.system.traitType.value,r=C.buildCombatSpecAbs(t,["Combat","animal"],void 0,a.mode);a.mode=="attack"&&n=="meleeAttack"?this.prepareMeleeAttack(e,t,a,s,r,!1):a.mode=="attack"&&n=="rangeAttack"?this.prepareRangeAttack(e,t,a,s,i,r):a.mode=="parry"&&this.prepareMeleeParry(e,t,a,s,r,!1),this.attackStatEffect(e,t.system[n=="meleeAttack"?"meleeStats":"rangeStats"][a.mode])}static setupDialog(e,t,a,s,i){let n=t.mode,r=a.name+" "+game.i18n.localize(n+"test"),o={opposable:t.mode!="parry",source:a,mode:n,extra:{actor:s.toObject(!1),options:t,speaker:C.buildSpeaker(s,i)}},c=P.multipleDefenseValue(s,a.toObject()),m={rollMode:t.rollMode,mode:n,defenseCountString:game.i18n.format("defenseCount",{malus:c})},d=getProperty(a,"system.traitType.value"),p=s?E.getRollModifiers(s,a,{mode:n}):[];this.getSituationalModifiers(p,s,m,a,i),m.situationalModifiers=p;let g={title:r,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:m,callback:(h,w={})=>(d=="meleeAttack"?ge.resolveMeleeDialog(o,y,h,s,w,c,n):ge.resolveRangeDialog(o,y,h,s,w),o.isRangeDefense=m.isRangeDefense,Hooks.call("callbackDialogCombatDSA5",o,s,h,a,i),{testData:o,cardOptions:y})},y=s._setupCardOptions("systems/dsa5/templates/chat/roll/combatskill-card.html",r,i);return _DiceDSA5.setupDialog({dialogOptions:g,testData:o,cardOptions:y})}};u(us,"TraitItemDSA5");var Ut=class extends C{static chatData(e,t){return[this._chatLineHelper("effect",e.effect.value)]}};u(Ut,"VantageItemDSA5");var Tt=class extends ie{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,resizable:!0}),e}static setData(e,t,a){let s=duplicate(Tt.rollModifiers);s.narrowSpace.mod=this.getNarrowSpaceModifier(a,a.mode);let i=`${t}RollModifiers`;if(e.system[i])for(let n of Object.keys(e.system[i]))s[n].mod+=Number(e.system[i][n]?.mod??0);return s}activateListeners(e){super.activateListeners(e);let t=e.find(".specAbs");t.mouseenter(i=>{if(i.currentTarget.getElementsByClassName("hovermenu").length==0){let n=document.createElement("div");n.classList.add("hovermenu");let r=document.createElement("i");r.classList.add("fas","fa-comment"),r.title=game.i18n.localize("SHEET.PostItem"),r.addEventListener("mousedown",this._postItem,!1),n.appendChild(r),i.currentTarget.appendChild(n)}}),t.mouseleave(i=>{let n=i.toElement||i.relatedTarget;n.parentNode==this||n==this||i.currentTarget.querySelectorAll(".hovermenu").forEach(r=>r.remove())}),e.find(".variantChange").mousedown(i=>this.changeSpecAbVariant(i)),e.on("mousedown",".specAbs",i=>{if(e.find(".opportunityAttack").is(":checked")){ui.notifications.error(game.i18n.localize("DSAError.opposedAttackNoSpecAbs"));return}let n=$(i.currentTarget),r=Number(n.attr("data-step")),o=Number(n.attr("data-maxStep")),c=Number(n.attr("data-category"));if(i.button==0){if(r=Math.min(o,r+1),[0,1].includes(c)&&game.settings.get("dsa5","limitCombatSpecAbs")){let m=n.siblings(`[data-category="${c}"]`);m.removeClass("active").attr("data-step",0),m.find(".step").text(ie.roman[0])}}else i.button==2&&(r=Math.clamped(o,0,r-1));n.attr("data-step",r),n.toggleClass("active",r>0),n.find(".step").text(ie.roman[r]),this.checkCounterAttack(i),this.calculateModifier()}),e.find(".opportunityAttack").change(i=>{if($(i.currentTarget).is(":checked"))for(let n of e.find(".specAbs"))$(n).removeClass("active").attr("data-step",0).find(".step").text("")}),e.on("change","input,select",i=>this.calculateModifier(i)),e.find(".modifiers option").mousedown(i=>{this.calculateModifier(i)}),e.find(".quantity-click").mousedown(i=>this.calculateModifier(i));let a=this.readTargets();this.calculateModifier();let s=this;this.checkTargets=setInterval(function(){a=s.compareTargets(e,a)},500)}checkCounterAttack(e){if(!this.dialogData.mode=="parry")return;let t=f.getSpeaker(this.dialogData.speaker);if(t&&t.items.get(e.currentTarget.dataset.id).name==game.i18n.localize("LocalizedIDs.counterAttack")){this.dialogData.counterAttack=e.button==0,this.prepareWeapon();let s=e.button==0?"attack":"parry",i=t.items.get(this.dialogData.source._id),n=E.getRollModifiers(t,i,{mode:s});if(C.getSubClass(i.type).getSituationalModifiers(n,t,{mode:s},i),s=="attack"){n=n.filter(p=>p.type!="defenseMalus");let o=n.findIndex(p=>p.name==game.i18n.localize("statuseffects")),c;o>=0&&(c=n.splice(o,1).pop());let m=[];C.getSubClass(i.type).getSituationalModifiers(m,t,{mode:"parry"},i),o=m.findIndex(p=>p.name==game.i18n.localize("statuseffects"));let d;o>=0&&(d=m.splice(o,1).pop()),n.unshift(...m),c?(d&&(c.value+=d.value),n.push(c)):d&&n.push(d)}let r=$(this._element).find("[name=situationalModifiers]");if(n.length>0){if(r.length==0){let c=`
    `,buttons:{Yes:{icon:'',label:game.i18n.localize("Roll"),callback:r=>{W.resolveBreakingTest(e,Number(r.find('[name="threshold"]').val()),a)}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}static async applyDamageLevelToItem(e,t){let a=Math.ceil(e.system.structure.max*.25)*t;await e.update({"system.structure.value":Math.max(0,e.system.structure.value-a)})}static async absoluteDamageLevelToItem(e,t){let a=Math.ceil(e.system.structure.max*.25)*t;await e.update({"system.structure.value":Math.min(e.system.structure.value,Math.max(0,e.system.structure.max-a))})}static async resolveBreakingTest(e,t,a){let s=await _DiceDSA5.manualRolls(await new Roll("1d20").evaluate({async:!0}),game.i18n.format("WEAR.check",{category:a}));await _DiceDSA5.showDiceSoNice(s,await game.settings.get("core","rollMode"));let i=s.total>t?1:0;await this.applyDamageLevelToItem(e,i);let r=W.calculateWear(e.data),n=await renderTemplate("systems/dsa5/templates/system/breakingtest.html",{wear:r,item:e,threshold:t,category:a,roll:s,result:game.i18n.localize(`WEAR.${e.type}.${r}`)});ChatMessage.create(f.chatDataSetup(n))}static damageTooltip(e){if(game.settings.get("dsa5","armorAndWeaponDamage")){let t=this.calculateWear(e);return{msg:game.i18n.localize(`WEAR.${e.type}.${t}`),css:`gearD damaged${t}`}}return{msg:"",css:""}}static weaponWearModifier(e){if(game.settings.get("dsa5","armorAndWeaponDamage"))switch(W.calculateWear(e)){case 1:e.attack-=1,e.parry&&(e.parry-=1);break;case 2:e.attack-=2,e.parry&&(e.parry-=2);break;case 3:case 4:e.attack=0,e.parry&&(e.parry=0)}}static calculateWear(e){return!e.system.structure||Number(e.system.structure.max<=0)?0:Math.floor((1-e.system.structure.value/e.system.structure.max)*4)}};u(W,"EquipmentDamage");var fe=class{static prepareSoundEffects(){fe.soundPaths={money:[],armor:[],meleeweapon:[],rangeweapon:[],default:[]},game.modules.get("gAudioBundle-3")&&(fe.soundPaths.money.push("modules/gAudioBundle-3/src/Mint Coins And Money/Coin_Slide_Carpet.ogg","modules/gAudioBundle-3/src/Mint Coins And Money/Coins_Drop_Carpet_06.ogg","modules/gAudioBundle-3/src/Mint Coins And Money/Coins_Bottlecaps_Drop.ogg","modules/gAudioBundle-3/src/Mint Coins And Money/Coins_In_Sack_Held_By_Drawstring_06.ogg","modules/gAudioBundle-3/src/Money/Money_Coins_Handle.ogg"),fe.soundPaths.meleeweapon.push("modules/gAudioBundle-3/src/Medieval Armor And Impacts/Weapon_Impact_Parry_01.ogg")),game.modules.get("gAudioBundle-2")&&(fe.soundPaths.meleeweapon.push("modules/gAudioBundle-2/src/Gore/Melee_Sword_Attack_04.ogg"),fe.soundPaths.armor.push("modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Foley_Soldier_Gear_Equipment_Metal_Cloth_Heavy_Movement_Light_08.ogg"),fe.soundPaths.default.push("modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Foley_Sports_Bag_Grab_Pickup_Catch_04.ogg","modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Footstep_Ice_Crunchy_Run_01.ogg","modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Footstep_Ice_Crunchy_Run_02.ogg")),game.modules.get("gAudioBundle-4")&&fe.soundPaths.rangeweapon.push("modules/gAudioBundle-4/src/Super Heroes Sound Design/Hawk's_Arrow_Flies_Bow_And_Arrow_Shoot_2.ogg"),Hooks.call("setDefaultDSASounds",fe.soundPaths)}static async playEffect(e,t,a,s=void 0,i=!1){let r=await this.getSound(e,t,a);if(r)try{s?(game.socket.emit("system.dsa5",{type:"playWhisperSound",payload:{whisper:s,soundPath:r}}),i||AudioHelper.play({src:r,volume:.8,loop:!1},!1)):AudioHelper.play({src:r,volume:.8,loop:!1},!0)}catch{console.warn(`Could not play item sound effect ${r}`)}}static async loadSoundConfig(){let e=await game.settings.get("dsa5","soundConfig");if(e)try{let a=await(await fetch(e)).json();this.sounds=a,console.log("DSA5 | Sound Config Loaded")}catch(t){console.warn(t)}}static successLevelToString(e){switch(e){case-1:return["fail"];case-2:return["botch","fail"];case 1:return["success"];case 2:return["crit","success"];default:return[]}}static async getSound(e,t,a){if(!this.sounds&&!this.triedInit&&(await this.loadSoundConfig(),this.triedInit=!0),!this.sounds)return;let s=this.successLevelToString(a),i=[],r;switch(t.type){case"meleeweapon":case"rangeweapon":i=[...s.map(n=>`${t.type}.manual.${t.name}.${e}_${n}`),`${t.type}.manual.${t.name}.${e}`,`${t.type}.manual.${t.name}.default.${e}`,`${t.type}.manual.${t.name}.default`,...s.map(n=>`${t.type}.${t.system.combatskill.value}.${e}_${n}`),`${t.type}.${t.system.combatskill.value}.${e}`,...s.map(n=>`${t.type}.${t.system.combatskill.value}.default_${n}`),`${t.type}.${t.system.combatskill.value}.default`];break;case"skill":i=[...s.map(n=>`${t.type}.${t.name}.${e}_${n}`),`${t.type}.${t.name}.${e}`,...s.map(n=>`${t.type}.${t.name}.default_${n}`),`${t.type}.${t.name}.default`];break;case"liturgy":case"spell":case"ceremony":case"ritual":i=[...s.map(n=>`${t.type}.${t.name}.${e}_${n}`),`${t.type}.${t.name}.${e}`,...s.map(n=>`${t.type}.${t.name}.default_${n}`),`${t.type}.${t.name}.default`];break}i.push(...s.map(n=>`${t.type}.default_${n}`),`${t.type}.default`);for(let n of i)if(!!hasProperty(this.sounds,n)&&(r=getProperty(this.sounds,n),r&&(typeof r=="string"||r instanceof String)))break;return r}static async playMoneySound(e=!1){let t=fe.soundPaths.money,a=t[Math.floor(Math.random()*t.length)];await this.playSoundPath(a,e)}static async playEquipmentWearStatusChange(e,t=!1){let a=fe.soundPaths[e.type]||fe.soundPaths.default;if(a.length>0){let s=a[Math.floor(Math.random()*a.length)];await this.playSoundPath(s,t,.5)}}static async playSoundPath(e,t=!1,a=.8){if(!!game.settings.get("dsa5","inventorySound"))try{AudioHelper.play({src:e,volume:a,loop:!1},t)}catch{console.warn(`Could not play item sound effect ${e}`)}}},K=fe;u(K,"DSA5SoundEffect"),L(K,"sounds"),L(K,"triedInit",!1);var X=class{constructor(e){this.item=e}async callMacro(e,t,a={}){let i=await game.packs.get(e)?.getDocuments({name:t});if(!i||!i.length){for(let n of game.packs.filter(o=>o.documentName=="Macro"&&/\(internal\)/.test(o.metadata.label)))if(i=await n.getDocuments({name:t}),i.length)break}let r={};if(i.length)try{a.result=r;let n=Object.getPrototypeOf(async function(){}).constructor,o=new n("args","actor","item",` - const that = this; - ${i[0].command.replace(/( |\(|{)this\./g," that.")} - `);r.ret=await o.call(this,a,this.item.actor,this.item)}catch(n){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(n),r.error=!0}else ui.notifications.error(game.i18n.format("DSAError.macroNotFound",{name:t}));return r}async executeOnUseEffect(){if(!this.item.actor)return;if(!game.user.can("MACRO_SCRIPT"))return ui.notifications.warn("You are not allowed to use JavaScript macros.");let e=X.getOnUseEffect(this.item);try{let t=Object.getPrototypeOf(async function(){}).constructor;await new t("item","actor",e).call(this,this.item,this.item.actor)}catch(t){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(t),console.warn(t.stack)}}static getOnUseEffect(e){return e.getFlag("dsa5","onUseEffect")}async automatedAnimation(e,t={}){f.moduleEnabled("autoanimations")&&console.warn("Animations for on use effects not enabled yet")}effectDummy(e,t,a){return{name:e,icon:"icons/svg/aura.svg",changes:t,duration:a,flags:{dsa5:{value:null,editable:!0,description:e,custom:!0}}}}async socketedConditionAddActor(e,t){if(game.user.isGM){let a=typeof t=="string";a&&(t=duplicate(CONFIG.statusEffects.find(i=>i.id==t)),t.name=game.i18n.localize(t.name));let s=[];for(let i of e)a?await i.addCondition(t,1,!1,!1):await i.addCondition(t),s.push(i.name);await this.createInfoMessage(t,s)}else{let a={id:this.item.uuid,data:t,actors:e.map(s=>s.id)};game.socket.emit("system.dsa5",{type:"socketedConditionAddActor",payload:a})}}async createInfoMessage(e,t,a=!0){if(t.length){let s=a?"ActiveEffects.appliedEffect":"ActiveEffects.removedEffect",i=game.i18n.format(s,{source:e.name,target:t.join(", ")});await ChatMessage.create(f.chatDataSetup(i))}}async socketedRemoveCondition(e,t,a=1){if(game.user.isGM){let s=[];for(let r of e){let n=canvas.tokens.get(r);n.actor&&(await n.actor.removeCondition(t,a,!1),s.push(n.name))}let i=CONFIG.statusEffects.find(r=>r.id==t);i.name=game.i18n.localize(i.name),await this.createInfoMessage(i,s,!1)}else{let s={id:this.item.uuid,coreId:t,targets:e};game.socket.emit("system.dsa5",{type:"socketedRemoveCondition",payload:s})}}async socketedActorTransformation(e,t){if(game.user.isGM)for(let a of e){let s=canvas.tokens.get(a);s.actor&&await s.actor.update(t)}else{let a={id:this.item.uuid,targets:e,update:t};game.socket.emit("system.dsa5",{type:"socketedActorTransformation",payload:a})}}async socketedConditionAdd(e,t){if(game.user.isGM){let a=typeof t=="string";a&&(t=duplicate(CONFIG.statusEffects.find(i=>i.id==t)),t.name=game.i18n.localize(t.name));let s=[];for(let i of e){let r=canvas.tokens.get(i);r.actor&&(a?await r.actor.addCondition(t,1,!1,!1):await r.actor.addCondition(t),s.push(r.name))}await this.createInfoMessage(t,s)}else{let a={id:this.item.uuid,data:t,targets:e};game.socket.emit("system.dsa5",{type:"socketedConditionAdd",payload:a})}}};u(X,"OnUseEffect");var Ue=class{static async postOpposed(e){let t=f.getSpeaker(e.attacker.speaker);!t||await this.runMacro(t,e.attacker.testResult,7,e)}static async postRoll(e){let t=f.getSpeaker(e.testData.speaker);!t||await this.runMacro(t,e.testData,6,e)}static async callMacro(e,t,a,s={}){return await new X(e).callMacro(t,a,s)}static async runMacro(e,t,a,s){if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else for(let[i,r]of Object.entries(e.dsatriggers[a])){let n=e.items.get(i),o=n.effects.get(r),c=o.getFlag("dsa5","args3");try{let m=Object.getPrototypeOf(async function(){}).constructor;return await new m("actor","testData","type","data","source","ef",c).call(this,e,t,a,s,n,o)}catch(m){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(m)}}}};u(Ue,"DSATriggers");var j=class{static async handleOpposedTarget(e){if(!e)return;let t=f.getSpeaker(e.speaker);if(!t)return;let a=e.flags.data.postData,s=e.flags.data.preData;t.flags.oppose?j.answerOpposedTest(t,e,a,s):game.user.targets.size&&e.flags.data.isOpposedTest&&!e.flags.data.defenderMessage&&!e.flags.data.attackerMessage?j.createOpposedTest(t,e,a,s):e.flags.data.defenderMessage||e.flags.data.attackerMessage?j.resolveFinalMessage(e):e.flags.data.unopposedStartMessage?j.redoUndefended(e):e.flags.data.startMessagesList?j.changeStartMessage(e):(await this.showDamage(e),await this.showSpellWithoutTarget(e))}static async redoUndefended(e){let t=game.messages.get(e.flags.data.unopposedStartMessage);startmessage.flags.unopposeData.attackMessageId=e.id,this.resolveUndefended(t)}static async answerOpposedTest(e,t,a,s){let i=game.messages.get(e.flags.oppose.messageId);if(!i)return ui.notifications.error(game.i18n.localize("DSAError.staleData")),await j.clearOpposed(e),j.createOpposedTest(e,t,a,s);let r={speaker:e.flags.oppose.speaker,testResult:i.flags.data.postData,messageId:i.id,img:f.getSpeaker(e.flags.oppose.speaker)?.img};r.testResult.source=i.flags.data.preData.source,r.testResult.ammo&&r.testResult.source.effects.push(...r.testResult.ammo.effects);let n={speaker:t.speaker,testResult:a,messageId:t.id,img:e.msg},o=i.flags.data.defenderMessage?Array.from(i.flags.data.defenderMessage):[];o.push(t.id),game.user.isGM&&await i.update({"flags.data.defenderMessage":o}),await t.update({"flags.data.attackerMessage":i.id}),await this.completeOpposedProcess(r,n,{target:!0,startMessageId:e.flags.oppose.startMessageId,whisper:t.whisper,blind:t.blind}),await j.clearOpposed(e)}static videoOrImgTag(e){return/\.webm$/.test(e)?``:``}static async createOpposedTest(e,t,a,s){let i;t.speaker.token?i=canvas.tokens.get(t.speaker.token).document:i=e.prototypeToken;let r=a.options?.mode=="damage";if(a.successLevel>0||r){let n=t.flags.data.preData.attackOfOpportunity,o=n?"":`
    `,c=[];game.user.targets.forEach(async m=>{if(m.actor){let d=`${j.opposeMessage(i,m,!1)} ${o}`,p=await ChatMessage.create({user:game.user.id,content:d,speaker:t.speaker,["flags.unopposeData"]:{attackMessageId:t.id,targetSpeaker:{scene:m.scene.id,token:m.id,alias:m.document.name}}}),g={speaker:t.speaker,messageId:t.id,startMessageId:p.id};game.user.isGM?await m.actor.update({"flags.oppose":g}):game.socket.emit("system.dsa5",{type:"target",payload:{target:m.id,scene:m.scene?.id||canvas.scene?.id,opposeFlag:g}}),c.push(p.id),n?await j.resolveUndefended(p,game.i18n.localize("OPPOSED.attackOfOpportunity")):r&&await j.resolveUndefended(p),Hooks.call("DSAOpposedRollStart",m)}}),t.flags.data.startMessagesList=c}else game.user.targets.forEach(async n=>{n.actor&&await ChatMessage.create({user:game.user.id,content:j.opposeMessage(i,n,!0),speaker:t.speaker})})}static opposeMessage(e,t,a){return`
    + `;$(this._element).find(".modifiers select").html(o)}else r.length>0&&(r.parent().remove(),this.position.height-=86,this.setPosition(this.position))}}changeSpecAbVariant(e){e.stopPropagation(),e.preventDefault();let t=f.getSpeaker(this.dialogData.speaker);if(t){let s=Number(e.currentTarget.dataset.current)+1;s>=Number(e.currentTarget.dataset.variantcount)&&(s=0),e.currentTarget.dataset.current=s,$(e.currentTarget).text(["A","B","C"][s]);let i=$(e.currentTarget).closest(".specAbs")[0],n=t.items.get(i.dataset.id),r=`effect.value${["","2","3"][s]}`,o=(this.dialogData.mode=="attack"?C.attackSpecAbs([n],t,r):C.defenseSpecAbs([n],t,r))[0];i.dataset.dmmalus=o.dmmalus||0,i.dataset.atbonus=o.atbonus||0,i.dataset.tpbonus=o.tpbonus||0,i.dataset.pabonus=o.pabonus||0,i.dataset.tooltip=o.label,this.calculateModifier()}}async close(e={}){return clearInterval(this.checkTargets),await super.close(e)}_postItem(e){e.stopPropagation();let t=$(e.currentTarget).closest(".specAbs"),a=t.attr("data-actor"),s=t.attr("data-id");return game.actors.get(a).items.get(s).postItem(),!1}recallSettings(e,t,a,s){return super.recallSettings(e,t,a,s),this.prepareWeapon(),this}prepareWeapon(){let e,t=this.dialogData.source;if(["meleeweapon","rangeweapon"].includes(t.type)){let a=f.getSpeaker(this.dialogData.speaker);if(a){let s=t.system.combatskill.value,i=T._calculateCombatSkillValues(a.items.find(n=>n.type=="combatskill"&&n.name==s).toObject(),a.system);switch(t.type){case"meleeweapon":e=T._prepareMeleeWeapon(t,[i],a);break;case"rangeweapon":e=T._prepareRangeWeapon(t,[],[i],a);break}this.dialogData.mode=="attack"||this.dialogData.counterAttack?this.dialogData.rollValue=e.attack:this.dialogData.mode=="parry"&&(this.dialogData.rollValue=e.parry)}else t.type=="dodge"?this.dialogData.rollValue=t.system.value:this.dialogData.mode=="attack"||this.dialogData.counterAttack?this.dialogData.rollValue=Number(t.system.at.value):this.dialogData.mode=="parry"&&(this.dialogData.rollValue=Number(t.system.pa))}}prepareFormRecall(e){super.prepareFormRecall(e);let t=f.getSpeaker(this.dialogData.speaker);J.lightLevel(t,e);let a=H.isRiding(t),s=e.find('[name="advantageousPosition"]')[0];if(this.dialogData.mode=="attack"){let i=Array.from(game.user.targets).some(r=>H.isRiding(r.actor));s&&(i||a)&&(s.checked=a&&!i);let n=e.find('[name="mountedOptions"]')[0];if(a&&n){let r=H.getHorse(t);r&&(n.selectedIndex=H.horseSpeedModifier(r))}}else if(this.dialogData.mode=="parry"&&t.flags.oppose){let i=f.getSpeaker(t.flags.oppose.speaker),n=H.isRiding(i);s&&(n||a)&&(s.checked=a&&!n)}this.calculateModifier()}static assassinationModifiers(e,t){let a=t.assassinate;if(!a||a=="-")return[];e.opposingWeaponSize=0;let s=t.advantageousPosition?2:0,i=b.meleeRangesArray.indexOf(t.weaponsize),n=game.i18n.localize(`DIALOG.${a}`),r=[{name:n,value:10-s-i}];if(a=="assassinate"){let o=b.meleeRangesArray.indexOf(e.source.system.reach.value);!P.isYieldedTwohanded(e.source)&&e.source.system.worn.wrongGrip&&(o=Math.min(o,1));let c=Math.max(1,new Roll(e.source.system.damage.value.replace(/[DWw]/g,"d")).terms.reduce((p,g)=>p+(g.faces?g.number:0),0))-1,m=[2,0,-2,-4][o]-c*2,d=Math.max(1,5-o-c);r.push({name:n+" ("+game.i18n.localize("CHARAbbrev.damage")+")",damageBonus:m,value:0,step:1},{name:n+" (*)",damageBonus:`*${d}`,value:0,step:1})}else e.source.effects||(e.source.effects=[]),e.source.effects.find(o=>o._id==n)||e.source.effects.push({_id:n,changes:[],disabled:!1,duration:{},icon:"icons/svg/aura.svg",name:n,transfer:!0,flags:{dsa5:{description:n,resistRoll:`${game.i18n.localize("LocalizedIDs.selfControl")} -3`,hideOnToken:!1,hidePlayers:!1,customDuration:"",advancedFunction:"1",args0:"unconscious",args1:""}}});return r}async calculateModifier(){if(this.dialogData.mode=="damage")return;let e=this.dialogData.source,t=e.type=="trait"&&getProperty(e,"system.traitType.value")=="meleeAttack"||e.type=="meleeweapon"||e.type=="dodge",a={source:this.dialogData.source,extra:{options:{}}},s=f.getSpeaker(this.dialogData.speaker);t?Tt.resolveMeleeDialog(a,{},this.element,s,{},-3,this.dialogData.mode):Tt.resolveRangeDialog(a,{},this.element,s,{},this.dialogData.mode),this.dialogData.modifier=await _DiceDSA5._situationalModifiers(a),this.updateRollButton(this.readTargets())}static getNarrowSpaceModifier(e,t){return t?P.isShield(e.source)?getProperty(b.narrowSpaceModifiers,`shield${e.source.system.reach.shieldSize}.${t}`)||0:getProperty(b.narrowSpaceModifiers,`weapon${e.source.system.reach.value}.${t}`)||0:0}static resolveMeleeDialog(e,t,a,s,i,n,r){this._resolveDefault(e,t,a,i);let o=new FormDataExtended(a.find("form")[0]).object,c=Tt.targetIsSwarm(e),m=s.isSwarm();e.opposingWeaponSize=m?0:o.weaponsize,e.attackOfOpportunity=this.attackOfOpportunity(e.situationalModifiers,o),e.situationalModifiers.push(C.parseValueType(game.i18n.localize("sight"),o.vision||0),{name:game.i18n.localize("attackFromBehind"),value:Number(o.attackFromBehind)||0},{name:game.i18n.localize("MODS.damage"),damageBonus:o.damageModifier,value:0,step:1},{name:game.i18n.format("defenseCount",{malus:n}),value:(Number(o.defenseCount)||0)*n},{name:game.i18n.localize("wrongHand"),value:Number(o.wrongHand)||0},{name:game.i18n.localize("advantageousPosition"),value:Number(o.advantageousPosition)||0},{name:game.i18n.localize("sizeCategory"),value:c?0:b.meleeSizeModifier[o.size]||0},...C.getSpecAbModifiers(a,r),...this.assassinationModifiers(e,o),{name:game.i18n.localize("narrowSpace"),value:Number(o.narrowSpace)||0},{name:game.i18n.localize("doubleAttack"),value:Number(o.doubleAttack)||0}),e.situationalModifiers.some(d=>d.name==game.i18n.localize("LocalizedIDs.counterAttack"))&&(e.mode="attack",e.extra.counterAttack=!0)}static resolveRangeDialog(e,t,a,s,i){this._resolveDefault(e,t,a,i);let n=new FormDataExtended(a.find("form")[0]).object,r=Number(n.quickChange)||0,o=b.rangeSizeModifier[n.size]||0,c=b.rangeMods[n.distance||"medium"].attack;e.situationalModifiers.push({name:game.i18n.localize("target")+" "+a.find('[name="targetMovement"] option:selected').text(),value:Number(n.targetMovement)||0},{name:game.i18n.localize("shooter")+" "+a.find('[name="shooterMovement"] option:selected').text(),value:Number(n.shooterMovement)||0},{name:game.i18n.localize("mount")+" "+a.find('[name="mountedOptions"] option:selected').text(),value:Number(n.mountedOptions)||0},{name:game.i18n.localize("rangeMovementOptions.QUICKCHANGE"),value:r},{name:game.i18n.localize("MODS.combatTurmoil"),value:Number(n.combatTurmoil)||0},{name:game.i18n.localize("aim"),value:Number(n.aim)||0},{name:game.i18n.localize("MODS.damage"),damageBonus:n.damageModifier,value:0,step:1},{name:game.i18n.localize("sight"),value:Number(n.vision)||0},{name:game.i18n.localize("sizeCategory"),value:o},{name:game.i18n.localize("distance"),value:c,damageBonus:b.rangeMods[n.distance||"medium"].damage},...C.getSpecAbModifiers(a,"attack"));let m=s.items.find(d=>d.type=="specialability"&&d.name==game.i18n.localize("LocalizedIDs.sharpshooter"));if(m){let d=getProperty(e.source,"system.combatskill.value")?.toLowerCase();if(d&&m.system.list.value.split(/;|,/).map(p=>p.trim().toLowerCase()).includes(d)){let p=[n.targetMovement,n.shooterMovement,n.mountedOptions,r,o,c],g=Math.abs(p.reduce((h,w)=>(Number(w)<0&&(h+=Number(w)),h),0)),y=Math.min(Number(m.system.step.value)*2,g);y&&e.situationalModifiers.push({name:game.i18n.localize("LocalizedIDs.sharpshooter"),value:y})}}}static _resolveDefault(e,t,a,s){t.rollMode=a.find('[name="rollMode"]').val(),e.situationalModifiers=T._parseModifiers(a),mergeObject(e.extra.options,s)}static targetIsSwarm(){let e=!1;return game.user.targets.forEach(t=>{if(t.actor?.isSwarm()){e=!0;return}}),e}static attackOfOpportunity(e,t){let a=Number(t.opportunityAttack)||0;if(a){e.push({name:game.i18n.localize("opportunityAttack"),value:a});let s=game.i18n.localize("LocalizedIDs.enemySense"),i=game.i18n.localize("LocalizedIDs.winhallStyle");game.user.targets.forEach(n=>{for(let r of n.actor?.items||[])r.type=="specialability"&&(r.name==s?e.push({name:s,value:-4}):r.name==i&&e.push({name:i,value:-2}))})}return a!=0}static getRollButtons(e,t,a,s){let i=ee.getRollButtons(e,t,a,s);if(e.source.type=="rangeweapon"||e.source.type=="trait"&&e.source.system.traitType.value=="rangeAttack"){let n=e.source.type=="trait"?Number(e.source.system.reloadTime.value):T.calcLZ(e.source,e.extra.actor),r=e.source.system.reloadTime.progress;r{let o=await f.getSpeaker(e.extra.speaker);await o.updateEmbeddedDocuments("Item",[{_id:e.source._id,"system.reloadTime.progress":r+1}]);let c=game.i18n.format("WEAPON.isReloading",{actor:o.token?.name||o.prototypeToken.name,item:e.source.name,status:`${r+1}/${n}`});await ChatMessage.create(f.chatDataSetup(c))}}})}return i}},ge=Tt;u(ge,"DSA5CombatDialog"),L(ge,"rollModifiers",{wrongHand:{mod:-4},advantageousPosition:{mod:2},attackFromBehindLabel:{mod:-4},opportunityAttack:{mod:-4},doubleAttack:{mod:-2},narrowSpace:{mod:0},combatTurmoil:{mod:-2},quickChange:{mod:-4},targetMovement:{mod:0}});var St=class extends ie{static getRollButtons(e,t,a,s){let i=ee.getRollButtons(e,t,a,s);i.rollButton.label=game.i18n.localize("Opposed");let n={nonOpposedButton:{label:game.i18n.localize("Roll"),callback:r=>{game.dsa5.memory.remember(e.extra.speaker,e.source,e.mode,r),e.opposable=!1,a(t.callback(r))}},routineRoll:{label:game.i18n.localize("ROLL.routine"),callback:r=>{game.dsa5.memory.remember(e.extra.speaker,e.source,e.mode,r),e.routine=!0,mergeObject(e.extra.options,{cheat:!0,predefinedResult:[{val:2,index:0},{val:2,index:1},{val:2,index:2}]}),a(t.callback(r))}}};return mergeObject(n,i),n}activateListeners(e){super.activateListeners(e),e.on("change","input,select",s=>this.rememberFormData(s));let t=this.readTargets(),a=this;this.checkTargets=setInterval(function(){t=a.compareTargets(e,t)},500),this.rememberFormData(),e.on("mousedown",".quantity-click",s=>this.rememberFormData(s)),e.find(".modifiers option").mousedown(s=>{this.rememberFormData(s)})}rememberFormData(e){let t=new FormDataExtended(this.element.find("form")[0]).object;t.situationalModifiers=T._parseModifiers(this._element),this.calculateRoutine(t)}async calculateRoutine(e){let t=f.getSpeaker(this.dialogData.speaker),a=this.element.find(".routineRoll");if(!t)return a.prop("disabled",!0);let s=!0;for(let d=0;d<3;d++)if(t.system.characteristics[e[`characteristics${d}`]].max*e[`ch${d}`].max<13){s=!1;break}let i=this.dialogData.source.system.talentValue.value+e.fw+await _DiceDSA5._situationalModifiers(e,"FW"),n=b.skillDifficultyModifiers[e.testDifficulty]+await _DiceDSA5._situationalModifiers(e),r=Math.clamped(10-n*3,1,19),o=i>=r,c=s&&o,m=game.i18n.localize("ROLL.routine");a.prop("disabled",!c),a.html(c?`${m} (${game.i18n.localize("CHARAbbrev.FW")} ${Math.round(i/2)})`:m)}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,resizable:!0}),e}};u(St,"DSA5SkillDialog");var ee=class extends ie{static getDialogForItem(e,t){let a=e.extra.actor,s=e.source.type;switch(s){case"rangeweapon":case"meleeweapon":case"dodge":case"trait":return t.rollModifiers=ge.setData(a,s,e),ge;case"spell":case"ritual":case"liturgy":case"ceremony":return t.rollModifiers=le.setData(a,s),le;case"skill":return St}return ee}static getRollButtons(e,t,a,s){let i={rollButton:{label:game.i18n.localize("Roll"),callback:n=>{game.dsa5.memory.remember(e.extra.speaker,e.source,e.mode,n),a(t.callback(n))}}};return game.user.isGM&&mergeObject(i,{cheat:{label:game.i18n.localize("DIALOG.cheat"),callback:n=>{game.dsa5.memory.remember(e.extra.speaker,e.source,e.mode,n),a(t.callback(n,{cheat:!0}))}}}),i}activateListeners(e){super.activateListeners(e),e.find(".dieButton").click(t=>{let a=$(t.currentTarget);a.attr("data-single")=="true"&&a.closest(".dialog-content").find(".dieButton").removeClass("dieSelected"),a.toggleClass("dieSelected")})}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{resizable:!0}),e}};u(ee,"DSA5Dialog");var ue=class extends te{static async traitAdded(e,t){b.addTraitRules[t.name]&&await b.addTraitRules[t.name](e,t)}static hasTrait(e,t){return super.hasItem(e,t,["trait"])}};u(ue,"TraitRulesDSA5");Hooks.on("setup",()=>{let l=game.i18n.localize("LocalizedIDs.familiar");b.addTraitRules[l]=async(e,t)=>{t.effects.length==0&&(t.effects=[{changes:[{key:"system.status.wounds.gearmodifier",mode:2,value:10},{key:"system.status.soulpower.gearmodifier",mode:2,value:1},{key:"system.status.toughness.gearmodifier",mode:2,value:1},{key:"system.status.astralenergy.gearmodifier",mode:2,value:15},{key:"system.characteristics.mu.gearmodifier",mode:2,value:1},{key:"system.characteristics.kl.gearmodifier",mode:2,value:1},{key:"system.characteristics.in.gearmodifier",mode:2,value:1},{key:"system.characteristics.ch.gearmodifier",mode:2,value:1},{key:"system.characteristics.ff.gearmodifier",mode:2,value:1},{key:"system.characteristics.ge.gearmodifier",mode:2,value:1},{key:"system.characteristics.ko.gearmodifier",mode:2,value:1},{key:"system.characteristics.kk.gearmodifier",mode:2,value:1},{key:"system.totalArmor",mode:2,value:1}],duration:{},icon:"icons/svg/aura.svg",name:l,transfer:!0,flags:{dsa5:{description:l,hideOnToken:!0,hidePlayers:!1}}}]);let a=game.i18n.localize("LocalizedIDs.witchSense");if(!te.hasItem(e,a,["trait"])){let s=await f.findAnyItem([{name:a,type:"trait"}]);await e.createEmbeddedDocuments("Item",s)}}});var ce=class extends Dialog{static async showDialog(e){let t=this.callbackResult;new ce({title:game.i18n.localize("Unopposed"),content:await this.getTemplate(e),default:"ok",buttons:{ok:{icon:'',label:game.i18n.localize("ok"),callback:a=>{t(a.find('[name="entryselection"]').val(),e)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}activateListeners(e){super.activateListeners(e),e.find(".select2").select2()}static getTargetActor(e){if(!canvas.tokens)return{};let t=e.flags.unopposeData.targetSpeaker,a=f.getSpeaker(t);return a?{actor:a,tokenId:t.token}:(ui.notifications.error(game.i18n.localize("DSAError.noProperActor")),{})}static async getTemplate(e){return""}static callbackResult(e,t,a){}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{resizable:!0}),e}};u(ce,"DialogReactDSA5");var ct=class extends ce{static async getTemplate(e){let s=game.messages.get(e.flags.unopposeData.attackMessageId).flags.data.preData.source.name,i=(await f.allSkillsList()).map(n=>({name:n,id:n}));return i.unshift({name:game.i18n.localize("doNothing"),id:"doNothing"}),renderTemplate("systems/dsa5/templates/dialog/dialog-act.html",{items:i,original:s,title:"DIALOG.selectReaction"})}static callbackResult(e,t){let{actor:a,tokenId:s}=ce.getTargetActor(t);if(e=="doNothing")j.resolveUndefended(t);else{let i=a.items.find(n=>n.name==e&&n.type=="skill");i&&a.setupSkill(i,{},s).then(n=>{a.basicTest(n)})}}};u(ct,"ReactToSkillDialog");var Re=class extends Dialog{static async showDialog(e,t){let a=new Re({title:game.i18n.localize("attacktest"),content:await this.getTemplate(e),buttons:{}});a.actor=e,a.tokenId=t,a.render(!0)}activateListeners(e){super.activateListeners(e),e.find(".reactClick").click(t=>{this.callbackResult(t.currentTarget.dataset.value,this.actor,this.tokenId),this.close()})}static async getTemplate(e){let t=e.items.filter(r=>r.type=="combatskill").map(r=>T._calculateCombatSkillValues(r.toObject(),e.system)),a=t.find(r=>r.name==game.i18n.localize("LocalizedIDs.wrestle")),s=[{name:game.i18n.localize("attackWeaponless"),id:"attackWeaponless",img:"systems/dsa5/icons/categories/attack_weaponless.webp",value:a.system.attack.value}],i=["meleeweapon","rangeweapon"],n=["meleeAttack","rangeAttack"];for(let r of e.items)if(i.includes(r.type)&&r.system.worn.value==!0){let o=r.type=="meleeweapon"?T._prepareMeleeWeapon(r.toObject(),t,e):T._prepareRangeWeapon(r.toObject(),[],t,e);s.push({name:r.name,id:r.name,img:r.img,value:o.attack,item:o})}else r.type=="trait"&&n.includes(r.system.traitType.value)&&s.push({name:r.name,id:r.name,img:r.img,value:r.system.at.value});return await renderTemplate("systems/dsa5/templates/dialog/dialog-reaction-attack.html",{dieClass:"die-mu",items:s,title:"DIALOG.selectAction"})}callbackResult(e,t,a){if(e=="attackWeaponless")t.setupWeaponless("attack",{},a).then(s=>{t.basicTest(s)});else{let s=["meleeweapon","trait","rangeweapon"],i=t.items.find(n=>s.includes(n.type)&&n.name==e);i&&t.setupWeapon(i,"attack",{},a).then(n=>{t.basicTest(n)})}}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:550}),e}};u(Re,"ActAttackDialog");var Me=class extends ce{static async showDialog(e){let t=new Me({title:game.i18n.localize("Unopposed"),content:await this.getTemplate(e),buttons:{}});t.startMessage=e,t.render(!0)}static getAttackActor(e){if(!canvas.tokens)return{};let t=e.flags.unopposeData.attackMessageId,s=game.messages.get(t).flags.data.preData.extra.speaker,i=f.getSpeaker(s);return i?{actor:i,tokenId:s.token}:(ui.notifications.error(game.i18n.localize("DSAError.noProperActor")),{})}activateListeners(e){super.activateListeners(e),e.find(".reactClick").click(t=>{this.callbackResult(t.currentTarget.dataset.value,this.startMessage),this.close()})}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:550}),e}static async getTemplate(e){let{actor:t,tokenId:a}=ce.getTargetActor(e),s=Me.getAttackActor(e),i=t.items.filter(m=>m.type=="combatskill").map(m=>T._calculateCombatSkillValues(m.toObject(),t.system)),n=i.find(m=>m.name==game.i18n.localize("LocalizedIDs.wrestle")),r=[{name:game.i18n.localize("doNothing"),id:"doNothing",img:"systems/dsa5/icons/categories/disease.webp"},{name:game.i18n.localize("dodge"),id:"dodge",img:"systems/dsa5/icons/categories/Dodge.webp",value:t.system.status.dodge.max},{name:game.i18n.localize("parryWeaponless"),id:"parryWeaponless",img:"systems/dsa5/icons/categories/attack_weaponless.webp",value:n.system.parry.value}],o=0,c="";if(t){let m=["meleeweapon"];for(let d of t.items)if(m.includes(d.type)&&d.system.worn.value==!0){let p=T._prepareMeleeWeapon(d.toObject(),i,t);r.push({name:d.name,id:d.name,img:d.img,value:p.parry})}else d.type=="trait"&&Number(d.system.pa)>0&&r.push({name:d.name,id:d.name,img:d.img,value:d.system.pa});if(s){let d=getProperty(s.actor.system,"status.size.value");d=="big"?c="DIALOGDESCRIPTION.bigEnemy":d=="giant"&&(c="DIALOGDESCRIPTION.giantEnemy")}game.combat&&(o=await game.combat.getDefenseCount({actor:t.id,token:a,scene:canvas.scene?canvas.scene.id:null}))}return await renderTemplate("systems/dsa5/templates/dialog/dialog-reaction-attack.html",{dieClass:"die-in",items:r,defenses:o,title:"DIALOG.selectReaction",sizeNotification:c})}callbackResult(e,t){let{actor:a,tokenId:s}=ce.getTargetActor(t);if(e=="doNothing")j.resolveUndefended(t);else if(e=="dodge")a.setupDodge({},s).then(i=>{a.basicTest(i)});else if(e=="parryWeaponless")a.setupWeaponless("parry",{},s).then(i=>{a.basicTest(i)});else{let i=["meleeweapon","trait"],n=a.items.find(r=>i.includes(r.type)&&r.name==e);n&&a.setupWeapon(n,"parry",{},s).then(r=>{a.basicTest(r)})}}};u(Me,"ReactToAttackDialog");var W=class{static armorWearModifier(e,t){if(game.settings.get("dsa5","armorAndWeaponDamage"))switch(W.calculateWear(e)){case 1:case 2:t-=1;break;case 3:case 4:t=0}return Math.max(0,Number(t))}static armorGetsDamage(e,t){return(e>14||t.successLevel>2)&&game.settings.get("dsa5","armorAndWeaponDamage")}static armorEncumbranceModifier(e){return game.settings.get("dsa5","armorAndWeaponDamage")&&W.calculateWear(e)>1?1:0}static async showDamageToGear(e,t){if(game.settings.get("dsa5","armorAndWeaponDamage")){let a=f.getSpeaker(e.extra.speaker),s=0,i=getProperty(a,"flags.oppose.messageId");if(i){let r=game.messages.get(i);r&&(s=getProperty(r,"flags.data.postData.successLevel")||0)}let n=e.source;if(n._id&&n.system.structure&&(t.successLevel<-2||s>2)&&["meleeweapon","rangeweapon","armor"].includes(n.type))return a=await f.getSpeaker(t.speaker),a.items.get(n._id).uuid}}static breakingTest(e){if(!e)return ui.notifications.warn(game.i18n.format("DSAError.notfound",{category:"",name:game.i18n.localize("equipment")}));if(e.system.structure.max<=0)return ui.notifications.warn(game.i18n.format("DSAError.noBreakingStructure",{name:e.name}));let t=0,a;if(e.type=="armor"?(a=game.i18n.localize(`ARMORSUBCATEGORIES.${e.system.subcategory}`),t=getProperty(e,"system.structure.breakPointRating")||b.armorSubcategories[e.system.subcategory]):(a=e.system.combatskill.value,t=getProperty(e,"system.structure.breakPointRating")||b.weaponStabilities[game.i18n.localize(`LocalizedCTs.${a}`)]),!t){ui.notifications.error(game.i18n.format("DSAError.noBreakingResistance",{item:e.name}));return}let s="",i=getProperty(e,"effect.attributes")||"";new RegExp(`${I.magical}`,"i").test(i)?s=`${game.i18n.format("WEAPON.attributeWarning",{domain:I.clerical})}
    `:new RegExp(`${I.clerical}`,"i").test(i)&&(s=`${game.i18n.format("WEAPON.attributeWarning",{domain:I.magical})}
    `),new ie({title:game.i18n.localize("DSASETTINGS.armorAndWeaponDamage"),content:`${s}: `,buttons:{Yes:{icon:'',label:game.i18n.localize("Roll"),callback:n=>{W.resolveBreakingTest(e,Number(n.find('[name="threshold"]').val()),a)}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}static async applyDamageLevelToItem(e,t){let a=Math.ceil(e.system.structure.max*.25)*t;await e.update({"system.structure.value":Math.max(0,e.system.structure.value-a)})}static async absoluteDamageLevelToItem(e,t){let a=Math.ceil(e.system.structure.max*.25)*t;await e.update({"system.structure.value":Math.min(e.system.structure.value,Math.max(0,e.system.structure.max-a))})}static async resolveBreakingTest(e,t,a){let s=await _DiceDSA5.manualRolls(await new Roll("1d20").evaluate({async:!0}),game.i18n.format("WEAR.check",{category:a}));await _DiceDSA5.showDiceSoNice(s,await game.settings.get("core","rollMode"));let i=s.total>t?1:0;await this.applyDamageLevelToItem(e,i);let n=W.calculateWear(e.data),r=await renderTemplate("systems/dsa5/templates/system/breakingtest.html",{wear:n,item:e,threshold:t,category:a,roll:s,result:game.i18n.localize(`WEAR.${e.type}.${n}`)});ChatMessage.create(f.chatDataSetup(r))}static damageTooltip(e){if(game.settings.get("dsa5","armorAndWeaponDamage")){let t=this.calculateWear(e);return{msg:game.i18n.localize(`WEAR.${e.type}.${t}`),css:`gearD damaged${t}`}}return{msg:"",css:""}}static weaponWearModifier(e){if(game.settings.get("dsa5","armorAndWeaponDamage"))switch(W.calculateWear(e)){case 1:e.attack-=1,e.parry&&(e.parry-=1);break;case 2:e.attack-=2,e.parry&&(e.parry-=2);break;case 3:case 4:e.attack=0,e.parry&&(e.parry=0)}}static calculateWear(e){return!e.system.structure||Number(e.system.structure.max<=0)?0:Math.floor((1-e.system.structure.value/e.system.structure.max)*4)}};u(W,"EquipmentDamage");var fe=class{static prepareSoundEffects(){fe.soundPaths={money:[],armor:[],meleeweapon:[],rangeweapon:[],default:[]},game.modules.get("gAudioBundle-3")&&(fe.soundPaths.money.push("modules/gAudioBundle-3/src/Mint Coins And Money/Coin_Slide_Carpet.ogg","modules/gAudioBundle-3/src/Mint Coins And Money/Coins_Drop_Carpet_06.ogg","modules/gAudioBundle-3/src/Mint Coins And Money/Coins_Bottlecaps_Drop.ogg","modules/gAudioBundle-3/src/Mint Coins And Money/Coins_In_Sack_Held_By_Drawstring_06.ogg","modules/gAudioBundle-3/src/Money/Money_Coins_Handle.ogg"),fe.soundPaths.meleeweapon.push("modules/gAudioBundle-3/src/Medieval Armor And Impacts/Weapon_Impact_Parry_01.ogg")),game.modules.get("gAudioBundle-2")&&(fe.soundPaths.meleeweapon.push("modules/gAudioBundle-2/src/Gore/Melee_Sword_Attack_04.ogg"),fe.soundPaths.armor.push("modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Foley_Soldier_Gear_Equipment_Metal_Cloth_Heavy_Movement_Light_08.ogg"),fe.soundPaths.default.push("modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Foley_Sports_Bag_Grab_Pickup_Catch_04.ogg","modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Footstep_Ice_Crunchy_Run_01.ogg","modules/gAudioBundle-2/src/Footsteps/Footstep And Foley Sounds/Footstep_Ice_Crunchy_Run_02.ogg")),game.modules.get("gAudioBundle-4")&&fe.soundPaths.rangeweapon.push("modules/gAudioBundle-4/src/Super Heroes Sound Design/Hawk's_Arrow_Flies_Bow_And_Arrow_Shoot_2.ogg"),Hooks.call("setDefaultDSASounds",fe.soundPaths)}static async playEffect(e,t,a,s=void 0,i=!1){let n=await this.getSound(e,t,a);if(n)try{s?(game.socket.emit("system.dsa5",{type:"playWhisperSound",payload:{whisper:s,soundPath:n}}),i||AudioHelper.play({src:n,volume:.8,loop:!1},!1)):AudioHelper.play({src:n,volume:.8,loop:!1},!0)}catch{console.warn(`Could not play item sound effect ${n}`)}}static async loadSoundConfig(){let e=await game.settings.get("dsa5","soundConfig");if(e)try{let a=await(await fetch(e)).json();this.sounds=a,console.log("DSA5 | Sound Config Loaded")}catch(t){console.warn(t)}}static successLevelToString(e){switch(e){case-1:return["fail"];case-2:return["botch","fail"];case 1:return["success"];case 2:return["crit","success"];default:return[]}}static async getSound(e,t,a){if(!this.sounds&&!this.triedInit&&(await this.loadSoundConfig(),this.triedInit=!0),!this.sounds)return;let s=this.successLevelToString(a),i=[],n;switch(t.type){case"meleeweapon":case"rangeweapon":i=[...s.map(r=>`${t.type}.manual.${t.name}.${e}_${r}`),`${t.type}.manual.${t.name}.${e}`,`${t.type}.manual.${t.name}.default.${e}`,`${t.type}.manual.${t.name}.default`,...s.map(r=>`${t.type}.${t.system.combatskill.value}.${e}_${r}`),`${t.type}.${t.system.combatskill.value}.${e}`,...s.map(r=>`${t.type}.${t.system.combatskill.value}.default_${r}`),`${t.type}.${t.system.combatskill.value}.default`];break;case"skill":i=[...s.map(r=>`${t.type}.${t.name}.${e}_${r}`),`${t.type}.${t.name}.${e}`,...s.map(r=>`${t.type}.${t.name}.default_${r}`),`${t.type}.${t.name}.default`];break;case"liturgy":case"spell":case"ceremony":case"ritual":i=[...s.map(r=>`${t.type}.${t.name}.${e}_${r}`),`${t.type}.${t.name}.${e}`,...s.map(r=>`${t.type}.${t.name}.default_${r}`),`${t.type}.${t.name}.default`];break}i.push(...s.map(r=>`${t.type}.default_${r}`),`${t.type}.default`);for(let r of i)if(!!hasProperty(this.sounds,r)&&(n=getProperty(this.sounds,r),n&&(typeof n=="string"||n instanceof String)))break;return n}static async playMoneySound(e=!1){let t=fe.soundPaths.money,a=t[Math.floor(Math.random()*t.length)];await this.playSoundPath(a,e)}static async playEquipmentWearStatusChange(e,t=!1){let a=fe.soundPaths[e.type]||fe.soundPaths.default;if(a.length>0){let s=a[Math.floor(Math.random()*a.length)];await this.playSoundPath(s,t,.5)}}static async playSoundPath(e,t=!1,a=.8){if(!!game.settings.get("dsa5","inventorySound"))try{AudioHelper.play({src:e,volume:a,loop:!1},t)}catch{console.warn(`Could not play item sound effect ${e}`)}}},K=fe;u(K,"DSA5SoundEffect"),L(K,"sounds"),L(K,"triedInit",!1);var X=class{constructor(e){this.item=e}async callMacro(e,t,a={}){let i=await game.packs.get(e)?.getDocuments({name:t});if(!i||!i.length){for(let r of game.packs.filter(o=>o.documentName=="Macro"&&/\(internal\)/.test(o.metadata.label)))if(i=await r.getDocuments({name:t}),i.length)break}let n={};if(i.length)try{a.result=n;let r=Object.getPrototypeOf(async function(){}).constructor,o=new r("args","actor","item",i[0].command);n.ret=await o.call(this,a,this.item.actor,this.item)}catch{try{let o=new AsyncFunction("args","actor","item",` + const that = this; + ${i[0].command.replace(/( |\(|{)this\./g," that.")} + `);n.ret=await o.call(this,a,this.item.actor)}catch(o){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(o),n.error=!0}}else ui.notifications.error(game.i18n.format("DSAError.macroNotFound",{name:t}));return n}async executeOnUseEffect(){if(!this.item.actor)return;if(!game.user.can("MACRO_SCRIPT"))return ui.notifications.warn("You are not allowed to use JavaScript macros.");let e=X.getOnUseEffect(this.item);try{let t=Object.getPrototypeOf(async function(){}).constructor;await new t("item","actor",e).call(this,this.item,this.item.actor)}catch(t){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(t),console.warn(t.stack)}}static getOnUseEffect(e){return e.getFlag("dsa5","onUseEffect")}async automatedAnimation(e,t={}){f.moduleEnabled("autoanimations")&&console.warn("Animations for on use effects not enabled yet")}effectDummy(e,t,a){return{name:e,icon:"icons/svg/aura.svg",changes:t,duration:a,flags:{dsa5:{value:null,editable:!0,description:e,custom:!0}}}}async socketedConditionAddActor(e,t){if(game.user.isGM){let a=typeof t=="string";a&&(t=duplicate(CONFIG.statusEffects.find(i=>i.id==t)),t.name=game.i18n.localize(t.name));let s=[];for(let i of e)a?await i.addCondition(t,1,!1,!1):await i.addCondition(t),s.push(i.name);await this.createInfoMessage(t,s)}else{let a={id:this.item.uuid,data:t,actors:e.map(s=>s.id)};game.socket.emit("system.dsa5",{type:"socketedConditionAddActor",payload:a})}}async createInfoMessage(e,t,a=!0){if(t.length){let s=a?"ActiveEffects.appliedEffect":"ActiveEffects.removedEffect",i=game.i18n.format(s,{source:e.name,target:t.join(", ")});await ChatMessage.create(f.chatDataSetup(i))}}async socketedRemoveCondition(e,t,a=1){if(game.user.isGM){let s=[];for(let n of e){let r=canvas.tokens.get(n);r.actor&&(await r.actor.removeCondition(t,a,!1),s.push(r.name))}let i=CONFIG.statusEffects.find(n=>n.id==t);i.name=game.i18n.localize(i.name),await this.createInfoMessage(i,s,!1)}else{let s={id:this.item.uuid,coreId:t,targets:e};game.socket.emit("system.dsa5",{type:"socketedRemoveCondition",payload:s})}}async socketedActorTransformation(e,t){if(game.user.isGM)for(let a of e){let s=canvas.tokens.get(a);s.actor&&await s.actor.update(t)}else{let a={id:this.item.uuid,targets:e,update:t};game.socket.emit("system.dsa5",{type:"socketedActorTransformation",payload:a})}}async socketedConditionAdd(e,t){if(game.user.isGM){let a=typeof t=="string";a&&(t=duplicate(CONFIG.statusEffects.find(i=>i.id==t)),t.name=game.i18n.localize(t.name));let s=[];for(let i of e){let n=canvas.tokens.get(i);n.actor&&(a?await n.actor.addCondition(t,1,!1,!1):await n.actor.addCondition(t),s.push(n.name))}await this.createInfoMessage(t,s)}else{let a={id:this.item.uuid,data:t,targets:e};game.socket.emit("system.dsa5",{type:"socketedConditionAdd",payload:a})}}};u(X,"OnUseEffect");var Ue=class{static async postOpposed(e){let t=f.getSpeaker(e.attacker.speaker);!t||await this.runMacro(t,e.attacker.testResult,7,e)}static async postRoll(e){let t=f.getSpeaker(e.testData.speaker);!t||await this.runMacro(t,e.testData,6,e)}static async callMacro(e,t,a,s={}){return await new X(e).callMacro(t,a,s)}static async runMacro(e,t,a,s){if(!game.user.can("MACRO_SCRIPT"))ui.notifications.warn("You are not allowed to use JavaScript macros.");else for(let[i,n]of Object.entries(e.dsatriggers[a])){let r=e.items.get(i),o=r.effects.get(n),c=o.getFlag("dsa5","args3");try{let m=Object.getPrototypeOf(async function(){}).constructor;return await new m("actor","testData","type","data","source","ef",c).call(this,e,t,a,s,r,o)}catch(m){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(m)}}}};u(Ue,"DSATriggers");var j=class{static async handleOpposedTarget(e){if(!e)return;let t=f.getSpeaker(e.speaker);if(!t)return;let a=e.flags.data.postData,s=e.flags.data.preData;t.flags.oppose?j.answerOpposedTest(t,e,a,s):game.user.targets.size&&e.flags.data.isOpposedTest&&!e.flags.data.defenderMessage&&!e.flags.data.attackerMessage?j.createOpposedTest(t,e,a,s):e.flags.data.defenderMessage||e.flags.data.attackerMessage?j.resolveFinalMessage(e):e.flags.data.unopposedStartMessage?j.redoUndefended(e):e.flags.data.startMessagesList?j.changeStartMessage(e):(await this.showDamage(e),await this.showSpellWithoutTarget(e))}static async redoUndefended(e){let t=game.messages.get(e.flags.data.unopposedStartMessage);startmessage.flags.unopposeData.attackMessageId=e.id,this.resolveUndefended(t)}static async answerOpposedTest(e,t,a,s){let i=game.messages.get(e.flags.oppose.messageId);if(!i)return ui.notifications.error(game.i18n.localize("DSAError.staleData")),await j.clearOpposed(e),j.createOpposedTest(e,t,a,s);let n={speaker:e.flags.oppose.speaker,testResult:i.flags.data.postData,messageId:i.id,img:f.getSpeaker(e.flags.oppose.speaker)?.img};n.testResult.source=i.flags.data.preData.source,n.testResult.ammo&&n.testResult.source.effects.push(...n.testResult.ammo.effects);let r={speaker:t.speaker,testResult:a,messageId:t.id,img:e.msg},o=i.flags.data.defenderMessage?Array.from(i.flags.data.defenderMessage):[];o.push(t.id),game.user.isGM&&await i.update({"flags.data.defenderMessage":o}),await t.update({"flags.data.attackerMessage":i.id}),await this.completeOpposedProcess(n,r,{target:!0,startMessageId:e.flags.oppose.startMessageId,whisper:t.whisper,blind:t.blind}),await j.clearOpposed(e)}static videoOrImgTag(e){return/\.webm$/.test(e)?``:``}static async createOpposedTest(e,t,a,s){let i;t.speaker.token?i=canvas.tokens.get(t.speaker.token).document:i=e.prototypeToken;let n=a.options?.mode=="damage";if(a.successLevel>0||n){let r=t.flags.data.preData.attackOfOpportunity,o=r?"":`
    `,c=[];game.user.targets.forEach(async m=>{if(m.actor){let d=`${j.opposeMessage(i,m,!1)} ${o}`,p=await ChatMessage.create({user:game.user.id,content:d,speaker:t.speaker,["flags.unopposeData"]:{attackMessageId:t.id,targetSpeaker:{scene:m.scene.id,token:m.id,alias:m.document.name}}}),g={speaker:t.speaker,messageId:t.id,startMessageId:p.id};game.user.isGM?await m.actor.update({"flags.oppose":g}):game.socket.emit("system.dsa5",{type:"target",payload:{target:m.id,scene:m.scene?.id||canvas.scene?.id,opposeFlag:g}}),c.push(p.id),r?await j.resolveUndefended(p,game.i18n.localize("OPPOSED.attackOfOpportunity")):n&&await j.resolveUndefended(p),Hooks.call("DSAOpposedRollStart",m)}}),t.flags.data.startMessagesList=c}else game.user.targets.forEach(async r=>{r.actor&&await ChatMessage.create({user:game.user.id,content:j.opposeMessage(i,r,!0),speaker:t.speaker})})}static opposeMessage(e,t,a){return`
    ${e.name} ${game.i18n.localize("ROLL.Targeting")} ${t.document.name} ${a?game.i18n.localize("ROLL.failed"):""}
    ${j.videoOrImgTag(e.texture.src)}
    ${j.videoOrImgTag(t.document.texture.src)}
    - `}static async changeStartMessage(e){for(let t of e.flags.data.startMessagesList){let a=game.messages.get(t),s=a.flags.unopposeData;game.socket.emit("system.dsa5",{type:"target",payload:{target:s.targetSpeaker.token,scene:canvas.scene.id,opposeFlag:{speaker:e.speaker,messageId:e.id,startMessageId:a.id}}}),await a.update({"flags.unopposeData.attackMessageId":e.id})}}static resolveFinalMessage(e){let t,a;if(e.flags.data.defenderMessage)for(let s of e.flags.data.defenderMessage){t=j.getMessageDude(e);let i=game.messages.get(s);a=j.getMessageDude(i),this.completeOpposedProcess(t,a,{blind:e.blind,whisper:e.whisper})}else{a=j.getMessageDude(e);let s=game.messages.get(e.flags.data.attackerMessage);t=j.getMessageDude(s),this.completeOpposedProcess(t,a,{blind:e.blind,whisper:e.whisper})}}static getMessageDude(e){let t={speaker:e.speaker,testResult:mergeObject(e.flags.data.postData,{source:e.flags.data.preData.source}),img:f.getSpeaker(e.speaker).img,messageId:e.id};return t.testResult.ammo&&t.testResult.source.effects.push(...t.testResult.ammo.effects),t}static async showDamage(e,t=!1){game.user.isGM?(!t||!e.flags.data.hideDamage)&&e.flags.data.postData.damageRoll&&(await e.update({content:e.content.replace(`data-hide-damage="${!t}"`,`data-hide-damage="${t}"`),"flags.data.hideDamage":t}),t||_DiceDSA5._addRollDiceSoNice(e.flags.data.preData,Roll.fromData(e.flags.data.postData.damageRoll),game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration("damage"))):game.socket.emit("system.dsa5",{type:"showDamage",payload:{id:e.id,hide:t}})}static async playAutomatedJBA2(e,t,a){if(f.moduleEnabled("autoanimations")){let s=f.getSpeaker(e.speaker).getActiveTokens()[0],i=f.getSpeaker(t.speaker).getActiveTokens()[0];if(!s||!s.actor||!i||!i.actor)return;let r=s.actor.items.get(e.testResult.source._id);if(r||(r=new A(e.testResult.source,{temporary:!0})),!r)return;r=r.toObject();let n=[i],o=a.winner=="attacker",c=o?n:[],m=e.testResult.successLevel>1&&o,d=e.testResult.successLevel<1&&!o,p=t.testResult.successLevel>1&&!o,g=t.testResult.successLevel<1&&o,y=[],h=[];m?h.push(game.i18n.localize("CriticalSuccess")):d?h.push(game.i18n.localize("CriticalFailure")):p?h.push(`${game.i18n.localize("CHAR.PARRY")} ${game.i18n.localize("CriticalSuccess")}`):g&&h.push(`${game.i18n.localize("CHAR.PARRY")} ${game.i18n.localize("CriticalFailure")}`),o||h.push(game.i18n.localize("CHAR.PARRY"));for(let w of h)y.push({name:`${r.name} (${w})`},{name:w});y.push(r);for(let w of y)if(await AutomatedAnimations.playAnimation(s,w,{targets:n,hitTargets:c,playOnMiss:!0}))break}}static async showSpellWithoutTarget(e){if(f.moduleEnabled("autoanimations")){let t=getProperty(e,"flags.data");if(!t||t.isOpposedTest)return;if((getProperty(t,"postData.result")||-1)>0){let s=f.getSpeaker(t.postData.speaker).getActiveTokens()[0];if(!s||!s.actor)return;let i=Array.from(game.user.targets),r=s.actor.items.get(t.preData.source._id);i.length||(i=[s]),AutomatedAnimations.playAnimation(s,r,{targets:i})}}}static async clearOpposed(e){game.user.isGM?await e.update({["flags.-=oppose"]:null}):game.socket.emit("system.dsa5",{type:"clearOpposed",payload:{actorId:e.id}})}static async _handleReaction(e){let t=$(e.currentTarget).parents(".message").attr("data-message-id"),a=game.messages.get(t);switch(game.messages.get(a.flags.unopposeData.attackMessageId).flags.data.preData.source.type){case"skill":ct.showDialog(a);break;default:Me.showDialog(a)}}static async chatListeners(e){e.on("click",".unopposed-button",t=>{t.preventDefault(),this._handleReaction(t)})}static async hideReactionButton(e){if(e)if(game.user.isGM){let t=game.messages.get(e),a=$(t.content);a.find("button.unopposed-button").remove(),a=$("
    ").append(a),await t.update({content:a.html()})}else game.socket.emit("system.dsa5",{type:"hideQueryButton",payload:{id:e}})}static async completeOpposedProcess(e,t,a){await Ue.postOpposed({attacker:e,defender:t,options:a});let s=await this.evaluateOpposedTest(e.testResult,t.testResult,a);return this.formatOpposedResult(s,e.speaker,t.speaker),this.rerenderMessagesWithModifiers(s,e,t),Hooks.call("finishOpposedTest",e,t,s,a),await this.finishOpposedTestHookAsync(e,t,s,a),this.playAutomatedJBA2(e,t,s),await this.renderOpposedResult(s,a),await this.hideReactionButton(a.startMessageId),s}static async finishOpposedTestHookAsync(e,t,a,s){}static async evaluateOpposedTest(e,t,a={}){let s={};if(s.other=[],a.additionalInfo&&s.other.push(a.additionalInfo),s.winner="attacker",["weapon","spell","liturgy","ceremony","ritual","combatskill"].includes(e.rollType)&&t.successLevel==null&&(t.successLevel=-5),e.rollType=="damage"&&(t.successLevel=-5,e.successLevel=1),t.successLevel!=null)switch(e.rollType){case"combatskill":case"talent":this._evaluateTalentOpposedRoll(e,t,s,a);break;case"ceremony":case"ritual":case"spell":case"liturgy":case"weapon":case"damage":this._evaluateWeaponOpposedRoll(e,t,s,a);break;default:ui.notifications.error("Can not oppose "+e.rollType),console.warn("Can not oppose "+e.rollType)}return s}static _evaluateWeaponOpposedRoll(e,t,a,s={}){if(e.successLevel>0&&t.successLevel<0){let i=this._calculateOpposedDamage(e,t,s);if(i.armorDamaged.damaged&&i.armorDamaged.ids.length){let c=i.armorDamaged.ids.join(";");a.other.push(`
    `)}t.counterAttack&&(i.damage+=2,i.sum=i.damage-i.armor,i.tooltip=game.i18n.localize("LocalizedIDs.counterAttack")+" 2"),i.messages.length&&(i.tooltip||(i.tooltip=""),i.tooltip+=` ${i.messages.join("
    ")}`),a.winner="attacker";let r=[i.armorMod!=0?`${i.armorMod+" "+game.i18n.localize("Modifier")}`:"",i.armorMultiplier!=1?"*"+i.armorMultiplier+" "+game.i18n.localize("Modifier"):"",i.spellArmor!=0?`${i.spellArmor} ${game.i18n.localize("spellArmor")}`:"",i.liturgyArmor!=0?`${i.liturgyArmor} ${game.i18n.localize("liturgyArmor")}`:""].join(""),o=`${game.combat?.isBrawling?game.i18n.localize("BRAWLING.temporary"):game.i18n.localize("damage")}: ${i.damage} - ${i.armor} = ${i.sum}`;a.damage={description:o,value:i.sum,sp:i.damage}}else a.winner="defender"}static _calculateOpposedDamage(e,t,a={}){let s=f.getSpeaker(t.speaker),i=[],r=e.damage,n=game.i18n.localize("LocalizedIDs.immuneToCrit");e.doubleDamage&&s.items.find(S=>S.name==n&&S.type=="trait")&&(r=Math.floor(r/e.doubleDamage),i.push(n)),a.origin=e.source,a.damage=r;let o=Q.applyRollTransformation(s,a,5).options.damage,{wornArmor:c,armor:m}=T.armorValue(s,a),d=[],p=0,g=e.armorPen||[];for(let S of g)/^\*/.test(S)?d.push(Number(S.replace("*",""))):p+=Number(S);let y=0,h=0;["spell","ritual"].includes(e.source.type)?y+=s.system.spellArmor||0:["liturgy","ceremony"].includes(e.source.type)&&(y+=s.system.liturgyArmor||0),m+=p;let w=d.reduce((S,z)=>S*z,1);m=Math.max(Math.round(m*w),0),m+=y+h;let x=W.armorGetsDamage(o,e),v=c.map(S=>S.uuid);return{damage:o,armor:m,armorDamaged:{damaged:x,ids:v},armorMod:p,spellArmor:y,liturgyArmor:h,armorMultiplier:w,messages:i,sum:o-m}}static _evaluateTalentOpposedRoll(e,t,a,s={}){e.successLevel>0&&e.successLevel>t.successLevel?a.winner="attacker":e.qualityStep>t.qualityStep||e.result>=0&&t.result<0?(a.winner="attacker",a.differenceSL=e.qualityStep-t.qualityStep):(a.winner="defender",a.differenceSL=t.qualityStep-e.qualityStep)}static formatOpposedResult(e,t,a){let s=e.differenceSL?"winsFP":"wins";return e.winner=="attacker"?(e.result=game.i18n.format("OPPOSED."+s,{winner:t.alias,loser:a.alias,SL:e.differenceSL}),e.img=t.img):e.winner=="defender"&&(e.result=game.i18n.format("OPPOSED."+s,{winner:a.alias,loser:t.alias,SL:e.differenceSL}),e.img=a.img),e.speakerAttack=t,e.speakerDefend=a,e}static rerenderMessagesWithModifiers(e,t,a){let s=game.messages.get(t.messageId);this.showDamage(s,e.winner!="attacker")}static async renderOpposedResult(e,t={}){e.hideData=game.settings.get("dsa5","hideOpposedDamage"),e.applyDamageInChat=game.settings.get("dsa5","applyDamageInChat"),e.isBrawling=game.combat?.isBrawling;let a=await renderTemplate("systems/dsa5/templates/chat/roll/opposed-result.html",e),s={user:game.user.id,content:a,"flags.opposeData":e,"flags.hideData":e.hideData,whisper:t.whisper,blind:t.blind};t.target&&(s["flags.startMessageId"]=t.startMessageId),await ChatMessage.create(s)}static async resolveUndefended(e,t=""){let a=e.flags.unopposeData,s=game.messages.get(a.attackMessageId),i={speaker:s.speaker,testResult:s.flags.data.postData,messageId:a.attackMessageId};i.testResult.source=s.flags.data.preData.source,i.testResult.ammo&&i.testResult.source.effects.push(...i.testResult.ammo.effects);let r=canvas.tokens.get(a.targetSpeaker.token),n={speaker:a.targetSpeaker,testResult:{actor:r.actor,speaker:{token:a.targetSpeaker.token}}};await this.clearOpposed(r.actor),await this.completeOpposedProcess(i,n,{target:!0,startMessageId:e.id,additionalInfo:t}),game.user.isGM?await s.update({"flags.data.unopposedStartMessage":e.id}):await game.socket.emit("system.dsa5",{type:"updateAttackMessage",payload:{messageId:s.id,startMessageId:e.id}})}};u(j,"OpposedDsa5");var Ve=class extends Dialog{static async showDialog(e){let t=new Ve({title:game.i18n.localize("WEAR.checkShort"),content:await this.getTemplate(e),buttons:{}});t.items=e,t.render(!0)}activateListeners(e){super.activateListeners(e),e.find(".reactClick").click(t=>{this.callbackResult(t),this.close()})}static async getTemplate(e){let t=e.map(a=>({name:a.name,id:a.id,img:a.img}));return await renderTemplate("systems/dsa5/templates/dialog/dialog-reaction-attack.html",{items:t,title:"WEAR.checkShort"})}callbackResult(e){W.breakingTest(this.items.find(t=>t.id==e.currentTarget.dataset.value))}};u(Ve,"EquipmentDamageDialog");var U=class{static async showBotchCard(e,t={}){t.speaker={token:e.token,actor:e.actor,scene:e.scene},t.source=e.source;let a=b.systemTables.find(i=>i.name==e.table),s=await U.getRollTable(a.pack[game.i18n.lang],game.i18n.localize(`TABLENAMES.${e.table}`),e);for(let i of s){let r=t.speaker?await U.hasEffect(i):!1,n=f.replaceDies(f.replaceConditions(i.results[0].text)),o=`${game.i18n.localize("TABLENAMES."+e.table)}`,c=await renderTemplate("systems/dsa5/templates/tables/tableCard.html",{result:n,title:o,hasEffect:r}),m=await this.buildEffects(i,r);ChatMessage.create({user:game.user.id,content:c,whisper:t.whisper,blind:t.blind,flags:{data:{preData:{source:{effects:m},extra:{actor:{id:t.speaker.actor},speaker:t.speaker},situationalModifiers:[]},postData:{}},dsa5:{hasEffect:r,options:t}}})}}static async hasEffect(e){return getProperty(e.results[0],"flags.dsa5")||!1}static async buildEffects(e,t){let a=[];if(t&&t.resistEffect){let s=Array.isArray(t.resistEffect.fail)?t.resistEffect.fail:[t.resistEffect.fail];for(let i of s){let r=new X().effectDummy(i.description,t.resistEffect.changes||[],t.resistEffect.duration||{});i.systemEffect?mergeObject(r,{_id:"botchEffect",flags:{dsa5:{hideOnToken:!1,hidePlayers:!1,advancedFunction:2,args3:`await actor.addCondition("${i.systemEffect}", ${i.level||1});`}}}):i.command&&mergeObject(r,{_id:"botchEffect",flags:{dsa5:{hideOnToken:!1,hidePlayers:!1,advancedFunction:2,args3:i.command}}}),a.push(r)}}return a}static async getRollTable(e,t,a={}){let i=(await game.packs.get(e).getDocuments({name__in:[t]}))[0],r=await i.draw({displayChat:!1});return a.weaponless=="true"&&r.roll.total<7&&(r.roll.editRollAtIndex([{index:0,val:r.roll.total+5}]),r=await i.draw({displayChat:!1,roll:r.roll})),[r]}static async tableEnabledFor(e){let t=b.systemTables.find(a=>a.name==e);return t?game.settings.get(t.setting.module,t.setting.key):!1}static rollCritBotchButton(e,t,a){let s=game.i18n.localize(`TABLENAMES.${e}`),i=a.extra.speaker,r=a.source._id;return`, ${s}`}static async defaultBotch(){return", "+game.i18n.localize("selfDamage")+(await new Roll("1d6+2").evaluate({async:!0})).total}static defaultAttackCrit(e){let t=", "+game.i18n.localize("halfDefense");return e&&(t+=", "+game.i18n.format("doubleDamage",{x:2})),t}static defaultParryCrit(){return", "+game.i18n.localize("attackOfOpportunity")}};u(U,"DSATables");var B=class{static async payMoney(e,t,a=!1,s=!0){let i=B.canPay(e,t,a);return i.success&&await B._updateMoney(e,i.actorsMoney.money,i.actorsMoney.sum-i.money,s),!a&&i.msg!=""&&ChatMessage.create(f.chatDataSetup(`

    ${i.msg}

    `,"roll")),i.success}static canPay(e,t,a){let s=this._getPaymoney(t),i={success:!1,msg:"",money:s};return s&&(i.actorsMoney=this._actorsMoney(e),i.actorsMoney.sum>=s?(i.msg=game.i18n.format("PAYMENT.pay",{actor:e.name,amount:B._moneyToString(s)}),i.success=!0):(i.msg=game.i18n.format("PAYMENT.cannotpay",{actor:e.name,amount:B._moneyToString(s)}),a&&ui.notifications.notify(i.msg))),i}static async getMoney(e,t,a=!1,s=!0){let i=this._getPaidmoney(t);if(i){let r=this._actorsMoney(e);await B._updateMoney(e,r.money,r.sum+i,s);let n=`

    ${game.i18n.format("PAYMENT.getPaid",{actor:e.name,amount:B._moneyToString(i)})}

    `;return a||ChatMessage.create(f.chatDataSetup(n,"roll")),!0}}static async _updateMoney(e,t,a,s=!0){let i=B._moneyToCoins(a);for(let r of t)switch(r.name){case"Money-D":r.system.quantity.value=i.D;break;case"Money-S":r.system.quantity.value=i.S;break;case"Money-H":r.system.quantity.value=i.H;break;case"Money-K":r.system.quantity.value=i.K;break}await e.updateEmbeddedDocuments("Item",t,{render:s})}static createGetPaidChatMessage(e,t=void 0){let a=this._getPaidmoney(e);if(a){let s=t?` (${t})`:"",i=`

    ${game.i18n.localize("PAYMENT.wage")}

    ${game.i18n.format("PAYMENT.getPaidSum",{amount:B._moneyToString(a)})}${s}

    `;ChatMessage.create(f.chatDataSetup(i,"roll"))}}static createPayChatMessage(e,t=void 0){let a=this._getPaymoney(e);if(a){let s=t?` (${t})`:"",i=`

    ${game.i18n.localize("PAYMENT.bill")}

    ${game.i18n.format("PAYMENT.paySum",{amount:B._moneyToString(a)})}${s}

    `;ChatMessage.create(f.chatDataSetup(i,"roll"))}}static _getPaidmoney(e){let t=this._parseMoneyString(e);if(!t){let a=`

    ${game.i18n.localize("PAYMENT.error")}

    ${game.i18n.localize("PAYMENT.getPaidexample")}

    `;return ChatMessage.create(f.chatDataSetup(a,"roll")),!1}return t}static _getPaymoney(e){let t=this._parseMoneyString(e);if(!t){let a=`

    ${game.i18n.localize("PAYMENT.error")}

    ${game.i18n.localize("PAYMENT.payexample")}

    `;return ChatMessage.create(f.chatDataSetup(a,"roll")),!1}return t}static _parseMoneyString(e){let t=e.replace(",",".").match(/\d{1,}(\.\d{1,3}|,\d{1,3})?/);return t?Number(t[0]):!1}static _actorsMoney(e){let t=duplicate(e.items.filter(a=>a.type=="money"));return{money:t,sum:t.reduce((a,s)=>a+Number(s.system.quantity.value)*Number(s.system.price.value),0)}}static async handlePayAction(e,t,a,s=void 0){if(game.user.isGM&&!s){ui.notifications.notify(game.i18n.localize("PAYMENT.onlyActors"));return}s?K.playMoneySound(!0):s=game.user.character;let i=!1;s&&t?i=await B.payMoney(s,a):s&&!t?i=await B.getMoney(s,a):ui.notifications.notify(game.i18n.localize("PAYMENT.onlyActors")),i&&e&&(e.fadeOut(),game.socket.emit("system.dsa5",{type:"updateMsg",payload:{id:e.closest(".message").attr("data-message-id"),updateData:{[`flags.dsa5.userHidden.${game.user.id}`]:!0}}}))}static _moneyToCoins(e){let t=Math.round(e*100),a=Math.floor(t/1e3),s=Math.floor((t-a*1e3)/100),i=Math.floor((t-a*1e3-s*100)/10);return{D:a,S:s,H:i,K:Math.round(t-a*1e3-s*100-i*10)}}static _moneyToString(e){let t=B._moneyToCoins(e),a=[];for(let[s,i]of Object.entries(t))i>0&&a.push(`${i} `);return a.join(", ")}static async chatListeners(e){e.on("click",".payButton",t=>{let a=$(t.currentTarget);B.handlePayAction(a,Number(a.attr("data-pay"))!=1,a.attr("data-amount")),K.playMoneySound()})}};u(B,"DSA5Payment");var Te=class{constructor(){Te.skills.length==0&&f.allSkills().then(e=>{Te.skills=e.map(t=>({name:t.name,type:"skill"})).concat(Object.values(game.dsa5.config.characteristics).map(t=>({name:game.i18n.localize(t),type:"attribute"})).concat([{name:game.i18n.localize("regenerate"),type:"regeneration"},{name:game.i18n.localize("fallingDamage"),type:"fallingDamage"}]))}),this.filtering=!1,this.combatConstants={dodge:game.i18n.localize("dodge"),parryWeaponless:game.i18n.localize("parryWeaponless"),attackWeaponless:game.i18n.localize("attackWeaponless")}}get regex(){return new RegExp(`^/(${Te.cmds.join(" |")})`)}async chatListeners(e){let t=this,a=e.find("#chat-message");e.on("keyup","#chat-message",async function(i){t._parseInput(i)}),e.on("click",".quick-item",async function(i){t._quickSelect($(i.currentTarget))}),a.on("keydown",function(i){t._navigateQuickFind(i)});let s=jQuery._data(a[0]).events.keydown;s.unshift(s.pop())}_parseInput(e){let t=e.target.value;if(this.regex.test(t)){if([38,40,13,9].includes(e.which))return!1;if(e.which==27)return this._closeQuickfind(e),!1;let a=this._getCmd(t),s=t.substring(1+a.length).toLowerCase().trim();this[`_filter${a}`](s,e),this.filtering=!0}else this._closeQuickfind(e)}_getCmd(e){return e.substring(1,3).toUpperCase().trim()}_completeCurrentEntry(e){$("#chat-message").val($("#chat-message").val().split(" ")[0]+" "+e.text())+""}_closeQuickfind(e){this.filtering=!1,$(e.currentTarget).closest("#chat-form").find(".quickfind").remove()}_filterW(e,t){let a=game.users.contents.filter(s=>s.active&&s.name.toLowerCase().trim().indexOf(e)!=-1).map(s=>({name:s.name,type:"user"}));this._checkEmpty(a),this._setList(a,"W",t)}_filterAT(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["meleeweapon","rangeweapon"],r=["meleeAttack","rangeAttack"],n=a.items.filter(o=>(i.includes(o.type)&&o.system.worn.value==!0||o.type=="trait"&&r.includes(o.system.traitType.value))&&o.name.toLowerCase().trim().indexOf(e)!=-1).slice(0,5).map(o=>({name:o.name,type:"item"})).concat([{name:this.combatConstants.attackWeaponless,type:"item"}].filter(o=>o.name.toLowerCase().trim().indexOf(e)!=-1));this._checkEmpty(n),this._setList(n,"AT",t)}}_filterPA(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["meleeweapon"],r=a.items.filter(n=>i.includes(n.type)&&n.name.toLowerCase().trim().indexOf(e)!=-1&&n.system.worn.value==!0).slice(0,5).map(n=>({name:n.name,type:"item"})).concat([{name:this.combatConstants.dodge,type:"item"},{name:this.combatConstants.parryWeaponless,type:"item"}].filter(n=>n.name.toLowerCase().trim().indexOf(e)!=-1));this._checkEmpty(r),this._setList(r,"PA",t)}}_filterSP(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["spell","ritual"],r=a.items.filter(n=>i.includes(n.type)&&n.name.toLowerCase().trim().indexOf(e)!=-1).slice(0,5).map(n=>({name:n.name,type:"item"}));this._checkEmpty(r),this._setList(r,"SP",t)}}_checkEmpty(e){e.length||e.push({name:game.i18n.localize("DSAError.noMatch"),type:"none"})}_filterLI(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["liturgy","ceremony"],r=a.items.filter(n=>i.includes(n.type)&&n.name.toLowerCase().trim().indexOf(e)!=-1).slice(0,5).map(n=>({name:n.name,type:"item"}));this._checkEmpty(r),this._setList(r,"LI",t)}}_getSkills(e,t=void 0){e=e.replace(/(-|\+)?\d+/g,"").trim();let a=Te.skills.filter(s=>s.name.toLowerCase().trim().indexOf(e)!=-1&&(t==null||t==s.type)).slice(0,5);return this._checkEmpty(a),a}_filterCH(e,t){this._setList(this._getSkills(e),"CH",t)}_filterSK(e,t){this._setList(this._getSkills(e),"SK",t)}_filterRQ(e,t){this._setList(this._getSkills(e),"RQ",t)}_filterGC(e,t){this._setList(this._getSkills(e,"skill"),"GC",t)}_setList(e,t,a){let s=$(`
      ${e.map(n=>`
    • ${n.name}
    • `).join("")}
    `);s.find(".quick-item:first").addClass("focus");let i=$(a.currentTarget).closest("#chat-form"),r=i.find(".quickfind");r.length?r.replaceWith(s):i.append(s)}_navigateQuickFind(e){if(this.filtering){let t=$(e.currentTarget).closest("#chat-form").find(".focus");switch(e.which){case 38:return t.prev(".quick-item").length&&t.removeClass("focus").prev(".quick-item").addClass("focus"),!1;case 40:return t.next(".quick-item").length&&t.removeClass("focus").next(".quick-item").addClass("focus"),!1;case 13:if(t.attr("data-category")=="W")break;return e.stopPropagation(),e.preventDefault(),this._quickSelect(t),!1;case 9:return e.stopPropagation(),e.preventDefault(),this._completeCurrentEntry(t),!1}}return!0}static _getActor(){let e=ChatMessage.getSpeaker(),t;return e.token&&(t=game.actors.tokens[e.token]),t||(t=game.actors.get(e.actor)),t?{actor:t,tokenId:e.token}:(ui.notifications.error(game.i18n.localize("DSAError.noProperActor")),{})}_quickSelect(e){let t=e.attr("data-category");switch(t){case"NM":case"GC":case"RQ":case"CH":this[`_quick${t}`](e);break;case"W":this._completeCurrentEntry(e);break;default:let{actor:a,tokenId:s}=Te._getActor();a&&(this._resetChatAutoCompletion(e),this[`_quick${t}`](e,a,s))}}_quickW(e,t,a){}_quickCH(e){ae.check3D20(e),this._resetChatAutoCompletion(e)}_quickSK(e,t,a){switch(e.attr("data-type")){case"skill":let s=t.items.find(r=>r.name==e.text()&&r.type=="skill");s&&t.setupSkill(s,{},a).then(r=>{t.basicTest(r)});break;case"attribute":let i=Object.keys(game.dsa5.config.characteristics).find(r=>game.i18n.localize(game.dsa5.config.characteristics[r])==e.text());t.setupCharacteristic(i,{},a).then(r=>{t.basicTest(r)});break;case"regeneration":t.setupRegeneration("regenerate",{},a).then(r=>{t.basicTest(r)});break}}_resetChatAutoCompletion(e){let t=e.closest("#chat-form");t.find("#chat-message").val(""),t.find(".quickfind").remove()}_quickGC(e){let t=Number($("#chat-message").val().match(/(-|\+)?\d+/g))||0;this._resetChatAutoCompletion(e),q.showGCMessage(e.text(),t)}_quickRQ(e){let t=Number($("#chat-message").val().match(/(-|\+)?\d+/g))||0;this._resetChatAutoCompletion(e),q.showRQMessage(e.text(),t)}_quickPA(e,t,a){let s=e.text();if(this.combatConstants.dodge==s)t.setupDodge({},a).then(i=>{t.basicTest(i)});else if(this.combatConstants.parryWeaponless==s)t.setupWeaponless("parry",{},a).then(i=>{t.basicTest(i)});else{let i=["meleeweapon"],r=t.items.find(n=>i.includes(n.type)&&n.name==e.text());r&&t.setupWeapon(r,"parry",{},a).then(n=>{t.basicTest(n)})}}_quickAT(e,t,a){let s=e.text();if(this.combatConstants.attackWeaponless==s)t.setupWeaponless("attack",{},a).then(i=>{t.basicTest(i)});else{let i=["meleeweapon","rangeweapon"],r=["meleeAttack","rangeAttack"],n=t.items.find(o=>i.includes(o.type)&&o.name==e.text());n||(n=t.items.find(o=>o.type=="trait"&&o.name==e.text()&&r.includes(o.system.traitType.value))),n&&t.setupWeapon(n,"attack",{},a).then(o=>{t.basicTest(o)})}}_quickSP(e,t,a){let s=["ritual","spell"],i=t.items.find(r=>s.includes(r.type)&&r.name==e.text());i&&t.setupSpell(i,{},a).then(r=>{t.basicTest(r)})}_quickLI(e,t,a){let s=["liturgy","ceremony"],i=t.items.find(r=>s.includes(r.type)&&r.name==e.text());i&&t.setupSpell(i,{},a).then(r=>{t.basicTest(r)})}static async infoItemAsync(e){(await fromUuid(e)).postItem()}static bindRollCommands(e){e.on("click",".request-roll",s=>{let i=s.currentTarget.dataset;return q.showRQMessage(i.name,Number(i.modifier)||0,i.label),s.stopPropagation(),!1}),e.on("click",".postInfo",s=>{let i=fromUuidSync(s.currentTarget.dataset.uuid);return i&&(typeof i.postItem=="function"?i.postItem():this.infoItemAsync(s.currentTarget.dataset.uuid)),s.stopPropagation(),!1}),e.on("click",".postContentChat",async s=>{let i=$(s.currentTarget).closest(".postChatSection").find(".postChatContent").html();lt.getDialog(i)}),e.on("click",".request-GC",s=>(q.showGCMessage(s.currentTarget.dataset.name,Number(s.currentTarget.dataset.modifier)||0),s.stopPropagation(),!1)),e.on("click",".request-CH",s=>(ae.check3D20(void 0,s.currentTarget.dataset.name,{modifier:Number(s.currentTarget.dataset.modifier)||0}),s.stopPropagation(),!1)),e.on("click",".request-Pay",s=>{!game.user.isGM||B.createPayChatMessage(s.currentTarget.dataset.modifier)}),e.on("click",".request-GetPaid",s=>{!game.user.isGM||B.createGetPaidChatMessage(s.currentTarget.dataset.modifier)}),e.on("click",".request-AP",s=>{if(!game.user.isGM)return;let i=game.dsa5.apps.gameMasterMenu;i.getExp(i.selectedIDs(),s.currentTarget.dataset.modifier)});let t=u(s=>{s.stopPropagation();let i=s.currentTarget.dataset.type,r=s.currentTarget.dataset.uuid;!r||!i||s.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:i,uuid:r}))},"itemDragStart"),a=e.find(".show-item");a.click(async s=>{let i=s.currentTarget.dataset.uuid;(await fromUuid(i)).sheet.render(!0)}),a.attr("draggable",!0).on("dragstart",s=>t(s)),e.on("click",".actorEmbeddedAbility",async s=>{let r=(await fromUuid(s.currentTarget.dataset.actor)).items.get(s.currentTarget.dataset.id);r&&r.sheet.render(!0)})}},se=Te;u(se,"DSA5ChatAutoCompletion"),L(se,"skills",[]),L(se,"cmds",["sk","at","pa","sp","li","rq","gc","w","ch"]);var q=class{static async requestGC(e,t,a,s=0){let{actor:i,tokenId:r}=se._getActor();if(!i)return;game.user.updateTokenTargets([]);let n={modifier:s,postFunction:{cummulative:a,functionName:"game.dsa5.apps.RequestRoll.autoEditGroupCheckRoll"}};switch(e){case"attribute":break;default:let o=i.items.find(c=>c.name==t&&c.type==e);i.setupSkill(o,n,r).then(async c=>{let m=await i.basicTest(c);await q.editGroupCheckRoll(a,m,t,e)})}}static async autoEditGroupCheckRoll(e,t,a){await q.editGroupCheckRoll(e.cummulative,t,a.name,a.type)}static async editGroupCheckRoll(e,t,a,s){let i=await game.messages.get(e),r=i.flags,o=t.result.successLevel>1?2:1;r.botched=r.botched||t.result.successLevel<-1;let c=f.getSpeaker(t.result.speaker),m={messageId:t.result.messageId,actor:c.name,qs:(t.result.qualityStep||0)*o,success:t.result.successLevel,target:a,type:s},d=r.results.findIndex(p=>p.messageId==m.messageId);d>=0?r.results[d]=m:r.results.push(m),q.rerenderGC(i,r)}static async requestRoll(e,t,a=0){let{actor:s,tokenId:i}=se._getActor();if(s){game.user.updateTokenTargets([]);let r={modifier:a};switch(e){case"attribute":let n=Object.keys(game.dsa5.config.characteristics).find(c=>game.i18n.localize(game.dsa5.config.characteristics[c])==t);s.setupCharacteristic(n,r,i).then(c=>{s.basicTest(c)});break;case"regeneration":s.setupRegeneration("regenerate",r,i).then(c=>{s.basicTest(c)});break;case"fallingDamage":s.setupFallingDamage(r,i);break;default:let o=s.items.find(c=>c.name==t&&c.type==e);s.setupSkill(o,r,i).then(c=>{s.basicTest(c)})}}}static async rerenderGC(e,t){if(game.user.isGM){let a=0;t.qs=t.results.reduce((i,r)=>(a+=r.success<0?1:0,r.success>1&&(a=0),i+r.qs),0),t.failed=a;for(let i of t.rollOptions)i.calculatedModifier=i.modifier-a;t.openRolls=t.maxRolls-t.results.length,t.doneRolls=t.results.length;let s=await renderTemplate("systems/dsa5/templates/chat/roll/groupcheck.html",t);e.update({content:s,flags:t})}else game.socket.emit("system.dsa5",{type:"updateGroupCheck",payload:{messageId:e.id,data:t}});$("#chat-log").find(`[data-message-id="${e.id}"`).appendTo("#chat-log")}static showRQMessage(e,t=0,a=void 0){let s=t<0?` ${t}`:t>0?` +${t}`:"",i=se.skills.find(n=>n.name==e).type,r=game.i18n.format("CHATNOTIFICATION.requestRoll",{user:game.user.name,item:` ${a||e}${s}`});ChatMessage.create(f.chatDataSetup(r))}static async showGCMessage(e,t=0,a={}){let s=se.skills.find(o=>o.name==e).type,i={results:[],qs:0,failed:0,modifier:t,name:game.user.name,maxRolls:7,openRolls:7,doneRolls:0,targetQs:10,rollOptions:[{type:s,modifier:t,calculatedModifier:t,target:e}]};mergeObject(i,a);let r=await renderTemplate("systems/dsa5/templates/chat/roll/groupcheck.html",i),n=f.chatDataSetup(r);n.flags=i,ChatMessage.create(n)}static async addSkillToGC(e){let t=$(e.currentTarget).parents(".message").attr("data-message-id"),a=await renderTemplate("systems/dsa5/templates/dialog/addgroupcheckskill.html",{skills:se.skills.filter(i=>i.type=="skill").sort((i,r)=>i.name.localeCompare(r.name))}),s={title:game.i18n.localize("HELP.groupcheck"),content:a,buttons:{ok:{icon:'',label:game.i18n.localize("ok"),callback:async i=>{let r=game.messages.get(t),n=r.flags;n.rollOptions.push({type:"skill",modifier:i.find('[name="modifier"]').val(),target:i.find('[name="skill"]').val()}),q.rerenderGC(r,n)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}};new ee(s).render(!0)}static async removeGCEntry(e){let t=$(e.currentTarget),a=Number(e.currentTarget.dataset.index),s=game.messages.get(t.parents(".message").attr("data-message-id")),i=s.flags;i.results.splice(a,1),q.rerenderGC(s,i)}static removeSkillFromGC(e){let t=$(e.currentTarget),a=game.messages.get(t.parents(".message").attr("data-message-id")),s=a.flags;s.rollOptions=s.rollOptions.filter(i=>!(i.type==e.currentTarget.dataset.type&&i.target==e.currentTarget.dataset.name)),s.results=s.results.filter(i=>!(i.type==e.currentTarget.dataset.type&&i.target==e.currentTarget.dataset.name)),q.rerenderGC(a,s)}static async editGC(e){let t=$(e.currentTarget),a=Number(e.currentTarget.dataset.index),s=game.messages.get(t.parents(".message").attr("data-message-id")),i=s.flags;if(a)i.results[a].qs=Number(t.val());else if(e.currentTarget.dataset.name){let r=i.rollOptions.find(n=>n.target==e.currentTarget.dataset.name&&e.currentTarget.dataset.type==n.type);r[e.currentTarget.dataset.field]=Number(t.val())}else i[e.currentTarget.dataset.field]=Number(t.val());q.rerenderGC(s,i)}static async updateInformationRoll(e,t,a){let s=[],i=await fromUuid(e.uuid),r=t.result.qualityStep||0;for(let n=1;n<=r;n++){let o=`qs${n}`;i.system[o]&&s.push(i.system[o])}if(t.result.successLevel>1&&i.system.crit?s.push(i.system.crit):t.result.successLevel<-1&&i.system.botch?s.push(i.system.botch):i.system.fail&&!r&&s.push(i.system.fail),s.length>0){await Promise.all(s.map(async o=>await TextEditor.enrichHTML(o,{async:!0}))),s.unshift(`

    ${i.name}

    `);let n=f.chatDataSetup(s.join(""));e.recipients.length&&(n.whisper=e.recipients),ChatMessage.create(n)}}static async informationRequestRoll(e){let t=e.currentTarget.dataset.mod,a=e.currentTarget.dataset.uuid,{actor:s,tokenId:i}=se._getActor();if(!s)return;let r=game.settings.get("dsa5","informationDistribution"),n=[];r==1?(n=game.users.filter(m=>m.isGM).map(m=>m.id),n.push(game.user.id)):r==2&&(n=game.users.filter(m=>m.isGM).map(m=>m.id));let o={modifier:t,postFunction:{functionName:"game.dsa5.apps.RequestRoll.updateInformationRoll",uuid:a,recipients:n}},c=s.items.find(m=>m.name==e.currentTarget.dataset.skill&&m.type=="skill");s.setupSkill(c,o,i).then(async m=>{m.testData.opposable=!1;let d=await s.basicTest(m);this.updateInformationRoll(o.postFunction,d)})}static chatListeners(e){e.on("change",".editGC",t=>q.editGC(t)),e.on("click",".request-roll",t=>{let a=t.currentTarget.dataset;q.requestRoll(a.type,a.name,Number(a.modifier)||0)}),e.on("click",".request-gc",t=>{let a=t.currentTarget.dataset;q.requestGC(a.type,a.name,$(t.currentTarget).parents(".message").attr("data-message-id"),Number(a.modifier)||0)}),e.on("click",".removeGC",t=>q.removeGCEntry(t)),e.on("click",".removeSkillFromGC",t=>q.removeSkillFromGC(t)),e.on("click",".addSkillToGC",t=>q.addSkillToGC(t)),e.on("click",".informationRequestRoll",t=>q.informationRequestRoll(t))}};u(q,"RequestRoll");var Vt,Kt,ye,dt=class extends MeasuredTemplate{constructor(){super(...arguments);aa(this,Vt,void 0);aa(this,Kt,0);aa(this,ye,void 0)}static async placeTemplateFromChat(t){let a=$(t.currentTarget).parents(".message").attr("data-message-id"),s=game.messages.get(a),i=s.flags.data.preData.source,r=s.flags.data.postData,n=this.fromItem(i,r.qualityStep);n&&n.drawPreview()}static fromItem(t,a){let s=t.system.target||{},i=game.dsa5.config.areaTargetTypes[s.type];if(!i||!s.value)return null;let r=Number(Roll.safeEval(`${s.value}`.replace(/(qs|ql)/gi,a)))||1,n={t:i,user:game.user.id,distance:r,direction:0,x:0,y:0,fillColor:game.user.color,flags:{dsa5:{origin:t.uuid}}};switch(i){case"cone":n.angle=Number(s.angle)||CONFIG.MeasuredTemplate.defaults.angle;break;case"rect":n.distance=Math.hypot(r,r),n.width=r,n.direction=45;break;case"ray":n.width=s.width&&Number(Roll.safeEval(`${s.width}`.replace(/(qs|ql)/gi,a)))||canvas.dimensions.distance;break}let o=CONFIG.MeasuredTemplate.documentClass,c=new o(n,{parent:canvas.scene}),m=new this(c);return m.item=t,m.actorSheet=t.actor?.sheet||null,m}drawPreview(){let t=canvas.activeLayer;return this.draw(),this.layer.activate(),this.layer.preview.addChild(this),this.activatePreviewListeners(t)}activatePreviewListeners(t){return new Promise((a,s)=>{sa(this,Vt,t),sa(this,ye,{cancel:this._onCancelPlacement.bind(this),confirm:this._onConfirmPlacement.bind(this),move:this._onMovePlacement.bind(this),resolve:a,reject:s,rotate:this._onRotatePlacement.bind(this)}),canvas.stage.on("mousemove",ve(this,ye).move),canvas.stage.on("mousedown",ve(this,ye).confirm),canvas.app.view.oncontextmenu=ve(this,ye).cancel,canvas.app.view.onwheel=ve(this,ye).rotate})}async _finishPlacement(t){this.layer._onDragLeftCancel(t),canvas.stage.off("mousemove",ve(this,ye).move),canvas.stage.off("mousedown",ve(this,ye).confirm),canvas.app.view.oncontextmenu=null,canvas.app.view.onwheel=null,ve(this,Vt).activate(),await this.actorSheet?.maximize()}_onMovePlacement(t){t.stopPropagation();let a=Date.now();if(a-ve(this,Kt)<=20)return;let s=t.data.getLocalPosition(this.layer),i=canvas.grid.getSnappedPosition(s.x,s.y,2);this.document.updateSource({x:i.x,y:i.y}),this.refresh(),sa(this,Kt,a)}_onRotatePlacement(t){t.ctrlKey&&t.preventDefault(),t.stopPropagation();let a=canvas.grid.type>CONST.GRID_TYPES.SQUARE?30:15,s=t.shiftKey?a:5,i={direction:this.document.direction+s*Math.sign(t.deltaY)};this.document.updateSource(i),this.refresh()}async _onConfirmPlacement(t){await this._finishPlacement(t);let a=canvas.grid.getSnappedPosition(this.document.x,this.document.y,2);this.document.updateSource(a),ve(this,ye).resolve(canvas.scene.createEmbeddedDocuments("MeasuredTemplate",[this.document.toObject()]))}async _onCancelPlacement(t){await this._finishPlacement(t),ve(this,ye).reject()}};u(dt,"MeasuredTemplateDSA"),Vt=new WeakMap,Kt=new WeakMap,ye=new WeakMap;var Ke=class{static async applyEffect(e,t){let a=game.messages.get(e),s=getProperty(a,"flags.dsa5.hasEffect"),i=getProperty(a,"flags.dsa5.options")||{};if(s){let r=["damageModifier","gearDamaged","gearLost","resistEffect","malus","selfDamage","nextAction"],n=[],o;if(t=="self"){let m=f.getSpeaker(i.speaker);n.push(m),o=i.source?m.items.get(i.source):void 0}else n=Array.from(game.user.targets).map(m=>m.actor);for(let m of r){let d=getProperty(s,m);d&&(await Ke[m](d,t,n,o,e,a)||console.warn(`Table effect for <${m} not working yet`,d,t,n,o))}let c=game.i18n.format("ActiveEffects.appliedEffect",{source:game.i18n.localize("table"),target:n.map(m=>m.name).join(", ")});await a.update({content:a.content.replace(/hideAnchor">/,`hideAnchor">`)})}}static async damageModifier(e,t,a,s){}static async nextAction(e,t,a,s){}static async opportunityAttack(e,t,a,s){}static async gearDamaged(e,t,a,s){if(s&&["meleeweapon","rangeweapon"].includes(s.type)){let i=getProperty(s,"system.effect.attributes")||"";return new RegExp(`(${I.magical}|${I.clerical})`,"i").test(i)?await s.update({"system.worn.value":!1}):await W.absoluteDamageLevelToItem(s,e),!0}}static async gearLost(e,t,a,s){if(s&&["meleeweapon","rangeweapon"].includes(s.type)){if(await s.update({"system.worn.value":!1}),e.distance){let i=await new Roll(e.distance).evaluate({async:!0}),r=await i.render(),n=game.i18n.format("WEAPON.dropped",{distance:i.total});ChatMessage.create(f.chatDataSetup(`

    ${n}

    ${r}`))}return!0}}static async resistEffect(e,t,a,s,i){for(let r of a){let n=[{skill:e.roll,mod:e.modifier||0,effect:{_id:"botchEffect",name:e.fail.description},target:r,token:r.token?r.token.id:void 0}];Q.createResistRollMessage(n,i,t)}return!0}static evaluateTargetArg(e,t){let a=t,s=!0;if(e.target=="victim"){let i=Array.from(game.user.targets).map(r=>r.actor);i.length?a=i:(s=!1,ui.notifications.warn("DSAError.noVictim"))}return{hasTargets:s,finalTargets:a}}static async malus(e,t,a,s){let{hasTargets:i,finalTargets:r}=this.evaluateTargetArg(e,a);for(let n of e){let o=!i&&n.noTarget,c=o?n.noTarget.systemEffect:n.systemEffect,m=o?n.noTarget.level:n.level||1,d=o?n.noTarget.changes:n.changes,p=o?n.noTarget.duration:n.duration;if(c){let g=CONFIG.statusEffects.find(h=>h.id==c);if(!d){d=duplicate(g.changes);let h=d.find(w=>w.key==`system.condition.${c}`);h&&(h.value=m)}let y;if(d){let h=game.i18n.localize(`CONDITION.${c}`)+" - "+game.i18n.localize("botchCritEffect");y=new X().effectDummy(h,d,p||{}),y.icon=g.icon}else y=c;for(let h of r)await h.addCondition(y);return!0}else if(d){let g=new X().effectDummy(game.i18n.localize("botchCritEffect"),d||[],p||{});mergeObject(g,{flags:{dsa5:{hideOnToken:!1,hidePlayers:!1}}});for(let y of r)await y.addCondition(g);return!0}}}static async selfAttack(e,t,a,s){let{hasTargets:i,finalTargets:r}=this.evaluateTargetArg(e,a)}static async selfDamage(e,t,a,s){let{hasTargets:i,finalTargets:r}=this.evaluateTargetArg(e,a);if(s){let n=f.toObjectIfPossible(s);for(let o of r){let c=o.items.filter(g=>g.type=="combatskill").map(g=>T._calculateCombatSkillValues(g.toObject(),o.system)),m;e.damage?m={damagedie:e.damage,damageAdd:""}:s.type=="rangeweapon"?m=T._prepareRangeWeapon(n,[],c,o):s.type=="meleeweapon"?m=T._prepareMeleeWeapon(n,c,o):m=s.system.traitType.value=="meleeAttack"?T._prepareRangeTrait(n):T._prepareMeleetrait(n);let d=(m.damagedie+m.damageAdd).replace(/wWD/g,"d"),p=await new Roll(`(${d})*${e.multiplier||1}${e.modifier||""}`).evaluate({async:!0});await o.applyDamage(Math.round(p.total)),ChatMessage.create(f.chatDataSetup(await p.render()))}return!0}else{for(let n of r){let o=await new Roll("1d6").evaluate({async:!0});await n.applyDamage(Math.round(o.total)),ChatMessage.create(f.chatDataSetup(await o.render()))}return!0}}};u(Ke,"TableEffects");var Ct=u(async(l,e,t=1)=>{let a=game.messages.get(l.attr("data-message-id")),s=a.flags.opposeData,i=s?.speakerDefend,r=f.getSpeaker(i);if(!r.isOwner)return ui.notifications.error(game.i18n.localize("DSAError.DamagePermission"));await r.applyDamage(s.damage[e]*t);let n={"flags.data.damageApplied":!0,content:a.content.replace(/hideAnchor">/,`hideAnchor">`)};game.user.isGM?await a.update(n):game.socket.emit("system.dsa5",{type:"updateMsg",payload:{id:l.attr("data-message-id"),updateData:n}})},"applyDamage");function Ii(){let l=u((N,D)=>f.fateAvailable(N,D),"fateAvailable"),e=u(function(N,D="damage.value"){let C=game.messages.get(N.attr("data-message-id")).flags.opposeData,G=C?f.getSpeaker(C.speakerDefend)?.isOwner:!1;return((game.user.isGM||G)&&N.find(".opposed-card").length||N.find(".dice-roll").length)&&(getProperty(C,D)||0)>0},"canHurt"),t=u(function(N){return e(N,"damage.sp")},"canHurtSP"),a=u(function(N){let D=game.messages.get(N.attr("data-message-id"));return D.speaker.actor&&D.flags.data&&(game.actors.get(D.speaker.actor).isOwner||game.user.isGM)?["liturgy","ceremony","spell","ritual","magicalsign"].includes(D.flags.data.preData.source.type)||getProperty(D.flags.data.preData,"calculatedSpellModifiers.costsMana"):!1},"canCostMana"),s=u(function(N){if(game.user.isGM&&game.settings.get("dsa5","hideOpposedDamage")){let D=game.messages.get(N.attr("data-message-id"));return"hideData"in D.flags&&D.flags.hideData}return!1},"canUnhideData"),i=u(function(N){if(game.user.isGM&&game.settings.get("dsa5","hideOpposedDamage")){let D=game.messages.get(N.attr("data-message-id"));return"hideData"in D.flags&&!D.flags.hideData}return!1},"canHideData"),r=u(function(N,D=!1){let C=game.messages.get(N.attr("data-message-id"));if(C.speaker.actor&&C.flags.data&&C.flags.data.postData.successLevel>-2){let G=game.actors.get(C.speaker.actor);if(G.isOwner&&l(G,D)){let Z=C.flags.data.preData.source.type,ke=C.flags.data.preData.mode||"";["skill","spell","liturgy","ritual","ceremony"].includes(Z)&&(Z="char");let we=game.i18n.localize(`SCHIPSKILLS.${Z}${ke}`);return!C.flags.data.fateImproved&&G.items.getName(we)}}return!1},"canImproveRoll"),n=u(function(N){return r(N,!0)},"canImproveRollGroup"),o=u(function(N,D=!1){let C=game.messages.get(N.attr("data-message-id"));if(C.speaker.actor&&C.flags.data){let G=game.actors.get(C.speaker.actor);if(G.isOwner&&l(G,D)&&!C.flags.data.fatePointAddQSUsed)return C.flags.data.postData.successLevel>0&&C.flags.data.postData.qualityStep!=null}return!1},"canIncreaseQS"),c=u(function(N){return o(N,!0)},"canIncreaseQSGroup"),m=u(function(N){let D=game.messages.get(N.attr("data-message-id"));if(D.speaker.actor&&D.flags.data){let C=game.actors.get(D.speaker.actor);if(C.isOwner)return C.items.find(G=>G.name==`${game.i18n.localize("LocalizedIDs.aptitude")} (${D.flags.data.preData.source.name})`)!=null&&!D.flags.data.talentedRerollUsed}return!1},"isTalented"),d=u(function(N,D=!1){let C=game.messages.get(N.attr("data-message-id"));if(C.speaker.actor&&C.flags.data){let G=game.actors.get(C.speaker.actor);if(G.isOwner&&l(G,D))return C.flags.data.postData.damageRoll!=null&&!C.flags.data.fatePointDamageRerollUsed}return!1},"canRerollDamage"),p=u(function(N){return d(N,!0)},"canRerollDamageGroup"),g=u(function(N,D=!1){let C=game.messages.get(N.attr("data-message-id"));if(C.speaker.actor&&C.flags.data){let G=game.actors.get(C.speaker.actor);if(G.isOwner&&l(G,D))return!C.flags.data.fatePointRerollUsed&&C.flags.data.postData.rollType!="regenerate"}return!1},"canReroll"),y=u(function(N){return g(N,!0)},"canRerollGroup"),h=u(function(N){let D=game.messages.get(N.attr("data-message-id"));return D.speaker.actor&&D.flags.data&&game.actors.get(D.speaker.actor).isOwner&&["LeP","KaP","AsP"].some(G=>getProperty(D.flags,`data.postData.${G}`)!=null)?!D.flags.data.healApplied:!1},"canHeal"),w=u(function(N){if(game.user.isGM){let D=game.messages.get(N.attr("data-message-id"));if("hideData"in D.flags){let C=!D.flags.hideData,G=$(D.content);G.find(".hideAnchor")[C?"addClass":"removeClass"]("hideData"),G=$("
    ").append(G),D.update({content:G.html(),"flags.hideData":C})}}},"showHideData"),x=u(N=>{let D=game.messages.get(N.data("messageId"));return!D||!canvas.tokens?!1:D.isRoll&&D.isContentVisible&&canvas.tokens.controlled.length&&N.find(".dice-roll").length},"canApplyDefaultRolls"),v=u((N,D,C=0)=>{let G=game.messages.get(N.attr("data-message-id"));game.actors.get(G.speaker.actor).useFateOnRoll(G,D,C)},"useFate"),S=u((N,D,C=1)=>{let Z=game.messages.get(N.data("messageId")).rolls[0];return Promise.all(canvas.tokens.controlled.map(ke=>{let we=ke.actor,rt=Math.round((D!="sp"?Z.total-T.armorValue(we).armor:Z.total)*C);return we.applyDamage(Math.max(0,rt))}))},"applyChatCardDamage"),z=u(async N=>{let D=game.messages.get(N.attr("data-message-id")),C=D.flags.data,G=f.getSpeaker(D.speaker);if(!G.isOwner)return ui.notifications.error(game.i18n.localize("DSAError.DamagePermission"));let Z=C.preData.calculatedSpellModifiers.maintainCost.trim(),ke=["ritual","spell"].includes(C.preData.source.type)||getProperty(C.preData.calculatedSpellModifiers,"costsMana")?"AsP":"KaP",we=await G.applyMana(C.preData.calculatedSpellModifiers.finalcost,ke);if(Z&&Z!=0&&we&&C.postData.successLevel>0){let rt=C.preData.source.name;try{let jt=Z.match(/^\d{1,3}/)[0],ft=Z.replace(/^\d{1,3}/,"").match(/\d{1,3}/);ft=ft&&Number(ft[0])||1;let ht={name:`${rt} (${game.i18n.localize("maintainCost")})`,icon:"icons/svg/daze.svg",flags:{dsa5:{description:Z,maintain:jt,payType:ke}},changes:[],duration:{}},ea=[{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.combatRounds"),"gi"),seconds:5},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.minutes"),"gi"),seconds:60},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.hours"),"gi"),seconds:3600},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.days"),"gi"),seconds:3600*24},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.seconds"),"gi"),seconds:1},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.weeks"),"gi"),seconds:3600*24*7},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.months"),"gi"),seconds:3600*24*30},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.years"),"gi"),seconds:3600*24*350}];for(let k of ea)if(k.regEx.test(Z)){let V=Number(ft)*k.seconds;ht.duration.seconds=V,ht.duration.rounds=ht.duration.seconds/5;break}await G.addCondition(ht)}catch{console.error(`Could not parse duration '${Z}' of '${rt}'`)}}await D.update({"flags.data.manaApplied":!0,content:D.content.replace(//,'')})},"payMana"),F=u(()=>game.i18n.localize(game.combat?.isBrawling?"CHATCONTEXT.ApplyDamagePP":"CHATCONTEXT.ApplyDamage"),"applyDamageLabel");Hooks.on("getChatLogEntryContext",(N,D)=>{D.push({name:game.i18n.localize("CHATCONTEXT.hideData"),icon:'',condition:i,callback:C=>{w(C)}},{name:game.i18n.localize("CHATCONTEXT.showData"),icon:'',condition:s,callback:C=>{w(C)}},{name:game.i18n.localize("regenerate"),icon:'',condition:h,callback:async C=>{let G=await game.messages.get(C.attr("data-message-id")),Z=f.getSpeaker(G.speaker);if(!Z.isOwner)return ui.notifications.error(game.i18n.localize("DSAError.DamagePermission"));await G.update({"flags.data.healApplied":!0,content:G.content.replace(/<\/div>$/,'
    ')}),await Z.applyRegeneration(G.flags.data.postData.LeP,G.flags.data.postData.AsP,G.flags.data.postData.KaP)}},{name:game.i18n.localize("CHATCONTEXT.ApplyMana"),icon:'',condition:a,callback:async C=>{z(C)}},{name:F(),icon:'',condition:e,callback:C=>{Ct(C,"value")}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP"),icon:'',condition:t,callback:C=>{Ct(C,"sp")}},{name:F(),icon:'',condition:x,callback:C=>{S(C,"value")}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP"),icon:'',condition:x,callback:C=>{S(C,"sp")}},{name:game.i18n.localize("CHATCONTEXT.Reroll"),icon:'',condition:g,callback:C=>{v(C,"reroll")}},{name:game.i18n.localize("CHATCONTEXT.RerollGroup"),icon:'',condition:y,callback:C=>{v(C,"reroll",1)}},{name:game.i18n.localize("CHATCONTEXT.talentedReroll"),icon:'',condition:m,callback:C=>{v(C,"isTalented")}},{name:game.i18n.localize("CHATCONTEXT.AddQS"),icon:'',condition:o,callback:C=>{v(C,"addQS")}},{name:game.i18n.localize("CHATCONTEXT.AddQSGroup"),icon:'',condition:c,callback:C=>{v(C,"addQS",1)}},{name:game.i18n.localize("CHATCONTEXT.rerollDamage"),icon:'',condition:d,callback:C=>{v(C,"rerollDamage")}},{name:game.i18n.localize("CHATCONTEXT.rerollDamageGroup"),icon:'',condition:p,callback:C=>{v(C,"rerollDamage",1)}},{name:game.i18n.localize("CHATCONTEXT.improveFate"),icon:'',condition:r,callback:C=>{v(C,"Improve")}},{name:game.i18n.localize("CHATCONTEXT.improveFateGroup"),icon:'',condition:n,callback:C=>{v(C,"Improve",1)}}),game.settings.get("dsa5","doubleDamageOptions")&&D.push({name:F()+" x2",icon:'',condition:e,callback:C=>{Ct(C,"value",2)}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP")+" x2",icon:'',condition:t,callback:C=>{Ct(C,"sp",2)}},{name:F()+" x2",icon:'',condition:x,callback:C=>{S(C,"value",2)}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP")+" x2",icon:'',condition:x,callback:C=>{S(C,"sp",2)}})})}u(Ii,"chatContext");var _DiceDSA5=class{static async rollTest(l){let e;switch(l.source.type){case"ceremony":case"ritual":case"liturgy":case"spell":e=await this.rollSpell(l);break;case"skill":e=await this.rollTalent(l);break;case"combatskill":e=await this.rollCombatskill(l);break;case"trait":l.mode=="parry"&&await this.updateDefenseCount(l),e=l.mode=="damage"?await this.rollDamage(l):await this.rollCombatTrait(l);break;case"regenerate":e=await this.rollRegeneration(l);break;case"meleeweapon":case"rangeweapon":l.mode=="parry"&&await this.updateDefenseCount(l),e=l.mode=="damage"?await this.rollDamage(l):await this.rollWeapon(l);break;case"dodge":await this.updateDefenseCount(l),e=await this.rollStatus(l);break;case"poison":case"disease":e=await this.rollItem(l);break;case"fallingDamage":e=await this.rollFallingDamage(l);break;default:e=await this.rollAttribute(l)}return mergeObject(e,deepClone(l.extra)),e}static async rollDices(l,e){if(!l.roll){let t=game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration,a;switch(l.source.type){case"liturgy":case"spell":case"ceremony":case"ritual":case"skill":a=await new Roll("1d20+1d20+1d20").evaluate({async:!0}),mergeObject(a.dice[0].options,t(l.source.system.characteristic1.value)),mergeObject(a.dice[1].options,t(l.source.system.characteristic2.value)),mergeObject(a.dice[2].options,t(l.source.system.characteristic3.value));break;case"regenerate":let s=[];l.regenerateLeP&&s.push([game.settings.get("dsa5","lessRegeneration")?"1d3":"1d6"]),l.extra.actor.isMage&&l.regenerateAsP&&s.push("1d6"),l.extra.actor.isPriest&&l.regenerateKaP&&s.push("1d6"),a=await new Roll(s.join("+")).evaluate({async:!0}),l.regenerateLeP&&mergeObject(a.dice[0].options,t("mu")),l.extra.actor.isMage&&l.regenerateAsP&&mergeObject(a.dice[s.length-1].options,t("ge")),l.extra.actor.isPriest&&l.regenerateKaP&&mergeObject(a.dice[s.length-1].options,t("in")),l.extra.actor.isMage&&l.regenerateAsP&&l.extra.actor.isPriest&&l.regenerateKaP&&mergeObject(a.dice[s.length-2].options,t("ge"));break;case"meleeweapon":case"rangeweapon":case"weaponless":case"combatskill":case"trait":if(l.mode=="damage"){let o=await this.damageFormula(l);a=await new Roll(o).evaluate({async:!0});for(let c=0;c{n.actor&&r.push({name:n.actor.name,id:n.id,img:n.actor.img})}),mergeObject(l.data,{hasSituationalModifiers:i.length>0,situationalModifiers:i,rollMode:l.data.rollMode||a,rollModes:CONFIG.Dice.rollModes,defenseCount:await this.getDefenseCount(e),targets:r}),mergeObject(t,{user:game.user.id}),e.extra.options.bypass)return t.rollMode=e.extra.options.rollMode||a,e.situationalModifiers||(e.situationalModifiers=[]),{testData:e,cardOptions:t};{let n=ee.getDialogForItem(e,l.data),o=await renderTemplate(l.template,l.data);return new Promise((c,m)=>{new n({title:l.title,content:o,buttons:n.getRollButtons(e,l,c,m),default:"rollButton"}).recallSettings(e.extra.speaker,e.source,e.mode,l.data).render(!0)})}}static async getDefenseCount(l){return game.combat?await game.combat.getDefenseCount(l.extra.speaker):0}static async _rollConfirm(){return await new Roll("1d20").evaluate({async:!0})}static async _rollSingleD20(l,e,t,a,s,i="",r=1){let n="",o=[];e+=a,e=Math.round(e*r);let c=e-l.terms[0].results[0].result,m=game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration(t);o.push({char:t,res:l.terms[0].results[0].result,suc:c>=0,tar:e});let d=c>=0?1:-1,p=20,g=1;if(s.source.type=="meleeweapon"&&(p=Math.min(s.extra.actor.system.meleeStats.botch,s.source.system.botch),g=Math.max(s.extra.actor.system.meleeStats.crit,s.source.system.crit)),s.source.type=="rangeweapon"&&(p=Math.min(s.extra.actor.system.rangeStats.botch,s.source.system.botch),g=Math.max(s.extra.actor.system.rangeStats.crit,s.source.system.crit)),P.improvisedWeapon.test(s.source.name)&&(R.hasAbility(s.extra.actor,game.i18n.localize("LocalizedIDs.improvisedWeaponMaster"))||(p=Math.min(19,p)),this._appendSituationalModifiers(s,`${game.i18n.localize("CHAR.ATTACK")} - ${game.i18n.localize("WEAPON.improvised")}`,2,"defenseMalus")),s.situationalModifiers.find(y=>y.name==game.i18n.localize("opportunityAttack")&&y.value!=0)&&(p=50,g=-50),l.terms[0].results.filter(y=>y.result<=g).length==1)if(n=game.i18n.localize("CriticalSuccess"),game.settings.get("dsa5","noConfirmationRoll"))d=3;else{let y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"confirmationRoll",s.extra.options),h=e-y.terms[0].results[0].result;if(O.hasVantage(s.extra.actor,`${game.i18n.localize("LocalizedIDs.weaponAptitude")} (${i})`)&&!(h>=0)){let w=y.terms[0].results[0].result;y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"LocalizedIDs.weaponAptitude",s.extra.options),h=e-y.terms[0].results[0].result,n+=", "+game.i18n.format("usedWeaponExpertise",{a:w,b:y.terms[0].results[0].result})}this._addRollDiceSoNice(s,y,m),o.push({char:t,res:y.terms[0].results[0].result,suc:h>=0,tar:e}),d=h>=0?3:2}else if(l.terms[0].results.filter(y=>y.result>=p).length==1)if(n=game.i18n.localize("CriticalFailure"),game.settings.get("dsa5","noConfirmationRoll"))d=-3;else{let y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"confirmationRoll",s.extra.options),h=e-y.terms[0].results[0].result;if(O.hasVantage(s.extra.actor,`${game.i18n.localize("LocalizedIDs.weaponAptitude")} (${i})`)&&!(h>=0)){let w=y.terms[0].results[0].result;y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"LocalizedIDs.weaponAptitude",s.extra.options),h=e-y.terms[0].results[0].result,n+=", "+game.i18n.format("usedWeaponExpertise",{a:w,b:y.terms[0].results[0].result})}this._addRollDiceSoNice(s,y,m),o.push({char:t,res:y.terms[0].results[0].result,suc:h>=0,tar:e}),d=h>=0?-2:-3}return n==""?n=game.i18n.localize(c>=0?"Success":"Failure"):game.settings.get("dsa5","noConfirmationRoll")||(Math.abs(d)==3?n=`${game.i18n.localize("confirmed")} ${n}`:Math.abs(d)==2&&(n=`${game.i18n.localize("unconfirmed")} ${n}`)),{successLevel:d,characteristics:o,description:n,preData:s,modifiers:a,extra:{}}}static async rollFallingDamage(l){let e=l.roll,t=[];for(let s of e.terms[0].results)t.push({char:"damage",res:s.result,suc:!1});return{rollType:"fallingDamage",preData:l,modifiers:await this._situationalModifiers(l),extra:{},damage:Math.max(0,e.total),formula:e.formula,characteristics:t}}static async rollRegeneration(l){let e=await this._situationalModifiers(l),t=l.roll,a=[],s={rollType:"regenerate",preData:l,modifiers:e,extra:{}},i=[];l.regenerateLeP&&i.push("LeP"),l.extra.actor.system.isMage&&l.regenerateAsP&&i.push("AsP"),l.extra.actor.system.isPriest&&l.regenerateKaP&&i.push("KaP");let r=0;if(l.extra.actor.effects.some(o=>o.statuses.includes("sick"))){this._appendSituationalModifiers(l,game.i18n.localize("CONDITION.sick"),"*0");for(let o of i)a.push({char:o,res:0,die:"d6"}),s[o]=0,r+=2}else for(let o of i)this._appendSituationalModifiers(l,game.i18n.localize(`LocalizedIDs.regeneration${o}`),O.vantageStep(l.extra.actor,game.i18n.localize(`LocalizedIDs.regeneration${o}`)),o),this._appendSituationalModifiers(l,game.i18n.localize(`LocalizedIDs.weakRegeneration${o}`),O.vantageStep(l.extra.actor,game.i18n.localize(`LocalizedIDs.weakRegeneration${o}`))*-1,o),this._appendSituationalModifiers(l,game.i18n.localize(`LocalizedIDs.advancedRegeneration${o}`),R.abilityStep(l.extra.actor,game.i18n.localize(`LocalizedIDs.advancedRegeneration${o}`)),o),this._appendSituationalModifiers(l,`${game.i18n.localize(`CHARAbbrev.${o}`)} ${game.i18n.localize("Modifier")}`,l[`${o}Modifier`],o),this._appendSituationalModifiers(l,`${game.i18n.localize(`CHARAbbrev.${o}`)} ${game.i18n.localize("regenerate")}`,l[`regeneration${o}`],o),a.push({char:o,res:t.terms[r].results[0].result,die:"d6"}),s[o]=Math.round(Math.max(0,Number(t.terms[r].results[0].result)+Number(e)+await this._situationalModifiers(l,o))*Number(l.regenerationFactor)),r+=2;return s.characteristics=a,s}static async rollStatus(l){let e=l.roll||await new Roll("1d20").evaluate({async:!0}),t=await this._rollSingleD20(e,l.source.system.max,l.extra.statusId,await this._situationalModifiers(l),l,"",this._situationalMultipliers(l));t.rollType="dodge";let a=l.extra.statusId=="dodge";return a&&t.successLevel==3?await U.tableEnabledFor("criticalMeleeDefense")?t.description+=U.rollCritBotchButton("criticalMeleeDefense",!1,l,l):t.description+=U.defaultParryCrit():a&&t.successLevel==-3&&(await U.tableEnabledFor("Defense")?t.description+=U.rollCritBotchButton("Defense",!0,l,l):t.description+=await U.defaultBotch()),t}static async rollAttribute(l){let e=l.roll?l.roll:await new Roll("1d20").evaluate({async:!0});this._appendSituationalModifiers(l,game.i18n.localize("Difficulty"),l.testDifficulty);let t=await this._rollSingleD20(e,l.source.system.value,l.extra.characteristicId,await this._situationalModifiers(l),l,"",this._situationalMultipliers(l));return t.rollType="attribute",t}static async damageFormula(l){let e;if(l.source.type=="meleeweapon"){let t=T._calculateCombatSkillValues(l.extra.actor.items.find(a=>a.type=="combatskill"&&a.name==l.source.system.combatskill.value),l.extra.actor.system);e=T._prepareMeleeWeapon(l.source,[t],l.extra.actor)}else if(l.source.type=="rangeweapon"){let t=T._calculateCombatSkillValues(l.extra.actor.items.find(a=>a.type=="combatskill"&&a.name==l.source.system.combatskill.value),l.extra.actor.system);e=T._prepareRangeWeapon(l.source,[],[t],l.extra.actor)}else e=l.source.system;return l.source.system.damage.value.replace(/[Ww]/g,"d")+`+${e.extraDamage||0}`}static async rollDamage(l){let e=await this._situationalModifiers(l),t=[],a=l.roll,s=a.total+e;for(let i of a.terms)if(i instanceof Die||i.class=="Die")for(let r of i.results)t.push({char:l.mode,res:r.result,die:"d"+i.faces});return{rollType:"damage",damage:s,characteristics:t,preData:l,modifiers:e,extra:{}}}static async _situationalModifiers(l,e=""){let t=0;for(let a of l.situationalModifiers){if(a.value==null)continue;let s=Number(a.value)||await this._stringToRoll(a.value);t+=a.type==e||e==""&&a.type==null?s:0}return t}static _situationalPartCheckModifiers(l){return l.situationalModifiers.reduce(function(e,t){if(t.type=="TPM"){let a=t.value.split("|");return a.length!=3||(e[0]=e[0]+Number(a[0]),e[1]=e[1]+Number(a[1]),e[2]=e[2]+Number(a[2])),e}else return e},[0,0,0])}static _situationalMultipliers(l){return l.situationalModifiers.reduce(function(e,t){return e*(t.type=="*"&&Number(`${t.value}`.replace(/,/,"."))||1)},1)}static _appendSituationalModifiers(l,e,t,a=""){let s=l.situationalModifiers.find(i=>i.name==e);s?s.value=t:l.situationalModifiers.push({name:e,value:t,type:a})}static async rollCombatTrait(l){let e=l.roll||await new Roll("1d20").evaluate({async:!0}),t=l.source,a=t.system.traitType.value=="meleeAttack",s=l.mode=="attack";if(a){let o={system:{combatskill:{value:"-"},reach:{value:t.system.reach.value}}};this._appendSituationalModifiers(l,game.i18n.localize("opposingWeaponSize"),this._compareWeaponReach(o,l))}let i=await this._rollSingleD20(e,Number(s?t.system.at.value:t.system.pa),l.mode,await this._situationalModifiers(l),l,"",this._situationalMultipliers(l)),r=i.successLevel>0;await this.detailedWeaponResult(i,l,t),s&&r&&await _DiceDSA5.evaluateDamage(l,i,t,!a,i.doubleDamage),i.rollType="weapon";let n=_DiceDSA5.parseEffect(t);return n&&(i.parsedEffect=n),i}static async _stringToRoll(l,e){let t=[],a=/\d{1}[dDwW]\d/g,s=`${l}`;s.replace(a,function(n){t.push(new Roll(n.replace(/[Ww]/,"d")).evaluate({async:!0}))});let i=await Promise.all(t),r=s.replace(a,()=>{let n=i.shift();return e&&_DiceDSA5._addRollDiceSoNice(e,n,game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration("ch")),n.total});return await Roll.safeEval(r)}static async evaluateDamage(l,e,t,a,s){let i=t.system.damage.value.replace(/[Ww]/g,"d"),r=[],n=t.dmgMultipliers||[],o=n.map(h=>`${h.name} *${h.val}`),c=[],m=0;for(let h of l.situationalModifiers){let w=0;if(h.armorPen&&c.push(h.armorPen),h.damageBonus){if(/^\*/.test(h.damageBonus)){n.push({name:h.name,val:Number(h.damageBonus.replace("*",""))});continue}let x=/^=/.test(h.damageBonus),v=`${h.damageBonus}`.replace(/^=/,""),S=await _DiceDSA5._stringToRoll(v,l);if(w=S*(h.step||1),x){i=v.replace(/[Ww]/,"d"),r.push({name:h.name,roll:S});continue}else h.damageBonus=S,m+=w}}let d=l.damageRoll?l.damageRoll:await _DiceDSA5.manualRolls(await new Roll(i).evaluate({async:!0}),"CHAR.DAMAGE",l.extra.options),p=d.total,g=0;for(let h of d.terms)if(h instanceof Die||h.class=="Die")for(let w of h.results)g+=Number(w.result),e.characteristics.push({char:"damage",res:w.result,die:"d"+h.faces});let y=p-g;if(r.length>0)o.push(r[0].name+" "+p);else{p+=m,o.push(game.i18n.localize("Roll")+" "+g),y!=0&&o.push(game.i18n.localize("weaponModifier")+" "+y),l.situationalModifiers.reduce((x,v)=>{if(v.damageBonus){let S=/^\*/.test(v.damageBonus)?v.damageBonus:Number(v.damageBonus)*(v.step||1);o.push(`${v.name} ${S}`)}},o),l.situationalModifiers.find(x=>x.name.indexOf(game.i18n.localize("CONDITION.bloodrush"))>-1)&&(p+=2,o.push(game.i18n.localize("CONDITION.bloodrush")+" "+2)),t.extraDamage&&(p=Number(t.extraDamage)+Number(p),o.push(game.i18n.localize("damageThreshold")+" "+t.extraDamage));let h=l.extra.actor.system[a?"rangeStats":"meleeStats"].damage,w=await _DiceDSA5._stringToRoll(h,l);w!=0&&(p+=w,o.push(game.i18n.localize("statuseffects")+" "+w))}s&&(p=p*s,o.push(game.i18n.format("doubleDamage",{x:s})));for(let h of n)p=p*h.val;e.armorPen=c,e.damagedescription=o.join(", "),e.damage=Math.round(p),e.damageRoll=duplicate(d)}static async rollWeapon(l){let e=l.roll||await new Roll("1d20").evaluate({async:!0}),t,a=l.source,s=a.system.combatskill.value,i=T._calculateCombatSkillValues(l.extra.actor.items.find(c=>c.type=="combatskill"&&c.name==s),l.extra.actor.system),r=a.type=="meleeweapon";r?(t=T._prepareMeleeWeapon(a,[i],l.extra.actor),l.mode=="attack"&&this._appendSituationalModifiers(l,game.i18n.localize("opposingWeaponSize"),this._compareWeaponReach(t,l))):t=T._prepareRangeWeapon(a,[],[i],l.extra.actor);let n=await this._rollSingleD20(e,t[l.mode],l.mode,await this._situationalModifiers(l),l,s,this._situationalMultipliers(l));await this.detailedWeaponResult(n,l,a),l.mode=="attack"&&n.successLevel>0&&!l.extra.counterAttack&&await _DiceDSA5.evaluateDamage(l,n,t,!r,n.doubleDamage),l.extra.counterAttack&&(f.getSpeaker(l.extra.speaker).addCondition("stunned"),n.description+=", "+f.replaceConditions(game.i18n.localize("stunnedByCounterAttack"))),n.rollType="weapon";let o=_DiceDSA5.parseEffect(t);return o&&(n.parsedEffect=o),n}static async detailedWeaponResult(l,e,t){let a=e.mode=="attack"&&!e.extra.counterAttack,s=t.type=="meleeweapon"||getProperty(t,"system.traitType.value")=="meleeAttack";switch(l.successLevel){case 3:a?(await U.tableEnabledFor("criticalAttack")?l.description+=U.rollCritBotchButton("criticalAttack",!1,e):(l.description+=U.defaultAttackCrit(!0),l.doubleDamage=2),l.halfDefense=!0):e.isRangeDefense&&await U.tableEnabledFor("criticalRangeDefense")?l.description+=U.rollCritBotchButton("criticalRangeDefense",!1,e):await U.tableEnabledFor("criticalMeleeDefense")?l.description+=U.rollCritBotchButton("criticalMeleeDefense",!1,e):l.description+=U.defaultParryCrit();break;case-3:let i=getProperty(t,"system.combatskill.value")==game.i18n.localize("LocalizedIDs.wrestle")||t.type=="trait";a&&s&&await U.tableEnabledFor("Melee")?l.description+=U.rollCritBotchButton("Melee",i,e):a&&await U.tableEnabledFor("Range")?l.description+=U.rollCritBotchButton("Range",!1,e):!a&&await U.tableEnabledFor("Defense")?l.description+=U.rollCritBotchButton("Defense",i,e):l.description+=await U.defaultBotch();break;case 2:a&&(l.description+=U.defaultAttackCrit(!1),l.halfDefense=!0);break;case-2:break}}static async _addRollDiceSoNice(l,e,t){if(l.rollMode){for(let a=0;a{new ee({title:game.i18n.localize(t.cheat?"DIALOG.cheat":"DSASETTINGS.allowPhysicalDice"),content:r,default:"ok",buttons:{ok:{icon:'',label:game.i18n.localize("yes"),callback:c=>{n([!0,c])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{n([!1,0])}}}}).render(!0)}),a){let n=[];s.find(".dieInput").each(function(o){let c=Number($(this).val());c>0&&n.push({val:c,index:o}),o++}),l.editRollAtIndex(n)}}return l}static parseEffect(l){let e=l.system.effect?l.system.effect.value:void 0,t=[];if(e){let s=/^[a-z]+\|[öäüÖÄÜa-zA-z ]+$/;for(let i of e.split(";"))if(s.test(i.trim())){let r=i.split("|").map(n=>n.trim());if(r[0]=="condition"){let n=CONFIG.statusEffects.find(o=>o.id==r[1]);t.push(` - ${game.i18n.localize(n.name)} - `)}else t.push(`${game.i18n.localize(r[0])}: ${r[1]}`)}}let a=getProperty(l,"flags.dsa5.poison");return a&&t.push(`${game.i18n.localize("poison")}: ${a.name}`),t.join(", ")}static async calculateEnergyCost(l,e,t){let a=[],s,i,r,n;if(e.successLevel<0){let o=["traditionWitch","traditionFjarning","braniborian"].map(m=>game.i18n.localize(`LocalizedIDs.${m}`)),c=t.extra.actor.items.some(m=>m.type=="specialability"&&o.includes(m.name))?3:2;e.preData.calculatedSpellModifiers.finalcost=Math.round(e.preData.calculatedSpellModifiers.finalcost/c)}if(l?(n="KaPCost",s=game.i18n.localize("LocalizedIDs.weakKarmicBody"),i=game.i18n.localize(`LocalizedIDs.${e.successLevel>0?"mightyKarmaControl":"karmaControl"}`),r={val:"kapModifier",name:"KaP"}):(n="AsPCost",s=game.i18n.localize("LocalizedIDs.weakAstralBody"),i=game.i18n.localize(`LocalizedIDs.${e.successLevel>0?"energyControl":"smallEnergyControl"}`),r={val:"aspModifier",name:"AsP"}),a.push({name:s,value:O.vantageStep(t.extra.actor,s)},{name:i,value:R.abilityStep(t.extra.actor,i)*-1},{name:`${game.i18n.localize("statuseffects")} (${game.i18n.localize("CHARAbbrev."+r.name)})`,value:t.extra.actor.system[r.val]+await this._situationalModifiers(t,n)}),a=a.filter(o=>o.value!=0),e.preData.calculatedSpellModifiers.description=a.map(o=>`${o.name} ${o.value}`).join(` -`),e.preData.calculatedSpellModifiers.finalcost=Math.max(1,Number(e.preData.calculatedSpellModifiers.finalcost)+a.reduce((o,c)=>o+c.value,0)),e.successLevel>0&&e.preData.calculatedSpellModifiers.maintainCost!=0){let o=e.preData.calculatedSpellModifiers.maintainCost.split(" ");o[0]=Math.round(Number(o[0])),e.preData.calculatedSpellModifiers.finalcost+=o[0],e.preData.calculatedSpellModifiers.maintainCost=o.join(" ")}}static async rollSpell(l){let e=await this._rollThreeD20(l),t=["ceremony","liturgy"].includes(l.source.type);if(e.rollType=l.source.type,e.preData.calculatedSpellModifiers.finalcost=e.preData.calculatedSpellModifiers.cost,e.successLevel>=2){let a=(await new Roll("1d6").evaluate({async:!0})).total;e.description=e.description+", "+game.i18n.localize("additionalFPs")+" "+a,e.result+=a,e.qualityStep=Math.min(game.settings.get("dsa5","capQSat"),Math.ceil(e.result/3)),e.preData.calculatedSpellModifiers.finalcost=Math.round(e.preData.calculatedSpellModifiers.cost/2)}else e.successLevel<=-2&&(e.description+=U.rollCritBotchButton(t?"Liturgy":"Spell",!1,l));if(e.successLevel>0&&l.source.system.effectFormula.value!=""){let a=l.source.system.effectFormula.value.replace(game.i18n.localize("CHARAbbrev.QS"),e.qualityStep).replace(/[Ww]/g,"d"),s=[];for(let o of l.situationalModifiers)o.armorPen&&s.push(o.armorPen);/(,|;)/.test(a)&&(a=a.split(/[,;]/)[e.qualityStep-1]);let i=l.damageRoll?l.damageRoll:await _DiceDSA5.manualRolls(await new Roll(a).evaluate({async:!0}),"CHAR.DAMAGE",l.extra.options);this._addRollDiceSoNice(l,i,game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration("damage")),e.calculatedEffectFormula=a;for(let o of i.terms)if(o instanceof Die||o.class=="Die")for(let c of o.results)e.characteristics.push({char:"effect",res:c.result,die:"d"+o.faces});let r=[],n=await _DiceDSA5._stringToRoll(l.extra.actor.system[t?"liturgyStats":"spellStats"].damage,l);n!=0&&r.push(game.i18n.localize("statuseffects")+" "+n),e.armorPen=s,e.damageRoll=i,e.damage=i.total+n,e.damagedescription=r.join(` -`)}await this.calculateEnergyCost(t,e,l);for(let a of["minorFairies","minorSpirits"]){let s=game.i18n.localize("CONDITION."+a);O.hasVantage(l.extra.actor,s)&&!l.extra.actor.effects.find(i=>i.name==s)&&(await new Roll("1d20").evaluate({async:!0})).total<=e.preData.calculatedSpellModifiers.finalcost&&(e.description+=", "+game.i18n.format("minorghostsappear",{creature:s}),f.getSpeaker(l.extra.speaker).addCondition(a))}return e}static async _rollThreeD20(l){let e=l.roll?Roll.fromData(l.roll):await new Roll("1d20+1d20+1d20").evaluate({async:!0}),t=[],a=0;this._appendSituationalModifiers(l,game.i18n.localize("Difficulty"),l.testDifficulty);let s=await this._situationalModifiers(l),i=l.source.system.talentValue.value+l.advancedModifiers.fws+await this._situationalModifiers(l,"FW"),r=this._situationalPartCheckModifiers(l,"TPM"),n=[1,2,3].map(g=>l.extra.actor.system.characteristics[l.source.system[`characteristic${g}`].value].value+s+l.advancedModifiers.chars[g-1]+r[g-1]),o=[0,1,2].map(g=>e.terms[g*2].results[0].result-n[g]);if(l.routine)i=Math.round(i/2);else for(let g of o)g>0&&(i-=g);let c=l.extra.actor.system.skillModifiers.crit,m=l.extra.actor.system.skillModifiers.botch;if(["spell","ritual"].includes(l.source.type)&&O.hasVantage(l.extra.actor,game.i18n.localize("LocalizedIDs.wildMagic"))&&(m=19),l.source.type=="skill"&&O.hasVantage(l.extra.actor,`${game.i18n.localize("LocalizedIDs.incompetent")} (${l.source.name})`)){let g=await new Roll("1d20").evaluate({async:!0}),y=o.reduce((w,x,v,S)=>x0&&(i+=await this._situationalModifiers(l,"FP"),p=Math.max(1,(i==0?1:i>0?Math.ceil(i/3):0)+(l.qualityStep!=null?Number(l.qualityStep):0))+(l.advancedModifiers.qls||0)+await this._situationalModifiers(l,"QL")),p=Math.min(game.settings.get("dsa5","capQSat"),p),p({char:l.source.system[`characteristic${g+1}`].value,res:e.terms[g*2].results[0].result,suc:o[g]<=0,tar:n[g]})),qualityStep:p,description:t,preData:l,successLevel:a,modifiers:s,extra:{}}}static async rollTalent(l){let e=await this._rollThreeD20(l);return e.rollType="talent",e}static get3D20SuccessLevel(l,e,t=20,a=1){let s=l.terms.filter(r=>r.results&&r.results[0].result<=a).length,i=l.terms.filter(r=>r.results&&r.results[0].result>=t).length;return s>=2?s:i>=2?i*-1:e>=0?1:-1}static getSuccessDescription(l){return game.i18n.localize(["AstoundingFailure","CriticalFailure","Failure","","Success","CriticalSuccess","AstoundingSuccess"][l+3])}static async rollItem(l){let e=l.roll||await new Roll("1d20+1d20+1d20").evaluate({async:!0}),t=[],a=await this._situationalModifiers(l),s=Number(l.source.system.step.value),i=[1,2,3].map(m=>10+Number(l.source.system.step.value)+a),r=[0,1,2].map(m=>e.terms[m*2].results[0].result-i[m]);for(let m of r)m>0&&(s-=m);let n=20,o=_DiceDSA5.get3D20SuccessLevel(e,s,n);t.push(_DiceDSA5.getSuccessDescription(o)),t=t.join(", ");let c={result:s,characteristics:[0,1,2].map(m=>({char:l.source.type,res:e.terms[m*2].results[0].result,suc:r[m]<=0,tar:i[m]})),qualityStep:Math.min(game.settings.get("dsa5","capQSat"),(s==0?1:s>0?Math.ceil(s/3):0)+(l.qualityStep!=null?Number(l.qualityStep):0)),description:t,preData:l,successLevel:o,modifiers:a,extra:{}};switch(l.source.type){case"poison":let m=l.source.system.duration.value.split(" / ").map(y=>y.trim()),d=l.source.system.effect.value.split(" / ").map(y=>y.trim());c.duration=m.length>1?c.successLevel>0?m[0]:m[1]:m[0],c.effect=d.length>1?c.successLevel>0?d[0]:d[1]:d[0];break;case"disease":let p=l.source.system.damage.value.split(" / ").map(y=>y.trim()),g=l.source.system.duration.value.split(" / ").map(y=>y.trim());c.damageeffect=p.length>1?c.successLevel>0?p[0]:p[1]:p[0],c.duration=g.length>1?c.successLevel>0?g[0]:g[1]:g[0];break}return c}static async updateDefenseCount(l){game.combat&&await game.combat.updateDefenseCount(l.extra.speaker)}static _compareWeaponReach(l,e){let t=e.situationalModifiers.find(i=>i.name==game.i18n.localize("LocalizedIDs.circumvent")),a=b.meleeRangesArray.indexOf(l.system.reach.value),s=b.meleeRangesArray.indexOf(e.opposingWeaponSize);return t&&s>a&&(t.value=Math.min(t.step,s-a)*2),Math.min(0,a-s)*2}static async showDiceSoNice(l,e){if(f.moduleEnabled("dice-so-nice")&&game.dice3d){let t=null,a=!1;switch(e){case"blindroll":a=!0,t=game.users.filter(i=>i.isGM).map(i=>i.id);break;case"gmroll":t=game.users.filter(i=>i.isGM).map(i=>i.id);break;case"selfroll":t=[];break}let s=game.dice3d.showForRoll(l,game.user,!0,t,a);game.settings.get("dice-so-nice","immediatelyDisplayChatMessages")||await s}}static addApplyEffectData(l){let e=l.preData.source;if(l.successLevel>0){if(["meleeweapon","rangeweapon"].includes(e.type)||e.type=="trait"&&["rangeAttack","meleeAttack"].includes(e.system.traitType.value)){if(e.effects.some(a=>!getProperty(a,"flags.dsa5.applyToOwner")))return!0}else if(["spell","liturgy","ritual","ceremony","trait","skill"].includes(e.type)&&e.effects.length>0)return!0}else if(["disease","poison"].includes(e.type))return e.effects.length>0;let t=l.preData.situationalModifiers.filter(a=>a.specAbId).map(a=>a.specAbId);if(t.length>0){let a=l.preData.extra.actor.items.filter(s=>t.includes(s._id));for(let s of a)if(s.effects.length>0)return!0}return!1}static async renderRollCard(chatOptions,testData,rerenderMessage){let applyEffect=this.addApplyEffectData(testData),immuneTo=I.checkImmunity(testData),preData=deepClone(testData.preData),hideDamage=rerenderMessage?rerenderMessage.flags.data.hideDamage:preData.mode=="attack";await Ue.postRoll({testData,preData}),Hooks.call("postProcessDSARoll",chatOptions,testData,rerenderMessage,hideDamage),await f.callAsyncHooks("postProcessDSARoll",[testData]),delete preData.extra.actor,delete testData.actor,delete testData.preData;let hasAreaTemplate=testData.successLevel>0&&preData.source.system.target&&preData.source.system.target.type in game.dsa5.config.areaTargetTypes,chatData={title:chatOptions.title,immuneTo,testData,hideData:game.user.isGM,preData,hideDamage,modifierList:preData.situationalModifiers.filter(l=>l.value!=0),applyEffect,hasAreaTemplate,showDamageToGear:await W.showDamageToGear(preData,testData)};if(preData.advancedModifiers&&(preData.advancedModifiers.chars.some(l=>l!=0)&&chatData.modifierList.push({name:game.i18n.localize("MODS.partChecks"),value:preData.advancedModifiers.chars}),preData.advancedModifiers.fws!=0&&chatData.modifierList.push({name:game.i18n.localize("MODS.FW"),value:preData.advancedModifiers.fws}),preData.advancedModifiers.qls!=0&&chatData.modifierList.push({name:game.i18n.localize("MODS.QS"),value:preData.advancedModifiers.qls})),["gmroll","blindroll"].includes(chatOptions.rollMode)&&(chatOptions.whisper=game.users.filter(l=>l.isGM).map(l=>l.id)),chatOptions.rollMode==="blindroll"?chatOptions.blind=!0:chatOptions.rollMode==="selfroll"&&(chatOptions.whisper=[game.user.id]),K.playEffect(preData.mode,preData.source,testData.successLevel,chatOptions.whisper,chatOptions.blind),chatOptions["flags.data"]={preData,postData:testData,template:chatOptions.template,rollMode:chatOptions.rollMode,isOpposedTest:chatOptions.isOpposedTest,title:chatOptions.title,hideData:chatData.hideData,hideDamage:chatData.hideDamage,isDSARoll:!0},rerenderMessage){let postFunction=getProperty(rerenderMessage,"flags.data.preData.extra.options.postFunction");postFunction&&(testData.messageId=rerenderMessage.id,await eval(postFunction.functionName)(postFunction,{result:testData,chatData},preData.source));let html=await renderTemplate(chatOptions.template,chatData),actor=ChatMessage.getSpeakerActor(rerenderMessage.speaker)||game.users.get(rerenderMessage.user).character,rollData=actor?actor.getRollData():{},enriched=await TextEditor.enrichHTML(html,{rollData,async:!0});chatOptions.content=enriched;let newMsg=await rerenderMessage.update({content:chatOptions.content,["flags.data"]:chatOptions["flags.data"]});return ui.chat.updateMessage(newMsg),newMsg}else return chatOptions.content=await renderTemplate(chatOptions.template,chatData),await ChatMessage.create(chatOptions,!1)}static async _itemRoll(l){let e=$(l.currentTarget),t=e.parents(".message").attr("data-message-id"),a=game.messages.get(t),s=a.speaker,i=e.attr("data-type"),r=e.attr("data-name"),n=f.getSpeaker(s);if(n){let o=n.items.find(c=>c.name==r&&c.type==i);if(o){let c=new A(o.toObject(),{temporary:!0}),m=e.attr("data-removecharge")?e.attr("data-removecharge")=="true":!1;if(m&&c.system.quantity.value<1){ui.notifications.error(game.i18n.localize("DSAError.NotEnoughCharges"));return}c.setupEffect().then(async d=>{await c.itemTest(d),m&&await o.update({"system.quantity.value":o.system.quantity.value-1})})}else ui.notifications.error(game.i18n.format("DSAError.notFound",{category:i,name:r}))}}static async _rollEdit(l){let e=$(l.currentTarget),t=e.parents(".message").attr("data-message-id"),a=game.messages.get(t),s=a.flags.data,i=s.preData;i.extra.actor=f.getSpeaker(i.extra.speaker).toObject(!1),i.extra.options.cheat&&delete i.extra.options.cheat;let r;switch(e.attr("data-edit-type")){case"roll":r=e.attr("data-edit-id");let o=Number(e.val());if(i.roll.terms.length>r*2){let m=Roll.fromData(i.roll);m.editRollAtIndex([{index:r,val:o}]),i.roll=m}else{let m=Roll.fromData(s.postData.damageRoll);r=r-i.roll.terms.filter(d=>d.results).length,m.editRollAtIndex([{index:r,val:o}]),i.damageRoll=m}break;case"mod":r=i.situationalModifiers.findIndex(m=>m.name==game.i18n.localize("chatEdit")),r>0&&i.situationalModifiers.splice(r,1);let c={name:game.i18n.localize("chatEdit"),value:Number(e.val())-await this._situationalModifiers(i)};i.situationalModifiers.push(c);break}let n={template:s.template,rollMode:s.rollMode,title:s.title,speaker:a.speaker,user:a.user.id};["gmroll","blindroll"].includes(n.rollMode)&&(n.whisper=game.users.filter(o=>o.isGM).map(o=>o.id)),n.rollMode==="blindroll"&&(n.blind=!0),["poison","disease"].includes(i.source.type)?new A(i.source,{temporary:!0})[`${s.postData.postFunction}`]({testData:i,cardOptions:n},{rerenderMessage:a}):f.getSpeaker(a.speaker)[`${s.postData.postFunction}`]({testData:i,cardOptions:n},{rerenderMessage:a})}static async gearDamaged(l){let e=l.currentTarget.dataset.uuid.split(";");if(e.length>1){let t=await Promise.all(e.map(a=>fromUuid(a)));Ve.showDialog(t)}else W.breakingTest(await fromUuid(e[0]))}static async rollResistPain(l){let e=l.currentTarget.dataset,t={token:e.token,actor:e.actor,scene:canvas.id},a=f.getSpeaker(t);a&&a.finishResistPainRoll()}static async wrapLock(l,e){let t=$(l.currentTarget);t.hasClass("locked")||(t.addClass("locked"),t.prepend(''),await e(l,t),setTimeout(()=>{t.removeClass("locked"),t.find("i").remove()},2e3))}static async chatListeners(l){l.on("click",".expand-mods",e=>{e.preventDefault();let t=$(e.currentTarget);t.find("i").toggleClass("fa-minus fa-plus"),t.siblings("ul,div").fadeToggle()}),l.on("click",".edit-toggle",e=>{e.preventDefault(),$(e.currentTarget).parents(".chat-card").find(".display-toggle").toggle()}),l.on("click",".botch-roll",e=>U.showBotchCard(e.currentTarget.dataset)),l.on("click",".roll-item",e=>_DiceDSA5._itemRoll(e)),l.on("click",".gearDamaged",async e=>_DiceDSA5.gearDamaged(e)),l.on("click",".applyDamage",async e=>Ct($(e.currentTarget).closest(".message"),e.currentTarget.dataset.mode)),l.on("change",".roll-edit",e=>_DiceDSA5._rollEdit(e)),l.on("click",".applyEffect",async e=>{_DiceDSA5.wrapLock(e,async(t,a)=>{let s=a.parents(".message").attr("data-message-id"),i=t.currentTarget.dataset.target;await Q.applyEffect(s,i)})}),l.on("click",".applyTableEffect",async e=>{_DiceDSA5.wrapLock(e,async(t,a)=>{let s=a.parents(".message").attr("data-message-id"),i=t.currentTarget.dataset.target;await Ke.applyEffect(s,i)})}),l.on("click",".placeTemplate",async e=>dt.placeTemplateFromChat(e)),l.on("click",".message-delete",e=>{let t=game.messages.get($(e.currentTarget).parents(".message").attr("data-message-id"));if(!t.flags.unopposeData)return;let s=canvas.tokens.get(t.flags.unopposeData.targetSpeaker.token);j.clearOpposed(s.actor)}),l.on("click",".resistEffect",e=>Q.resistEffect(e)),l.on("click",".resistPain",e=>_DiceDSA5.rollResistPain(e)),q.chatListeners(l)}};u(_DiceDSA5,"DiceDSA5");var T=class extends Actor{static async create(e,t){if(e instanceof Array||e.items)return await super.create(e,t);(!e.img||e.img=="icons/svg/mystery-man.svg")&&(e.img="icons/svg/mystery-man-black.svg");let a=await f.allSkills()||[],s=await f.allCombatSkills()||[],i=await f.allMoneyItems()||[];return e.items=[...a,...s,...i],e.type!="character"&&(e.system={status:{fatePoints:{current:0,value:0}}}),e.type!="creature"&&[void 0,0].includes(getProperty(e,"system.status.wounds.value"))&&mergeObject(e,{system:{status:{wounds:{value:16}}}}),await super.create(e,t)}_getArmorCompensation(e,t,a){let s=R.abilityStep(e,game.i18n.localize("LocalizedIDs.inuredToEncumbrance")),i=t.reduce((r,n)=>r+=Number(n.system.encumbrance.value),0);if(s>i){let r=[game.i18n.localize("CHARAbbrev.GS"),game.i18n.localize("CHARAbbrev.INI")];for(let n of r)!a[n]||(a[n]=a[n].filter(o=>o.type!="armor"))}}_getItemModifiers(){let e=[],t={};for(let a of this.items.filter(s=>["meleeweapon","rangeweapon","armor","equipment"].includes(s.type)&&getProperty(s,"system.worn.value")||["advantage","specialability","disadvantage"].includes(s.type)))this._buildGearAndAbilityModifiers(t,a),a.type=="armor"&&e.push(a);this._getArmorCompensation(this,e,t),this._applyModiferTransformations(t)}prepareDerivedData(){var t,a,s,i;let e=this.system;try{this._getItemModifiers();for(let h of Object.values(e.characteristics))h.value=h.initial+h.advances+(h.modifier||0)+h.gearmodifier;e.totalWeight=0;let r=[],n=game.i18n.localize("LocalizedIDs.familiar"),o=game.i18n.localize("LocalizedIDs.companion"),c=new Map,m=this.items.filter(h=>h.type=="equipment"&&h.system.equipmentType.value=="bags");for(let h of m)c.set(h.id,[]);for(let h of this.items)if(b.equipmentCategories.has(h.type)){let w=getProperty(h,"system.parent_id");if(w&&w!=h._id&&c.has(w)){c.get(w).push(h);continue}h.type=="armor"?(h.system.preparedWeight=parseFloat((h.system.weight.value*h.system.quantity.value).toFixed(3)),e.totalWeight+=parseFloat((h.system.weight.value*(h.system.worn.value?Math.max(0,h.system.quantity.value-1):h.system.quantity.value)).toFixed(3)),h.system.worn.value&&r.push(h)):(h.system.preparedWeight=parseFloat((h.system.weight.value*h.system.quantity.value).toFixed(3)),e.totalWeight+=Number(h.system.preparedWeight))}else switch(h.type){case"trait":h.name==n&&(e.isFamiliar=!0),h.name==o&&(e.isPet=!0);break;case"spell":case"ritual":case"magictrick":e.isMage=!0;break;case"liturgy":case"ceremony":case"blessing":e.isPriest=!0;break;case"specialability":b.sortedSpecs.magical.has(h.system.category.value)?e.isMage=!0:b.sortedSpecs.clerical.has(h.system.category.value)&&(e.isPriest=!0);break}e.isMage||(e.isMage=e.isFamiliar);for(let h of m){let w=getProperty(h,"system.parent_id");(!w||!c.has(w))&&(e.totalWeight+=this._calcBagweight(h,c,!0))}e.canAdvance=this.isOwner&&(this.type=="character"||e.isFamiliar||e.isPet),this.canAdvance=e.canAdvance,e.carrycapacity=e.characteristics.kk.value*2+e.carryModifier,e.canAdvance&&(e.details.experience.current=e.details.experience.total-e.details.experience.spent,e.details.experience.description=f.experienceDescription(e.details.experience.total)),(this.type=="character"||this.type=="npc")&&(e.status.wounds.current=e.status.wounds.initial+e.characteristics.ko.value*2,e.status.soulpower.value=(e.status.soulpower.initial||0)+Math.round((e.characteristics.mu.value+e.characteristics.kl.value+e.characteristics.in.value)/6),e.status.toughness.value=(e.status.toughness.initial||0)+Math.round((e.characteristics.ko.value+e.characteristics.ko.value+e.characteristics.kk.value)/6),e.status.wounds.min=-1*e.characteristics.ko.value),e.status.fatePoints.max=Number(e.status.fatePoints.current)+Number(e.status.fatePoints.modifier)+e.status.fatePoints.gearmodifier,this.type=="creature"&&(e.status.wounds.current=e.status.wounds.initial,e.status.astralenergy.current=e.status.astralenergy.initial,e.status.karmaenergy.current=e.status.karmaenergy.initial),e.status.wounds.max=Math.round((e.status.wounds.current+e.status.wounds.modifier+e.status.wounds.advances)*e.status.wounds.multiplier+e.status.wounds.gearmodifier),e.status.regeneration.LePmax=e.status.regeneration.LePTemp+e.status.regeneration.LePMod+e.status.regeneration.LePgearmodifier,e.status.regeneration.KaPmax=e.status.regeneration.KaPTemp+e.status.regeneration.KaPMod+e.status.regeneration.KaPgearmodifier,e.status.regeneration.AsPmax=e.status.regeneration.AsPTemp+e.status.regeneration.AsPMod+e.status.regeneration.AsPgearmodifier;let d=e.guidevalue;(t=e.status.astralenergy).rebuy||(t.rebuy=0),(a=e.status.karmaenergy).rebuy||(a.rebuy=0),(s=e.status.astralenergy).permanentLoss||(s.permanentLoss=0),(i=e.status.karmaenergy).permanentLoss||(i.permanentLoss=0),e.status.astralenergy.permanentLossSum=e.status.astralenergy.permanentLoss-e.status.astralenergy.rebuy+e.status.astralenergy.permanentGear,e.status.karmaenergy.permanentLossSum=e.status.karmaenergy.permanentLoss-e.status.karmaenergy.rebuy+e.status.karmaenergy.permanentGear,(e.isFamiliar||d&&this.type!="creature")&&(e.status.astralenergy.current=e.status.astralenergy.initial,e.status.karmaenergy.current=e.status.karmaenergy.initial,e.characteristics[d.magical]&&(e.status.astralenergy.current+=Math.round(e.characteristics[d.magical].value*e.energyfactor.magical)),e.characteristics[d.clerical]&&(e.status.karmaenergy.current+=Math.round(e.characteristics[d.clerical].value*e.energyfactor.clerical))),e.status.astralenergy.max=e.status.astralenergy.current+e.status.astralenergy.modifier+e.status.astralenergy.advances+e.status.astralenergy.gearmodifier-e.status.astralenergy.permanentLossSum,e.status.karmaenergy.max=e.status.karmaenergy.current+e.status.karmaenergy.modifier+e.status.karmaenergy.advances+e.status.karmaenergy.gearmodifier-e.status.karmaenergy.permanentLossSum,e.status.soulpower.max=e.status.soulpower.value+e.status.soulpower.modifier+e.status.soulpower.gearmodifier,e.status.toughness.max=e.status.toughness.value+e.status.toughness.modifier+e.status.toughness.gearmodifier,e.status.dodge.value=Math.round(e.characteristics.ge.value/2)+e.status.dodge.gearmodifier;let p=this.calcEncumbrance(e),g=H.isRiding(this)?H.getHorse(this):void 0;this.calcInitiative(e,p,g),e.status.dodge.max=Number(e.status.dodge.value)+Number(e.status.dodge.modifier)+Number(game.settings.get("dsa5","higherDefense"))/2,e.armorEncumbrance=this.getArmorEncumbrance(this,r),this.prepareSwarm(e),this.effectivePain(e);let y=this.statuses.has("fixated");this.calcSpeed(e,y,g),y&&(e.status.dodge.max=Math.max(0,e.status.dodge.max-4))}catch(r){console.error(`Something went wrong with preparing actor data ${this.name}: `+r+r.stack),ui.notifications.error(game.i18n.format("DSAError.PreparationError",{name:this.name})+r+r.stack)}}static async deferredEffectAddition(e,t,a){let i=(t.effects.find(n=>n.statuses.has(e))?.flags.dsa5.auto||0)!=a,r=`changing${e}`;t[r]=i,i&&await t.addCondition(e,a,!0).then(()=>t[r]=void 0)}static async postUpdateConditions(e){let t=e.system,a=e.isMerchant();if(!ue.hasTrait(e,game.i18n.localize("LocalizedIDs.painImmunity"))){let r=e.woundPain(t);await this.deferredEffectAddition("inpain",e,r)}let s=t.armorEncumbrance;(e.type!="creature"||e.canAdvance)&&!a&&(s+=Math.max(0,Math.ceil((t.totalWeight-t.carrycapacity-4)/4))),await this.deferredEffectAddition("encumbered",e,s);let i=e.woundPain(t,"temporaryLeP");await this.deferredEffectAddition("stunned",e,i),O.hasVantage(e,game.i18n.localize("LocalizedIDs.blind"))&&await e.addCondition("blind"),O.hasVantage(e,game.i18n.localize("LocalizedIDs.mute"))&&await e.addCondition("mute"),O.hasVantage(e,game.i18n.localize("LocalizedIDs.deaf"))&&await e.addCondition("deaf"),a&&await e.prepareMerchant()}static async _onCreateDocuments(e,t){for(let a of e)await T.postUpdateConditions(a);return super._onCreateDocuments(e,t)}static async _onUpdateDocuments(e,t){for(let a of e)await T.postUpdateConditions(a);return super._onUpdateDocuments(e,t)}prepareSwarm(e){let t=Number(e.swarm.count)||1;if(t<2)return;e.swarm.maxwounds=e.status.wounds.max,e.status.wounds.max*=t;let a=Math.min(Math.ceil(e.status.wounds.value/e.swarm.maxwounds),t),s=Number(e.swarm.gg)||1;e.swarm.attack+=Math.min(10,Math.floor(a/s)),e.swarm.parry+=-1,e.swarm.effectiveCount=a,e.swarm.damage=Math.min(5,Math.floor(a/s))}effectivePain(e){let t=e.condition.inpain||0;t<4&&(t-=O.vantageStep(this,game.i18n.localize("LocalizedIDs.ruggedFighter"))+O.vantageStep(this,game.i18n.localize("LocalizedIDs.ruggedAnimal"))+(R.hasAbility(this,game.i18n.localize("LocalizedIDs.traditionKor"))?1:0)),t>0&&(t+=O.vantageStep(this,game.i18n.localize("LocalizedIDs.sensitiveToPain"))+O.vantageStep(this,game.i18n.localize("LocalizedIDs.fragileAnimal"))),t=Math.clamped(t,0,4),e.condition.inpain=t}woundPain(e,t="wounds"){let a=0;return e.status[t].max>0&&(this.type!="creature"||e.status[t].max>=20?(a=Math.floor((1-e.status[t].value/e.status[t].max)*4),e.status[t].value<=5&&(a=4)):a=Math.floor(5-5*e.status[t].value/e.status[t].max)),Math.clamped(a,0,4)}calcSpeed(e,t,a){if(a){if(e.status.speed.max=a.system.status.speed.max,!e.status.speed.max){let s=a.system;a.calcSpeed(s,a.hasCondition("fixated"))}e.status.speed.max=a.system.status.speed.max}else{e.status.speed.max=e.status.speed.initial+(e.status.speed.modifier||0)+(e.status.speed.gearmodifier||0),e.status.speed.max=Math.round(Math.max(0,e.status.speed.max-Math.min(4,this.calcEncumbrance(e)))*e.status.speed.multiplier),this.hasCondition("bloodrush")||(e.status.speed.max=Math.max(0,e.status.speed.max-(e.condition?.inpain||0)));let s=this.hasCondition("paralysed");s&&(e.status.speed.max=Math.round(e.status.speed.max*(1-s.flags.dsa5.value*.25))),t||this.hasCondition("rooted")||this.hasCondition("incapacitated")?e.status.speed.max=0:this.hasCondition("prone")&&(e.status.speed.max=Math.min(1,e.status.speed.max)),H.updateRiderSpeed(this,e.status.speed.max)}}calcEncumbrance(e){return Math.clamped(e.condition?.encumbered||0,0,4)}calcInitiative(e,t,a){if(this.type=="character"||this.type=="npc"?e.status.initiative.value=Math.round((e.characteristics.mu.value+e.characteristics.ge.value)/2)+(e.status.initiative.modifier||0):e.status.initiative.value=e.status.initiative.current+(e.status.initiative.modifier||0),a){if(e.status.initiative.value=a.system.status.initiative.value,!e.status.initiative.value){let s=a.system;a.calcInitiative(s,a.calcEncumbrance(s)),e.status.initiative.value=s.status.initiative.value}}else{e.status.initiative.value+=(e.status.initiative.gearmodifier||0)-Math.min(4,t);let s=Number((.01*e.status.initiative.value).toFixed(2));e.status.initiative.value*=e.status.initiative.multiplier||1,e.status.initiative.value=Math.round(e.status.initiative.value)+s}}get creatureType(){return I.creatureTypeName(this)}async prepareMerchant(){if(getProperty(this,"system.merchant.merchantType")=="loot"){if(getProperty(this,"system.merchant.locked")&&!this.hasCondition("locked"))await this.addCondition(T.lockedCondition());else if(!getProperty(this,"system.merchant.locked")){let e=this.effects.find(t=>t.statuses.has("locked"));e&&await this.deleteEmbeddedDocuments("ActiveEffect",[e.id])}}}static lockedCondition(){return{id:"locked",name:game.i18n.localize("MERCHANT.locked"),icon:"icons/svg/padlock.svg",flags:{dsa5:{noEffect:!0,hidePlayers:!0,description:game.i18n.localize("MERCHANT.locked")}}}}applyActiveEffects(){let e={};this.statuses??(this.statuses=new Set);let t=new Map;for(let o of Object.values(CONFIG.specialStatusEffects))t.set(o,this.statuses.has(o));this.statuses.clear();let a=[],s=1;for(let o of this.effects){if(o.disabled)continue;s=1;let c=o.getFlag("dsa5","value");c&&(s=Number(c));for(let m=0;m(d=foundry.utils.duplicate(d),d.effect=o,d.priority=d.priority?d.priority:d.mode*10,d)));for(let m of o.statuses)this.statuses.add(m)}let i=!0,r=this.items.filter(o=>["rangeweapon","meleeweapon","equipment","armor"].includes(o.type)&&o.system.isArtifact&&(o.system.worn.value||o.type=="equipment"&&!o.system.worn.wearable)).map(o=>o.system.artifact);this.dsatriggers={6:{},7:{}};for(let o of this.items)for(let c of o.effects)if(!c.disabled&&!!c.transfer){switch(i=!0,o.type){case"meleeweapon":case"rangeweapon":i=o.system.worn.value&&c.getFlag("dsa5","applyToOwner");break;case"armor":i=o.system.worn.value;break;case"equipment":i=!o.system.worn.wearable||o.system.worn.wearable&&o.system.worn.value;break;case"trait":i=!["meleeAttack","rangeAttack"].includes(o.system.traitType.value)||c.getFlag("dsa5","applyToOwner"),s=Number(getProperty(o.system,"step.value"))||1;break;case"ammunition":case"plant":case"consumable":case"combatskill":case"magicsign":case"poison":case"spell":case"liturgy":case"ceremony":case"ritual":case"skill":case"spellextension":i=!1;break;case"specialability":switch(o.system.category.value){case"Combat":i=[2,3].includes(Number(o.system.category.sub));break;case"staff":i=o.system.permanentEffects||r.includes(o.system.artifact);break;default:i=!0}s=Number(o.system.step.value)||1;let m=getProperty(c,"flags.dsa5.advancedFunction");this.dsatriggers.hasOwnProperty(m)&&(this.dsatriggers[m][o.id]=c.id);break;case"advantage":case"disadvantage":s=Number(o.system.step.value)||1;break}if(c.notApplicable=!i,!!i){for(let m=0;m(d=foundry.utils.duplicate(d),d.effect=c,d.priority=d.priority?d.priority:d.mode*10,d)));for(let m of c.statuses)this.statuses.add(m)}}a.sort((o,c)=>o.priority-c.priority);for(let o of a){if(!o.key)continue;let c=o.effect.apply(this,o);Object.assign(e,c)}this.overrides=foundry.utils.expandObject(e);let n;for(let[o,c]of t){let m=this.statuses.has(o);if(m!==c){n??(n=this.getActiveTokens());for(let d of n)d._onApplyStatusEffect(o,m)}}}_setOnUseEffect(e){getProperty(e,"flags.dsa5.onUseEffect")&&(e.OnUseEffect=!0)}_setAEPayments(e){if(e.OnUseEffect)return;Number(getProperty(e,"system.AsPCost"))&&(e.AEpayable=!0)}prepareBaseData(){let e=this.system;mergeObject(e,{itemModifiers:{},condition:{},swarm:{attack:0,parry:0,damage:0},creatureType:this.creatureType,skillModifiers:{FP:[],step:[],QL:[],TPM:[],FW:[],botch:20,crit:1,global:[],conditional:{AsPCost:[],KaPCost:[]},feature:{FP:[],step:[],QL:[],TPM:[],FW:[],KaPCost:[],AsPCost:[]},...["liturgy","ceremony","ritual","spell","skill"].reduce((t,a)=>(t[a]={FP:[],step:[],QL:[],TPM:[],FW:[]},t),{})},status:{initiative:{multiplier:1},astralenergy:{permanentGear:0},karmaenergy:{permanentGear:0},wounds:{multiplier:1},speed:{multiplier:1},regeneration:{LePgearmodifier:0,KaPgearmodifier:0,AsPgearmodifier:0}},repeatingEffects:{startOfRound:{wounds:[],karmaenergy:[],astralenergy:[]}},temperature:{heatProtection:0,coldProtection:0},totalArmor:0,spellArmor:0,liturgyArmor:0,carryModifier:0,aspModifier:0,kapModifier:0,immunities:[],creatureBonus:[],miracle:{attack:0,parry:0},spellStats:{damage:"0"},liturgyStats:{damage:"0"},meleeStats:{parry:0,attack:0,damage:"0",defenseMalus:0,botch:20,crit:1},rangeStats:{attack:0,damage:"0",defenseMalus:0,botch:20,crit:1}});for(let t of b.gearModifyableCalculatedAttributes)e.status[t]&&(e.status[t].gearmodifier=0);for(let t of Object.values(e.characteristics))t.gearmodifier=0}getSkillModifier(e,t){let a=[],s=["FP","step","QL","TPM","FW"];for(let i of s){let r=i=="step"?"":i;a.push(...this.system.skillModifiers[i].filter(n=>n.target==e).map(n=>({name:n.source,value:n.value,type:r}))),this.system.skillModifiers[t]&&a.push(...this.system.skillModifiers[t][i].map(n=>({name:n.source,value:n.value,type:r})))}return a}prepareSheet(e){let t={system:{characteristics:{}}};if(mergeObject(t,this.prepareItems(e)),t.canAdvance){let a=["wounds","astralenergy","karmaenergy"];for(let s of a)mergeObject(t.system,{status:{[s]:{cost:game.i18n.format("advancementCost",{cost:f._calculateAdvCost(this.system.status[s].advances,"D")}),refund:game.i18n.format("refundCost",{cost:f._calculateAdvCost(this.system.status[s].advances,"D",0)})}}});for(let[s,i]of Object.entries(this.system.characteristics))t.system.characteristics[s]={cost:game.i18n.format("advancementCost",{cost:f._calculateAdvCost(i.initial+i.advances,"E")}),refund:game.i18n.format("refundCost",{cost:f._calculateAdvCost(i.initial+i.advances,"E",0)})}}return t}static canAdvance(e){return e.canAdvance}static armorValue(e,t={}){let a=e.items.filter(r=>r.type=="armor"&&r.system.worn.value==!0);t.origin&&(a=a.map(r=>{let n=mergeObject(duplicate(t),{armor:r});return Q.applyRollTransformation(e,n,4).options.armor}));let s=a.reduce((r,n)=>r+W.armorWearModifier(n,n.system.protection.value),0),i=e.items.filter(r=>r.type=="trait"&&r.system.traitType.value=="armor").reduce((r,n)=>r+Number(n.system.at.value),0);return{wornArmor:a,armor:s+i+(e.system.totalArmor||0)}}static _calculateCombatSkillValues(e,t){if(e.system.weapontype.value=="melee"){let a=e.system.guidevalue.value.split("/").map(r=>Number(t.characteristics[r].initial)+Number(t.characteristics[r].modifier)+Number(t.characteristics[r].advances)+Number(t.characteristics[r].gearmodifier)),s=Math.max(...a);e.system.parry.value=Math.ceil(e.system.talentValue.value/2)+Math.max(0,Math.floor((s-8)/3))+Number(game.settings.get("dsa5","higherDefense"));let i=t.characteristics.mu.initial+t.characteristics.mu.modifier+t.characteristics.mu.advances+t.characteristics.mu.gearmodifier;e.system.attack.value=e.system.talentValue.value+Math.max(0,Math.floor((i-8)/3))}else{e.system.parry.value=0;let a=t.characteristics.ff.initial+t.characteristics.ff.modifier+t.characteristics.ff.advances+t.characteristics.ff.gearmodifier;e.system.attack.value=e.system.talentValue.value+Math.max(0,Math.floor((a-8)/3))}return e.cost=game.i18n.format("advancementCost",{cost:f._calculateAdvCost(e.system.talentValue.value,e.system.StF.value)}),e}_perpareItemAdvancementCost(e){return e.cost=game.i18n.format("advancementCost",{cost:f._calculateAdvCost(e.system.talentValue.value,e.system.StF.value)}),e.refund=game.i18n.format("refundCost",{cost:f._calculateAdvCost(e.system.talentValue.value,e.system.StF.value,0)}),e}async modifyTokenAttribute(e,t,a=!1,s=!0){let i=foundry.utils.getProperty(this.system,e),r;return s?(a&&(t=Math.clamped(i.min||0,Number(i.value)+t,i.max)),r={[`system.${e}.value`]:t}):(a&&(t=Number(i)+t),r={[`system.${e}`]:t}),Hooks.call("modifyTokenAttribute",{attribute:e,value:t,isDelta:a,isBar:s},r)!==!1?this.update(r):this}schipshtml(){let e=[];for(let t=1;t<=Number(this.system.status.fatePoints.max);t++)e.push({value:t,cssClass:t<=Number(this.system.status.fatePoints.value)?"fullSchip":"emptySchip"});return e}prepareItems(e){let t=this.toObject(!1),a=[],s=[],i=[],r=[],n=[],o=[],c=[],m=[],d=[],p=[],g=Object.fromEntries(Object.keys(b.specialAbilityCategories).map(k=>[k,[]])),y=Object.fromEntries(Object.keys(b.traitCategories).map(k=>[k,[]])),h=[],w=[],x=[],v=[],S={hasSpells:this.system.isMage,hasPrayers:this.system.isPriest,liturgy:[],spell:[],ritual:[],ceremony:[],blessing:[],magictrick:[],magicalsign:[]},z={spell:{},ritual:{},ceremony:{},liturgy:{}},F=this.hasPlayerOwner?P.getGroupSchips():[],N=this.schipshtml(),D={meleeweapons:{items:[],show:!1,dataType:"meleeweapon"},rangeweapons:{items:[],show:!1,dataType:"rangeweapon"},armor:{items:[],show:!1,dataType:"armor"},ammunition:{items:[],show:!1,dataType:"ammunition"},plant:{items:[],show:!1,dataType:"plant"},poison:{items:[],show:!1,dataType:"poison"}};for(let k in b.equipmentTypes)D[k]={items:[],show:!1,dataType:k};D.misc.show=!0;let C={coins:[],total:0,show:!0};t.items=t.items.sort((k,V)=>k.name.localeCompare(V.name));let G=t.system.totalArmor||0,Z={body:[],social:[],knowledge:[],trade:[],nature:[]},ke=new Map;for(let k of t.items.filter(V=>V.type=="equipment"&&V.system.equipmentType.value=="bags"))ke.set(k._id,[]);let we=new Map,rt=[],jt=!1,ft=t.items.some(k=>!["skill","combatskill","money"].includes(k.type)),ht=H.getHorse(this,!0);for(let k of t.items)try{let V=getProperty(k,"system.parent_id");if(k.type=="ammunition"&&rt.push(T._prepareitemStructure(k)),V&&V!=k._id&&ke.has(V)){ke.get(V).push(k);continue}switch(e.details&&e.details.includes(k._id)&&(k.detailed="shown"),k.system.isArtifact&&(k.volume=b.traditionArtifacts[k.system.artifact]||0,k.volumeFinal=0,v.push(k)),k.type){case"skill":Z[k.system.group.value].push(this._perpareItemAdvancementCost(k));break;case"information":m.push(k);break;case"aggregatedTest":r.push(k);break;case"spellextension":z[k.system.category][k.system.source]?z[k.system.category][k.system.source].push(k.name):z[k.system.category][k.system.source]=[k.name];break;case"ritual":case"spell":case"liturgy":case"ceremony":S[k.type].push(T.buildSpellChargeProgress(this._perpareItemAdvancementCost(k)));break;case"magicalsign":case"magictrick":case"blessing":S[k.type].push(k);break;case"trait":switch(k.system.traitType.value){case"rangeAttack":k=T._prepareRangeTrait(k);break;case"meleeAttack":k=T._prepareMeleetrait(k);break;case"armor":G+=Number(k.system.at.value);break}y[k.system.traitType.value].push(k),jt=!0;break;case"combatskill":a.push(T._calculateCombatSkillValues(k,this.system));break;case"ammunition":D.ammunition.items.push(T.prepareMag(k)),D.ammunition.show=!0;break;case"meleeweapon":k.toggleValue=k.system.worn.value||!1,k.toggle=!0,this._setOnUseEffect(k),D.meleeweapons.items.push(T._prepareitemStructure(k)),D.meleeweapons.show=!0,k.toggleValue&&c.push(k);break;case"rangeweapon":k.toggleValue=k.system.worn.value||!1,k.toggle=!0,this._setOnUseEffect(k),D.rangeweapons.items.push(T._prepareitemStructure(k)),D.rangeweapons.show=!0;break;case"armor":k.toggleValue=k.system.worn.value||!1,D.armor.items.push(T._prepareitemStructure(k)),D.armor.show=!0,k.toggle=!0,this._setOnUseEffect(k),k.system.worn.value&&(k.system.protection.value=W.armorWearModifier(k,k.system.protection.value),G+=Number(k.system.protection.value),h.push(k));break;case"poison":case"plant":D[k.type].items.push(k),D[k.type].show=!0;break;case"consumable":D[k.system.equipmentType.value].items.push(T._prepareConsumable(k)),D[k.system.equipmentType.value].show=!0;break;case"equipment":k.toggle=getProperty(k,"system.worn.wearable")||!1,k.toggle&&(k.toggleValue=k.system.worn.value||!1),this._setOnUseEffect(k),D[k.system.equipmentType.value].items.push(T._prepareitemStructure(k)),D[k.system.equipmentType.value].show=!0;break;case"money":C.coins.push(k),C.total+=k.system.quantity.value*k.system.price.value;break;case"advantage":this._setOnUseEffect(k),s.push(k);break;case"disadvantage":this._setOnUseEffect(k),i.push(k);break;case"specialability":this._setOnUseEffect(k),this._setAEPayments(k),g[k.system.category.value].push(k);break;case"disease":n.push(k);break;case"patron":g.magical.push(k);break;case"demonmark":o.push(k);break;case"essence":d.push(k);break;case"imprint":p.push(k);break;case"application":we.has(k.system.skill)?we.get(k.system.skill).push(k):we.set(k.system.skill,[k]);break}}catch(V){this._itemPreparationError(k,V)}for(let k of D.bags.items)this._setBagContent(k,ke);for(let[k,V]of Object.entries(z))for(let[nt,ta]of Object.entries(V)){let wi=S[k].find(_i=>_i.name==nt);wi?wi.extensions=ta.join(", "):ui.notifications.warn(game.i18n.format("DSAError.noSpellForExtension",{name:nt,category:f.categoryLocalization(k),extension:ta.join(",")}))}for(let k of D.rangeweapons.items)try{k.system.worn.value&&w.push(T._prepareRangeWeapon(k,rt,a,this))}catch(V){this._itemPreparationError(k,V)}for(let k of c)try{x.push(T._prepareMeleeWeapon(k,a,t,c.filter(V=>V._id!=k._id&&!P.isYieldedTwohanded(V))))}catch(V){this._itemPreparationError(k,V)}for(let k of Object.values(Z))for(let V of k)V.applications=we.get(V.name)||[];C.coins=C.coins.sort((k,V)=>k.system.price.value>V.system.price.value?-1:1),g.magical.push(...g.pact),g.clerical.push(...g.ceremonial);for(let k of g.staff){let V=v.find(nt=>nt.system.artifact==k.system.artifact);if(V){V.abilities==null&&(V.abilities=[]),V.abilities.push(k);let nt=Number(k.system.volume)||0,ta=nt>0?"volumeFinal":"volume";V[ta]+=Math.abs(nt)*Number(k.system.step.value)}else g.magical.push(k)}let ea=duplicate(b.characteristics);return ea["-"]="-",{totalWeight:parseFloat(this.system.totalWeight.toFixed(3)),traditionArtifacts:v,armorSum:G,sortedSpecs:b.sortedSpecs,spellArmor:t.system.spellArmor||0,liturgyArmor:t.system.liturgyArmor||0,money:C,encumbrance:this.system.condition?.encumbered||0,carrycapacity:this.system.carrycapacity,isSwarm:this.isSwarm(),canSwarm:!this.prototypeToken.actorLink,wornRangedWeapons:w,wornMeleeWeapons:x,horseActor:ht,advantages:s,hasAnyItem:ft,disadvantages:i,specAbs:g,information:m,aggregatedtests:r,wornArmor:h,essence:d,imprint:p,inventory:D,hasTrait:jt,demonmarks:o,diseases:n,canBuild:game.dsa5.sheets.DSACharBuilder&&!t.system.details.species?.value,itemModifiers:this.system.itemModifiers,languagePoints:{used:t.system.freeLanguagePoints?.used||0,available:t.system.freeLanguagePoints?.value||0},schips:N,groupschips:F,guidevalues:ea,magic:S,traits:y,combatskills:a,canAdvance:this.canAdvance,sheetLocked:t.system.sheetLocked.value,bodyAttrs:["ff","ge","ko","kk"],mentalAttrs:["mu","kl","in","ch"],allSkillsLeft:{body:Z.body,social:Z.social,nature:Z.nature},allSkillsRight:{knowledge:Z.knowledge,trade:Z.trade}}}isSwarm(){return this.system.swarm.count>1&&!this.prototypeToken.actorLink}getArmorEncumbrance(e,t){let a=t.reduce((i,r)=>(r.system.calculatedEncumbrance=Number(r.system.encumbrance.value)+W.armorEncumbranceModifier(r),r.system.damageToolTip=W.damageTooltip(r),i+=r.system.calculatedEncumbrance),0),s=H.isRiding(this)?-1:0;return Math.max(0,a-R.abilityStep(e,game.i18n.localize("LocalizedIDs.inuredToEncumbrance"))+s)}_calcBagweight(e,t,a=!0){let s=0;if(t.has(e._id)){let i=0;!e.system.worn.value&&a&&(s-=e.system.preparedWeight);for(let r of t.get(e._id))r.system.preparedWeight=Number(parseFloat((r.system.weight.value*r.system.quantity.value).toFixed(3))),t.has(r._id)?i+=this._calcBagweight(r,t,!1):i+=r.system.preparedWeight;a?e.system.worn.value&&(s+=i):s+=i+e.system.preparedWeight,e.system.bagweight=`${i.toFixed(3)}/${e.system.capacity}`}return s}_setBagContent(e,t){if(t.has(e._id)){e.children=[];for(let a of t.get(e._id))e.children.push(T._prepareitemStructure(T._prepareConsumable(a))),t.has(a._id)&&this._setBagContent(a,t)}}isMerchant(){return["merchant","loot"].includes(getProperty(this,"system.merchant.merchantType"))}_itemPreparationError(e,t){console.error("Something went wrong with preparing item "+e.name+": "+t),console.warn(t),console.warn(e),ui.notifications.error("Something went wrong with preparing item "+e.name+": "+t)}_applyModiferTransformations(e){this.system.itemModifiers={};for(let t of Object.keys(e)){let a=game.dsa5.config.knownShortcuts[t.toLowerCase()];if(a){let s=e[t].reduce((i,r)=>i=i+r.value,0);this.system[a[0]][a[1]][a[2]]+=s,this.system.itemModifiers[t]={value:s,sources:e[t].map(i=>i.source)}}}}_buildGearAndAbilityModifiers(e,t){let a=getProperty(t,"system.effect.value");if(!!a)for(let s of a.split(/,|;/).map(i=>i.trim())){let i=s.replace(/(\s+)/g," ").trim().split(" ");if(i.length==2&&!isNaN(i[0])){let r={value:Number(i[0])*(t.system.step&&Number(t.system.step.value)||1),source:t.name,type:t.type};e[i[1]]==null?e[i[1]]=[r]:e[i[1]].push(r)}}}async _updateAPs(e,t={},a={}){if(T.canAdvance(this))if(!isNaN(e)&&e!=null){let s=Number(e);t["system.details.experience.spent"]=Number(this.system.details.experience.spent)+s,await this.update(t,a);let i=game.i18n.format(s>0?"advancementCost":"refundCost",{cost:Math.abs(s)});de(i)}else ui.notifications.error(game.i18n.localize("DSAError.APUpdateError"))}async checkEnoughXP(e){if(!T.canAdvance(this)||isNaN(e)||e==null||Number(this.system.details.experience.total)-Number(this.system.details.experience.spent)>=e)return!0;if(Number(this.system.details.experience.total)==0){let t=await renderTemplate("systems/dsa5/templates/dialog/parts/expChoices.html",{entries:b.startXP}),a=0,s=!1;if([s,a]=await new Promise((i,r)=>{new Dialog({title:game.i18n.localize("DSAError.NotEnoughXP"),content:t,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:n=>{i([!0,n.find(".APsel")[0].value])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{i([!1,0])}}}}).render(!0)}),s)return await this.update({"system.details.experience.total":Number(a)}),!0}return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughXP")),!1}setupWeapon(e,t,a,s){return a.mode=t,A.getSubClass(e.type).setupDialog(null,a,e,this,s)}setupWeaponless(e,t={},a){let s=foundry.utils.duplicate(b.defaultWeapon);s.name=game.i18n.localize(`${e}Weaponless`),s.system.combatskill={value:game.i18n.localize("LocalizedIDs.wrestle")},s.system.damageThreshold.value=14;let i=[];return R.hasAbility(this,game.i18n.localize("LocalizedIDs.mightyAstralBody"))&&i.push(game.i18n.localize("magical")),R.hasAbility(this,game.i18n.localize("LocalizedIDs.mightyKarmalBody"))&&i.push(game.i18n.localize("blessed")),mergeObject(s,{system:{effect:{attributes:i.join(", ")}}}),t.mode=e,A.getSubClass(s.type).setupDialog(null,t,s,this,a)}setupSpell(e,t={},a){return A.getSubClass(e.type).setupDialog(null,t,e,this,a)}setupSkill(e,t={},a){return A.getSubClass(e.type).setupDialog(null,t,e,this,a)}tokenScrollingText(e){let t=this.isToken?[this.token?.object]:this.getActiveTokens(!0);for(let a of t){if(!a)continue;let s=0;for(let i of e)canvas.interface.createScrollingText(a.center,i.value,{anchor:s,direction:i.value>0?2:1,fontSize:game.settings.get("dsa5","scrollingFontsize"),stroke:i.stroke,strokeThickness:1,jitter:.25,duration:1e3}),s+=1}}async _preUpdate(e,t,a){await super._preUpdate(e,t,a);let s={wounds:9109504,astralenergy:723929,karmaenergy:303670};game.combat?.isBrawling&&(s.temporaryLeP=16525967);let i=[];for(let o of Object.keys(s)){let c=getProperty(e,`system.status.${o}.value`);c&&i.push({value:c-this.system.status[o].value,stroke:s[o]})}i.length&&this.tokenScrollingText(i);let r=getProperty(e,"system.swarm.count");if(r&&!t.skipSwarmUpdate){let o=getProperty(e,"system.status.wounds.value")||this.system.status.wounds.value,c=r-(this.system.swarm.count||1),m=this.system.swarm.maxwounds||this.system.status.wounds.max;setProperty(e,"system.status.wounds.value",Math.max(0,o+c*m))}let n=getProperty(e,"system.details.experience.total");if(n){let o=this.system.details.experience.total;_.track(this,{type:"sum",previous:o,next:n},n-o)}}async applyDamage(e){if(game.combat?.isBrawling){let t=Math.min(this.system.status.temporaryLeP.max,this.system.status.temporaryLeP.value-e);await this.update({"system.status.temporaryLeP.value":t})}else{let t=Math.min(this.system.status.wounds.max,this.system.status.wounds.value-e);await this.update({"system.status.wounds.value":t})}}async applyRegeneration(e,t,a){let s={"system.status.wounds.value":Math.min(this.system.status.wounds.max,this.system.status.wounds.value+(e||0)),"system.status.karmaenergy.value":Math.min(this.system.status.karmaenergy.max,this.system.status.karmaenergy.value+(a||0)),"system.status.astralenergy.value":Math.min(this.system.status.astralenergy.max,this.system.status.astralenergy.value+(t||0))};await this.update(s)}async applyMana(e,t){let a=t=="AsP"?"astralenergy":"karmaenergy",s=Math.min(this.system.status[a].max,this.system.status[a].value-e);return s>=0?(await this.update({[`data.status.${a}.value`]:s}),!0):(ui.notifications.error(game.i18n.localize(`DSAError.NotEnough${t}`)),!1)}preparePostRollAction(e){let t=e.flags.data,a={flags:{img:e.flags.img},rollMode:t.rollMode,speaker:e.speaker,template:t.template,title:t.title,user:e.user};return t.attackerMessage&&(a.attackerMessage=t.attackerMessage),t.defenderMessage&&(a.defenderMessage=t.defenderMessage),t.unopposedStartMessage&&(a.unopposedStartMessage=t.unopposedStartMessage),a}resetTargetAndMessage(e,t){e.originalTargets?.size&&(game.user.targets=e.originalTargets,game.user.targets.user=game.user),!e.defenderMessage&&e.startMessagesList&&(t.startMessagesList=e.startMessagesList)}async fatererollDamage(e,t,a,s,i,r){t.fatePointDamageRerollUsed=!0,this.resetTargetAndMessage(i,t);let n=i.postData.damageRoll,o=await _DiceDSA5.manualRolls(await new Roll(n.formula||n._formula).evaluate({async:!0}),"CHATCONTEXT.rerollDamage");for(let c=0;c${game.i18n.localize("CHATFATE.fatepointUsed")} - ${game.i18n.format("CHATFATE.isTalented",{character:""+this.name+""})}
    `;let r=await renderTemplate("systems/dsa5/templates/dialog/isTalentedReroll-dialog.html",{testData:a,postData:i.postData});new ee({title:game.i18n.localize("CHATFATE.selectDice"),content:r,buttons:{Yes:{icon:'',label:game.i18n.localize("Ok"),callback:async n=>{let o=n.find(".dieSelected").map(function(){return Number($(this).attr("data-index"))}).get();if(o.length>0){let c=[];for(let p of o){let g=a.roll.terms[p*2];c.push(g.number+"d"+g.faces+"["+g.options.colorset+"]")}c=await _DiceDSA5.manualRolls(await new Roll(c.join("+")).evaluate({async:!0}),"CHATCONTEXT.talentedReroll"),await _DiceDSA5.showDiceSoNice(c,a.rollMode);let m=0,d=[];for(let p of o){let g=a.source.system[`characteristic${p+1}`],y=g?game.i18n.localize(`CHARAbbrev.${g.value.toUpperCase()}`)+" - ":"";d.push(`${y}${a.roll.terms[p*2].results[0].result}/${c.terms[m*2].results[0].result}`),a.roll.terms[p*2].results[0].result=Math.min(c.terms[m*2].results[0].result,a.roll.terms[p*2].results[0].result),m+=1}e+=`${game.i18n.localize("Roll")}: ${d.join(", ")}`,ChatMessage.create(f.chatDataSetup(e)),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.talentedRerollUsed":!0})}}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}async fatereroll(e,t,a,s,i,r){t.fatePointDamageRerollUsed=!0,this.resetTargetAndMessage(i,t);let n=await renderTemplate("systems/dsa5/templates/dialog/fateReroll-dialog.html",{testData:a,postData:i.postData,singleDie:i.postData.characteristics.length==1});new ee({title:game.i18n.localize("CHATFATE.selectDice"),content:n,buttons:{Yes:{icon:'',label:game.i18n.localize("Ok"),callback:async o=>{let c=o.find(".dieSelected").map(function(){return Number($(this).attr("data-index"))}).get();if(c.length>0){let m=[];for(let w of c){let x=a.roll.terms[w*2];m.push(x.number+"d"+x.faces+"["+x.options.colorset+"]")}m=await _DiceDSA5.manualRolls(await new Roll(m.join("+")).evaluate({async:!0}),"CHATCONTEXT.Reroll"),await _DiceDSA5.showDiceSoNice(m,a.rollMode);let d=0,p=[],g=f.getSpeaker(a.extra.speaker),y=game.i18n.localize("LocalizedIDs.traditionPhex"),h=g.items.some(w=>w.type=="specialability"&&w.name==y);for(let w of c){let x=a.source.system[`characteristic${w+1}`],v=x?`${game.i18n.localize(`CHARAbbrev.${x.value.toUpperCase()}`)} - `:"";p.push(`${v}${a.roll.terms[w*2].results[0].result}/${m.terms[d*2].results[0].result}`),h?a.roll.terms[w*2].results[0].result=Math.min(m.terms[d*2].results[0].result,a.roll.terms[w*2].results[0].result):a.roll.terms[w*2].results[0].result=m.terms[d*2].results[0].result,d+=1}e+=`
    ${game.i18n.localize("Roll")}: ${p.join(", ")}`,ChatMessage.create(f.chatDataSetup(e)),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fatePointRerollUsed":!0}),await this.reduceSchips(r)}}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}async fateaddQS(e,t,a,s,i,r){ChatMessage.create(f.chatDataSetup(e)),game.user.targets.forEach(n=>n.setTarget(!1,{user:game.user,releaseOthers:!1,groupSelection:!0})),t.fatePointAddQSUsed=!0,a.qualityStep=1,this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fatePointAddQSUsed":!0}),await this.reduceSchips(r)}async fateImprove(e,t,a,s,i,r){ChatMessage.create(f.chatDataSetup(e)),this.resetTargetAndMessage(i,t);let n=s.flags.data.preData.source.type;if(["spell","liturgy","ceremony","ritual","skill"].includes(n)){let o=await renderTemplate("systems/dsa5/templates/dialog/fateImprove-dialog.html",{testData:a,postData:i.postData});new ee({title:game.i18n.localize("CHATFATE.selectDice"),content:o,buttons:{Yes:{icon:'',label:game.i18n.localize("Ok"),callback:async c=>{let m=[0,0,0],d=c.find(".dieSelected").map(function(){return Number($(this).attr("data-index"))}).get();if(d.length==1){m[d]=2;let p={name:game.i18n.localize("CHATCONTEXT.improveFate"),value:m.join("|"),type:"roll"};a.roll.terms[d*2].results[0].result=Math.max(1,a.roll.terms[d*2].results[0].result-2),a.situationalModifiers.push(p),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fateImproved":!0}),await this.reduceSchips(r)}}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}else{let o={name:game.i18n.localize("CHATCONTEXT.improveFate"),value:2,type:"roll"};a.situationalModifiers.push(o),a.roll.terms[0].results[0].result=Math.max(1,a.roll.terms[0].results[0].result-2),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fateImproved":!0}),await this.reduceSchips(r)}}async reduceSchips(e){e==0?await this.update({"system.status.fatePoints.value":this.system.status.fatePoints.value-1}):await T.reduceGroupSchip()}static async reduceGroupSchip(){if(game.user.isGM){let e=game.settings.get("dsa5","groupschips").split("/").map(t=>Number(t));e[0]=e[0]-1,await game.settings.set("dsa5","groupschips",e.join("/"))}else game.socket.emit("system.dsa5",{type:"reduceGroupSchip",payload:{}})}async useFateOnRoll(e,t,a){if(t=="isTalented"||f.fateAvailable(this,a==1)){let s=e.flags.data,i=this.preparePostRollAction(e),r,n;a==0?(r=this.system.status.fatePoints.value-1,n="PointsRemaining"):(r=game.settings.get("dsa5","groupschips").split("/")[0],n="GroupPointsRemaining");let o=`

    ${game.i18n.localize("CHATFATE.fatepointUsed")}

    + `}static async changeStartMessage(e){for(let t of e.flags.data.startMessagesList){let a=game.messages.get(t),s=a.flags.unopposeData;game.socket.emit("system.dsa5",{type:"target",payload:{target:s.targetSpeaker.token,scene:canvas.scene.id,opposeFlag:{speaker:e.speaker,messageId:e.id,startMessageId:a.id}}}),await a.update({"flags.unopposeData.attackMessageId":e.id})}}static resolveFinalMessage(e){let t,a;if(e.flags.data.defenderMessage)for(let s of e.flags.data.defenderMessage){t=j.getMessageDude(e);let i=game.messages.get(s);a=j.getMessageDude(i),this.completeOpposedProcess(t,a,{blind:e.blind,whisper:e.whisper})}else{a=j.getMessageDude(e);let s=game.messages.get(e.flags.data.attackerMessage);t=j.getMessageDude(s),this.completeOpposedProcess(t,a,{blind:e.blind,whisper:e.whisper})}}static getMessageDude(e){let t={speaker:e.speaker,testResult:mergeObject(e.flags.data.postData,{source:e.flags.data.preData.source}),img:f.getSpeaker(e.speaker).img,messageId:e.id};return t.testResult.ammo&&t.testResult.source.effects.push(...t.testResult.ammo.effects),t}static async showDamage(e,t=!1){game.user.isGM?(!t||!e.flags.data.hideDamage)&&e.flags.data.postData.damageRoll&&(await e.update({content:e.content.replace(`data-hide-damage="${!t}"`,`data-hide-damage="${t}"`),"flags.data.hideDamage":t}),t||_DiceDSA5._addRollDiceSoNice(e.flags.data.preData,Roll.fromData(e.flags.data.postData.damageRoll),game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration("damage"))):game.socket.emit("system.dsa5",{type:"showDamage",payload:{id:e.id,hide:t}})}static async playAutomatedJBA2(e,t,a){if(f.moduleEnabled("autoanimations")){let s=f.getSpeaker(e.speaker).getActiveTokens()[0],i=f.getSpeaker(t.speaker).getActiveTokens()[0];if(!s||!s.actor||!i||!i.actor)return;let n=s.actor.items.get(e.testResult.source._id);if(n||(n=new C(e.testResult.source,{temporary:!0})),!n)return;n=n.toObject();let r=[i],o=a.winner=="attacker",c=o?r:[],m=e.testResult.successLevel>1&&o,d=e.testResult.successLevel<1&&!o,p=t.testResult.successLevel>1&&!o,g=t.testResult.successLevel<1&&o,y=[],h=[];m?h.push(game.i18n.localize("CriticalSuccess")):d?h.push(game.i18n.localize("CriticalFailure")):p?h.push(`${game.i18n.localize("CHAR.PARRY")} ${game.i18n.localize("CriticalSuccess")}`):g&&h.push(`${game.i18n.localize("CHAR.PARRY")} ${game.i18n.localize("CriticalFailure")}`),o||h.push(game.i18n.localize("CHAR.PARRY"));for(let w of h)y.push({name:`${n.name} (${w})`},{name:w});y.push(n);for(let w of y)if(await AutomatedAnimations.playAnimation(s,w,{targets:r,hitTargets:c,playOnMiss:!0}))break}}static async showSpellWithoutTarget(e){if(f.moduleEnabled("autoanimations")){let t=getProperty(e,"flags.data");if(!t||t.isOpposedTest)return;if((getProperty(t,"postData.result")||-1)>0){let s=f.getSpeaker(t.postData.speaker).getActiveTokens()[0];if(!s||!s.actor)return;let i=Array.from(game.user.targets),n=s.actor.items.get(t.preData.source._id);i.length||(i=[s]),AutomatedAnimations.playAnimation(s,n,{targets:i})}}}static async clearOpposed(e){game.user.isGM?await e.update({["flags.-=oppose"]:null}):game.socket.emit("system.dsa5",{type:"clearOpposed",payload:{actorId:e.id}})}static async _handleReaction(e){let t=$(e.currentTarget).parents(".message").attr("data-message-id"),a=game.messages.get(t);switch(game.messages.get(a.flags.unopposeData.attackMessageId).flags.data.preData.source.type){case"skill":ct.showDialog(a);break;default:Me.showDialog(a)}}static async chatListeners(e){e.on("click",".unopposed-button",t=>{t.preventDefault(),this._handleReaction(t)})}static async hideReactionButton(e){if(e)if(game.user.isGM){let t=game.messages.get(e),a=$(t.content);a.find("button.unopposed-button").remove(),a=$("
    ").append(a),await t.update({content:a.html()})}else game.socket.emit("system.dsa5",{type:"hideQueryButton",payload:{id:e}})}static async completeOpposedProcess(e,t,a){await Ue.postOpposed({attacker:e,defender:t,options:a});let s=await this.evaluateOpposedTest(e.testResult,t.testResult,a);return this.formatOpposedResult(s,e.speaker,t.speaker),this.rerenderMessagesWithModifiers(s,e,t),Hooks.call("finishOpposedTest",e,t,s,a),await this.finishOpposedTestHookAsync(e,t,s,a),this.playAutomatedJBA2(e,t,s),await this.renderOpposedResult(s,a),await this.hideReactionButton(a.startMessageId),s}static async finishOpposedTestHookAsync(e,t,a,s){}static async evaluateOpposedTest(e,t,a={}){let s={};if(s.other=[],a.additionalInfo&&s.other.push(a.additionalInfo),s.winner="attacker",["weapon","spell","liturgy","ceremony","ritual","combatskill"].includes(e.rollType)&&t.successLevel==null&&(t.successLevel=-5),e.rollType=="damage"&&(t.successLevel=-5,e.successLevel=1),t.successLevel!=null)switch(e.rollType){case"combatskill":case"talent":this._evaluateTalentOpposedRoll(e,t,s,a);break;case"ceremony":case"ritual":case"spell":case"liturgy":case"weapon":case"damage":this._evaluateWeaponOpposedRoll(e,t,s,a);break;default:ui.notifications.error("Can not oppose "+e.rollType),console.warn("Can not oppose "+e.rollType)}return s}static _evaluateWeaponOpposedRoll(e,t,a,s={}){if(e.successLevel>0&&t.successLevel<0){let i=this._calculateOpposedDamage(e,t,s);if(i.armorDamaged.damaged&&i.armorDamaged.ids.length){let c=i.armorDamaged.ids.join(";");a.other.push(`
    `)}t.counterAttack&&(i.damage+=2,i.sum=i.damage-i.armor,i.tooltip=game.i18n.localize("LocalizedIDs.counterAttack")+" 2"),i.messages.length&&(i.tooltip||(i.tooltip=""),i.tooltip+=` ${i.messages.join("
    ")}`),a.winner="attacker";let n=[i.armorMod!=0?`${i.armorMod+" "+game.i18n.localize("Modifier")}`:"",i.armorMultiplier!=1?"*"+i.armorMultiplier+" "+game.i18n.localize("Modifier"):"",i.spellArmor!=0?`${i.spellArmor} ${game.i18n.localize("spellArmor")}`:"",i.liturgyArmor!=0?`${i.liturgyArmor} ${game.i18n.localize("liturgyArmor")}`:""].join(""),o=`${game.combat?.isBrawling?game.i18n.localize("BRAWLING.temporary"):game.i18n.localize("damage")}: ${i.damage} - ${i.armor} = ${i.sum}`;a.damage={description:o,value:i.sum,sp:i.damage}}else a.winner="defender"}static _calculateOpposedDamage(e,t,a={}){let s=f.getSpeaker(t.speaker),i=[],n=e.damage,r=game.i18n.localize("LocalizedIDs.immuneToCrit");e.doubleDamage&&s.items.find(S=>S.name==r&&S.type=="trait")&&(n=Math.floor(n/e.doubleDamage),i.push(r)),a.origin=e.source,a.damage=n;let o=Q.applyRollTransformation(s,a,5).options.damage,{wornArmor:c,armor:m}=T.armorValue(s,a),d=[],p=0,g=e.armorPen||[];for(let S of g)/^\*/.test(S)?d.push(Number(S.replace("*",""))):p+=Number(S);let y=0,h=0;["spell","ritual"].includes(e.source.type)?y+=s.system.spellArmor||0:["liturgy","ceremony"].includes(e.source.type)&&(y+=s.system.liturgyArmor||0),m+=p;let w=d.reduce((S,x)=>S*x,1);m=Math.max(Math.round(m*w),0),m+=y+h;let z=W.armorGetsDamage(o,e),v=c.map(S=>S.uuid);return{damage:o,armor:m,armorDamaged:{damaged:z,ids:v},armorMod:p,spellArmor:y,liturgyArmor:h,armorMultiplier:w,messages:i,sum:o-m}}static _evaluateTalentOpposedRoll(e,t,a,s={}){e.successLevel>0&&e.successLevel>t.successLevel?a.winner="attacker":e.qualityStep>t.qualityStep||e.result>=0&&t.result<0?(a.winner="attacker",a.differenceSL=e.qualityStep-t.qualityStep):(a.winner="defender",a.differenceSL=t.qualityStep-e.qualityStep)}static formatOpposedResult(e,t,a){let s=e.differenceSL?"winsFP":"wins";return e.winner=="attacker"?(e.result=game.i18n.format("OPPOSED."+s,{winner:t.alias,loser:a.alias,SL:e.differenceSL}),e.img=t.img):e.winner=="defender"&&(e.result=game.i18n.format("OPPOSED."+s,{winner:a.alias,loser:t.alias,SL:e.differenceSL}),e.img=a.img),e.speakerAttack=t,e.speakerDefend=a,e}static rerenderMessagesWithModifiers(e,t,a){let s=game.messages.get(t.messageId);this.showDamage(s,e.winner!="attacker")}static async renderOpposedResult(e,t={}){e.hideData=game.settings.get("dsa5","hideOpposedDamage"),e.applyDamageInChat=game.settings.get("dsa5","applyDamageInChat"),e.isBrawling=game.combat?.isBrawling;let a=await renderTemplate("systems/dsa5/templates/chat/roll/opposed-result.html",e),s={user:game.user.id,content:a,"flags.opposeData":e,"flags.hideData":e.hideData,whisper:t.whisper,blind:t.blind};t.target&&(s["flags.startMessageId"]=t.startMessageId),await ChatMessage.create(s)}static async resolveUndefended(e,t=""){let a=e.flags.unopposeData,s=game.messages.get(a.attackMessageId),i={speaker:s.speaker,testResult:s.flags.data.postData,messageId:a.attackMessageId};i.testResult.source=s.flags.data.preData.source,i.testResult.ammo&&i.testResult.source.effects.push(...i.testResult.ammo.effects);let n=canvas.tokens.get(a.targetSpeaker.token),r={speaker:a.targetSpeaker,testResult:{actor:n.actor,speaker:{token:a.targetSpeaker.token}}};await this.clearOpposed(n.actor),await this.completeOpposedProcess(i,r,{target:!0,startMessageId:e.id,additionalInfo:t}),game.user.isGM?await s.update({"flags.data.unopposedStartMessage":e.id}):await game.socket.emit("system.dsa5",{type:"updateAttackMessage",payload:{messageId:s.id,startMessageId:e.id}})}};u(j,"OpposedDsa5");var Ve=class extends Dialog{static async showDialog(e){let t=new Ve({title:game.i18n.localize("WEAR.checkShort"),content:await this.getTemplate(e),buttons:{}});t.items=e,t.render(!0)}activateListeners(e){super.activateListeners(e),e.find(".reactClick").click(t=>{this.callbackResult(t),this.close()})}static async getTemplate(e){let t=e.map(a=>({name:a.name,id:a.id,img:a.img}));return await renderTemplate("systems/dsa5/templates/dialog/dialog-reaction-attack.html",{items:t,title:"WEAR.checkShort"})}callbackResult(e){W.breakingTest(this.items.find(t=>t.id==e.currentTarget.dataset.value))}};u(Ve,"EquipmentDamageDialog");var U=class{static async showBotchCard(e,t={}){t.speaker={token:e.token,actor:e.actor,scene:e.scene},t.source=e.source;let a=b.systemTables.find(i=>i.name==e.table),s=await U.getRollTable(a.pack[game.i18n.lang],game.i18n.localize(`TABLENAMES.${e.table}`),e);for(let i of s){let n=t.speaker?await U.hasEffect(i):!1,r=f.replaceDies(f.replaceConditions(i.results[0].text)),o=`${game.i18n.localize("TABLENAMES."+e.table)}`,c=await renderTemplate("systems/dsa5/templates/tables/tableCard.html",{result:r,title:o,hasEffect:n}),m=await this.buildEffects(i,n);ChatMessage.create({user:game.user.id,content:c,whisper:t.whisper,blind:t.blind,flags:{data:{preData:{source:{effects:m},extra:{actor:{id:t.speaker.actor},speaker:t.speaker},situationalModifiers:[]},postData:{}},dsa5:{hasEffect:n,options:t}}})}}static async hasEffect(e){return getProperty(e.results[0],"flags.dsa5")||!1}static async buildEffects(e,t){let a=[];if(t&&t.resistEffect){let s=Array.isArray(t.resistEffect.fail)?t.resistEffect.fail:[t.resistEffect.fail];for(let i of s){let n=new X().effectDummy(i.description,t.resistEffect.changes||[],t.resistEffect.duration||{});i.systemEffect?mergeObject(n,{_id:"botchEffect",flags:{dsa5:{hideOnToken:!1,hidePlayers:!1,advancedFunction:2,args3:`await actor.addCondition("${i.systemEffect}", ${i.level||1});`}}}):i.command&&mergeObject(n,{_id:"botchEffect",flags:{dsa5:{hideOnToken:!1,hidePlayers:!1,advancedFunction:2,args3:i.command}}}),a.push(n)}}return a}static async getRollTable(e,t,a={}){let i=(await game.packs.get(e).getDocuments({name__in:[t]}))[0],n=await i.draw({displayChat:!1});return a.weaponless=="true"&&n.roll.total<7&&(n.roll.editRollAtIndex([{index:0,val:n.roll.total+5}]),n=await i.draw({displayChat:!1,roll:n.roll})),[n]}static async tableEnabledFor(e){let t=b.systemTables.find(a=>a.name==e);return t?game.settings.get(t.setting.module,t.setting.key):!1}static rollCritBotchButton(e,t,a){let s=game.i18n.localize(`TABLENAMES.${e}`),i=a.extra.speaker,n=a.source._id;return`, ${s}`}static async defaultBotch(){return", "+game.i18n.localize("selfDamage")+(await new Roll("1d6+2").evaluate({async:!0})).total}static defaultAttackCrit(e){let t=", "+game.i18n.localize("halfDefense");return e&&(t+=", "+game.i18n.format("doubleDamage",{x:2})),t}static defaultParryCrit(){return", "+game.i18n.localize("attackOfOpportunity")}};u(U,"DSATables");var B=class{static async payMoney(e,t,a=!1,s=!0){let i=B.canPay(e,t,a);return i.success&&await B._updateMoney(e,i.actorsMoney.money,i.actorsMoney.sum-i.money,s),!a&&i.msg!=""&&ChatMessage.create(f.chatDataSetup(`

    ${i.msg}

    `,"roll")),i.success}static canPay(e,t,a){let s=this._getPaymoney(t),i={success:!1,msg:"",money:s};return s&&(i.actorsMoney=this._actorsMoney(e),i.actorsMoney.sum>=s?(i.msg=game.i18n.format("PAYMENT.pay",{actor:e.name,amount:B._moneyToString(s)}),i.success=!0):(i.msg=game.i18n.format("PAYMENT.cannotpay",{actor:e.name,amount:B._moneyToString(s)}),a&&ui.notifications.notify(i.msg))),i}static async getMoney(e,t,a=!1,s=!0){let i=this._getPaidmoney(t);if(i){let n=this._actorsMoney(e);await B._updateMoney(e,n.money,n.sum+i,s);let r=`

    ${game.i18n.format("PAYMENT.getPaid",{actor:e.name,amount:B._moneyToString(i)})}

    `;return a||ChatMessage.create(f.chatDataSetup(r,"roll")),!0}}static async _updateMoney(e,t,a,s=!0){let i=B._moneyToCoins(a);for(let n of t)switch(n.name){case"Money-D":n.system.quantity.value=i.D;break;case"Money-S":n.system.quantity.value=i.S;break;case"Money-H":n.system.quantity.value=i.H;break;case"Money-K":n.system.quantity.value=i.K;break}await e.updateEmbeddedDocuments("Item",t,{render:s})}static createGetPaidChatMessage(e,t=void 0){let a=this._getPaidmoney(e);if(a){let s=t?` (${t})`:"",i=`

    ${game.i18n.localize("PAYMENT.wage")}

    ${game.i18n.format("PAYMENT.getPaidSum",{amount:B._moneyToString(a)})}${s}

    `;ChatMessage.create(f.chatDataSetup(i,"roll"))}}static createPayChatMessage(e,t=void 0){let a=this._getPaymoney(e);if(a){let s=t?` (${t})`:"",i=`

    ${game.i18n.localize("PAYMENT.bill")}

    ${game.i18n.format("PAYMENT.paySum",{amount:B._moneyToString(a)})}${s}

    `;ChatMessage.create(f.chatDataSetup(i,"roll"))}}static _getPaidmoney(e){let t=this._parseMoneyString(e);if(!t){let a=`

    ${game.i18n.localize("PAYMENT.error")}

    ${game.i18n.localize("PAYMENT.getPaidexample")}

    `;return ChatMessage.create(f.chatDataSetup(a,"roll")),!1}return t}static _getPaymoney(e){let t=this._parseMoneyString(e);if(!t){let a=`

    ${game.i18n.localize("PAYMENT.error")}

    ${game.i18n.localize("PAYMENT.payexample")}

    `;return ChatMessage.create(f.chatDataSetup(a,"roll")),!1}return t}static _parseMoneyString(e){let t=e.replace(",",".").match(/\d{1,}(\.\d{1,3}|,\d{1,3})?/);return t?Number(t[0]):!1}static _actorsMoney(e){let t=duplicate(e.items.filter(a=>a.type=="money"));return{money:t,sum:t.reduce((a,s)=>a+Number(s.system.quantity.value)*Number(s.system.price.value),0)}}static async handlePayAction(e,t,a,s=void 0){if(game.user.isGM&&!s){ui.notifications.notify(game.i18n.localize("PAYMENT.onlyActors"));return}s?K.playMoneySound(!0):s=game.user.character;let i=!1;s&&t?i=await B.payMoney(s,a):s&&!t?i=await B.getMoney(s,a):ui.notifications.notify(game.i18n.localize("PAYMENT.onlyActors")),i&&e&&(e.fadeOut(),game.socket.emit("system.dsa5",{type:"updateMsg",payload:{id:e.closest(".message").attr("data-message-id"),updateData:{[`flags.dsa5.userHidden.${game.user.id}`]:!0}}}))}static _moneyToCoins(e){let t=Math.round(e*100),a=Math.floor(t/1e3),s=Math.floor((t-a*1e3)/100),i=Math.floor((t-a*1e3-s*100)/10);return{D:a,S:s,H:i,K:Math.round(t-a*1e3-s*100-i*10)}}static _moneyToString(e){let t=B._moneyToCoins(e),a=[];for(let[s,i]of Object.entries(t))i>0&&a.push(`${i} `);return a.join(", ")}static async chatListeners(e){e.on("click",".payButton",t=>{let a=$(t.currentTarget);B.handlePayAction(a,Number(a.attr("data-pay"))!=1,a.attr("data-amount")),K.playMoneySound()})}};u(B,"DSA5Payment");var Te=class{constructor(){Te.skills.length==0&&f.allSkills().then(e=>{Te.skills=e.map(t=>({name:t.name,type:"skill"})).concat(Object.values(game.dsa5.config.characteristics).map(t=>({name:game.i18n.localize(t),type:"attribute"})).concat([{name:game.i18n.localize("regenerate"),type:"regeneration"},{name:game.i18n.localize("fallingDamage"),type:"fallingDamage"}]))}),this.filtering=!1,this.combatConstants={dodge:game.i18n.localize("dodge"),parryWeaponless:game.i18n.localize("parryWeaponless"),attackWeaponless:game.i18n.localize("attackWeaponless")}}get regex(){return new RegExp(`^/(${Te.cmds.join(" |")})`)}async chatListeners(e){let t=this,a=e.find("#chat-message");e.on("keyup","#chat-message",async function(i){t._parseInput(i)}),e.on("click",".quick-item",async function(i){t._quickSelect($(i.currentTarget))}),a.on("keydown",function(i){t._navigateQuickFind(i)});let s=jQuery._data(a[0]).events.keydown;s.unshift(s.pop())}_parseInput(e){let t=e.target.value;if(this.regex.test(t)){if([38,40,13,9].includes(e.which))return!1;if(e.which==27)return this._closeQuickfind(e),!1;let a=this._getCmd(t),s=t.substring(1+a.length).toLowerCase().trim();this[`_filter${a}`](s,e),this.filtering=!0}else this._closeQuickfind(e)}_getCmd(e){return e.substring(1,3).toUpperCase().trim()}_completeCurrentEntry(e){$("#chat-message").val($("#chat-message").val().split(" ")[0]+" "+e.text())+""}_closeQuickfind(e){this.filtering=!1,$(e.currentTarget).closest("#chat-form").find(".quickfind").remove()}_filterW(e,t){let a=game.users.contents.filter(s=>s.active&&s.name.toLowerCase().trim().indexOf(e)!=-1).map(s=>({name:s.name,type:"user"}));this._checkEmpty(a),this._setList(a,"W",t)}_filterAT(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["meleeweapon","rangeweapon"],n=["meleeAttack","rangeAttack"],r=a.items.filter(o=>(i.includes(o.type)&&o.system.worn.value==!0||o.type=="trait"&&n.includes(o.system.traitType.value))&&o.name.toLowerCase().trim().indexOf(e)!=-1).slice(0,5).map(o=>({name:o.name,type:"item"})).concat([{name:this.combatConstants.attackWeaponless,type:"item"}].filter(o=>o.name.toLowerCase().trim().indexOf(e)!=-1));this._checkEmpty(r),this._setList(r,"AT",t)}}_filterPA(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["meleeweapon"],n=a.items.filter(r=>i.includes(r.type)&&r.name.toLowerCase().trim().indexOf(e)!=-1&&r.system.worn.value==!0).slice(0,5).map(r=>({name:r.name,type:"item"})).concat([{name:this.combatConstants.dodge,type:"item"},{name:this.combatConstants.parryWeaponless,type:"item"}].filter(r=>r.name.toLowerCase().trim().indexOf(e)!=-1));this._checkEmpty(n),this._setList(n,"PA",t)}}_filterSP(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["spell","ritual"],n=a.items.filter(r=>i.includes(r.type)&&r.name.toLowerCase().trim().indexOf(e)!=-1).slice(0,5).map(r=>({name:r.name,type:"item"}));this._checkEmpty(n),this._setList(n,"SP",t)}}_checkEmpty(e){e.length||e.push({name:game.i18n.localize("DSAError.noMatch"),type:"none"})}_filterLI(e,t){let{actor:a,tokenId:s}=Te._getActor();if(a){let i=["liturgy","ceremony"],n=a.items.filter(r=>i.includes(r.type)&&r.name.toLowerCase().trim().indexOf(e)!=-1).slice(0,5).map(r=>({name:r.name,type:"item"}));this._checkEmpty(n),this._setList(n,"LI",t)}}_getSkills(e,t=void 0){e=e.replace(/(-|\+)?\d+/g,"").trim();let a=Te.skills.filter(s=>s.name.toLowerCase().trim().indexOf(e)!=-1&&(t==null||t==s.type)).slice(0,5);return this._checkEmpty(a),a}_filterCH(e,t){this._setList(this._getSkills(e),"CH",t)}_filterSK(e,t){this._setList(this._getSkills(e),"SK",t)}_filterRQ(e,t){this._setList(this._getSkills(e),"RQ",t)}_filterGC(e,t){this._setList(this._getSkills(e,"skill"),"GC",t)}_setList(e,t,a){let s=$(`
      ${e.map(r=>`
    • ${r.name}
    • `).join("")}
    `);s.find(".quick-item:first").addClass("focus");let i=$(a.currentTarget).closest("#chat-form"),n=i.find(".quickfind");n.length?n.replaceWith(s):i.append(s)}_navigateQuickFind(e){if(this.filtering){let t=$(e.currentTarget).closest("#chat-form").find(".focus");switch(e.which){case 38:return t.prev(".quick-item").length&&t.removeClass("focus").prev(".quick-item").addClass("focus"),!1;case 40:return t.next(".quick-item").length&&t.removeClass("focus").next(".quick-item").addClass("focus"),!1;case 13:if(t.attr("data-category")=="W")break;return e.stopPropagation(),e.preventDefault(),this._quickSelect(t),!1;case 9:return e.stopPropagation(),e.preventDefault(),this._completeCurrentEntry(t),!1}}return!0}static _getActor(){let e=ChatMessage.getSpeaker(),t;return e.token&&(t=game.actors.tokens[e.token]),t||(t=game.actors.get(e.actor)),t?{actor:t,tokenId:e.token}:(ui.notifications.error(game.i18n.localize("DSAError.noProperActor")),{})}_quickSelect(e){let t=e.attr("data-category");switch(t){case"NM":case"GC":case"RQ":case"CH":this[`_quick${t}`](e);break;case"W":this._completeCurrentEntry(e);break;default:let{actor:a,tokenId:s}=Te._getActor();a&&(this._resetChatAutoCompletion(e),this[`_quick${t}`](e,a,s))}}_quickW(e,t,a){}_quickCH(e){ae.check3D20(e),this._resetChatAutoCompletion(e)}_quickSK(e,t,a){switch(e.attr("data-type")){case"skill":let s=t.items.find(n=>n.name==e.text()&&n.type=="skill");s&&t.setupSkill(s,{},a).then(n=>{t.basicTest(n)});break;case"attribute":let i=Object.keys(game.dsa5.config.characteristics).find(n=>game.i18n.localize(game.dsa5.config.characteristics[n])==e.text());t.setupCharacteristic(i,{},a).then(n=>{t.basicTest(n)});break;case"regeneration":t.setupRegeneration("regenerate",{},a).then(n=>{t.basicTest(n)});break}}_resetChatAutoCompletion(e){let t=e.closest("#chat-form");t.find("#chat-message").val(""),t.find(".quickfind").remove()}_quickGC(e){let t=Number($("#chat-message").val().match(/(-|\+)?\d+/g))||0;this._resetChatAutoCompletion(e),q.showGCMessage(e.text(),t)}_quickRQ(e){let t=Number($("#chat-message").val().match(/(-|\+)?\d+/g))||0;this._resetChatAutoCompletion(e),q.showRQMessage(e.text(),t)}_quickPA(e,t,a){let s=e.text();if(this.combatConstants.dodge==s)t.setupDodge({},a).then(i=>{t.basicTest(i)});else if(this.combatConstants.parryWeaponless==s)t.setupWeaponless("parry",{},a).then(i=>{t.basicTest(i)});else{let i=["meleeweapon"],n=t.items.find(r=>i.includes(r.type)&&r.name==e.text());n&&t.setupWeapon(n,"parry",{},a).then(r=>{t.basicTest(r)})}}_quickAT(e,t,a){let s=e.text();if(this.combatConstants.attackWeaponless==s)t.setupWeaponless("attack",{},a).then(i=>{t.basicTest(i)});else{let i=["meleeweapon","rangeweapon"],n=["meleeAttack","rangeAttack"],r=t.items.find(o=>i.includes(o.type)&&o.name==e.text());r||(r=t.items.find(o=>o.type=="trait"&&o.name==e.text()&&n.includes(o.system.traitType.value))),r&&t.setupWeapon(r,"attack",{},a).then(o=>{t.basicTest(o)})}}_quickSP(e,t,a){let s=["ritual","spell"],i=t.items.find(n=>s.includes(n.type)&&n.name==e.text());i&&t.setupSpell(i,{},a).then(n=>{t.basicTest(n)})}_quickLI(e,t,a){let s=["liturgy","ceremony"],i=t.items.find(n=>s.includes(n.type)&&n.name==e.text());i&&t.setupSpell(i,{},a).then(n=>{t.basicTest(n)})}static async infoItemAsync(e){(await fromUuid(e)).postItem()}static bindRollCommands(e){e.on("click",".request-roll",s=>{let i=s.currentTarget.dataset;return q.showRQMessage(i.name,Number(i.modifier)||0,i.label),s.stopPropagation(),!1}),e.on("click",".postInfo",s=>{let i=fromUuidSync(s.currentTarget.dataset.uuid);return i&&(typeof i.postItem=="function"?i.postItem():this.infoItemAsync(s.currentTarget.dataset.uuid)),s.stopPropagation(),!1}),e.on("click",".postContentChat",async s=>{let i=$(s.currentTarget).closest(".postChatSection").find(".postChatContent").html();lt.getDialog(i)}),e.on("click",".request-GC",s=>(q.showGCMessage(s.currentTarget.dataset.name,Number(s.currentTarget.dataset.modifier)||0),s.stopPropagation(),!1)),e.on("click",".request-CH",s=>(ae.check3D20(void 0,s.currentTarget.dataset.name,{modifier:Number(s.currentTarget.dataset.modifier)||0}),s.stopPropagation(),!1)),e.on("click",".request-Pay",s=>{!game.user.isGM||B.createPayChatMessage(s.currentTarget.dataset.modifier)}),e.on("click",".request-GetPaid",s=>{!game.user.isGM||B.createGetPaidChatMessage(s.currentTarget.dataset.modifier)}),e.on("click",".request-AP",s=>{if(!game.user.isGM)return;let i=game.dsa5.apps.gameMasterMenu;i.getExp(i.selectedIDs(),s.currentTarget.dataset.modifier)});let t=u(s=>{s.stopPropagation();let i=s.currentTarget.dataset.type,n=s.currentTarget.dataset.uuid;!n||!i||s.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:i,uuid:n}))},"itemDragStart"),a=e.find(".show-item");a.click(async s=>{let i=s.currentTarget.dataset.uuid;(await fromUuid(i)).sheet.render(!0)}),a.attr("draggable",!0).on("dragstart",s=>t(s)),e.on("click",".actorEmbeddedAbility",async s=>{let n=(await fromUuid(s.currentTarget.dataset.actor)).items.get(s.currentTarget.dataset.id);n&&n.sheet.render(!0)})}},se=Te;u(se,"DSA5ChatAutoCompletion"),L(se,"skills",[]),L(se,"cmds",["sk","at","pa","sp","li","rq","gc","w","ch"]);var q=class{static async requestGC(e,t,a,s=0){let{actor:i,tokenId:n}=se._getActor();if(!i)return;game.user.updateTokenTargets([]);let r={modifier:s,postFunction:{cummulative:a,functionName:"game.dsa5.apps.RequestRoll.autoEditGroupCheckRoll"}};switch(e){case"attribute":break;default:let o=i.items.find(c=>c.name==t&&c.type==e);i.setupSkill(o,r,n).then(async c=>{let m=await i.basicTest(c);await q.editGroupCheckRoll(a,m,t,e)})}}static async autoEditGroupCheckRoll(e,t,a){await q.editGroupCheckRoll(e.cummulative,t,a.name,a.type)}static async editGroupCheckRoll(e,t,a,s){let i=await game.messages.get(e),n=i.flags,o=t.result.successLevel>1?2:1;n.botched=n.botched||t.result.successLevel<-1;let c=f.getSpeaker(t.result.speaker),m={messageId:t.result.messageId,actor:c.name,qs:(t.result.qualityStep||0)*o,success:t.result.successLevel,target:a,type:s},d=n.results.findIndex(p=>p.messageId==m.messageId);d>=0?n.results[d]=m:n.results.push(m),q.rerenderGC(i,n)}static async requestRoll(e,t,a=0){let{actor:s,tokenId:i}=se._getActor();if(s){game.user.updateTokenTargets([]);let n={modifier:a};switch(e){case"attribute":let r=Object.keys(game.dsa5.config.characteristics).find(c=>game.i18n.localize(game.dsa5.config.characteristics[c])==t);s.setupCharacteristic(r,n,i).then(c=>{s.basicTest(c)});break;case"regeneration":s.setupRegeneration("regenerate",n,i).then(c=>{s.basicTest(c)});break;case"fallingDamage":s.setupFallingDamage(n,i);break;default:let o=s.items.find(c=>c.name==t&&c.type==e);s.setupSkill(o,n,i).then(c=>{s.basicTest(c)})}}}static async rerenderGC(e,t){if(game.user.isGM){let a=0;t.qs=t.results.reduce((i,n)=>(a+=n.success<0?1:0,n.success>1&&(a=0),i+n.qs),0),t.failed=a;for(let i of t.rollOptions)i.calculatedModifier=i.modifier-a;t.openRolls=t.maxRolls-t.results.length,t.doneRolls=t.results.length;let s=await renderTemplate("systems/dsa5/templates/chat/roll/groupcheck.html",t);e.update({content:s,flags:t})}else game.socket.emit("system.dsa5",{type:"updateGroupCheck",payload:{messageId:e.id,data:t}});$("#chat-log").find(`[data-message-id="${e.id}"`).appendTo("#chat-log")}static showRQMessage(e,t=0,a=void 0){let s=t<0?` ${t}`:t>0?` +${t}`:"",i=se.skills.find(r=>r.name==e).type,n=game.i18n.format("CHATNOTIFICATION.requestRoll",{user:game.user.name,item:` ${a||e}${s}`});ChatMessage.create(f.chatDataSetup(n))}static async showGCMessage(e,t=0,a={}){let s=se.skills.find(o=>o.name==e).type,i={results:[],qs:0,failed:0,modifier:t,name:game.user.name,maxRolls:7,openRolls:7,doneRolls:0,targetQs:10,rollOptions:[{type:s,modifier:t,calculatedModifier:t,target:e}]};mergeObject(i,a);let n=await renderTemplate("systems/dsa5/templates/chat/roll/groupcheck.html",i),r=f.chatDataSetup(n);r.flags=i,ChatMessage.create(r)}static async addSkillToGC(e){let t=$(e.currentTarget).parents(".message").attr("data-message-id"),a=await renderTemplate("systems/dsa5/templates/dialog/addgroupcheckskill.html",{skills:se.skills.filter(i=>i.type=="skill").sort((i,n)=>i.name.localeCompare(n.name))}),s={title:game.i18n.localize("HELP.groupcheck"),content:a,buttons:{ok:{icon:'',label:game.i18n.localize("ok"),callback:async i=>{let n=game.messages.get(t),r=n.flags;r.rollOptions.push({type:"skill",modifier:i.find('[name="modifier"]').val(),target:i.find('[name="skill"]').val()}),q.rerenderGC(n,r)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}};new ee(s).render(!0)}static async removeGCEntry(e){let t=$(e.currentTarget),a=Number(e.currentTarget.dataset.index),s=game.messages.get(t.parents(".message").attr("data-message-id")),i=s.flags;i.results.splice(a,1),q.rerenderGC(s,i)}static removeSkillFromGC(e){let t=$(e.currentTarget),a=game.messages.get(t.parents(".message").attr("data-message-id")),s=a.flags;s.rollOptions=s.rollOptions.filter(i=>!(i.type==e.currentTarget.dataset.type&&i.target==e.currentTarget.dataset.name)),s.results=s.results.filter(i=>!(i.type==e.currentTarget.dataset.type&&i.target==e.currentTarget.dataset.name)),q.rerenderGC(a,s)}static async editGC(e){let t=$(e.currentTarget),a=Number(e.currentTarget.dataset.index),s=game.messages.get(t.parents(".message").attr("data-message-id")),i=s.flags;if(a)i.results[a].qs=Number(t.val());else if(e.currentTarget.dataset.name){let n=i.rollOptions.find(r=>r.target==e.currentTarget.dataset.name&&e.currentTarget.dataset.type==r.type);n[e.currentTarget.dataset.field]=Number(t.val())}else i[e.currentTarget.dataset.field]=Number(t.val());q.rerenderGC(s,i)}static async updateInformationRoll(e,t,a){let s=[],i=await fromUuid(e.uuid),n=t.result.qualityStep||0;for(let r=1;r<=n;r++){let o=`qs${r}`;i.system[o]&&s.push(i.system[o])}if(t.result.successLevel>1&&i.system.crit?s.push(i.system.crit):t.result.successLevel<-1&&i.system.botch?s.push(i.system.botch):i.system.fail&&!n&&s.push(i.system.fail),s.length>0){await Promise.all(s.map(async o=>await TextEditor.enrichHTML(o,{async:!0}))),s.unshift(`

    ${i.name}

    `);let r=f.chatDataSetup(s.join(""));e.recipients.length&&(r.whisper=e.recipients),ChatMessage.create(r)}}static async informationRequestRoll(e){let t=e.currentTarget.dataset.mod,a=e.currentTarget.dataset.uuid,{actor:s,tokenId:i}=se._getActor();if(!s)return;let n=game.settings.get("dsa5","informationDistribution"),r=[];n==1?(r=game.users.filter(m=>m.isGM).map(m=>m.id),r.push(game.user.id)):n==2&&(r=game.users.filter(m=>m.isGM).map(m=>m.id));let o={modifier:t,postFunction:{functionName:"game.dsa5.apps.RequestRoll.updateInformationRoll",uuid:a,recipients:r}},c=s.items.find(m=>m.name==e.currentTarget.dataset.skill&&m.type=="skill");s.setupSkill(c,o,i).then(async m=>{m.testData.opposable=!1;let d=await s.basicTest(m);this.updateInformationRoll(o.postFunction,d)})}static chatListeners(e){e.on("change",".editGC",t=>q.editGC(t)),e.on("click",".request-roll",t=>{let a=t.currentTarget.dataset;q.requestRoll(a.type,a.name,Number(a.modifier)||0)}),e.on("click",".request-gc",t=>{let a=t.currentTarget.dataset;q.requestGC(a.type,a.name,$(t.currentTarget).parents(".message").attr("data-message-id"),Number(a.modifier)||0)}),e.on("click",".removeGC",t=>q.removeGCEntry(t)),e.on("click",".removeSkillFromGC",t=>q.removeSkillFromGC(t)),e.on("click",".addSkillToGC",t=>q.addSkillToGC(t)),e.on("click",".informationRequestRoll",t=>q.informationRequestRoll(t))}};u(q,"RequestRoll");var Vt,Kt,ye,dt=class extends MeasuredTemplate{constructor(){super(...arguments);aa(this,Vt,void 0);aa(this,Kt,0);aa(this,ye,void 0)}static async placeTemplateFromChat(t){let a=$(t.currentTarget).parents(".message").attr("data-message-id"),s=game.messages.get(a),i=s.flags.data.preData.source,n=s.flags.data.postData,r=this.fromItem(i,n.qualityStep);r&&r.drawPreview()}static fromItem(t,a){let s=t.system.target||{},i=game.dsa5.config.areaTargetTypes[s.type];if(!i||!s.value)return null;let n=Number(Roll.safeEval(`${s.value}`.replace(/(qs|ql)/gi,a)))||1,r={t:i,user:game.user.id,distance:n,direction:0,x:0,y:0,fillColor:game.user.color,flags:{dsa5:{origin:t.uuid}}};switch(i){case"cone":r.angle=Number(s.angle)||CONFIG.MeasuredTemplate.defaults.angle;break;case"rect":r.distance=Math.hypot(n,n),r.width=n,r.direction=45;break;case"ray":r.width=s.width&&Number(Roll.safeEval(`${s.width}`.replace(/(qs|ql)/gi,a)))||canvas.dimensions.distance;break}let o=CONFIG.MeasuredTemplate.documentClass,c=new o(r,{parent:canvas.scene}),m=new this(c);return m.item=t,m.actorSheet=t.actor?.sheet||null,m}drawPreview(){let t=canvas.activeLayer;return this.draw(),this.layer.activate(),this.layer.preview.addChild(this),this.activatePreviewListeners(t)}activatePreviewListeners(t){return new Promise((a,s)=>{sa(this,Vt,t),sa(this,ye,{cancel:this._onCancelPlacement.bind(this),confirm:this._onConfirmPlacement.bind(this),move:this._onMovePlacement.bind(this),resolve:a,reject:s,rotate:this._onRotatePlacement.bind(this)}),canvas.stage.on("mousemove",ve(this,ye).move),canvas.stage.on("mousedown",ve(this,ye).confirm),canvas.app.view.oncontextmenu=ve(this,ye).cancel,canvas.app.view.onwheel=ve(this,ye).rotate})}async _finishPlacement(t){this.layer._onDragLeftCancel(t),canvas.stage.off("mousemove",ve(this,ye).move),canvas.stage.off("mousedown",ve(this,ye).confirm),canvas.app.view.oncontextmenu=null,canvas.app.view.onwheel=null,ve(this,Vt).activate(),await this.actorSheet?.maximize()}_onMovePlacement(t){t.stopPropagation();let a=Date.now();if(a-ve(this,Kt)<=20)return;let s=t.data.getLocalPosition(this.layer),i=canvas.grid.getSnappedPosition(s.x,s.y,2);this.document.updateSource({x:i.x,y:i.y}),this.refresh(),sa(this,Kt,a)}_onRotatePlacement(t){t.ctrlKey&&t.preventDefault(),t.stopPropagation();let a=canvas.grid.type>CONST.GRID_TYPES.SQUARE?30:15,s=t.shiftKey?a:5,i={direction:this.document.direction+s*Math.sign(t.deltaY)};this.document.updateSource(i),this.refresh()}async _onConfirmPlacement(t){await this._finishPlacement(t);let a=canvas.grid.getSnappedPosition(this.document.x,this.document.y,2);this.document.updateSource(a),ve(this,ye).resolve(canvas.scene.createEmbeddedDocuments("MeasuredTemplate",[this.document.toObject()]))}async _onCancelPlacement(t){await this._finishPlacement(t),ve(this,ye).reject()}};u(dt,"MeasuredTemplateDSA"),Vt=new WeakMap,Kt=new WeakMap,ye=new WeakMap;var Ke=class{static async applyEffect(e,t){let a=game.messages.get(e),s=getProperty(a,"flags.dsa5.hasEffect"),i=getProperty(a,"flags.dsa5.options")||{};if(s){let n=["damageModifier","gearDamaged","gearLost","resistEffect","malus","selfDamage","nextAction"],r=[],o;if(t=="self"){let m=f.getSpeaker(i.speaker);r.push(m),o=i.source?m.items.get(i.source):void 0}else r=Array.from(game.user.targets).map(m=>m.actor);for(let m of n){let d=getProperty(s,m);d&&(await Ke[m](d,t,r,o,e,a)||console.warn(`Table effect for <${m} not working yet`,d,t,r,o))}let c=game.i18n.format("ActiveEffects.appliedEffect",{source:game.i18n.localize("table"),target:r.map(m=>m.name).join(", ")});await a.update({content:a.content.replace(/hideAnchor">/,`hideAnchor">`)})}}static async damageModifier(e,t,a,s){}static async nextAction(e,t,a,s){}static async opportunityAttack(e,t,a,s){}static async gearDamaged(e,t,a,s){if(s&&["meleeweapon","rangeweapon"].includes(s.type)){let i=getProperty(s,"system.effect.attributes")||"";return new RegExp(`(${I.magical}|${I.clerical})`,"i").test(i)?await s.update({"system.worn.value":!1}):await W.absoluteDamageLevelToItem(s,e),!0}}static async gearLost(e,t,a,s){if(s&&["meleeweapon","rangeweapon"].includes(s.type)){if(await s.update({"system.worn.value":!1}),e.distance){let i=await new Roll(e.distance).evaluate({async:!0}),n=await i.render(),r=game.i18n.format("WEAPON.dropped",{distance:i.total});ChatMessage.create(f.chatDataSetup(`

    ${r}

    ${n}`))}return!0}}static async resistEffect(e,t,a,s,i){for(let n of a){let r=[{skill:e.roll,mod:e.modifier||0,effect:{_id:"botchEffect",name:e.fail.description},target:n,token:n.token?n.token.id:void 0}];Q.createResistRollMessage(r,i,t)}return!0}static evaluateTargetArg(e,t){let a=t,s=!0;if(e.target=="victim"){let i=Array.from(game.user.targets).map(n=>n.actor);i.length?a=i:(s=!1,ui.notifications.warn("DSAError.noVictim"))}return{hasTargets:s,finalTargets:a}}static async malus(e,t,a,s){let{hasTargets:i,finalTargets:n}=this.evaluateTargetArg(e,a);for(let r of e){let o=!i&&r.noTarget,c=o?r.noTarget.systemEffect:r.systemEffect,m=o?r.noTarget.level:r.level||1,d=o?r.noTarget.changes:r.changes,p=o?r.noTarget.duration:r.duration;if(c){let g=CONFIG.statusEffects.find(h=>h.id==c);if(!d){d=duplicate(g.changes);let h=d.find(w=>w.key==`system.condition.${c}`);h&&(h.value=m)}let y;if(d){let h=game.i18n.localize(`CONDITION.${c}`)+" - "+game.i18n.localize("botchCritEffect");y=new X().effectDummy(h,d,p||{}),y.icon=g.icon}else y=c;for(let h of n)await h.addCondition(y);return!0}else if(d){let g=new X().effectDummy(game.i18n.localize("botchCritEffect"),d||[],p||{});mergeObject(g,{flags:{dsa5:{hideOnToken:!1,hidePlayers:!1}}});for(let y of n)await y.addCondition(g);return!0}}}static async selfAttack(e,t,a,s){let{hasTargets:i,finalTargets:n}=this.evaluateTargetArg(e,a)}static async selfDamage(e,t,a,s){let{hasTargets:i,finalTargets:n}=this.evaluateTargetArg(e,a);if(s){let r=f.toObjectIfPossible(s);for(let o of n){let c=o.items.filter(g=>g.type=="combatskill").map(g=>T._calculateCombatSkillValues(g.toObject(),o.system)),m;e.damage?m={damagedie:e.damage,damageAdd:""}:s.type=="rangeweapon"?m=T._prepareRangeWeapon(r,[],c,o):s.type=="meleeweapon"?m=T._prepareMeleeWeapon(r,c,o):m=s.system.traitType.value=="meleeAttack"?T._prepareRangeTrait(r):T._prepareMeleetrait(r);let d=(m.damagedie+m.damageAdd).replace(/wWD/g,"d"),p=await new Roll(`(${d})*${e.multiplier||1}${e.modifier||""}`).evaluate({async:!0});await o.applyDamage(Math.round(p.total)),ChatMessage.create(f.chatDataSetup(await p.render()))}return!0}else{for(let r of n){let o=await new Roll("1d6").evaluate({async:!0});await r.applyDamage(Math.round(o.total)),ChatMessage.create(f.chatDataSetup(await o.render()))}return!0}}};u(Ke,"TableEffects");var Ct=u(async(l,e,t=1)=>{let a=game.messages.get(l.attr("data-message-id")),s=a.flags.opposeData,i=s?.speakerDefend,n=f.getSpeaker(i);if(!n.isOwner)return ui.notifications.error(game.i18n.localize("DSAError.DamagePermission"));await n.applyDamage(s.damage[e]*t);let r={"flags.data.damageApplied":!0,content:a.content.replace(/hideAnchor">/,`hideAnchor">`)};game.user.isGM?await a.update(r):game.socket.emit("system.dsa5",{type:"updateMsg",payload:{id:l.attr("data-message-id"),updateData:r}})},"applyDamage");function Ii(){let l=u((N,D)=>f.fateAvailable(N,D),"fateAvailable"),e=u(function(N,D="damage.value"){let A=game.messages.get(N.attr("data-message-id")).flags.opposeData,G=A?f.getSpeaker(A.speakerDefend)?.isOwner:!1;return((game.user.isGM||G)&&N.find(".opposed-card").length||N.find(".dice-roll").length)&&(getProperty(A,D)||0)>0},"canHurt"),t=u(function(N){return e(N,"damage.sp")},"canHurtSP"),a=u(function(N){let D=game.messages.get(N.attr("data-message-id"));return D.speaker.actor&&D.flags.data&&(game.actors.get(D.speaker.actor).isOwner||game.user.isGM)?["liturgy","ceremony","spell","ritual","magicalsign"].includes(D.flags.data.preData.source.type)||getProperty(D.flags.data.preData,"calculatedSpellModifiers.costsMana"):!1},"canCostMana"),s=u(function(N){if(game.user.isGM&&game.settings.get("dsa5","hideOpposedDamage")){let D=game.messages.get(N.attr("data-message-id"));return"hideData"in D.flags&&D.flags.hideData}return!1},"canUnhideData"),i=u(function(N){if(game.user.isGM&&game.settings.get("dsa5","hideOpposedDamage")){let D=game.messages.get(N.attr("data-message-id"));return"hideData"in D.flags&&!D.flags.hideData}return!1},"canHideData"),n=u(function(N,D=!1){let A=game.messages.get(N.attr("data-message-id"));if(A.speaker.actor&&A.flags.data&&A.flags.data.postData.successLevel>-2){let G=game.actors.get(A.speaker.actor);if(G.isOwner&&l(G,D)){let Z=A.flags.data.preData.source.type,ke=A.flags.data.preData.mode||"";["skill","spell","liturgy","ritual","ceremony"].includes(Z)&&(Z="char");let we=game.i18n.localize(`SCHIPSKILLS.${Z}${ke}`);return!A.flags.data.fateImproved&&G.items.getName(we)}}return!1},"canImproveRoll"),r=u(function(N){return n(N,!0)},"canImproveRollGroup"),o=u(function(N,D=!1){let A=game.messages.get(N.attr("data-message-id"));if(A.speaker.actor&&A.flags.data){let G=game.actors.get(A.speaker.actor);if(G.isOwner&&l(G,D)&&!A.flags.data.fatePointAddQSUsed)return A.flags.data.postData.successLevel>0&&A.flags.data.postData.qualityStep!=null}return!1},"canIncreaseQS"),c=u(function(N){return o(N,!0)},"canIncreaseQSGroup"),m=u(function(N){let D=game.messages.get(N.attr("data-message-id"));if(D.speaker.actor&&D.flags.data){let A=game.actors.get(D.speaker.actor);if(A.isOwner)return A.items.find(G=>G.name==`${game.i18n.localize("LocalizedIDs.aptitude")} (${D.flags.data.preData.source.name})`)!=null&&!D.flags.data.talentedRerollUsed}return!1},"isTalented"),d=u(function(N,D=!1){let A=game.messages.get(N.attr("data-message-id"));if(A.speaker.actor&&A.flags.data){let G=game.actors.get(A.speaker.actor);if(G.isOwner&&l(G,D))return A.flags.data.postData.damageRoll!=null&&!A.flags.data.fatePointDamageRerollUsed}return!1},"canRerollDamage"),p=u(function(N){return d(N,!0)},"canRerollDamageGroup"),g=u(function(N,D=!1){let A=game.messages.get(N.attr("data-message-id"));if(A.speaker.actor&&A.flags.data){let G=game.actors.get(A.speaker.actor);if(G.isOwner&&l(G,D))return!A.flags.data.fatePointRerollUsed&&A.flags.data.postData.rollType!="regenerate"}return!1},"canReroll"),y=u(function(N){return g(N,!0)},"canRerollGroup"),h=u(function(N){let D=game.messages.get(N.attr("data-message-id"));return D.speaker.actor&&D.flags.data&&game.actors.get(D.speaker.actor).isOwner&&["LeP","KaP","AsP"].some(G=>getProperty(D.flags,`data.postData.${G}`)!=null)?!D.flags.data.healApplied:!1},"canHeal"),w=u(function(N){if(game.user.isGM){let D=game.messages.get(N.attr("data-message-id"));if("hideData"in D.flags){let A=!D.flags.hideData,G=$(D.content);G.find(".hideAnchor")[A?"addClass":"removeClass"]("hideData"),G=$("
    ").append(G),D.update({content:G.html(),"flags.hideData":A})}}},"showHideData"),z=u(N=>{let D=game.messages.get(N.data("messageId"));return!D||!canvas.tokens?!1:D.isRoll&&D.isContentVisible&&canvas.tokens.controlled.length&&N.find(".dice-roll").length},"canApplyDefaultRolls"),v=u((N,D,A=0)=>{let G=game.messages.get(N.attr("data-message-id"));game.actors.get(G.speaker.actor).useFateOnRoll(G,D,A)},"useFate"),S=u((N,D,A=1)=>{let Z=game.messages.get(N.data("messageId")).rolls[0];return Promise.all(canvas.tokens.controlled.map(ke=>{let we=ke.actor,nt=Math.round((D!="sp"?Z.total-T.armorValue(we).armor:Z.total)*A);return we.applyDamage(Math.max(0,nt))}))},"applyChatCardDamage"),x=u(async N=>{let D=game.messages.get(N.attr("data-message-id")),A=D.flags.data,G=f.getSpeaker(D.speaker);if(!G.isOwner)return ui.notifications.error(game.i18n.localize("DSAError.DamagePermission"));let Z=A.preData.calculatedSpellModifiers.maintainCost.trim(),ke=["ritual","spell"].includes(A.preData.source.type)||getProperty(A.preData.calculatedSpellModifiers,"costsMana")?"AsP":"KaP",we=await G.applyMana(A.preData.calculatedSpellModifiers.finalcost,ke);if(Z&&Z!=0&&we&&A.postData.successLevel>0){let nt=A.preData.source.name;try{let jt=Z.match(/^\d{1,3}/)[0],ft=Z.replace(/^\d{1,3}/,"").match(/\d{1,3}/);ft=ft&&Number(ft[0])||1;let ht={name:`${nt} (${game.i18n.localize("maintainCost")})`,icon:"icons/svg/daze.svg",flags:{dsa5:{description:Z,maintain:jt,payType:ke}},changes:[],duration:{}},ea=[{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.combatRounds"),"gi"),seconds:5},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.minutes"),"gi"),seconds:60},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.hours"),"gi"),seconds:3600},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.days"),"gi"),seconds:3600*24},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.seconds"),"gi"),seconds:1},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.weeks"),"gi"),seconds:3600*24*7},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.months"),"gi"),seconds:3600*24*30},{regEx:new RegExp(game.i18n.localize("DSAREGEXmaintain.years"),"gi"),seconds:3600*24*350}];for(let k of ea)if(k.regEx.test(Z)){let V=Number(ft)*k.seconds;ht.duration.seconds=V,ht.duration.rounds=ht.duration.seconds/5;break}await G.addCondition(ht)}catch{console.error(`Could not parse duration '${Z}' of '${nt}'`)}}await D.update({"flags.data.manaApplied":!0,content:D.content.replace(//,'')})},"payMana"),F=u(()=>game.i18n.localize(game.combat?.isBrawling?"CHATCONTEXT.ApplyDamagePP":"CHATCONTEXT.ApplyDamage"),"applyDamageLabel");Hooks.on("getChatLogEntryContext",(N,D)=>{D.push({name:game.i18n.localize("CHATCONTEXT.hideData"),icon:'',condition:i,callback:A=>{w(A)}},{name:game.i18n.localize("CHATCONTEXT.showData"),icon:'',condition:s,callback:A=>{w(A)}},{name:game.i18n.localize("regenerate"),icon:'',condition:h,callback:async A=>{let G=await game.messages.get(A.attr("data-message-id")),Z=f.getSpeaker(G.speaker);if(!Z.isOwner)return ui.notifications.error(game.i18n.localize("DSAError.DamagePermission"));await G.update({"flags.data.healApplied":!0,content:G.content.replace(/<\/div>$/,'
    ')}),await Z.applyRegeneration(G.flags.data.postData.LeP,G.flags.data.postData.AsP,G.flags.data.postData.KaP)}},{name:game.i18n.localize("CHATCONTEXT.ApplyMana"),icon:'',condition:a,callback:async A=>{x(A)}},{name:F(),icon:'',condition:e,callback:A=>{Ct(A,"value")}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP"),icon:'',condition:t,callback:A=>{Ct(A,"sp")}},{name:F(),icon:'',condition:z,callback:A=>{S(A,"value")}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP"),icon:'',condition:z,callback:A=>{S(A,"sp")}},{name:game.i18n.localize("CHATCONTEXT.Reroll"),icon:'',condition:g,callback:A=>{v(A,"reroll")}},{name:game.i18n.localize("CHATCONTEXT.RerollGroup"),icon:'',condition:y,callback:A=>{v(A,"reroll",1)}},{name:game.i18n.localize("CHATCONTEXT.talentedReroll"),icon:'',condition:m,callback:A=>{v(A,"isTalented")}},{name:game.i18n.localize("CHATCONTEXT.AddQS"),icon:'',condition:o,callback:A=>{v(A,"addQS")}},{name:game.i18n.localize("CHATCONTEXT.AddQSGroup"),icon:'',condition:c,callback:A=>{v(A,"addQS",1)}},{name:game.i18n.localize("CHATCONTEXT.rerollDamage"),icon:'',condition:d,callback:A=>{v(A,"rerollDamage")}},{name:game.i18n.localize("CHATCONTEXT.rerollDamageGroup"),icon:'',condition:p,callback:A=>{v(A,"rerollDamage",1)}},{name:game.i18n.localize("CHATCONTEXT.improveFate"),icon:'',condition:n,callback:A=>{v(A,"Improve")}},{name:game.i18n.localize("CHATCONTEXT.improveFateGroup"),icon:'',condition:r,callback:A=>{v(A,"Improve",1)}}),game.settings.get("dsa5","doubleDamageOptions")&&D.push({name:F()+" x2",icon:'',condition:e,callback:A=>{Ct(A,"value",2)}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP")+" x2",icon:'',condition:t,callback:A=>{Ct(A,"sp",2)}},{name:F()+" x2",icon:'',condition:z,callback:A=>{S(A,"value",2)}},{name:game.i18n.localize("CHATCONTEXT.ApplyDamageSP")+" x2",icon:'',condition:z,callback:A=>{S(A,"sp",2)}})})}u(Ii,"chatContext");var _DiceDSA5=class{static async rollTest(l){let e;switch(l.source.type){case"ceremony":case"ritual":case"liturgy":case"spell":e=await this.rollSpell(l);break;case"skill":e=await this.rollTalent(l);break;case"combatskill":e=await this.rollCombatskill(l);break;case"trait":l.mode=="parry"&&await this.updateDefenseCount(l),e=l.mode=="damage"?await this.rollDamage(l):await this.rollCombatTrait(l);break;case"regenerate":e=await this.rollRegeneration(l);break;case"meleeweapon":case"rangeweapon":l.mode=="parry"&&await this.updateDefenseCount(l),e=l.mode=="damage"?await this.rollDamage(l):await this.rollWeapon(l);break;case"dodge":await this.updateDefenseCount(l),e=await this.rollStatus(l);break;case"poison":case"disease":e=await this.rollItem(l);break;case"fallingDamage":e=await this.rollFallingDamage(l);break;default:e=await this.rollAttribute(l)}return mergeObject(e,deepClone(l.extra)),e}static async rollDices(l,e){if(!l.roll){let t=game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration,a;switch(l.source.type){case"liturgy":case"spell":case"ceremony":case"ritual":case"skill":a=await new Roll("1d20+1d20+1d20").evaluate({async:!0}),mergeObject(a.dice[0].options,t(l.source.system.characteristic1.value)),mergeObject(a.dice[1].options,t(l.source.system.characteristic2.value)),mergeObject(a.dice[2].options,t(l.source.system.characteristic3.value));break;case"regenerate":let s=[];l.regenerateLeP&&s.push([game.settings.get("dsa5","lessRegeneration")?"1d3":"1d6"]),l.extra.actor.isMage&&l.regenerateAsP&&s.push("1d6"),l.extra.actor.isPriest&&l.regenerateKaP&&s.push("1d6"),a=await new Roll(s.join("+")).evaluate({async:!0}),l.regenerateLeP&&mergeObject(a.dice[0].options,t("mu")),l.extra.actor.isMage&&l.regenerateAsP&&mergeObject(a.dice[s.length-1].options,t("ge")),l.extra.actor.isPriest&&l.regenerateKaP&&mergeObject(a.dice[s.length-1].options,t("in")),l.extra.actor.isMage&&l.regenerateAsP&&l.extra.actor.isPriest&&l.regenerateKaP&&mergeObject(a.dice[s.length-2].options,t("ge"));break;case"meleeweapon":case"rangeweapon":case"weaponless":case"combatskill":case"trait":if(l.mode=="damage"){let o=await this.damageFormula(l);a=await new Roll(o).evaluate({async:!0});for(let c=0;c{r.actor&&n.push({name:r.actor.name,id:r.id,img:r.actor.img})}),mergeObject(l.data,{hasSituationalModifiers:i.length>0,situationalModifiers:i,rollMode:l.data.rollMode||a,rollModes:CONFIG.Dice.rollModes,defenseCount:await this.getDefenseCount(e),targets:n}),mergeObject(t,{user:game.user.id}),e.extra.options.bypass)return t.rollMode=e.extra.options.rollMode||a,e.situationalModifiers||(e.situationalModifiers=[]),{testData:e,cardOptions:t};{let r=ee.getDialogForItem(e,l.data),o=await renderTemplate(l.template,l.data);return new Promise((c,m)=>{new r({title:l.title,content:o,buttons:r.getRollButtons(e,l,c,m),default:"rollButton"}).recallSettings(e.extra.speaker,e.source,e.mode,l.data).render(!0)})}}static async getDefenseCount(l){return game.combat?await game.combat.getDefenseCount(l.extra.speaker):0}static async _rollConfirm(){return await new Roll("1d20").evaluate({async:!0})}static async _rollSingleD20(l,e,t,a,s,i="",n=1){let r="",o=[];e+=a,e=Math.round(e*n);let c=e-l.terms[0].results[0].result,m=game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration(t);o.push({char:t,res:l.terms[0].results[0].result,suc:c>=0,tar:e});let d=c>=0?1:-1,p=20,g=1;if(s.source.type=="meleeweapon"&&(p=Math.min(s.extra.actor.system.meleeStats.botch,s.source.system.botch),g=Math.max(s.extra.actor.system.meleeStats.crit,s.source.system.crit)),s.source.type=="rangeweapon"&&(p=Math.min(s.extra.actor.system.rangeStats.botch,s.source.system.botch),g=Math.max(s.extra.actor.system.rangeStats.crit,s.source.system.crit)),P.improvisedWeapon.test(s.source.name)&&(R.hasAbility(s.extra.actor,game.i18n.localize("LocalizedIDs.improvisedWeaponMaster"))||(p=Math.min(19,p)),this._appendSituationalModifiers(s,`${game.i18n.localize("CHAR.ATTACK")} - ${game.i18n.localize("WEAPON.improvised")}`,2,"defenseMalus")),s.situationalModifiers.find(y=>y.name==game.i18n.localize("opportunityAttack")&&y.value!=0)&&(p=50,g=-50),l.terms[0].results.filter(y=>y.result<=g).length==1)if(r=game.i18n.localize("CriticalSuccess"),game.settings.get("dsa5","noConfirmationRoll"))d=3;else{let y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"confirmationRoll",s.extra.options),h=e-y.terms[0].results[0].result;if(O.hasVantage(s.extra.actor,`${game.i18n.localize("LocalizedIDs.weaponAptitude")} (${i})`)&&!(h>=0)){let w=y.terms[0].results[0].result;y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"LocalizedIDs.weaponAptitude",s.extra.options),h=e-y.terms[0].results[0].result,r+=", "+game.i18n.format("usedWeaponExpertise",{a:w,b:y.terms[0].results[0].result})}this._addRollDiceSoNice(s,y,m),o.push({char:t,res:y.terms[0].results[0].result,suc:h>=0,tar:e}),d=h>=0?3:2}else if(l.terms[0].results.filter(y=>y.result>=p).length==1)if(r=game.i18n.localize("CriticalFailure"),game.settings.get("dsa5","noConfirmationRoll"))d=-3;else{let y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"confirmationRoll",s.extra.options),h=e-y.terms[0].results[0].result;if(O.hasVantage(s.extra.actor,`${game.i18n.localize("LocalizedIDs.weaponAptitude")} (${i})`)&&!(h>=0)){let w=y.terms[0].results[0].result;y=await _DiceDSA5.manualRolls(await _DiceDSA5._rollConfirm(),"LocalizedIDs.weaponAptitude",s.extra.options),h=e-y.terms[0].results[0].result,r+=", "+game.i18n.format("usedWeaponExpertise",{a:w,b:y.terms[0].results[0].result})}this._addRollDiceSoNice(s,y,m),o.push({char:t,res:y.terms[0].results[0].result,suc:h>=0,tar:e}),d=h>=0?-2:-3}return r==""?r=game.i18n.localize(c>=0?"Success":"Failure"):game.settings.get("dsa5","noConfirmationRoll")||(Math.abs(d)==3?r=`${game.i18n.localize("confirmed")} ${r}`:Math.abs(d)==2&&(r=`${game.i18n.localize("unconfirmed")} ${r}`)),{successLevel:d,characteristics:o,description:r,preData:s,modifiers:a,extra:{}}}static async rollFallingDamage(l){let e=l.roll,t=[];for(let s of e.terms[0].results)t.push({char:"damage",res:s.result,suc:!1});return{rollType:"fallingDamage",preData:l,modifiers:await this._situationalModifiers(l),extra:{},damage:Math.max(0,e.total),formula:e.formula,characteristics:t}}static async rollRegeneration(l){let e=await this._situationalModifiers(l),t=l.roll,a=[],s={rollType:"regenerate",preData:l,modifiers:e,extra:{}},i=[];l.regenerateLeP&&i.push("LeP"),l.extra.actor.system.isMage&&l.regenerateAsP&&i.push("AsP"),l.extra.actor.system.isPriest&&l.regenerateKaP&&i.push("KaP");let n=0;if(l.extra.actor.effects.some(o=>o.statuses.includes("sick"))){this._appendSituationalModifiers(l,game.i18n.localize("CONDITION.sick"),"*0");for(let o of i)a.push({char:o,res:0,die:"d6"}),s[o]=0,n+=2}else for(let o of i)this._appendSituationalModifiers(l,game.i18n.localize(`LocalizedIDs.regeneration${o}`),O.vantageStep(l.extra.actor,game.i18n.localize(`LocalizedIDs.regeneration${o}`)),o),this._appendSituationalModifiers(l,game.i18n.localize(`LocalizedIDs.weakRegeneration${o}`),O.vantageStep(l.extra.actor,game.i18n.localize(`LocalizedIDs.weakRegeneration${o}`))*-1,o),this._appendSituationalModifiers(l,game.i18n.localize(`LocalizedIDs.advancedRegeneration${o}`),R.abilityStep(l.extra.actor,game.i18n.localize(`LocalizedIDs.advancedRegeneration${o}`)),o),this._appendSituationalModifiers(l,`${game.i18n.localize(`CHARAbbrev.${o}`)} ${game.i18n.localize("Modifier")}`,l[`${o}Modifier`],o),this._appendSituationalModifiers(l,`${game.i18n.localize(`CHARAbbrev.${o}`)} ${game.i18n.localize("regenerate")}`,l[`regeneration${o}`],o),a.push({char:o,res:t.terms[n].results[0].result,die:"d6"}),s[o]=Math.round(Math.max(0,Number(t.terms[n].results[0].result)+Number(e)+await this._situationalModifiers(l,o))*Number(l.regenerationFactor)),n+=2;return s.characteristics=a,s}static async rollStatus(l){let e=l.roll||await new Roll("1d20").evaluate({async:!0}),t=await this._rollSingleD20(e,l.source.system.max,l.extra.statusId,await this._situationalModifiers(l),l,"",this._situationalMultipliers(l));t.rollType="dodge";let a=l.extra.statusId=="dodge";return a&&t.successLevel==3?await U.tableEnabledFor("criticalMeleeDefense")?t.description+=U.rollCritBotchButton("criticalMeleeDefense",!1,l,l):t.description+=U.defaultParryCrit():a&&t.successLevel==-3&&(await U.tableEnabledFor("Defense")?t.description+=U.rollCritBotchButton("Defense",!0,l,l):t.description+=await U.defaultBotch()),t}static async rollAttribute(l){let e=l.roll?l.roll:await new Roll("1d20").evaluate({async:!0});this._appendSituationalModifiers(l,game.i18n.localize("Difficulty"),l.testDifficulty);let t=await this._rollSingleD20(e,l.source.system.value,l.extra.characteristicId,await this._situationalModifiers(l),l,"",this._situationalMultipliers(l));return t.rollType="attribute",t}static async damageFormula(l){let e;if(l.source.type=="meleeweapon"){let t=T._calculateCombatSkillValues(l.extra.actor.items.find(a=>a.type=="combatskill"&&a.name==l.source.system.combatskill.value),l.extra.actor.system);e=T._prepareMeleeWeapon(l.source,[t],l.extra.actor)}else if(l.source.type=="rangeweapon"){let t=T._calculateCombatSkillValues(l.extra.actor.items.find(a=>a.type=="combatskill"&&a.name==l.source.system.combatskill.value),l.extra.actor.system);e=T._prepareRangeWeapon(l.source,[],[t],l.extra.actor)}else e=l.source.system;return l.source.system.damage.value.replace(/[Ww]/g,"d")+`+${e.extraDamage||0}`}static async rollDamage(l){let e=await this._situationalModifiers(l),t=[],a=l.roll,s=a.total+e;for(let i of a.terms)if(i instanceof Die||i.class=="Die")for(let n of i.results)t.push({char:l.mode,res:n.result,die:"d"+i.faces});return{rollType:"damage",damage:s,characteristics:t,preData:l,modifiers:e,extra:{}}}static async _situationalModifiers(l,e=""){let t=0;for(let a of l.situationalModifiers){if(a.value==null)continue;let s=Number(a.value)||await this._stringToRoll(a.value);t+=a.type==e||e==""&&a.type==null?s:0}return t}static _situationalPartCheckModifiers(l){return l.situationalModifiers.reduce(function(e,t){if(t.type=="TPM"){let a=t.value.split("|");return a.length!=3||(e[0]=e[0]+Number(a[0]),e[1]=e[1]+Number(a[1]),e[2]=e[2]+Number(a[2])),e}else return e},[0,0,0])}static _situationalMultipliers(l){return l.situationalModifiers.reduce(function(e,t){return e*(t.type=="*"&&Number(`${t.value}`.replace(/,/,"."))||1)},1)}static _appendSituationalModifiers(l,e,t,a=""){let s=l.situationalModifiers.find(i=>i.name==e);s?s.value=t:l.situationalModifiers.push({name:e,value:t,type:a})}static async rollCombatTrait(l){let e=l.roll||await new Roll("1d20").evaluate({async:!0}),t=l.source,a=t.system.traitType.value=="meleeAttack",s=l.mode=="attack";if(a){let o={system:{combatskill:{value:"-"},reach:{value:t.system.reach.value}}};this._appendSituationalModifiers(l,game.i18n.localize("opposingWeaponSize"),this._compareWeaponReach(o,l))}let i=await this._rollSingleD20(e,Number(s?t.system.at.value:t.system.pa),l.mode,await this._situationalModifiers(l),l,"",this._situationalMultipliers(l)),n=i.successLevel>0;await this.detailedWeaponResult(i,l,t),s&&n&&await _DiceDSA5.evaluateDamage(l,i,t,!a,i.doubleDamage),i.rollType="weapon";let r=_DiceDSA5.parseEffect(t);return r&&(i.parsedEffect=r),i}static async _stringToRoll(l,e){let t=[],a=/\d{1}[dDwW]\d/g,s=`${l}`;s.replace(a,function(r){t.push(new Roll(r.replace(/[Ww]/,"d")).evaluate({async:!0}))});let i=await Promise.all(t),n=s.replace(a,()=>{let r=i.shift();return e&&_DiceDSA5._addRollDiceSoNice(e,r,game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration("ch")),r.total});return await Roll.safeEval(n)}static async evaluateDamage(l,e,t,a,s){let i=t.system.damage.value.replace(/[Ww]/g,"d"),n=[],r=t.dmgMultipliers||[],o=r.map(h=>`${h.name} *${h.val}`),c=[],m=0;for(let h of l.situationalModifiers){let w=0;if(h.armorPen&&c.push(h.armorPen),h.damageBonus){if(/^\*/.test(h.damageBonus)){r.push({name:h.name,val:Number(h.damageBonus.replace("*",""))});continue}let z=/^=/.test(h.damageBonus),v=`${h.damageBonus}`.replace(/^=/,""),S=await _DiceDSA5._stringToRoll(v,l);if(w=S*(h.step||1),z){i=v.replace(/[Ww]/,"d"),n.push({name:h.name,roll:S});continue}else h.damageBonus=S,m+=w}}let d=l.damageRoll?l.damageRoll:await _DiceDSA5.manualRolls(await new Roll(i).evaluate({async:!0}),"CHAR.DAMAGE",l.extra.options),p=d.total,g=0;for(let h of d.terms)if(h instanceof Die||h.class=="Die")for(let w of h.results)g+=Number(w.result),e.characteristics.push({char:"damage",res:w.result,die:"d"+h.faces});let y=p-g;if(n.length>0)o.push(n[0].name+" "+p);else{p+=m,o.push(game.i18n.localize("Roll")+" "+g),y!=0&&o.push(game.i18n.localize("weaponModifier")+" "+y),l.situationalModifiers.reduce((z,v)=>{if(v.damageBonus){let S=/^\*/.test(v.damageBonus)?v.damageBonus:Number(v.damageBonus)*(v.step||1);o.push(`${v.name} ${S}`)}},o),l.situationalModifiers.find(z=>z.name.indexOf(game.i18n.localize("CONDITION.bloodrush"))>-1)&&(p+=2,o.push(game.i18n.localize("CONDITION.bloodrush")+" "+2)),t.extraDamage&&(p=Number(t.extraDamage)+Number(p),o.push(game.i18n.localize("damageThreshold")+" "+t.extraDamage));let h=l.extra.actor.system[a?"rangeStats":"meleeStats"].damage,w=await _DiceDSA5._stringToRoll(h,l);w!=0&&(p+=w,o.push(game.i18n.localize("statuseffects")+" "+w))}s&&(p=p*s,o.push(game.i18n.format("doubleDamage",{x:s})));for(let h of r)p=p*h.val;e.armorPen=c,e.damagedescription=o.join(", "),e.damage=Math.round(p),e.damageRoll=duplicate(d)}static async rollWeapon(l){let e=l.roll||await new Roll("1d20").evaluate({async:!0}),t,a=l.source,s=a.system.combatskill.value,i=T._calculateCombatSkillValues(l.extra.actor.items.find(c=>c.type=="combatskill"&&c.name==s),l.extra.actor.system),n=a.type=="meleeweapon";n?(t=T._prepareMeleeWeapon(a,[i],l.extra.actor),l.mode=="attack"&&this._appendSituationalModifiers(l,game.i18n.localize("opposingWeaponSize"),this._compareWeaponReach(t,l))):t=T._prepareRangeWeapon(a,[],[i],l.extra.actor);let r=await this._rollSingleD20(e,t[l.mode],l.mode,await this._situationalModifiers(l),l,s,this._situationalMultipliers(l));await this.detailedWeaponResult(r,l,a),l.mode=="attack"&&r.successLevel>0&&!l.extra.counterAttack&&await _DiceDSA5.evaluateDamage(l,r,t,!n,r.doubleDamage),l.extra.counterAttack&&(f.getSpeaker(l.extra.speaker).addCondition("stunned"),r.description+=", "+f.replaceConditions(game.i18n.localize("stunnedByCounterAttack"))),r.rollType="weapon";let o=_DiceDSA5.parseEffect(t);return o&&(r.parsedEffect=o),r}static async detailedWeaponResult(l,e,t){let a=e.mode=="attack"&&!e.extra.counterAttack,s=t.type=="meleeweapon"||getProperty(t,"system.traitType.value")=="meleeAttack";switch(l.successLevel){case 3:a?(await U.tableEnabledFor("criticalAttack")?l.description+=U.rollCritBotchButton("criticalAttack",!1,e):(l.description+=U.defaultAttackCrit(!0),l.doubleDamage=2),l.halfDefense=!0):e.isRangeDefense&&await U.tableEnabledFor("criticalRangeDefense")?l.description+=U.rollCritBotchButton("criticalRangeDefense",!1,e):await U.tableEnabledFor("criticalMeleeDefense")?l.description+=U.rollCritBotchButton("criticalMeleeDefense",!1,e):l.description+=U.defaultParryCrit();break;case-3:let i=getProperty(t,"system.combatskill.value")==game.i18n.localize("LocalizedIDs.wrestle")||t.type=="trait";a&&s&&await U.tableEnabledFor("Melee")?l.description+=U.rollCritBotchButton("Melee",i,e):a&&await U.tableEnabledFor("Range")?l.description+=U.rollCritBotchButton("Range",!1,e):!a&&await U.tableEnabledFor("Defense")?l.description+=U.rollCritBotchButton("Defense",i,e):l.description+=await U.defaultBotch();break;case 2:a&&(l.description+=U.defaultAttackCrit(!1),l.halfDefense=!0);break;case-2:break}}static async _addRollDiceSoNice(l,e,t){if(l.rollMode){for(let a=0;a{new ee({title:game.i18n.localize(t.cheat?"DIALOG.cheat":"DSASETTINGS.allowPhysicalDice"),content:n,default:"ok",buttons:{ok:{icon:'',label:game.i18n.localize("yes"),callback:c=>{r([!0,c])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{r([!1,0])}}}}).render(!0)}),a){let r=[];s.find(".dieInput").each(function(o){let c=Number($(this).val());c>0&&r.push({val:c,index:o}),o++}),l.editRollAtIndex(r)}}return l}static parseEffect(l){let e=l.system.effect?l.system.effect.value:void 0,t=[];if(e){let s=/^[a-z]+\|[öäüÖÄÜa-zA-z ]+$/;for(let i of e.split(";"))if(s.test(i.trim())){let n=i.split("|").map(r=>r.trim());if(n[0]=="condition"){let r=CONFIG.statusEffects.find(o=>o.id==n[1]);t.push(` + ${game.i18n.localize(r.name)} + `)}else t.push(`${game.i18n.localize(n[0])}: ${n[1]}`)}}let a=getProperty(l,"flags.dsa5.poison");return a&&t.push(`${game.i18n.localize("poison")}: ${a.name}`),t.join(", ")}static async calculateEnergyCost(l,e,t){let a=[],s,i,n,r;if(e.successLevel<0){let o=["traditionWitch","traditionFjarning","braniborian"].map(m=>game.i18n.localize(`LocalizedIDs.${m}`)),c=t.extra.actor.items.some(m=>m.type=="specialability"&&o.includes(m.name))?3:2;e.preData.calculatedSpellModifiers.finalcost=Math.round(e.preData.calculatedSpellModifiers.finalcost/c)}if(l?(r="KaPCost",s=game.i18n.localize("LocalizedIDs.weakKarmicBody"),i=game.i18n.localize(`LocalizedIDs.${e.successLevel>0?"mightyKarmaControl":"karmaControl"}`),n={val:"kapModifier",name:"KaP"}):(r="AsPCost",s=game.i18n.localize("LocalizedIDs.weakAstralBody"),i=game.i18n.localize(`LocalizedIDs.${e.successLevel>0?"energyControl":"smallEnergyControl"}`),n={val:"aspModifier",name:"AsP"}),a.push({name:s,value:O.vantageStep(t.extra.actor,s)},{name:i,value:R.abilityStep(t.extra.actor,i)*-1},{name:`${game.i18n.localize("statuseffects")} (${game.i18n.localize("CHARAbbrev."+n.name)})`,value:t.extra.actor.system[n.val]+await this._situationalModifiers(t,r)}),a=a.filter(o=>o.value!=0),e.preData.calculatedSpellModifiers.description=a.map(o=>`${o.name} ${o.value}`).join(` +`),e.preData.calculatedSpellModifiers.finalcost=Math.max(1,Number(e.preData.calculatedSpellModifiers.finalcost)+a.reduce((o,c)=>o+c.value,0)),e.successLevel>0&&e.preData.calculatedSpellModifiers.maintainCost!=0){let o=e.preData.calculatedSpellModifiers.maintainCost.split(" ");o[0]=Math.round(Number(o[0])),e.preData.calculatedSpellModifiers.finalcost+=o[0],e.preData.calculatedSpellModifiers.maintainCost=o.join(" ")}}static async rollSpell(l){let e=await this._rollThreeD20(l),t=["ceremony","liturgy"].includes(l.source.type);if(e.rollType=l.source.type,e.preData.calculatedSpellModifiers.finalcost=e.preData.calculatedSpellModifiers.cost,e.successLevel>=2){let a=(await new Roll("1d6").evaluate({async:!0})).total;e.description=e.description+", "+game.i18n.localize("additionalFPs")+" "+a,e.result+=a,e.qualityStep=Math.min(game.settings.get("dsa5","capQSat"),Math.ceil(e.result/3)),e.preData.calculatedSpellModifiers.finalcost=Math.round(e.preData.calculatedSpellModifiers.cost/2)}else e.successLevel<=-2&&(e.description+=U.rollCritBotchButton(t?"Liturgy":"Spell",!1,l));if(e.successLevel>0&&l.source.system.effectFormula.value!=""){let a=l.source.system.effectFormula.value.replace(game.i18n.localize("CHARAbbrev.QS"),e.qualityStep).replace(/[Ww]/g,"d"),s=[];for(let o of l.situationalModifiers)o.armorPen&&s.push(o.armorPen);/(,|;)/.test(a)&&(a=a.split(/[,;]/)[e.qualityStep-1]);let i=l.damageRoll?l.damageRoll:await _DiceDSA5.manualRolls(await new Roll(a).evaluate({async:!0}),"CHAR.DAMAGE",l.extra.options);this._addRollDiceSoNice(l,i,game.dsa5.apps.DiceSoNiceCustomization.getAttributeConfiguration("damage")),e.calculatedEffectFormula=a;for(let o of i.terms)if(o instanceof Die||o.class=="Die")for(let c of o.results)e.characteristics.push({char:"effect",res:c.result,die:"d"+o.faces});let n=[],r=await _DiceDSA5._stringToRoll(l.extra.actor.system[t?"liturgyStats":"spellStats"].damage,l);r!=0&&n.push(game.i18n.localize("statuseffects")+" "+r),e.armorPen=s,e.damageRoll=i,e.damage=i.total+r,e.damagedescription=n.join(` +`)}await this.calculateEnergyCost(t,e,l);for(let a of["minorFairies","minorSpirits"]){let s=game.i18n.localize("CONDITION."+a);O.hasVantage(l.extra.actor,s)&&!l.extra.actor.effects.find(i=>i.name==s)&&(await new Roll("1d20").evaluate({async:!0})).total<=e.preData.calculatedSpellModifiers.finalcost&&(e.description+=", "+game.i18n.format("minorghostsappear",{creature:s}),f.getSpeaker(l.extra.speaker).addCondition(a))}return e}static async _rollThreeD20(l){let e=l.roll?Roll.fromData(l.roll):await new Roll("1d20+1d20+1d20").evaluate({async:!0}),t=[],a=0;this._appendSituationalModifiers(l,game.i18n.localize("Difficulty"),l.testDifficulty);let s=await this._situationalModifiers(l),i=l.source.system.talentValue.value+l.advancedModifiers.fws+await this._situationalModifiers(l,"FW"),n=this._situationalPartCheckModifiers(l,"TPM"),r=[1,2,3].map(g=>l.extra.actor.system.characteristics[l.source.system[`characteristic${g}`].value].value+s+l.advancedModifiers.chars[g-1]+n[g-1]),o=[0,1,2].map(g=>e.terms[g*2].results[0].result-r[g]);if(l.routine)i=Math.round(i/2);else for(let g of o)g>0&&(i-=g);let c=l.extra.actor.system.skillModifiers.crit,m=l.extra.actor.system.skillModifiers.botch;if(["spell","ritual"].includes(l.source.type)&&O.hasVantage(l.extra.actor,game.i18n.localize("LocalizedIDs.wildMagic"))&&(m=19),l.source.type=="skill"&&O.hasVantage(l.extra.actor,`${game.i18n.localize("LocalizedIDs.incompetent")} (${l.source.name})`)){let g=await new Roll("1d20").evaluate({async:!0}),y=o.reduce((w,z,v,S)=>z0&&(i+=await this._situationalModifiers(l,"FP"),p=Math.max(1,(i==0?1:i>0?Math.ceil(i/3):0)+(l.qualityStep!=null?Number(l.qualityStep):0))+(l.advancedModifiers.qls||0)+await this._situationalModifiers(l,"QL")),p=Math.min(game.settings.get("dsa5","capQSat"),p),p({char:l.source.system[`characteristic${g+1}`].value,res:e.terms[g*2].results[0].result,suc:o[g]<=0,tar:r[g]})),qualityStep:p,description:t,preData:l,successLevel:a,modifiers:s,extra:{}}}static async rollTalent(l){let e=await this._rollThreeD20(l);return e.rollType="talent",e}static get3D20SuccessLevel(l,e,t=20,a=1){let s=l.terms.filter(n=>n.results&&n.results[0].result<=a).length,i=l.terms.filter(n=>n.results&&n.results[0].result>=t).length;return s>=2?s:i>=2?i*-1:e>=0?1:-1}static getSuccessDescription(l){return game.i18n.localize(["AstoundingFailure","CriticalFailure","Failure","","Success","CriticalSuccess","AstoundingSuccess"][l+3])}static async rollItem(l){let e=l.roll||await new Roll("1d20+1d20+1d20").evaluate({async:!0}),t=[],a=await this._situationalModifiers(l),s=Number(l.source.system.step.value),i=[1,2,3].map(m=>10+Number(l.source.system.step.value)+a),n=[0,1,2].map(m=>e.terms[m*2].results[0].result-i[m]);for(let m of n)m>0&&(s-=m);let r=20,o=_DiceDSA5.get3D20SuccessLevel(e,s,r);t.push(_DiceDSA5.getSuccessDescription(o)),t=t.join(", ");let c={result:s,characteristics:[0,1,2].map(m=>({char:l.source.type,res:e.terms[m*2].results[0].result,suc:n[m]<=0,tar:i[m]})),qualityStep:Math.min(game.settings.get("dsa5","capQSat"),(s==0?1:s>0?Math.ceil(s/3):0)+(l.qualityStep!=null?Number(l.qualityStep):0)),description:t,preData:l,successLevel:o,modifiers:a,extra:{}};switch(l.source.type){case"poison":let m=l.source.system.duration.value.split(" / ").map(y=>y.trim()),d=l.source.system.effect.value.split(" / ").map(y=>y.trim());c.duration=m.length>1?c.successLevel>0?m[0]:m[1]:m[0],c.effect=d.length>1?c.successLevel>0?d[0]:d[1]:d[0];break;case"disease":let p=l.source.system.damage.value.split(" / ").map(y=>y.trim()),g=l.source.system.duration.value.split(" / ").map(y=>y.trim());c.damageeffect=p.length>1?c.successLevel>0?p[0]:p[1]:p[0],c.duration=g.length>1?c.successLevel>0?g[0]:g[1]:g[0];break}return c}static async updateDefenseCount(l){game.combat&&await game.combat.updateDefenseCount(l.extra.speaker)}static _compareWeaponReach(l,e){let t=e.situationalModifiers.find(i=>i.name==game.i18n.localize("LocalizedIDs.circumvent")),a=b.meleeRangesArray.indexOf(l.system.reach.value),s=b.meleeRangesArray.indexOf(e.opposingWeaponSize);return t&&s>a&&(t.value=Math.min(t.step,s-a)*2),Math.min(0,a-s)*2}static async showDiceSoNice(l,e){if(f.moduleEnabled("dice-so-nice")&&game.dice3d){let t=null,a=!1;switch(e){case"blindroll":a=!0,t=game.users.filter(i=>i.isGM).map(i=>i.id);break;case"gmroll":t=game.users.filter(i=>i.isGM).map(i=>i.id);break;case"selfroll":t=[];break}let s=game.dice3d.showForRoll(l,game.user,!0,t,a);game.settings.get("dice-so-nice","immediatelyDisplayChatMessages")||await s}}static addApplyEffectData(l){let e=l.preData.source;if(l.successLevel>0){if(["meleeweapon","rangeweapon"].includes(e.type)||e.type=="trait"&&["rangeAttack","meleeAttack"].includes(e.system.traitType.value)){if(e.effects.some(a=>!getProperty(a,"flags.dsa5.applyToOwner")))return!0}else if(["spell","liturgy","ritual","ceremony","trait","skill"].includes(e.type)&&e.effects.length>0)return!0}else if(["disease","poison"].includes(e.type))return e.effects.length>0;let t=l.preData.situationalModifiers.filter(a=>a.specAbId).map(a=>a.specAbId);if(t.length>0){let a=l.preData.extra.actor.items.filter(s=>t.includes(s._id));for(let s of a)if(s.effects.length>0)return!0}return!1}static async renderRollCard(chatOptions,testData,rerenderMessage){let applyEffect=this.addApplyEffectData(testData),immuneTo=I.checkImmunity(testData),preData=deepClone(testData.preData),hideDamage=rerenderMessage?rerenderMessage.flags.data.hideDamage:preData.mode=="attack";await Ue.postRoll({testData,preData}),Hooks.call("postProcessDSARoll",chatOptions,testData,rerenderMessage,hideDamage),await f.callAsyncHooks("postProcessDSARoll",[testData]),delete preData.extra.actor,delete testData.actor,delete testData.preData;let hasAreaTemplate=testData.successLevel>0&&preData.source.system.target&&preData.source.system.target.type in game.dsa5.config.areaTargetTypes,chatData={title:chatOptions.title,immuneTo,testData,hideData:game.user.isGM,preData,hideDamage,modifierList:preData.situationalModifiers.filter(l=>l.value!=0),applyEffect,hasAreaTemplate,showDamageToGear:await W.showDamageToGear(preData,testData)};if(preData.advancedModifiers&&(preData.advancedModifiers.chars.some(l=>l!=0)&&chatData.modifierList.push({name:game.i18n.localize("MODS.partChecks"),value:preData.advancedModifiers.chars}),preData.advancedModifiers.fws!=0&&chatData.modifierList.push({name:game.i18n.localize("MODS.FW"),value:preData.advancedModifiers.fws}),preData.advancedModifiers.qls!=0&&chatData.modifierList.push({name:game.i18n.localize("MODS.QS"),value:preData.advancedModifiers.qls})),["gmroll","blindroll"].includes(chatOptions.rollMode)&&(chatOptions.whisper=game.users.filter(l=>l.isGM).map(l=>l.id)),chatOptions.rollMode==="blindroll"?chatOptions.blind=!0:chatOptions.rollMode==="selfroll"&&(chatOptions.whisper=[game.user.id]),K.playEffect(preData.mode,preData.source,testData.successLevel,chatOptions.whisper,chatOptions.blind),chatOptions["flags.data"]={preData,postData:testData,template:chatOptions.template,rollMode:chatOptions.rollMode,isOpposedTest:chatOptions.isOpposedTest,title:chatOptions.title,hideData:chatData.hideData,hideDamage:chatData.hideDamage,isDSARoll:!0},rerenderMessage){let postFunction=getProperty(rerenderMessage,"flags.data.preData.extra.options.postFunction");postFunction&&(testData.messageId=rerenderMessage.id,await eval(postFunction.functionName)(postFunction,{result:testData,chatData},preData.source));let html=await renderTemplate(chatOptions.template,chatData),actor=ChatMessage.getSpeakerActor(rerenderMessage.speaker)||game.users.get(rerenderMessage.user).character,rollData=actor?actor.getRollData():{},enriched=await TextEditor.enrichHTML(html,{rollData,async:!0});chatOptions.content=enriched;let newMsg=await rerenderMessage.update({content:chatOptions.content,["flags.data"]:chatOptions["flags.data"]});return ui.chat.updateMessage(newMsg),newMsg}else return chatOptions.content=await renderTemplate(chatOptions.template,chatData),await ChatMessage.create(chatOptions,!1)}static async _itemRoll(l){let e=$(l.currentTarget),t=e.parents(".message").attr("data-message-id"),a=game.messages.get(t),s=a.speaker,i=e.attr("data-type"),n=e.attr("data-name"),r=f.getSpeaker(s);if(r){let o=r.items.find(c=>c.name==n&&c.type==i);if(o){let c=new C(o.toObject(),{temporary:!0}),m=e.attr("data-removecharge")?e.attr("data-removecharge")=="true":!1;if(m&&c.system.quantity.value<1){ui.notifications.error(game.i18n.localize("DSAError.NotEnoughCharges"));return}c.setupEffect().then(async d=>{await c.itemTest(d),m&&await o.update({"system.quantity.value":o.system.quantity.value-1})})}else ui.notifications.error(game.i18n.format("DSAError.notFound",{category:i,name:n}))}}static async _rollEdit(l){let e=$(l.currentTarget),t=e.parents(".message").attr("data-message-id"),a=game.messages.get(t),s=a.flags.data,i=s.preData;i.extra.actor=f.getSpeaker(i.extra.speaker).toObject(!1),i.extra.options.cheat&&delete i.extra.options.cheat;let n;switch(e.attr("data-edit-type")){case"roll":n=e.attr("data-edit-id");let o=Number(e.val());if(i.roll.terms.length>n*2){let m=Roll.fromData(i.roll);m.editRollAtIndex([{index:n,val:o}]),i.roll=m}else{let m=Roll.fromData(s.postData.damageRoll);n=n-i.roll.terms.filter(d=>d.results).length,m.editRollAtIndex([{index:n,val:o}]),i.damageRoll=m}break;case"mod":n=i.situationalModifiers.findIndex(m=>m.name==game.i18n.localize("chatEdit")),n>0&&i.situationalModifiers.splice(n,1);let c={name:game.i18n.localize("chatEdit"),value:Number(e.val())-await this._situationalModifiers(i)};i.situationalModifiers.push(c);break}let r={template:s.template,rollMode:s.rollMode,title:s.title,speaker:a.speaker,user:a.user.id};["gmroll","blindroll"].includes(r.rollMode)&&(r.whisper=game.users.filter(o=>o.isGM).map(o=>o.id)),r.rollMode==="blindroll"&&(r.blind=!0),["poison","disease"].includes(i.source.type)?new C(i.source,{temporary:!0})[`${s.postData.postFunction}`]({testData:i,cardOptions:r},{rerenderMessage:a}):f.getSpeaker(a.speaker)[`${s.postData.postFunction}`]({testData:i,cardOptions:r},{rerenderMessage:a})}static async gearDamaged(l){let e=l.currentTarget.dataset.uuid.split(";");if(e.length>1){let t=await Promise.all(e.map(a=>fromUuid(a)));Ve.showDialog(t)}else W.breakingTest(await fromUuid(e[0]))}static async rollResistPain(l){let e=l.currentTarget.dataset,t={token:e.token,actor:e.actor,scene:canvas.id},a=f.getSpeaker(t);a&&a.finishResistPainRoll()}static async wrapLock(l,e){let t=$(l.currentTarget);t.hasClass("locked")||(t.addClass("locked"),t.prepend(''),await e(l,t),setTimeout(()=>{t.removeClass("locked"),t.find("i").remove()},2e3))}static async chatListeners(l){l.on("click",".expand-mods",e=>{e.preventDefault();let t=$(e.currentTarget);t.find("i").toggleClass("fa-minus fa-plus"),t.siblings("ul,div").fadeToggle()}),l.on("click",".edit-toggle",e=>{e.preventDefault(),$(e.currentTarget).parents(".chat-card").find(".display-toggle").toggle()}),l.on("click",".botch-roll",e=>U.showBotchCard(e.currentTarget.dataset)),l.on("click",".roll-item",e=>_DiceDSA5._itemRoll(e)),l.on("click",".gearDamaged",async e=>_DiceDSA5.gearDamaged(e)),l.on("click",".applyDamage",async e=>Ct($(e.currentTarget).closest(".message"),e.currentTarget.dataset.mode)),l.on("change",".roll-edit",e=>_DiceDSA5._rollEdit(e)),l.on("click",".applyEffect",async e=>{_DiceDSA5.wrapLock(e,async(t,a)=>{let s=a.parents(".message").attr("data-message-id"),i=t.currentTarget.dataset.target;await Q.applyEffect(s,i)})}),l.on("click",".applyTableEffect",async e=>{_DiceDSA5.wrapLock(e,async(t,a)=>{let s=a.parents(".message").attr("data-message-id"),i=t.currentTarget.dataset.target;await Ke.applyEffect(s,i)})}),l.on("click",".placeTemplate",async e=>dt.placeTemplateFromChat(e)),l.on("click",".message-delete",e=>{let t=game.messages.get($(e.currentTarget).parents(".message").attr("data-message-id"));if(!t.flags.unopposeData)return;let s=canvas.tokens.get(t.flags.unopposeData.targetSpeaker.token);j.clearOpposed(s.actor)}),l.on("click",".resistEffect",e=>Q.resistEffect(e)),l.on("click",".resistPain",e=>_DiceDSA5.rollResistPain(e)),q.chatListeners(l)}};u(_DiceDSA5,"DiceDSA5");var T=class extends Actor{static async create(e,t){if(e instanceof Array||e.items)return await super.create(e,t);(!e.img||e.img=="icons/svg/mystery-man.svg")&&(e.img="icons/svg/mystery-man-black.svg");let a=await f.allSkills()||[],s=await f.allCombatSkills()||[],i=await f.allMoneyItems()||[];return e.items=[...a,...s,...i],e.type!="character"&&(e.system={status:{fatePoints:{current:0,value:0}}}),e.type!="creature"&&[void 0,0].includes(getProperty(e,"system.status.wounds.value"))&&mergeObject(e,{system:{status:{wounds:{value:16}}}}),await super.create(e,t)}_getArmorCompensation(e,t,a){let s=R.abilityStep(e,game.i18n.localize("LocalizedIDs.inuredToEncumbrance")),i=t.reduce((n,r)=>n+=Number(r.system.encumbrance.value),0);if(s>i){let n=[game.i18n.localize("CHARAbbrev.GS"),game.i18n.localize("CHARAbbrev.INI")];for(let r of n)!a[r]||(a[r]=a[r].filter(o=>o.type!="armor"))}}_getItemModifiers(){let e=[],t={};for(let a of this.items.filter(s=>["meleeweapon","rangeweapon","armor","equipment"].includes(s.type)&&getProperty(s,"system.worn.value")||["advantage","specialability","disadvantage"].includes(s.type)))this._buildGearAndAbilityModifiers(t,a),a.type=="armor"&&e.push(a);this._getArmorCompensation(this,e,t),this._applyModiferTransformations(t)}prepareDerivedData(){var t,a,s,i;let e=this.system;try{this._getItemModifiers();for(let h of Object.values(e.characteristics))h.value=h.initial+h.advances+(h.modifier||0)+h.gearmodifier;e.totalWeight=0;let n=[],r=game.i18n.localize("LocalizedIDs.familiar"),o=game.i18n.localize("LocalizedIDs.companion"),c=new Map,m=this.items.filter(h=>h.type=="equipment"&&h.system.equipmentType.value=="bags");for(let h of m)c.set(h.id,[]);for(let h of this.items)if(b.equipmentCategories.has(h.type)){let w=getProperty(h,"system.parent_id");if(w&&w!=h._id&&c.has(w)){c.get(w).push(h);continue}h.type=="armor"?(h.system.preparedWeight=parseFloat((h.system.weight.value*h.system.quantity.value).toFixed(3)),e.totalWeight+=parseFloat((h.system.weight.value*(h.system.worn.value?Math.max(0,h.system.quantity.value-1):h.system.quantity.value)).toFixed(3)),h.system.worn.value&&n.push(h)):(h.system.preparedWeight=parseFloat((h.system.weight.value*h.system.quantity.value).toFixed(3)),e.totalWeight+=Number(h.system.preparedWeight))}else switch(h.type){case"trait":h.name==r&&(e.isFamiliar=!0),h.name==o&&(e.isPet=!0);break;case"spell":case"ritual":case"magictrick":e.isMage=!0;break;case"liturgy":case"ceremony":case"blessing":e.isPriest=!0;break;case"specialability":b.sortedSpecs.magical.has(h.system.category.value)?e.isMage=!0:b.sortedSpecs.clerical.has(h.system.category.value)&&(e.isPriest=!0);break}e.isMage||(e.isMage=e.isFamiliar);for(let h of m){let w=getProperty(h,"system.parent_id");(!w||!c.has(w))&&(e.totalWeight+=this._calcBagweight(h,c,!0))}e.canAdvance=this.isOwner&&(this.type=="character"||e.isFamiliar||e.isPet),this.canAdvance=e.canAdvance,e.carrycapacity=e.characteristics.kk.value*2+e.carryModifier,e.canAdvance&&(e.details.experience.current=e.details.experience.total-e.details.experience.spent,e.details.experience.description=f.experienceDescription(e.details.experience.total)),(this.type=="character"||this.type=="npc")&&(e.status.wounds.current=e.status.wounds.initial+e.characteristics.ko.value*2,e.status.soulpower.value=(e.status.soulpower.initial||0)+Math.round((e.characteristics.mu.value+e.characteristics.kl.value+e.characteristics.in.value)/6),e.status.toughness.value=(e.status.toughness.initial||0)+Math.round((e.characteristics.ko.value+e.characteristics.ko.value+e.characteristics.kk.value)/6),e.status.wounds.min=-1*e.characteristics.ko.value),e.status.fatePoints.max=Number(e.status.fatePoints.current)+Number(e.status.fatePoints.modifier)+e.status.fatePoints.gearmodifier,this.type=="creature"&&(e.status.wounds.current=e.status.wounds.initial,e.status.astralenergy.current=e.status.astralenergy.initial,e.status.karmaenergy.current=e.status.karmaenergy.initial),e.status.wounds.max=Math.round((e.status.wounds.current+e.status.wounds.modifier+e.status.wounds.advances)*e.status.wounds.multiplier+e.status.wounds.gearmodifier),e.status.regeneration.LePmax=e.status.regeneration.LePTemp+e.status.regeneration.LePMod+e.status.regeneration.LePgearmodifier,e.status.regeneration.KaPmax=e.status.regeneration.KaPTemp+e.status.regeneration.KaPMod+e.status.regeneration.KaPgearmodifier,e.status.regeneration.AsPmax=e.status.regeneration.AsPTemp+e.status.regeneration.AsPMod+e.status.regeneration.AsPgearmodifier;let d=e.guidevalue;(t=e.status.astralenergy).rebuy||(t.rebuy=0),(a=e.status.karmaenergy).rebuy||(a.rebuy=0),(s=e.status.astralenergy).permanentLoss||(s.permanentLoss=0),(i=e.status.karmaenergy).permanentLoss||(i.permanentLoss=0),e.status.astralenergy.permanentLossSum=e.status.astralenergy.permanentLoss-e.status.astralenergy.rebuy+e.status.astralenergy.permanentGear,e.status.karmaenergy.permanentLossSum=e.status.karmaenergy.permanentLoss-e.status.karmaenergy.rebuy+e.status.karmaenergy.permanentGear,(e.isFamiliar||d&&this.type!="creature")&&(e.status.astralenergy.current=e.status.astralenergy.initial,e.status.karmaenergy.current=e.status.karmaenergy.initial,e.characteristics[d.magical]&&(e.status.astralenergy.current+=Math.round(e.characteristics[d.magical].value*e.energyfactor.magical)),e.characteristics[d.clerical]&&(e.status.karmaenergy.current+=Math.round(e.characteristics[d.clerical].value*e.energyfactor.clerical))),e.status.astralenergy.max=e.status.astralenergy.current+e.status.astralenergy.modifier+e.status.astralenergy.advances+e.status.astralenergy.gearmodifier-e.status.astralenergy.permanentLossSum,e.status.karmaenergy.max=e.status.karmaenergy.current+e.status.karmaenergy.modifier+e.status.karmaenergy.advances+e.status.karmaenergy.gearmodifier-e.status.karmaenergy.permanentLossSum,e.status.soulpower.max=e.status.soulpower.value+e.status.soulpower.modifier+e.status.soulpower.gearmodifier,e.status.toughness.max=e.status.toughness.value+e.status.toughness.modifier+e.status.toughness.gearmodifier,e.status.dodge.value=Math.round(e.characteristics.ge.value/2)+e.status.dodge.gearmodifier;let p=this.calcEncumbrance(e),g=H.isRiding(this)?H.getHorse(this):void 0;this.calcInitiative(e,p,g),e.status.dodge.max=Number(e.status.dodge.value)+Number(e.status.dodge.modifier)+Number(game.settings.get("dsa5","higherDefense"))/2,e.armorEncumbrance=this.getArmorEncumbrance(this,n),this.prepareSwarm(e),this.effectivePain(e);let y=this.statuses.has("fixated");this.calcSpeed(e,y,g),y&&(e.status.dodge.max=Math.max(0,e.status.dodge.max-4))}catch(n){console.error(`Something went wrong with preparing actor data ${this.name}: `+n+n.stack),ui.notifications.error(game.i18n.format("DSAError.PreparationError",{name:this.name})+n+n.stack)}}static async deferredEffectAddition(e,t,a){let i=(t.effects.find(r=>r.statuses.has(e))?.flags.dsa5.auto||0)!=a,n=`changing${e}`;t[n]=i,i&&await t.addCondition(e,a,!0,!0).then(()=>t[n]=void 0)}static async postUpdateConditions(e){let t=e.system,a=e.isMerchant();if(!ue.hasTrait(e,game.i18n.localize("LocalizedIDs.painImmunity"))){let n=e.woundPain(t);await this.deferredEffectAddition("inpain",e,n)}let s=t.armorEncumbrance;(e.type!="creature"||e.canAdvance)&&!a&&(s+=Math.max(0,Math.ceil((t.totalWeight-t.carrycapacity-4)/4))),await this.deferredEffectAddition("encumbered",e,s);let i=e.woundPain(t,"temporaryLeP");await this.deferredEffectAddition("stunned",e,i),O.hasVantage(e,game.i18n.localize("LocalizedIDs.blind"))&&await e.addCondition("blind"),O.hasVantage(e,game.i18n.localize("LocalizedIDs.mute"))&&await e.addCondition("mute"),O.hasVantage(e,game.i18n.localize("LocalizedIDs.deaf"))&&await e.addCondition("deaf"),a&&await e.prepareMerchant()}static async _onCreateDocuments(e,t){for(let a of e)await T.postUpdateConditions(a);return super._onCreateDocuments(e,t)}static async _onUpdateDocuments(e,t){for(let a of e)await T.postUpdateConditions(a);return super._onUpdateDocuments(e,t)}prepareSwarm(e){let t=Number(e.swarm.count)||1;if(t<2)return;e.swarm.maxwounds=e.status.wounds.max,e.status.wounds.max*=t;let a=Math.min(Math.ceil(e.status.wounds.value/e.swarm.maxwounds),t),s=Number(e.swarm.gg)||1;e.swarm.attack+=Math.min(10,Math.floor(a/s)),e.swarm.parry+=-1,e.swarm.effectiveCount=a,e.swarm.damage=Math.min(5,Math.floor(a/s))}effectivePain(e){let t=e.condition.inpain||0;t<4&&(t-=O.vantageStep(this,game.i18n.localize("LocalizedIDs.ruggedFighter"))+O.vantageStep(this,game.i18n.localize("LocalizedIDs.ruggedAnimal"))+(R.hasAbility(this,game.i18n.localize("LocalizedIDs.traditionKor"))?1:0)),t>0&&(t+=O.vantageStep(this,game.i18n.localize("LocalizedIDs.sensitiveToPain"))+O.vantageStep(this,game.i18n.localize("LocalizedIDs.fragileAnimal"))),t=Math.clamped(t,0,4),e.condition.inpain=t}woundPain(e,t="wounds"){let a=0;return e.status[t].max>0&&(this.type!="creature"||e.status[t].max>=20?(a=Math.floor((1-e.status[t].value/e.status[t].max)*4),e.status[t].value<=5&&(a=4)):a=Math.floor(5-5*e.status[t].value/e.status[t].max)),Math.clamped(a,0,4)}calcSpeed(e,t,a){if(a){if(e.status.speed.max=a.system.status.speed.max,!e.status.speed.max){let s=a.system;a.calcSpeed(s,a.hasCondition("fixated"))}e.status.speed.max=a.system.status.speed.max}else{e.status.speed.max=e.status.speed.initial+(e.status.speed.modifier||0)+(e.status.speed.gearmodifier||0),e.status.speed.max=Math.round(Math.max(0,e.status.speed.max-Math.min(4,this.calcEncumbrance(e)))*e.status.speed.multiplier),this.hasCondition("bloodrush")||(e.status.speed.max=Math.max(0,e.status.speed.max-(e.condition?.inpain||0)));let s=this.hasCondition("paralysed");s&&(e.status.speed.max=Math.round(e.status.speed.max*(1-s.flags.dsa5.value*.25))),t||this.hasCondition("rooted")||this.hasCondition("incapacitated")?e.status.speed.max=0:this.hasCondition("prone")&&(e.status.speed.max=Math.min(1,e.status.speed.max)),H.updateRiderSpeed(this,e.status.speed.max)}}calcEncumbrance(e){return Math.clamped(e.condition?.encumbered||0,0,4)}calcInitiative(e,t,a){if(this.type=="character"||this.type=="npc"?e.status.initiative.value=Math.round((e.characteristics.mu.value+e.characteristics.ge.value)/2)+(e.status.initiative.modifier||0):e.status.initiative.value=e.status.initiative.current+(e.status.initiative.modifier||0),a){if(e.status.initiative.value=a.system.status.initiative.value,!e.status.initiative.value){let s=a.system;a.calcInitiative(s,a.calcEncumbrance(s)),e.status.initiative.value=s.status.initiative.value}}else{e.status.initiative.value+=(e.status.initiative.gearmodifier||0)-Math.min(4,t);let s=Number((.01*e.status.initiative.value).toFixed(2));e.status.initiative.value*=e.status.initiative.multiplier||1,e.status.initiative.value=Math.round(e.status.initiative.value)+s}}get creatureType(){return I.creatureTypeName(this)}async prepareMerchant(){if(getProperty(this,"system.merchant.merchantType")=="loot"){if(getProperty(this,"system.merchant.locked")&&!this.hasCondition("locked"))await this.addCondition(T.lockedCondition());else if(!getProperty(this,"system.merchant.locked")){let e=this.effects.find(t=>t.statuses.has("locked"));e&&await this.deleteEmbeddedDocuments("ActiveEffect",[e.id])}}}static lockedCondition(){return{id:"locked",name:game.i18n.localize("MERCHANT.locked"),icon:"icons/svg/padlock.svg",flags:{dsa5:{noEffect:!0,hidePlayers:!0,description:game.i18n.localize("MERCHANT.locked")}}}}applyActiveEffects(){let e={};this.statuses??(this.statuses=new Set);let t=new Map;for(let o of Object.values(CONFIG.specialStatusEffects))t.set(o,this.statuses.has(o));this.statuses.clear();let a=[],s=1;for(let o of this.effects){if(o.disabled)continue;s=1;let c=o.getFlag("dsa5","value");c&&(s=Number(c));for(let m=0;m(d=foundry.utils.duplicate(d),d.effect=o,d.priority=d.priority?d.priority:d.mode*10,d)));for(let m of o.statuses)this.statuses.add(m)}let i=!0,n=this.items.filter(o=>["rangeweapon","meleeweapon","equipment","armor"].includes(o.type)&&o.system.isArtifact&&(o.system.worn.value||o.type=="equipment"&&!o.system.worn.wearable)).map(o=>o.system.artifact);this.dsatriggers={6:{},7:{}};for(let o of this.items)for(let c of o.effects)if(!c.disabled&&!!c.transfer){switch(i=!0,o.type){case"meleeweapon":case"rangeweapon":i=o.system.worn.value&&c.getFlag("dsa5","applyToOwner");break;case"armor":i=o.system.worn.value;break;case"equipment":i=!o.system.worn.wearable||o.system.worn.wearable&&o.system.worn.value;break;case"trait":i=!["meleeAttack","rangeAttack"].includes(o.system.traitType.value)||c.getFlag("dsa5","applyToOwner"),s=Number(getProperty(o.system,"step.value"))||1;break;case"ammunition":case"plant":case"consumable":case"combatskill":case"magicsign":case"poison":case"spell":case"liturgy":case"ceremony":case"ritual":case"skill":case"spellextension":i=!1;break;case"specialability":switch(o.system.category.value){case"Combat":i=[2,3].includes(Number(o.system.category.sub));break;case"staff":i=o.system.permanentEffects||n.includes(o.system.artifact);break;default:i=!0}s=Number(o.system.step.value)||1;let m=getProperty(c,"flags.dsa5.advancedFunction");this.dsatriggers.hasOwnProperty(m)&&(this.dsatriggers[m][o.id]=c.id);break;case"advantage":case"disadvantage":s=Number(o.system.step.value)||1;break}if(c.notApplicable=!i,!!i){for(let m=0;m(d=foundry.utils.duplicate(d),d.effect=c,d.priority=d.priority?d.priority:d.mode*10,d)));for(let m of c.statuses)this.statuses.add(m)}}a.sort((o,c)=>o.priority-c.priority);for(let o of a){if(!o.key)continue;let c=o.effect.apply(this,o);Object.assign(e,c)}this.overrides=foundry.utils.expandObject(e);let r;for(let[o,c]of t){let m=this.statuses.has(o);if(m!==c){r??(r=this.getActiveTokens());for(let d of r)d._onApplyStatusEffect(o,m)}}}_setOnUseEffect(e){getProperty(e,"flags.dsa5.onUseEffect")&&(e.OnUseEffect=!0)}_setAEPayments(e){if(e.OnUseEffect)return;Number(getProperty(e,"system.AsPCost"))&&(e.AEpayable=!0)}prepareBaseData(){let e=this.system;mergeObject(e,{itemModifiers:{},condition:{},swarm:{attack:0,parry:0,damage:0},creatureType:this.creatureType,skillModifiers:{FP:[],step:[],QL:[],TPM:[],FW:[],botch:20,crit:1,global:[],conditional:{AsPCost:[],KaPCost:[]},feature:{FP:[],step:[],QL:[],TPM:[],FW:[],KaPCost:[],AsPCost:[]},...["liturgy","ceremony","ritual","spell","skill"].reduce((t,a)=>(t[a]={FP:[],step:[],QL:[],TPM:[],FW:[]},t),{})},status:{initiative:{multiplier:1},astralenergy:{permanentGear:0},karmaenergy:{permanentGear:0},wounds:{multiplier:1},speed:{multiplier:1},regeneration:{LePgearmodifier:0,KaPgearmodifier:0,AsPgearmodifier:0}},repeatingEffects:{startOfRound:{wounds:[],karmaenergy:[],astralenergy:[]}},temperature:{heatProtection:0,coldProtection:0},totalArmor:0,spellArmor:0,liturgyArmor:0,carryModifier:0,aspModifier:0,kapModifier:0,immunities:[],creatureBonus:[],miracle:{attack:0,parry:0},spellStats:{damage:"0"},liturgyStats:{damage:"0"},meleeStats:{parry:0,attack:0,damage:"0",defenseMalus:0,botch:20,crit:1},rangeStats:{attack:0,damage:"0",defenseMalus:0,botch:20,crit:1}});for(let t of b.gearModifyableCalculatedAttributes)e.status[t]&&(e.status[t].gearmodifier=0);for(let t of Object.values(e.characteristics))t.gearmodifier=0}getSkillModifier(e,t){let a=[],s=["FP","step","QL","TPM","FW"];for(let i of s){let n=i=="step"?"":i;a.push(...this.system.skillModifiers[i].filter(r=>r.target==e).map(r=>({name:r.source,value:r.value,type:n}))),this.system.skillModifiers[t]&&a.push(...this.system.skillModifiers[t][i].map(r=>({name:r.source,value:r.value,type:n})))}return a}prepareSheet(e){let t={system:{characteristics:{}}};if(mergeObject(t,this.prepareItems(e)),t.canAdvance){let a=["wounds","astralenergy","karmaenergy"];for(let s of a)mergeObject(t.system,{status:{[s]:{cost:game.i18n.format("advancementCost",{cost:f._calculateAdvCost(this.system.status[s].advances,"D")}),refund:game.i18n.format("refundCost",{cost:f._calculateAdvCost(this.system.status[s].advances,"D",0)})}}});for(let[s,i]of Object.entries(this.system.characteristics))t.system.characteristics[s]={cost:game.i18n.format("advancementCost",{cost:f._calculateAdvCost(i.initial+i.advances,"E")}),refund:game.i18n.format("refundCost",{cost:f._calculateAdvCost(i.initial+i.advances,"E",0)})}}return t}static canAdvance(e){return e.canAdvance}static armorValue(e,t={}){let a=e.items.filter(n=>n.type=="armor"&&n.system.worn.value==!0);t.origin&&(a=a.map(n=>{let r=mergeObject(duplicate(t),{armor:n});return Q.applyRollTransformation(e,r,4).options.armor}));let s=a.reduce((n,r)=>n+W.armorWearModifier(r,r.system.protection.value),0),i=e.items.filter(n=>n.type=="trait"&&n.system.traitType.value=="armor").reduce((n,r)=>n+Number(r.system.at.value),0);return{wornArmor:a,armor:s+i+(e.system.totalArmor||0)}}static _calculateCombatSkillValues(e,t){if(e.system.weapontype.value=="melee"){let a=e.system.guidevalue.value.split("/").map(n=>Number(t.characteristics[n].initial)+Number(t.characteristics[n].modifier)+Number(t.characteristics[n].advances)+Number(t.characteristics[n].gearmodifier)),s=Math.max(...a);e.system.parry.value=Math.ceil(e.system.talentValue.value/2)+Math.max(0,Math.floor((s-8)/3))+Number(game.settings.get("dsa5","higherDefense"));let i=t.characteristics.mu.initial+t.characteristics.mu.modifier+t.characteristics.mu.advances+t.characteristics.mu.gearmodifier;e.system.attack.value=e.system.talentValue.value+Math.max(0,Math.floor((i-8)/3))}else{e.system.parry.value=0;let a=t.characteristics.ff.initial+t.characteristics.ff.modifier+t.characteristics.ff.advances+t.characteristics.ff.gearmodifier;e.system.attack.value=e.system.talentValue.value+Math.max(0,Math.floor((a-8)/3))}return e.cost=game.i18n.format("advancementCost",{cost:f._calculateAdvCost(e.system.talentValue.value,e.system.StF.value)}),e}_perpareItemAdvancementCost(e){return e.cost=game.i18n.format("advancementCost",{cost:f._calculateAdvCost(e.system.talentValue.value,e.system.StF.value)}),e.refund=game.i18n.format("refundCost",{cost:f._calculateAdvCost(e.system.talentValue.value,e.system.StF.value,0)}),e}async modifyTokenAttribute(e,t,a=!1,s=!0){let i=foundry.utils.getProperty(this.system,e),n;return s?(a&&(t=Math.clamped(i.min||0,Number(i.value)+t,i.max)),n={[`system.${e}.value`]:t}):(a&&(t=Number(i)+t),n={[`system.${e}`]:t}),Hooks.call("modifyTokenAttribute",{attribute:e,value:t,isDelta:a,isBar:s},n)!==!1?this.update(n):this}schipshtml(){let e=[];for(let t=1;t<=Number(this.system.status.fatePoints.max);t++)e.push({value:t,cssClass:t<=Number(this.system.status.fatePoints.value)?"fullSchip":"emptySchip"});return e}prepareItems(e){let t=this.toObject(!1),a=[],s=[],i=[],n=[],r=[],o=[],c=[],m=[],d=[],p=[],g=Object.fromEntries(Object.keys(b.specialAbilityCategories).map(k=>[k,[]])),y=Object.fromEntries(Object.keys(b.traitCategories).map(k=>[k,[]])),h=[],w=[],z=[],v=[],S={hasSpells:this.system.isMage,hasPrayers:this.system.isPriest,liturgy:[],spell:[],ritual:[],ceremony:[],blessing:[],magictrick:[],magicalsign:[]},x={spell:{},ritual:{},ceremony:{},liturgy:{}},F=this.hasPlayerOwner?P.getGroupSchips():[],N=this.schipshtml(),D={meleeweapons:{items:[],show:!1,dataType:"meleeweapon"},rangeweapons:{items:[],show:!1,dataType:"rangeweapon"},armor:{items:[],show:!1,dataType:"armor"},ammunition:{items:[],show:!1,dataType:"ammunition"},plant:{items:[],show:!1,dataType:"plant"},poison:{items:[],show:!1,dataType:"poison"}};for(let k in b.equipmentTypes)D[k]={items:[],show:!1,dataType:k};D.misc.show=!0;let A={coins:[],total:0,show:!0};t.items=t.items.sort((k,V)=>k.name.localeCompare(V.name));let G=t.system.totalArmor||0,Z={body:[],social:[],knowledge:[],trade:[],nature:[]},ke=new Map;for(let k of t.items.filter(V=>V.type=="equipment"&&V.system.equipmentType.value=="bags"))ke.set(k._id,[]);let we=new Map,nt=[],jt=!1,ft=t.items.some(k=>!["skill","combatskill","money"].includes(k.type)),ht=H.getHorse(this,!0);for(let k of t.items)try{let V=getProperty(k,"system.parent_id");if(k.type=="ammunition"&&nt.push(T._prepareitemStructure(k)),V&&V!=k._id&&ke.has(V)){ke.get(V).push(k);continue}switch(e.details&&e.details.includes(k._id)&&(k.detailed="shown"),k.system.isArtifact&&(k.volume=b.traditionArtifacts[k.system.artifact]||0,k.volumeFinal=0,v.push(k)),k.type){case"skill":Z[k.system.group.value].push(this._perpareItemAdvancementCost(k));break;case"information":m.push(k);break;case"aggregatedTest":n.push(k);break;case"spellextension":x[k.system.category][k.system.source]?x[k.system.category][k.system.source].push(k.name):x[k.system.category][k.system.source]=[k.name];break;case"ritual":case"spell":case"liturgy":case"ceremony":S[k.type].push(T.buildSpellChargeProgress(this._perpareItemAdvancementCost(k)));break;case"magicalsign":case"magictrick":case"blessing":S[k.type].push(k);break;case"trait":switch(k.system.traitType.value){case"rangeAttack":k=T._prepareRangeTrait(k);break;case"meleeAttack":k=T._prepareMeleetrait(k);break;case"armor":G+=Number(k.system.at.value);break}y[k.system.traitType.value].push(k),jt=!0;break;case"combatskill":a.push(T._calculateCombatSkillValues(k,this.system));break;case"ammunition":D.ammunition.items.push(T.prepareMag(k)),D.ammunition.show=!0;break;case"meleeweapon":k.toggleValue=k.system.worn.value||!1,k.toggle=!0,this._setOnUseEffect(k),D.meleeweapons.items.push(T._prepareitemStructure(k)),D.meleeweapons.show=!0,k.toggleValue&&c.push(k);break;case"rangeweapon":k.toggleValue=k.system.worn.value||!1,k.toggle=!0,this._setOnUseEffect(k),D.rangeweapons.items.push(T._prepareitemStructure(k)),D.rangeweapons.show=!0;break;case"armor":k.toggleValue=k.system.worn.value||!1,D.armor.items.push(T._prepareitemStructure(k)),D.armor.show=!0,k.toggle=!0,this._setOnUseEffect(k),k.system.worn.value&&(k.system.protection.value=W.armorWearModifier(k,k.system.protection.value),G+=Number(k.system.protection.value),h.push(k));break;case"poison":case"plant":D[k.type].items.push(k),D[k.type].show=!0;break;case"consumable":D[k.system.equipmentType.value].items.push(T._prepareConsumable(k)),D[k.system.equipmentType.value].show=!0;break;case"equipment":k.toggle=getProperty(k,"system.worn.wearable")||!1,k.toggle&&(k.toggleValue=k.system.worn.value||!1),this._setOnUseEffect(k),D[k.system.equipmentType.value].items.push(T._prepareitemStructure(k)),D[k.system.equipmentType.value].show=!0;break;case"money":A.coins.push(k),A.total+=k.system.quantity.value*k.system.price.value;break;case"advantage":this._setOnUseEffect(k),s.push(k);break;case"disadvantage":this._setOnUseEffect(k),i.push(k);break;case"specialability":this._setOnUseEffect(k),this._setAEPayments(k),g[k.system.category.value].push(k);break;case"disease":r.push(k);break;case"patron":g.magical.push(k);break;case"demonmark":o.push(k);break;case"essence":d.push(k);break;case"imprint":p.push(k);break;case"application":we.has(k.system.skill)?we.get(k.system.skill).push(k):we.set(k.system.skill,[k]);break}}catch(V){this._itemPreparationError(k,V)}for(let k of D.bags.items)this._setBagContent(k,ke);for(let[k,V]of Object.entries(x))for(let[rt,ta]of Object.entries(V)){let wi=S[k].find(_i=>_i.name==rt);wi?wi.extensions=ta.join(", "):ui.notifications.warn(game.i18n.format("DSAError.noSpellForExtension",{name:rt,category:f.categoryLocalization(k),extension:ta.join(",")}))}for(let k of D.rangeweapons.items)try{k.system.worn.value&&w.push(T._prepareRangeWeapon(k,nt,a,this))}catch(V){this._itemPreparationError(k,V)}for(let k of c)try{z.push(T._prepareMeleeWeapon(k,a,t,c.filter(V=>V._id!=k._id&&!P.isYieldedTwohanded(V))))}catch(V){this._itemPreparationError(k,V)}for(let k of Object.values(Z))for(let V of k)V.applications=we.get(V.name)||[];A.coins=A.coins.sort((k,V)=>k.system.price.value>V.system.price.value?-1:1),g.magical.push(...g.pact),g.clerical.push(...g.ceremonial);for(let k of g.staff){let V=v.find(rt=>rt.system.artifact==k.system.artifact);if(V){V.abilities==null&&(V.abilities=[]),V.abilities.push(k);let rt=Number(k.system.volume)||0,ta=rt>0?"volumeFinal":"volume";V[ta]+=Math.abs(rt)*Number(k.system.step.value)}else g.magical.push(k)}let ea=duplicate(b.characteristics);return ea["-"]="-",{totalWeight:parseFloat(this.system.totalWeight.toFixed(3)),traditionArtifacts:v,armorSum:G,sortedSpecs:b.sortedSpecs,spellArmor:t.system.spellArmor||0,liturgyArmor:t.system.liturgyArmor||0,money:A,encumbrance:this.system.condition?.encumbered||0,carrycapacity:this.system.carrycapacity,isSwarm:this.isSwarm(),canSwarm:!this.prototypeToken.actorLink,wornRangedWeapons:w,wornMeleeWeapons:z,horseActor:ht,advantages:s,hasAnyItem:ft,disadvantages:i,specAbs:g,information:m,aggregatedtests:n,wornArmor:h,essence:d,imprint:p,inventory:D,hasTrait:jt,demonmarks:o,diseases:r,canBuild:game.dsa5.sheets.DSACharBuilder&&!t.system.details.species?.value,itemModifiers:this.system.itemModifiers,languagePoints:{used:t.system.freeLanguagePoints?.used||0,available:t.system.freeLanguagePoints?.value||0},schips:N,groupschips:F,guidevalues:ea,magic:S,traits:y,combatskills:a,canAdvance:this.canAdvance,sheetLocked:t.system.sheetLocked.value,bodyAttrs:["ff","ge","ko","kk"],mentalAttrs:["mu","kl","in","ch"],allSkillsLeft:{body:Z.body,social:Z.social,nature:Z.nature},allSkillsRight:{knowledge:Z.knowledge,trade:Z.trade}}}isSwarm(){return this.system.swarm.count>1&&!this.prototypeToken.actorLink}getArmorEncumbrance(e,t){let a=t.reduce((i,n)=>(n.system.calculatedEncumbrance=Number(n.system.encumbrance.value)+W.armorEncumbranceModifier(n),n.system.damageToolTip=W.damageTooltip(n),i+=n.system.calculatedEncumbrance),0),s=H.isRiding(this)?-1:0;return Math.max(0,a-R.abilityStep(e,game.i18n.localize("LocalizedIDs.inuredToEncumbrance"))+s)}_calcBagweight(e,t,a=!0){let s=0;if(t.has(e._id)){let i=0;!e.system.worn.value&&a&&(s-=e.system.preparedWeight);for(let n of t.get(e._id))n.system.preparedWeight=Number(parseFloat((n.system.weight.value*n.system.quantity.value).toFixed(3))),t.has(n._id)?i+=this._calcBagweight(n,t,!1):i+=n.system.preparedWeight;a?e.system.worn.value&&(s+=i):s+=i+e.system.preparedWeight,e.system.bagweight=`${i.toFixed(3)}/${e.system.capacity}`}return s}_setBagContent(e,t){if(t.has(e._id)){e.children=[];for(let a of t.get(e._id))e.children.push(T._prepareitemStructure(T._prepareConsumable(a))),t.has(a._id)&&this._setBagContent(a,t)}}isMerchant(){return["merchant","loot"].includes(getProperty(this,"system.merchant.merchantType"))}_itemPreparationError(e,t){console.error("Something went wrong with preparing item "+e.name+": "+t),console.warn(t),console.warn(e),ui.notifications.error("Something went wrong with preparing item "+e.name+": "+t)}_applyModiferTransformations(e){this.system.itemModifiers={};for(let t of Object.keys(e)){let a=game.dsa5.config.knownShortcuts[t.toLowerCase()];if(a){let s=e[t].reduce((i,n)=>i=i+n.value,0);this.system[a[0]][a[1]][a[2]]+=s,this.system.itemModifiers[t]={value:s,sources:e[t].map(i=>i.source)}}}}_buildGearAndAbilityModifiers(e,t){let a=getProperty(t,"system.effect.value");if(!!a)for(let s of a.split(/,|;/).map(i=>i.trim())){let i=s.replace(/(\s+)/g," ").trim().split(" ");if(i.length==2&&!isNaN(i[0])){let n={value:Number(i[0])*(t.system.step&&Number(t.system.step.value)||1),source:t.name,type:t.type};e[i[1]]==null?e[i[1]]=[n]:e[i[1]].push(n)}}}async _updateAPs(e,t={},a={}){if(T.canAdvance(this))if(!isNaN(e)&&e!=null){let s=Number(e);t["system.details.experience.spent"]=Number(this.system.details.experience.spent)+s,await this.update(t,a);let i=game.i18n.format(s>0?"advancementCost":"refundCost",{cost:Math.abs(s)});de(i)}else ui.notifications.error(game.i18n.localize("DSAError.APUpdateError"))}async checkEnoughXP(e){if(!T.canAdvance(this)||isNaN(e)||e==null||Number(this.system.details.experience.total)-Number(this.system.details.experience.spent)>=e)return!0;if(Number(this.system.details.experience.total)==0){let t=await renderTemplate("systems/dsa5/templates/dialog/parts/expChoices.html",{entries:b.startXP}),a=0,s=!1;if([s,a]=await new Promise((i,n)=>{new Dialog({title:game.i18n.localize("DSAError.NotEnoughXP"),content:t,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:r=>{i([!0,r.find(".APsel")[0].value])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{i([!1,0])}}}}).render(!0)}),s)return await this.update({"system.details.experience.total":Number(a)}),!0}return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughXP")),!1}setupWeapon(e,t,a,s){return a.mode=t,C.getSubClass(e.type).setupDialog(null,a,e,this,s)}setupWeaponless(e,t={},a){let s=foundry.utils.duplicate(b.defaultWeapon);s.name=game.i18n.localize(`${e}Weaponless`),s.system.combatskill={value:game.i18n.localize("LocalizedIDs.wrestle")},s.system.damageThreshold.value=14;let i=[];return R.hasAbility(this,game.i18n.localize("LocalizedIDs.mightyAstralBody"))&&i.push(game.i18n.localize("magical")),R.hasAbility(this,game.i18n.localize("LocalizedIDs.mightyKarmalBody"))&&i.push(game.i18n.localize("blessed")),mergeObject(s,{system:{effect:{attributes:i.join(", ")}}}),t.mode=e,C.getSubClass(s.type).setupDialog(null,t,s,this,a)}setupSpell(e,t={},a){return C.getSubClass(e.type).setupDialog(null,t,e,this,a)}setupSkill(e,t={},a){return C.getSubClass(e.type).setupDialog(null,t,e,this,a)}tokenScrollingText(e){let t=this.isToken?[this.token?.object]:this.getActiveTokens(!0);for(let a of t){if(!a)continue;let s=0;for(let i of e)canvas.interface.createScrollingText(a.center,i.value,{anchor:s,direction:i.value>0?2:1,fontSize:game.settings.get("dsa5","scrollingFontsize"),stroke:i.stroke,strokeThickness:1,jitter:.25,duration:1e3}),s+=1}}async _preUpdate(e,t,a){await super._preUpdate(e,t,a);let s={wounds:9109504,astralenergy:723929,karmaenergy:303670};game.combat?.isBrawling&&(s.temporaryLeP=16525967);let i=[];for(let o of Object.keys(s)){let c=getProperty(e,`system.status.${o}.value`);c&&i.push({value:c-this.system.status[o].value,stroke:s[o]})}i.length&&this.tokenScrollingText(i);let n=getProperty(e,"system.swarm.count");if(n&&!t.skipSwarmUpdate){let o=getProperty(e,"system.status.wounds.value")||this.system.status.wounds.value,c=n-(this.system.swarm.count||1),m=this.system.swarm.maxwounds||this.system.status.wounds.max;setProperty(e,"system.status.wounds.value",Math.max(0,o+c*m))}let r=getProperty(e,"system.details.experience.total");if(r){let o=this.system.details.experience.total;_.track(this,{type:"sum",previous:o,next:r},r-o)}}async applyDamage(e){if(game.combat?.isBrawling){let t=Math.min(this.system.status.temporaryLeP.max,this.system.status.temporaryLeP.value-e);await this.update({"system.status.temporaryLeP.value":t})}else{let t=Math.min(this.system.status.wounds.max,this.system.status.wounds.value-e);await this.update({"system.status.wounds.value":t})}}async applyRegeneration(e,t,a){let s={"system.status.wounds.value":Math.min(this.system.status.wounds.max,this.system.status.wounds.value+(e||0)),"system.status.karmaenergy.value":Math.min(this.system.status.karmaenergy.max,this.system.status.karmaenergy.value+(a||0)),"system.status.astralenergy.value":Math.min(this.system.status.astralenergy.max,this.system.status.astralenergy.value+(t||0))};await this.update(s)}async applyMana(e,t){let a=t=="AsP"?"astralenergy":"karmaenergy",s=Math.min(this.system.status[a].max,this.system.status[a].value-e);return s>=0?(await this.update({[`data.status.${a}.value`]:s}),!0):(ui.notifications.error(game.i18n.localize(`DSAError.NotEnough${t}`)),!1)}preparePostRollAction(e){let t=e.flags.data,a={flags:{img:e.flags.img},rollMode:t.rollMode,speaker:e.speaker,template:t.template,title:t.title,user:e.user};return t.attackerMessage&&(a.attackerMessage=t.attackerMessage),t.defenderMessage&&(a.defenderMessage=t.defenderMessage),t.unopposedStartMessage&&(a.unopposedStartMessage=t.unopposedStartMessage),a}resetTargetAndMessage(e,t){e.originalTargets?.size&&(game.user.targets=e.originalTargets,game.user.targets.user=game.user),!e.defenderMessage&&e.startMessagesList&&(t.startMessagesList=e.startMessagesList)}async fatererollDamage(e,t,a,s,i,n){t.fatePointDamageRerollUsed=!0,this.resetTargetAndMessage(i,t);let r=i.postData.damageRoll,o=await _DiceDSA5.manualRolls(await new Roll(r.formula||r._formula).evaluate({async:!0}),"CHATCONTEXT.rerollDamage");for(let c=0;c${game.i18n.localize("CHATFATE.fatepointUsed")} + ${game.i18n.format("CHATFATE.isTalented",{character:""+this.name+""})}
    `;let n=await renderTemplate("systems/dsa5/templates/dialog/isTalentedReroll-dialog.html",{testData:a,postData:i.postData});new ee({title:game.i18n.localize("CHATFATE.selectDice"),content:n,buttons:{Yes:{icon:'',label:game.i18n.localize("Ok"),callback:async r=>{let o=r.find(".dieSelected").map(function(){return Number($(this).attr("data-index"))}).get();if(o.length>0){let c=[];for(let p of o){let g=a.roll.terms[p*2];c.push(g.number+"d"+g.faces+"["+g.options.colorset+"]")}c=await _DiceDSA5.manualRolls(await new Roll(c.join("+")).evaluate({async:!0}),"CHATCONTEXT.talentedReroll"),await _DiceDSA5.showDiceSoNice(c,a.rollMode);let m=0,d=[];for(let p of o){let g=a.source.system[`characteristic${p+1}`],y=g?game.i18n.localize(`CHARAbbrev.${g.value.toUpperCase()}`)+" - ":"";d.push(`${y}${a.roll.terms[p*2].results[0].result}/${c.terms[m*2].results[0].result}`),a.roll.terms[p*2].results[0].result=Math.min(c.terms[m*2].results[0].result,a.roll.terms[p*2].results[0].result),m+=1}e+=`${game.i18n.localize("Roll")}: ${d.join(", ")}`,ChatMessage.create(f.chatDataSetup(e)),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.talentedRerollUsed":!0})}}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}async fatereroll(e,t,a,s,i,n){t.fatePointDamageRerollUsed=!0,this.resetTargetAndMessage(i,t);let r=await renderTemplate("systems/dsa5/templates/dialog/fateReroll-dialog.html",{testData:a,postData:i.postData,singleDie:i.postData.characteristics.length==1});new ee({title:game.i18n.localize("CHATFATE.selectDice"),content:r,buttons:{Yes:{icon:'',label:game.i18n.localize("Ok"),callback:async o=>{let c=o.find(".dieSelected").map(function(){return Number($(this).attr("data-index"))}).get();if(c.length>0){let m=[];for(let w of c){let z=a.roll.terms[w*2];m.push(z.number+"d"+z.faces+"["+z.options.colorset+"]")}m=await _DiceDSA5.manualRolls(await new Roll(m.join("+")).evaluate({async:!0}),"CHATCONTEXT.Reroll"),await _DiceDSA5.showDiceSoNice(m,a.rollMode);let d=0,p=[],g=f.getSpeaker(a.extra.speaker),y=game.i18n.localize("LocalizedIDs.traditionPhex"),h=g.items.some(w=>w.type=="specialability"&&w.name==y);for(let w of c){let z=a.source.system[`characteristic${w+1}`],v=z?`${game.i18n.localize(`CHARAbbrev.${z.value.toUpperCase()}`)} - `:"";p.push(`${v}${a.roll.terms[w*2].results[0].result}/${m.terms[d*2].results[0].result}`),h?a.roll.terms[w*2].results[0].result=Math.min(m.terms[d*2].results[0].result,a.roll.terms[w*2].results[0].result):a.roll.terms[w*2].results[0].result=m.terms[d*2].results[0].result,d+=1}e+=`
    ${game.i18n.localize("Roll")}: ${p.join(", ")}`,ChatMessage.create(f.chatDataSetup(e)),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fatePointRerollUsed":!0}),await this.reduceSchips(n)}}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}async fateaddQS(e,t,a,s,i,n){ChatMessage.create(f.chatDataSetup(e)),game.user.targets.forEach(r=>r.setTarget(!1,{user:game.user,releaseOthers:!1,groupSelection:!0})),t.fatePointAddQSUsed=!0,a.qualityStep=1,this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fatePointAddQSUsed":!0}),await this.reduceSchips(n)}async fateImprove(e,t,a,s,i,n){ChatMessage.create(f.chatDataSetup(e)),this.resetTargetAndMessage(i,t);let r=s.flags.data.preData.source.type;if(["spell","liturgy","ceremony","ritual","skill"].includes(r)){let o=await renderTemplate("systems/dsa5/templates/dialog/fateImprove-dialog.html",{testData:a,postData:i.postData});new ee({title:game.i18n.localize("CHATFATE.selectDice"),content:o,buttons:{Yes:{icon:'',label:game.i18n.localize("Ok"),callback:async c=>{let m=[0,0,0],d=c.find(".dieSelected").map(function(){return Number($(this).attr("data-index"))}).get();if(d.length==1){m[d]=2;let p={name:game.i18n.localize("CHATCONTEXT.improveFate"),value:m.join("|"),type:"roll"};a.roll.terms[d*2].results[0].result=Math.max(1,a.roll.terms[d*2].results[0].result-2),a.situationalModifiers.push(p),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fateImproved":!0}),await this.reduceSchips(n)}}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)}else{let o={name:game.i18n.localize("CHATCONTEXT.improveFate"),value:2,type:"roll"};a.situationalModifiers.push(o),a.roll.terms[0].results[0].result=Math.max(1,a.roll.terms[0].results[0].result-2),this[`${i.postData.postFunction}`]({testData:a,cardOptions:t},{rerenderMessage:s}),await s.update({"flags.data.fateImproved":!0}),await this.reduceSchips(n)}}async reduceSchips(e){e==0?await this.update({"system.status.fatePoints.value":this.system.status.fatePoints.value-1}):await T.reduceGroupSchip()}static async reduceGroupSchip(){if(game.user.isGM){let e=game.settings.get("dsa5","groupschips").split("/").map(t=>Number(t));e[0]=e[0]-1,await game.settings.set("dsa5","groupschips",e.join("/"))}else game.socket.emit("system.dsa5",{type:"reduceGroupSchip",payload:{}})}async useFateOnRoll(e,t,a){if(t=="isTalented"||f.fateAvailable(this,a==1)){let s=e.flags.data,i=this.preparePostRollAction(e),n,r;a==0?(n=this.system.status.fatePoints.value-1,r="PointsRemaining"):(n=game.settings.get("dsa5","groupschips").split("/")[0],r="GroupPointsRemaining");let o=`

    ${game.i18n.localize("CHATFATE.fatepointUsed")}

    ${game.i18n.format("CHATFATE."+t,{character:""+this.name+""})}
    - ${game.i18n.localize(`CHATFATE.${n}`)}: ${r}`,c=s.preData;c.extra.actor=f.getSpeaker(c.extra.speaker).toObject(!1),this[`fate${t}`](o,i,c,e,s,a)}}get horseSpeed(){return H.getHorseSpeed(this)}setupFallingDamage(e,t){let a=game.i18n.localize("fallingDamage"),s=this.items.find(r=>r.type=="skill"&&r.name==game.i18n.localize("LocalizedIDs.bodyControl")).toObject(),i={subtitle:` (${a})`,postFunction:{functionName:"game.dsa5.entities.Actordsa5.updateFallingDamage",options:e,tokenId:t,speaker:A.buildSpeaker(this,t)}};this.setupSkill(s,i,t).then(async r=>{r.testData.opposable=!1;let n=await this.basicTest(r,{suppressMessage:!0});await T.updateFallingDamage(i.postFunction,n),await _DiceDSA5.renderRollCard(n.cardOptions,n.result,n.options.rerenderMessage)})}static async updateFallingDamage(e,t,a){let s=(t.result.qualityStep||0)*2;mergeObject(e.options,{availableQs:s});let i=f.getSpeaker(e.speaker),r=await i._setupFallingHeight(e.options,e.tokenId),n=await i.basicTest(r,{suppressMessage:!0}),o=await renderTemplate("systems/dsa5/templates/chat/roll/fallingdamage-card.html",n);t.result.other||(t.result.other=[]),t.result.other.push(o),t.chatData&&(t.chatData.other=[o])}_setupFallingHeight(e,t){let a=game.i18n.localize("fallingDamage"),s={source:{type:"fallingDamage"},opposable:!1,extra:{actor:this.toObject(!1),options:e,speaker:A.buildSpeaker(this,t)}},i=[],r={title:a,template:"/systems/dsa5/templates/dialog/fallingdamage-dialog.html",data:{rollMode:e.rollMode,situationalModifiers:i,fallingFloorOptions:b.fallingConditions,modifier:e.modifier||0},callback:(o,c={})=>(s.situationalModifiers=[],s.situationalModifiers.push({name:game.i18n.localize("fallingFloor"),value:o.find('[name="fallingFloor"]').val()}),n.rollMode=o.find('[name="rollMode"]').val(),s.fallingHeight=o.find('[name="testModifier"]').val(),mergeObject(s.extra.options,c),{testData:s,cardOptions:n})},n=this._setupCardOptions("systems/dsa5/templates/chat/roll/fallingdamage-card.html",a,t);return _DiceDSA5.setupDialog({dialogOptions:r,testData:s,cardOptions:n})}setupRegeneration(e,t={},a){let s=game.i18n.localize("regenerationTest"),i={source:{type:"regenerate",system:{}},opposable:!1,extra:{statusId:e,actor:this.toObject(!1),options:t,speaker:A.buildSpeaker(this,a)}};i.extra.actor.isMage=this.system.isMage,i.extra.actor.isPriest=this.system.isPriest;let r=E.getRollModifiers(i.extra.actor,i.source),n={title:s,template:"/systems/dsa5/templates/dialog/regeneration-dialog.html",data:{rollMode:t.rollMode,regenerationInterruptOptions:b.regenerationInterruptOptions,regnerationCampLocations:b.regnerationCampLocations,showAspModifier:this.system.isMage,showKapModifier:this.system.isPriest,situationalModifiers:r,modifier:t.modifier||0},callback:(c,m={})=>{i.situationalModifiers=T._parseModifiers(c),o.rollMode=c.find('[name="rollMode"]').val(),i.situationalModifiers.push({name:game.i18n.localize("camplocation")+" - "+c.find('[name="regnerationCampLocations"] option:selected').text(),value:c.find('[name="regnerationCampLocations"]').val()},{name:game.i18n.localize("interruption")+" - "+c.find('[name="regenerationInterruptOptions"] option:selected').text(),value:c.find('[name="regenerationInterruptOptions"]').val()}),i.regenerationFactor=c.find('[name="badEnvironment"]').is(":checked")?.5:1;let d=["LeP","KaP","AsP"],p={};for(let g of d){i[`${g}Modifier`]=Number(c.find(`[name="${g}Modifier"]`).val()||0),i[`regeneration${g}`]=Number(this.system.status.regeneration[`${g}max`]);let y=c.find(`[name="regenerate${g}"]`).is(":checked")?1:0;i[`regenerate${g}`]=y,y&&(p[`system.status.regeneration.${g}Temp`]=0)}return mergeObject(i.extra.options,m),this.update(p),{testData:i,cardOptions:o}}},o=this._setupCardOptions("systems/dsa5/templates/chat/roll/regeneration-card.html",s,a);return _DiceDSA5.setupDialog({dialogOptions:n,testData:i,cardOptions:o})}setupDodge(e={},t){let a="dodge",s=this.system.status[a],i=game.i18n.localize(a)+" "+game.i18n.localize("Test"),r={source:{system:s,type:a},opposable:!1,extra:{statusId:a,actor:this.toObject(!1),options:e,speaker:A.buildSpeaker(this,t)}},n=[game.i18n.localize(a),game.i18n.localize("LocalizedIDs.wrestle")],o=A.buildCombatSpecAbs(this,["Combat"],n,"parry"),c=E.getRollModifiers(r.extra.actor,r.source),m=A.getDefenseMalus(c,this),d=P.multipleDefenseValue(this,r.source),p={title:i,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:{rollMode:e.rollMode,combatSpecAbs:o,showDefense:!0,situationalModifiers:c,isRangeAttack:m,defenseCountString:game.i18n.format("defenseCount",{malus:d}),isDodge:!0},callback:(y,h={})=>(g.rollMode=y.find('[name="rollMode"]').val(),r.situationalModifiers=T._parseModifiers(y),r.situationalModifiers.push(...A.getSpecAbModifiers(y,"parry")),r.situationalModifiers.push({name:game.i18n.localize("attackFromBehind"),value:y.find('[name="attackFromBehind"]').is(":checked")?-4:0},{name:game.i18n.format("defenseCount",{malus:d}),value:(Number(y.find('[name="defenseCount"]').val())||0)*d},{name:game.i18n.localize("advantageousPosition"),value:y.find('[name="advantageousPosition"]').is(":checked")?2:0}),mergeObject(r.extra.options,h),{testData:r,cardOptions:g})},g=this._setupCardOptions("systems/dsa5/templates/chat/roll/status-card.html",i,t);return _DiceDSA5.setupDialog({dialogOptions:p,testData:r,cardOptions:g})}setupCharacteristic(e,t={},a){let s=duplicate(this.system.characteristics[e]),i=f.attributeLocalization(e)+" "+game.i18n.localize("Test");s.attr=e;let r={opposable:!1,source:{type:"char",system:s},extra:{characteristicId:e,actor:this.toObject(!1),options:t,speaker:A.buildSpeaker(this,a)}},n={title:i,template:"/systems/dsa5/templates/dialog/characteristic-dialog.html",data:{rollMode:t.rollMode,difficultyLabels:b.attributeDifficultyLabels,modifier:t.modifier||0},callback:(c,m={})=>(o.rollMode=c.find('[name="rollMode"]').val(),r.testDifficulty=b.attributeDifficultyModifiers[c.find('[name="testDifficulty"]').val()],r.situationalModifiers=T._parseModifiers(c),mergeObject(r.extra.options,m),{testData:r,cardOptions:o})},o=this._setupCardOptions("systems/dsa5/templates/chat/roll/characteristic-card.html",i,a);return _DiceDSA5.setupDialog({dialogOptions:n,testData:r,cardOptions:o})}static _parseModifiers(e,t){let a=[];return e.find('[name="situationalModifiers"] option:selected').each(function(){let s=$(this).val(),i={name:$(this).text().trim().split("[")[0],value:isNaN(s)?s:Number(s),type:$(this).attr("data-type")};i.type=="dmg"&&(i.damageBonus=i.value,i.value=0),$(this).attr("data-specAbId")&&(i.specAbId=$(this).attr("data-specAbId")),$(this).attr("data-armorPen")&&(i.armorPen=$(this).attr("data-armorPen")),a.push(i)}),a.push({name:game.i18n.localize("manual"),value:Number(e.find('[name="testModifier"]').val()),type:""}),a}static _prepareConsumable(e){return e.system.maxCharges&&(e.consumable=!0,e.structureMax=e.system.maxCharges,e.structureCurrent=e.system.charges),e}static prepareMag(e){return e.system.ammunitiongroup.value=="mag"&&(e.structureMax=e.system.mag.max,e.structureCurrent=e.system.mag.value),e}static _prepareitemStructure(e){e.system.structure&&e.system.structure.max!=0&&(e.structureMax=e.system.structure.max,e.structureCurrent=e.system.structure.value);let t=getProperty(e,"flags.dsa5.enchantments");if(t&&t.length>0)e.enchantClass="rar";else if(e.effects.length>0)e.enchantClass="common";else if(e.system.effect&&e.system.effect.value!="")if(e.type=="armor")for(let a of e.system.effect.value.split(/,|;/).map(s=>s.trim())){let s=a.replace(/(\s+)/g," ").trim().split(" ");if(!(s.length==2&&[game.i18n.localize("CHARAbbrev.INI").toLowerCase(),game.i18n.localize("CHARAbbrev.GS").toLowerCase()].includes(s[1].toLowerCase())&&!isNaN(s[0])&&s[0]==-1)){e.enchantClass="common";break}}else e.enchantClass="common";return e}static _prepareMeleetrait(e){return e.attack=Number(e.system.at.value),e.system.pa!=0&&(e.parry=e.system.pa),this._parseDmg(e)}static _prepareMeleeWeapon(e,t,a,s=null){let i=t.find(r=>r.name==e.system.combatskill.value);if(i){e.attack=Number(i.system.attack.value)+Number(e.system.atmod.value);let r=e.system.guidevalue.value.split("/").map(c=>a.system.characteristics[c]?Number(a.system.characteristics[c].initial)+Number(a.system.characteristics[c].modifier)+Number(a.system.characteristics[c].advances)+Number(a.system.characteristics[c].gearmodifier):0),n=Math.ceil(i.system.talentValue.value/2)+Math.max(0,Math.floor((Math.max(...r)-8)/3))+Number(game.settings.get("dsa5","higherDefense"));e.parry=n+Number(e.system.pamod.value)+(P.isShield(e)?Number(e.system.pamod.value):0),e.yieldedTwoHand=P.isYieldedTwohanded(e),e.yieldedTwoHand||(s||(s=a.items.filter(c=>c.type=="meleeweapon"&&c.system.worn.value&&c._id!=e._id&&!P.isYieldedTwohanded(c))),s.length>0&&(e.parry+=Math.max(...s.map(c=>c.system.pamod.offhandMod)),e.attack+=Math.max(...s.map(c=>c.system.atmod.offhandMod))));let o=0;if(e.system.worn.wrongGrip)if(e.yieldedTwoHand)e.parry-=1,o=1;else switch(e.system.reach.value="medium",game.i18n.localize(`LocalizedCTs.${e.system.combatskill.value}`)){case"Two-Handed Impact Weapons":case"Two-Handed Swords":if(e.parry-=3,new RegExp(game.i18n.localize("wrongGrip.wrongGripBastardRegex")).test(e.name))o=-2;else{let d=game.i18n.localize("wrongGrip.oneHanded");e.gripDamageText=` (${d} * 0.5)`,e.dmgMultipliers=[{name:d,val:"0.5"}]}break;default:e.parry-=1,o=-1}if(e=this._parseDmg(e),e.system.guidevalue.value!="-"){let c=Math.max(...e.system.guidevalue.value.split("/").map(d=>Number(a.system.characteristics[d].value))),m=Math.max(c-Number(e.system.damageThreshold.value),0)+o;m>0&&(e.extraDamage=m,e.damageAdd=Roll.safeEval(e.damageAdd+" + "+Number(m)),e.damageAdd=(e.damageAdd>0?"+":"")+e.damageAdd)}W.weaponWearModifier(e),e.system.damageToolTip=W.damageTooltip(e)}else ui.notifications.error(game.i18n.format("DSAError.unknownCombatSkill",{skill:e.system.combatskill.value,item:e.name}));return e}async actorEffects(){let e=["dead"];return game.user.isGM||this.testUserPermission(game.user,"OBSERVER")||!game.settings.get("dsa5","hideEffects")?this.effects.filter(a=>a.isVisibleEffect()):this.effects.filter(a=>e.some(s=>a.statuses.has(s)))}async _preCreate(e,t,a){await super._preCreate(e,t,a);let s={};e.img||(s.img="icons/svg/mystery-man-black.svg"),e.type=="character"&&mergeObject(s,{prototypeToken:{sight:{enabled:!0},actorLink:!0}}),this.updateSource(s)}async exclusiveEquipWeapon(e,t=!1){let a=this.items.get(e);if(!a)return;let s=[];switch(a.type){case"armor":case"rangeweapon":s=this.items.filter(o=>o.type==a.type&&o.id!=e&&o.system.worn.value).map(o=>({_id:o.id,"system.worn.value":!1})),s.push({_id:e,"system.worn.value":!0});break;case"meleeweapon":let r=this.items.filter(o=>o.type==a.type&&o.id!=e&&o.system.worn.value),n={_id:e,"system.worn.value":!0};P.isYieldedTwohanded(a)||(r=r.filter(o=>P.isYieldedTwohanded(o)||o.system.worn.offHand==t),n["system.worn.offHand"]=t),s=r.map(o=>({_id:o.id,"system.worn.value":!1})),s.push(n);break}s&&await this.updateEmbeddedDocuments("Item",s)}static _prepareRangeTrait(e){return e.attack=Number(e.system.at.value),e.LZ=Number(e.system.reloadTime.value),e.LZ>0&&T.buildReloadProgress(e),this._parseDmg(e)}static calcLZ(e,t){let a=1,s=0;e.system.combatskill.value==game.i18n.localize("LocalizedIDs.Throwing Weapons")?s=R.abilityStep(t,game.i18n.localize("LocalizedIDs.quickdraw"))*-1:e.system.combatskill.value==game.i18n.localize("LocalizedIDs.Crossbows")&&R.hasAbility(t,`${game.i18n.localize("LocalizedIDs.quickload")} (${game.i18n.localize("LocalizedIDs.Crossbows")})`)?a=.5:s=R.abilityStep(t,`${game.i18n.localize("LocalizedIDs.quickload")} (${game.i18n.localize(e.system.combatskill.value)})`)*-1;let i=`${e.system.reloadTime.value}`.split("/");if(e.system.ammunitiongroup.value=="mag"){let r=t.items.find(o=>o.id==e.system.currentAmmo.value||o._id==e.system.currentAmmo.value),n=0;r&&(r=f.toObjectIfPossible(r),r.system.mag.value<=0&&(n=1)),i=i[n]||i[0]}else i=i[0];return Math.max(0,Math.round(Number(i)*a)+s)}static _parseDmg(e,t=void 0){let a=new Roll(e.system.damage.value.replace(/[Ww]/g,"d"),{async:!1}),s="",i="",r="+";for(let n of a.terms)n.faces?s=n.number+"d"+n.faces:n.operator?r=n.operator:n.number&&(i+=Number(`${r}${n.number}`));if(t){let n=getProperty(t,"system.damageMod");Number(n)?i+=`+${Number(n)}`:n&&(e.damageBonusDescription=`, ${n} ${game.i18n.localize("CHARAbbrev.damage")} ${t.name}`)}return i&&(i=Roll.safeEval(i)),e.damagedie=s||"0d6",e.damageAdd=i!=""?(Number(i)>=0?"+":"")+i:"",e}static buildReloadProgress(e){let t=e.system.reloadTime.progress/e.LZ;e.title=game.i18n.format("WEAPON.loading",{status:`${e.system.reloadTime.progress}/${e.LZ}`}),e.progress=`${e.system.reloadTime.progress}/${e.LZ}`,t>=1&&(e.title=game.i18n.localize("WEAPON.loaded")),this.progressTransformation(e,t)}static progressTransformation(e,t){t>=.5?(e.transformRight="181deg",e.transformLeft=`${Math.round(t*360-179)}deg`):(e.transformRight=`${Math.round(t*360+1)}deg`,e.transformLeft=0)}static buildSpellChargeProgress(e){if(e.LZ=Number(e.system.castingTime.modified)||0,e.LZ>1){let t=e.system.castingTime.progress/e.LZ;e.title=game.i18n.format("SPELL.loading",{status:`${e.system.castingTime.progress}/${e.LZ}`}),e.progress=`${e.system.castingTime.progress}/${e.LZ}`,this.progressTransformation(e,t)}return e}static _prepareRangeWeapon(e,t,a,s){let i=a.find(n=>n.name==e.system.combatskill.value);e.calculatedRange=e.system.reach.value;let r;if(i){if(e.attack=Number(i.system.attack.value),e.system.ammunitiongroup.value!="-"&&(e.ammo=t.filter(n=>n.system.ammunitiongroup.value==e.system.ammunitiongroup.value),r=t.find(n=>n._id==e.system.currentAmmo.value),r)){let n=Number(r.system.rangeMultiplier)||1;e.calculatedRange=e.calculatedRange.split("/").map(o=>Math.round(Number(o)*n)).join("/"),e.attack+=Number(r.system.atmod)||0,r.system.ammunitiongroup.value=="mag"&&(e.ammoMax=r.system.mag.max,e.ammoCurrent=r.system.mag.value)}e.LZ=T.calcLZ(e,s),e.LZ>0&&T.buildReloadProgress(e),W.weaponWearModifier(e),e.system.damageToolTip=W.damageTooltip(e)}else ui.notifications.error(game.i18n.format("DSAError.unknownCombatSkill",{skill:e.system.combatskill.value,item:e.name}));return this._parseDmg(e,r)}_setupCardOptions(e,t,a){let s=game.canvas?.tokens?.get(a),i={speaker:{alias:s?s.name:this.prototypeToken.name,actor:this.id},title:t,template:e,flags:{img:this.prototypeToken.randomImg?this.img:this.prototypeToken.img}};if(this.token)i.speaker.alias=this.token.name,i.speaker.token=this.token.id,i.speaker.scene=canvas.scene.id,i.flags.img=this.token.img;else{let r=ChatMessage.getSpeaker();r.actor==this.id&&(i.speaker.alias=r.alias,i.speaker.token=r.token,i.speaker.scene=r.scene,i.flags.img=r.token?canvas.tokens.get(r.token).img:i.flags.img)}return i}async swapMag(e){let t=this.items.get(e),a=this.items.get(t.system.currentAmmo.value);if(a&&a.system.quantity.value>1)return await this.updateEmbeddedDocuments("Item",[{_id:a.id,"system.quantity.value":a.system.quantity.value-1,"system.mag.value":a.system.mag.max}]),K.playEquipmentWearStatusChange(a),a;ui.notifications.error(game.i18n.localize("DSAError.NoAmmo"))}async payMiracles(e){if(!e.extra.miraclePaid){e.extra.miraclePaid=!0;let t=e.situationalModifiers.some(i=>i.name.trim()==game.i18n.localize("LocalizedIDs.miracleMight")),a=e.situationalModifiers.some(i=>i.name.trim()==game.i18n.localize("LocalizedIDs.miracle")),s=t?6:a?4:0;s&&await this.update({"system.status.karmaenergy.value":this.system.status.karmaenergy.value-s})}}async consumeAmmunition(e){if(e.extra.ammo&&!e.extra.ammoDecreased){if(e.extra.ammoDecreased=!0,e.extra.ammo._id){let t={_id:e.extra.ammo._id};e.extra.ammo.system.ammunitiongroup.value=="mag"?e.extra.ammo.system.mag.value<=0?(e.extra.ammo.system.quantity.value--,t["system.quantity.value"]=e.extra.ammo.system.quantity.value,t["system.mag.value"]=e.extra.ammo.system.mag.max-1):t["system.mag.value"]=e.extra.ammo.system.mag.value-1:(e.extra.ammo.system.quantity.value--,t["system.quantity.value"]=e.extra.ammo.system.quantity.value),await this.updateEmbeddedDocuments("Item",[t,{_id:e.source._id,"system.reloadTime.progress":0}])}}else(e.source.type=="rangeweapon"||e.source.type=="trait"&&e.source.system.traitType.value=="rangeAttack")&&!e.extra.ammoDecreased?(e.extra.ammoDecreased=!0,await this.updateEmbeddedDocuments("Item",[{_id:e.source._id,"system.reloadTime.progress":0}])):["spell","liturgy"].includes(e.source.type)&&e.extra.speaker.token!="emptyActor"&&await this.updateEmbeddedDocuments("Item",[{_id:e.source._id,"system.castingTime.progress":0,"system.castingTime.modified":0}])}_checkMaximumItemAdvancement(e,t){let a=0;switch(e.type){case"combatskill":a=Math.max(...e.system.guidevalue.value.split("/").map(o=>this.system.characteristics[o].value))+2+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalCombatTechnique")} (${e.name})`);break;case"spell":case"ritual":let i=0;for(let o of e.system.feature.replace(/\(a-z äöü\-\)/gi,"").split(",").map(c=>c.trim()))if(R.hasAbility(this,`${game.i18n.localize("LocalizedIDs.propertyKnowledge")} (${o})`)){i=this.maxByAttr(e);break}a=Math.max(14+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalSkill")} (${e.name})`),i);break;case"liturgy":case"ceremony":let r=new RegExp(`^${game.i18n.localize("LocalizedIDs.aspectKnowledge")}`),n=0;this.items.filter(o=>o.type=="specialability"&&r.test(o.name)).some(o=>e.system.distribution.value.includes(o.name.split("(")[1].split(")")[0]))&&(n=this.maxByAttr(e)),a=Math.max(14+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalSkill")} (${e.name})`),n);break;case"skill":a=this.maxByAttr(e);break}let s=t<=a;return s||ui.notifications.error(game.i18n.localize("DSAError.AdvanceMaximumReached")),{result:s,max:a}}maxByAttr(e){return Math.max(this.system.characteristics[e.system.characteristic1.value].value,this.system.characteristics[e.system.characteristic2.value].value,this.system.characteristics[e.system.characteristic3.value].value)+2+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalSkill")} (${e.name})`)}async basicTest({testData:e,cardOptions:t},a={}){e=await _DiceDSA5.rollDices(e,t);let s=await _DiceDSA5.rollTest(e);if(e.extra.options.other&&(s.other||(s.other=[]),s.other.push(...e.extra.options.other)),s.postFunction="basicTest",game.user.targets.size){t.isOpposedTest=e.opposable;let i=` - ${game.i18n.localize("Opposed")}`;t.isOpposedTest&&t.title.match(i+"$")!=i&&(t.title+=i)}if(await this.consumeAmmunition(e),await this.payMiracles(e),!a.suppressMessage){let i=await _DiceDSA5.renderRollCard(t,s,a.rerenderMessage);await j.handleOpposedTarget(i),s.messageId=i.id}return{result:s,cardOptions:t,options:a}}async addCondition(e,t=1,a=!1,s=!0){if(e=="bleeding"||e.id=="bleeding")return await P.bleedingMessage(this);if(this.isToken&&!this.token?.object){console.warn("Actor token object is null for",this.name);return}return await E.addCondition(this,e,t,a,s)}async addTimedCondition(e,t=1,a=!1,s=!0,i={}){return e=="bleeding"||e.id=="bleeding"?await P.bleedingMessage(this):(typeof e=="string"&&i.duration&&(e=duplicate(CONFIG.statusEffects.find(r=>r.id==e)),e.flags.dsa5.description=game.i18n.localize(e.name),e.name=game.i18n.localize(e.name),delete e.description,delete e.flags.dsa5.value,delete e.flags.dsa5.max,delete e.id,mergeObject(e,i)),await E.addCondition(this,e,t,a,s))}async initResistPainRoll(e){let t=game.settings.get("dsa5","selfControlOnPain");if(this.hasCondition("incapacitated"))return;if(t==2||t==1&&!this.hasPlayerOwner){await this.addCondition("incapacitated");return}let a=await renderTemplate("systems/dsa5/templates/chat/roll/resist-pain.html",{actor:this});await ChatMessage.create(f.chatDataSetup(a))}async finishResistPainRoll(){let e=this.items.find(t=>t.name==game.i18n.localize("LocalizedIDs.selfControl")&&t.type=="skill");this.setupSkill(e,{subtitle:` (${game.i18n.localize("ActiveEffects.resistRoll")})`},this.token?.id).then(async t=>{((await this.basicTest(t)).result.successLevel||0)<1&&this.addCondition("incapacitated")})}async removeCondition(e,t=1,a=!0,s=!1){return await E.removeCondition(this,e,t,a,s)}hasCondition(e){return E.hasCondition(this,e)}async markDead(e){let t=this.getActiveTokens();for(let a of t)a.combatant&&await a.combatant.update({defeated:e})}};u(T,"Actordsa5");function Ei(){let l={Rq:"roll",Gc:"GC",Ch:"CH"},e={Rq:"dice",Gc:"dice",Ch:"user-shield",AP:"trophy",Pay:"coins",GetPaid:"piggy-bank"},t={Rq:"",Gc:`${game.i18n.localize("HELP.groupcheck")} `,Ch:"",AP:"",Pay:"",GetPaid:""},a=/(-|\+)?\d+/,s=/(-|\+)?\d+(\.\d+)?/,i=/\[[a-zA-ZöüäÖÜÄ&; -]+/,r=/[\[\]]/g,n={Pay:game.i18n.localize("PAYMENT.payButton"),GetPaid:game.i18n.localize("PAYMENT.getPaidButton"),AP:game.i18n.localize("MASTER.awardXP")};if(!b.statusRegex){let o=b.statusEffects.map(m=>game.i18n.localize(m.name).toLowerCase()),c=["status","condition","level","levels"].map(m=>game.i18n.localize(m)).join("|");b.statusRegex={effects:o,regex:new RegExp(`(${c}) (${o.join("|")})`,"gi")}}CONFIG.TextEditor.enrichers.push({pattern:/@(Rq|Gc|Ch)\[[a-zA-ZöüäÖÜÄ&; -]+ (-|\+)?\d+\]({[a-zA-ZöüäÖÜÄß\(\)&; -]+})?/g,enricher:(o,c)=>{let m=o[0],d=o[1],p=Number(m.match(a)[0]),g=m.replace(p,"").match(i)[0].replace(r,"").trim(),y=m.match(/\{.*\}/)?m.match(/\{.*\}/)[0].replace(/[\{\}]/g,""):g;return $(`${t[d]}${y} ${p}`)[0]}},{pattern:/@(Pay|GetPaid|AP)\[(-|\+)?\d+(\.\d+)?\]({[a-zA-ZöüäÖÜÄß\(\)&; -]+})?/g,enricher:(o,c)=>{let m=o[0],d=o[1],p=Number(m.match(s)[0]),g=m.match(/\{.*\}/)?m.match(/\{.*\}/)[0].replace(/[\{\}]/g,""):n[d];return $(`${t[d]}${g} (${p})`)[0]}},{pattern:b.statusRegex.regex,enricher:(o,c)=>$(ai(o))[0]},{pattern:/@Info\[[a-zA-ZöüäÖÜÄ&; -\.0-9]+\]/g,enricher:async(o,c)=>{let m=o[0].match(/(?:\[)(.*?)(?=\])/)[0].slice(1),d=await fromUuid(m);if(!d||d.type!="information")return $('info')[0];if(!game.user.isGM)return $(`${game.i18n.localize("GM notes")}`)[0];let p={enrichedqs1:await TextEditor.enrichHTML(d.system.qs1,{async:!0}),enrichedqs2:await TextEditor.enrichHTML(d.system.qs2,{async:!0}),enrichedqs3:await TextEditor.enrichHTML(d.system.qs3,{async:!0}),enrichedqs4:await TextEditor.enrichHTML(d.system.qs4,{async:!0}),enrichedqs5:await TextEditor.enrichHTML(d.system.qs5,{async:!0}),enrichedqs6:await TextEditor.enrichHTML(d.system.qs6,{async:!0}),enrichedCrit:await TextEditor.enrichHTML(d.system.crit,{async:!0}),enrichedBotch:await TextEditor.enrichHTML(d.system.botch,{async:!0}),enrichedFail:await TextEditor.enrichHTML(d.system.fail,{async:!0})},g=await renderTemplate("systems/dsa5/templates/items/infopreview.html",{item:d,enriched:p});return $(g)[0]}},{pattern:/@EmbedItem\[[a-zA-ZöüäÖÜÄ&ë;'\(\)„“:, -\.0-9›‹âïß\/]+\]({[a-zA-Z=]+})?/g,enricher:async(o,c)=>{let m=o[0].match(/(?:\[)(.*?)(?=\])/)[0].slice(1),d=await fromUuid(m);if(!d){let x=m.split("."),v=game.packs.get(x[0]+"."+x[1]);v&&(d=await v.getDocuments({name:x[2]}),d=d[0])}if(!d)return $('')[0];let p=o[0],g=p.match(/\{.*\}/)?p.match(/\{.*\}/)[0].replace(/[\{\}]/g,""):"",y={};if(g)for(let x of g.split(" ")){let v=x.split("=");v.length==2&&(y[v[0]]=v[1])}let h=`systems/dsa5/templates/items/browse/${d.type}.html`,w=await renderTemplate(h,{document:d,isGM:game.user.isGM,...await d.sheet.getData(),...y});return $(w)[0]}},{pattern:/@PostChat\[(.*?)\]/g,enricher:async(o,c)=>{let m=o[1];return $(`
    ${m}
    `)[0]}})}u(Ei,"setEnrichers");function ai(l){let t=l[0].split(" "),a=t.shift();t=t.join(" ");let s=b.statusEffects[b.statusRegex.effects.indexOf(t.toLowerCase())];return`${a} ${t}`}u(ai,"conditionsMatcher");var f=class{static async skillByName(e){let t=game.packs.get(game.i18n.lang=="de"?"dsa5.skills":"dsa5.skillsen");await t.getIndex();let a=t.index.find(s=>s.name===e);return await t.getDocument(a._id)}static async allSkills(){let e=game.i18n.lang=="de"?"dsa5.skills":"dsa5.skillsen";return await this.getCompendiumEntries(e,"skill")}static moduleEnabled(e){return game.modules.get(e)&&game.modules.get(e).active}static async allCombatSkills(){let e=game.i18n.lang=="de"?"dsa5.skills":"dsa5.skillsen";return await this.getCompendiumEntries(e,"combatskill")}static async getCompendiumEntries(e,t){let a=await game.packs.get(e);if(!a)return ui.notifications.error("No content found");let s=Array.isArray(t)?t:[t];return(await a.getDocuments()).filter(r=>s.includes(r.type)).map(r=>r.toObject())}static renderToggle(e){e.rendered?e._minimized?e.maximize():e.close():e.render(!0)}static calcTokenSize(e,t){let a=game.dsa5.config.tokenSizeCategories[e.system.status.size.value];if(a)if(a<1)mergeObject(t,{texture:{scaleX:a,scaleY:a},width:1,height:1});else{let s=Math.floor(a),i=Math.max(a/s,.25);mergeObject(t,{width:s,height:s,texture:{scaleX:i,scaleY:i}})}}static async allMoneyItems(){return(await this.getCompendiumEntries("dsa5.money","money")).map(t=>(t.system.quantity.value=0,t)).filter(t=>Object.values(b.moneyNames).map(a=>a.toLowerCase()).includes(t.name.toLowerCase())).sort((t,a)=>t.system.price.value>a.system.price.value?-1:1)}static async allSkillsList(){return(await this.allSkills()||[]).map(e=>e.name).sort((e,t)=>e.localeCompare(t))}static async allCombatSkillsList(e){return((await this.allCombatSkills()).filter(t=>t.system.weapontype.value==e)||[]).map(t=>t.name).sort((t,a)=>t.localeCompare(a))}static async callItemTransformationMacro(e,t,a,s={}){let i=e.split("."),r=game.packs.get(`${i[0]}.${i[1]}`);if(!r)return console.warn(`Pack ${r} not found`),{};let n=await r.getDocuments({name:i[2]}),o={};if(n.length){let c=Object.getPrototypeOf(async function(){}).constructor,m=new c("args","source","effect",n[0].command);try{s.result=o,await m.call(this,s,t,a)}catch(d){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(d),o.error=!0}}else ui.notifications.error(game.i18n.format("DSAError.macroNotFound",{name:e}));return o}static isActiveGM(){let e=game.users.activeGM;return e||ui.notifications.warn(game.i18n.localize("DSAError.requiresGM")),e?.isSelf}static parseAbilityString(e){return{original:e.replace(/ (FP|SR|FW|SP)?[+-]?\d{1,2}$/,"").trim(),name:e.replace(/\((.+?)\)/g,"()").replace(/ (FP|SR|FW|SP)?[+-]?\d{1,2}$/,"").trim(),step:Number((e.match(/[+-]?\d{1,2}$/)||[1])[0]),special:(e.match(/\(([^()]+)\)/)||["",""])[1],type:e.match(/ (FP|SP)[+-]?\d{1,2}/)?"FP":e.match(/ (FW|SR)[+-]?\d{1,2}/)?"FW":"",bonus:e.match(/[-+]\d{1,2}$/)!=null}}static categoryLocalization(e){return game.i18n.localize(`TYPES.Item.${e}`)}static attributeLocalization(e){return game.i18n.localize(`CHAR.${e.toUpperCase()}`)}static attributeAbbrLocalization(e){return game.i18n.localize(`CHARAbbrev.${e.toUpperCase()}`)}static async callAsyncHooks(e,t){for(let a of b.asyncHooks[e])await a(...t)}static chatDataSetup(e,t,a,s){let i={user:game.user.id,rollMode:t||game.settings.get("core","rollMode"),content:e};return["gmroll","blindroll"].includes(i.rollMode)&&(i.whisper=ChatMessage.getWhisperRecipients("GM").map(r=>r.id)),i.rollMode==="blindroll"?i.blind=!0:i.rollMode==="selfroll"&&(i.whisper=[game.user]),a&&(i.speaker=ChatMessage.getSpeaker(),i.whisper=ChatMessage.getWhisperRecipients(a)),s&&(i.speaker=ChatMessage.getSpeaker(),i.whisper=s),i}static getSpeaker(e){let t=ChatMessage.getSpeakerActor(e);if(!t&&canvas.tokens){let a=canvas.tokens.get(e.token);a&&(t=a.actor)}if(!t){let a=game.scenes.get(e.scene);try{a&&(t=new Token(a.getEmbeddedDocument("Token",e.token))?.actor)}catch{}}return t}static fateAvailable(e,t){return t?game.settings.get("dsa5","groupschips").split("/").map(a=>Number(a))[0]>0:e.system.status.fatePoints.value>0}static _calculateAdvCost(e,t,a=1){return b.advancementCosts[t][Number(e)+a]}static async getFolderForType(e,t=null,a=null,s=0,i="",r=void 0){let n=await game.folders.contents.find(o=>o.name==a&&o.type==e&&o.folder?.id==t);return n||(n=await Folder.create({name:a,type:e,sorting:r||(e=="JournalEntry"?"a":"m"),color:i,sort:s,parent:t})),n}static toObjectIfPossible(e){return typeof e.toObject=="function"?e.toObject(!1):duplicate(e)}static async showArtwork({img:e,name:t,uuid:a,isOwner:s},i=!1){return new ImagePopout(e,{title:i?s?t:"-":t,shareable:!0,uuid:a}).render(!0)}static async findAnyItem(e){let t=[],a=e.map(i=>i.name),s=e.map(i=>i.type);for(let i of game.items.contents){let r=a.indexOf(i.name);if(r>=0&&s[r]==i.type&&(a.splice(r,1),s.splice(r,1),t.push(i.toObject())),a.length<=0)break}if(a.length>0){let i=/^dsa5-core/,r=Array.from(game.packs.keys()).sort((n,o)=>(i.test(n)&&i.test(o)&&n.localeCompare(o),i.test(o)?-1:i.test(n)?1:n.localeCompare(o)));for(let n of r){let o=game.packs.get(n);if(o.documentName=="Item"&&(game.user.isGM||!o.private)&&(await o.getDocuments({name__in:a,type__in:s}).then(c=>{for(let m of c){let d=a.indexOf(m.name);d>=0&&s[d]==m.type&&(a.splice(d,1),s.splice(d,1),t.push(m.toObject()))}}),a.length<=0))break}}return t}static replaceDies(e,t=!1){let a=/( |^)(\d{1,2})?[wWdD][0-9]+((\+|-)[0-9]+)?/g,s=t?"":"/r ";return e.replace(a,function(i){return` [[${s}${i.replace(/[DwW]/,"d")}]]`})}static escapeRegex(e){return(typeof e=="string"||e instanceof String?e:"").replace(/[-[/\]{}()*+?.,\\^$|#\s]/g,"\\$&")}static replaceConditions(e){return e&&e.replace(b.statusRegex.regex,t=>ai([t]))}static experienceDescription(e){let t=[2100,1700,1400,1200,1100,1e3],a=["EXP.legendary","EXP.brillant","EXP.masterful","EXP.competent","EXP.experienced","EXP.average"],s=0;for(let i of t){if(Number(e)>=Number(i))return a[s];s++}return"EXP.inexperienced"}static async emptyActor(e=12,t="Alrik"){Array.isArray(e)||(e=[e,e,e,e,e,e,e,e]);let a=await T.create({name:t,type:"npc",items:[],system:{status:{wounds:{value:50},fatePoints:{}},characteristics:{mu:{initial:e[0]},kl:{initial:e[1]},in:{initial:e[2]},ch:{initial:e[3]},ff:{initial:e[4]},ge:{initial:e[5]},ko:{initial:e[6]},kk:{initial:e[7]}}}},{temporary:!0,noHook:!0});return a.prepareData(),a}};u(f,"DSA5_Utility");var Ie=class{static async showDialog(e,t=!1){let[a]=await new Promise((s,i)=>{let r={Yes:{icon:'',label:game.i18n.localize("update"),callback:()=>{s([!0])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{s([!1])}}};t&&(r.migrateAll={icon:'',label:game.i18n.localize("replace"),callback:()=>{s([2])}}),new Dialog({title:game.i18n.localize("Migrakel.Migration"),content:e,default:"yes",buttons:r,close:()=>{s([!1])}}).render(!0)});return a}static async refreshStatusEffects(e){let t=[];for(let a of e.effects)a.origin&&t.push(a.id);await e.deleteEmbeddedDocuments("ActiveEffect",t)}static async updateVals(e,t,a){let s=game.dsa5.itemLibrary,i=[],r=[],n=new Map;if(await this.refreshStatusEffects(e),t({type:"equipment"})){let o=[],c=[];for(let d of e.items.filter(p=>p.type=="equipment"&&p.system.equipmentType.value=="bags")){let p=await s.findCompendiumItem(d.name,d.type);if(p.length>0){if(p=p.find(y=>y.name==d.name&&y.type==d.type),!p)continue;console.log(`MIGRATION - Updated ${d.name}`);let g=mergeObject(d.toObject(),a(p));c.push(g),o.push(d.id)}}let m=await e.createEmbeddedDocuments("Item",c);for(let d=0;dt(c)&&!(c.type=="equipment"&&c.system.equipmentType.value=="bags"))){let c=await s.findCompendiumItem(o.name,o.type);if(c.length>0){if(c=c.find(d=>d.name==o.name&&d.type==o.type),!c)continue;console.log(`MIGRATION - Updated ${o.name}`);let m=mergeObject(o.toObject(),a(c));m.system.parent_id&&n.has(m.system.parent_id)&&(m.system.parent_id=n.get(m.system.parent_id)),r.push(m),i.push(o.id)}}await e.createEmbeddedDocuments("Item",r),await e.deleteEmbeddedDocuments("Item",i),Ie.silent||ui.notifications.notify(game.i18n.localize("Migrakel.migrationDone"))}static async updateSpellsAndLiturgies(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.spells"),!0),s=u(i=>["spell","liturgy","ritual","ceremony","spellextension"].includes(i.type),"condition");if(a==2){let i=u(r=>{let n=r.toObject();return delete n.system.talentValue,n},"updator");await this.updateVals(e,s,i)}else if(a){let i=u(r=>{let n={effects:r.effects.toObject()};return r.type!="spellextension"&&(n.system={effectFormula:{value:r.system.effectFormula.value}}),n},"updator");await this.updateVals(e,s,i)}return a}static async updateSpecialAbilities(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.abilities"));if(a){let s=u(r=>{let n={system:{effect:{value:r.system.effect.value}},effects:r.effects.toObject()};return r.type=="specialability"&&(mergeObject(n,{system:{category:{sub:r.system.category.sub||0},list:{value:r.system.list.value},effect:{value2:getProperty(r,"system.effect.value2")||"",value3:getProperty(r,"system.effect.value3")||""}}}),r.system.category.value=="staff"&&mergeObject(n,{system:{feature:getProperty(r,"system.feature")||"",AsPCost:getProperty(r,"system.AsPCost")||"",volume:Number(getProperty(r,"system.volume"))||0,artifact:getProperty(r,"system.artifact")||"",permanentEffects:getProperty(r,"system.permanentEffects")||!1}})),this.updateMacro(n,r),n},"updator"),i=u(r=>["specialability","advantage","disadvantage","trait"].includes(r.type),"condition");await this.updateVals(e,i,s)}return a}static async updateCombatskills(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.cskills"));if(a){let s=u(r=>({effects:r.effects.toObject()}),"updator"),i=u(r=>["combatskill"].includes(r.type),"condition");await this.updateVals(e,i,s)}return a}static async updateSkills(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.skills"));if(a){let s=u(r=>["skill"].includes(r.type),"condition"),i=u(r=>({img:r.img,effects:r.effects.toObject()}),"updator");await this.updateVals(e,s,i)}return a}static updateMacro(e,t){let a=t.getFlag("dsa5","onUseEffect");a&&mergeObject(e,{flags:{dsa5:{onUseEffect:a}}})}static async updateGear(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.gear"));if(a){let s=u(r=>["meleeweapon","armor","rangeweapon","equipment","poison","consumable","ammunition"].includes(r.type),"condition"),i=u(r=>{let n={img:r.img,effects:r.effects.toObject()};return["poison","consumable"].includes(r.type)||mergeObject(n,{system:{effect:{value:r.system.effect.value}}}),["armor"].includes(r.type)&&mergeObject(n,{system:{subcategory:r.system.subcategory}}),["meleeweapon","rangeweapon","armor"].includes(r.type)&&mergeObject(n,{system:{structure:{max:r.system.structure.max,value:r.system.structure.value}}}),this.updateMacro(n,r),n},"updator");await this.updateVals(e,s,i)}return a}};u(Ie,"Migrakel");var Ye=class extends Dialog{constructor(e,t){super(t),this.actor=e,this.lock=!1}static async buildDialog(e){let t=await renderTemplate("systems/dsa5/templates/actors/parts/actorConfig.html",{actor:e});new Ye(e,{title:game.i18n.localize("SHEET.actorConfig"),content:t,default:"Save",buttons:{}}).render(!0)}async updateWrapper(e,t){if(this.lock)return;u(async()=>{this.lock=!0,$(t.currentTarget).prepend(''),await Ie[e](this.actor),$(t.currentTarget).find("i").remove(),this.lock=!1},"upd")()}activateListeners(e){super.activateListeners(e),e.find(".updateSpells").click(async t=>this.updateWrapper("updateSpellsAndLiturgies",t)),e.find(".updateAbilities").click(async t=>this.updateWrapper("updateSpecialAbilities",t)),e.find(".updatecSkills").click(async t=>this.updateWrapper("updateCombatskills",t)),e.find(".updateSkills").click(async t=>this.updateWrapper("updateSkills",t)),e.find(".updateGear").click(async t=>this.updateWrapper("updateGear",t))}};u(Ye,"DialogActorConfig");function mt(l,e="img"){!game.user.isGM||l.find(e).each(function(t,a){a.setAttribute("draggable",!0),a.addEventListener("dragstart",s=>Vi(s))})}u(mt,"bindImgToCanvasDragStart");var Vi=u(l=>{canvas.tiles.activate();let e=l.currentTarget.src,t=l.currentTarget,a=canvas.dimensions.sceneHeight/t.naturalHeight,s=canvas.dimensions.sceneWidth/t.naturalWidth,i=Math.min(1,s,a),r=Math.round(canvas.dimensions.size/i),n={type:"Tile",texture:{src:e},tileSize:r};l.dataTransfer.setData("text/plain",JSON.stringify(n));let o=t.naturalWidth*i*canvas.stage.scale.x,c=t.naturalHeight*i*canvas.stage.scale.y,m=DragDrop.createDragImage(t,o,c);l.dataTransfer.setDragImage(m,o/2,c/2)},"dragTileImg");var At=class extends FormApplication{constructor(e,t,a){super(),this.editfield=t,this.actorId=e,this.fieldname=a;let s=game.actors.get(this.actorId);this.object={fieldContent:getProperty(s,this.editfield)}}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{resizable:!0,width:600,height:600}),e}isEditable(){return!0}get title(){return`${game.actors.get(this.actorId).name} - ${game.i18n.localize(this.fieldname)}`}async _updateObject(e,t){game.socket.emit("system.dsa5",{type:"updateKeepField",payload:{actorId:this.actorId,field:this.editfield,updateData:t.fieldContent}})}async getData(e){let t=super.getData(e);return mergeObject(t,{fieldContent:this.object.fieldContent}),t}get template(){return"systems/dsa5/templates/dialog/foreignfieldeditor.html"}activateListeners(e){super.activateListeners(e)}};u(At,"ForeignFieldEditor");var pe=class extends Application{static get defaultOptions(){let e=super.defaultOptions;return e.template="systems/dsa5/templates/actors/merchant/merchant-trade.html",e.width=900,e.resizable=!0,e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"main"}],e.title=game.i18n.localize("MERCHANT.exchange"),e.classes.push("noscrollWizard"),e}constructor(e,t,a={}){super(),this.tradeData={offered:{},offer:{},id:a.id||randomID(),sourceId:e,targetId:t,offerAccepted:!1,offeredAccepted:!1}}async startTrade(){game.socket.emit("system.dsa5",{type:"startTrade",payload:{sourceId:this.tradeData.sourceId,targetId:this.tradeData.targetId,id:this.tradeData.id}}),this.render(!0)}_filterGear(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.element).find(".inventory .item");a.removeClass("filterHide"),a.filter(function(){return $(this).find("a.item-edit").text().toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide")}}async getData(){let e=await super.getData(),t=f.getSpeaker(this.tradeData.sourceId),a=t.prepareItems({details:[]});a.inventory.money={items:a.money.coins.map(s=>(s.name=game.i18n.localize(s.name),s)),show:!0,dataType:"money"};for(let s of Object.values(a.inventory))for(let i of s.items)this.tradeData.offer[i._id]&&(i.system.quantity.value-=this.tradeData.offer[i._id].system.quantity.value);return mergeObject(e,{tradeData:this.tradeData,actor:f.getSpeaker(this.tradeData.targetId),tradeFriend:t,inventory:a}),e}static findTradeApp(e){for(let t of Object.values(ui.windows))if(t instanceof this&&t?.tradeData?.id===e)return t;return!1}async close(e={}){return e.skipSocket||game.socket.emit("system.dsa5",{type:"tradeCanceled",payload:{id:this.tradeData.id}}),super.close(e)}activateListeners(e){super.activateListeners(e),e.find(".trade").click(s=>this._offerItem(s));let t=u(s=>this._filterGear($(s.currentTarget)),"filterGear");e.find(".item-edit").click(s=>this._editItem(s,this.tradeData.sourceId)),e.find(".item-external-edit").click(s=>this._editItem(s,this.tradeData.targetId)),e.find(".acceptTrade").click(s=>this.acceptTrade(s));let a=e.find(".gearSearch");a.keyup(s=>t(s)),a[0]&&a[0].addEventListener("search",t,!1)}_editItem(e,t){f.getSpeaker(t).items.get(e.currentTarget.dataset.itemId).sheet.render(!0)}_offerItem(e){if(this.tradeData.offerAccepted)return;let t=e.currentTarget.dataset.itemId,s=f.getSpeaker(this.tradeData.sourceId).items.get(t),i=e.ctrlKey?10:1,r=e.currentTarget.dataset.stopTrade,n=r?this.tradeData.offer[t].system.quantity.value:s.system.quantity.value;s&&(r?(this.tradeData.offer[t].system.quantity.value-=Math.min(i,n),this.tradeData.offer[t].system.quantity.value<=0&&delete this.tradeData.offer[t],this.offerChanged(),this.render()):(this.tradeData.offer[t]?n-=this.tradeData.offer[t].system.quantity.value:(this.tradeData.offer[t]=s.toObject(),this.tradeData.offer[t].system.quantity.value=0),n>0&&(this.tradeData.offer[t].system.quantity.value+=Math.min(i,n),this.offerChanged(),this.render())),K.playMoneySound())}async offerChanged(){game.socket.emit("system.dsa5",{type:"receiveOfferedItems",payload:{id:this.tradeData.id,trader:this.tradeData.sourceId,offered:this.tradeData.offer}})}static receiveOfferedItems(e){let t=this.findTradeApp(e.payload.id);t&&(e.payload.trader==t.tradeData.sourceId?(t.tradeData.offer=e.payload.offered,t.tradeData.offerAccepted=!1):(t.tradeData.offered=e.payload.offered,t.tradeData.offeredAccepted=!1),t.render())}static isGMTrade(e){return game.user.isGM&&!e.hasPlayerOwner}static isPlayerTrade(e){return!game.user.isGM&&e.isOwner}static socketStartTrade(e){let t=f.getSpeaker(e.payload.targetId);(this.isGMTrade(t)||this.isPlayerTrade(t))&&new pe(e.payload.targetId,e.payload.sourceId,{id:e.payload.id}).render(!0)}acceptTrade(){this.tradeData.offerAccepted=!this.tradeData.offerAccepted,this.render(!0),game.socket.emit("system.dsa5",{type:"acceptTrade",payload:{id:this.tradeData.id,accepted:this.tradeData.offerAccepted}})}static tradeWasAccepted(e){let t=this.findTradeApp(e.payload.id);t&&(t.tradeData.offeredAccepted=e.payload.accepted,t.tradeData.offerAccepted&&t.tradeData.offeredAccepted?(t.finishTrade(),K.playMoneySound()):t.render())}async finishTrade(){f.isActiveGM()&&await pe.updateData(this.tradeData),game.socket.emit("system.dsa5",{type:"tradeFinished",payload:{id:this.tradeData.id,tradeData:this.tradeData}}),this.close({skipSocket:!0}),K.playMoneySound()}static async updateData(e){let t=f.getSpeaker(e.sourceId),a=f.getSpeaker(e.targetId);await this.modifyActor(t,e.offer,e.offered),await this.modifyActor(a,e.offered,e.offer)}static async modifyActor(e,t,a){let s=[],i=[];for(let r of Object.keys(t)){let n=e.items.get(r);n&&(n.system.quantity.value<=t[r].system.quantity.value&&n.type!="money"?s.push(r):i.push({_id:r,"system.quantity.value":n.system.quantity.value-t[r].system.quantity.value}))}await e.deleteEmbeddedDocuments("Item",s,{render:!1}),await e.updateEmbeddedDocuments("Item",i,{render:!1});for(let r of Object.values(a))await e.sheet._manageDragItems(r,r.type)}static tradeWasFinished(e){let t=this.findTradeApp(e.payload.id);f.isActiveGM()&&pe.updateData(e.payload.tradeData),t&&t.close({skipSocket:!0})}static tradeWasCanceled(e){let t=this.findTradeApp(e.payload.id);t&&t.close({skipSocket:!0})}static socketListeners(e){switch(e.type){case"receiveOfferedItems":return this.receiveOfferedItems(e),!0;case"startTrade":return this.socketStartTrade(e),!0;case"acceptTrade":return this.tradeWasAccepted(e),!0;case"tradeCanceled":return this.tradeWasCanceled(e),!0;case"tradeFinished":return this.tradeWasFinished(e),!0}}};u(pe,"Trade");var Yt=class extends Application{constructor(e,t){super(t),this.actorId=A.buildSpeaker(e,e.token?.id)}async getData(e){let t=await super.getData(e);return t.actors=game.actors.filter(a=>a.hasPlayerOwner&&a.id!=this.actorId.actor),t}static get defaultOptions(){let e=super.defaultOptions;return e.template="systems/dsa5/templates/actors/merchant/merchant-tradeoptions.html",e.resizable=!0,e.title=game.i18n.localize("MERCHANT.exchange"),e}_startTrade(e){let t=game.actors.get(e.currentTarget.dataset.id);new pe(this.actorId,A.buildSpeaker(t,t.token?.id)).startTrade(),this.close()}activateListeners(e){super.activateListeners(e),e.find(".startTrade").on("dblclick",t=>this._startTrade(t))}};u(Yt,"TradeOptions");var ne=class extends Application{static registerTokenHotbar(){game.dsa5.apps.tokenHotbar||(game.dsa5.apps.tokenHotbar=new ne,game.dsa5.apps.tokenHotbar.updateDSA5Hotbar(),game.settings.get("dsa5","disableTokenhotbar")||game.dsa5.apps.tokenHotbar.render(!0),Hooks.call("dsa5TokenHotbarReady",game.dsa5.apps.tokenHotbar))}constructor(e){if(super(e),this.searching="",ne.combatSkills=["selfControl","featOfStrength","bodyControl","perception","loyalty"].map(a=>game.i18n.localize(`LocalizedIDs.${a}`)),ne.defaultSkills=new Set([game.i18n.localize("LocalizedIDs.perception")]),game.user.isGM){this.callbackFunctions={};let a=game.settings.get("dsa5","enableMasterTokenFunctions");this.gmItems=[{name:"gmMenu",disabled:a.masterMenu,icon:"systems/dsa5/icons/categories/DSA-Auge.webp",id:"masterMenu",cssClass:"gm",abbrev:"",subfunction:"gm"},{name:"MASTER.randomPlayer",disabled:a.randomVictim,iconClass:"fa fa-dice-six",id:"randomVictim",cssClass:"gm",abbrev:"",subfunction:"gm"},{name:"TT.tokenhotbarMoney",disabled:a.payMoney,icon:"systems/dsa5/icons/money-D.webp",id:"payMoney",cssClass:"gm",abbrev:"",subfunction:"gm"}]}let t=u(a=>{let s=a.parent?a.parent.id:void 0;s&&ne.hookUpdate(s)},"parentUpdate");Hooks.on("controlToken",(a,s)=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}),Hooks.on("updateActor",(a,s)=>{ne.hookUpdate(a.id)}),Hooks.on("updateToken",(a,s,i)=>{!game.dsa5.apps.tokenHotbar||s._id==getProperty(game.dsa5.apps.tokenHotbar,"actor.prototypeToken.id")&&game.dsa5.apps.tokenHotbar.updateDSA5Hotbar()}),Hooks.on("updateOwnedItem",(a,s)=>{ne.hookUpdate(a.data.id)}),Hooks.on("createOwnedItem",(a,s)=>{ne.hookUpdate(a.data.id)}),Hooks.on("deleteOwnedItem",(a,s)=>{ne.hookUpdate(a.data.id)}),Hooks.on("updateItem",(a,s)=>{t(a)}),Hooks.on("createItem",(a,s)=>{t(a)}),Hooks.on("deleteItem",(a,s)=>{t(a)}),Hooks.on("deleteActiveEffect",(a,s)=>{t(a)}),Hooks.on("updateActiveEffect",(a,s)=>{console.log(a,a.parent,a.parent.id),t(a)}),Hooks.on("createActiveEffect",(a,s)=>{t(a)}),Hooks.on("canvasInit",()=>{!this.rendered||this.render()})}registerMasterFunction(e,t){let a=game.settings.get("dsa5","enableMasterTokenFunctions");e.disabled=a[e.id],this.gmItems.push(e),this.callbackFunctions[e.id]=t}async prepareSkills(){let e=await f.allSkills();return this.skills=e.map(t=>({name:t.name,icon:t.img,id:t.name,cssClass:"skillgm",addClass:t.system.group.value,abbrev:t.name[0],subfunction:"skillgm"})),this.skills=this.skills.sort((t,a)=>t.addClass.localeCompare(a.addClass)||t.name.localeCompare(a.name)),this.skills}static hookUpdate(e){e==game.dsa5.apps.tokenHotbar?.actor?.id?game.dsa5.apps.tokenHotbar.updateDSA5Hotbar():ui.hotbar.token?.actor?.id==e&&ui.hotbar.updateDSA5Hotbar()}resetPosition(){let e=$("#hotbar").first().position(),t=game.settings.get("dsa5","tokenhotbarSize");this.position.left=e.left+8,this.position.top=e.top-t-25}static get defaultOptions(){let e=super.defaultOptions,t=$("#hotbar").first().position(),a=game.settings.get("dsa5","tokenhotbarSize"),s=game.settings.get("dsa5","tokenhotbarPosition");return mergeObject(e,{classes:e.classes.concat(["dsa5","tokenQuickHot"]),itemWidth:a,resizable:!1,height:a+45,zIndex:61,left:t.left+8,top:t.top-a-25,template:"systems/dsa5/templates/status/tokenHotbar.html",title:"TokenHotbar"}),mergeObject(e,s),e}async _onWheelResize(e){let t=game.settings.get("dsa5","tokenhotbarSize");e.originalEvent.deltaY>0?t=Math.min(100,t+5):t=Math.max(15,t-5),await game.settings.set("dsa5","tokenhotbarSize",t),await this.render(!0)}async _cycleLayout(e){if(e.button==2){let t=game.settings.get("dsa5","tokenhotbarLayout")+1;t==4&&(t=0),await game.settings.set("dsa5","tokenhotbarLayout",t),await this.render(!0)}}changeDarkness(e){let t=Number(e.currentTarget.value);canvas.scene&&canvas.scene.update({darkness:t},{animateDarkness:3e3}),de(t)}activateListeners(e){super.activateListeners(e);let t=e.find(".dragHandler");t[0]&&new Draggable(this,e,t[0],this.options.resizable),t.on("wheel",async i=>(i.stopPropagation(),i.preventDefault(),await this._onWheelResize(i),!1)),e.find(".itdarkness input").change(i=>this.changeDarkness(i));let a=this,s=u(function(i){return a.filterButtons(i),!1},"fn");e.find(".filterable").hover(function(){$(document).on("keydown",s)},function(){$(document).off("keydown",s)}),e.find(".quantity-click").mousedown(i=>P.quantityClick(i)),e.on("mousedown","li",async i=>(i.stopPropagation(),await this.executeQuickButton(i),!1)),e.on("mouseenter","li.primary",i=>{let r=i.currentTarget.dataset.category;this.category=r,setTimeout(()=>{e.find(".secondary").removeClass("shown"),r==this.category&&e.find(`.secondary[data-category="${r}"]`).addClass("shown")},700)}),e.on("mouseleave","li.primary",i=>{let r=i.currentTarget.dataset.category;this.category=void 0,setTimeout(()=>{r!=this.category&&(a.searching="",$(i.currentTarget).find(".secondary").removeClass("dsahidden"),e.find(`.secondary[data-category="${r}"]`).removeClass("shown"))},50)})}async handleEffect(e,t,a,s){let i=t.effects.get(a),r=[...i.statuses][0];e.button==0?r?await t.addCondition(r,1,!1,!1):i.sheet.render(!0):e.button==2&&(r?await t.removeCondition(r,1,!1):await t.sheet._deleteActiveEffect(a))}async handleGMRoll(e){let t=e.currentTarget.dataset.id,a=Math.round($(e.currentTarget).closest(".tokenHotbarInner,#hotbar").find(".modifierVal").val());e.ctrlKey?game.dsa5.apps.DSA5ChatListeners.check3D20(void 0,t,{modifier:a}):e.button==2?game.dsa5.macro.requestGC(t,a,{maxRolls:7}):game.dsa5.macro.requestRoll(t,a)}async handleSkillRoll(e,t,a,s){let i={};if(e.button==2&&(i.rollMode="blindroll"),a=="rideLoyaltyID")H.rollLoyalty(t,i);else if(a=="attackWeaponless")t.setupWeaponless("attack",i,s).then(r=>{t.basicTest(r)});else{let r=t.items.get(a);if(r){if(e.originalEvent.ctrlKey)return r.sheet.render(!0);switch(r.type){case"meleeweapon":case"rangeweapon":e.originalEvent.altKey?r.update({"system.worn.value":!1}):r.system.worn.value?t.setupWeapon(r,"attack",i,s).then(n=>{t.basicTest(n)}):t.exclusiveEquipWeapon(r.id,e.button==2);break;case"trait":t.setupWeapon(r,"attack",i,s).then(n=>{t.basicTest(n)});break;case"liturgy":case"spell":t.setupSpell(r,i,s).then(n=>{t.basicTest(n)});break;case"skill":t.setupSkill(r,i,s).then(n=>{t.basicTest(n)});break;case"consumable":new Dialog({title:game.i18n.localize("SHEET.ConsumeItem")+": "+r.name,content:game.i18n.localize("SHEET.ConsumeItem")+": "+r.name,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async()=>{await r.setupEffect(null,{},s),await this.updateDSA5Hotbar()}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0);break}}}}async handleTradeStart(e,t,a,s){if(!game.user.targets.size)return ui.notifications.error(game.i18n.localize("DIALOG.noTarget"));for(let i of game.user.targets)i.actor&&new pe(A.buildSpeaker(t,s),A.buildSpeaker(i.actor,i.id)).startTrade()}async handleOnUse(e,t,a,s){let i=t.items.get(a);await new X(i).executeOnUseEffect()}async handleGM(e,t,a,s){switch(a){case"masterMenu":f.renderToggle(game.dsa5.apps.gameMasterMenu);break;case"payMoney":this.payMoney(e);break;case"randomVictim":this.handleGMRandomVictim(e);break;default:a in this.callbackFunctions&&this.callbackFunctions[a](e,t,a,s)}}payMoney(e){let t=`${$(e.currentTarget).closest(".tokenHotbarInner,#hotbar").find(".modifierVal").val()}`;e.button==2?B.createGetPaidChatMessage(t):B.createPayChatMessage(t)}async handleGMRandomVictim(e){let t=await game.dsa5.apps.gameMasterMenu.rollRandomPlayer(e.button==2),a=game.actors.get(t);if(a){let s=await f.showArtwork(a);e.originalEvent.ctrlKey||setTimeout(()=>{s.close()},2e3)}}async handleSharedEffect(e){for(let t of canvas.tokens.controlled){let a=t.actor,s=t.id,i=a.effects.find(r=>r.name==e.currentTarget.dataset.name)?.id;await this.handleEffect(e,a,i,s)}}async executeQuickButton(e){let t=canvas.tokens.controlled[0]?.actor,a=canvas.tokens.controlled[0]?.id,s=e.currentTarget.dataset.id;switch(e.currentTarget.dataset.subfunction){case"trade":this.handleTradeStart(e,t,s,a);break;case"addEffect":Ee.showDialog();break;case"effect":this.handleEffect(e,t,s,a);break;case"sharedEffect":this.handleSharedEffect(e);break;case"onUse":this.handleOnUse(e,t,s,a);break;case"gm":this.handleGM(e,t,s,a);break;case"none":case"darkness":break;case"skillgm":this.handleGMRoll(e);break;default:this.handleSkillRoll(e,t,s,a)}}subWidth(e,t,a=7){return`style="width:${Math.ceil(e.length/a)*200}px"`}async getData(){let e=await super.getData(),t=this.actor,a={attacks:[],spells:[],default:[],skills:[],functions:[],gm:[]},s,i,r=[],n=[],o=[],c=game.settings.get("dsa5","tokenhotbarLayout"),m=c%2,d=ne.defaultOptions.itemWidth,p=!1;if(t){let y=[],h=[],w=H.isRiding(t),x=game.i18n.localize("LocalizedIDs.riding");if(o=await this._effectEntries(t),game.combat){let v=t.items.filter(z=>z.type=="combatskill").map(z=>T._calculateCombatSkillValues(z.toObject(),t.system)),S=this._brawlEntry(v);S&&a.attacks.push(S);for(let z of t.items)z.type=="skill"&&(ne.combatSkills.some(F=>z.name.startsWith(F))||w&&x==z.name)&&a.default.push(this._skillEntry(z,"skill filterable")),z.type=="trait"&&ne.traitTypes.has(z.system.traitType.value)?a.attacks.push(this._traitEntry(z)):ne.attackTypes.has(z.type)&&z.system.worn.value==!0?a.attacks.push(this._combatEntry(z,v,t)):ne.spellTypes.has(z.type)?z.system.effectFormula.value?a.spells.push(this._skillEntry(z,"spell filterable")):h.push(this._skillEntry(z,"spell filterable")):z.type=="skill"?y.push(this._skillEntry(z,"skill filterable",{addClass:z.system.group.value})):z.type=="consumable"&&r.push(this._actionEntry(z,"consumable",{abbrev:z.system.quantity.value})),z.getFlag("dsa5","onUseEffect")&&n.push(this._actionEntry(z,"onUse",{subfunction:"onUse"}));if(s=r.pop(),w){let z=this._ridingEntry(t);z&&a.default.push(z)}}else{let v=[];for(let S of t.items){if(S.type=="skill"&&(ne.defaultSkills.has(S.name)||w&&x==S.name)&&a.default.push(this._skillEntry(S,"skill filterable")),S.type=="skill"){let z=this._skillEntry(S,"skill filterable",{addClass:S.system.group.value});S.system.talentValue.value>0&&v.push(z),y.push(z)}else ne.spellTypes.has(S.type)&&(S.system.effectFormula.value?a.spells.push(this._actionEntry(S,"spell filterable")):h.push(this._actionEntry(S,"spell filterable")));S.getFlag("dsa5","onUseEffect")&&n.push(this._actionEntry(S,"onUse",{subfunction:"onUse"}))}a.skills.push(...v.sort((S,z)=>z.tw-S.tw).slice(0,5))}i=n.pop(),a.functions=this._functionEntries(),a.spells.length==0&&h.length>0&&a.spells.push(h.pop()),a.spells.length>0&&h.length>0&&(a.spells[0].more=h.sort((v,S)=>v.name.localeCompare(S.name)),a.spells[0].subwidth=this.subWidth(h,d)),a.default.length>0&&y.length>0&&(a.default[0].more=y.sort((v,S)=>v.addClass.localeCompare(S.addClass)||v.name.localeCompare(S.name)),a.default[0].subwidth=this.subWidth(y,d,20)),s&&(r.length>0&&(s.more=r,s.subwidth=this.subWidth(r,d)),a.consumables=[s]),i&&(n.length>0&&(i.more=n,i.subwidth=this.subWidth(n,d)),a.onUsages=[i])}else if(game.user.isGM&&!game.settings.get("dsa5","disableTokenhotbarMaster")){p=!0;let y=this.skills||await this.prepareSkills();a.gm=this._gmEntries().concat([{name:"TT.tokenhotbarSkill",id:"skillgm",icon:"systems/dsa5/icons/categories/Skill.webp",cssClass:"skillgm filterable",abbrev:"",subfunction:"none",more:y,subwidth:this.subWidth(y,d,20)}])}if(this.showEffects){let y=game.i18n.localize("CONDITION.add"),h={name:"CONDITION.add",id:"",icon:"icons/svg/aura.svg",cssClass:"effect",abbrev:y[0],subfunction:"addEffect"};if(o.length>0)h.more=o,h.subwidth=this.subWidth(o,d);else if(canvas.tokens.controlled.length>1){let w=await this.tokenHotbar._effectEntries(canvas.tokens.controlled[0].actor,{subfunction:"sharedEffect"});for(let x of canvas.tokens.controlled){let v=(await x.actor.actorEffects()).map(S=>S.name);w=w.filter(S=>v.includes(S.name))}h.more=w,h.subwidth=this.subWidth(w,d)}a.effects=[h]}let g=Object.keys(a).reduce((y,h)=>y+a[h].length,0)+(p?3:0);return m?(this.position.width=d,this.position.height=d*g+14):(this.position.width=d*g+14,this.position.height=d),mergeObject(e,{items:a,itemWidth:d,direction:c,count:g,gmMode:p,darkness:canvas?.scene?.darkness||0,opacity:game.settings.get("dsa5","tokenhotbaropacity")}),e}_functionEntries(){let e=game.i18n.localize("MERCHANT.exchangeWithTarget");return[{name:e,id:"trade",cssClass:"function",abbrev:e[0],iconClass:"fas fa-coins",subfunction:"trade"}]}_brawlEntry(e){let t=e.find(a=>a.name==game.i18n.localize("LocalizedIDs.wrestle"));if(t)return{name:game.i18n.localize("attackWeaponless"),id:"attackWeaponless",icon:"systems/dsa5/icons/categories/attack_weaponless.webp",attack:t.system.attack.value,damage:"1d6",cssClass:"zbrawl"}}_ridingEntry(e){if(isRiding){let t=H.getHorse(e);if(t){let a=H.getLoyaltyFromHorse(t);if(a)return{name:`${a.name} (${a.system.talentValue.value})`,id:"rideLoyaltyID",icon:a.img,cssClass:"skill",abbrev:a.name[0]}}}}_gmEntries(){return this.gmItems.filter(e=>!e.disabled)}_actionEntry(e,t,a={}){return{name:e.name,id:e.id,icon:e.img,cssClass:t,abbrev:e.name[0],...a}}_skillEntry(e,t,a={}){let s=e.system?.talentValue.value;return{name:s?`${e.name} (${s})`:e.name,id:e.id,icon:e.img,cssClass:t,addClass:e.system?.group?.value,abbrev:e.name[0],tw:s,...a}}_traitEntry(e){let t=T._parseDmg(e.toObject());return{name:e.name,id:e.id,icon:e.img,cssClass:"weapon",abbrev:e.name[0],attack:e.system.at.value,damage:t.damagedie,dadd:t.damageAdd}}_combatEntry(e,t,a,s=[]){let i=e.type=="meleeweapon"?T._prepareMeleeWeapon(e.toObject(),t,a):T._prepareRangeWeapon(e.toObject(),[],t,a);return{name:e.name,id:e.id,icon:e.img,cssClass:"weapon",abbrev:e.name[0],attack:i.attack,damage:i.damagedie,dadd:i.damageAdd,...s}}async _effectEntries(e,t={}){return(await e.actorEffects()).map(a=>{let s=a.getFlag("dsa5","value")||"";return{name:s?`${a.name} (${s})`:a.name,id:a.id,icon:a.icon,cssClass:"effect",abbrev:`${a.name[0]} ${s}`,subfunction:"effect",indicator:s,...t}})}filterButtons(e){switch(e.which){case 91:case 18:case 17:return;case 8:this.searching=this.searching.slice(0,-1);break;default:this.searching+=e.key}e.preventDefault(),e.stopPropagation();let t=this.searching.toLowerCase();de(t);let a=$(e.currentTarget).find(".subbuttons li");a.find(".dsahidden").removeClass("dsahidden"),a.filter(function(){return $(this).find("label").text().toLowerCase().trim().indexOf(t)==-1}).addClass("dsahidden")}async render(e,t={}){let a=await super.render(e,t);return this._element&&this._element.css({zIndex:61}),a}setPosition({left:e,top:t,width:a,height:s,scale:i}={}){let r=super.setPosition({left:e,top:t,width:a,height:s,scale:i}),n=this.element[0];if(!n.style.width||a){let o=a||n.offsetWidth,c=n.style.maxWidth||window.innerWidth;r.width=a=Math.clamped(o,0,c),n.style.width=a+"px",a+r.left>window.innerWidth&&(e=r.left)}return game.settings.set("dsa5","tokenhotbarPosition",{left:r.left,top:r.top}),r}async updateDSA5Hotbar(){if(ui.hotbar.updateDSA5Hotbar(),game.settings.get("dsa5","disableTokenhotbar"))return;let e=canvas.tokens.controlled;if(this.actor=void 0,this.showEffects=!1,e.length===1){let t=e[0].actor;t&&t.isOwner&&(this.actor=t)}e.length>=1&&(this.showEffects=!0),await this.render(!0,{focus:!1})}},Se=ne;u(Se,"TokenHotbar2"),L(Se,"attackTypes",new Set(["meleeweapon","rangeweapon"])),L(Se,"traitTypes",new Set(["meleeAttack","rangeAttack"])),L(Se,"spellTypes",new Set(["liturgy","spell"]));var Ee=class extends Dialog{static async showDialog(){let e=duplicate(CONFIG.statusEffects).map(a=>({name:game.i18n.localize(a.name),icon:a.icon,description:game.i18n.localize(a.description),id:a.id})).sort((a,s)=>a.name.localeCompare(s.name)),t=new Ee({title:game.i18n.localize("CONDITION.add"),content:await renderTemplate("systems/dsa5/templates/dialog/addstatusdialog.html",{effects:e}),buttons:{}});t.position.height=Math.ceil(e.length/3)*36+170,t.render(!0)}activateListeners(e){super.activateListeners(e),e.find(".reactClick").mouseenter(s=>{if(s.currentTarget.getElementsByClassName("hovermenu").length==0){let i=document.createElement("div");i.classList.add("hovermenu"),i.style.cssText="font-size: var(--font-size-20);";let r=document.createElement("i");r.classList.add("fas","fa-cogs"),r.title=game.i18n.localize("ActiveEffects.custom"),r.addEventListener("click",async n=>this.configureEffect(n),!1),i.appendChild(r),s.currentTarget.appendChild(i)}}),e.find(".reactClick").mouseleave(s=>{let i=s.toElement||s.relatedTarget;i.parentNode==this||i==this||s.currentTarget.querySelectorAll(".hovermenu").forEach(r=>r.remove())}),e.find(".quantity-click").mousedown(s=>P.quantityClick(s)),e.find(".reactClick").click(s=>this.addEffect(s.currentTarget.dataset.value));let t=u(s=>this._filterConditions($(s.currentTarget),e),"filterConditions"),a=e.find(".conditionSearch");a.keyup(s=>this._filterConditions($(s.currentTarget),e)),a[0]&&a[0].addEventListener("search",t,!1)}_filterConditions(e,t){if(e.val()!=null){let a=e.val().toLowerCase().trim(),s=t.find(".filterable");t.find(".filterHide").removeClass("filterHide"),s.filter(function(){return $(this).find("span").text().toLowerCase().trim().indexOf(a)==-1}).addClass("filterHide")}}static async modifyEffectDialog(e,t){new Ee({title:game.i18n.localize("CONDITION."+e),content:await renderTemplate("systems/dsa5/templates/dialog/configurestatusdialog.html"),default:"add",buttons:{add:{icon:'',label:game.i18n.localize("CONDITION.add"),callback:async a=>{let s={},i=a.find("[name=unit]:checked").val()=="seconds"?Math.round(a.find(".duration").val()/5):a.find(".duration").val(),r=a.find(".effectname").val();i>0&&mergeObject(s,P._buildDuration(i)),r&&(s.name=r),await t(e,s)}}}}).render(!0,{width:400,resizable:!1,classes:["dsa5","dialog"]})}async configureEffect(e){e.stopPropagation();let a=$(e.currentTarget).closest(".reactClick").attr("data-value");this.close(),Ee.modifyEffectDialog(a,async(s,i)=>this.addEffect(s,i))}async addEffect(e,t={}){for(let a of canvas.tokens.controlled)await a.actor.addTimedCondition(e,1,!1,!1,t);this.close()}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:["dsa5","tokenStatusEffects"],width:700,resizable:!0}),e}};u(Ee,"AddEffectDialog");var si=u(async(l,e,t,a)=>{if(game.user.isGM){let s=await game.dsa5.apps.DSA5_Utility.allMoneyItems(),i=await f.getFolderForType("Actor",null,"Dropped Items"),n=game.users.filter(p=>!p.isGM).map(p=>p.id).reduce((p,g)=>(p[g]=1,p),{default:0}),o=e.toObject();o.system.quantity.value=a,P.obfuscateDropData(o,t.tabsinvisible),getProperty(o,"system.worn.value")&&(o.system.worn.value=!1);let c={type:"npc",name:e.name,img:e.img,prototypeToken:{img:e.img,width:.4,height:.4},ownership:n,items:[...s,o],flags:{core:{sheetClass:"dsa5.MerchantSheetDSA5"}},folder:i,system:{merchant:{merchantType:"loot",temporary:!0,hidePlayer:1},status:{wounds:{value:16}}}},d=await(await game.dsa5.entities.Actordsa5.create(c)).getTokenDocument({x:t.x,y:t.y,hidden:!1});if(!canvas.dimensions.rect.contains(d.x,d.y))return!1;if(l){await canvas.scene.createEmbeddedDocuments("Token",[d],{noHook:!0});let p=e.system.quantity.value-a;p<1?await l.deleteEmbeddedDocuments("Item",[e.id]):await l.updateEmbeddedDocuments("Item",[{_id:e.id,"system.quantity.value":p}])}else await canvas.scene.createEmbeddedDocuments("Token",[d])}else{let s={itemId:e.uuid,sourceActorId:l?.id,data:t,amount:a};game.socket.emit("system.dsa5",{type:"itemDrop",payload:s})}},"dropToGround"),Ki=u(async(l,e)=>{let t=await Item.implementation.fromDropData(e),a=t.parent;if(!b.equipmentCategories.has(t.type))return;let s=u(async i=>{si(a,t,e,i)},"callback");Je.create(game.i18n.localize("DSASETTINGS.enableItemDropToCanvas"),game.i18n.format("MERCHANT.dropGround",{name:t.name}),t.system.quantity.value,s)},"handleItemDrop"),Yi=u(async(l,e)=>{let t=e.x,a=e.y,s=0,i=l.grid.size,r=Math.ceil(Math.sqrt(e.ids.length));for(let n of e.ids){let o=game.actors.get(n);if(!o)continue;let c=await o.getTokenDocument({x:t,y:a,hidden:!1});c.constructor.create(c,{parent:l.scene}),r%s==0&&s>0?(a+=i,t=e.x):t+=i,s++}},"handleGroupDrop"),$i=u(()=>{Hooks.on("dropCanvasData",async(l,e)=>{if(!!(game.settings.get("dsa5","enableItemDropToCanvas")||game.user.isGM||e.tokenId)){if(e.type=="Item")return Ki(l,e),!1;if(e.type=="GroupDrop")return Yi(l,e),!1}})},"connectHook"),Je=class extends Dialog{static async create(e,t,a,s,i=1,r=void 0){r=r||a;let n=await renderTemplate("systems/dsa5/templates/dialog/dropToGround.html",{name:t,min:i,max:r,count:a});new Je({title:e,content:n,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async o=>s(Number(o.find('[name="count"]').val()))},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}activateListeners(e){super.activateListeners(e),e.find('input[type="range"]').change(t=>{$(t.currentTarget).closest(".row-section").find(".range-value").html($(t.currentTarget).val())})}};u(Je,"RangeSelectDialog");var $e=class extends ActorSheet{get actorType(){return this.actor.type}async _render(e=!1,t={}){this._saveSearchFields(),this._saveCollapsed(),await super._render(e,t),this._setCollapsed(),this._restoreSeachFields();let a=$(this._element),s={".close":"SHEET.Close",".configure-sheet":"SHEET.Configure",".configure-token":"SHEET.Token",".import":"SHEET.Import",".locksheet":"SHEET.Lock",".library":"SHEET.Library",".playerview":"SHEET.switchLimited",".actorConfig":"SHEET.actorConfig"};for(let i of Object.keys(s))a.find(i).attr("data-tooltip",s[i]);this.currentFocus&&(a.find('[data-item-id="'+this.currentFocus+'"] input').trigger("focus").trigger("select"),this.currentFocus=null)}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"skills"}],mergeObject(e,{width:770,height:740,scrollY:[".save-scroll"],dragDrop:[{dragSelector:".content .item",dropSelector:null},{dragSelector:".mainEffects .statusEffect",dropSelector:null}]}),e}_saveSearchFields(){if(this.form===null)return;let e=$(this.form).parent();this.searchFields={talentFiltered:$(e.find(".filterTalents")).hasClass("filtered"),searchText:$(e.find(".talentSearch")).val(),gearSearch:$(e.find(".gearSearch")).val()}}_restoreSeachFields(){if(this.searchFields!=null){let e=$(this.form).parent();this.searchFields.talentFiltered&&($(e.find(".filterTalents")).addClass("filtered"),$(e.find(".allTalents")).removeClass("showAll"));let t=$(e.find(".talentSearch"));t.val(this.searchFields.searchText),this.searchFields.searchText!=""&&this._filterTalents(t);let a=$(e.find(".gearSearch"));a.val(this.searchFields.gearSearch),this.searchFields.searchText!=""&&this._filterGear(a)}}_saveCollapsed(){if(this.form===null)return;let e=$(this.form).parent();this.collapsedBoxes=[],this.openDetails=[];let t=e.find(".ch-collapse i");for(let a of t)this.collapsedBoxes.push($(a).attr("class"));for(let a of $(e.find(".expandDetails.shown")))this.openDetails.push($(a).closest(".item").attr("data-item-id"))}_setCollapsed(){let e=$(this.form).parent();if(this.collapsedBoxes){let t=e.find(".ch-collapse i");for(let a=0;an.name==s&&n.type=="skill"),r=`

    ${game.i18n.localize("TYPES.Item.aggregatedTest")}

    `;a.system.usedTestCount.value>=a.system.allowedTestCount.value?(r+=`${game.i18n.localize("Aggregated.noMoreAllowed")}`,ChatMessage.create(f.chatDataSetup(r))):this.actor.setupSkill(i,{moreModifiers:[{name:game.i18n.localize("failedTests"),value:-1*a.system.previousFailedTests.value,selected:!0},{name:game.i18n.localize("Modifier"),value:a.system.baseModifier,selected:!0}]},this.getTokenId()).then(n=>{this.actor.basicTest(n).then(o=>{o.result.successLevel>0?(a.system.cummulatedQS.value=o.result.qualityStep+a.system.cummulatedQS.value,a.system.cummulatedQS.value=Math.min(10,a.system.cummulatedQS.value)):a.system.previousFailedTests.value+=1,a.system.usedTestCount.value+=1,this.actor.updateEmbeddedDocuments("Item",[a]).then(()=>{let c=this.actor.items.get(t);c.postItem(),a.system.cummulatedQS.value>=10&&c.sheet.postFinishedItem()})})})}async consumeItem(e){new Dialog({title:game.i18n.localize("SHEET.ConsumeItem")+": "+e.name,content:game.i18n.localize("SHEET.ConsumeItem")+": "+e.name,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{e.setupEffect(null,{},this.getTokenId())}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}async _advanceAttribute(e){let t=Number(this.actor.system.characteristics[e].advances),a=t+Number(this.actor.system.characteristics[e].initial),s=f._calculateAdvCost(a,"E");await this._checkEnoughXP(s)&&(await this._updateAPs(s,{[`system.characteristics.${e}.advances`]:t+1}),await _.track(this.actor,{type:"attribute",attr:e,previous:a,next:a+1},s))}async _refundAttributeAdvance(e){let t=Number(this.actor.system.characteristics[e].advances),a=t+Number(this.actor.system.characteristics[e].initial);if(t>0){let s=f._calculateAdvCost(a,"E",0)*-1;await this._updateAPs(s,{[`system.characteristics.${e}.advances`]:t-1}),await _.track(this.actor,{type:"attribute",attr:e,previous:a,next:a-1},s)}}async _rebuyPC(e){if(this.actor.system.status[e].permanentLossSum>0&&await this._checkEnoughXP(2)){let t=Number(this.actor.system.status[e].rebuy);await this._updateAPs(2,{[`system.status.${e}.rebuy`]:t+1}),await _.track(this.actor,{type:"permanentLoss",attr:e,previous:t,next:t+1},2)}}async _refundPC(e){if(this.actor.system.status[e].rebuy>0){let t=Number(this.actor.system.status[e].rebuy);await this._updateAPs(-2,{[`system.status.${e}.rebuy`]:t-1}),await _.track(this.actor,{type:"permanentLoss",attr:e,previous:t,next:t-1},-2)}}async _advancePoints(e){let t=Number(this.actor.system.status[e].advances),a=f._calculateAdvCost(t,"D");await this._checkEnoughXP(a)&&this._checkMaximumPointAdvancement(e,t+1)&&(await this._updateAPs(a,{[`system.status.${e}.advances`]:t+1}),await _.track(this.actor,{type:"point",attr:e,previous:t,next:t+1},a))}async _refundPointsAdvance(e){let t=Number(this.actor.system.status[e].advances);if(t>0){let a=f._calculateAdvCost(t,"D",0)*-1;await this._updateAPs(a,{[`system.status.${e}.advances`]:t-1}),await _.track(this.actor,{type:"point",attr:e,previous:t,next:t-1},a)}}async _advanceItem(e){let t=this.actor.items.get(e),a=Number(t.system.talentValue.value),s=f._calculateAdvCost(a,t.system.StF.value);await this._checkEnoughXP(s)&&this.actor._checkMaximumItemAdvancement(t,a+1)?.result&&(await this.actor.updateEmbeddedDocuments("Item",[{_id:e,"system.talentValue.value":a+1}]),await this._updateAPs(s),await _.track(this.actor,{type:"item",item:t,previous:a,next:a+1},s))}async _refundItemAdvance(e){let t=this.actor.items.get(e),a=t.type=="combatskill"?6:0,s=Number(t.system.talentValue.value);if(s>a){let i=f._calculateAdvCost(s,t.system.StF.value,0)*-1;await this.actor.updateEmbeddedDocuments("Item",[{_id:e,"system.talentValue.value":s-1}]),await this._updateAPs(i),await _.track(this.actor,{type:"item",item:t,previous:s,next:s-1},i)}}_checkMaximumPointAdvancement(e,t){let a=!1;switch(e){case"wounds":a=t<=this.actor.system.characteristics.ko.value;break;case"astralenergy":a=t<=(this.actor.system.characteristics[this.actor.system.guidevalue.magical]==null?0:this.actor.system.characteristics[this.actor.system.guidevalue.magical].value*this.actor.system.energyfactor.magical);break;case"karmaenergy":a=t<=(this.actor.system.characteristics[this.actor.system.guidevalue.clerical]==null?0:this.actor.system.characteristics[this.actor.system.guidevalue.clerical].value*this.actor.system.energyfactor.clerical);break}return a||ui.notifications.error(game.i18n.localize("DSAError.AdvanceMaximumReached")),a}async _openLibrary(){game.dsa5.itemLibrary.render(!0)}async _configActor(){Ye.buildDialog(this.actor)}_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"library",icon:"fas fa-university",onclick:async()=>this._openLibrary()}),this.actor.isOwner&&(e.unshift({class:"actorConfig",icon:"fas fa-link",onclick:async()=>this._configActor()}),e.unshift({class:"playerview",icon:"fas fa-toggle-on",onclick:async t=>this._togglePlayerview(t)})),this.actor.system.canAdvance&&e.unshift({class:"locksheet",icon:`fas fa-${this.actor.system.sheetLocked.value?"":"un"}lock`,onclick:async t=>this._changeAdvanceLock(t)}),e}async _changeAdvanceLock(e){await this.actor.update({"system.sheetLocked.value":!this.actor.system.sheetLocked.value}),$(e.currentTarget).find("i").toggleClass("fa-unlock fa-lock")}async _checkEnoughXP(e){return await this.actor.checkEnoughXP(e)}async advanceWrapper(e,t,a){let i=$(e.currentTarget).find("i");i.hasClass("fa-spin")||(i.addClass("fa-spin fa-spinner"),await this[t](a),i.removeClass("fa-spin fa-spinner"))}playerViewEnabled(){return getProperty(this.actor.system,"playerView")}_togglePlayerview(e){this.actor.update({"system.playerView":!getProperty(this.actor.system,"playerView")})}showLimited(){return!game.user.isGM&&this.actor.limited||this.playerViewEnabled()}getTokenId(){return this.token?.id}rollDisease(e){let t=this.actor.items.get(e),a=this.actor.system.status.soulpower.max*-1,s=this.actor.system.status.toughness.max*-1;t.setupEffect(void 0,{rollMode:"gmroll",manualResistance:{SKModifier:a,ZKModifier:s}}).then(async i=>{let r=await t.itemTest(i);await this.actor.updateEmbeddedDocuments("Item",[{_id:t.id,"system.duration.resolved":r.result.duration}])})}async swapWeaponHand(e){let t=this._getItemId(e),a=this.actor.items.get(t);["Daggers","Fencing Weapons"].includes(game.i18n.localize(`LocalizedCTs.${a.system.combatskill.value}`))||await this.actor.updateEmbeddedDocuments("Item",[{_id:t,"system.worn.wrongGrip":!a.system.worn.wrongGrip}])}activateListeners(e){super.activateListeners(e);let t=u(d=>{this.actor.items.get(this._getItemId(d)).postItem()},"posthand");e.find(".roll-disease").click(d=>this.rollDisease(this._getItemId(d))),oe(e),e.find(".condition-edit").click(async d=>{(d.currentTarget.dataset.uuid?await fromUuid(d.currentTarget.dataset.uuid):this.actor.effects.get(d.currentTarget.dataset.id)).sheet.render(!0)}),e.find(".ch-collapse").click(d=>{$(d.currentTarget).find("i").toggleClass("fa-angle-up fa-angle-down"),$(d.currentTarget).closest(".groupbox").find(".row-section:nth-child(2)").fadeToggle()}),e.find(".status-create").click(d=>{let p=$(d.currentTarget).closest(".statusEffectMenu").find("ul");p.fadeIn("fast",()=>{p.find("input").trigger("focus")})}),e.find(".statusEffectMenu ul").mouseleave(d=>$(d.currentTarget).fadeOut()),e.find(".roll-aggregated").mousedown(d=>this._handleAggregatedProbe(d)),e.find(".skill-select").mousedown(d=>{let p=this._getItemId(d),g=this.actor.items.get(p);d.button==0?this.actor.setupSkill(g,{},this.getTokenId()).then(y=>{this.actor.basicTest(y)}):d.button==2&&g.sheet.render(!0)}),e.find(".spell-select").mousedown(d=>{let p=this._getItemId(d),g=this.actor.items.get(p);d.button==0?this.actor.setupSpell(g,{},this.getTokenId()).then(y=>this.actor.basicTest(y)):d.button==2&&g.sheet.render(!0)}),e.find(".item-post").click(d=>t(d)),e.find(".item-dropdown").click(d=>{d.preventDefault(),$(d.currentTarget).closest(".item").find(".expandDetails:first").toggleClass("shown")}),e.find(".condition-show").mousedown(d=>{d.preventDefault();let p=d.currentTarget.dataset.id,g=$(d.currentTarget).parents(".statusEffect").attr("data-descriptor");if(d.button==0){let y=$(d.currentTarget).parents(".statusEffect").attr("data-origin");if(y)fromUuid(y).then(h=>h.sheet.render(!0));else{let h,w;g?(h=CONFIG.statusEffects.find(v=>v.id==g),w=$(`
    ${game.i18n.localize(h.name)}: ${game.i18n.localize(h.description)}
    `)):(h=this.actor.effects.find(v=>v.id==p),h&&(w=$(`
    ${game.i18n.localize(h.name)}: ${game.i18n.localize(h.flags.dsa5.description)}
    `)));let x=$(d.currentTarget).closest(".groupbox").find(".effectDescription");x.fadeOut("fast",function(){x.html(w).fadeIn("fast")})}}else d.button==2&&!d.currentTarget.dataset.locked&&this._deleteActiveEffect(p)}),e.on("click",".chat-condition",d=>ae.postStatus(d.currentTarget.dataset.id)),e.find(".money-change, .skill-advances").focusin(d=>{this.currentFocus=$(d.currentTarget).closest("[data-item-id]").attr("data-item-id")}),e.find(".item-edit").click(d=>{d.preventDefault();let p=this._getItemId(d);this.actor.items.get(p).sheet.render(!0)}),e.find(".showApplication").mousedown(d=>{if(d.preventDefault(),d.button==2)this._deleteItem(d);else{let p=this._getItemId(d);this.actor.items.get(p).sheet.render(!0)}}),e.find(".ch-value").click(d=>{d.preventDefault();let p=d.currentTarget.attributes["data-char"].value;this.actor.setupCharacteristic(p,{},this.getTokenId()).then(g=>this.actor.basicTest(g))}),e.find(".ch-status").click(d=>{d.preventDefault(),this.actor.setupDodge({},this.getTokenId()).then(p=>{this.actor.basicTest(p)})}),e.find(".ch-regenerate").click(d=>{d.preventDefault(),this.actor.setupRegeneration("regenerate",{},this.getTokenId()).then(p=>this.actor.basicTest(p))}),e.find(".ch-weaponless").click(d=>{d.preventDefault();let p=d.currentTarget.attributes["data-char"].value;this.actor.setupWeaponless(p,{},this.getTokenId()).then(g=>this.actor.basicTest(g))}),e.find(".ch-fallingDamage").click(d=>{d.preventDefault(),this.actor.setupFallingDamage({},this.getTokenId())}),e.find(".ch-rollCombat").click(d=>{d.preventDefault();let p=this._getItemId(d),g=d.currentTarget.dataset.mode,y=this.actor.items.get(p);this.actor.setupWeapon(y,g,{},this.getTokenId()).then(h=>this.actor.basicTest(h))});let a=u(d=>this._deleteItem(d),"deletehand");e.find(".cards .item").mouseenter(d=>{if(d.currentTarget.getElementsByClassName("hovermenu").length==0){let p=document.createElement("div");p.classList.add("hovermenu");let g=document.createElement("i");g.classList.add("fas","fa-times"),g.title=game.i18n.localize("SHEET.DeleteItem"),g.addEventListener("click",a,!1);let y=document.createElement("i");y.classList.add("fas","fa-comment"),y.title=game.i18n.localize("SHEET.PostItem"),y.addEventListener("click",t,!1),p.appendChild(y),p.appendChild(g),d.currentTarget.appendChild(p)}}),e.find(".cards .item").mouseleave(d=>{let p=d.toElement||d.relatedTarget;!p||p.parentNode==this||p==this||d.currentTarget.querySelectorAll(".hovermenu").forEach(g=>g.remove())});let s=this.actor.uuid;e.find(".actorDrag").each(function(d,p){p.setAttribute("draggable",!0),p.addEventListener("dragstart",g=>{let y={type:"Actor",uuid:s};g.dataTransfer.setData("text/plain",JSON.stringify(y))})}),e.find(".filterTalents").click(d=>{$(d.currentTarget).closest(".content").find(".allTalents").toggleClass("showAll"),$(d.currentTarget).toggleClass("filtered")}),e.find(".charimg").mousedown(d=>{d.button==2&&f.showArtwork(this.actor,!0)}),se.bindRollCommands(e);let i=u(d=>this._filterTalents($(d.currentTarget)),"filterTalents"),r=e.find(".talentSearch");r.keyup(d=>this._filterTalents($(d.currentTarget))),r[0]&&r[0].addEventListener("search",i,!1);let n=u(d=>this._filterConditions($(d.currentTarget)),"filterConditions"),o=e.find(".conditionSearch");o.keyup(d=>this._filterConditions($(d.currentTarget))),o[0]&&o[0].addEventListener("search",n,!1);let c=u(d=>this._filterGear($(d.currentTarget)),"filterGear"),m=e.find(".gearSearch");m.keyup(d=>this._filterGear($(d.currentTarget))),m[0]&&m[0].addEventListener("search",c,!1),mt(e,"img.charimg"),H.activateListeners(e,this.actor),this._bindKeepFieldsEnabled(e),this.isEditable&&(new ContextMenu(e,".item .withContext",[],{onOpen:this._onItemContext.bind(this)}),e.find(".startCharacterBuilder").click(()=>this.actor.setFlag("core","sheetClass","dsa5.DSACharBuilder")),e.find(".schipUpdate").click(d=>{d.preventDefault();let p=Number(d.currentTarget.getAttribute("data-val"));p==1&&$(this.form).find(".fullSchip").length==1&&(p=0),this.actor.update({"system.status.fatePoints.value":p})}),e.find(".swapWeaponHand").click(d=>this.swapWeaponHand(d)),e.find(".defenseToggle").click(()=>this.actor.update({"system.config.defense":!this.actor.system.config.defense})),e.find(".loadWeapon").mousedown(async d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject();if(getProperty(g,"system.currentAmmo.value")==="")return;let y={_id:p};if(d.button==0){let h=g.type=="trait"?g.system.reloadTime.value:T.calcLZ(g,this.actor);y["system.reloadTime.progress"]=Math.min(g.system.reloadTime.progress+1,h)}else d.button==2&&(y["system.reloadTime.progress"]=0);await this.actor.updateEmbeddedDocuments("Item",[y])}),e.find(".chargeSpell").mousedown(async d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject(),y=Number(g.system.castingTime.modified);d.button==0?g.system.castingTime.progress=Math.min(g.system.castingTime.progress+1,y):d.button==2&&(g.system.castingTime.progress=0,g.system.castingTime.modified=0),await this.actor.updateEmbeddedDocuments("Item",[g])}),e.find(".item-swapMag").click(async d=>{await this.actor.swapMag(this._getItemId(d))}),e.find(".ammo-selector").change(async d=>{d.preventDefault();let p=this._getItemId(d);await this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.currentAmmo.value":$(d.currentTarget).val()}])}),e.find(".item-toggle").click(d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject();switch(g.type){case"armor":case"rangeweapon":case"meleeweapon":case"equipment":this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.worn.value":!g.system.worn.value}]),K.playEquipmentWearStatusChange(g);break}}),e.find(".quantity-click").mousedown(d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject();P.increment(d,g,"system.quantity.value",0),this.actor.updateEmbeddedDocuments("Item",[g])}),e.find(".status-add").mousedown(async d=>{let p=d.currentTarget.dataset.id;p=="custom"?E.createCustomEffect(this.actor):d.button==0?await this.actor.addCondition(p,1,!1,!1):d.button==2&&Ee.modifyEffectDialog(p,async(g,y)=>this.actor.addTimedCondition(g,1,!1,!1,y))}),e.find(".money-change").change(async d=>{let p=this._getItemId(d);await this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.quantity.value":Number(d.target.value)}])}),e.find(".skill-advances").change(async d=>{let p=this._getItemId(d);await this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.talentValue.value":Number(d.target.value)}])}),e.find(".advance-attribute").mousedown(d=>this.advanceWrapper(d,"_advanceAttribute",d.currentTarget.dataset.attr)),e.find(".refund-attribute").mousedown(d=>this.advanceWrapper(d,"_refundAttributeAdvance",d.currentTarget.dataset.attr)),e.find(".advance-item").mousedown(d=>this.advanceWrapper(d,"_advanceItem",this._getItemId(d))),e.find(".refund-item").mousedown(d=>this.advanceWrapper(d,"_refundItemAdvance",this._getItemId(d))),e.find(".advance-points").mousedown(d=>this.advanceWrapper(d,"_advancePoints",d.currentTarget.dataset.attr)),e.find(".refund-points").mousedown(d=>this.advanceWrapper(d,"_refundPointsAdvance",d.currentTarget.dataset.attr)),e.find(".rebuy-pc").mousedown(d=>this.advanceWrapper(d,"_rebuyPC",d.currentTarget.dataset.attr)),e.find(".refund-pc").mousedown(d=>this.advanceWrapper(d,"_refundPC",d.currentTarget.dataset.attr)),e.find(".onUseItem").mousedown(d=>this._onMacroUseItem(d)),e.find(".traditionPayCost").mousedown(d=>this._payAeSpecialAbilityCost(d)),e.find(".item-create").click(d=>this._onItemCreate(d)),e.find(".condition-toggle").mousedown(async d=>{let p=$(d.currentTarget).parents(".statusEffect").attr("data-id"),g=this.actor.effects.get(p);await g.update({disabled:!g.disabled})}),e.find(".condition-value").mousedown(async d=>{let p=$(d.currentTarget).parents(".statusEffect").attr("data-descriptor");d.button==0?await this.actor.addCondition(p,1,!1,!1):d.button==2&&await this.actor.removeCondition(p,1,!1)}),e.find(".item-delete").click(d=>this._deleteItem(d)),e.find(".tradition-delete").click(d=>this._deleteTraditionArtifact(d)),e.find(".selectTraditionartifact").click(()=>this.selectTraditionartifact()),e.find(".disableRegeneration").click(d=>{let g=`system.repeatingEffects.disabled.${d.currentTarget.dataset.type}`;this.actor.update({[g]:!getProperty(this.actor,g)})}))}_onItemContext(e){let t=this.actor.items.get($(e).closest(".item").attr("data-item-id"));!t||(ui.context.menuItems=this._getItemContextOptions(t),Hooks.call("dsa5.getItemContextOptions",t,ui.context.menuItems))}_getItemContextOptions(e){let t=[{name:"SHEET.EditItem",icon:"",callback:()=>e.sheet.render(!0)},{name:"SHEET.PostItem",icon:"",callback:()=>e.postItem()},{name:"SHEET.DuplicateItem",icon:"",callback:()=>this.handleItemCopy(e.toObject(),e.type)},{name:"SHEET.ConsumeItem",icon:"",condition:()=>e.type=="consumable",callback:()=>this.consumeItem(e)},{name:"SHEET.onUseEffect",icon:"",condition:()=>getProperty(e,"flags.dsa5.onUseEffect"),callback:()=>new X(e).executeOnUseEffect()},{name:"SHEET.DeleteItem",icon:"",callback:()=>this._itemDeleteDialog(e)},{name:"MERCHANT.exchange",icon:"",condition:()=>b.equipmentCategories.has(e.type),callback:()=>this._startTrade(e)}];return(hasProperty(e,"system.worn.wearable")||["meleeweapon","rangeweapon","armor"].includes(e.type))&&t.push({name:"SHEET.EquipItem",icon:"",callback:()=>e.update({"system.worn.value":!e.system.worn.value})}),Number(getProperty(e,"system.quantity.value"))>1&&t.push({name:"SHEET.SplitItem",icon:"",callback:()=>this._splitItem(e)}),t}async _startTrade(e){new Yt(this.actor).render(!0)}_splitItem(e){let t=u(async a=>{let s=e.toObject();s.system.quantity.value=a,await this.actor.createEmbeddedDocuments("Item",[s],{render:!1}),await this.actor.updateEmbeddedDocuments("Item",[{_id:e.id,"system.quantity.value":e.system.quantity.value-a}])},"callback");Je.create(game.i18n.localize("SHEET.SplitItem"),game.i18n.format("MERCHANT.splitItem",{name:e.name}),e.system.quantity.value-1,t,1,e.system.quantity.value-1)}_bindKeepFieldsEnabled(e){if(!this.isEditable){let t=e.find(".keepFieldsEnabled");for(let a of t){let s=a.dataset.attr,i=a.dataset.name;$(a).find(".editor").append(``),$(a).find(".editor-edit").click(r=>this._openKeepFieldEditpage(r))}}}_openKeepFieldEditpage(e){let t=e.currentTarget.dataset.attr,a=e.currentTarget.dataset.name;new At(this.actor.id,t,a).render(!0)}async _onMacroUseItem(e){let t=this.actor.items.get(this._getItemId(e));await new X(t).executeOnUseEffect()}async _payAeSpecialAbilityCost(e){let t=this.actor.items.get(this._getItemId(e)),a=Number(getProperty(t,"system.AsPCost"));if(!this.actor.applyMana(a,"AsP"))return;let i=game.i18n.format("CHATNOTIFICATION.paysTraditionAbility",{name:this.actor.name,ability:t.name,cost:a});e.button==2?ChatMessage.create(f.chatDataSetup(i,"gmroll")):ChatMessage.create(f.chatDataSetup(i))}_filterGear(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.element).find(".inventory .item");a.removeClass("filterHide"),a.filter(function(){return $(this).find("a.item-edit").text().toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide")}}async selectTraditionartifact(){!this.isEditable||new ps(this.actor).render(!0)}_deleteTraditionArtifact(e){if(!this.isEditable)return;this.actor.items.get(this._getItemId(e)).update({"system.isArtifact":!1})}_filterTalents(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.form).parent().find(".allTalents");a.find(".item, .table-header, .table-title").removeClass("filterHide"),a.addClass("showAll").find(".item").filter(function(){return $(this).find(".talentName").text().toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide"),t.length>0?(a.find(".table-header, .table-title:not(:eq(0))").addClass("filterHide"),a.addClass("filterfull")):a.removeClass("filterfull")}}_filterConditions(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.form).find(".statusEffectMenu li:not(.search)");a.removeClass("filterHide"),a.filter(function(){return game.i18n.localize($(this).find("a").attr("data-tooltip")).toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide")}}async _deleteActiveEffect(e){if(!this.isEditable)return;let t=this.actor.effects.find(a=>a.id==e);t&&(this.token?this.token.actor:this.actor)&&await this.actor.deleteEmbeddedDocuments("ActiveEffect",[t.id])}async _itemDeleteDialog(e){let t=game.i18n.format("DIALOG.DeleteItemDetail",{item:e.name}),a=await renderTemplate("systems/dsa5/templates/dialog/delete-item-dialog.html",{message:t});await new Promise((s,i)=>{new Dialog({title:game.i18n.localize("DIALOG.deleteConfirmation"),content:a,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async()=>{await this._cleverDeleteItem(e.id),s(!0)}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)})}async _deleteItem(e){if(!this.isEditable)return;let t=this._getItemId(e),a=this.actor.items.get(t);this._itemDeleteDialog(a)}async _cleverDeleteItem(e){let t=this.actor.items.get(e),a=[e];switch(t.type){case"advantage":case"disadvantage":await O.vantageRemoved(this.actor,t,!1);break;case"specialability":await R.abilityRemoved(this.actor,t,!1);break;case"blessing":case"magictrick":await this._updateAPs(-1,{},{render:!1}),await _.track(this.actor,{type:"item",item:t,state:-1},-1);break;case"ritual":case"ceremony":case"liturgy":case"spell":{let s=0;for(let r=0;r<=t.system.talentValue.value;r++)s+=f._calculateAdvCost(r,t.system.StF.value,0);let i=this.actor.items.filter(r=>r.type=="spellextension"&&t.type==r.system.category&&t.name==r.system.source);i&&(s+=i.reduce((r,n)=>r+(Number(n.system.APValue.value)||0),0),a.push(...i.map(r=>r.id))),await this._updateAPs(s*-1,{},{render:!1}),await _.track(this.actor,{type:"item",item:t,state:-1},s)}break}await this.actor.deleteEmbeddedDocuments("Item",a)}_getItemId(e){return $(e.currentTarget).closest(".item").attr("data-item-id")}async _addMoney(e){let a=duplicate(this.actor.items.filter(s=>s.type=="money")).find(s=>s.name==e.name);a?(a.system.quantity.value+=e.system.quantity.value,await this.actor.updateEmbeddedDocuments("Item",[a])):await this.actor.createEmbeddedDocuments("Item",[e])}async _updateAPs(e,t={},a={}){await this.actor._updateAPs(e,t,a)}async _addVantage(e,t){O.needsAdoption(this.actor,e,t)}async _addSpecialAbility(e,t){R.needsAdoption(this.actor,e,t)}_onDragStart(e){let t=e.currentTarget;if(e.target.classList.contains("content-link"))return;let a;t.dataset.itemId&&(a=this.actor.items.get(t.dataset.itemId).toDragData(),t.dataset.mod&&(a.mod=t.dataset.mod)),t.dataset.id&&(a=this.actor.effects.get(t.dataset.id).toDragData()),a&&e.dataTransfer.setData("text/plain",JSON.stringify(a))}async _handleSpellExtension(e){if(!this.actor.items.find(a=>a.type==e.type&&a.name==e.name)){e=duplicate(e);let a=this.actor.items.find(s=>s.type==e.system.category&&s.name==e.system.source);if(!a)ui.notifications.error(game.i18n.format("DSAError.noSpellForExtension",{name:e.system.source,category:f.categoryLocalization(e.system.category),extension:e.name}));else{if(a.system.talentValue.values.type==e.type&&s.name==e.name),a;if(e=duplicate(e),!t){switch(e.type){case"spell":case"liturgy":case"ceremony":case"ritual":a=f._calculateAdvCost(0,e.system.StF.value,0);break;case"blessing":case"magictrick":a=1;break;case"magicalsign":a=e.system.APValue.value;break;default:return}if(await this.actor.checkEnoughXP(a)){await this._updateAPs(a,{},{render:!1});let s=(await this.actor.createEmbeddedDocuments("Item",[e]))[0];await _.track(this.actor,{type:"item",item:s,state:1},a)}}}async _addLoot(e){e=duplicate(e);let t=this.actor.items.find(a=>A.areEquals(e,a));return t?(await A.stackItems(t,e,this.actor))[0]:(this._tabs[0].active=="combat"&&e.system.worn&&(e.system.worn.value=!0),(await this.actor.createEmbeddedDocuments("Item",[e]))[0])}async _addUniqueItem(e){if(e=duplicate(e),!this.actor.items.some(t=>A.areEquals(e,t)))return(await this.actor.createEmbeddedDocuments("Item",[e]))[0]}async _addDemonMarkOrPatron(e){return await this._addUniqueItem(e)}async _addDisease(e){return e.system.duration.resolved="?",await this._addUniqueItem(e)}async handleItemCopy(e,t){e.name+=" (Copy)",this._manageDragItems(e,t)}async _addFullPack(e){let a=(await game.packs.get(e.name).getDocuments()).filter(s=>!this.actor.items.find(i=>i.type==s.type&&i.name==s.name));e.onlyType&&(a=a.filter(s=>s.type==e.onlyType)),await this.actor.createEmbeddedDocuments("Item",a.map(s=>s.toObject()))}async creatureDrop(e){game.dsa5.config.hooks.shapeshift?new Dialog({title:game.i18n.localize("DIALOG.ItemRequiresAdoption")+": "+e.name,content:game.i18n.localize("DIALOG.whichFunction")+": "+e.name,default:"horse",buttons:{shapeshift:{icon:'',label:game.i18n.localize("CONDITION.shapeshift"),callback:()=>{let t=game.dsa5.config.hooks.shapeshift;t.setShapeshift(this.actor,e),t.render(!0)}},horse:{icon:'',label:game.i18n.localize("RIDING.horse"),callback:()=>{H.setHorse(this.actor,e)}}}}).render(!0):H.setHorse(this.actor,e)}async _manageDragItems(e,t){switch(t){case"disease":await this._addDisease(e);break;case"meleeweapon":case"rangeweapon":case"equipment":case"ammunition":case"armor":case"poison":case"consumable":case"plant":return await this._addLoot(e);case"disadvantage":case"advantage":await this._addVantage(e,t);break;case"specialability":await this._addSpecialAbility(e,t);break;case"money":await this._addMoney(e);break;case"ritual":case"ceremony":case"blessing":case"magictrick":case"liturgy":case"spell":case"magicalsign":await this._addSpellOrLiturgy(e);break;case"effectwrapper":await this._handleEffectWrapper(e);break;case"application":await this._handleApplication(e);break;case"spellextension":await this._handleSpellExtension(e);break;case"creature":this.creatureDrop(e);break;case"skill":case"imprint":case"essence":case"information":await this._addUniqueItem(e);break;case"patron":case"demonmark":await this._addDemonMarkOrPatron(e);break;default:ui.notifications.error(game.i18n.format("DSAError.canNotBeAdded",{item:e.name,category:game.i18n.localize(e.type)}))}}async _handleEffectWrapper(e){this.actor.createEmbeddedDocuments("ActiveEffect",e.effects.map(t=>(t.origin=null,t)))}async _handleLookup(e){let t=await f.findAnyItem(e.items);if(t){for(let a of e.items)if(a.count){let s=t.find(i=>i.name==a.name&&i.type==a.type);s?(s.system.quantity.value=a.count,a.qs&&a.type=="consumable"&&(s.system.QL=a.qs)):ui.notifications.warn(game.i18n.format("DSAError.notFound",{category:a.type,name:a.name}))}await this.actor.createEmbeddedDocuments("Item",t)}else ui.notifications.error(game.i18n.format("DSAError.notFound",{category:thing.type,name:thing.name}))}async _handleApplication(e){e=duplicate(e),this.actor.items.find(a=>a.type==e.type&&a.name==e.name)||await this.actor.createEmbeddedDocuments("Item",[e])}async _handleRemoveSourceOnDrop(e){let t=e.parent;t&&t.isOwner&&await t.deleteEmbeddedDocuments("Item",[e._id])}async _onDropItemCreate(e){return e instanceof Array?this.actor.createEmbeddedDocuments("Item",e):await this._manageDragItems(e,e.type)}async _onDropActor(e,t){if(!this.actor.isOwner)return!1;let{item:a,typeClass:s,selfTarget:i}=await Ge(t,this.id,!1);if(!i)return await this._manageDragItems(a,s)}async _onDropActiveEffect(e,t){let a=await ActiveEffect.implementation.fromDropData(t);if(!this.actor.isOwner||!a||this.actor.uuid===a.parent?.uuid)return!1;let s=a.toObject();return s.origin=null,ActiveEffect.create(s,{parent:this.actor})}async _onDropItem(e,t){if(!this.actor.isOwner)return!1;let a=await Item.implementation.fromDropData(t),s=a.toObject();P.obfuscateDropData(s,t.tabsinvisible);let i,r=!1,n=$(e.target).parents(".item");if(n&&b.equipmentCategories.has(a.type)){let c=n.attr("data-item-id");c!=a.id&&(n.attr("data-category")=="bags"?i=c:(n=this.actor.items.get(c),r=n&&hasProperty(a,"system.quantity.value")&&hasProperty(n,"system.quantity.value")&&A.areEquals(a,n)))}let o=this.actor.uuid===a.parent?.uuid;if(o)if(e.ctrlKey)await this.handleItemCopy(s,a.type);else if(r)await n.update({"system.quantity.value":n.system.quantity.value+a.system.quantity.value},{render:!1}),await this.actor.deleteEmbeddedDocuments("Item",[a.id]);else if(i){let c={_id:a.id,"system.parent_id":i};a.system.worn&&a.system.worn.value&&(c["system.worn.value"]=!1),await this.actor.updateEmbeddedDocuments("Item",[c])}else b.equipmentCategories.has(a.type)&&await this.actor.updateEmbeddedDocuments("Item",[{_id:a.id,system:{parent_id:0}}]);else{if(this._itemHasPrice(t)){let m=`${a.type=="consumable"?A.getSubClass(s.type).consumablePrice(s):Number(s.system.price.value)}`;if(m&&!await B.payMoney(this.actor,m,!0,!1))return;de(game.i18n.format("PAYMENT.pay",{actor:this.actor.name,amount:m})),K.playMoneySound()}await this._onDropItemCreate(s)}e.altKey&&!o&&b.equipmentCategories.has(a.type)&&await this._handleRemoveSourceOnDrop(a)}_itemHasPrice(e){return e.pay}};u($e,"ActorSheetDsa5");var ps=class extends Application{constructor(e,t={}){super(t),this.actor=e}get template(){return"systems/dsa5/templates/actors/traditionPicker.html"}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:440,resizable:!0}),e}async getData(e){let t=await super.getData(e),a=this.actor.items.filter(s=>["equipment","armor","rangeweapon","meleeweapon"].includes(s.type));return mergeObject(t,{items:a}),t}activateListeners(e){super.activateListeners(e),e.find(".slot").click(async t=>{let a=this.actor.items.get(t.currentTarget.dataset.itemId);await a.update({"system.isArtifact":!a.system.isArtifact})})}};u(ps,"TraditionArtifactpicker");var re=class extends Application{constructor(e){super(e),this.actor=null,this.errors=[],this.attributes=[],this.updating=!1}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"description"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog","generationWizard"]),width:770,height:740}),e.resizable=!0,e}async findCompendiumItem(e,t){for(let a of t){let s=await game.dsa5.itemLibrary.findCompendiumItem(e,a);if(s=s.find(i=>i.name==e&&i.type==a&&i.system),s)return s}}_parseAttributes(e,t=","){let a=[],s=game.i18n.localize("combatskillcountdivider")+":";for(let i of e.split(t))if(i.includes(s)){let r=i.split(":");a.push({choices:r[1].split("/").map(n=>n.trim()),allowedCount:Number(r[0].match(/\d/g))})}return a}async parseToItem(e,t){return e.trim()==""?[]:await Promise.all(e.split(", ").map(async a=>{let s=f.parseAbilityString(a.trim()),i=await this.findCompendiumItem(s.original,t);if(i||(i=await this.findCompendiumItem(s.name,t)),i){let n=i.uuid;i=duplicate(i),i.uuid=n,i.tooltip=game.i18n.localize("Details"),i=te.reverseAdoptionCalculation(this.actor,s,i),i.system.APValue&&(i.APunparseable=isNaN(i.system.APValue.value),i.apCost=i.APunparseable?i.system.APValue.value:s.step*Number(i.system.APValue.value))}else if(this.attributes.includes(s.name)){let n=0;for(let o=this.actor.system.characteristics[game.dsa5.config.knownShortcuts[s.name.toLowerCase()][1]].value+1;o`);let n=t.map(o=>f.categoryLocalization(o)).join("/");this.errors.push(`${n}: ${a}`),i={name:a.trim(),notFound:!0,tooltip:game.i18n.localize("DSAError.itemNotFound"),apCost:"?"}}i.replaceName=s.original,i.step=s.step;let r=this.actor.items.find(n=>t.includes(n.type)&&n.name==s.original)!=null;return i.disabled=r||i.notFound||i.APunparseable,r&&(i.tooltip=game.i18n.localize("YouAlreadyHaveit")),i}))}mergeLevels(e,t,a){let s=!1,i=e.find(r=>r.name==t.name&&r.type==t.type);if(i){s=!0;let r=Number(getProperty(t,"system.step.value"));r&&(i.system.step.value=Math.min(i.system.step.value+=r,i.system[a].value))}else e.push(t);return s}async addSelections(e,t=!0){let a=[];for(let s of e){if($(s).val()=="")continue;let r=(await fromUuid($(s).val())).toObject(),n=f.parseAbilityString(r.name);switch(r.name=$(s).attr("name"),r.type){case"advantage":case"disadvantage":r.system.step.value=Number(s.dataset.step),r=te.reverseAdoptionCalculation(this.actor,n,r),this.mergeLevels(a,r,"max")||O.vantageAdded(this.actor,r);break;case"specialability":r.system.step.value=Number(s.dataset.step),s.dataset.free=="true"&&(r.system.APValue.value=0),r=te.reverseAdoptionCalculation(this.actor,n,r),this.mergeLevels(a,r,"maxRank")||R.abilityAdded(this.actor,r);break;case"magictrick":this.mergeLevels(a,r);break}}await this.actor.createEmbeddedDocuments("Item",a,{render:t})}async fixPreviousCosts(e,t){for(let a of t){let s=e.find(i=>i.type==a.type&&i.name==a.name);s&&(a.apCost-=s.apCost)}}async alreadyAdded(e,t){if(e=="")return!1;let a=!1;return a=await new Promise((s,i)=>{new Dialog({title:game.i18n.localize("DIALOG.warning"),content:game.i18n.format("DIALOG.alreadyAddedCharacterpart",{category:f.categoryLocalization(t)}),default:"ok",buttons:{ok:{icon:'',label:game.i18n.localize("Ok"),default:!0,callback:()=>{s(!1)}},cancel:{icon:'',label:game.i18n.localize("Cancel"),default:!0,callback:()=>{s(!0)}}}}).render(!0)}),a}async updateSkill(e,t,a=1,s=!0){let i=[];for(let r of e){let n=f.parseAbilityString(r.trim()),o=this.actor.items.find(c=>c.type==t&&c.name==n.name);o?i.push({_id:o.id,"system.talentValue.value":Math.max(0,a*n.step+(s?Number(o.system.talentValue.value):0))}):(console.warn(`Could not find ${t} ${r}`),this.errors.push(`${f.categoryLocalization(t)}: ${r}`))}await this.actor.updateEmbeddedDocuments("Item",i,{render:!1})}async getData(e){let t=await super.getData(e);return await game.dsa5.itemLibrary.buildEquipmentIndex(),t}_validateInput(e,t=this){let a=/^exclusive_/;for(let s of e.find(".tab")){let i=$(s),r=new Set;for(let n of i.find(".exclusive"))r.add(n.className.split(/\s+/).filter(o=>a.test(o))[0]);for(let n of r){let o=i.find(".allowedCount_"+n.split("_")[1]),c=Number(o.attr("data-count"));if(i.find(`.${n}:checked`).length!=c)return this._showInputValidation(o,i,t),!1}}return!0}_showInputValidation(e,t,a){ui.notifications.error(game.i18n.localize("DSAError.MissingChoices"));let s=e.closest(".tab").attr("data-tab");a.activateTab(s),re.flashElem(t.find(`.tabs a[data-tab='${s}']`)),re.flashElem(e.closest("div"))}activateListeners(e){super.activateListeners(e),oe(e),e.find("button.ok").click(()=>{this.updating||(this.updating=!0,this.updateCharacter($(this._element)).then(()=>this.updating=!1))}),e.find("button.cancel").click(()=>{this.close()});let t=u(s=>{s.stopPropagation();let i=s.currentTarget.dataset.type,r=s.currentTarget.dataset.uuid;!r||!i||s.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:i,uuid:r}))},"itemDragStart"),a=e.find(".show-item");a.click(async s=>{let i=s.currentTarget.dataset.uuid;(await fromUuid(i)).sheet.render(!0)}),a.attr("draggable",!0).on("dragstart",s=>t(s)),e.on("click",".searchableAbility a",s=>yt(s)),e.find(".exclusive").change(s=>{let i=$(s.currentTarget).closest(".tab"),r=$(s.currentTarget).attr("data-sel"),n=i.find(`.allowedCount_${r}`),o=Number(n.attr("data-count"));if(i.find(`.exclusive_${r}:checked`).length>o){s.currentTarget.checked=!1,re.flashElem(n);return}})}static flashElem(e,t="emphasize"){e.addClass(t),setTimeout(function(){e.removeClass(t)},600)}finalizeUpdate(){this.errors.length==0?this.close():$(this._element).find(".dialog-buttons").html(`

    ${game.i18n.localize("DSAError.notUnderstood")}

    • ${this.errors.join("
    • ")}
    `)}};u(re,"WizardDSA5");var Qe=class extends re{static get defaultOptions(){let e=super.defaultOptions;return e.title=game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.culture")}`}),e.template="systems/dsa5/templates/wizard/add-culture-wizard.html",e}activateListeners(e){super.activateListeners(e),e.find(".optional").change(t=>{let a=$(t.currentTarget).closest(".content"),s=Number(a.attr("data-cost"));a.find(".optional:checked").each(function(){s+=Number($(this).attr("data-cost"))});let i=a.find(".apCost");i.text(s),re.flashElem(i,"emphasize2")})}async getData(e){let t=await super.getData(e),a=await this.parseToItem(this.culture.system.recommendedAdvantages.value,["advantage"]),s=await this.parseToItem(this.culture.system.recommendedDisadvantages.value,["disadvantage"]),i=this.culture.system.writing.value==""?[]:await this.parseToItem(this.culture.system.writing.value.split(",").map(o=>`${game.i18n.localize("LocalizedIDs.literacy")} (${o.trim()})`).join(", "),["specialability"]),r=this.culture.system.language.value==""?[]:await this.parseToItem(this.culture.system.language.value.split(",").map(o=>`${game.i18n.localize("LocalizedIDs.language")} (${o.trim()}) 3`).join(", "),["specialability"]),n=Number(this.culture.system.APValue.value);return mergeObject(t,{title:game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.culture")} ${this.culture.name}`}),culture:this.culture,description:game.i18n.format("WIZARD.culturedescr",{culture:this.culture.name,cost:n}),advantages:a,disadvantages:s,writings:i,languages:r,advantagesToChose:a.length>0,disadvantagesToChose:s.length>0,writingsToChose:i.length>0,languagesToChose:r.length>0,languagesToSelect:r.length>1,vantagesToChose:a.length>0||s.length>0,generalToChose:i.length>0||r.length>0,enrichedClothing:await TextEditor.enrichHTML(getProperty(this.culture.system,"clothing.value"),{secrets:!1,async:!0}),enrichedDescription:await TextEditor.enrichHTML(getProperty(this.culture.system,"description.value"),{secrets:!1,async:!0})}),t}async addCulture(e,t){this.actor=e,this.culture=t}_validateInput(e,t=this){let a=e.find(".localKnowledge");if(a.val()=="")return this._showInputValidation(a,e,t),!1;let s=e.find(".selectOnlyOne");return s.length&&s.find(".optional:checked").length!=1?(this._showInputValidation(s,e,t),!1):super._validateInput(e,t)}async updateCharacter(e,t=this){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");let a=Number(e.find(".apCost").text());if(!this._validateInput(e,t)||!await this.actor.checkEnoughXP(a)||await this.alreadyAdded(this.actor.system.details.culture.value,"culture")){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");return}let s={"system.details.culture.value":this.culture.name},i=await this.findCompendiumItem(`${game.i18n.localize("LocalizedIDs.localKnowledge")} ()`,["specialability"]);i&&(i=duplicate(i),i.name=`${game.i18n.localize("LocalizedIDs.localKnowledge")} (${e.find(".localKnowledge").val()})`,i.system.APValue.value=0,await this.actor.createEmbeddedDocuments("Item",[i],{render:!1})),await this.addSelections(e.find(".optional:checked"),!1),await this.actor._updateAPs(a,{},{render:!1}),await this.updateSkill(this.culture.system.skills.value.split(","),"skill"),await this.actor.update(s),await _.track(this.actor,{type:"item",item:this.culture,state:1},a),this.finalizeUpdate()}};u(Qe,"CultureWizard");var Xe=class extends re{constructor(e){super(e),this.attributes=Object.keys(b.characteristics).map(t=>game.i18n.localize(`CHARAbbrev.${t.toUpperCase()}`))}static get defaultOptions(){let e=super.defaultOptions;return e.title=game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.career")}`}),e.template="systems/dsa5/templates/wizard/add-career-wizard.html",e}activateListeners(e){super.activateListeners(e),e.find(".optional").change(t=>{let a=$(t.currentTarget).closest(".content");if($(t.currentTarget).hasClass("exclusiveTricks")){let r=Number(a.find(".maxTricks").attr("data-spelltricklimit"));if(a.find(".exclusiveTricks:checked").length>r){t.currentTarget.checked=!1,re.flashElem(a.find(".maxTricks"));return}}let s=Number(a.attr("data-cost"));a.find(".optional:checked").each(function(){s+=Number($(this).attr("data-cost"))}),a.find(".attributes:checked").each(function(){s+=Number($(this).attr("data-cost"))});let i=a.find(".apCost");i.text(s),re.flashElem(i,"emphasize2")})}_validateInput(e,t=this){let a=e.find(".maxTricks"),s=Number(a.attr("data-spelltricklimit"))||0;return e.find(".exclusiveTricks:checked").length!=s?(this._showInputValidation(a,e,t),!1):super._validateInput(e,t)}async getData(e){let t=await super.getData(e),a=await this.parseToItem(this.career.system.requirements.value,["disadvantage","advantage","specialability"]),s=a.filter(h=>["advantage","disadvantage"].includes(h.type)&&!h.disabled),i=await this.parseToItem(this.career.system.recommendedAdvantages.value,["advantage"]);this.fixPreviousCosts(a,i);let r=await this.parseToItem(this.career.system.recommendedDisadvantages.value,["disadvantage"]);this.fixPreviousCosts(a,r);let n=a.filter(h=>h.attributeRequirement),o=this._parseAttributes(this.career.system.combatSkills.value,/,|;/),c=this._parseAttributes(this.career.system.specialAbilities.value),m=this._parseAttributes(this.career.system.spells.value),d=this._parseAttributes(this.career.system.liturgies.value),p=Number(this.career.system.APValue.value),g=a.reduce(function(h,w){return h+(w.disabled?0:Number(w.system.APValue.value)||0)},0),y=a.filter(h=>h.type=="specialability"&&!h.disabled);return mergeObject(t,{title:game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("career")} ${this.career.name}`}),career:this.career,description:game.i18n.format("WIZARD.careerdescr",{career:this.career.name,cost:p+g}),baseCost:p,advantages:i,disadvantages:r,missingVantages:s,specAbChoices:c,spellChoices:m,liturgyChoices:d,missingSpecialabilities:y,combatskillchoices:o,spelltricks:await this.parseToItem(this.career.system.spelltricks.value,["magictrick"]),attributeRequirements:n,advantagesToChose:i.length,disadvantagesToChose:r.length,vantagesToChose:i.length||r.length||s.length,missingVantagesToChose:s.length,missingSpecialabiltiesToChose:y.length,combatToChose:o.length,magicToChose:this.career.system.spelltrickCount.value||m.length,religionToChose:d.length,anyAttributeRequirements:n.length,generalToChose:y.length||n.length||c.length,enrichedClothing:await TextEditor.enrichHTML(getProperty(this.career.system,"clothing.value"),{secrets:!1,async:!0}),enrichedDescription:await TextEditor.enrichHTML(getProperty(this.career.system,"description.value"),{secrets:!1,async:!0})}),t}async addCareer(e,t){this.actor=e,this.career=t}async setAbility(e,t,a=[]){if(e.trim()=="")return;let s=[],i=[],r=game.i18n.localize("combatskillcountdivider")+":";for(let n of e.split(",").concat(a)){if(n.includes(r)||n=="")continue;let o=f.parseAbilityString(n.trim()),c=this.actor.items.find(m=>t.includes(m.type)&&m.name==o.original);if(c)c=duplicate(c),c.system.talentValue?c.system.talentValue.value=o.step:c.system.step&&(c.system.step.value=o.step),c=te.reverseAdoptionCalculation(this.actor,o,c),i.push(c);else if(c=await this.findCompendiumItem(o.original,t),c||(c=await this.findCompendiumItem(o.name,t)),c)c=duplicate(c),c.name=o.original,c.system.talentValue?c.system.talentValue.value=o.step:c.system.step&&(c.system.step.value=o.step),c=te.reverseAdoptionCalculation(this.actor,o,c),s.push(c);else{let m=t.map(d=>f.categoryLocalization(d)).join("/");this.errors.push(`${m}: ${n}`),ui.notifications.error(game.i18n.format("DSAError.notFound",{category:m,name:n}))}}await this.actor.updateEmbeddedDocuments("Item",i,{render:!1}),await this.actor.createEmbeddedDocuments("Item",s,{render:!1})}async addBlessing(e,t){let a=[];for(let s of e){let i=s.trim();if(i=="")continue;let r=this.actor.items.find(n=>t==n.type&&n.name==i);r||(r=await this.findCompendiumItem(i,[t]),r?(r=duplicate(r),a.push(r)):(this.errors.push(`${f.categoryLocalization(t)}: ${s}`),ui.notifications.error(game.i18n.format("DSAError.notFound",{category:game.i18n.localize(t),name:i}))))}await this.actor.createEmbeddedDocuments("Item",a,{render:!1})}getExclusiveChoices(e,t){let a=[];for(let s of e.find(`${t}.exclusive:checked`))a.push($(s).val());return a}async updateCharacter(e,t=this){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");let a=Number(e.find(".apCost").text());if(!this._validateInput(e,t)||!await this.actor.checkEnoughXP(a)||await this.alreadyAdded(this.actor.system.details.career.value,"career")){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");return}let s={"system.details.career.value":this.career.name,"system.freeLanguagePoints.value":this.career.system.languagePoints.value};for(let r of e.find(".attributes")){let n=$(r).attr("data-attribute").toLowerCase();n=game.dsa5.config.knownShortcuts[n.toLowerCase()][1],Number(this.actor.system.characteristics[n].initial)+Number(this.actor.system.characteristics[n].advances)!(r.includes(game.i18n.localize("combatskillcountdivider")+":")||r==""));await this.updateSkill(i,"combatskill",1,!1),await this.actor.update(s),await _.track(this.actor,{type:"item",item:this.career,state:1},a),this.finalizeUpdate()}};u(Xe,"CareerWizard");var Ze=class extends re{static get defaultOptions(){let e=super.defaultOptions;return e.title=game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.species")}`}),e.template="systems/dsa5/templates/wizard/add-species-wizard.html",e}activateListeners(e){super.activateListeners(e),e.find(".optional").change(t=>{let a=$(t.currentTarget).closest(".content"),s=Number(a.attr("data-cost"));a.find(".optional:checked").each(function(){s+=Number($(this).attr("data-cost"))});let i=a.find(".apCost");i.text(s),re.flashElem(i,"emphasize2")})}async _toGroups(e,t,a){return await Promise.all(e.split(` -`).map(async i=>{let r=i.split(":"),n;return r.length>1?n={name:r[0].trim(),res:await this.parseToItem(r[1].trim(),t)}:n={name:"",res:await this.parseToItem(i,t)},this.fixPreviousCosts(a,n.res),n}))}async getData(e){let t=await super.getData(e),a=await this.parseToItem(this.species.system.requirements.value,["disadvantage","advantage"]),s=a.filter(m=>["advantage","disadvantage"].includes(m.type)&&!m.disabled),i=await this._toGroups(this.species.system.recommendedAdvantages.value,["advantage"],a),r=await this._toGroups(this.species.system.recommendedDisadvantages.value,["disadvantage"],a),n=this._parseAttributes(this.species.system.attributeChange.value),o=Number(this.species.system.APValue.value),c=a.reduce(function(m,d){return m+(d.disabled?0:Number(d.system.APValue.value)||0)},0);return mergeObject(t,{title:game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.species")} ${this.species.name}`}),species:this.species,description:game.i18n.format("WIZARD.speciesdescr",{species:this.species.name,cost:o+c}),advantagegroups:i,baseCost:o,disadvantagegroups:r,missingVantages:s,attributeRequirements:n,hasLocalization:game.i18n.has(`Racedescr.${this.species.name}`),anyAttributeRequirements:n.length>0,advantagesToChose:i.length>0,missingVantagesToChose:s.length>0,disadvantagesToChose:r.length>0,vantagesToChose:i.length>0||r.length>0||s.length>0,generalToChose:n.length>0}),t}async addSpecies(e,t){this.actor=e,this.species=t}async updateCharacter(e,t=this){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");let a=Number(e.find(".apCost").text());if(!this._validateInput(e,t)||!await this.actor.checkEnoughXP(a)||await this.alreadyAdded(this.actor.system.details.species.value,"species")){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");return}let s={"system.details.species.value":this.species.name,"system.status.speed.initial":this.species.system.baseValues.speed.value,"system.status.soulpower.initial":this.species.system.baseValues.soulpower.value,"system.status.toughness.initial":this.species.system.baseValues.toughness.value,"system.status.wounds.initial":this.species.system.baseValues.wounds.value,"system.status.wounds.value":this.species.system.baseValues.wounds.value+this.actor.system.characteristics.ko.value*2},i=[];for(let r of e.find(".exclusive:checked"))i.push($(r).val());Object.keys(b.characteristics).forEach(r=>{s[`system.characteristics.${r}.species`]=0});for(let r of this.species.system.attributeChange.value.split(",").concat(i)){if(r.includes(game.i18n.localize("combatskillcountdivider")+":")||r=="")continue;let n=r.trim().split(" "),o=game.dsa5.config.knownShortcuts[n[0].toLowerCase().trim()].slice(0);o[o.length-1]="species",s[`system.${o.join(".")}`]=Number(n[1])}await this.actor._updateAPs(a,{},{render:!1}),await this.addSelections(e.find(".optional:checked"),!1),await this.actor.update(s),await this.actor.removeCondition("incapacitated"),await _.track(this.actor,{type:"item",item:this.species,state:1},a),this.finalizeUpdate()}};u(Ze,"SpeciesWizard");var be=class extends $e{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","actor","character-sheet"]),width:784}),e}get template(){return this.showLimited()?"systems/dsa5/templates/actors/npc-limited.html":"systems/dsa5/templates/actors/actor-sheet.html"}async _manageDragItems(e,t){switch(t){case"aggregatedTest":await this.actor.createEmbeddedDocuments("Item",[e]);break;case"species":let a=new Ze;await a.addSpecies(this.actor,e),a.render(!0);break;case"culture":let s=new Qe;await s.addCulture(this.actor,e),s.render(!0);break;case"career":let i=new Xe;await i.addCareer(this.actor,e),i.render(!0);break;default:return super._manageDragItems(e,t)}}};u(be,"ActorSheetdsa5Character");var Oe=class extends $e{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","actor","creature-sheet"])}),e}get template(){return this.showLimited()?"systems/dsa5/templates/actors/creature-limited.html":"systems/dsa5/templates/actors/creature-sheet.html"}async getData(e){let t=await super.getData(e);return t.enrichedDescription=await TextEditor.enrichHTML(getProperty(this.actor.system,"description.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedBehaviour=await TextEditor.enrichHTML(getProperty(this.actor.system,"behaviour.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedFlight=await TextEditor.enrichHTML(getProperty(this.actor.system,"flight.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedSpecialrules=await TextEditor.enrichHTML(getProperty(this.actor.system,"specialRules.value"),{secrets:this.object.isOwner,async:!0}),t}async _cleverDeleteItem(e){let t=this.actor.items.find(a=>a.id==e);switch(t.type){case"trait":let a=t.system.APValue.value*-1;await this._updateAPs(a,{},{render:!1}),await _.track(actor,{type:"item",item:t,state:-1},a);break}await super._cleverDeleteItem(e)}async _addTrait(e){if(!this.actor.items.find(a=>a.type=="trait"&&a.name==e.name)){await this._updateAPs(e.system.APValue.value,{},{render:!1}),await ue.traitAdded(this.actor,e);let a=(await this.actor.createEmbeddedDocuments("Item",[e]))[0];await _.track(actor,{type:"item",item:a,state:1},e.system.APValue.value)}}async _onDropItemCreate(e){return e.type=="trait"?this._addTrait(e):super._onDropItemCreate(e)}};u(Oe,"ActorSheetdsa5Creature");var xe=class extends be{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","actor","npc-sheet"])}),e}get template(){return this.showLimited()?"systems/dsa5/templates/actors/npc-limited.html":"systems/dsa5/templates/actors/npc-sheet.html"}};u(xe,"ActorSheetdsa5NPC");var et=u(l=>class extends l{async obfuscateItem(e){e.stopPropagation(),e.preventDefault();let t=e.currentTarget.dataset.obfuscate;await this.item.update({[`system.obfuscation.${t}`]:!this.isObfuscated(t)})}isObfuscated(e){return getProperty(this.item,`system.obfuscation.${e}`)}activateListeners(e){super.activateListeners(e),e.on("click",".obfuscateSection",t=>this.obfuscateItem(t))}obfuscationCss(e){return this.isObfuscated(e)?"":" pale"}async _render(e=!1,t={}){await super._render(e,t);let a=["details","effects","description","enchantment"],s=!1;for(let i of a){let r=$(this._element).find(`nav [data-tab="${i}"]`);if(!r.length)continue;let n=t.tabsinvisible||this.isObfuscated(i),o=game.i18n.localize(`SHEET.${n?"deobfuscateItem":"obfuscateItem"}`);if(game.user.isGM){let c=`obfuscateSection${this.obfuscationCss(i)}`,m=r.find(`.${c}`),d=``;m.length?m.replaceWith(d):r.append(` ${d}`)}else n&&(r.hasClass("active")&&(s=!0),r.remove(),i=="details"&&$(this._element).find('[name="system.price.value"],[name="system.price.raw"]').replaceWith(""))}if(s){let i=$(this._element).find("nav .item:first-child");if(i.length)this.activateTab(i.attr("data-tab"));else{let r=await renderTemplate("systems/dsa5/templates/items/obfuscatedItem.html",{item:this.item});$(this._element).find(".content").html(r)}}}},"ItemSheetObfuscation");var Y=class extends ItemSheet{_getSubmitData(e={}){let t=super._getSubmitData(e),a=foundry.utils.flattenObject(this.item.overrides||{});return Object.keys(a).forEach(s=>delete t[s]),t}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{tabs:[{navSelector:".tabs",contentSelector:".content"}],classes:e.classes.concat(["dsa5","item"]),width:471,height:500}),e}static setupSheets(){Items.unregisterSheet("core",ItemSheet),Items.registerSheet("dsa5",Y,{makeDefault:!0}),Items.registerSheet("dsa5",xs,{makeDefault:!0,types:["species"]}),Items.registerSheet("dsa5",Cs,{makeDefault:!0,types:["career"]}),Items.registerSheet("dsa5",Ds,{makeDefault:!0,types:["culture"]}),Items.registerSheet("dsa5",Ns,{makeDefault:!0,types:["advantage","disadvantage"]}),Items.registerSheet("dsa5",zs,{makeDefault:!0,types:["ritual","ceremony","liturgy","spell"]}),Items.registerSheet("dsa5",Os,{makeDefault:!0,types:["specialability"]}),Items.registerSheet("dsa5",Es,{makeDefault:!0,types:["meleeweapon"]}),Items.registerSheet("dsa5",$s,{makeDefault:!0,types:["poison"]}),Items.registerSheet("dsa5",Ms,{makeDefault:!0,types:["disease"]}),Items.registerSheet("dsa5",As,{makeDefault:!0,types:["consumable"]}),Items.registerSheet("dsa5",Ps,{makeDefault:!0,types:["spellextension"]}),Items.registerSheet("dsa5",Is,{makeDefault:!0,types:["magictrick"]}),Items.registerSheet("dsa5",Ss,{makeDefault:!0,types:["blessing"]}),Items.registerSheet("dsa5",Ts,{makeDefault:!0,types:["rangeweapon"]}),Items.registerSheet("dsa5",ys,{makeDefault:!0,types:["equipment"]}),Items.registerSheet("dsa5",bs,{makeDefault:!0,types:["armor"]}),Items.registerSheet("dsa5",hs,{makeDefault:!0,types:["ammunition"]}),Items.registerSheet("dsa5",ks,{makeDefault:!0,types:["plant"]}),Items.registerSheet("dsa5",vs,{makeDefault:!0,types:["magicalsign"]}),Items.registerSheet("dsa5",ws,{makeDefault:!0,types:["patron"]}),Items.registerSheet("dsa5",fs,{makeDefault:!0,types:["information"]}),Items.registerSheet("dsa5",gs,{makeDefault:!0,types:["aggregatedTest"]}),Items.unregisterSheet("dsa5",Y,{types:["armor","equipment","rangeweapon","blessing","magictrick","spellextension","consumable","aggregatedTest","species","career","culture","advantage","specialability","disadvantage","ritual","information","ceremony","liturgy","spell","disease","poison","meleeweapon","ammunition","plant","magicalsign","patron"]})}async _render(e=!1,t={}){await super._render(e,t),$(this._element).find(".close").attr("data-tooltip","SHEET.Close"),$(this._element).find(".configure-sheet").attr("data-tooltip","SHEET.Configure"),$(this._element).find(".import").attr("data-tooltip","SHEET.Import"),$(this._element).find(".rolleffect").attr("data-tooltip","SHEET.RollEffect"),$(this._element).find(".showItemHead").attr("data-tooltip","SHEET.PostItem"),$(this._element).find(".consumeItem").attr("data-tooltip","SHEET.ConsumeItem"),$(this._element).find(".rollDamaged").attr("data-tooltip","DSASETTINGS.armorAndWeaponDamage"),$(this._element).find(".onUseEffect").attr("data-tooltip","SHEET.onUseEffect"),$(this._element).find(".postAsGroupCheck").attr("data-tooltip","SHEET.postAsGroupCheck")}_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"showItemHead",icon:"fas fa-comment",onclick:async()=>this.item.postItem()}),this.item.actor&&X.getOnUseEffect(this.item)&&e.unshift({class:"onUseEffect",icon:"fas fa-dice-six",onclick:async()=>{new X(this.item).executeOnUseEffect()}}),e}setupEffect(e){this.item.setupEffect().then(t=>this.item.itemTest(t))}get template(){return`systems/dsa5/templates/items/item-${this.item.type}-sheet.html`}_getItemId(e){return $(e.currentTarget).parents(".item").attr("data-item-id")}_advanceStep(){}_refundStep(){}async advanceWrapper(e,t){let s=$(e.currentTarget).find("i");s.hasClass("fa-spin")||(s.addClass("fa-spin fa-spinner"),await this[t](),s.removeClass("fa-spin fa-spinner"))}activateListeners(e){super.activateListeners(e),oe(e),e.find(".advance-step").mousedown(a=>this.advanceWrapper(a,"_advanceStep")),e.find(".refund-step").mousedown(a=>this.advanceWrapper(a,"_refundStep")),e.find(".domainsPretty").click(a=>{$(a.currentTarget).hide(),$(a.currentTarget).next(".domainToggle").show()}),e.find('[data-edit="img"]').mousedown(a=>{a.button==2&&f.showArtwork(this.item)}),e.find(".status-add").click(()=>{E.createCustomEffect(this.item,"",this.item.name)}),e.find(".condition-show").mousedown(a=>{a.preventDefault();let s=a.currentTarget.dataset.id;a.button==0?this.item.effects.get(s).sheet.render(!0):a.button==2&&this.item.deleteEmbeddedDocuments("ActiveEffect",[s])}),e.find(".select2").select2(),e.find(".condition-toggle").mousedown(a=>{let s=$(a.currentTarget).parents(".statusEffect").attr("data-id"),i=this.item.effects.get(s);i.update({disabled:!i.disabled})}),e.find(".condition-edit").click(a=>{this.item.effects.get(a.currentTarget.dataset.id).sheet.render(!0)}),se.bindRollCommands(e),E.bindButtons(e);let t=e.find(".item-header");if(t.length){let a=t.find("svg");if(a){new ResizeObserver(function(r){let n=r[0];Si(a,n.contentRect.width)}).observe(t.get(0));let i=t.find("input");i.get(0).disabled||(a.click(()=>{a.hide(),i.show(),i.focus()}),i.blur(function(){a.show(),i.hide()}))}}}async getData(e){let t=super.getData(e).data;switch(this.item.type){case"skill":t.characteristics=b.characteristics,t.skillGroups=b.skillGroups,t.skillBurdens=b.skillBurdens,t.hasLocalization=game.i18n.has(`SKILLdescr.${this.item.name}`),t.StFs=b.StFs;break;case"application":t.hasLocalization=game.i18n.has(`APPLICATION.${this.item.system.skill} - ${this.item.name}`),t.localization=game.i18n.localize(`APPLICATION.${this.item.system.skill} - ${this.item.name}`),t.allSkills=await f.allSkillsList();break;case"combatskill":t.weapontypes=b.weapontypes,t.guidevalues=b.combatskillsGuidevalues,t.hasLocalization=game.i18n.has(`Combatskilldescr.${this.item.name}`),t.StFs=b.StFs;break;case"trait":t.traitCategories=b.traitCategories,t.ranges=b.meleeRanges;break}if(t.isOwned=this.item.actor,t.editable=this.isEditable,t.isOwned){t.canAdvance=this.item.actor.canAdvance&&this._advancable();let a=getProperty(this.item,"flags.dsa5.customPriceTag");!this.isEditable&&a&&(t.customPrice=a)}return E.prepareActiveEffects(this.item,t),t.item=this.item,t.armorAndWeaponDamage=game.settings.get("dsa5","armorAndWeaponDamage"),t.isGM=game.user.isGM,t.enrichedDescription=await TextEditor.enrichHTML(getProperty(this.item.system,"description.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedGmdescription=await TextEditor.enrichHTML(getProperty(this.item.system,"gmdescription.value"),{secrets:this.object.isOwner,async:!0}),t}_advancable(){return!1}};u(Y,"ItemSheetdsa5");var gs=class extends Y{async getData(e){let t=await super.getData(e),a=this.item.getFlag("dsa5","embeddedItem"),s;return a&&(s=await renderTemplate(`systems/dsa5/templates/items/browse/${a.type}.html`,{document:a})),mergeObject(t,{allSkills:await f.allSkillsList(),embeddedItem:a,renderedItem:s,enrichedsuccess:await TextEditor.enrichHTML(this.item.system.success,{secrets:this.item.isOwner,async:!0}),enrichedpartsuccess:await TextEditor.enrichHTML(this.item.system.partsuccess,{secrets:this.item.isOwner,async:!0})}),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned||e.unshift({class:"postAsGroupCheck",icon:"fas fa-dice-d20",onclick:async()=>this.postAsGroupCheck()}),e}async postAsGroupCheck(){let e=["value","value2","value3"].filter(a=>this.item.system.talent[a]).map(a=>({type:"skill",modifier:this.item.system.baseModifier,calculatedModifier:this.item.system.baseModifier,target:this.item.system.talent[a]}));if(!e.length)return;let t={modifier:this.item.system.baseModifier,maxRolls:this.item.system.allowedTestCount.value,enrichedsuccess:await TextEditor.enrichHTML(this.item.system.success,{secrets:this.item.isOwner,async:!0}),enrichedpartsuccess:await TextEditor.enrichHTML(this.item.system.partsuccess,{secrets:this.item.isOwner,async:!0}),rollOptions:e};q.showGCMessage(e[0].target,0,t)}activateListeners(e){super.activateListeners(e),e.find(".buildItem").click(async()=>this.postFinishedItem())}async postFinishedItem(){if(!this.item.actor)return;let e=this.item.getFlag("dsa5","embeddedItem");if(!e)return;let t=await renderTemplate("systems/dsa5/templates/chat/production-result.html",{actor:this.item.actor,item:e,actorImg:j.videoOrImgTag(this.item.actor.img)}),a=f.chatDataSetup(t);a.flags={dsa5:{embeddedItem:e}},await ChatMessage.create(a)}};u(gs,"AggregatedTestSheet");var tt=class extends Y{async _onDrop(e){await this.enchant(e),this.isPoisonable&&await this.poison(e)}async enchant(e){let t=JSON.parse(e.dataTransfer.getData("text/plain"));await this._enchant([t])}async _enchant(e){let t=this.item.getFlag("dsa5","enchantments")||[];if(t.length+e.length>7)return ui.notifications.error(game.i18n.localize("DSAError.tooManyEnchants"));for(let a of e){let{item:s,typeClass:i,selfTarget:r}=await Ge(a,void 0,!1);if(["spell","liturgy","ceremony","ritual"].includes(i)){if(!s.pack)return ui.notifications.error(game.i18n.localize("DSAError.onlyCompendiumSpells"));let n={name:s.name,pack:s.pack,id:t.length,itemId:s.id,permanent:["liturgy","ceremony"].includes(i)||a.permanent,actorId:a.actorId,charged:!0,talisman:["liturgy","ceremony"].includes(i),fw:["liturgy","ceremony"].includes(i)?18:a.fw||0};t.push(n)}}if(t.length){let a={flags:{dsa5:{enchantments:t}}};await this.item.update(a)}}async poison(e){let t=JSON.parse(e.dataTransfer.getData("text/plain")),{item:a,typeClass:s,selfTarget:i}=await Ge(t,void 0,!1);if(s=="poison"){let n={flags:{dsa5:{poison:{name:a.name,pack:a.pack,itemId:a._id,permanent:!1,actorId:t.actorId}}}};await this.item.update(n)}}toggleChargedState(e,t){for(let a of t)if(a.id==e){a.charged=a.talisman&&a.permanent?!0:!a.charged;break}this.item.update({flags:{dsa5:{enchantments:t}}})}activateListeners(e){super.activateListeners(e),e.find(".ench-toggle-permanent").click(t=>{let{id:a,enchantments:s}=this.enchantMentId(t);for(let i of s)if(i.id==a){i.permanent=!i.permanent;break}this.item.update({flags:{dsa5:{enchantments:s}}})}),e.find(".ench-toggle-charge").click(t=>{let{id:a,enchantments:s}=this.enchantMentId(t);this.toggleChargedState(a,s)}),e.find(".ench-roll").click(async t=>{let{id:a,enchantments:s}=this.enchantMentId(t),i=s.find(n=>n.id==a);if(!i.charged)return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughCharges"));let r=await this.getSpell(i);if(r){r=r.toObject(),r.system.talentValue.value=i.fw;let n=await f.emptyActor(14,this.item.name);n.setupSpell(r,{},"emptyActor").then(async o=>{let c=game.i18n.format("CHATNOTIFICATION.enchantmentUsed",{item:this.item.name,spell:r.name});await ChatMessage.create(f.chatDataSetup(c)),await n.basicTest(o),i.permanent?this.toggleChargedState(a,s):this.deleteEnchantment(a,s)})}}),e.find(".ench-fw").change(t=>{let{id:a,enchantments:s}=this.enchantMentId(t),i=Number($(t.currentTarget).val());if(!!i){for(let r of s)if(r.id==a){r.fw=i;break}this.item.update({flags:{dsa5:{enchantments:s}}})}}),e.find(".ench-delete").click(t=>{let{id:a,enchantments:s}=this.enchantMentId(t);this.deleteEnchantment(a,s)}),e.find(".ench-show").click(async t=>{let{id:a,enchantments:s}=this.enchantMentId(t),i=s.find(n=>n.id==a),r=await this.getSpell(i);r&&r.sheet.render(!0)}),e.find(".poison-toggle-permanent").click(t=>{this.item.update({flags:{dsa5:{poison:{permanent:!this.item.flags.dsa5.poison.permanent}}}})}),e.find(".poison-delete").click(t=>{this.deletePoison()}),e.find(".poison-show").click(async()=>{let t;this.item.actor&&(t=this.item.actor.items.find(a=>a.type=="poison"&&a.name==this.item.flags.dsa5.poison.name)),t||(t=await this.getSpell(this.item.flags.dsa5.poison)),t&&t.sheet.render(!0)})}deletePoison(){this.item.update({["flags.dsa5.-=poison"]:null})}deleteEnchantment(e,t){let a=t.findIndex(s=>s.id==e);t.splice(a,1),this.item.update({flags:{dsa5:{enchantments:t}}})}async getSpell(e){let t=await game.packs.get(e.pack);if(!t){ui.notifications.error(game.i18n.localize("DSAError.enchantmentNotFound"));return}let a=await t.getDocument(e.itemId);if(!a){let s=await t.index.getName(e.name);s&&(a=await t.getDocument(s._id))}return a||ui.notifications.error(game.i18n.localize("DSAError.enchantmentNotFound")),a}enchantMentId(e){return{id:$(e.currentTarget).parents(".statusEffect").attr("data-id"),enchantments:this.item.getFlag("dsa5","enchantments")}}prepareDomains(){let e=getProperty(this.item.system,"effect.attributes");if(e){let t=new RegExp(game.i18n.localize("WEAPON.magical"),"i"),a=new RegExp(game.i18n.localize("WEAPON.clerical"),"i");e=e.split(",").map(s=>{let i="";return t.test(s)?i="magical":a.test(s)&&(i="blessed"),`
  • ${s}
  • `}).join("")}return e}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{dragDrop:[{dragSelector:".item-list .item",dropSelector:".content"}]}),e}_canDragDrop(e){return this.isEditable}async getData(e){let t=await super.getData(e);t.enchantments=this.item.getFlag("dsa5","enchantments");let a=[];return t.poison=this.item.getFlag("dsa5","poison"),t.poison&&a.push("poison"),t.enchantments&&t.enchantments.some(s=>!s.talisman)&&a.push("enchantment"),t.enchantments&&t.enchantments.some(s=>s.talisman)&&a.push("talisman"),t.enchantmentLabel=a.map(s=>game.i18n.localize(s)).join("/"),t.traditionArtifacts=b.traditionArtifacts,t.hasEnchantments=t.poison||t.enchantments&&t.enchantments.length>0,t}};u(tt,"Enchantable");var fs=class extends Y{async getData(e){let t=await super.getData(e);return mergeObject(t,{allSkills:await f.allSkillsList(),enrichedqs1:await TextEditor.enrichHTML(this.item.system.qs1,{async:!0}),enrichedqs2:await TextEditor.enrichHTML(this.item.system.qs2,{async:!0}),enrichedqs3:await TextEditor.enrichHTML(this.item.system.qs3,{async:!0}),enrichedqs4:await TextEditor.enrichHTML(this.item.system.qs4,{async:!0}),enrichedqs5:await TextEditor.enrichHTML(this.item.system.qs5,{async:!0}),enrichedqs6:await TextEditor.enrichHTML(this.item.system.qs6,{async:!0}),enrichedCrit:await TextEditor.enrichHTML(this.item.system.crit,{async:!0}),enrichedBotch:await TextEditor.enrichHTML(this.item.system.botch,{async:!0}),enrichedFail:await TextEditor.enrichHTML(this.item.system.fail,{async:!0})}),t}};u(fs,"InformationSheet");var hs=class extends tt{constructor(e,t){super(e,t),this.isPoisonable=!0}async getData(e){let t=await super.getData(e);return t.ammunitiongroups=b.ammunitiongroups,t.domains=this.prepareDomains(),t}};u(hs,"AmmunitionSheet");var ys=class extends et(tt){async getData(e){let t=await super.getData(e);if(mergeObject(t,{equipmentTypes:b.equipmentTypes,domains:this.prepareDomains(),canOnUseEffect:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro")}),this.isBagWithContents()){let a=0;mergeObject(t,{containerContent:this.item.actor.items.filter(s=>b.equipmentCategories.has(s.type)&&s.system.parent_id==this.item.id).map(s=>{s.system.preparedWeight=parseFloat((s.system.weight.value*s.system.quantity.value).toFixed(3)),a+=Number(s.system.preparedWeight);let i=getProperty(s,"flags.dsa5.enchantments");return i&&i.length>0?s.enchantClass="rar":(s.system.effect&&s.system.effect.value!=""||s.effects.length>0)&&(s.enchantClass="common"),s}),weightSum:parseFloat(a.toFixed(3)),weightWidth:`style="width: ${Math.min(this.item.system.capacity?a/this.item.system.capacity*100:0,100)}%"`,weightExceeded:a>Number(this.item.system.capacity)?"exceeded":""})}return t}async breakOverflow(e,t){let a=$(await renderTemplate("systems/dsa5/templates/items/baghover.html",e)),s=t.offset().top+52,i=t.offset().left-75;return a.appendTo($("body")),a.css({position:"absolute",left:i+"px",top:s+"px",bottom:"auto",right:"auto","z-index":1e4}),a}activateListeners(e){super.activateListeners(e);let t=e.find(".slot");t.mouseenter(async a=>{let s=$(a.currentTarget),i=await this.breakOverflow({name:s.attr("data-name"),weight:s.attr("data-weight"),quantity:s.attr("data-quantity")},s);i.fadeIn(),s.mouseleave(()=>{i.remove(),s.off("mouseleave")})}),t.mousedown(async a=>{let s=a.currentTarget.dataset.itemId,i=this.actor.items.get(s);a.button==0?i.sheet.render(!0):a.button==2&&($(".itemInfo").remove(),await i.update({"system.parent_id":0}),this.render(!0))})}isBagWithContents(){return this.item.actor&&getProperty(this.item,"system.equipmentType.value")=="bags"}async _onDrop(e){if(this.isBagWithContents()){let t=JSON.parse(e.dataTransfer.getData("text/plain")),{item:a,typeClass:s,selfTarget:i}=await Ge(t,void 0),r=this.item.id==a.id,n=this.item.parent.id==t.actorId;if(b.equipmentCategories.has(s)&&!r){a.system.parent_id=this.item.id,a.system.worn&&a.system.worn.value&&(a.system.worn.value=!1),n?await this.item.actor.updateEmbeddedDocuments("Item",[a]):await this.item.actor.sheet._addLoot(a),this.render(!0);return}}await super._onDrop(e)}};u(ys,"EquipmentSheet");var bs=class extends et(tt){async getData(e){let t=await super.getData(e);return mergeObject(t,{domains:this.prepareDomains(),armorSubcategories:Object.keys(b.armorSubcategories),breakPointRating:b.armorSubcategories[this.item.system.subcategory]}),t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&game.settings.get("dsa5","armorAndWeaponDamage")&&this.item.system.structure.max>0&&e.unshift({class:"rollDamaged",icon:"fas fa-dice-d20",onclick:async()=>W.breakingTest(this.item)}),e}};u(bs,"ArmorSheet");var ks=class extends et(Y){async getData(e){let t=await super.getData(e);return t.attributes=Object.keys(t.system.planttype).map(a=>({name:a,checked:t.system.planttype[a]})),t.enrichedEffect=await TextEditor.enrichHTML(getProperty(this.item.system,"effect"),{secrets:this.object.isOwner,async:!0}),t.enrichedRecipes=await TextEditor.enrichHTML(getProperty(this.item.system,"recipes"),{secrets:this.object.isOwner,async:!0}),t.enrichedInformation=await TextEditor.enrichHTML(getProperty(this.item.system,"infos"),{secrets:this.object.isOwner,async:!0}),t}};u(ks,"PlantSheet");var ws=class extends Y{async getData(e){let t=await super.getData(e);return t.patronCategories=[0,1,2,3].map(a=>({name:game.i18n.localize(`PATRON.${a}`),val:a})),t.priorities={0:game.i18n.localize("PATRON.primary"),1:game.i18n.localize("PATRON.secondary")},t}};u(ws,"PatronSheet");var vs=class extends Y{async getData(e){let t=await super.getData(e);return t.categories={1:game.i18n.localize("TYPES.Item.magicalsign"),2:game.i18n.localize("additionalsign")},t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async setupEffect(e){let t=Number(this.item.system.asp)||0;if(this.item.actor.system.status.astralenergy.valuen.type=="skill"&&n.name==game.i18n.localize("LocalizedIDs.artisticAbility")),r=`

    ${this.item.name}

    ${this.item.system.description.value}

    ${s.chatData(this.item.system,"").join("
    ")}

    `;a.setupSkill(i,{other:[r],subtitle:` (${game.i18n.localize("TYPES.Item.magicalsign")})`},void 0).then(async n=>{let o=await a.basicTest(n,{suppressMessage:!0});o.result.preData.calculatedSpellModifiers={finalcost:t,costsMana:!0},await _DiceDSA5.renderRollCard(o.cardOptions,o.result,o.options.rerenderMessage)})}};u(vs,"MagicalSignSheet");var Ts=class extends et(tt){_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&game.settings.get("dsa5","armorAndWeaponDamage")&&this.item.system.structure.max>0&&e.unshift({class:"rollDamaged",icon:"fas fa-dice-d20",onclick:async()=>W.breakingTest(this.item)}),e}async getData(e){let t=await super.getData(e);return mergeObject(t,{canOnUseEffect:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),ammunitiongroups:b.ammunitiongroups,combatskills:await f.allCombatSkillsList("range"),domains:this.prepareDomains(),breakPointRating:b.weaponStabilities[game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`)]}),t}};u(Ts,"RangeweaponSheet");var Ss=class extends Y{_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}async setupEffect(e){if(this.item.actor.system.status.karmaenergy.value<1)return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughKaP"));let t=game.dsa5.config.ItemSubclasses.magictrick;await this.item.actor.update({"system.status.karmaenergy.value":this.item.actor.system.status.karmaenergy.value-=1});let a=`

    ${this.item.name} - ${game.i18n.localize("blessing")} ${game.i18n.localize("probe")}

    ${this.item.system.description.value}

    ${t.chatData(this.item.system,"").join("
    ")}

    `;await ChatMessage.create(f.chatDataSetup(a))}};u(Ss,"BlessingSheetDSA5");var Cs=class extends Y{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,height:700}),e}async getData(e){let t=await super.getData(e),a=duplicate(b.characteristics);return a["-"]="-",t.mageLevels=b.mageLevels,t.guidevalues=a,t.enrichedClothing=await TextEditor.enrichHTML(getProperty(this.item.system,"clothing.value"),{secrets:this.object.isOwner,async:!0}),t}};u(Cs,"ItemCareerDSA5");var As=class extends et(Y){static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:480}),e}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"consumeItem",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.calculatedPrice=A.getSubClass(this.item.type).consumablePrice(this.item),t.availableSteps=t.system.QLList.split(` -`).map((a,s)=>s+1),t.equipmentTypes=b.equipmentTypes,t.enrichedIngredients=await TextEditor.enrichHTML(getProperty(this.item.system,"ingredients"),{secrets:this.object.isOwner,async:!0}),t}setupEffect(e){this.item.setupEffect()}};u(As,"ConsumableSheetDSA5");var Ds=class extends Y{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,height:700}),e}async getData(e){let t=await super.getData(e);return t.enrichedClothing=await TextEditor.enrichHTML(getProperty(this.item.system,"clothing.value"),{secrets:this.object.isOwner,async:!0}),t}};u(Ds,"ItemCultureDSA5");var Ms=class extends Y{_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.resistances=b.magicResistanceModifiers,t}};u(Ms,"DiseaseSheetDSA5");var Is=class extends Y{_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}async setupEffect(e){if(this.item.actor.system.status.astralenergy.value<1)return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughAsP"));let t=game.dsa5.config.ItemSubclasses.magictrick;await this.item.actor.update({"system.status.astralenergy.value":this.item.actor.system.status.astralenergy.value-=1});let a=`

    ${this.item.name} - ${game.i18n.localize("magictrick")} ${game.i18n.localize("probe")}

    ${this.item.system.description.value}

    ${t.chatData(this.item.system,"").join("
    ")}

    `;await ChatMessage.create(f.chatDataSetup(a))}};u(Is,"MagictrickSheetDSA5");var Es=class extends et(tt){constructor(e,t){super(e,t),this.isPoisonable=!0}async getData(e){let t=await super.getData(e),a=mergeObject(duplicate(b.characteristics),{"ge/kk":game.i18n.localize("CHAR.GEKK"),["-"]:"-"}),s=P.regex2h.test(this.item.name),i="";if(!s)i="wrongGrip.yieldTwo";else switch(game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`)){case"Two-Handed Impact Weapons":case"Two-Handed Swords":new RegExp(game.i18n.localize("wrongGrip.wrongGripBastardRegex")).test(this.item.name)?i="wrongGrip.yieldOneBastard":i="wrongGrip.yieldOneSwordBlunt";break;default:i="wrongGrip.yieldOnePolearms"}if(mergeObject(t,{characteristics:a,twoHanded:s,wrongGripLabel:s?"wrongGrip.oneHanded":"wrongGrip.twoHanded",wrongGripHint:i,combatskills:await f.allCombatSkillsList("melee"),ranges:b.meleeRanges,shieldSizes:b.shieldSizes,isShield:P.isShield(this.item),domains:this.prepareDomains(),breakPointRating:b.weaponStabilities[game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`)]}),this.item.actor){let r=this.item.actor.items.find(n=>n.type=="combatskill"&&n.name==this.item.system.combatskill.value);t.canBeOffHand=r&&!r.system.weapontype.twoHanded&&this.item.system.worn.value,t.canBeWrongGrip=!["Daggers","Fencing Weapons"].includes(game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`))}return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&game.settings.get("dsa5","armorAndWeaponDamage")&&this.item.system.structure.max>0&&e.unshift({class:"rollDamaged",icon:"fas fa-dice-d20",onclick:async()=>W.breakingTest(this.item)}),e}};u(Es,"MeleeweaponSheetDSA5");var $s=class extends et(Y){_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.resistances=b.magicResistanceModifiers,t}};u($s,"PoisonSheetDSA5");var Os=class extends Y{async _refundStep(){let e=this.item.system.step.value;if(e>1){let t=await R.stepXPCost(this.item,e-1);t=await R.refundFreelanguage(this.item,this.item.actor,t,!1),await this.item.actor._updateAPs(t*-1,{},{render:!1}),await this.item.update({"system.step.value":e-1}),await _.track(this.item.actor,{type:"item",item:this.item,previous:e,next:e-1},t)}}async _advanceStep(){let e=this.item.system.step.value;if(e0}async getData(e){let t=await super.getData(e);return mergeObject(t,{categories:b.specialAbilityCategories,subCategories:b.combatSkillSubCategories,traditionArtifacts:b.traditionArtifacts,canOnUseEffect:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro")}),t}};u(Os,"SpecialAbilitySheetDSA5");var xs=class extends Y{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:530,height:570}),e}async getData(e){let t=await super.getData(e);return mergeObject(t,{hasLocalization:game.i18n.has(`Racedescr.${this.item.name}`)}),t}};u(xs,"ItemSpeciesDSA5");var zs=class extends Y{async getData(e){let t=await super.getData(e);return t.characteristics=b.characteristics,t.StFs=b.StFs,t.resistances=b.magicResistanceModifiers,t.targetTypes=b.areaTargetTypes,t.isOwned&&(t.extensions=this.item.actor.items.filter(a=>a.type=="spellextension"&&a.system.source==this.item.name&&this.item.type==a.system.category)),t}activateListeners(e){super.activateListeners(e),e.find(".item-edit").click(t=>{t.preventDefault();let a=this._getItemId(t);this.item.actor.items.get(a).sheet.render(!0)}),e.find(".item-delete").click(t=>{this._deleteItem(t)})}_deleteItem(e){let t=this._getItemId(e),a=this.actor.items.find(i=>i.id==t),s=game.i18n.format("DIALOG.DeleteItemDetail",{item:a.name});renderTemplate("systems/dsa5/templates/dialog/delete-item-dialog.html",{message:s}).then(i=>{new Dialog({title:game.i18n.localize("DIALOG.deleteConfirmation"),content:i,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{this._cleverDeleteItem(t),$(e.currentTarget).closest(".item").remove()}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)})}async _cleverDeleteItem(e){let t=this.item.actor.items.find(a=>a.id==e);await this.item.actor._updateAPs(-1*t.system.APValue.value,{},{render:!1}),await this.item.actor.deleteEmbeddedDocuments("Item",[e]),await _.track(this.actor,{type:"item",item:t,state:-1},apCost)}};u(zs,"SpellSheetDSA5");var Ps=class extends Y{async getData(e){let t=await super.getData(e);return mergeObject(t,{categories:{spell:"spell",liturgy:"liturgy",ritual:"ritual",ceremony:"ceremony"}}),t}};u(Ps,"SpellExtensionSheetDSA5");var Ns=class extends Y{_advancable(){return this.item.system.max.value>0}async getData(e){let t=await super.getData(e);return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}async _refundStep(){let e=this.item.system.step.value;if(e>1){let t=await O.stepXPCost(this.item,e-1);t=await O.reduceSingularVantages(this.item.actor,this.item,t),await this.item.actor._updateAPs(t*-1,{},{render:!1}),await this.item.update({"system.step.value":e-1}),await _.track(this.item.actor,{type:"item",item:this.item,previous:e,next:e-1},t)}}async _advanceStep(){let e=this.item.system.step.value;if(e`+l.split(",").map(t=>`${t}`).join(", ")+""}u(Qi,"clickableAbilities");function Oi(l,e,t,a){if(a)return e.map(s=>`${s.name}${xi(getProperty(s.system,t),getProperty(s.system,a))}`).join(", ");if(t){let s=[];for(let i of e){let r=getProperty(i.system,t);if(r){s.push(`${i.name} ${r}`);continue}}return s.join(", ")}else return e.map(s=>`${s.name}`).join(", ")}u(Oi,"clickableActorItems");function Xi(l,e,t,a){let s=[];for(let i of Object.values(e)){if(i.length==0)continue;let r=Oi(l,i,t,a);r&&s.push(r)}return s.join(", ")}u(Xi,"clickableSection");function xi(l,e){return e!=null&&Number(e)<2?"":[" I"," II"," III"," IV"," V"," VI"," VII"," VIII"," IX"," X"][l-1]}u(xi,"roman");function ii(){Handlebars.registerHelper({concatUp:(l,e)=>l+e.toUpperCase(),mod:(l,e)=>l%e,roman:(l,e)=>xi(l,e),isWEBM:l=>/.webm$/.test(l),itemCategory:l=>f.categoryLocalization(l),joinStr:(l,e)=>e.join(l),attrName:l=>f.attributeLocalization(l),attrAbbr:l=>f.attributeAbbrLocalization(l),diceThingsUp:(l,e)=>f.replaceDies(l,!1),clickableAbilities:(l,e)=>Qi(l,e),traitName:l=>game.i18n.localize(b.traitCategories[l]),consumableQL:l=>l.system.QLList.split(` -`)[Number(l.system.QL)-1],clickableActorItems:(l,e,t,a)=>Oi(l,e,t,a),clickableSection:(l,e,t,a)=>Xi(l,e,t,a),hasLocalization:(l,e)=>{let t=l.string||l;return game.i18n.has(t)?game.i18n.localize(t):e||""},replaceConditions:f.replaceConditions,floor:l=>Math.floor(Number(l)),sum:(l,e)=>l+e,br:l=>l.replace(/\n/g,"
    "),getAttr:(l,e,t)=>l.system.characteristics[e][t],hasElem:(l,e)=>l.some(t=>e==t),situationalTooltip:l=>{let e=game.i18n.localize(Ji[l.type]||"Modifier"),t=`${l.name}
    ${e}: ${l.value}`;return l.source&&(t+=`
    ${game.i18n.localize("source")}: ${l.source}`),t},grouped_each:(l,e,t)=>{let a="",s=[],i;if(e&&e.length>0){for(i=0;i0&&i%l===0&&(a+=t.fn(s),s=[]),s.push(e[i]);a+=t.fn(s)}return a},plantify:l=>game.i18n.localize(`PLANT.avLevels.${l||0}`),oddLength:l=>l.length%2==1})}u(ii,"default");function ri(){Hooks.once("init",()=>{game.dsa5.apps.DiceSoNiceCustomization=new _e}),Hooks.once("diceSoNiceReady",(l,e,t,a)=>{l.addColorset({name:"mu",description:"DSA5.mu",category:"DSA5.dies",foreground:"#FFFFFF",background:"#b3241a",edge:"#b3241a",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"kl",description:"DSA5.kl",category:"DSA5.dies",foreground:"#FFFFFF",background:"#8259a3",edge:"#8259a3",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"in",description:"DSA5.in",category:"DSA5.dies",foreground:"#FFFFFF",background:"#388834",edge:"#388834",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ch",description:"DSA5.ch",category:"DSA5.dies",foreground:"#FFFFFF",background:"#0d0d0d",edge:"#0d0d0d",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ff",description:"DSA5.ff",category:"DSA5.dies",foreground:"#000000",background:"#d5b467",edge:"#d5b467",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ge",description:"DSA5.ge",category:"DSA5.dies",foreground:"#000000",background:"#688ec4",edge:"#688ec4",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ko",description:"DSA5.ko",category:"DSA5.dies",foreground:"#000000",background:"#a3a3a3",edge:"#a3a3a3",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"kk",description:"DSA5.kk",category:"DSA5.dies",foreground:"#000000",background:"#d6a878",edge:"#d6a878",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"attack",description:"DSA5.attack",category:"DSA5.dies",foreground:"#FFFFFF",background:"#b3241a",edge:"#b3241a",outline:"#b3241a",texture:"none"}),l.addColorset({name:"dodge",description:"DSA5.dodge",category:"DSA5.dies",foreground:"#FFFFFF",background:"#388834",edge:"#388834",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"parry",description:"DSA5.parry",category:"DSA5.dies",foreground:"#FFFFFF",background:"#388834",edge:"#388834",outline:"#FFFFFF",texture:"none"}),game.dsa5.apps.DiceSoNiceCustomization.initConfigs(),_e.onConnect()})}u(ri,"default");var at=class extends Application{initConfigs(){let e=game.dice3d.exports.Utils.prepareColorsetList();this.choices={};for(let[a,s]of Object.entries(e))mergeObject(this.choices,s);let t={damage:"black"};delete this.choices.custom,game.settings.registerMenu("dsa5","dicesonicesettings",{name:"DiceSoNiceSettings",label:"DiceSoNice Settings",hint:game.i18n.localize("DSASETTINGS.dicesonicesettings"),type:Ls,restricted:!1});for(let a of at.attrs)game.settings.register("dsa5",`dice3d_${a}`,{name:`CHAR.${a.toUpperCase()}`,scope:"client",config:!1,default:t[a]||a,type:String}),game.settings.register("dsa5",`dice3d_system_${a}`,{name:`CHAR.${a.toUpperCase()}`,scope:"client",config:!1,default:"standard",type:String})}getAttributeConfiguration(e){return f.moduleEnabled("dice-so-nice")&&game.dice3d?{colorset:game.settings.get("dsa5",`dice3d_${e}`),appearance:{colorset:game.settings.get("dsa5",`dice3d_${e}`),system:game.settings.get("dsa5",`dice3d_system_${e}`)}}:{colorset:e}}activateListeners(e){super.activateListeners(),e.find('[name="entryselection"]').change(async t=>{await game.settings.set("dsa5",`dice3d_${t.currentTarget.dataset.attr}`,t.currentTarget.value)}),e.find('[name="systemselection"]').change(async t=>{await game.settings.set("dsa5",`dice3d_system_${t.currentTarget.dataset.attr}`,t.currentTarget.value),at.preloadDiceAssets([t.currentTarget.value]),game.socket.emit("system.dsa5",{type:"preloadDice3d",payload:{toPreload:[t.currentTarget.value]}})})}static onConnect(){game.socket.on("system.dsa5",e=>{switch(e.type){case"preloadDice3d":console.warn("Preloading forced DSA dice assets"),at.preloadDiceAssets(e.payload);break;case"getPreloadDice3d":at.requestDicePreloads();break}}),this.collectPreloads(),game.socket.emit("system.dsa5",{type:"getPreloadDice3d"})}static collectPreloads(e=!0){let t=new Set;for(let a of at.attrs)t.add(game.settings.get("dsa5",`dice3d_system_${a}`));t=Array.from(t),e&&this.preloadDiceAssets(t),game.socket.emit("system.dsa5",{type:"preloadDice3d",payload:t})}static requestDicePreloads(){this.collectPreloads(!1)}static async preloadDiceAssets(e,t=[]){console.warn("loading",e);for(let a of e){let s=game.dice3d.DiceFactory.systems[a];if(!s){this.unloadedModels.push(a);continue}let i=s.dice.filter(r=>t.length==0||t.includes(r.type));for(let r of i)try{r.modelFile?await r.loadModel(game.dice3d.DiceFactory.loaderGLTF):await r.loadTextures()}catch{console.warn("Unable to load dice model",a,r)}}this.unloadedModels.length&&this.retries<6&&!this.retrying&&(this.retrying=!0,setTimeout(()=>{this.retries+=1;let a=new Set(this.unloadedModels);this.unloadedModels=[],this.retrying=!1,this.preloadDiceAssets(a)},1e4))}async getData(e){let t=await super.getData(e);t.choices=this.choices,t.systems=game.dice3d.DiceFactory.systems,t.selections={};for(let a of at.attrs)t.selections[a]={color:game.settings.get("dsa5",`dice3d_${a}`),system:game.settings.get("dsa5",`dice3d_system_${a}`)};return t}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{template:"systems/dsa5/templates/wizard/dicesonice-configuration.html",title:game.i18n.localize("DSASETTINGS.dicesonicesettings"),width:600}),e}},_e=at;u(_e,"DiceSoNiceCustomization"),L(_e,"unloadedModels",[]),L(_e,"retries",0),L(_e,"retrying",!1),L(_e,"attrs",["mu","kl","in","ch","ff","ge","ko","kk","attack","dodge","parry","damage"]);var Ls=class extends FormApplication{render(){game.dsa5.apps.DiceSoNiceCustomization.render(!0)}};u(Ls,"DiceSoNiceForm");function ni(){Hooks.on("preDeleteActiveEffect",(r,n,o)=>{if(n.noHook)return;let c=r.parent;if(c&&c.documentName=="Actor"&&getProperty(r,"flags.dsa5.maintain")){let m=[r._id],d=r.name.replace("("+game.i18n.localize("maintainCost")+")","").trim(),p=c.effects.filter(y=>y.name.startsWith(d)&&!y.origin&&y.id!=r._id),g=game.i18n.format("DIALOG.updateMaintainSpell",{actor:c.name});return p&&(g+=`

    ${game.i18n.localize("DIALOG.dependentMaintainEffects")}

    `,g+=p.map(y=>`

    `).join("")),new Dialog({title:r.name,content:g,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("HELP.pay"),callback:async()=>{if(await c.applyMana(Number(getProperty(r,"flags.dsa5.maintain")),getProperty(r,"flags.dsa5.payType"))){let h={startTime:game.time.worldTime};game.combat&&(h.startRound=game.combat.round,h.startTurn=game.combat.turn),c.updateEmbeddedDocuments("ActiveEffect",[{_id:r._id,duration:h}])}}},delete:{icon:'',label:game.i18n.localize("delete"),callback:y=>{for(let h of y.find(".effectRemoveSelector:checked"))m.push($(h).val());c.deleteEmbeddedDocuments("ActiveEffect",m,{noHook:!0})}}}}).render(!0),!1}}),Hooks.on("updateActor",(r,n)=>{!game.user.isGM&&r.limited&&hasProperty(n,"system.merchant.hidePlayer")&&ui.sidebar.render(!0)}),Hooks.on("deleteActiveEffect",(r,n)=>{if(!f.isActiveGM()||n.noHook)return;let o=r.parent;if(o&&o.documentName=="Actor"){let c=[...r.statuses][0];if(c=="bloodrush")return o.addCondition("stunned",2,!1,!1),!1;if(c=="dead"&&game.combat)return o.markDead(!1),!1;if(Q.onEffectRemove(o,r),Hooks.call("deleteActorActiveEffect",o,r)===!1)return!1}}),Hooks.on("dropActorSheetData",(r,n,o)=>{switch(o.data?.type){case"condition":return r.addCondition(o.data.payload.id,1,!1,!1),!1;case"lookup":return n._handleLookup(o.data),!1;case"fullpack":return n._addFullPack(o.data),!1}}),Hooks.on("createActiveEffect",(r,n,o)=>{!f.isActiveGM()||(l(r),e(r))}),Hooks.on("deleteActiveEffect",(r,n,o)=>{!f.isActiveGM()||l(r)}),Hooks.on("updateActiveEffect",(r,n,o)=>{!f.isActiveGM()||(l(r),t(r))});function l(r){if(game.combat&&r.changes.some(n=>/(system\.status\.initiative|system\.characteristics.mu|system\.characteristics\.ge)/.test(n.key))){let n=r.parent.id,o=game.combat.combatants.find(c=>c.actor.id==n);o&&o.recalcInitiative()}}u(l,"checkIniChange");let e=u(async r=>{let n=r.parent;if(!n)return;await t(r,{},n);let o=[...r.statuses][0];o=="dead"&&game.combat?await n.markDead(!0):o=="unconscious"&&await n.addCondition("prone")},"createEffects"),t=u(async(r,n={},o)=>{if(o||(o=r.parent),!o||o.documentName!="Actor")return;let c=/^system\.condition\./;for(let m of r.changes||[])c.test(m.key)&&m.mode==2&&(n[m.key.split(".")[2]]=Number(m.value));for(let m of Object.keys(n))if(o.system.condition[m]>=4&&(m=="inpain"?await o.initResistPainRoll(r):["encumbered","stunned","feared","confused","trance"].includes(m)?await o.addCondition("incapacitated"):m=="paralysed"?await o.addCondition("rooted"):["drunken","exhaustion"].includes(m)&&(await o.addCondition("stunned"),await o.removeCondition(m))),(Number(n.inpain)||0)>0&&!o.hasCondition("bloodrush")&&o.system.condition.inpain>0&&O.hasVantage(o,game.i18n.localize("LocalizedIDs.frenzy"))){await o.addCondition("bloodrush");let d=f.replaceConditions(`${game.i18n.format("CHATNOTIFICATION.gainsBloodrush",{character:""+o.name+""})}`);ChatMessage.create(f.chatDataSetup(d))}},"countableDependentEffects"),a=u(async(r,n)=>{(game.dsa5.apps.AskForNameDialog||Rs).getDialog(r,n)},"askForName"),s=u(async r=>{if(!!f.isActiveGM()&&game.settings.get("dsa5","randomWeaponSelection")&&r.actor.type!="character"){let n=[],o=[],c=[];for(let d of r.actor.items)d.type=="meleeweapon"&&d.system.worn.value?P.isShield(d)?o.push(d):n.push(d):d.type=="rangeweapon"&&d.system.worn.value&&c.push(d);let m=[];if(n.length){let d=n[Math.floor(Math.random()*n.length)],p=d._id,g;!P.regex2h.test(d.name)&&o.length&&(g=o[Math.floor(Math.random()*o.length)]._id);for(let y of n)y._id!=p&&m.push({_id:y._id,system:{worn:{value:!1}}});for(let y of o)y._id!=g&&m.push({_id:y._id,system:{worn:{value:!1}}})}if(c.length){let d=c[Math.floor(Math.random()*c.length)]._id;for(let p of c)p._id!=d&&m.push({_id:p._id,system:{worn:{value:!1}}})}m.length&&r.actor.updateEmbeddedDocuments("Item",m)}},"randomWeaponSelection"),i=u(async(r,n)=>{if(!f.isActiveGM())return;let o=r.actor;if(o.hasPlayerOwner)return;let c=Number(game.settings.get("dsa5","obfuscateTokenNames"));if(c==0||getProperty(o,"merchant.merchantType")=="loot")return;let m=canvas.scene.tokens.filter(p=>p.actor&&p.actor.id===o.id),d=game.i18n.localize("unknown");if([2,4].includes(c)){if(!(r.id||r._id))return;a(r,c);return}if(m.length>0&&c<3){let p=m.length;for(let g of m){let y=g.name.match(/\d+$/);y&&Number(y[0])>p&&(p=Number(y[0]))}d=`${m[0].name.replace(/ \d{1,}$/,"")} ${p+1}`}n.name=d},"obfuscateName");Hooks.on("updateToken",(r,n,o)=>{H.updateTokenHook(r,n,o)}),Hooks.on("deleteToken",r=>{H.deleteTokenHook(r),st.hide(r)}),Hooks.on("preCreateToken",(r,n,o,c)=>{let m=r.actor;if(!m)return;let d={};getProperty(m,"system.merchant.merchantType")=="loot"?mergeObject(d,{displayBars:0}):getProperty(m,"system.config.autoBar")&&(mergeObject(d,{bar1:{attribute:"status.wounds"}}),m.system.isMage?mergeObject(d,{bar2:{attribute:"status.astralenergy"}}):m.system.isPriest?mergeObject(d,{bar2:{attribute:"status.karmaenergy"}}):mergeObject(d,{bar2:{attribute:"tbd"}})),getProperty(m,"system.config.autoSize")&&f.calcTokenSize(m,d),i(r,d),r.updateSource(d)}),Hooks.on("createToken",(r,n,o)=>{n.noHook||(i(r,{}),s(r),H.createTokenHook(r,n,o))}),Hooks.on("hoverToken",(r,n)=>{!game.settings.get("dsa5","showWeaponsOnHover")||(n?st.show(r):st.hide(r))})}u(ni,"default");var st=class{static show(e){if(!game.combat||canvas.hud?.token?.rendered)return;let t=e.actor.items.filter(a=>a.type=="meleeweapon"||a.type=="rangeweapon"?a.system.worn.value:!1);if(t.length){let a=t.map(i=>``).join(" "),s=$(`
    ${a}
    `);$("#hud").append(s),this.position(s,e,t.length)}}static position(e,t,a){let s=t.document,i=canvas.dimensions.size/100,r=a*43,n={width:r,height:42,left:t.center.x-r/2*i,top:t.y+s.height*canvas.dimensions.size+32};i!==1&&(n.transform=`scale(${i})`),e.css(n)}static hide(e){$(`#hoverhud_${e.id}`).remove()}};u(st,"TokenHoverHud");var Rs=class extends Dialog{static async getDialog(e,t){new Dialog({title:game.i18n.localize("DSASETTINGS.obfuscateTokenNames"),content:` `,default:"Yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async a=>{let s=e.id||e._id,i=a.find('[name="name"]').val();if(t==2){let n=canvas.scene.tokens.filter(o=>o.name===i);if(n.length>0){let o=n.length;for(let c of n){let m=c.name.match(/\d+$/);m&&Number(m[0])>o&&(o=Number(m[0]))}i=`${n[0].name.replace(/ \d{1,}$/,"")} ${o+1}`}}await canvas.scene.tokens.get(s).update({name:i})}},unknown:{icon:'',label:game.i18n.localize("unknown"),callback:async()=>{let a=e.id||e._id;await canvas.scene.tokens.get(a).update({name:game.i18n.localize("unknown")})}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}};u(Rs,"AskForNameDialog");function oi(){Hooks.on("hotbarDrop",(l,e,t)=>{if(e.mod=="dodge"){let a={name:game.i18n.localize(e.mod),img:"systems/dsa5/icons/categories/Dodge.webp"},s;return game.user.isGM||e.actorId==null?s=`game.dsa5.macro.charMacro("${e.mod}")`:s=`game.dsa5.macro.charMacroById("${e.mod}", "${e.actorId}")`,_s(s,a.name,a.img,t)}else if(e.mod=="attackWeaponless"||e.mod=="parryWeaponless"){let a={name:game.i18n.localize(e.mod),img:"systems/dsa5/icons/categories/attack_weaponless.webp"},s;return game.user.isGM||e.actorId==null?s=`game.dsa5.macro.weaponLessMacro("${e.mod}")`:s=`game.dsa5.macro.weaponLessMacroId("${e.mod}", "${e.actorId}")`,_s(s,a.name,a.img,t)}else if(e.type=="Item"){let a=fromUuidSync(e.uuid);if(!["ritual","ceremony","meleeweapon","rangeweapon","skill","combatskill","spell","liturgy","char","trait"].includes(a.type)||(a.type=="meleeweapon"||a.type=="combatskill")&&!["attack","parry"].includes(e.mod))return;if((a.type=="rangeweapon"||a.type=="trait")&&!["attack"].includes(e.mod))return;let i=`{mod: "${e.mod}"}`,r;game.user.isGM||e.actorId==null?r=`game.dsa5.macro.itemMacro("${a.name}", "${a.type}", ${i});`:r=`game.dsa5.macro.itemMacroById("${e.actorId}", "${a.name}", "${a.type}", ${i})`;let n=e.mod==null?a.name:`${a.name} - ${game.i18n.localize("CHAR."+e.mod.toUpperCase())}`;return _s(r,n,a.img,t)}else if(e.type=="Actor"||e.type=="JournalEntry"){let a=fromUuidSync(e.uuid),s=`(await fromUuid('${e.uuid}')).sheet.render(true)`;return _s(s,a.name,a.img,t)}})}u(oi,"default");function _s(l,e,t,a){let s=game.macros.contents.find(i=>i.name===e&&i.command===l);return s?game.user.assignHotbarMacro(s,a):Macro.create({name:e,type:"script",img:t,command:l},{displaySheet:!1}).then(i=>game.user.assignHotbarMacro(i,a)),!1}u(_s,"createHotBarMacro");function li(){Hooks.on("renderChatLog",(l,e,t)=>{j.chatListeners(e),_DiceDSA5.chatListeners(e),B.chatListeners(e);let a=new se;Hooks.call("startDSA5ChatAutoCompletion",a),a.chatListeners(e),ae.chatListeners(e)}),Hooks.on("renderChatMessage",(l,e,t)=>{if(game.user.isGM)e.find(".chat-button-player").remove();else{e.find(".chat-button-gm").remove();let a,s=e.find(".chat-button-target");s.length&&(a=ce.getTargetActor(t.message),a&&a.actor&&!a.actor.isOwner&&s.remove());let i=f.getSpeaker(t.message.speaker);i&&!i.isOwner&&(e.find(".selfButton").remove(),e.find(".d20").attr("data-tooltip",""));let r=e.find(".onlyTarget");r.length&&(a=f.getSpeaker({token:r.attr("data-token"),actor:r.attr("data-actor"),scene:canvas.scene?canvas.scene.id:null}),a&&!a.isOwner&&r.remove()),e.find(".hideData").remove(),getProperty(t.message,`flags.dsa5.userHidden.${game.user.id}`)&&e.find(".payButton").remove()}game.settings.get("dsa5","expandChatModifierlist")&&(e.find(".expand-mods i").toggleClass("fa-minus fa-plus"),e.find(".expand-mods + ul").css({display:"block"})),E.bindButtons(e),e.find(".embeddedItemDrag").each(function(a,s){s.setAttribute("draggable",!0),s.addEventListener("dragstart",i=>sr(i))})}),Hooks.on("chatMessage",(l,e,t)=>{let a=e.match(/^\/(pay|getPaid|help$|conditions$|tables)/);switch(a=a?a[0]:"",a){case"/pay":return game.user.isGM?B.createPayChatMessage(e):B.payMoney(f.getSpeaker(t.speaker),e),!1;case"/getPaid":return game.user.isGM?B.createGetPaidChatMessage(e):B.getMoney(f.getSpeaker(t.speaker),e),!1;case"/help":return ae.getHelp(),!1;case"/conditions":return ae.showConditions(),!1;case"/tables":return ae.showTables(),!1}}),Hooks.on("preCreateChatMessage",(l,e,t,a)=>{if(getProperty(l,"flags.core.initiativeRoll")){let s=l.rolls[0].terms,i=`${s[0].number}`.split(".")[0],r=`${game.i18n.localize("baseValue")}: ${i}, ${game.i18n.localize("randomValue")}: ${s.at(-3).values[0]}")}`,n=[];for(let m of s)if(m.faces&&m.faces==6)for(let d=0;d${m.results[d].result}
    `);let c={content:`
    + ${game.i18n.localize(`CHATFATE.${r}`)}: ${n}`,c=s.preData;c.extra.actor=f.getSpeaker(c.extra.speaker).toObject(!1),this[`fate${t}`](o,i,c,e,s,a)}}get horseSpeed(){return H.getHorseSpeed(this)}setupFallingDamage(e,t){let a=game.i18n.localize("fallingDamage"),s=this.items.find(n=>n.type=="skill"&&n.name==game.i18n.localize("LocalizedIDs.bodyControl")).toObject(),i={subtitle:` (${a})`,postFunction:{functionName:"game.dsa5.entities.Actordsa5.updateFallingDamage",options:e,tokenId:t,speaker:C.buildSpeaker(this,t)}};this.setupSkill(s,i,t).then(async n=>{n.testData.opposable=!1;let r=await this.basicTest(n,{suppressMessage:!0});await T.updateFallingDamage(i.postFunction,r),await _DiceDSA5.renderRollCard(r.cardOptions,r.result,r.options.rerenderMessage)})}static async updateFallingDamage(e,t,a){let s=(t.result.qualityStep||0)*2;mergeObject(e.options,{availableQs:s});let i=f.getSpeaker(e.speaker),n=await i._setupFallingHeight(e.options,e.tokenId),r=await i.basicTest(n,{suppressMessage:!0}),o=await renderTemplate("systems/dsa5/templates/chat/roll/fallingdamage-card.html",r);t.result.other||(t.result.other=[]),t.result.other.push(o),t.chatData&&(t.chatData.other=[o])}_setupFallingHeight(e,t){let a=game.i18n.localize("fallingDamage"),s={source:{type:"fallingDamage"},opposable:!1,extra:{actor:this.toObject(!1),options:e,speaker:C.buildSpeaker(this,t)}},i=[],n={title:a,template:"/systems/dsa5/templates/dialog/fallingdamage-dialog.html",data:{rollMode:e.rollMode,situationalModifiers:i,fallingFloorOptions:b.fallingConditions,modifier:e.modifier||0},callback:(o,c={})=>(s.situationalModifiers=[],s.situationalModifiers.push({name:game.i18n.localize("fallingFloor"),value:o.find('[name="fallingFloor"]').val()}),r.rollMode=o.find('[name="rollMode"]').val(),s.fallingHeight=o.find('[name="testModifier"]').val(),mergeObject(s.extra.options,c),{testData:s,cardOptions:r})},r=this._setupCardOptions("systems/dsa5/templates/chat/roll/fallingdamage-card.html",a,t);return _DiceDSA5.setupDialog({dialogOptions:n,testData:s,cardOptions:r})}setupRegeneration(e,t={},a){let s=game.i18n.localize("regenerationTest"),i={source:{type:"regenerate",system:{}},opposable:!1,extra:{statusId:e,actor:this.toObject(!1),options:t,speaker:C.buildSpeaker(this,a)}};i.extra.actor.isMage=this.system.isMage,i.extra.actor.isPriest=this.system.isPriest;let n=E.getRollModifiers(i.extra.actor,i.source),r={title:s,template:"/systems/dsa5/templates/dialog/regeneration-dialog.html",data:{rollMode:t.rollMode,regenerationInterruptOptions:b.regenerationInterruptOptions,regnerationCampLocations:b.regnerationCampLocations,showAspModifier:this.system.isMage,showKapModifier:this.system.isPriest,situationalModifiers:n,modifier:t.modifier||0},callback:(c,m={})=>{i.situationalModifiers=T._parseModifiers(c),o.rollMode=c.find('[name="rollMode"]').val(),i.situationalModifiers.push({name:game.i18n.localize("camplocation")+" - "+c.find('[name="regnerationCampLocations"] option:selected').text(),value:c.find('[name="regnerationCampLocations"]').val()},{name:game.i18n.localize("interruption")+" - "+c.find('[name="regenerationInterruptOptions"] option:selected').text(),value:c.find('[name="regenerationInterruptOptions"]').val()}),i.regenerationFactor=c.find('[name="badEnvironment"]').is(":checked")?.5:1;let d=["LeP","KaP","AsP"],p={};for(let g of d){i[`${g}Modifier`]=Number(c.find(`[name="${g}Modifier"]`).val()||0),i[`regeneration${g}`]=Number(this.system.status.regeneration[`${g}max`]);let y=c.find(`[name="regenerate${g}"]`).is(":checked")?1:0;i[`regenerate${g}`]=y,y&&(p[`system.status.regeneration.${g}Temp`]=0)}return mergeObject(i.extra.options,m),this.update(p),{testData:i,cardOptions:o}}},o=this._setupCardOptions("systems/dsa5/templates/chat/roll/regeneration-card.html",s,a);return _DiceDSA5.setupDialog({dialogOptions:r,testData:i,cardOptions:o})}setupDodge(e={},t){let a="dodge",s=this.system.status[a],i=game.i18n.localize(a)+" "+game.i18n.localize("Test"),n={source:{system:s,type:a},opposable:!1,extra:{statusId:a,actor:this.toObject(!1),options:e,speaker:C.buildSpeaker(this,t)}},r=[game.i18n.localize(a),game.i18n.localize("LocalizedIDs.wrestle")],o=C.buildCombatSpecAbs(this,["Combat"],r,"parry"),c=E.getRollModifiers(n.extra.actor,n.source),m=C.getDefenseMalus(c,this),d=P.multipleDefenseValue(this,n.source),p={title:i,template:"/systems/dsa5/templates/dialog/combatskill-enhanced-dialog.html",data:{rollMode:e.rollMode,combatSpecAbs:o,showDefense:!0,situationalModifiers:c,isRangeAttack:m,defenseCountString:game.i18n.format("defenseCount",{malus:d}),isDodge:!0},callback:(y,h={})=>(g.rollMode=y.find('[name="rollMode"]').val(),n.situationalModifiers=T._parseModifiers(y),n.situationalModifiers.push(...C.getSpecAbModifiers(y,"parry")),n.situationalModifiers.push({name:game.i18n.localize("attackFromBehind"),value:y.find('[name="attackFromBehind"]').is(":checked")?-4:0},{name:game.i18n.format("defenseCount",{malus:d}),value:(Number(y.find('[name="defenseCount"]').val())||0)*d},{name:game.i18n.localize("advantageousPosition"),value:y.find('[name="advantageousPosition"]').is(":checked")?2:0}),mergeObject(n.extra.options,h),{testData:n,cardOptions:g})},g=this._setupCardOptions("systems/dsa5/templates/chat/roll/status-card.html",i,t);return _DiceDSA5.setupDialog({dialogOptions:p,testData:n,cardOptions:g})}setupCharacteristic(e,t={},a){let s=duplicate(this.system.characteristics[e]),i=f.attributeLocalization(e)+" "+game.i18n.localize("Test");s.attr=e;let n={opposable:!1,source:{type:"char",system:s},extra:{characteristicId:e,actor:this.toObject(!1),options:t,speaker:C.buildSpeaker(this,a)}},r={title:i,template:"/systems/dsa5/templates/dialog/characteristic-dialog.html",data:{rollMode:t.rollMode,difficultyLabels:b.attributeDifficultyLabels,modifier:t.modifier||0},callback:(c,m={})=>(o.rollMode=c.find('[name="rollMode"]').val(),n.testDifficulty=b.attributeDifficultyModifiers[c.find('[name="testDifficulty"]').val()],n.situationalModifiers=T._parseModifiers(c),mergeObject(n.extra.options,m),{testData:n,cardOptions:o})},o=this._setupCardOptions("systems/dsa5/templates/chat/roll/characteristic-card.html",i,a);return _DiceDSA5.setupDialog({dialogOptions:r,testData:n,cardOptions:o})}static _parseModifiers(e,t){let a=[];return e.find('[name="situationalModifiers"] option:selected').each(function(){let s=$(this).val(),i={name:$(this).text().trim().split("[")[0],value:isNaN(s)?s:Number(s),type:$(this).attr("data-type")};i.type=="dmg"&&(i.damageBonus=i.value,i.value=0),$(this).attr("data-specAbId")&&(i.specAbId=$(this).attr("data-specAbId")),$(this).attr("data-armorPen")&&(i.armorPen=$(this).attr("data-armorPen")),a.push(i)}),a.push({name:game.i18n.localize("manual"),value:Number(e.find('[name="testModifier"]').val()),type:""}),a}static _prepareConsumable(e){return e.system.maxCharges&&(e.consumable=!0,e.structureMax=e.system.maxCharges,e.structureCurrent=e.system.charges),e}static prepareMag(e){return e.system.ammunitiongroup.value=="mag"&&(e.structureMax=e.system.mag.max,e.structureCurrent=e.system.mag.value),e}static _prepareitemStructure(e){e.system.structure&&e.system.structure.max!=0&&(e.structureMax=e.system.structure.max,e.structureCurrent=e.system.structure.value);let t=getProperty(e,"flags.dsa5.enchantments");if(t&&t.length>0)e.enchantClass="rar";else if(e.effects.length>0)e.enchantClass="common";else if(e.system.effect&&e.system.effect.value!="")if(e.type=="armor")for(let a of e.system.effect.value.split(/,|;/).map(s=>s.trim())){let s=a.replace(/(\s+)/g," ").trim().split(" ");if(!(s.length==2&&[game.i18n.localize("CHARAbbrev.INI").toLowerCase(),game.i18n.localize("CHARAbbrev.GS").toLowerCase()].includes(s[1].toLowerCase())&&!isNaN(s[0])&&s[0]==-1)){e.enchantClass="common";break}}else e.enchantClass="common";return e}static _prepareMeleetrait(e){return e.attack=Number(e.system.at.value),e.system.pa!=0&&(e.parry=e.system.pa),this._parseDmg(e)}static _prepareMeleeWeapon(e,t,a,s=null){let i=t.find(n=>n.name==e.system.combatskill.value);if(i){e.attack=Number(i.system.attack.value)+Number(e.system.atmod.value);let n=e.system.guidevalue.value.split("/").map(c=>a.system.characteristics[c]?Number(a.system.characteristics[c].initial)+Number(a.system.characteristics[c].modifier)+Number(a.system.characteristics[c].advances)+Number(a.system.characteristics[c].gearmodifier):0),r=Math.ceil(i.system.talentValue.value/2)+Math.max(0,Math.floor((Math.max(...n)-8)/3))+Number(game.settings.get("dsa5","higherDefense"));e.parry=r+Number(e.system.pamod.value)+(P.isShield(e)?Number(e.system.pamod.value):0),e.yieldedTwoHand=P.isYieldedTwohanded(e),e.yieldedTwoHand||(s||(s=a.items.filter(c=>c.type=="meleeweapon"&&c.system.worn.value&&c._id!=e._id&&!P.isYieldedTwohanded(c))),s.length>0&&(e.parry+=Math.max(...s.map(c=>c.system.pamod.offhandMod)),e.attack+=Math.max(...s.map(c=>c.system.atmod.offhandMod))));let o=0;if(e.system.worn.wrongGrip)if(e.yieldedTwoHand)e.parry-=1,o=1;else switch(e.system.reach.value="medium",game.i18n.localize(`LocalizedCTs.${e.system.combatskill.value}`)){case"Two-Handed Impact Weapons":case"Two-Handed Swords":if(e.parry-=3,new RegExp(game.i18n.localize("wrongGrip.wrongGripBastardRegex")).test(e.name))o=-2;else{let d=game.i18n.localize("wrongGrip.oneHanded");e.gripDamageText=` (${d} * 0.5)`,e.dmgMultipliers=[{name:d,val:"0.5"}]}break;default:e.parry-=1,o=-1}if(e=this._parseDmg(e),e.system.guidevalue.value!="-"){let c=Math.max(...e.system.guidevalue.value.split("/").map(d=>Number(a.system.characteristics[d].value))),m=Math.max(c-Number(e.system.damageThreshold.value),0)+o;m>0&&(e.extraDamage=m,e.damageAdd=Roll.safeEval(e.damageAdd+" + "+Number(m)),e.damageAdd=(e.damageAdd>0?"+":"")+e.damageAdd)}W.weaponWearModifier(e),e.system.damageToolTip=W.damageTooltip(e)}else ui.notifications.error(game.i18n.format("DSAError.unknownCombatSkill",{skill:e.system.combatskill.value,item:e.name}));return e}async actorEffects(){let e=["dead"];return game.user.isGM||this.testUserPermission(game.user,"OBSERVER")||!game.settings.get("dsa5","hideEffects")?this.effects.filter(a=>a.isVisibleEffect()):this.effects.filter(a=>e.some(s=>a.statuses.has(s)))}async _preCreate(e,t,a){await super._preCreate(e,t,a);let s={};e.img||(s.img="icons/svg/mystery-man-black.svg"),e.type=="character"&&mergeObject(s,{prototypeToken:{sight:{enabled:!0},actorLink:!0}}),this.updateSource(s)}async exclusiveEquipWeapon(e,t=!1){let a=this.items.get(e);if(!a)return;let s=[];switch(a.type){case"armor":case"rangeweapon":s=this.items.filter(o=>o.type==a.type&&o.id!=e&&o.system.worn.value).map(o=>({_id:o.id,"system.worn.value":!1})),s.push({_id:e,"system.worn.value":!0});break;case"meleeweapon":let n=this.items.filter(o=>o.type==a.type&&o.id!=e&&o.system.worn.value),r={_id:e,"system.worn.value":!0};P.isYieldedTwohanded(a)||(n=n.filter(o=>P.isYieldedTwohanded(o)||o.system.worn.offHand==t),r["system.worn.offHand"]=t),s=n.map(o=>({_id:o.id,"system.worn.value":!1})),s.push(r);break}s&&await this.updateEmbeddedDocuments("Item",s)}static _prepareRangeTrait(e){return e.attack=Number(e.system.at.value),e.LZ=Number(e.system.reloadTime.value),e.LZ>0&&T.buildReloadProgress(e),this._parseDmg(e)}static calcLZ(e,t){let a=1,s=0;e.system.combatskill.value==game.i18n.localize("LocalizedIDs.Throwing Weapons")?s=R.abilityStep(t,game.i18n.localize("LocalizedIDs.quickdraw"))*-1:e.system.combatskill.value==game.i18n.localize("LocalizedIDs.Crossbows")&&R.hasAbility(t,`${game.i18n.localize("LocalizedIDs.quickload")} (${game.i18n.localize("LocalizedIDs.Crossbows")})`)?a=.5:s=R.abilityStep(t,`${game.i18n.localize("LocalizedIDs.quickload")} (${game.i18n.localize(e.system.combatskill.value)})`)*-1;let i=`${e.system.reloadTime.value}`.split("/");if(e.system.ammunitiongroup.value=="mag"){let n=t.items.find(o=>o.id==e.system.currentAmmo.value||o._id==e.system.currentAmmo.value),r=0;n&&(n=f.toObjectIfPossible(n),n.system.mag.value<=0&&(r=1)),i=i[r]||i[0]}else i=i[0];return Math.max(0,Math.round(Number(i)*a)+s)}static _parseDmg(e,t=void 0){let a=new Roll(e.system.damage.value.replace(/[Ww]/g,"d"),{async:!1}),s="",i="",n="+";for(let r of a.terms)r.faces?s=r.number+"d"+r.faces:r.operator?n=r.operator:r.number&&(i+=Number(`${n}${r.number}`));if(t){let r=getProperty(t,"system.damageMod");Number(r)?i+=`+${Number(r)}`:r&&(e.damageBonusDescription=`, ${r} ${game.i18n.localize("CHARAbbrev.damage")} ${t.name}`)}return i&&(i=Roll.safeEval(i)),e.damagedie=s||"0d6",e.damageAdd=i!=""?(Number(i)>=0?"+":"")+i:"",e}static buildReloadProgress(e){let t=e.system.reloadTime.progress/e.LZ;e.title=game.i18n.format("WEAPON.loading",{status:`${e.system.reloadTime.progress}/${e.LZ}`}),e.progress=`${e.system.reloadTime.progress}/${e.LZ}`,t>=1&&(e.title=game.i18n.localize("WEAPON.loaded")),this.progressTransformation(e,t)}static progressTransformation(e,t){t>=.5?(e.transformRight="181deg",e.transformLeft=`${Math.round(t*360-179)}deg`):(e.transformRight=`${Math.round(t*360+1)}deg`,e.transformLeft=0)}static buildSpellChargeProgress(e){if(e.LZ=Number(e.system.castingTime.modified)||0,e.LZ>1){let t=e.system.castingTime.progress/e.LZ;e.title=game.i18n.format("SPELL.loading",{status:`${e.system.castingTime.progress}/${e.LZ}`}),e.progress=`${e.system.castingTime.progress}/${e.LZ}`,this.progressTransformation(e,t)}return e}static _prepareRangeWeapon(e,t,a,s){let i=a.find(r=>r.name==e.system.combatskill.value);e.calculatedRange=e.system.reach.value;let n;if(i){if(e.attack=Number(i.system.attack.value),e.system.ammunitiongroup.value!="-"&&(e.ammo=t.filter(r=>r.system.ammunitiongroup.value==e.system.ammunitiongroup.value),n=t.find(r=>r._id==e.system.currentAmmo.value),n)){let r=Number(n.system.rangeMultiplier)||1;e.calculatedRange=e.calculatedRange.split("/").map(o=>Math.round(Number(o)*r)).join("/"),e.attack+=Number(n.system.atmod)||0,n.system.ammunitiongroup.value=="mag"&&(e.ammoMax=n.system.mag.max,e.ammoCurrent=n.system.mag.value)}e.LZ=T.calcLZ(e,s),e.LZ>0&&T.buildReloadProgress(e),W.weaponWearModifier(e),e.system.damageToolTip=W.damageTooltip(e)}else ui.notifications.error(game.i18n.format("DSAError.unknownCombatSkill",{skill:e.system.combatskill.value,item:e.name}));return this._parseDmg(e,n)}_setupCardOptions(e,t,a){let s=game.canvas?.tokens?.get(a),i={speaker:{alias:s?s.name:this.prototypeToken.name,actor:this.id},title:t,template:e,flags:{img:this.prototypeToken.randomImg?this.img:this.prototypeToken.img}};if(this.token)i.speaker.alias=this.token.name,i.speaker.token=this.token.id,i.speaker.scene=canvas.scene.id,i.flags.img=this.token.img;else{let n=ChatMessage.getSpeaker();n.actor==this.id&&(i.speaker.alias=n.alias,i.speaker.token=n.token,i.speaker.scene=n.scene,i.flags.img=n.token?canvas.tokens.get(n.token).img:i.flags.img)}return i}async swapMag(e){let t=this.items.get(e),a=this.items.get(t.system.currentAmmo.value);if(a&&a.system.quantity.value>1)return await this.updateEmbeddedDocuments("Item",[{_id:a.id,"system.quantity.value":a.system.quantity.value-1,"system.mag.value":a.system.mag.max}]),K.playEquipmentWearStatusChange(a),a;ui.notifications.error(game.i18n.localize("DSAError.NoAmmo"))}async payMiracles(e){if(!e.extra.miraclePaid){e.extra.miraclePaid=!0;let t=e.situationalModifiers.some(i=>i.name.trim()==game.i18n.localize("LocalizedIDs.miracleMight")),a=e.situationalModifiers.some(i=>i.name.trim()==game.i18n.localize("LocalizedIDs.miracle")),s=t?6:a?4:0;s&&await this.update({"system.status.karmaenergy.value":this.system.status.karmaenergy.value-s})}}async consumeAmmunition(e){if(e.extra.ammo&&!e.extra.ammoDecreased){if(e.extra.ammoDecreased=!0,e.extra.ammo._id){let t={_id:e.extra.ammo._id};e.extra.ammo.system.ammunitiongroup.value=="mag"?e.extra.ammo.system.mag.value<=0?(e.extra.ammo.system.quantity.value--,t["system.quantity.value"]=e.extra.ammo.system.quantity.value,t["system.mag.value"]=e.extra.ammo.system.mag.max-1):t["system.mag.value"]=e.extra.ammo.system.mag.value-1:(e.extra.ammo.system.quantity.value--,t["system.quantity.value"]=e.extra.ammo.system.quantity.value),await this.updateEmbeddedDocuments("Item",[t,{_id:e.source._id,"system.reloadTime.progress":0}])}}else(e.source.type=="rangeweapon"||e.source.type=="trait"&&e.source.system.traitType.value=="rangeAttack")&&!e.extra.ammoDecreased?(e.extra.ammoDecreased=!0,await this.updateEmbeddedDocuments("Item",[{_id:e.source._id,"system.reloadTime.progress":0}])):["spell","liturgy"].includes(e.source.type)&&e.extra.speaker.token!="emptyActor"&&await this.updateEmbeddedDocuments("Item",[{_id:e.source._id,"system.castingTime.progress":0,"system.castingTime.modified":0}])}_checkMaximumItemAdvancement(e,t){let a=0;switch(e.type){case"combatskill":a=Math.max(...e.system.guidevalue.value.split("/").map(o=>this.system.characteristics[o].value))+2+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalCombatTechnique")} (${e.name})`);break;case"spell":case"ritual":let i=0;for(let o of e.system.feature.replace(/\(a-z äöü\-\)/gi,"").split(",").map(c=>c.trim()))if(R.hasAbility(this,`${game.i18n.localize("LocalizedIDs.propertyKnowledge")} (${o})`)){i=this.maxByAttr(e);break}a=Math.max(14+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalSkill")} (${e.name})`),i);break;case"liturgy":case"ceremony":let n=new RegExp(`^${game.i18n.localize("LocalizedIDs.aspectKnowledge")}`),r=0;this.items.filter(o=>o.type=="specialability"&&n.test(o.name)).some(o=>e.system.distribution.value.includes(o.name.split("(")[1].split(")")[0]))&&(r=this.maxByAttr(e)),a=Math.max(14+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalSkill")} (${e.name})`),r);break;case"skill":a=this.maxByAttr(e);break}let s=t<=a;return s||ui.notifications.error(game.i18n.localize("DSAError.AdvanceMaximumReached")),{result:s,max:a}}maxByAttr(e){return Math.max(this.system.characteristics[e.system.characteristic1.value].value,this.system.characteristics[e.system.characteristic2.value].value,this.system.characteristics[e.system.characteristic3.value].value)+2+O.vantageStep(this,`${game.i18n.localize("LocalizedIDs.exceptionalSkill")} (${e.name})`)}async basicTest({testData:e,cardOptions:t},a={}){e=await _DiceDSA5.rollDices(e,t);let s=await _DiceDSA5.rollTest(e);if(e.extra.options.other&&(s.other||(s.other=[]),s.other.push(...e.extra.options.other)),s.postFunction="basicTest",game.user.targets.size){t.isOpposedTest=e.opposable;let i=` - ${game.i18n.localize("Opposed")}`;t.isOpposedTest&&t.title.match(i+"$")!=i&&(t.title+=i)}if(await this.consumeAmmunition(e),await this.payMiracles(e),!a.suppressMessage){let i=await _DiceDSA5.renderRollCard(t,s,a.rerenderMessage);await j.handleOpposedTarget(i),s.messageId=i.id}return{result:s,cardOptions:t,options:a}}async addCondition(e,t=1,a=!1,s=!1){if(e=="bleeding"||e.id=="bleeding")return await P.bleedingMessage(this);if(this.isToken&&!this.token?.object){console.warn("Actor token object is null for",this.name);return}return await E.addCondition(this,e,t,a,s)}async addTimedCondition(e,t=1,a=!1,s=!0,i={}){return e=="bleeding"||e.id=="bleeding"?await P.bleedingMessage(this):(typeof e=="string"&&i.duration&&(e=duplicate(CONFIG.statusEffects.find(n=>n.id==e)),e.flags.dsa5.description=game.i18n.localize(e.name),e.name=game.i18n.localize(e.name),delete e.description,delete e.flags.dsa5.value,delete e.flags.dsa5.max,delete e.id,mergeObject(e,i)),await E.addCondition(this,e,t,a,s))}async initResistPainRoll(e){let t=game.settings.get("dsa5","selfControlOnPain");if(this.hasCondition("incapacitated"))return;if(t==2||t==1&&!this.hasPlayerOwner){await this.addCondition("incapacitated");return}let a=await renderTemplate("systems/dsa5/templates/chat/roll/resist-pain.html",{actor:this});await ChatMessage.create(f.chatDataSetup(a))}async finishResistPainRoll(){let e=this.items.find(t=>t.name==game.i18n.localize("LocalizedIDs.selfControl")&&t.type=="skill");this.setupSkill(e,{subtitle:` (${game.i18n.localize("ActiveEffects.resistRoll")})`},this.token?.id).then(async t=>{((await this.basicTest(t)).result.successLevel||0)<1&&this.addCondition("incapacitated")})}async removeCondition(e,t=1,a=!0,s=!1){return await E.removeCondition(this,e,t,a,s)}hasCondition(e){return E.hasCondition(this,e)}async markDead(e){let t=this.getActiveTokens();for(let a of t)a.combatant&&await a.combatant.update({defeated:e})}};u(T,"Actordsa5");function Ei(){let l={Rq:"roll",Gc:"GC",Ch:"CH"},e={Rq:"dice",Gc:"dice",Ch:"user-shield",AP:"trophy",Pay:"coins",GetPaid:"piggy-bank"},t={Rq:"",Gc:`${game.i18n.localize("HELP.groupcheck")} `,Ch:"",AP:"",Pay:"",GetPaid:""},a=/(-|\+)?\d+/,s=/(-|\+)?\d+(\.\d+)?/,i=/\[[a-zA-ZöüäÖÜÄ&; -]+/,n=/[\[\]]/g,r={Pay:game.i18n.localize("PAYMENT.payButton"),GetPaid:game.i18n.localize("PAYMENT.getPaidButton"),AP:game.i18n.localize("MASTER.awardXP")};if(!b.statusRegex){let o=b.statusEffects.map(m=>game.i18n.localize(m.name).toLowerCase()),c=["status","condition","level","levels"].map(m=>game.i18n.localize(m)).join("|");b.statusRegex={effects:o,regex:new RegExp(`(${c}) (${o.join("|")})`,"gi")}}CONFIG.TextEditor.enrichers.push({pattern:/@(Rq|Gc|Ch)\[[a-zA-ZöüäÖÜÄ&; -]+ (-|\+)?\d+\]({[a-zA-ZöüäÖÜÄß\(\)&; -]+})?/g,enricher:(o,c)=>{let m=o[0],d=o[1],p=Number(m.match(a)[0]),g=m.replace(p,"").match(i)[0].replace(n,"").trim(),y=m.match(/\{.*\}/)?m.match(/\{.*\}/)[0].replace(/[\{\}]/g,""):g;return $(`${t[d]}${y} ${p}`)[0]}},{pattern:/@(Pay|GetPaid|AP)\[(-|\+)?\d+(\.\d+)?\]({[a-zA-ZöüäÖÜÄß\(\)&; -]+})?/g,enricher:(o,c)=>{let m=o[0],d=o[1],p=Number(m.match(s)[0]),g=m.match(/\{.*\}/)?m.match(/\{.*\}/)[0].replace(/[\{\}]/g,""):r[d];return $(`${t[d]}${g} (${p})`)[0]}},{pattern:b.statusRegex.regex,enricher:(o,c)=>$(ai(o))[0]},{pattern:/@Info\[[a-zA-ZöüäÖÜÄ&; -\.0-9]+\]/g,enricher:async(o,c)=>{let m=o[0].match(/(?:\[)(.*?)(?=\])/)[0].slice(1),d=await fromUuid(m);if(!d||d.type!="information")return $('info')[0];if(!game.user.isGM)return $(`${game.i18n.localize("GM notes")}`)[0];let p={enrichedqs1:await TextEditor.enrichHTML(d.system.qs1,{async:!0}),enrichedqs2:await TextEditor.enrichHTML(d.system.qs2,{async:!0}),enrichedqs3:await TextEditor.enrichHTML(d.system.qs3,{async:!0}),enrichedqs4:await TextEditor.enrichHTML(d.system.qs4,{async:!0}),enrichedqs5:await TextEditor.enrichHTML(d.system.qs5,{async:!0}),enrichedqs6:await TextEditor.enrichHTML(d.system.qs6,{async:!0}),enrichedCrit:await TextEditor.enrichHTML(d.system.crit,{async:!0}),enrichedBotch:await TextEditor.enrichHTML(d.system.botch,{async:!0}),enrichedFail:await TextEditor.enrichHTML(d.system.fail,{async:!0})},g=await renderTemplate("systems/dsa5/templates/items/infopreview.html",{item:d,enriched:p});return $(g)[0]}},{pattern:/@EmbedItem\[[a-zA-ZöüäÖÜÄ&ë;'\(\)„“:,’ -\.0-9›‹âïßôñé\/]+\]({[a-zA-Z=]+})?/g,enricher:async(o,c)=>{let m=o[0].match(/(?:\[)(.*?)(?=\])/)[0].slice(1),d=await fromUuid(m);if(!d){let z=m.split("."),v=game.packs.get(z[0]+"."+z[1]);v&&(d=await v.getDocuments({name:z[2]}),d=d[0])}if(!d)return $('')[0];let p=o[0],g=p.match(/\{.*\}/)?p.match(/\{.*\}/)[0].replace(/[\{\}]/g,""):"",y={};if(g)for(let z of g.split(" ")){let v=z.split("=");v.length==2&&(y[v[0]]=v[1])}let h=`systems/dsa5/templates/items/browse/${d.type}.html`,w=await renderTemplate(h,{document:d,isGM:game.user.isGM,...await d.sheet.getData(),...y});return $(w)[0]}},{pattern:/@PostChat\[(.*?)\]/g,enricher:async(o,c)=>{let m=o[1];return $(`
    ${m}
    `)[0]}})}u(Ei,"setEnrichers");function ai(l){let t=l[0].split(" "),a=t.shift();t=t.join(" ");let s=b.statusEffects[b.statusRegex.effects.indexOf(t.toLowerCase())];return`${a} ${t}`}u(ai,"conditionsMatcher");var f=class{static async skillByName(e){let t=game.packs.get(game.i18n.lang=="de"?"dsa5.skills":"dsa5.skillsen");await t.getIndex();let a=t.index.find(s=>s.name===e);return await t.getDocument(a._id)}static async allSkills(){let e=game.i18n.lang=="de"?"dsa5.skills":"dsa5.skillsen";return await this.getCompendiumEntries(e,"skill")}static moduleEnabled(e){return game.modules.get(e)&&game.modules.get(e).active}static async allCombatSkills(){let e=game.i18n.lang=="de"?"dsa5.skills":"dsa5.skillsen";return await this.getCompendiumEntries(e,"combatskill")}static async getCompendiumEntries(e,t){let a=await game.packs.get(e);if(!a)return ui.notifications.error("No content found");let s=Array.isArray(t)?t:[t];return(await a.getDocuments()).filter(n=>s.includes(n.type)).map(n=>n.toObject())}static renderToggle(e){e.rendered?e._minimized?e.maximize():e.close():e.render(!0)}static calcTokenSize(e,t){let a=game.dsa5.config.tokenSizeCategories[e.system.status.size.value];if(a)if(a<1)mergeObject(t,{texture:{scaleX:a,scaleY:a},width:1,height:1});else{let s=Math.floor(a),i=Math.max(a/s,.25);mergeObject(t,{width:s,height:s,texture:{scaleX:i,scaleY:i}})}}static async allMoneyItems(){return(await this.getCompendiumEntries("dsa5.money","money")).map(t=>(t.system.quantity.value=0,t)).filter(t=>Object.values(b.moneyNames).map(a=>a.toLowerCase()).includes(t.name.toLowerCase())).sort((t,a)=>t.system.price.value>a.system.price.value?-1:1)}static async allSkillsList(){return(await this.allSkills()||[]).map(e=>e.name).sort((e,t)=>e.localeCompare(t))}static async allCombatSkillsList(e){return((await this.allCombatSkills()).filter(t=>t.system.weapontype.value==e)||[]).map(t=>t.name).sort((t,a)=>t.localeCompare(a))}static async callItemTransformationMacro(e,t,a,s={}){let i=e.split("."),n=game.packs.get(`${i[0]}.${i[1]}`);if(!n)return console.warn(`Pack ${n} not found`),{};let r=await n.getDocuments({name:i[2]}),o={};if(r.length){let c=Object.getPrototypeOf(async function(){}).constructor,m=new c("args","source","effect",r[0].command);try{s.result=o,await m.call(this,s,t,a)}catch(d){ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details"),console.error(d),o.error=!0}}else ui.notifications.error(game.i18n.format("DSAError.macroNotFound",{name:e}));return o}static isActiveGM(){let e=game.users.activeGM;return e||ui.notifications.warn(game.i18n.localize("DSAError.requiresGM")),e?.isSelf}static parseAbilityString(e){return{original:e.replace(/ (FP|SR|FW|SP)?[+-]?\d{1,2}$/,"").trim(),name:e.replace(/\((.+?)\)/g,"()").replace(/ (FP|SR|FW|SP)?[+-]?\d{1,2}$/,"").trim(),step:Number((e.match(/[+-]?\d{1,2}$/)||[1])[0]),special:(e.match(/\(([^()]+)\)/)||["",""])[1],type:e.match(/ (FP|SP)[+-]?\d{1,2}/)?"FP":e.match(/ (FW|SR)[+-]?\d{1,2}/)?"FW":"",bonus:e.match(/[-+]\d{1,2}$/)!=null}}static categoryLocalization(e){return game.i18n.localize(`TYPES.Item.${e}`)}static attributeLocalization(e){return game.i18n.localize(`CHAR.${e.toUpperCase()}`)}static attributeAbbrLocalization(e){return game.i18n.localize(`CHARAbbrev.${e.toUpperCase()}`)}static async callAsyncHooks(e,t){for(let a of b.asyncHooks[e])await a(...t)}static chatDataSetup(e,t,a,s){let i={user:game.user.id,rollMode:t||game.settings.get("core","rollMode"),content:e};return["gmroll","blindroll"].includes(i.rollMode)&&(i.whisper=ChatMessage.getWhisperRecipients("GM").map(n=>n.id)),i.rollMode==="blindroll"?i.blind=!0:i.rollMode==="selfroll"&&(i.whisper=[game.user]),a&&(i.speaker=ChatMessage.getSpeaker(),i.whisper=ChatMessage.getWhisperRecipients(a)),s&&(i.speaker=ChatMessage.getSpeaker(),i.whisper=s),i}static getSpeaker(e){let t=ChatMessage.getSpeakerActor(e);if(!t&&canvas.tokens){let a=canvas.tokens.get(e.token);a&&(t=a.actor)}if(!t){let a=game.scenes.get(e.scene);try{a&&(t=new Token(a.getEmbeddedDocument("Token",e.token))?.actor)}catch{}}return t}static fateAvailable(e,t){return t?game.settings.get("dsa5","groupschips").split("/").map(a=>Number(a))[0]>0:e.system.status.fatePoints.value>0}static _calculateAdvCost(e,t,a=1){return b.advancementCosts[t][Number(e)+a]}static async getFolderForType(e,t=null,a=null,s=0,i="",n=void 0){let r=await game.folders.contents.find(o=>o.name==a&&o.type==e&&o.folder?.id==t);return r||(r=await Folder.create({name:a,type:e,sorting:n||(e=="JournalEntry"?"a":"m"),color:i,sort:s,parent:t})),r}static toObjectIfPossible(e){return typeof e.toObject=="function"?e.toObject(!1):duplicate(e)}static async showArtwork({img:e,name:t,uuid:a,isOwner:s},i=!1){return new ImagePopout(e,{title:i?s?t:"-":t,shareable:!0,uuid:a}).render(!0)}static async findAnyItem(e){let t=[],a=e.map(i=>i.name),s=e.map(i=>i.type);for(let i of game.items.contents){let n=a.indexOf(i.name);if(n>=0&&s[n]==i.type&&(a.splice(n,1),s.splice(n,1),t.push(i.toObject())),a.length<=0)break}if(a.length>0){let i=/^dsa5-core/,n=Array.from(game.packs.keys()).sort((r,o)=>(i.test(r)&&i.test(o)&&r.localeCompare(o),i.test(o)?-1:i.test(r)?1:r.localeCompare(o)));for(let r of n){let o=game.packs.get(r);if(o.documentName=="Item"&&(game.user.isGM||!o.private)&&(await o.getDocuments({name__in:a,type__in:s}).then(c=>{for(let m of c){let d=a.indexOf(m.name);d>=0&&s[d]==m.type&&(a.splice(d,1),s.splice(d,1),t.push(m.toObject()))}}),a.length<=0))break}}return t}static replaceDies(e,t=!1){let a=/( |^)(\d{1,2})?[wWdD][0-9]+((\+|-)[0-9]+)?/g,s=t?"":"/r ";return e.replace(a,function(i){return` [[${s}${i.replace(/[DwW]/,"d")}]]`})}static escapeRegex(e){return(typeof e=="string"||e instanceof String?e:"").replace(/[-[/\]{}()*+?.,\\^$|#\s]/g,"\\$&")}static replaceConditions(e){return e&&e.replace(b.statusRegex.regex,t=>ai([t]))}static experienceDescription(e){let t=[2100,1700,1400,1200,1100,1e3],a=["EXP.legendary","EXP.brillant","EXP.masterful","EXP.competent","EXP.experienced","EXP.average"],s=0;for(let i of t){if(Number(e)>=Number(i))return a[s];s++}return"EXP.inexperienced"}static async emptyActor(e=12,t="Alrik"){Array.isArray(e)||(e=[e,e,e,e,e,e,e,e]);let a=await T.create({name:t,type:"npc",items:[],system:{status:{wounds:{value:50},fatePoints:{}},characteristics:{mu:{initial:e[0]},kl:{initial:e[1]},in:{initial:e[2]},ch:{initial:e[3]},ff:{initial:e[4]},ge:{initial:e[5]},ko:{initial:e[6]},kk:{initial:e[7]}}}},{temporary:!0,noHook:!0});return a.prepareData(),a}};u(f,"DSA5_Utility");var Ie=class{static async showDialog(e,t=!1){let[a]=await new Promise((s,i)=>{let n={Yes:{icon:'',label:game.i18n.localize("update"),callback:()=>{s([!0])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{s([!1])}}};t&&(n.migrateAll={icon:'',label:game.i18n.localize("replace"),callback:()=>{s([2])}}),new Dialog({title:game.i18n.localize("Migrakel.Migration"),content:e,default:"yes",buttons:n,close:()=>{s([!1])}}).render(!0)});return a}static async refreshStatusEffects(e){let t=[];for(let a of e.effects)a.origin&&t.push(a.id);await e.deleteEmbeddedDocuments("ActiveEffect",t)}static async updateVals(e,t,a){let s=game.dsa5.itemLibrary,i=[],n=[],r=new Map;if(await this.refreshStatusEffects(e),t({type:"equipment"})){let o=[],c=[];for(let d of e.items.filter(p=>p.type=="equipment"&&p.system.equipmentType.value=="bags")){let p=await s.findCompendiumItem(d.name,d.type);if(p.length>0){if(p=p.find(y=>y.name==d.name&&y.type==d.type),!p)continue;console.log(`MIGRATION - Updated ${d.name}`);let g=mergeObject(d.toObject(),a(p));c.push(g),o.push(d.id)}}let m=await e.createEmbeddedDocuments("Item",c);for(let d=0;dt(c)&&!(c.type=="equipment"&&c.system.equipmentType.value=="bags"))){let c=await s.findCompendiumItem(o.name,o.type);if(c.length>0){if(c=c.find(d=>d.name==o.name&&d.type==o.type),!c)continue;console.log(`MIGRATION - Updated ${o.name}`);let m=mergeObject(o.toObject(),a(c));m.system.parent_id&&r.has(m.system.parent_id)&&(m.system.parent_id=r.get(m.system.parent_id)),n.push(m),i.push(o.id)}}await e.createEmbeddedDocuments("Item",n),await e.deleteEmbeddedDocuments("Item",i),Ie.silent||ui.notifications.notify(game.i18n.localize("Migrakel.migrationDone"))}static async updateSpellsAndLiturgies(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.spells"),!0),s=u(i=>["spell","liturgy","ritual","ceremony","spellextension"].includes(i.type),"condition");if(a==2){let i=u(n=>{let r=n.toObject();return delete r.system.talentValue,r},"updator");await this.updateVals(e,s,i)}else if(a){let i=u(n=>{let r={effects:n.effects.toObject()};return n.type!="spellextension"&&(r.system={effectFormula:{value:n.system.effectFormula.value}}),r},"updator");await this.updateVals(e,s,i)}return a}static async updateSpecialAbilities(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.abilities"));if(a){let s=u(n=>{let r={system:{effect:{value:n.system.effect.value}},effects:n.effects.toObject()};return n.type=="specialability"&&(mergeObject(r,{system:{category:{sub:n.system.category.sub||0},list:{value:n.system.list.value},effect:{value2:getProperty(n,"system.effect.value2")||"",value3:getProperty(n,"system.effect.value3")||""}}}),n.system.category.value=="staff"&&mergeObject(r,{system:{feature:getProperty(n,"system.feature")||"",AsPCost:getProperty(n,"system.AsPCost")||"",volume:Number(getProperty(n,"system.volume"))||0,artifact:getProperty(n,"system.artifact")||"",permanentEffects:getProperty(n,"system.permanentEffects")||!1}})),this.updateMacro(r,n),r},"updator"),i=u(n=>["specialability","advantage","disadvantage","trait"].includes(n.type),"condition");await this.updateVals(e,i,s)}return a}static async updateCombatskills(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.cskills"));if(a){let s=u(n=>({effects:n.effects.toObject()}),"updator"),i=u(n=>["combatskill"].includes(n.type),"condition");await this.updateVals(e,i,s)}return a}static async updateSkills(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.skills"));if(a){let s=u(n=>["skill"].includes(n.type),"condition"),i=u(n=>({img:n.img,effects:n.effects.toObject()}),"updator");await this.updateVals(e,s,i)}return a}static updateMacro(e,t){let a=t.getFlag("dsa5","onUseEffect");a&&mergeObject(e,{flags:{dsa5:{onUseEffect:a}}})}static async updateGear(e,t=void 0){let a=t??await this.showDialog(game.i18n.localize("Migrakel.gear"));if(a){let s=u(n=>["meleeweapon","armor","rangeweapon","equipment","poison","consumable","ammunition"].includes(n.type),"condition"),i=u(n=>{let r={img:n.img,effects:n.effects.toObject()};return["poison","consumable"].includes(n.type)||mergeObject(r,{system:{effect:{value:n.system.effect.value}}}),["armor"].includes(n.type)&&mergeObject(r,{system:{subcategory:n.system.subcategory}}),["meleeweapon","rangeweapon","armor"].includes(n.type)&&mergeObject(r,{system:{structure:{max:n.system.structure.max,value:n.system.structure.value}}}),this.updateMacro(r,n),r},"updator");await this.updateVals(e,s,i)}return a}};u(Ie,"Migrakel");var Ye=class extends Dialog{constructor(e,t){super(t),this.actor=e,this.lock=!1}static async buildDialog(e){let t=await renderTemplate("systems/dsa5/templates/actors/parts/actorConfig.html",{actor:e});new Ye(e,{title:game.i18n.localize("SHEET.actorConfig"),content:t,default:"Save",buttons:{}}).render(!0)}async updateWrapper(e,t){if(this.lock)return;u(async()=>{this.lock=!0,$(t.currentTarget).prepend(''),await Ie[e](this.actor),$(t.currentTarget).find("i").remove(),this.lock=!1},"upd")()}activateListeners(e){super.activateListeners(e),e.find(".updateSpells").click(async t=>this.updateWrapper("updateSpellsAndLiturgies",t)),e.find(".updateAbilities").click(async t=>this.updateWrapper("updateSpecialAbilities",t)),e.find(".updatecSkills").click(async t=>this.updateWrapper("updateCombatskills",t)),e.find(".updateSkills").click(async t=>this.updateWrapper("updateSkills",t)),e.find(".updateGear").click(async t=>this.updateWrapper("updateGear",t))}};u(Ye,"DialogActorConfig");function mt(l,e="img"){!game.user.isGM||l.find(e).each(function(t,a){a.setAttribute("draggable",!0),a.addEventListener("dragstart",s=>Ki(s))})}u(mt,"bindImgToCanvasDragStart");var Ki=u(l=>{canvas.tiles.activate();let e=l.currentTarget.src,t=l.currentTarget,a=canvas.dimensions.sceneHeight/t.naturalHeight,s=canvas.dimensions.sceneWidth/t.naturalWidth,i=Math.min(1,s,a),n=Math.round(canvas.dimensions.size/i),r={type:"Tile",texture:{src:e},tileSize:n};l.dataTransfer.setData("text/plain",JSON.stringify(r));let o=t.naturalWidth*i*canvas.stage.scale.x,c=t.naturalHeight*i*canvas.stage.scale.y,m=DragDrop.createDragImage(t,o,c);l.dataTransfer.setDragImage(m,o/2,c/2)},"dragTileImg");var At=class extends FormApplication{constructor(e,t,a){super(),this.editfield=t,this.actorId=e,this.fieldname=a;let s=game.actors.get(this.actorId);this.object={fieldContent:getProperty(s,this.editfield)}}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{resizable:!0,width:600,height:600}),e}isEditable(){return!0}get title(){return`${game.actors.get(this.actorId).name} - ${game.i18n.localize(this.fieldname)}`}async _updateObject(e,t){game.socket.emit("system.dsa5",{type:"updateKeepField",payload:{actorId:this.actorId,field:this.editfield,updateData:t.fieldContent}})}async getData(e){let t=super.getData(e);return mergeObject(t,{fieldContent:this.object.fieldContent}),t}get template(){return"systems/dsa5/templates/dialog/foreignfieldeditor.html"}activateListeners(e){super.activateListeners(e)}};u(At,"ForeignFieldEditor");var pe=class extends Application{static get defaultOptions(){let e=super.defaultOptions;return e.template="systems/dsa5/templates/actors/merchant/merchant-trade.html",e.width=900,e.resizable=!0,e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"main"}],e.title=game.i18n.localize("MERCHANT.exchange"),e.classes.push("noscrollWizard"),e}constructor(e,t,a={}){super(),this.tradeData={offered:{},offer:{},id:a.id||randomID(),sourceId:e,targetId:t,offerAccepted:!1,offeredAccepted:!1}}async startTrade(){game.socket.emit("system.dsa5",{type:"startTrade",payload:{sourceId:this.tradeData.sourceId,targetId:this.tradeData.targetId,id:this.tradeData.id}}),this.render(!0)}_filterGear(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.element).find(".inventory .item");a.removeClass("filterHide"),a.filter(function(){return $(this).find("a.item-edit").text().toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide")}}async getData(){let e=await super.getData(),t=f.getSpeaker(this.tradeData.sourceId),a=t.prepareItems({details:[]});a.inventory.money={items:a.money.coins.map(s=>(s.name=game.i18n.localize(s.name),s)),show:!0,dataType:"money"};for(let s of Object.values(a.inventory))for(let i of s.items)this.tradeData.offer[i._id]&&(i.system.quantity.value-=this.tradeData.offer[i._id].system.quantity.value);return mergeObject(e,{tradeData:this.tradeData,actor:f.getSpeaker(this.tradeData.targetId),tradeFriend:t,inventory:a}),e}static findTradeApp(e){for(let t of Object.values(ui.windows))if(t instanceof this&&t?.tradeData?.id===e)return t;return!1}async close(e={}){return e.skipSocket||game.socket.emit("system.dsa5",{type:"tradeCanceled",payload:{id:this.tradeData.id}}),super.close(e)}activateListeners(e){super.activateListeners(e),e.find(".trade").click(s=>this._offerItem(s));let t=u(s=>this._filterGear($(s.currentTarget)),"filterGear");e.find(".item-edit").click(s=>this._editItem(s,this.tradeData.sourceId)),e.find(".item-external-edit").click(s=>this._editItem(s,this.tradeData.targetId)),e.find(".acceptTrade").click(s=>this.acceptTrade(s));let a=e.find(".gearSearch");a.keyup(s=>t(s)),a[0]&&a[0].addEventListener("search",t,!1)}_editItem(e,t){f.getSpeaker(t).items.get(e.currentTarget.dataset.itemId).sheet.render(!0)}_offerItem(e){if(this.tradeData.offerAccepted)return;let t=e.currentTarget.dataset.itemId,s=f.getSpeaker(this.tradeData.sourceId).items.get(t),i=e.ctrlKey?10:1,n=e.currentTarget.dataset.stopTrade,r=n?this.tradeData.offer[t].system.quantity.value:s.system.quantity.value;s&&(n?(this.tradeData.offer[t].system.quantity.value-=Math.min(i,r),this.tradeData.offer[t].system.quantity.value<=0&&delete this.tradeData.offer[t],this.offerChanged(),this.render()):(this.tradeData.offer[t]?r-=this.tradeData.offer[t].system.quantity.value:(this.tradeData.offer[t]=s.toObject(),this.tradeData.offer[t].system.quantity.value=0),r>0&&(this.tradeData.offer[t].system.quantity.value+=Math.min(i,r),this.offerChanged(),this.render())),K.playMoneySound())}async offerChanged(){game.socket.emit("system.dsa5",{type:"receiveOfferedItems",payload:{id:this.tradeData.id,trader:this.tradeData.sourceId,offered:this.tradeData.offer}})}static receiveOfferedItems(e){let t=this.findTradeApp(e.payload.id);t&&(e.payload.trader==t.tradeData.sourceId?(t.tradeData.offer=e.payload.offered,t.tradeData.offerAccepted=!1):(t.tradeData.offered=e.payload.offered,t.tradeData.offeredAccepted=!1),t.render())}static isGMTrade(e){return game.user.isGM&&!e.hasPlayerOwner}static isPlayerTrade(e){return!game.user.isGM&&e.isOwner}static socketStartTrade(e){let t=f.getSpeaker(e.payload.targetId);(this.isGMTrade(t)||this.isPlayerTrade(t))&&new pe(e.payload.targetId,e.payload.sourceId,{id:e.payload.id}).render(!0)}acceptTrade(){this.tradeData.offerAccepted=!this.tradeData.offerAccepted,this.render(!0),game.socket.emit("system.dsa5",{type:"acceptTrade",payload:{id:this.tradeData.id,accepted:this.tradeData.offerAccepted}})}static tradeWasAccepted(e){let t=this.findTradeApp(e.payload.id);t&&(t.tradeData.offeredAccepted=e.payload.accepted,t.tradeData.offerAccepted&&t.tradeData.offeredAccepted?(t.finishTrade(),K.playMoneySound()):t.render())}async finishTrade(){f.isActiveGM()&&await pe.updateData(this.tradeData),game.socket.emit("system.dsa5",{type:"tradeFinished",payload:{id:this.tradeData.id,tradeData:this.tradeData}}),this.close({skipSocket:!0}),K.playMoneySound()}static async updateData(e){let t=f.getSpeaker(e.sourceId),a=f.getSpeaker(e.targetId);await this.modifyActor(t,e.offer,e.offered),await this.modifyActor(a,e.offered,e.offer)}static async modifyActor(e,t,a){let s=[],i=[];for(let n of Object.keys(t)){let r=e.items.get(n);r&&(r.system.quantity.value<=t[n].system.quantity.value&&r.type!="money"?s.push(n):i.push({_id:n,"system.quantity.value":r.system.quantity.value-t[n].system.quantity.value}))}await e.deleteEmbeddedDocuments("Item",s,{render:!1}),await e.updateEmbeddedDocuments("Item",i,{render:!1});for(let n of Object.values(a))await e.sheet._manageDragItems(n,n.type)}static tradeWasFinished(e){let t=this.findTradeApp(e.payload.id);f.isActiveGM()&&pe.updateData(e.payload.tradeData),t&&t.close({skipSocket:!0})}static tradeWasCanceled(e){let t=this.findTradeApp(e.payload.id);t&&t.close({skipSocket:!0})}static socketListeners(e){switch(e.type){case"receiveOfferedItems":return this.receiveOfferedItems(e),!0;case"startTrade":return this.socketStartTrade(e),!0;case"acceptTrade":return this.tradeWasAccepted(e),!0;case"tradeCanceled":return this.tradeWasCanceled(e),!0;case"tradeFinished":return this.tradeWasFinished(e),!0}}};u(pe,"Trade");var Yt=class extends Application{constructor(e,t){super(t),this.actorId=C.buildSpeaker(e,e.token?.id)}async getData(e){let t=await super.getData(e);return t.actors=game.actors.filter(a=>a.hasPlayerOwner&&a.id!=this.actorId.actor),t}static get defaultOptions(){let e=super.defaultOptions;return e.template="systems/dsa5/templates/actors/merchant/merchant-tradeoptions.html",e.resizable=!0,e.title=game.i18n.localize("MERCHANT.exchange"),e}_startTrade(e){let t=game.actors.get(e.currentTarget.dataset.id);new pe(this.actorId,C.buildSpeaker(t,t.token?.id)).startTrade(),this.close()}activateListeners(e){super.activateListeners(e),e.find(".startTrade").on("dblclick",t=>this._startTrade(t))}};u(Yt,"TradeOptions");var re=class extends Application{static registerTokenHotbar(){game.dsa5.apps.tokenHotbar||(game.dsa5.apps.tokenHotbar=new re,game.dsa5.apps.tokenHotbar.updateDSA5Hotbar(),game.settings.get("dsa5","disableTokenhotbar")||game.dsa5.apps.tokenHotbar.render(!0),Hooks.call("dsa5TokenHotbarReady",game.dsa5.apps.tokenHotbar))}constructor(e){if(super(e),this.searching="",re.combatSkills=["selfControl","featOfStrength","bodyControl","perception","loyalty"].map(a=>game.i18n.localize(`LocalizedIDs.${a}`)),re.defaultSkills=new Set([game.i18n.localize("LocalizedIDs.perception")]),game.user.isGM){this.callbackFunctions={};let a=game.settings.get("dsa5","enableMasterTokenFunctions");this.gmItems=[{name:"gmMenu",disabled:a.masterMenu,icon:"systems/dsa5/icons/categories/DSA-Auge.webp",id:"masterMenu",cssClass:"gm",abbrev:"",subfunction:"gm"},{name:"MASTER.randomPlayer",disabled:a.randomVictim,iconClass:"fa fa-dice-six",id:"randomVictim",cssClass:"gm",abbrev:"",subfunction:"gm"},{name:"TT.tokenhotbarMoney",disabled:a.payMoney,icon:"systems/dsa5/icons/money-D.webp",id:"payMoney",cssClass:"gm",abbrev:"",subfunction:"gm"}]}let t=u(a=>{let s=a.parent?a.parent.id:void 0;s&&re.hookUpdate(s)},"parentUpdate");Hooks.on("controlToken",(a,s)=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}),Hooks.on("updateActor",(a,s)=>{re.hookUpdate(a.id)}),Hooks.on("updateToken",(a,s,i)=>{!game.dsa5.apps.tokenHotbar||s._id==getProperty(game.dsa5.apps.tokenHotbar,"actor.prototypeToken.id")&&game.dsa5.apps.tokenHotbar.updateDSA5Hotbar()}),Hooks.on("updateOwnedItem",(a,s)=>{re.hookUpdate(a.data.id)}),Hooks.on("createOwnedItem",(a,s)=>{re.hookUpdate(a.data.id)}),Hooks.on("deleteOwnedItem",(a,s)=>{re.hookUpdate(a.data.id)}),Hooks.on("updateItem",(a,s)=>{t(a)}),Hooks.on("createItem",(a,s)=>{t(a)}),Hooks.on("deleteItem",(a,s)=>{t(a)}),Hooks.on("deleteActiveEffect",(a,s)=>{t(a)}),Hooks.on("updateActiveEffect",(a,s)=>{t(a)}),Hooks.on("createActiveEffect",(a,s)=>{t(a)}),Hooks.on("canvasInit",()=>{!this.rendered||this.render()})}registerMasterFunction(e,t){let a=game.settings.get("dsa5","enableMasterTokenFunctions");e.disabled=a[e.id],this.gmItems.push(e),this.callbackFunctions[e.id]=t}async prepareSkills(){let e=await f.allSkills();return this.skills=e.map(t=>({name:t.name,icon:t.img,id:t.name,cssClass:"skillgm",addClass:t.system.group.value,abbrev:t.name[0],subfunction:"skillgm"})),this.skills=this.skills.sort((t,a)=>t.addClass.localeCompare(a.addClass)||t.name.localeCompare(a.name)),this.skills}static hookUpdate(e){e==game.dsa5.apps.tokenHotbar?.actor?.id?game.dsa5.apps.tokenHotbar.updateDSA5Hotbar():ui.hotbar.token?.actor?.id==e&&ui.hotbar.updateDSA5Hotbar()}resetPosition(){let e=$("#hotbar").first().position(),t=game.settings.get("dsa5","tokenhotbarSize");this.position.left=e.left+8,this.position.top=e.top-t-25}static get defaultOptions(){let e=super.defaultOptions,t=$("#hotbar").first().position(),a=game.settings.get("dsa5","tokenhotbarSize"),s=game.settings.get("dsa5","tokenhotbarPosition");return mergeObject(e,{classes:e.classes.concat(["dsa5","tokenQuickHot"]),itemWidth:a,resizable:!1,height:a+45,zIndex:61,left:t.left+8,top:t.top-a-25,template:"systems/dsa5/templates/status/tokenHotbar.html",title:"TokenHotbar"}),mergeObject(e,s),e}async _onWheelResize(e){let t=game.settings.get("dsa5","tokenhotbarSize");e.originalEvent.deltaY>0?t=Math.min(100,t+5):t=Math.max(15,t-5),await game.settings.set("dsa5","tokenhotbarSize",t),await this.render(!0)}async _cycleLayout(e){if(e.button==2){let t=game.settings.get("dsa5","tokenhotbarLayout")+1;t==4&&(t=0),await game.settings.set("dsa5","tokenhotbarLayout",t),await this.render(!0)}}changeDarkness(e){let t=Number(e.currentTarget.value);canvas.scene&&canvas.scene.update({darkness:t},{animateDarkness:3e3}),de(t)}activateListeners(e){super.activateListeners(e);let t=e.find(".dragHandler");t[0]&&new Draggable(this,e,t[0],this.options.resizable),t.on("wheel",async i=>(i.stopPropagation(),i.preventDefault(),await this._onWheelResize(i),!1)),e.find(".itdarkness input").change(i=>this.changeDarkness(i));let a=this,s=u(function(i){return a.filterButtons(i),!1},"fn");e.find(".filterable").hover(function(){$(document).on("keydown",s)},function(){$(document).off("keydown",s)}),e.find(".quantity-click").mousedown(i=>P.quantityClick(i)),e.on("mousedown","li",async i=>(i.stopPropagation(),await this.executeQuickButton(i),!1)),e.on("mouseenter","li.primary",i=>{let n=i.currentTarget.dataset.category;this.category=n,setTimeout(()=>{e.find(".secondary").removeClass("shown"),n==this.category&&e.find(`.secondary[data-category="${n}"]`).addClass("shown")},700)}),e.on("mouseleave","li.primary",i=>{let n=i.currentTarget.dataset.category;this.category=void 0,setTimeout(()=>{n!=this.category&&(a.searching="",$(i.currentTarget).find(".secondary").removeClass("dsahidden"),e.find(`.secondary[data-category="${n}"]`).removeClass("shown"))},50)})}async handleEffect(e,t,a,s){let i=t.effects.get(a),n=[...i.statuses][0];e.button==0?n?await t.addCondition(n,1,!1,!1):i.sheet.render(!0):e.button==2&&(n?await t.removeCondition(n,1,!1):await t.sheet._deleteActiveEffect(a))}async handleGMRoll(e){let t=e.currentTarget.dataset.id,a=Math.round($(e.currentTarget).closest(".tokenHotbarInner,#hotbar").find(".modifierVal").val());e.ctrlKey?game.dsa5.apps.DSA5ChatListeners.check3D20(void 0,t,{modifier:a}):e.button==2?game.dsa5.macro.requestGC(t,a,{maxRolls:7}):game.dsa5.macro.requestRoll(t,a)}async handleSkillRoll(e,t,a,s){let i={};if(e.button==2&&(i.rollMode="blindroll"),a=="rideLoyaltyID")H.rollLoyalty(t,i);else if(a=="attackWeaponless")t.setupWeaponless("attack",i,s).then(n=>{t.basicTest(n)});else{let n=t.items.get(a);if(n){if(e.originalEvent.ctrlKey)return n.sheet.render(!0);switch(n.type){case"meleeweapon":case"rangeweapon":e.originalEvent.altKey?n.update({"system.worn.value":!1}):n.system.worn.value?t.setupWeapon(n,"attack",i,s).then(r=>{t.basicTest(r)}):t.exclusiveEquipWeapon(n.id,e.button==2);break;case"trait":t.setupWeapon(n,"attack",i,s).then(r=>{t.basicTest(r)});break;case"liturgy":case"spell":t.setupSpell(n,i,s).then(r=>{t.basicTest(r)});break;case"skill":t.setupSkill(n,i,s).then(r=>{t.basicTest(r)});break;case"consumable":new Dialog({title:game.i18n.localize("SHEET.ConsumeItem")+": "+n.name,content:game.i18n.localize("SHEET.ConsumeItem")+": "+n.name,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async()=>{await n.setupEffect(null,{},s),await this.updateDSA5Hotbar()}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0);break}}}}async handleTradeStart(e,t,a,s){if(!game.user.targets.size)return ui.notifications.error(game.i18n.localize("DIALOG.noTarget"));for(let i of game.user.targets)i.actor&&new pe(C.buildSpeaker(t,s),C.buildSpeaker(i.actor,i.id)).startTrade()}async handleOnUse(e,t,a,s){let i=t.items.get(a);await new X(i).executeOnUseEffect()}async handleGM(e,t,a,s){switch(a){case"masterMenu":f.renderToggle(game.dsa5.apps.gameMasterMenu);break;case"payMoney":this.payMoney(e);break;case"randomVictim":this.handleGMRandomVictim(e);break;default:a in this.callbackFunctions&&this.callbackFunctions[a](e,t,a,s)}}payMoney(e){let t=`${$(e.currentTarget).closest(".tokenHotbarInner,#hotbar").find(".modifierVal").val()}`;e.button==2?B.createGetPaidChatMessage(t):B.createPayChatMessage(t)}async handleGMRandomVictim(e){let t=await game.dsa5.apps.gameMasterMenu.rollRandomPlayer(e.button==2),a=game.actors.get(t);if(a){let s=await f.showArtwork(a);e.originalEvent.ctrlKey||setTimeout(()=>{s.close()},2e3)}}async handleSharedEffect(e){for(let t of canvas.tokens.controlled){let a=t.actor,s=t.id,i=a.effects.find(n=>n.name==e.currentTarget.dataset.name)?.id;await this.handleEffect(e,a,i,s)}}async executeQuickButton(e){let t=canvas.tokens.controlled[0]?.actor,a=canvas.tokens.controlled[0]?.id,s=e.currentTarget.dataset.id;switch(e.currentTarget.dataset.subfunction){case"trade":this.handleTradeStart(e,t,s,a);break;case"addEffect":Ee.showDialog();break;case"effect":this.handleEffect(e,t,s,a);break;case"sharedEffect":this.handleSharedEffect(e);break;case"onUse":this.handleOnUse(e,t,s,a);break;case"gm":this.handleGM(e,t,s,a);break;case"none":case"darkness":break;case"skillgm":this.handleGMRoll(e);break;default:this.handleSkillRoll(e,t,s,a)}}subWidth(e,t,a=7){return`style="width:${Math.ceil(e.length/a)*200}px"`}async getData(){let e=await super.getData(),t=this.actor,a={attacks:[],spells:[],default:[],skills:[],functions:[],gm:[]},s,i,n=[],r=[],o=[],c=game.settings.get("dsa5","tokenhotbarLayout"),m=c%2,d=re.defaultOptions.itemWidth,p=!1;if(t){let y=[],h=[],w=H.isRiding(t),z=game.i18n.localize("LocalizedIDs.riding");if(o=await this._effectEntries(t),game.combat){let v=t.items.filter(x=>x.type=="combatskill").map(x=>T._calculateCombatSkillValues(x.toObject(),t.system)),S=this._brawlEntry(v);S&&a.attacks.push(S);for(let x of t.items)x.type=="skill"&&(re.combatSkills.some(F=>x.name.startsWith(F))||w&&z==x.name)&&a.default.push(this._skillEntry(x,"skill filterable")),x.type=="trait"&&re.traitTypes.has(x.system.traitType.value)?a.attacks.push(this._traitEntry(x)):re.attackTypes.has(x.type)&&x.system.worn.value==!0?a.attacks.push(this._combatEntry(x,v,t)):re.spellTypes.has(x.type)?x.system.effectFormula.value?a.spells.push(this._skillEntry(x,"spell filterable")):h.push(this._skillEntry(x,"spell filterable")):x.type=="skill"?y.push(this._skillEntry(x,"skill filterable",{addClass:x.system.group.value})):x.type=="consumable"&&n.push(this._actionEntry(x,"consumable",{abbrev:x.system.quantity.value})),x.getFlag("dsa5","onUseEffect")&&r.push(this._actionEntry(x,"onUse",{subfunction:"onUse"}));if(s=n.pop(),w){let x=this._ridingEntry(t);x&&a.default.push(x)}}else{let v=[];for(let S of t.items){if(S.type=="skill"&&(re.defaultSkills.has(S.name)||w&&z==S.name)&&a.default.push(this._skillEntry(S,"skill filterable")),S.type=="skill"){let x=this._skillEntry(S,"skill filterable",{addClass:S.system.group.value});S.system.talentValue.value>0&&v.push(x),y.push(x)}else re.spellTypes.has(S.type)&&(S.system.effectFormula.value?a.spells.push(this._actionEntry(S,"spell filterable")):h.push(this._actionEntry(S,"spell filterable")));S.getFlag("dsa5","onUseEffect")&&r.push(this._actionEntry(S,"onUse",{subfunction:"onUse"}))}a.skills.push(...v.sort((S,x)=>x.tw-S.tw).slice(0,5))}i=r.pop(),a.functions=this._functionEntries(),a.spells.length==0&&h.length>0&&a.spells.push(h.pop()),a.spells.length>0&&h.length>0&&(a.spells[0].more=h.sort((v,S)=>v.name.localeCompare(S.name)),a.spells[0].subwidth=this.subWidth(h,d)),a.default.length>0&&y.length>0&&(a.default[0].more=y.sort((v,S)=>v.addClass.localeCompare(S.addClass)||v.name.localeCompare(S.name)),a.default[0].subwidth=this.subWidth(y,d,20)),s&&(n.length>0&&(s.more=n,s.subwidth=this.subWidth(n,d)),a.consumables=[s]),i&&(r.length>0&&(i.more=r,i.subwidth=this.subWidth(r,d)),a.onUsages=[i])}else if(game.user.isGM&&!game.settings.get("dsa5","disableTokenhotbarMaster")){p=!0;let y=this.skills||await this.prepareSkills();a.gm=this._gmEntries().concat([{name:"TT.tokenhotbarSkill",id:"skillgm",icon:"systems/dsa5/icons/categories/Skill.webp",cssClass:"skillgm filterable",abbrev:"",subfunction:"none",more:y,subwidth:this.subWidth(y,d,20)}])}if(this.showEffects){let y=game.i18n.localize("CONDITION.add"),h={name:"CONDITION.add",id:"",icon:"icons/svg/aura.svg",cssClass:"effect",abbrev:y[0],subfunction:"addEffect"};if(o.length>0)h.more=o,h.subwidth=this.subWidth(o,d);else if(canvas.tokens.controlled.length>1){let w=await this.tokenHotbar._effectEntries(canvas.tokens.controlled[0].actor,{subfunction:"sharedEffect"});for(let z of canvas.tokens.controlled){let v=(await z.actor.actorEffects()).map(S=>S.name);w=w.filter(S=>v.includes(S.name))}h.more=w,h.subwidth=this.subWidth(w,d)}a.effects=[h]}let g=Object.keys(a).reduce((y,h)=>y+a[h].length,0)+(p?3:0);return m?(this.position.width=d,this.position.height=d*g+14):(this.position.width=d*g+14,this.position.height=d),mergeObject(e,{items:a,itemWidth:d,direction:c,count:g,gmMode:p,darkness:canvas?.scene?.darkness||0,opacity:game.settings.get("dsa5","tokenhotbaropacity")}),e}_functionEntries(){let e=game.i18n.localize("MERCHANT.exchangeWithTarget");return[{name:e,id:"trade",cssClass:"function",abbrev:e[0],iconClass:"fas fa-coins",subfunction:"trade"}]}_brawlEntry(e){let t=e.find(a=>a.name==game.i18n.localize("LocalizedIDs.wrestle"));if(t)return{name:game.i18n.localize("attackWeaponless"),id:"attackWeaponless",icon:"systems/dsa5/icons/categories/attack_weaponless.webp",attack:t.system.attack.value,damage:"1d6",cssClass:"zbrawl"}}_ridingEntry(e){if(isRiding){let t=H.getHorse(e);if(t){let a=H.getLoyaltyFromHorse(t);if(a)return{name:`${a.name} (${a.system.talentValue.value})`,id:"rideLoyaltyID",icon:a.img,cssClass:"skill",abbrev:a.name[0]}}}}_gmEntries(){return this.gmItems.filter(e=>!e.disabled)}_actionEntry(e,t,a={}){return{name:e.name,id:e.id,icon:e.img,cssClass:t,abbrev:e.name[0],...a}}_skillEntry(e,t,a={}){let s=e.system?.talentValue.value;return{name:s?`${e.name} (${s})`:e.name,id:e.id,icon:e.img,cssClass:t,addClass:e.system?.group?.value,abbrev:e.name[0],tw:s,...a}}_traitEntry(e){let t=T._parseDmg(e.toObject());return{name:e.name,id:e.id,icon:e.img,cssClass:"weapon",abbrev:e.name[0],attack:e.system.at.value,damage:t.damagedie,dadd:t.damageAdd}}_combatEntry(e,t,a,s=[]){let i=e.type=="meleeweapon"?T._prepareMeleeWeapon(e.toObject(),t,a):T._prepareRangeWeapon(e.toObject(),[],t,a);return{name:e.name,id:e.id,icon:e.img,cssClass:"weapon",abbrev:e.name[0],attack:i.attack,damage:i.damagedie,dadd:i.damageAdd,...s}}async _effectEntries(e,t={}){return(await e.actorEffects()).map(a=>{let s=a.getFlag("dsa5","value")||"";return{name:s?`${a.name} (${s})`:a.name,id:a.id,icon:a.icon,cssClass:"effect",abbrev:`${a.name[0]} ${s}`,subfunction:"effect",indicator:s,...t}})}filterButtons(e){switch(e.which){case 8:this.searching=this.searching.slice(0,-1);break;default:if(!e.key.match(/[a-zA-Z0-9öäüÖÄÜ]/))return;this.searching+=e.key}e.preventDefault(),e.stopPropagation();let t=this.searching.toLowerCase();de(t);let a=$(e.currentTarget).find(".subbuttons li");a.find(".dsahidden").removeClass("dsahidden"),a.filter(function(){return $(this).find("label").text().toLowerCase().trim().indexOf(t)==-1}).addClass("dsahidden")}async render(e,t={}){let a=await super.render(e,t);return this._element&&this._element.css({zIndex:61}),a}setPosition({left:e,top:t,width:a,height:s,scale:i}={}){let n=super.setPosition({left:e,top:t,width:a,height:s,scale:i}),r=this.element[0];if(!r.style.width||a){let o=a||r.offsetWidth,c=r.style.maxWidth||window.innerWidth;n.width=a=Math.clamped(o,0,c),r.style.width=a+"px",a+n.left>window.innerWidth&&(e=n.left)}return game.settings.set("dsa5","tokenhotbarPosition",{left:n.left,top:n.top}),n}async updateDSA5Hotbar(){if(ui.hotbar.updateDSA5Hotbar(),game.settings.get("dsa5","disableTokenhotbar"))return;let e=canvas.tokens.controlled;if(this.actor=void 0,this.showEffects=!1,e.length===1){let t=e[0].actor;t&&t.isOwner&&(this.actor=t)}e.length>=1&&(this.showEffects=!0),await this.render(!0,{focus:!1})}},Se=re;u(Se,"TokenHotbar2"),L(Se,"attackTypes",new Set(["meleeweapon","rangeweapon"])),L(Se,"traitTypes",new Set(["meleeAttack","rangeAttack"])),L(Se,"spellTypes",new Set(["liturgy","spell"]));var Ee=class extends Dialog{static async showDialog(){let e=duplicate(CONFIG.statusEffects).map(a=>({name:game.i18n.localize(a.name),icon:a.icon,description:game.i18n.localize(a.description),id:a.id})).sort((a,s)=>a.name.localeCompare(s.name)),t=new Ee({title:game.i18n.localize("CONDITION.add"),content:await renderTemplate("systems/dsa5/templates/dialog/addstatusdialog.html",{effects:e}),buttons:{}});t.position.height=Math.ceil(e.length/3)*36+170,t.render(!0)}activateListeners(e){super.activateListeners(e),e.find(".reactClick").mouseenter(s=>{if(s.currentTarget.getElementsByClassName("hovermenu").length==0){let i=document.createElement("div");i.classList.add("hovermenu"),i.style.cssText="font-size: var(--font-size-20);";let n=document.createElement("i");n.classList.add("fas","fa-cogs"),n.title=game.i18n.localize("ActiveEffects.custom"),n.addEventListener("click",async r=>this.configureEffect(r),!1),i.appendChild(n),s.currentTarget.appendChild(i)}}),e.find(".reactClick").mouseleave(s=>{let i=s.toElement||s.relatedTarget;i.parentNode==this||i==this||s.currentTarget.querySelectorAll(".hovermenu").forEach(n=>n.remove())}),e.find(".quantity-click").mousedown(s=>P.quantityClick(s)),e.find(".reactClick").click(s=>this.addEffect(s.currentTarget.dataset.value));let t=u(s=>this._filterConditions($(s.currentTarget),e),"filterConditions"),a=e.find(".conditionSearch");a.keyup(s=>this._filterConditions($(s.currentTarget),e)),a[0]&&a[0].addEventListener("search",t,!1)}_filterConditions(e,t){if(e.val()!=null){let a=e.val().toLowerCase().trim(),s=t.find(".filterable");t.find(".filterHide").removeClass("filterHide"),s.filter(function(){return $(this).find("span").text().toLowerCase().trim().indexOf(a)==-1}).addClass("filterHide")}}static async modifyEffectDialog(e,t){new Ee({title:game.i18n.localize("CONDITION."+e),content:await renderTemplate("systems/dsa5/templates/dialog/configurestatusdialog.html"),default:"add",buttons:{add:{icon:'',label:game.i18n.localize("CONDITION.add"),callback:async a=>{let s={},i=a.find("[name=unit]:checked").val()=="seconds"?Math.round(a.find(".duration").val()/5):a.find(".duration").val(),n=a.find(".effectname").val();i>0&&mergeObject(s,P._buildDuration(i)),n&&(s.name=n),await t(e,s)}}}}).render(!0,{width:400,resizable:!1,classes:["dsa5","dialog"]})}async configureEffect(e){e.stopPropagation();let a=$(e.currentTarget).closest(".reactClick").attr("data-value");this.close(),Ee.modifyEffectDialog(a,async(s,i)=>this.addEffect(s,i))}async addEffect(e,t={}){for(let a of canvas.tokens.controlled)await a.actor.addTimedCondition(e,1,!1,!1,t);this.close()}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:["dsa5","tokenStatusEffects"],width:700,resizable:!0}),e}};u(Ee,"AddEffectDialog");var si=u(async(l,e,t,a)=>{if(game.user.isGM){let s=await game.dsa5.apps.DSA5_Utility.allMoneyItems(),i=await f.getFolderForType("Actor",null,"Dropped Items"),r=game.users.filter(p=>!p.isGM).map(p=>p.id).reduce((p,g)=>(p[g]=1,p),{default:0}),o=e.toObject();o.system.quantity.value=a,P.obfuscateDropData(o,t.tabsinvisible),getProperty(o,"system.worn.value")&&(o.system.worn.value=!1);let c={type:"npc",name:e.name,img:e.img,prototypeToken:{img:e.img,width:.4,height:.4},ownership:r,items:[...s,o],flags:{core:{sheetClass:"dsa5.MerchantSheetDSA5"}},folder:i,system:{merchant:{merchantType:"loot",temporary:!0,hidePlayer:1},status:{wounds:{value:16}}}},d=await(await game.dsa5.entities.Actordsa5.create(c)).getTokenDocument({x:t.x,y:t.y,hidden:!1});if(!canvas.dimensions.rect.contains(d.x,d.y))return!1;if(l){await canvas.scene.createEmbeddedDocuments("Token",[d],{noHook:!0});let p=e.system.quantity.value-a;p<1?await l.deleteEmbeddedDocuments("Item",[e.id]):await l.updateEmbeddedDocuments("Item",[{_id:e.id,"system.quantity.value":p}])}else await canvas.scene.createEmbeddedDocuments("Token",[d])}else{let s={itemId:e.uuid,sourceActorId:l?.id,data:t,amount:a};game.socket.emit("system.dsa5",{type:"itemDrop",payload:s})}},"dropToGround"),Yi=u(async(l,e)=>{let t=await Item.implementation.fromDropData(e),a=t.parent;if(!b.equipmentCategories.has(t.type))return;let s=u(async i=>{si(a,t,e,i)},"callback");Je.create(game.i18n.localize("DSASETTINGS.enableItemDropToCanvas"),game.i18n.format("MERCHANT.dropGround",{name:t.name}),t.system.quantity.value,s)},"handleItemDrop"),Ji=u(async(l,e)=>{let t=e.x,a=e.y,s=0,i=l.grid.size,n=Math.ceil(Math.sqrt(e.ids.length));for(let r of e.ids){let o=game.actors.get(r);if(!o)continue;let c=await o.getTokenDocument({x:t,y:a,hidden:!1});c.constructor.create(c,{parent:l.scene}),n%s==0&&s>0?(a+=i,t=e.x):t+=i,s++}},"handleGroupDrop"),$i=u(()=>{Hooks.on("dropCanvasData",async(l,e)=>{if(!!(game.settings.get("dsa5","enableItemDropToCanvas")||game.user.isGM||e.tokenId)){if(e.type=="Item")return Yi(l,e),!1;if(e.type=="GroupDrop")return Ji(l,e),!1}})},"connectHook"),Je=class extends Dialog{static async create(e,t,a,s,i=1,n=void 0){n=n||a;let r=await renderTemplate("systems/dsa5/templates/dialog/dropToGround.html",{name:t,min:i,max:n,count:a});new Je({title:e,content:r,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async o=>s(Number(o.find('[name="count"]').val()))},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}activateListeners(e){super.activateListeners(e),e.find('input[type="range"]').change(t=>{$(t.currentTarget).closest(".row-section").find(".range-value").html($(t.currentTarget).val())})}};u(Je,"RangeSelectDialog");var $e=class extends ActorSheet{get actorType(){return this.actor.type}async _render(e=!1,t={}){this._saveSearchFields(),this._saveCollapsed(),await super._render(e,t),this._setCollapsed(),this._restoreSeachFields();let a=$(this._element),s={".close":"SHEET.Close",".configure-sheet":"SHEET.Configure",".configure-token":"SHEET.Token",".import":"SHEET.Import",".locksheet":"SHEET.Lock",".library":"SHEET.Library",".playerview":"SHEET.switchLimited",".actorConfig":"SHEET.actorConfig"};for(let i of Object.keys(s))a.find(i).attr("data-tooltip",s[i]);this.currentFocus&&(a.find('[data-item-id="'+this.currentFocus+'"] input').trigger("focus").trigger("select"),this.currentFocus=null)}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"skills"}],mergeObject(e,{width:770,height:740,scrollY:[".save-scroll"],dragDrop:[{dragSelector:".content .item",dropSelector:null},{dragSelector:".mainEffects .statusEffect",dropSelector:null}]}),e}_saveSearchFields(){if(this.form===null)return;let e=$(this.form).parent();this.searchFields={talentFiltered:$(e.find(".filterTalents")).hasClass("filtered"),searchText:$(e.find(".talentSearch")).val(),gearSearch:$(e.find(".gearSearch")).val()}}_restoreSeachFields(){if(this.searchFields!=null){let e=$(this.form).parent();this.searchFields.talentFiltered&&($(e.find(".filterTalents")).addClass("filtered"),$(e.find(".allTalents")).removeClass("showAll"));let t=$(e.find(".talentSearch"));t.val(this.searchFields.searchText),this.searchFields.searchText!=""&&this._filterTalents(t);let a=$(e.find(".gearSearch"));a.val(this.searchFields.gearSearch),this.searchFields.searchText!=""&&this._filterGear(a)}}_saveCollapsed(){if(this.form===null)return;let e=$(this.form).parent();this.collapsedBoxes=[],this.openDetails=[];let t=e.find(".ch-collapse i");for(let a of t)this.collapsedBoxes.push($(a).attr("class"));for(let a of $(e.find(".expandDetails.shown")))this.openDetails.push($(a).closest(".item").attr("data-item-id"))}_setCollapsed(){let e=$(this.form).parent();if(this.collapsedBoxes){let t=e.find(".ch-collapse i");for(let a=0;ar.name==s&&r.type=="skill"),n=`

    ${game.i18n.localize("TYPES.Item.aggregatedTest")}

    `;a.system.usedTestCount.value>=a.system.allowedTestCount.value?(n+=`${game.i18n.localize("Aggregated.noMoreAllowed")}`,ChatMessage.create(f.chatDataSetup(n))):this.actor.setupSkill(i,{moreModifiers:[{name:game.i18n.localize("failedTests"),value:-1*a.system.previousFailedTests.value,selected:!0},{name:game.i18n.localize("Modifier"),value:a.system.baseModifier,selected:!0}]},this.getTokenId()).then(r=>{this.actor.basicTest(r).then(o=>{o.result.successLevel>0?(a.system.cummulatedQS.value=o.result.qualityStep+a.system.cummulatedQS.value,a.system.cummulatedQS.value=Math.min(10,a.system.cummulatedQS.value)):a.system.previousFailedTests.value+=1,a.system.usedTestCount.value+=1,this.actor.updateEmbeddedDocuments("Item",[a]).then(()=>{let c=this.actor.items.get(t);c.postItem(),a.system.cummulatedQS.value>=10&&c.sheet.postFinishedItem()})})})}async consumeItem(e){new Dialog({title:game.i18n.localize("SHEET.ConsumeItem")+": "+e.name,content:game.i18n.localize("SHEET.ConsumeItem")+": "+e.name,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{e.setupEffect(null,{},this.getTokenId())}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}async _advanceAttribute(e){let t=Number(this.actor.system.characteristics[e].advances),a=t+Number(this.actor.system.characteristics[e].initial),s=f._calculateAdvCost(a,"E");await this._checkEnoughXP(s)&&(await this._updateAPs(s,{[`system.characteristics.${e}.advances`]:t+1}),await _.track(this.actor,{type:"attribute",attr:e,previous:a,next:a+1},s))}async _refundAttributeAdvance(e){let t=Number(this.actor.system.characteristics[e].advances),a=t+Number(this.actor.system.characteristics[e].initial);if(t>0){let s=f._calculateAdvCost(a,"E",0)*-1;await this._updateAPs(s,{[`system.characteristics.${e}.advances`]:t-1}),await _.track(this.actor,{type:"attribute",attr:e,previous:a,next:a-1},s)}}async _rebuyPC(e){if(this.actor.system.status[e].permanentLossSum>0&&await this._checkEnoughXP(2)){let t=Number(this.actor.system.status[e].rebuy);await this._updateAPs(2,{[`system.status.${e}.rebuy`]:t+1}),await _.track(this.actor,{type:"permanentLoss",attr:e,previous:t,next:t+1},2)}}async _refundPC(e){if(this.actor.system.status[e].rebuy>0){let t=Number(this.actor.system.status[e].rebuy);await this._updateAPs(-2,{[`system.status.${e}.rebuy`]:t-1}),await _.track(this.actor,{type:"permanentLoss",attr:e,previous:t,next:t-1},-2)}}async _advancePoints(e){let t=Number(this.actor.system.status[e].advances),a=f._calculateAdvCost(t,"D");await this._checkEnoughXP(a)&&this._checkMaximumPointAdvancement(e,t+1)&&(await this._updateAPs(a,{[`system.status.${e}.advances`]:t+1}),await _.track(this.actor,{type:"point",attr:e,previous:t,next:t+1},a))}async _refundPointsAdvance(e){let t=Number(this.actor.system.status[e].advances);if(t>0){let a=f._calculateAdvCost(t,"D",0)*-1;await this._updateAPs(a,{[`system.status.${e}.advances`]:t-1}),await _.track(this.actor,{type:"point",attr:e,previous:t,next:t-1},a)}}async _advanceItem(e){let t=this.actor.items.get(e),a=Number(t.system.talentValue.value),s=f._calculateAdvCost(a,t.system.StF.value);await this._checkEnoughXP(s)&&this.actor._checkMaximumItemAdvancement(t,a+1)?.result&&(await this.actor.updateEmbeddedDocuments("Item",[{_id:e,"system.talentValue.value":a+1}]),await this._updateAPs(s),await _.track(this.actor,{type:"item",item:t,previous:a,next:a+1},s))}async _refundItemAdvance(e){let t=this.actor.items.get(e),a=t.type=="combatskill"?6:0,s=Number(t.system.talentValue.value);if(s>a){let i=f._calculateAdvCost(s,t.system.StF.value,0)*-1;await this.actor.updateEmbeddedDocuments("Item",[{_id:e,"system.talentValue.value":s-1}]),await this._updateAPs(i),await _.track(this.actor,{type:"item",item:t,previous:s,next:s-1},i)}}_checkMaximumPointAdvancement(e,t){let a=!1;switch(e){case"wounds":a=t<=this.actor.system.characteristics.ko.value;break;case"astralenergy":a=t<=(this.actor.system.characteristics[this.actor.system.guidevalue.magical]==null?0:this.actor.system.characteristics[this.actor.system.guidevalue.magical].value*this.actor.system.energyfactor.magical);break;case"karmaenergy":a=t<=(this.actor.system.characteristics[this.actor.system.guidevalue.clerical]==null?0:this.actor.system.characteristics[this.actor.system.guidevalue.clerical].value*this.actor.system.energyfactor.clerical);break}return a||ui.notifications.error(game.i18n.localize("DSAError.AdvanceMaximumReached")),a}async _openLibrary(){game.dsa5.itemLibrary.render(!0)}async _configActor(){Ye.buildDialog(this.actor)}_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"library",icon:"fas fa-university",onclick:async()=>this._openLibrary()}),this.actor.isOwner&&(e.unshift({class:"actorConfig",icon:"fas fa-link",onclick:async()=>this._configActor()}),e.unshift({class:"playerview",icon:"fas fa-toggle-on",onclick:async t=>this._togglePlayerview(t)})),this.actor.system.canAdvance&&e.unshift({class:"locksheet",icon:`fas fa-${this.actor.system.sheetLocked.value?"":"un"}lock`,onclick:async t=>this._changeAdvanceLock(t)}),e}async _changeAdvanceLock(e){await this.actor.update({"system.sheetLocked.value":!this.actor.system.sheetLocked.value}),$(e.currentTarget).find("i").toggleClass("fa-unlock fa-lock")}async _checkEnoughXP(e){return await this.actor.checkEnoughXP(e)}async advanceWrapper(e,t,a){let i=$(e.currentTarget).find("i");i.hasClass("fa-spin")||(i.addClass("fa-spin fa-spinner"),await this[t](a),i.removeClass("fa-spin fa-spinner"))}playerViewEnabled(){return getProperty(this.actor.system,"playerView")}_togglePlayerview(e){this.actor.update({"system.playerView":!getProperty(this.actor.system,"playerView")})}showLimited(){return!game.user.isGM&&this.actor.limited||this.playerViewEnabled()}getTokenId(){return this.token?.id}rollDisease(e){let t=this.actor.items.get(e),a=this.actor.system.status.soulpower.max*-1,s=this.actor.system.status.toughness.max*-1;t.setupEffect(void 0,{rollMode:"gmroll",manualResistance:{SKModifier:a,ZKModifier:s}}).then(async i=>{let n=await t.itemTest(i);await this.actor.updateEmbeddedDocuments("Item",[{_id:t.id,"system.duration.resolved":n.result.duration}])})}async swapWeaponHand(e){let t=this._getItemId(e),a=this.actor.items.get(t);["Daggers","Fencing Weapons"].includes(game.i18n.localize(`LocalizedCTs.${a.system.combatskill.value}`))||await this.actor.updateEmbeddedDocuments("Item",[{_id:t,"system.worn.wrongGrip":!a.system.worn.wrongGrip}])}activateListeners(e){super.activateListeners(e);let t=u(d=>{this.actor.items.get(this._getItemId(d)).postItem()},"posthand");e.find(".roll-disease").click(d=>this.rollDisease(this._getItemId(d))),oe(e),e.find(".condition-edit").click(async d=>{(d.currentTarget.dataset.uuid?await fromUuid(d.currentTarget.dataset.uuid):this.actor.effects.get(d.currentTarget.dataset.id)).sheet.render(!0)}),e.find(".ch-collapse").click(d=>{$(d.currentTarget).find("i").toggleClass("fa-angle-up fa-angle-down"),$(d.currentTarget).closest(".groupbox").find(".row-section:nth-child(2)").fadeToggle()}),e.find(".status-create").click(d=>{let p=$(d.currentTarget).closest(".statusEffectMenu").find("ul");p.fadeIn("fast",()=>{p.find("input").trigger("focus")})}),e.find(".statusEffectMenu ul").mouseleave(d=>$(d.currentTarget).fadeOut()),e.find(".roll-aggregated").mousedown(d=>this._handleAggregatedProbe(d)),e.find(".skill-select").mousedown(d=>{let p=this._getItemId(d),g=this.actor.items.get(p);d.button==0?this.actor.setupSkill(g,{},this.getTokenId()).then(y=>{this.actor.basicTest(y)}):d.button==2&&g.sheet.render(!0)}),e.find(".spell-select").mousedown(d=>{let p=this._getItemId(d),g=this.actor.items.get(p);d.button==0?this.actor.setupSpell(g,{},this.getTokenId()).then(y=>this.actor.basicTest(y)):d.button==2&&g.sheet.render(!0)}),e.find(".item-post").click(d=>t(d)),e.find(".item-dropdown").click(d=>{d.preventDefault(),$(d.currentTarget).closest(".item").find(".expandDetails:first").toggleClass("shown")}),e.find(".condition-show").mousedown(d=>{d.preventDefault();let p=d.currentTarget.dataset.id,g=$(d.currentTarget).parents(".statusEffect").attr("data-descriptor");if(d.button==0){let y=$(d.currentTarget).parents(".statusEffect").attr("data-origin");if(y)fromUuid(y).then(h=>h.sheet.render(!0));else{let h,w;g?(h=CONFIG.statusEffects.find(v=>v.id==g),w=$(`
    ${game.i18n.localize(h.name)}: ${game.i18n.localize(h.description)}
    `)):(h=this.actor.effects.find(v=>v.id==p),h&&(w=$(`
    ${game.i18n.localize(h.name)}: ${game.i18n.localize(h.flags.dsa5.description)}
    `)));let z=$(d.currentTarget).closest(".groupbox").find(".effectDescription");z.fadeOut("fast",function(){z.html(w).fadeIn("fast")})}}else d.button==2&&!d.currentTarget.dataset.locked&&this._deleteActiveEffect(p)}),e.on("click",".chat-condition",d=>ae.postStatus(d.currentTarget.dataset.id)),e.find(".money-change, .skill-advances").focusin(d=>{this.currentFocus=$(d.currentTarget).closest("[data-item-id]").attr("data-item-id")}),e.find(".item-edit").click(d=>{d.preventDefault();let p=this._getItemId(d);this.actor.items.get(p).sheet.render(!0)}),e.find(".showApplication").mousedown(d=>{if(d.preventDefault(),d.button==2)this._deleteItem(d);else{let p=this._getItemId(d);this.actor.items.get(p).sheet.render(!0)}}),e.find(".ch-value").click(d=>{d.preventDefault();let p=d.currentTarget.attributes["data-char"].value;this.actor.setupCharacteristic(p,{},this.getTokenId()).then(g=>this.actor.basicTest(g))}),e.find(".ch-status").click(d=>{d.preventDefault(),this.actor.setupDodge({},this.getTokenId()).then(p=>{this.actor.basicTest(p)})}),e.find(".ch-regenerate").click(d=>{d.preventDefault(),this.actor.setupRegeneration("regenerate",{},this.getTokenId()).then(p=>this.actor.basicTest(p))}),e.find(".ch-weaponless").click(d=>{d.preventDefault();let p=d.currentTarget.attributes["data-char"].value;this.actor.setupWeaponless(p,{},this.getTokenId()).then(g=>this.actor.basicTest(g))}),e.find(".ch-fallingDamage").click(d=>{d.preventDefault(),this.actor.setupFallingDamage({},this.getTokenId())}),e.find(".ch-rollCombat").click(d=>{d.preventDefault();let p=this._getItemId(d),g=d.currentTarget.dataset.mode,y=this.actor.items.get(p);this.actor.setupWeapon(y,g,{},this.getTokenId()).then(h=>this.actor.basicTest(h))});let a=u(d=>this._deleteItem(d),"deletehand");e.find(".cards .item").mouseenter(d=>{if(d.currentTarget.getElementsByClassName("hovermenu").length==0){let p=document.createElement("div");p.classList.add("hovermenu");let g=document.createElement("i");g.classList.add("fas","fa-times"),g.title=game.i18n.localize("SHEET.DeleteItem"),g.addEventListener("click",a,!1);let y=document.createElement("i");y.classList.add("fas","fa-comment"),y.title=game.i18n.localize("SHEET.PostItem"),y.addEventListener("click",t,!1),p.appendChild(y),p.appendChild(g),d.currentTarget.appendChild(p)}}),e.find(".cards .item").mouseleave(d=>{let p=d.toElement||d.relatedTarget;!p||p.parentNode==this||p==this||d.currentTarget.querySelectorAll(".hovermenu").forEach(g=>g.remove())});let s=this.actor.uuid;e.find(".actorDrag").each(function(d,p){p.setAttribute("draggable",!0),p.addEventListener("dragstart",g=>{let y={type:"Actor",uuid:s};g.dataTransfer.setData("text/plain",JSON.stringify(y))})}),e.find(".filterTalents").click(d=>{$(d.currentTarget).closest(".content").find(".allTalents").toggleClass("showAll"),$(d.currentTarget).toggleClass("filtered")}),e.find(".charimg").mousedown(d=>{d.button==2&&f.showArtwork(this.actor,!0)}),se.bindRollCommands(e);let i=u(d=>this._filterTalents($(d.currentTarget)),"filterTalents"),n=e.find(".talentSearch");n.keyup(d=>this._filterTalents($(d.currentTarget))),n[0]&&n[0].addEventListener("search",i,!1);let r=u(d=>this._filterConditions($(d.currentTarget)),"filterConditions"),o=e.find(".conditionSearch");o.keyup(d=>this._filterConditions($(d.currentTarget))),o[0]&&o[0].addEventListener("search",r,!1);let c=u(d=>this._filterGear($(d.currentTarget)),"filterGear"),m=e.find(".gearSearch");m.keyup(d=>this._filterGear($(d.currentTarget))),m[0]&&m[0].addEventListener("search",c,!1),mt(e,"img.charimg"),H.activateListeners(e,this.actor),this._bindKeepFieldsEnabled(e),this.isEditable&&(new ContextMenu(e,".item .withContext",[],{onOpen:this._onItemContext.bind(this)}),e.find(".startCharacterBuilder").click(()=>this.actor.setFlag("core","sheetClass","dsa5.DSACharBuilder")),e.find(".schipUpdate").click(d=>{d.preventDefault();let p=Number(d.currentTarget.getAttribute("data-val"));p==1&&$(this.form).find(".fullSchip").length==1&&(p=0),this.actor.update({"system.status.fatePoints.value":p})}),e.find(".swapWeaponHand").click(d=>this.swapWeaponHand(d)),e.find(".defenseToggle").click(()=>this.actor.update({"system.config.defense":!this.actor.system.config.defense})),e.find(".loadWeapon").mousedown(async d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject();if(getProperty(g,"system.currentAmmo.value")==="")return;let y={_id:p};if(d.button==0){let h=g.type=="trait"?g.system.reloadTime.value:T.calcLZ(g,this.actor);y["system.reloadTime.progress"]=Math.min(g.system.reloadTime.progress+1,h)}else d.button==2&&(y["system.reloadTime.progress"]=0);await this.actor.updateEmbeddedDocuments("Item",[y])}),e.find(".chargeSpell").mousedown(async d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject(),y=Number(g.system.castingTime.modified);d.button==0?g.system.castingTime.progress=Math.min(g.system.castingTime.progress+1,y):d.button==2&&(g.system.castingTime.progress=0,g.system.castingTime.modified=0),await this.actor.updateEmbeddedDocuments("Item",[g])}),e.find(".item-swapMag").click(async d=>{await this.actor.swapMag(this._getItemId(d))}),e.find(".ammo-selector").change(async d=>{d.preventDefault();let p=this._getItemId(d);await this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.currentAmmo.value":$(d.currentTarget).val()}])}),e.find(".item-toggle").click(d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject();switch(g.type){case"armor":case"rangeweapon":case"meleeweapon":case"equipment":this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.worn.value":!g.system.worn.value}]),K.playEquipmentWearStatusChange(g);break}}),e.find(".quantity-click").mousedown(d=>{let p=this._getItemId(d),g=this.actor.items.get(p).toObject();P.increment(d,g,"system.quantity.value",0),this.actor.updateEmbeddedDocuments("Item",[g])}),e.find(".status-add").mousedown(async d=>{let p=d.currentTarget.dataset.id;p=="custom"?E.createCustomEffect(this.actor):d.button==0?await this.actor.addCondition(p,1,!1,!1):d.button==2&&Ee.modifyEffectDialog(p,async(g,y)=>this.actor.addTimedCondition(g,1,!1,!1,y))}),e.find(".money-change").change(async d=>{let p=this._getItemId(d);await this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.quantity.value":Number(d.target.value)}])}),e.find(".skill-advances").change(async d=>{let p=this._getItemId(d);await this.actor.updateEmbeddedDocuments("Item",[{_id:p,"system.talentValue.value":Number(d.target.value)}])}),e.find(".advance-attribute").mousedown(d=>this.advanceWrapper(d,"_advanceAttribute",d.currentTarget.dataset.attr)),e.find(".refund-attribute").mousedown(d=>this.advanceWrapper(d,"_refundAttributeAdvance",d.currentTarget.dataset.attr)),e.find(".advance-item").mousedown(d=>this.advanceWrapper(d,"_advanceItem",this._getItemId(d))),e.find(".refund-item").mousedown(d=>this.advanceWrapper(d,"_refundItemAdvance",this._getItemId(d))),e.find(".advance-points").mousedown(d=>this.advanceWrapper(d,"_advancePoints",d.currentTarget.dataset.attr)),e.find(".refund-points").mousedown(d=>this.advanceWrapper(d,"_refundPointsAdvance",d.currentTarget.dataset.attr)),e.find(".rebuy-pc").mousedown(d=>this.advanceWrapper(d,"_rebuyPC",d.currentTarget.dataset.attr)),e.find(".refund-pc").mousedown(d=>this.advanceWrapper(d,"_refundPC",d.currentTarget.dataset.attr)),e.find(".onUseItem").mousedown(d=>this._onMacroUseItem(d)),e.find(".traditionPayCost").mousedown(d=>this._payAeSpecialAbilityCost(d)),e.find(".item-create").click(d=>this._onItemCreate(d)),e.find(".condition-toggle").mousedown(async d=>{let p=$(d.currentTarget).parents(".statusEffect").attr("data-id"),g=this.actor.effects.get(p);await g.update({disabled:!g.disabled})}),e.find(".condition-value").mousedown(async d=>{let p=$(d.currentTarget).parents(".statusEffect").attr("data-descriptor");d.button==0?await this.actor.addCondition(p,1,!1,!1):d.button==2&&await this.actor.removeCondition(p,1,!1)}),e.find(".item-delete").click(d=>this._deleteItem(d)),e.find(".tradition-delete").click(d=>this._deleteTraditionArtifact(d)),e.find(".selectTraditionartifact").click(()=>this.selectTraditionartifact()),e.find(".disableRegeneration").click(d=>{let g=`system.repeatingEffects.disabled.${d.currentTarget.dataset.type}`;this.actor.update({[g]:!getProperty(this.actor,g)})}))}_onItemContext(e){let t=this.actor.items.get($(e).closest(".item").attr("data-item-id"));!t||(ui.context.menuItems=this._getItemContextOptions(t),Hooks.call("dsa5.getItemContextOptions",t,ui.context.menuItems))}_getItemContextOptions(e){let t=[{name:"SHEET.EditItem",icon:"",callback:()=>e.sheet.render(!0)},{name:"SHEET.PostItem",icon:"",callback:()=>e.postItem()},{name:"SHEET.DuplicateItem",icon:"",callback:()=>this.handleItemCopy(e.toObject(),e.type)},{name:"SHEET.ConsumeItem",icon:"",condition:()=>e.type=="consumable",callback:()=>this.consumeItem(e)},{name:"SHEET.onUseEffect",icon:"",condition:()=>getProperty(e,"flags.dsa5.onUseEffect"),callback:()=>new X(e).executeOnUseEffect()},{name:"SHEET.DeleteItem",icon:"",callback:()=>this._itemDeleteDialog(e)},{name:"MERCHANT.exchange",icon:"",condition:()=>b.equipmentCategories.has(e.type),callback:()=>this._startTrade(e)}];return(hasProperty(e,"system.worn.wearable")||["meleeweapon","rangeweapon","armor"].includes(e.type))&&t.push({name:"SHEET.EquipItem",icon:"",callback:()=>e.update({"system.worn.value":!e.system.worn.value})}),Number(getProperty(e,"system.quantity.value"))>1&&t.push({name:"SHEET.SplitItem",icon:"",callback:()=>this._splitItem(e)}),t}async _startTrade(e){new Yt(this.actor).render(!0)}_splitItem(e){let t=u(async a=>{let s=e.toObject();s.system.quantity.value=a,await this.actor.createEmbeddedDocuments("Item",[s],{render:!1}),await this.actor.updateEmbeddedDocuments("Item",[{_id:e.id,"system.quantity.value":e.system.quantity.value-a}])},"callback");Je.create(game.i18n.localize("SHEET.SplitItem"),game.i18n.format("MERCHANT.splitItem",{name:e.name}),e.system.quantity.value-1,t,1,e.system.quantity.value-1)}_bindKeepFieldsEnabled(e){if(!this.isEditable){let t=e.find(".keepFieldsEnabled");for(let a of t){let s=a.dataset.attr,i=a.dataset.name;$(a).find(".editor").append(``),$(a).find(".editor-edit").click(n=>this._openKeepFieldEditpage(n))}}}_openKeepFieldEditpage(e){let t=e.currentTarget.dataset.attr,a=e.currentTarget.dataset.name;new At(this.actor.id,t,a).render(!0)}async _onMacroUseItem(e){let t=this.actor.items.get(this._getItemId(e));await new X(t).executeOnUseEffect()}async _payAeSpecialAbilityCost(e){let t=this.actor.items.get(this._getItemId(e)),a=Number(getProperty(t,"system.AsPCost"));if(!this.actor.applyMana(a,"AsP"))return;let i=game.i18n.format("CHATNOTIFICATION.paysTraditionAbility",{name:this.actor.name,ability:t.name,cost:a});e.button==2?ChatMessage.create(f.chatDataSetup(i,"gmroll")):ChatMessage.create(f.chatDataSetup(i))}_filterGear(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.element).find(".inventory .item");a.removeClass("filterHide"),a.filter(function(){return $(this).find("a.item-edit").text().toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide")}}async selectTraditionartifact(){!this.isEditable||new ps(this.actor).render(!0)}_deleteTraditionArtifact(e){if(!this.isEditable)return;this.actor.items.get(this._getItemId(e)).update({"system.isArtifact":!1})}_filterTalents(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.form).parent().find(".allTalents");a.find(".item, .table-header, .table-title").removeClass("filterHide"),a.addClass("showAll").find(".item").filter(function(){return $(this).find(".talentName").text().toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide"),t.length>0?(a.find(".table-header, .table-title:not(:eq(0))").addClass("filterHide"),a.addClass("filterfull")):a.removeClass("filterfull")}}_filterConditions(e){if(e.val()!=null){let t=e.val().toLowerCase().trim(),a=$(this.form).find(".statusEffectMenu li:not(.search)");a.removeClass("filterHide"),a.filter(function(){return game.i18n.localize($(this).find("a").attr("data-tooltip")).toLowerCase().trim().indexOf(t)==-1}).addClass("filterHide")}}async _deleteActiveEffect(e){if(!this.isEditable)return;let t=this.actor.effects.find(a=>a.id==e);t&&(this.token?this.token.actor:this.actor)&&await this.actor.deleteEmbeddedDocuments("ActiveEffect",[t.id])}async _itemDeleteDialog(e){let t=game.i18n.format("DIALOG.DeleteItemDetail",{item:e.name}),a=await renderTemplate("systems/dsa5/templates/dialog/delete-item-dialog.html",{message:t});await new Promise((s,i)=>{new Dialog({title:game.i18n.localize("DIALOG.deleteConfirmation"),content:a,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async()=>{await this._cleverDeleteItem(e.id),s(!0)}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)})}async _deleteItem(e){if(!this.isEditable)return;let t=this._getItemId(e),a=this.actor.items.get(t);this._itemDeleteDialog(a)}async _cleverDeleteItem(e){let t=this.actor.items.get(e),a=[e];switch(t.type){case"advantage":case"disadvantage":await O.vantageRemoved(this.actor,t,!1);break;case"specialability":await R.abilityRemoved(this.actor,t,!1);break;case"blessing":case"magictrick":await this._updateAPs(-1,{},{render:!1}),await _.track(this.actor,{type:"item",item:t,state:-1},-1);break;case"ritual":case"ceremony":case"liturgy":case"spell":{let s=0;for(let n=0;n<=t.system.talentValue.value;n++)s+=f._calculateAdvCost(n,t.system.StF.value,0);let i=this.actor.items.filter(n=>n.type=="spellextension"&&t.type==n.system.category&&t.name==n.system.source);i&&(s+=i.reduce((n,r)=>n+(Number(r.system.APValue.value)||0),0),a.push(...i.map(n=>n.id))),await this._updateAPs(s*-1,{},{render:!1}),await _.track(this.actor,{type:"item",item:t,state:-1},s)}break}await this.actor.deleteEmbeddedDocuments("Item",a)}_getItemId(e){return $(e.currentTarget).closest(".item").attr("data-item-id")}async _addMoney(e){let a=duplicate(this.actor.items.filter(s=>s.type=="money")).find(s=>s.name==e.name);a?(a.system.quantity.value+=e.system.quantity.value,await this.actor.updateEmbeddedDocuments("Item",[a])):await this.actor.createEmbeddedDocuments("Item",[e])}async _updateAPs(e,t={},a={}){await this.actor._updateAPs(e,t,a)}async _addVantage(e,t){O.needsAdoption(this.actor,e,t)}async _addSpecialAbility(e,t){R.needsAdoption(this.actor,e,t)}_onDragStart(e){let t=e.currentTarget;if(e.target.classList.contains("content-link"))return;let a;t.dataset.itemId&&(a=this.actor.items.get(t.dataset.itemId).toDragData(),t.dataset.mod&&(a.mod=t.dataset.mod)),t.dataset.id&&(a=this.actor.effects.get(t.dataset.id).toDragData()),a&&e.dataTransfer.setData("text/plain",JSON.stringify(a))}async _handleSpellExtension(e){if(!this.actor.items.find(a=>a.type==e.type&&a.name==e.name)){e=duplicate(e);let a=this.actor.items.find(s=>s.type==e.system.category&&s.name==e.system.source);if(!a)ui.notifications.error(game.i18n.format("DSAError.noSpellForExtension",{name:e.system.source,category:f.categoryLocalization(e.system.category),extension:e.name}));else{if(a.system.talentValue.values.type==e.type&&s.name==e.name),a;if(e=duplicate(e),!t){switch(e.type){case"spell":case"liturgy":case"ceremony":case"ritual":a=f._calculateAdvCost(0,e.system.StF.value,0);break;case"blessing":case"magictrick":a=1;break;case"magicalsign":a=e.system.APValue.value;break;default:return}if(await this.actor.checkEnoughXP(a)){await this._updateAPs(a,{},{render:!1});let s=(await this.actor.createEmbeddedDocuments("Item",[e]))[0];await _.track(this.actor,{type:"item",item:s,state:1},a)}}}async _addLoot(e){e=duplicate(e);let t=this.actor.items.find(a=>C.areEquals(e,a));return t?(await C.stackItems(t,e,this.actor))[0]:(this._tabs[0].active=="combat"&&e.system.worn&&(e.system.worn.value=!0),(await this.actor.createEmbeddedDocuments("Item",[e]))[0])}async _addUniqueItem(e){if(e=duplicate(e),!this.actor.items.some(t=>C.areEquals(e,t)))return(await this.actor.createEmbeddedDocuments("Item",[e]))[0]}async _addDemonMarkOrPatron(e){return await this._addUniqueItem(e)}async _addDisease(e){return e.system.duration.resolved="?",await this._addUniqueItem(e)}async handleItemCopy(e,t){e.name+=" (Copy)",this._manageDragItems(e,t)}async _addFullPack(e){let a=(await game.packs.get(e.name).getDocuments()).filter(s=>!this.actor.items.find(i=>i.type==s.type&&i.name==s.name));e.onlyType&&(a=a.filter(s=>s.type==e.onlyType)),await this.actor.createEmbeddedDocuments("Item",a.map(s=>s.toObject()))}async creatureDrop(e){game.dsa5.config.hooks.shapeshift?new Dialog({title:game.i18n.localize("DIALOG.ItemRequiresAdoption")+": "+e.name,content:game.i18n.localize("DIALOG.whichFunction")+": "+e.name,default:"horse",buttons:{shapeshift:{icon:'',label:game.i18n.localize("CONDITION.shapeshift"),callback:()=>{let t=game.dsa5.config.hooks.shapeshift;t.setShapeshift(this.actor,e),t.render(!0)}},horse:{icon:'',label:game.i18n.localize("RIDING.horse"),callback:()=>{H.setHorse(this.actor,e)}}}}).render(!0):H.setHorse(this.actor,e)}async _manageDragItems(e,t){switch(t){case"disease":await this._addDisease(e);break;case"meleeweapon":case"rangeweapon":case"equipment":case"ammunition":case"armor":case"poison":case"consumable":case"plant":return await this._addLoot(e);case"disadvantage":case"advantage":await this._addVantage(e,t);break;case"specialability":await this._addSpecialAbility(e,t);break;case"money":await this._addMoney(e);break;case"ritual":case"ceremony":case"blessing":case"magictrick":case"liturgy":case"spell":case"magicalsign":await this._addSpellOrLiturgy(e);break;case"effectwrapper":await this._handleEffectWrapper(e);break;case"application":await this._handleApplication(e);break;case"spellextension":await this._handleSpellExtension(e);break;case"creature":this.creatureDrop(e);break;case"skill":case"imprint":case"essence":case"information":await this._addUniqueItem(e);break;case"patron":case"demonmark":await this._addDemonMarkOrPatron(e);break;default:ui.notifications.error(game.i18n.format("DSAError.canNotBeAdded",{item:e.name,category:game.i18n.localize(e.type)}))}}async _handleEffectWrapper(e){this.actor.createEmbeddedDocuments("ActiveEffect",e.effects.map(t=>(t.origin=null,t)))}async _handleLookup(e){let t=await f.findAnyItem(e.items);if(t){for(let a of e.items)if(a.count){let s=t.find(i=>i.name==a.name&&i.type==a.type);s?(s.system.quantity.value=a.count,a.qs&&a.type=="consumable"&&(s.system.QL=a.qs)):ui.notifications.warn(game.i18n.format("DSAError.notFound",{category:a.type,name:a.name}))}await this.actor.createEmbeddedDocuments("Item",t)}else ui.notifications.error(game.i18n.format("DSAError.notFound",{category:thing.type,name:thing.name}))}async _handleApplication(e){e=duplicate(e),this.actor.items.find(a=>a.type==e.type&&a.name==e.name)||await this.actor.createEmbeddedDocuments("Item",[e])}async _handleRemoveSourceOnDrop(e){let t=e.parent;t&&t.isOwner&&await t.deleteEmbeddedDocuments("Item",[e._id])}async _onDropItemCreate(e){return e instanceof Array?this.actor.createEmbeddedDocuments("Item",e):await this._manageDragItems(e,e.type)}async _onDropActor(e,t){if(!this.actor.isOwner)return!1;let{item:a,typeClass:s,selfTarget:i}=await Ge(t,this.id,!1);if(!i)return await this._manageDragItems(a,s)}async _onDropActiveEffect(e,t){let a=await ActiveEffect.implementation.fromDropData(t);if(!this.actor.isOwner||!a||this.actor.uuid===a.parent?.uuid)return!1;let s=a.toObject();return s.origin=null,ActiveEffect.create(s,{parent:this.actor})}async _onDropItem(e,t){if(!this.actor.isOwner)return!1;let a=await Item.implementation.fromDropData(t),s=a.toObject();P.obfuscateDropData(s,t.tabsinvisible);let i,n=!1,r=$(e.target).parents(".item");if(r&&b.equipmentCategories.has(a.type)){let c=r.attr("data-item-id");c!=a.id&&(r.attr("data-category")=="bags"?i=c:(r=this.actor.items.get(c),n=r&&hasProperty(a,"system.quantity.value")&&hasProperty(r,"system.quantity.value")&&C.areEquals(a,r)))}let o=this.actor.uuid===a.parent?.uuid;if(o)if(e.ctrlKey)await this.handleItemCopy(s,a.type);else if(n)await r.update({"system.quantity.value":r.system.quantity.value+a.system.quantity.value},{render:!1}),await this.actor.deleteEmbeddedDocuments("Item",[a.id]);else if(i){let c={_id:a.id,"system.parent_id":i};a.system.worn&&a.system.worn.value&&(c["system.worn.value"]=!1),await this.actor.updateEmbeddedDocuments("Item",[c])}else b.equipmentCategories.has(a.type)&&await this.actor.updateEmbeddedDocuments("Item",[{_id:a.id,system:{parent_id:0}}]);else{if(this._itemHasPrice(t)){let m=`${a.type=="consumable"?C.getSubClass(s.type).consumablePrice(s):Number(s.system.price.value)}`;if(m&&!await B.payMoney(this.actor,m,!0,!1))return;de(game.i18n.format("PAYMENT.pay",{actor:this.actor.name,amount:m})),K.playMoneySound()}await this._onDropItemCreate(s)}e.altKey&&!o&&b.equipmentCategories.has(a.type)&&await this._handleRemoveSourceOnDrop(a)}_itemHasPrice(e){return e.pay}};u($e,"ActorSheetDsa5");var ps=class extends Application{constructor(e,t={}){super(t),this.actor=e}get template(){return"systems/dsa5/templates/actors/traditionPicker.html"}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:440,resizable:!0}),e}async getData(e){let t=await super.getData(e),a=this.actor.items.filter(s=>["equipment","armor","rangeweapon","meleeweapon"].includes(s.type));return mergeObject(t,{items:a}),t}activateListeners(e){super.activateListeners(e),e.find(".slot").click(async t=>{let a=this.actor.items.get(t.currentTarget.dataset.itemId);await a.update({"system.isArtifact":!a.system.isArtifact})})}};u(ps,"TraditionArtifactpicker");var ne=class extends Application{constructor(e){super(e),this.actor=null,this.errors=[],this.attributes=[],this.updating=!1}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"description"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog","generationWizard"]),width:770,height:740}),e.resizable=!0,e}async findCompendiumItem(e,t){for(let a of t){let s=await game.dsa5.itemLibrary.findCompendiumItem(e,a);if(s=s.find(i=>i.name==e&&i.type==a&&i.system),s)return s}}_parseAttributes(e,t=","){let a=[],s=game.i18n.localize("combatskillcountdivider")+":";for(let i of e.split(t))if(i.includes(s)){let n=i.split(":");a.push({choices:n[1].split("/").map(r=>r.trim()),allowedCount:Number(n[0].match(/\d/g))})}return a}async parseToItem(e,t){return e.trim()==""?[]:await Promise.all(e.split(", ").map(async a=>{let s=f.parseAbilityString(a.trim()),i=await this.findCompendiumItem(s.original,t);if(i||(i=await this.findCompendiumItem(s.name,t)),i){let r=i.uuid;i=duplicate(i),i.uuid=r,i.tooltip=game.i18n.localize("Details"),i=te.reverseAdoptionCalculation(this.actor,s,i),i.system.APValue&&(i.APunparseable=isNaN(i.system.APValue.value),i.apCost=i.APunparseable?i.system.APValue.value:s.step*Number(i.system.APValue.value))}else if(this.attributes.includes(s.name)){let r=0;for(let o=this.actor.system.characteristics[game.dsa5.config.knownShortcuts[s.name.toLowerCase()][1]].value+1;o`);let r=t.map(o=>f.categoryLocalization(o)).join("/");this.errors.push(`${r}: ${a}`),i={name:a.trim(),notFound:!0,tooltip:game.i18n.localize("DSAError.itemNotFound"),apCost:"?"}}i.replaceName=s.original,i.step=s.step;let n=this.actor.items.find(r=>t.includes(r.type)&&r.name==s.original)!=null;return i.disabled=n||i.notFound||i.APunparseable,n&&(i.tooltip=game.i18n.localize("YouAlreadyHaveit")),i}))}mergeLevels(e,t,a){let s=!1,i=e.find(n=>n.name==t.name&&n.type==t.type);if(i){s=!0;let n=Number(getProperty(t,"system.step.value"));n&&(i.system.step.value=Math.min(i.system.step.value+=n,i.system[a].value))}else e.push(t);return s}async addSelections(e,t=!0){let a=[];for(let s of e){if($(s).val()=="")continue;let n=(await fromUuid($(s).val())).toObject(),r=f.parseAbilityString(n.name);switch(n.name=$(s).attr("name"),n.type){case"advantage":case"disadvantage":n.system.step.value=Number(s.dataset.step),n=te.reverseAdoptionCalculation(this.actor,r,n),this.mergeLevels(a,n,"max")||O.vantageAdded(this.actor,n);break;case"specialability":n.system.step.value=Number(s.dataset.step),s.dataset.free=="true"&&(n.system.APValue.value=0),n=te.reverseAdoptionCalculation(this.actor,r,n),this.mergeLevels(a,n,"maxRank")||R.abilityAdded(this.actor,n);break;case"magictrick":this.mergeLevels(a,n);break}}await this.actor.createEmbeddedDocuments("Item",a,{render:t})}async fixPreviousCosts(e,t){for(let a of t){let s=e.find(i=>i.type==a.type&&i.name==a.name);s&&(a.apCost-=s.apCost)}}async alreadyAdded(e,t){if(e=="")return!1;let a=!1;return a=await new Promise((s,i)=>{new Dialog({title:game.i18n.localize("DIALOG.warning"),content:game.i18n.format("DIALOG.alreadyAddedCharacterpart",{category:f.categoryLocalization(t)}),default:"ok",buttons:{ok:{icon:'',label:game.i18n.localize("Ok"),default:!0,callback:()=>{s(!1)}},cancel:{icon:'',label:game.i18n.localize("Cancel"),default:!0,callback:()=>{s(!0)}}}}).render(!0)}),a}async updateSkill(e,t,a=1,s=!0){let i=[];for(let n of e){let r=f.parseAbilityString(n.trim()),o=this.actor.items.find(c=>c.type==t&&c.name==r.name);o?i.push({_id:o.id,"system.talentValue.value":Math.max(0,a*r.step+(s?Number(o.system.talentValue.value):0))}):(console.warn(`Could not find ${t} ${n}`),this.errors.push(`${f.categoryLocalization(t)}: ${n}`))}await this.actor.updateEmbeddedDocuments("Item",i,{render:!1})}async getData(e){let t=await super.getData(e);return await game.dsa5.itemLibrary.buildEquipmentIndex(),t}_validateInput(e,t=this){let a=/^exclusive_/;for(let s of e.find(".tab")){let i=$(s),n=new Set;for(let r of i.find(".exclusive"))n.add(r.className.split(/\s+/).filter(o=>a.test(o))[0]);for(let r of n){let o=i.find(".allowedCount_"+r.split("_")[1]),c=Number(o.attr("data-count"));if(i.find(`.${r}:checked`).length!=c)return this._showInputValidation(o,i,t),!1}}return!0}_showInputValidation(e,t,a){ui.notifications.error(game.i18n.localize("DSAError.MissingChoices"));let s=e.closest(".tab").attr("data-tab");a.activateTab(s),ne.flashElem(t.find(`.tabs a[data-tab='${s}']`)),ne.flashElem(e.closest("div"))}activateListeners(e){super.activateListeners(e),oe(e),e.find("button.ok").click(()=>{this.updating||(this.updating=!0,this.updateCharacter($(this._element)).then(()=>this.updating=!1))}),e.find("button.cancel").click(()=>{this.close()});let t=u(s=>{s.stopPropagation();let i=s.currentTarget.dataset.type,n=s.currentTarget.dataset.uuid;!n||!i||s.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:i,uuid:n}))},"itemDragStart"),a=e.find(".show-item");a.click(async s=>{let i=s.currentTarget.dataset.uuid;(await fromUuid(i)).sheet.render(!0)}),a.attr("draggable",!0).on("dragstart",s=>t(s)),e.on("click",".searchableAbility a",s=>yt(s)),e.find(".exclusive").change(s=>{let i=$(s.currentTarget).closest(".tab"),n=$(s.currentTarget).attr("data-sel"),r=i.find(`.allowedCount_${n}`),o=Number(r.attr("data-count"));if(i.find(`.exclusive_${n}:checked`).length>o){s.currentTarget.checked=!1,ne.flashElem(r);return}})}static flashElem(e,t="emphasize"){e.addClass(t),setTimeout(function(){e.removeClass(t)},600)}finalizeUpdate(){this.errors.length==0?this.close():$(this._element).find(".dialog-buttons").html(`

    ${game.i18n.localize("DSAError.notUnderstood")}

    • ${this.errors.join("
    • ")}
    `)}};u(ne,"WizardDSA5");var Qe=class extends ne{static get defaultOptions(){let e=super.defaultOptions;return e.title=game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.culture")}`}),e.template="systems/dsa5/templates/wizard/add-culture-wizard.html",e}activateListeners(e){super.activateListeners(e),e.find(".optional").change(t=>{let a=$(t.currentTarget).closest(".content"),s=Number(a.attr("data-cost"));a.find(".optional:checked").each(function(){s+=Number($(this).attr("data-cost"))});let i=a.find(".apCost");i.text(s),ne.flashElem(i,"emphasize2")})}async getData(e){let t=await super.getData(e),a=await this.parseToItem(this.culture.system.recommendedAdvantages.value,["advantage"]),s=await this.parseToItem(this.culture.system.recommendedDisadvantages.value,["disadvantage"]),i=this.culture.system.writing.value==""?[]:await this.parseToItem(this.culture.system.writing.value.split(",").map(o=>`${game.i18n.localize("LocalizedIDs.literacy")} (${o.trim()})`).join(", "),["specialability"]),n=this.culture.system.language.value==""?[]:await this.parseToItem(this.culture.system.language.value.split(",").map(o=>`${game.i18n.localize("LocalizedIDs.language")} (${o.trim()}) 3`).join(", "),["specialability"]),r=Number(this.culture.system.APValue.value);return mergeObject(t,{title:game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.culture")} ${this.culture.name}`}),culture:this.culture,description:game.i18n.format("WIZARD.culturedescr",{culture:this.culture.name,cost:r}),advantages:a,disadvantages:s,writings:i,languages:n,advantagesToChose:a.length>0,disadvantagesToChose:s.length>0,writingsToChose:i.length>0,languagesToChose:n.length>0,languagesToSelect:n.length>1,vantagesToChose:a.length>0||s.length>0,generalToChose:i.length>0||n.length>0,enrichedClothing:await TextEditor.enrichHTML(getProperty(this.culture.system,"clothing.value"),{secrets:!1,async:!0}),enrichedDescription:await TextEditor.enrichHTML(getProperty(this.culture.system,"description.value"),{secrets:!1,async:!0})}),t}async addCulture(e,t){this.actor=e,this.culture=t}_validateInput(e,t=this){let a=e.find(".localKnowledge");if(a.val()=="")return this._showInputValidation(a,e,t),!1;let s=e.find(".selectOnlyOne");return s.length&&s.find(".optional:checked").length!=1?(this._showInputValidation(s,e,t),!1):super._validateInput(e,t)}async updateCharacter(e,t=this){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");let a=Number(e.find(".apCost").text());if(!this._validateInput(e,t)||!await this.actor.checkEnoughXP(a)||await this.alreadyAdded(this.actor.system.details.culture.value,"culture")){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");return}let s={"system.details.culture.value":this.culture.name},i=await this.findCompendiumItem(`${game.i18n.localize("LocalizedIDs.localKnowledge")} ()`,["specialability"]);i&&(i=duplicate(i),i.name=`${game.i18n.localize("LocalizedIDs.localKnowledge")} (${e.find(".localKnowledge").val()})`,i.system.APValue.value=0,await this.actor.createEmbeddedDocuments("Item",[i],{render:!1})),await this.addSelections(e.find(".optional:checked"),!1),await this.actor._updateAPs(a,{},{render:!1}),await this.updateSkill(this.culture.system.skills.value.split(","),"skill"),await this.actor.update(s),await _.track(this.actor,{type:"item",item:this.culture,state:1},a),this.finalizeUpdate()}};u(Qe,"CultureWizard");var Xe=class extends ne{constructor(e){super(e),this.attributes=Object.keys(b.characteristics).map(t=>game.i18n.localize(`CHARAbbrev.${t.toUpperCase()}`))}static get defaultOptions(){let e=super.defaultOptions;return e.title=game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.career")}`}),e.template="systems/dsa5/templates/wizard/add-career-wizard.html",e}activateListeners(e){super.activateListeners(e),e.find(".optional").change(t=>{let a=$(t.currentTarget).closest(".content");if($(t.currentTarget).hasClass("exclusiveTricks")){let n=Number(a.find(".maxTricks").attr("data-spelltricklimit"));if(a.find(".exclusiveTricks:checked").length>n){t.currentTarget.checked=!1,ne.flashElem(a.find(".maxTricks"));return}}let s=Number(a.attr("data-cost"));a.find(".optional:checked").each(function(){s+=Number($(this).attr("data-cost"))}),a.find(".attributes:checked").each(function(){s+=Number($(this).attr("data-cost"))});let i=a.find(".apCost");i.text(s),ne.flashElem(i,"emphasize2")})}_validateInput(e,t=this){let a=e.find(".maxTricks"),s=Number(a.attr("data-spelltricklimit"))||0;return e.find(".exclusiveTricks:checked").length!=s?(this._showInputValidation(a,e,t),!1):super._validateInput(e,t)}async getData(e){let t=await super.getData(e),a=await this.parseToItem(this.career.system.requirements.value,["disadvantage","advantage","specialability"]),s=a.filter(h=>["advantage","disadvantage"].includes(h.type)&&!h.disabled),i=await this.parseToItem(this.career.system.recommendedAdvantages.value,["advantage"]);this.fixPreviousCosts(a,i);let n=await this.parseToItem(this.career.system.recommendedDisadvantages.value,["disadvantage"]);this.fixPreviousCosts(a,n);let r=a.filter(h=>h.attributeRequirement),o=this._parseAttributes(this.career.system.combatSkills.value,/,|;/),c=this._parseAttributes(this.career.system.specialAbilities.value),m=this._parseAttributes(this.career.system.spells.value),d=this._parseAttributes(this.career.system.liturgies.value),p=Number(this.career.system.APValue.value),g=a.reduce(function(h,w){return h+(w.disabled?0:Number(w.system.APValue.value)||0)},0),y=a.filter(h=>h.type=="specialability"&&!h.disabled);return mergeObject(t,{title:game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("career")} ${this.career.name}`}),career:this.career,description:game.i18n.format("WIZARD.careerdescr",{career:this.career.name,cost:p+g}),baseCost:p,advantages:i,disadvantages:n,missingVantages:s,specAbChoices:c,spellChoices:m,liturgyChoices:d,missingSpecialabilities:y,combatskillchoices:o,spelltricks:await this.parseToItem(this.career.system.spelltricks.value,["magictrick"]),attributeRequirements:r,advantagesToChose:i.length,disadvantagesToChose:n.length,vantagesToChose:i.length||n.length||s.length,missingVantagesToChose:s.length,missingSpecialabiltiesToChose:y.length,combatToChose:o.length,magicToChose:this.career.system.spelltrickCount.value||m.length,religionToChose:d.length,anyAttributeRequirements:r.length,generalToChose:y.length||r.length||c.length,enrichedClothing:await TextEditor.enrichHTML(getProperty(this.career.system,"clothing.value"),{secrets:!1,async:!0}),enrichedDescription:await TextEditor.enrichHTML(getProperty(this.career.system,"description.value"),{secrets:!1,async:!0})}),t}async addCareer(e,t){this.actor=e,this.career=t}async setAbility(e,t,a=[]){if(e.trim()=="")return;let s=[],i=[],n=game.i18n.localize("combatskillcountdivider")+":";for(let r of e.split(",").concat(a)){if(r.includes(n)||r=="")continue;let o=f.parseAbilityString(r.trim()),c=this.actor.items.find(m=>t.includes(m.type)&&m.name==o.original);if(c)c=duplicate(c),c.system.talentValue?c.system.talentValue.value=o.step:c.system.step&&(c.system.step.value=o.step),c=te.reverseAdoptionCalculation(this.actor,o,c),i.push(c);else if(c=await this.findCompendiumItem(o.original,t),c||(c=await this.findCompendiumItem(o.name,t)),c)c=duplicate(c),c.name=o.original,c.system.talentValue?c.system.talentValue.value=o.step:c.system.step&&(c.system.step.value=o.step),c=te.reverseAdoptionCalculation(this.actor,o,c),s.push(c);else{let m=t.map(d=>f.categoryLocalization(d)).join("/");this.errors.push(`${m}: ${r}`),ui.notifications.error(game.i18n.format("DSAError.notFound",{category:m,name:r}))}}await this.actor.updateEmbeddedDocuments("Item",i,{render:!1}),await this.actor.createEmbeddedDocuments("Item",s,{render:!1})}async addBlessing(e,t){let a=[];for(let s of e){let i=s.trim();if(i=="")continue;let n=this.actor.items.find(r=>t==r.type&&r.name==i);n||(n=await this.findCompendiumItem(i,[t]),n?(n=duplicate(n),a.push(n)):(this.errors.push(`${f.categoryLocalization(t)}: ${s}`),ui.notifications.error(game.i18n.format("DSAError.notFound",{category:game.i18n.localize(t),name:i}))))}await this.actor.createEmbeddedDocuments("Item",a,{render:!1})}getExclusiveChoices(e,t){let a=[];for(let s of e.find(`${t}.exclusive:checked`))a.push($(s).val());return a}async updateCharacter(e,t=this){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");let a=Number(e.find(".apCost").text());if(!this._validateInput(e,t)||!await this.actor.checkEnoughXP(a)||await this.alreadyAdded(this.actor.system.details.career.value,"career")){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");return}let s={"system.details.career.value":this.career.name,"system.freeLanguagePoints.value":this.career.system.languagePoints.value};for(let n of e.find(".attributes")){let r=$(n).attr("data-attribute").toLowerCase();r=game.dsa5.config.knownShortcuts[r.toLowerCase()][1],Number(this.actor.system.characteristics[r].initial)+Number(this.actor.system.characteristics[r].advances)!(n.includes(game.i18n.localize("combatskillcountdivider")+":")||n==""));await this.updateSkill(i,"combatskill",1,!1),await this.actor.update(s),await _.track(this.actor,{type:"item",item:this.career,state:1},a),this.finalizeUpdate()}};u(Xe,"CareerWizard");var Ze=class extends ne{static get defaultOptions(){let e=super.defaultOptions;return e.title=game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.species")}`}),e.template="systems/dsa5/templates/wizard/add-species-wizard.html",e}activateListeners(e){super.activateListeners(e),e.find(".optional").change(t=>{let a=$(t.currentTarget).closest(".content"),s=Number(a.attr("data-cost"));a.find(".optional:checked").each(function(){s+=Number($(this).attr("data-cost"))});let i=a.find(".apCost");i.text(s),ne.flashElem(i,"emphasize2")})}async _toGroups(e,t,a){return await Promise.all(e.split(` +`).map(async i=>{let n=i.split(":"),r;return n.length>1?r={name:n[0].trim(),res:await this.parseToItem(n[1].trim(),t)}:r={name:"",res:await this.parseToItem(i,t)},this.fixPreviousCosts(a,r.res),r}))}async getData(e){let t=await super.getData(e),a=await this.parseToItem(this.species.system.requirements.value,["disadvantage","advantage"]),s=a.filter(m=>["advantage","disadvantage"].includes(m.type)&&!m.disabled),i=await this._toGroups(this.species.system.recommendedAdvantages.value,["advantage"],a),n=await this._toGroups(this.species.system.recommendedDisadvantages.value,["disadvantage"],a),r=this._parseAttributes(this.species.system.attributeChange.value),o=Number(this.species.system.APValue.value),c=a.reduce(function(m,d){return m+(d.disabled?0:Number(d.system.APValue.value)||0)},0);return mergeObject(t,{title:game.i18n.format("WIZARD.addItem",{item:`${game.i18n.localize("TYPES.Item.species")} ${this.species.name}`}),species:this.species,description:game.i18n.format("WIZARD.speciesdescr",{species:this.species.name,cost:o+c}),advantagegroups:i,baseCost:o,disadvantagegroups:n,missingVantages:s,attributeRequirements:r,hasLocalization:game.i18n.has(`Racedescr.${this.species.name}`),anyAttributeRequirements:r.length>0,advantagesToChose:i.length>0,missingVantagesToChose:s.length>0,disadvantagesToChose:n.length>0,vantagesToChose:i.length>0||n.length>0||s.length>0,generalToChose:r.length>0}),t}async addSpecies(e,t){this.actor=e,this.species=t}async updateCharacter(e,t=this){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");let a=Number(e.find(".apCost").text());if(!this._validateInput(e,t)||!await this.actor.checkEnoughXP(a)||await this.alreadyAdded(this.actor.system.details.species.value,"species")){e.find("button.ok i").toggleClass("fa-check fa-spinner fa-spin");return}let s={"system.details.species.value":this.species.name,"system.status.speed.initial":this.species.system.baseValues.speed.value,"system.status.soulpower.initial":this.species.system.baseValues.soulpower.value,"system.status.toughness.initial":this.species.system.baseValues.toughness.value,"system.status.wounds.initial":this.species.system.baseValues.wounds.value,"system.status.wounds.value":this.species.system.baseValues.wounds.value+this.actor.system.characteristics.ko.value*2},i=[];for(let n of e.find(".exclusive:checked"))i.push($(n).val());Object.keys(b.characteristics).forEach(n=>{s[`system.characteristics.${n}.species`]=0});for(let n of this.species.system.attributeChange.value.split(",").concat(i)){if(n.includes(game.i18n.localize("combatskillcountdivider")+":")||n=="")continue;let r=n.trim().split(" "),o=game.dsa5.config.knownShortcuts[r[0].toLowerCase().trim()].slice(0);o[o.length-1]="species",s[`system.${o.join(".")}`]=Number(r[1])}await this.actor._updateAPs(a,{},{render:!1}),await this.addSelections(e.find(".optional:checked"),!1),await this.actor.update(s),await this.actor.removeCondition("incapacitated"),await _.track(this.actor,{type:"item",item:this.species,state:1},a),this.finalizeUpdate()}};u(Ze,"SpeciesWizard");var be=class extends $e{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","actor","character-sheet"]),width:784}),e}get template(){return this.showLimited()?"systems/dsa5/templates/actors/npc-limited.html":"systems/dsa5/templates/actors/actor-sheet.html"}async _manageDragItems(e,t){switch(t){case"aggregatedTest":await this.actor.createEmbeddedDocuments("Item",[e]);break;case"species":let a=new Ze;await a.addSpecies(this.actor,e),a.render(!0);break;case"culture":let s=new Qe;await s.addCulture(this.actor,e),s.render(!0);break;case"career":let i=new Xe;await i.addCareer(this.actor,e),i.render(!0);break;default:return super._manageDragItems(e,t)}}};u(be,"ActorSheetdsa5Character");var Oe=class extends $e{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","actor","creature-sheet"])}),e}get template(){return this.showLimited()?"systems/dsa5/templates/actors/creature-limited.html":"systems/dsa5/templates/actors/creature-sheet.html"}async getData(e){let t=await super.getData(e);return t.enrichedDescription=await TextEditor.enrichHTML(getProperty(this.actor.system,"description.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedBehaviour=await TextEditor.enrichHTML(getProperty(this.actor.system,"behaviour.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedFlight=await TextEditor.enrichHTML(getProperty(this.actor.system,"flight.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedSpecialrules=await TextEditor.enrichHTML(getProperty(this.actor.system,"specialRules.value"),{secrets:this.object.isOwner,async:!0}),t}async _cleverDeleteItem(e){let t=this.actor.items.find(a=>a.id==e);switch(t.type){case"trait":let a=t.system.APValue.value*-1;await this._updateAPs(a,{},{render:!1}),await _.track(actor,{type:"item",item:t,state:-1},a);break}await super._cleverDeleteItem(e)}async _addTrait(e){if(!this.actor.items.find(a=>a.type=="trait"&&a.name==e.name)){await this._updateAPs(e.system.APValue.value,{},{render:!1}),await ue.traitAdded(this.actor,e);let a=(await this.actor.createEmbeddedDocuments("Item",[e]))[0];await _.track(actor,{type:"item",item:a,state:1},e.system.APValue.value)}}async _onDropItemCreate(e){return e.type=="trait"?this._addTrait(e):super._onDropItemCreate(e)}};u(Oe,"ActorSheetdsa5Creature");var ze=class extends be{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","actor","npc-sheet"])}),e}get template(){return this.showLimited()?"systems/dsa5/templates/actors/npc-limited.html":"systems/dsa5/templates/actors/npc-sheet.html"}};u(ze,"ActorSheetdsa5NPC");var et=u(l=>class extends l{async obfuscateItem(e){e.stopPropagation(),e.preventDefault();let t=e.currentTarget.dataset.obfuscate;await this.item.update({[`system.obfuscation.${t}`]:!this.isObfuscated(t)})}isObfuscated(e){return getProperty(this.item,`system.obfuscation.${e}`)}activateListeners(e){super.activateListeners(e),e.on("click",".obfuscateSection",t=>this.obfuscateItem(t))}obfuscationCss(e){return this.isObfuscated(e)?"":" pale"}async _render(e=!1,t={}){await super._render(e,t);let a=["details","effects","description","enchantment"],s=!1;for(let i of a){let n=$(this._element).find(`nav [data-tab="${i}"]`);if(!n.length)continue;let r=t.tabsinvisible||this.isObfuscated(i),o=game.i18n.localize(`SHEET.${r?"deobfuscateItem":"obfuscateItem"}`);if(game.user.isGM){let c=`obfuscateSection${this.obfuscationCss(i)}`,m=n.find(`.${c}`),d=``;m.length?m.replaceWith(d):n.append(` ${d}`)}else r&&(n.hasClass("active")&&(s=!0),n.remove(),i=="details"&&$(this._element).find('[name="system.price.value"],[name="system.price.raw"]').replaceWith(""))}if(s){let i=$(this._element).find("nav .item:first-child");if(i.length)this.activateTab(i.attr("data-tab"));else{let n=await renderTemplate("systems/dsa5/templates/items/obfuscatedItem.html",{item:this.item});$(this._element).find(".content").html(n)}}}},"ItemSheetObfuscation");var Y=class extends ItemSheet{_getSubmitData(e={}){let t=super._getSubmitData(e),a=foundry.utils.flattenObject(this.item.overrides||{});return Object.keys(a).forEach(s=>delete t[s]),t}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{tabs:[{navSelector:".tabs",contentSelector:".content"}],classes:e.classes.concat(["dsa5","item"]),width:471,height:500}),e}static setupSheets(){Items.unregisterSheet("core",ItemSheet),Items.registerSheet("dsa5",Y,{makeDefault:!0}),Items.registerSheet("dsa5",zs,{makeDefault:!0,types:["species"]}),Items.registerSheet("dsa5",Cs,{makeDefault:!0,types:["career"]}),Items.registerSheet("dsa5",Ds,{makeDefault:!0,types:["culture"]}),Items.registerSheet("dsa5",Ns,{makeDefault:!0,types:["advantage","disadvantage"]}),Items.registerSheet("dsa5",xs,{makeDefault:!0,types:["ritual","ceremony","liturgy","spell"]}),Items.registerSheet("dsa5",Os,{makeDefault:!0,types:["specialability"]}),Items.registerSheet("dsa5",Es,{makeDefault:!0,types:["meleeweapon"]}),Items.registerSheet("dsa5",$s,{makeDefault:!0,types:["poison"]}),Items.registerSheet("dsa5",Ms,{makeDefault:!0,types:["disease"]}),Items.registerSheet("dsa5",As,{makeDefault:!0,types:["consumable"]}),Items.registerSheet("dsa5",Ps,{makeDefault:!0,types:["spellextension"]}),Items.registerSheet("dsa5",Is,{makeDefault:!0,types:["magictrick"]}),Items.registerSheet("dsa5",Ss,{makeDefault:!0,types:["blessing"]}),Items.registerSheet("dsa5",Ts,{makeDefault:!0,types:["rangeweapon"]}),Items.registerSheet("dsa5",ys,{makeDefault:!0,types:["equipment"]}),Items.registerSheet("dsa5",bs,{makeDefault:!0,types:["armor"]}),Items.registerSheet("dsa5",hs,{makeDefault:!0,types:["ammunition"]}),Items.registerSheet("dsa5",ks,{makeDefault:!0,types:["plant"]}),Items.registerSheet("dsa5",vs,{makeDefault:!0,types:["magicalsign"]}),Items.registerSheet("dsa5",ws,{makeDefault:!0,types:["patron"]}),Items.registerSheet("dsa5",fs,{makeDefault:!0,types:["information"]}),Items.registerSheet("dsa5",gs,{makeDefault:!0,types:["aggregatedTest"]}),Items.unregisterSheet("dsa5",Y,{types:["armor","equipment","rangeweapon","blessing","magictrick","spellextension","consumable","aggregatedTest","species","career","culture","advantage","specialability","disadvantage","ritual","information","ceremony","liturgy","spell","disease","poison","meleeweapon","ammunition","plant","magicalsign","patron"]})}async _render(e=!1,t={}){await super._render(e,t),$(this._element).find(".close").attr("data-tooltip","SHEET.Close"),$(this._element).find(".configure-sheet").attr("data-tooltip","SHEET.Configure"),$(this._element).find(".import").attr("data-tooltip","SHEET.Import"),$(this._element).find(".rolleffect").attr("data-tooltip","SHEET.RollEffect"),$(this._element).find(".showItemHead").attr("data-tooltip","SHEET.PostItem"),$(this._element).find(".consumeItem").attr("data-tooltip","SHEET.ConsumeItem"),$(this._element).find(".rollDamaged").attr("data-tooltip","DSASETTINGS.armorAndWeaponDamage"),$(this._element).find(".onUseEffect").attr("data-tooltip","SHEET.onUseEffect"),$(this._element).find(".postAsGroupCheck").attr("data-tooltip","SHEET.postAsGroupCheck")}_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"showItemHead",icon:"fas fa-comment",onclick:async()=>this.item.postItem()}),this.item.actor&&X.getOnUseEffect(this.item)&&e.unshift({class:"onUseEffect",icon:"fas fa-dice-six",onclick:async()=>{new X(this.item).executeOnUseEffect()}}),e}setupEffect(e){this.item.setupEffect().then(t=>this.item.itemTest(t))}get template(){return`systems/dsa5/templates/items/item-${this.item.type}-sheet.html`}_getItemId(e){return $(e.currentTarget).parents(".item").attr("data-item-id")}_advanceStep(){}_refundStep(){}async advanceWrapper(e,t){let s=$(e.currentTarget).find("i");s.hasClass("fa-spin")||(s.addClass("fa-spin fa-spinner"),await this[t](),s.removeClass("fa-spin fa-spinner"))}activateListeners(e){super.activateListeners(e),oe(e),e.find(".advance-step").mousedown(a=>this.advanceWrapper(a,"_advanceStep")),e.find(".refund-step").mousedown(a=>this.advanceWrapper(a,"_refundStep")),e.find(".domainsPretty").click(a=>{$(a.currentTarget).hide(),$(a.currentTarget).next(".domainToggle").show()}),e.find('[data-edit="img"]').mousedown(a=>{a.button==2&&f.showArtwork(this.item)}),e.find(".status-add").click(()=>{E.createCustomEffect(this.item,"",this.item.name)}),e.find(".condition-show").mousedown(a=>{a.preventDefault();let s=a.currentTarget.dataset.id;a.button==0?this.item.effects.get(s).sheet.render(!0):a.button==2&&this.item.deleteEmbeddedDocuments("ActiveEffect",[s])}),e.find(".select2").select2(),e.find(".condition-toggle").mousedown(a=>{let s=$(a.currentTarget).parents(".statusEffect").attr("data-id"),i=this.item.effects.get(s);i.update({disabled:!i.disabled})}),e.find(".condition-edit").click(a=>{this.item.effects.get(a.currentTarget.dataset.id).sheet.render(!0)}),se.bindRollCommands(e),E.bindButtons(e);let t=e.find(".item-header");if(t.length){let a=t.find("svg");if(a){new ResizeObserver(function(n){let r=n[0];Si(a,r.contentRect.width)}).observe(t.get(0));let i=t.find("input");i.get(0).disabled||(a.click(()=>{a.hide(),i.show(),i.focus()}),i.blur(function(){a.show(),i.hide()}))}}}async getData(e){let t=super.getData(e).data;switch(this.item.type){case"skill":t.characteristics=b.characteristics,t.skillGroups=b.skillGroups,t.skillBurdens=b.skillBurdens,t.hasLocalization=game.i18n.has(`SKILLdescr.${this.item.name}`),t.StFs=b.StFs;break;case"application":t.hasLocalization=game.i18n.has(`APPLICATION.${this.item.system.skill} - ${this.item.name}`),t.localization=game.i18n.localize(`APPLICATION.${this.item.system.skill} - ${this.item.name}`),t.allSkills=await f.allSkillsList();break;case"combatskill":t.weapontypes=b.weapontypes,t.guidevalues=b.combatskillsGuidevalues,t.hasLocalization=game.i18n.has(`Combatskilldescr.${this.item.name}`),t.StFs=b.StFs;break;case"trait":t.traitCategories=b.traitCategories,t.ranges=b.meleeRanges;break}if(t.isOwned=this.item.actor,t.editable=this.isEditable,t.isOwned){t.canAdvance=this.item.actor.canAdvance&&this._advancable();let a=getProperty(this.item,"flags.dsa5.customPriceTag");!this.isEditable&&a&&(t.customPrice=a)}return E.prepareActiveEffects(this.item,t),t.item=this.item,t.armorAndWeaponDamage=game.settings.get("dsa5","armorAndWeaponDamage"),t.isGM=game.user.isGM,t.enrichedDescription=await TextEditor.enrichHTML(getProperty(this.item.system,"description.value"),{secrets:this.object.isOwner,async:!0}),t.enrichedGmdescription=await TextEditor.enrichHTML(getProperty(this.item.system,"gmdescription.value"),{secrets:this.object.isOwner,async:!0}),t}_advancable(){return!1}};u(Y,"ItemSheetdsa5");var gs=class extends Y{async getData(e){let t=await super.getData(e),a=this.item.getFlag("dsa5","embeddedItem"),s;return a&&(s=await renderTemplate(`systems/dsa5/templates/items/browse/${a.type}.html`,{document:a})),mergeObject(t,{allSkills:await f.allSkillsList(),embeddedItem:a,renderedItem:s,enrichedsuccess:await TextEditor.enrichHTML(this.item.system.success,{secrets:this.item.isOwner,async:!0}),enrichedpartsuccess:await TextEditor.enrichHTML(this.item.system.partsuccess,{secrets:this.item.isOwner,async:!0})}),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned||e.unshift({class:"postAsGroupCheck",icon:"fas fa-dice-d20",onclick:async()=>this.postAsGroupCheck()}),e}async postAsGroupCheck(){let e=["value","value2","value3"].filter(a=>this.item.system.talent[a]).map(a=>({type:"skill",modifier:this.item.system.baseModifier,calculatedModifier:this.item.system.baseModifier,target:this.item.system.talent[a]}));if(!e.length)return;let t={modifier:this.item.system.baseModifier,maxRolls:this.item.system.allowedTestCount.value,enrichedsuccess:await TextEditor.enrichHTML(this.item.system.success,{secrets:this.item.isOwner,async:!0}),enrichedpartsuccess:await TextEditor.enrichHTML(this.item.system.partsuccess,{secrets:this.item.isOwner,async:!0}),rollOptions:e};q.showGCMessage(e[0].target,0,t)}activateListeners(e){super.activateListeners(e),e.find(".buildItem").click(async()=>this.postFinishedItem())}async postFinishedItem(){if(!this.item.actor)return;let e=this.item.getFlag("dsa5","embeddedItem");if(!e)return;let t=await renderTemplate("systems/dsa5/templates/chat/production-result.html",{actor:this.item.actor,item:e,actorImg:j.videoOrImgTag(this.item.actor.img)}),a=f.chatDataSetup(t);a.flags={dsa5:{embeddedItem:e}},await ChatMessage.create(a)}};u(gs,"AggregatedTestSheet");var tt=class extends Y{async _onDrop(e){await this.enchant(e),this.isPoisonable&&await this.poison(e)}async enchant(e){let t=JSON.parse(e.dataTransfer.getData("text/plain"));await this._enchant([t])}async _enchant(e){let t=this.item.getFlag("dsa5","enchantments")||[];if(t.length+e.length>7)return ui.notifications.error(game.i18n.localize("DSAError.tooManyEnchants"));for(let a of e){let{item:s,typeClass:i,selfTarget:n}=await Ge(a,void 0,!1);if(["spell","liturgy","ceremony","ritual"].includes(i)){if(!s.pack)return ui.notifications.error(game.i18n.localize("DSAError.onlyCompendiumSpells"));let r={name:s.name,pack:s.pack,id:t.length,itemId:s.id,permanent:["liturgy","ceremony"].includes(i)||a.permanent,actorId:a.actorId,charged:!0,talisman:["liturgy","ceremony"].includes(i),fw:["liturgy","ceremony"].includes(i)?18:a.fw||0};t.push(r)}}if(t.length){let a={flags:{dsa5:{enchantments:t}}};await this.item.update(a)}}async poison(e){let t=JSON.parse(e.dataTransfer.getData("text/plain")),{item:a,typeClass:s,selfTarget:i}=await Ge(t,void 0,!1);if(s=="poison"){let r={flags:{dsa5:{poison:{name:a.name,pack:a.pack,itemId:a._id,permanent:!1,actorId:t.actorId}}}};await this.item.update(r)}}toggleChargedState(e,t){for(let a of t)if(a.id==e){a.charged=a.talisman&&a.permanent?!0:!a.charged;break}this.item.update({flags:{dsa5:{enchantments:t}}})}activateListeners(e){super.activateListeners(e),e.find(".ench-toggle-permanent").click(t=>{let{id:a,enchantments:s}=this.enchantMentId(t);for(let i of s)if(i.id==a){i.permanent=!i.permanent;break}this.item.update({flags:{dsa5:{enchantments:s}}})}),e.find(".ench-toggle-charge").click(t=>{let{id:a,enchantments:s}=this.enchantMentId(t);this.toggleChargedState(a,s)}),e.find(".ench-roll").click(async t=>{let{id:a,enchantments:s}=this.enchantMentId(t),i=s.find(r=>r.id==a);if(!i.charged)return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughCharges"));let n=await this.getSpell(i);if(n){n=n.toObject(),n.system.talentValue.value=i.fw;let r=await f.emptyActor(14,this.item.name);r.setupSpell(n,{},"emptyActor").then(async o=>{let c=game.i18n.format("CHATNOTIFICATION.enchantmentUsed",{item:this.item.name,spell:n.name});await ChatMessage.create(f.chatDataSetup(c)),await r.basicTest(o),i.permanent?this.toggleChargedState(a,s):this.deleteEnchantment(a,s)})}}),e.find(".ench-fw").change(t=>{let{id:a,enchantments:s}=this.enchantMentId(t),i=Number($(t.currentTarget).val());if(!!i){for(let n of s)if(n.id==a){n.fw=i;break}this.item.update({flags:{dsa5:{enchantments:s}}})}}),e.find(".ench-delete").click(t=>{let{id:a,enchantments:s}=this.enchantMentId(t);this.deleteEnchantment(a,s)}),e.find(".ench-show").click(async t=>{let{id:a,enchantments:s}=this.enchantMentId(t),i=s.find(r=>r.id==a),n=await this.getSpell(i);n&&n.sheet.render(!0)}),e.find(".poison-toggle-permanent").click(t=>{this.item.update({flags:{dsa5:{poison:{permanent:!this.item.flags.dsa5.poison.permanent}}}})}),e.find(".poison-delete").click(t=>{this.deletePoison()}),e.find(".poison-show").click(async()=>{let t;this.item.actor&&(t=this.item.actor.items.find(a=>a.type=="poison"&&a.name==this.item.flags.dsa5.poison.name)),t||(t=await this.getSpell(this.item.flags.dsa5.poison)),t&&t.sheet.render(!0)})}deletePoison(){this.item.update({["flags.dsa5.-=poison"]:null})}deleteEnchantment(e,t){let a=t.findIndex(s=>s.id==e);t.splice(a,1),this.item.update({flags:{dsa5:{enchantments:t}}})}async getSpell(e){let t=await game.packs.get(e.pack);if(!t){ui.notifications.error(game.i18n.localize("DSAError.enchantmentNotFound"));return}let a=await t.getDocument(e.itemId);if(!a){let s=await t.index.getName(e.name);s&&(a=await t.getDocument(s._id))}return a||ui.notifications.error(game.i18n.localize("DSAError.enchantmentNotFound")),a}enchantMentId(e){return{id:$(e.currentTarget).parents(".statusEffect").attr("data-id"),enchantments:this.item.getFlag("dsa5","enchantments")}}prepareDomains(){let e=getProperty(this.item.system,"effect.attributes");if(e){let t=new RegExp(game.i18n.localize("WEAPON.magical"),"i"),a=new RegExp(game.i18n.localize("WEAPON.clerical"),"i");e=e.split(",").map(s=>{let i="";return t.test(s)?i="magical":a.test(s)&&(i="blessed"),`
  • ${s}
  • `}).join("")}return e}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{dragDrop:[{dragSelector:".item-list .item",dropSelector:".content"}]}),e}_canDragDrop(e){return this.isEditable}async getData(e){let t=await super.getData(e);t.enchantments=this.item.getFlag("dsa5","enchantments");let a=[];return t.poison=this.item.getFlag("dsa5","poison"),t.poison&&a.push("poison"),t.enchantments&&t.enchantments.some(s=>!s.talisman)&&a.push("enchantment"),t.enchantments&&t.enchantments.some(s=>s.talisman)&&a.push("talisman"),t.enchantmentLabel=a.map(s=>game.i18n.localize(s)).join("/"),t.traditionArtifacts=b.traditionArtifacts,t.hasEnchantments=t.poison||t.enchantments&&t.enchantments.length>0,t}};u(tt,"Enchantable");var fs=class extends Y{async getData(e){let t=await super.getData(e);return mergeObject(t,{allSkills:await f.allSkillsList(),enrichedqs1:await TextEditor.enrichHTML(this.item.system.qs1,{async:!0}),enrichedqs2:await TextEditor.enrichHTML(this.item.system.qs2,{async:!0}),enrichedqs3:await TextEditor.enrichHTML(this.item.system.qs3,{async:!0}),enrichedqs4:await TextEditor.enrichHTML(this.item.system.qs4,{async:!0}),enrichedqs5:await TextEditor.enrichHTML(this.item.system.qs5,{async:!0}),enrichedqs6:await TextEditor.enrichHTML(this.item.system.qs6,{async:!0}),enrichedCrit:await TextEditor.enrichHTML(this.item.system.crit,{async:!0}),enrichedBotch:await TextEditor.enrichHTML(this.item.system.botch,{async:!0}),enrichedFail:await TextEditor.enrichHTML(this.item.system.fail,{async:!0})}),t}};u(fs,"InformationSheet");var hs=class extends tt{constructor(e,t){super(e,t),this.isPoisonable=!0}async getData(e){let t=await super.getData(e);return t.ammunitiongroups=b.ammunitiongroups,t.domains=this.prepareDomains(),t}};u(hs,"AmmunitionSheet");var ys=class extends et(tt){async getData(e){let t=await super.getData(e);if(mergeObject(t,{equipmentTypes:b.equipmentTypes,domains:this.prepareDomains(),canOnUseEffect:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro")}),this.isBagWithContents()){let a=0;mergeObject(t,{containerContent:this.item.actor.items.filter(s=>b.equipmentCategories.has(s.type)&&s.system.parent_id==this.item.id).map(s=>{s.system.preparedWeight=parseFloat((s.system.weight.value*s.system.quantity.value).toFixed(3)),a+=Number(s.system.preparedWeight);let i=getProperty(s,"flags.dsa5.enchantments");return i&&i.length>0?s.enchantClass="rar":(s.system.effect&&s.system.effect.value!=""||s.effects.length>0)&&(s.enchantClass="common"),s}),weightSum:parseFloat(a.toFixed(3)),weightWidth:`style="width: ${Math.min(this.item.system.capacity?a/this.item.system.capacity*100:0,100)}%"`,weightExceeded:a>Number(this.item.system.capacity)?"exceeded":""})}return t}async breakOverflow(e,t){let a=$(await renderTemplate("systems/dsa5/templates/items/baghover.html",e)),s=t.offset().top+52,i=t.offset().left-75;return a.appendTo($("body")),a.css({position:"absolute",left:i+"px",top:s+"px",bottom:"auto",right:"auto","z-index":1e4}),a}activateListeners(e){super.activateListeners(e);let t=e.find(".slot");t.mouseenter(async a=>{let s=$(a.currentTarget),i=await this.breakOverflow({name:s.attr("data-name"),weight:s.attr("data-weight"),quantity:s.attr("data-quantity")},s);i.fadeIn(),s.mouseleave(()=>{i.remove(),s.off("mouseleave")})}),t.mousedown(async a=>{let s=a.currentTarget.dataset.itemId,i=this.actor.items.get(s);a.button==0?i.sheet.render(!0):a.button==2&&($(".itemInfo").remove(),await i.update({"system.parent_id":0}),this.render(!0))})}isBagWithContents(){return this.item.actor&&getProperty(this.item,"system.equipmentType.value")=="bags"}async _onDrop(e){if(this.isBagWithContents()){let t=JSON.parse(e.dataTransfer.getData("text/plain")),{item:a,typeClass:s,selfTarget:i}=await Ge(t,void 0),n=this.item.id==a.id,r=this.item.parent.id==t.actorId;if(b.equipmentCategories.has(s)&&!n){a.system.parent_id=this.item.id,a.system.worn&&a.system.worn.value&&(a.system.worn.value=!1),r?await this.item.actor.updateEmbeddedDocuments("Item",[a]):await this.item.actor.sheet._addLoot(a),this.render(!0);return}}await super._onDrop(e)}};u(ys,"EquipmentSheet");var bs=class extends et(tt){async getData(e){let t=await super.getData(e);return mergeObject(t,{domains:this.prepareDomains(),armorSubcategories:Object.keys(b.armorSubcategories),breakPointRating:b.armorSubcategories[this.item.system.subcategory]}),t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&game.settings.get("dsa5","armorAndWeaponDamage")&&this.item.system.structure.max>0&&e.unshift({class:"rollDamaged",icon:"fas fa-dice-d20",onclick:async()=>W.breakingTest(this.item)}),e}};u(bs,"ArmorSheet");var ks=class extends et(Y){async getData(e){let t=await super.getData(e);return t.attributes=Object.keys(t.system.planttype).map(a=>({name:a,checked:t.system.planttype[a]})),t.enrichedEffect=await TextEditor.enrichHTML(getProperty(this.item.system,"effect"),{secrets:this.object.isOwner,async:!0}),t.enrichedRecipes=await TextEditor.enrichHTML(getProperty(this.item.system,"recipes"),{secrets:this.object.isOwner,async:!0}),t.enrichedInformation=await TextEditor.enrichHTML(getProperty(this.item.system,"infos"),{secrets:this.object.isOwner,async:!0}),t}};u(ks,"PlantSheet");var ws=class extends Y{async getData(e){let t=await super.getData(e);return t.patronCategories=[0,1,2,3].map(a=>({name:game.i18n.localize(`PATRON.${a}`),val:a})),t.priorities={0:game.i18n.localize("PATRON.primary"),1:game.i18n.localize("PATRON.secondary")},t}};u(ws,"PatronSheet");var vs=class extends Y{async getData(e){let t=await super.getData(e);return t.categories={1:game.i18n.localize("TYPES.Item.magicalsign"),2:game.i18n.localize("additionalsign")},t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async setupEffect(e){let t=Number(this.item.system.asp)||0;if(this.item.actor.system.status.astralenergy.valuer.type=="skill"&&r.name==game.i18n.localize("LocalizedIDs.artisticAbility")),n=`

    ${this.item.name}

    ${this.item.system.description.value}

    ${s.chatData(this.item.system,"").join("
    ")}

    `;a.setupSkill(i,{other:[n],subtitle:` (${game.i18n.localize("TYPES.Item.magicalsign")})`},void 0).then(async r=>{let o=await a.basicTest(r,{suppressMessage:!0});o.result.preData.calculatedSpellModifiers={finalcost:t,costsMana:!0},await _DiceDSA5.renderRollCard(o.cardOptions,o.result,o.options.rerenderMessage)})}};u(vs,"MagicalSignSheet");var Ts=class extends et(tt){_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&game.settings.get("dsa5","armorAndWeaponDamage")&&this.item.system.structure.max>0&&e.unshift({class:"rollDamaged",icon:"fas fa-dice-d20",onclick:async()=>W.breakingTest(this.item)}),e}async getData(e){let t=await super.getData(e);return mergeObject(t,{canOnUseEffect:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),ammunitiongroups:b.ammunitiongroups,combatskills:await f.allCombatSkillsList("range"),domains:this.prepareDomains(),breakPointRating:b.weaponStabilities[game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`)]}),t}};u(Ts,"RangeweaponSheet");var Ss=class extends Y{_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}async setupEffect(e){if(this.item.actor.system.status.karmaenergy.value<1)return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughKaP"));let t=game.dsa5.config.ItemSubclasses.magictrick;await this.item.actor.update({"system.status.karmaenergy.value":this.item.actor.system.status.karmaenergy.value-=1});let a=`

    ${this.item.name} - ${game.i18n.localize("blessing")} ${game.i18n.localize("probe")}

    ${this.item.system.description.value}

    ${t.chatData(this.item.system,"").join("
    ")}

    `;await ChatMessage.create(f.chatDataSetup(a))}};u(Ss,"BlessingSheetDSA5");var Cs=class extends Y{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,height:700}),e}async getData(e){let t=await super.getData(e),a=duplicate(b.characteristics);return a["-"]="-",t.mageLevels=b.mageLevels,t.guidevalues=a,t.enrichedClothing=await TextEditor.enrichHTML(getProperty(this.item.system,"clothing.value"),{secrets:this.object.isOwner,async:!0}),t}};u(Cs,"ItemCareerDSA5");var As=class extends et(Y){static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:480}),e}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"consumeItem",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.calculatedPrice=C.getSubClass(this.item.type).consumablePrice(this.item),t.availableSteps=t.system.QLList.split(` +`).map((a,s)=>s+1),t.equipmentTypes=b.equipmentTypes,t.enrichedIngredients=await TextEditor.enrichHTML(getProperty(this.item.system,"ingredients"),{secrets:this.object.isOwner,async:!0}),t}setupEffect(e){this.item.setupEffect()}};u(As,"ConsumableSheetDSA5");var Ds=class extends Y{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:700,height:700}),e}async getData(e){let t=await super.getData(e);return t.enrichedClothing=await TextEditor.enrichHTML(getProperty(this.item.system,"clothing.value"),{secrets:this.object.isOwner,async:!0}),t}};u(Ds,"ItemCultureDSA5");var Ms=class extends Y{_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.resistances=b.magicResistanceModifiers,t}};u(Ms,"DiseaseSheetDSA5");var Is=class extends Y{_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}async setupEffect(e){if(this.item.actor.system.status.astralenergy.value<1)return ui.notifications.error(game.i18n.localize("DSAError.NotEnoughAsP"));let t=game.dsa5.config.ItemSubclasses.magictrick;await this.item.actor.update({"system.status.astralenergy.value":this.item.actor.system.status.astralenergy.value-=1});let a=`

    ${this.item.name} - ${game.i18n.localize("magictrick")} ${game.i18n.localize("probe")}

    ${this.item.system.description.value}

    ${t.chatData(this.item.system,"").join("
    ")}

    `;await ChatMessage.create(f.chatDataSetup(a))}};u(Is,"MagictrickSheetDSA5");var Es=class extends et(tt){constructor(e,t){super(e,t),this.isPoisonable=!0}async getData(e){let t=await super.getData(e),a=mergeObject(duplicate(b.characteristics),{"ge/kk":game.i18n.localize("CHAR.GEKK"),["-"]:"-"}),s=P.regex2h.test(this.item.name),i="";if(!s)i="wrongGrip.yieldTwo";else switch(game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`)){case"Two-Handed Impact Weapons":case"Two-Handed Swords":new RegExp(game.i18n.localize("wrongGrip.wrongGripBastardRegex")).test(this.item.name)?i="wrongGrip.yieldOneBastard":i="wrongGrip.yieldOneSwordBlunt";break;default:i="wrongGrip.yieldOnePolearms"}if(mergeObject(t,{characteristics:a,twoHanded:s,wrongGripLabel:s?"wrongGrip.oneHanded":"wrongGrip.twoHanded",wrongGripHint:i,combatskills:await f.allCombatSkillsList("melee"),ranges:b.meleeRanges,shieldSizes:b.shieldSizes,isShield:P.isShield(this.item),domains:this.prepareDomains(),breakPointRating:b.weaponStabilities[game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`)]}),this.item.actor){let n=this.item.actor.items.find(r=>r.type=="combatskill"&&r.name==this.item.system.combatskill.value);t.canBeOffHand=n&&!n.system.weapontype.twoHanded&&this.item.system.worn.value,t.canBeWrongGrip=!["Daggers","Fencing Weapons"].includes(game.i18n.localize(`LocalizedCTs.${this.item.system.combatskill.value}`))}return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}_getHeaderButtons(){let e=super._getHeaderButtons();return this.item.isOwned&&game.settings.get("dsa5","armorAndWeaponDamage")&&this.item.system.structure.max>0&&e.unshift({class:"rollDamaged",icon:"fas fa-dice-d20",onclick:async()=>W.breakingTest(this.item)}),e}};u(Es,"MeleeweaponSheetDSA5");var $s=class extends et(Y){_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"rolleffect",icon:"fas fa-dice-d20",onclick:async t=>this.setupEffect(t)}),e}async getData(e){let t=await super.getData(e);return t.resistances=b.magicResistanceModifiers,t}};u($s,"PoisonSheetDSA5");var Os=class extends Y{async _refundStep(){let e=this.item.system.step.value;if(e>1){let t=await R.stepXPCost(this.item,e-1);t=await R.refundFreelanguage(this.item,this.item.actor,t,!1),await this.item.actor._updateAPs(t*-1,{},{render:!1}),await this.item.update({"system.step.value":e-1}),await _.track(this.item.actor,{type:"item",item:this.item,previous:e,next:e-1},t)}}async _advanceStep(){let e=this.item.system.step.value;if(e0}async getData(e){let t=await super.getData(e);return mergeObject(t,{categories:b.specialAbilityCategories,subCategories:b.combatSkillSubCategories,traditionArtifacts:b.traditionArtifacts,canOnUseEffect:game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro")}),t}};u(Os,"SpecialAbilitySheetDSA5");var zs=class extends Y{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{width:530,height:570}),e}async getData(e){let t=await super.getData(e);return mergeObject(t,{hasLocalization:game.i18n.has(`Racedescr.${this.item.name}`)}),t}};u(zs,"ItemSpeciesDSA5");var xs=class extends Y{async getData(e){let t=await super.getData(e);return t.characteristics=b.characteristics,t.StFs=b.StFs,t.resistances=b.magicResistanceModifiers,t.targetTypes=b.areaTargetTypes,t.isOwned&&(t.extensions=this.item.actor.items.filter(a=>a.type=="spellextension"&&a.system.source==this.item.name&&this.item.type==a.system.category)),t}activateListeners(e){super.activateListeners(e),e.find(".item-edit").click(t=>{t.preventDefault();let a=this._getItemId(t);this.item.actor.items.get(a).sheet.render(!0)}),e.find(".item-delete").click(t=>{this._deleteItem(t)})}_deleteItem(e){let t=this._getItemId(e),a=this.actor.items.find(i=>i.id==t),s=game.i18n.format("DIALOG.DeleteItemDetail",{item:a.name});renderTemplate("systems/dsa5/templates/dialog/delete-item-dialog.html",{message:s}).then(i=>{new Dialog({title:game.i18n.localize("DIALOG.deleteConfirmation"),content:i,buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{this._cleverDeleteItem(t),$(e.currentTarget).closest(".item").remove()}},cancel:{icon:'',label:game.i18n.localize("cancel")}},default:"Yes"}).render(!0)})}async _cleverDeleteItem(e){let t=this.item.actor.items.find(a=>a.id==e);await this.item.actor._updateAPs(-1*t.system.APValue.value,{},{render:!1}),await this.item.actor.deleteEmbeddedDocuments("Item",[e]),await _.track(this.actor,{type:"item",item:t,state:-1},apCost)}};u(xs,"SpellSheetDSA5");var Ps=class extends Y{async getData(e){let t=await super.getData(e);return mergeObject(t,{categories:{spell:"spell",liturgy:"liturgy",ritual:"ritual",ceremony:"ceremony"}}),t}};u(Ps,"SpellExtensionSheetDSA5");var Ns=class extends Y{_advancable(){return this.item.system.max.value>0}async getData(e){let t=await super.getData(e);return t.canOnUseEffect=game.user.isGM||await game.settings.get("dsa5","playerCanEditSpellMacro"),t}async _refundStep(){let e=this.item.system.step.value;if(e>1){let t=await O.stepXPCost(this.item,e-1);t=await O.reduceSingularVantages(this.item.actor,this.item,t),await this.item.actor._updateAPs(t*-1,{},{render:!1}),await this.item.update({"system.step.value":e-1}),await _.track(this.item.actor,{type:"item",item:this.item,previous:e,next:e-1},t)}}async _advanceStep(){let e=this.item.system.step.value;if(e`+l.split(",").map(t=>`${t}`).join(", ")+""}u(Xi,"clickableAbilities");function Oi(l,e,t,a){if(a)return e.map(s=>`${s.name}${zi(getProperty(s.system,t),getProperty(s.system,a))}`).join(", ");if(t){let s=[];for(let i of e){let n=getProperty(i.system,t);if(n){s.push(`${i.name} ${n}`);continue}}return s.join(", ")}else return e.map(s=>`${s.name}`).join(", ")}u(Oi,"clickableActorItems");function Zi(l,e,t,a){let s=[];for(let i of Object.values(e)){if(i.length==0)continue;let n=Oi(l,i,t,a);n&&s.push(n)}return s.join(", ")}u(Zi,"clickableSection");function zi(l,e){return e!=null&&Number(e)<2?"":[" I"," II"," III"," IV"," V"," VI"," VII"," VIII"," IX"," X"][l-1]}u(zi,"roman");function ii(){Handlebars.registerHelper({concatUp:(l,e)=>l+e.toUpperCase(),mod:(l,e)=>l%e,roman:(l,e)=>zi(l,e),isWEBM:l=>/.webm$/.test(l),itemCategory:l=>f.categoryLocalization(l),joinStr:(l,e)=>e.join(l),attrName:l=>f.attributeLocalization(l),attrAbbr:l=>f.attributeAbbrLocalization(l),diceThingsUp:(l,e)=>f.replaceDies(l,!1),clickableAbilities:(l,e)=>Xi(l,e),traitName:l=>game.i18n.localize(b.traitCategories[l]),consumableQL:l=>l.system.QLList.split(` +`)[Number(l.system.QL)-1],clickableActorItems:(l,e,t,a)=>Oi(l,e,t,a),clickableSection:(l,e,t,a)=>Zi(l,e,t,a),hasLocalization:(l,e)=>{let t=l.string||l;return game.i18n.has(t)?game.i18n.localize(t):e||""},replaceConditions:f.replaceConditions,floor:l=>Math.floor(Number(l)),sum:(l,e)=>l+e,br:l=>l.replace(/\n/g,"
    "),getAttr:(l,e,t)=>l.system.characteristics[e][t],hasElem:(l,e)=>l.some(t=>e==t),situationalTooltip:l=>{let e=game.i18n.localize(Qi[l.type]||"Modifier"),t=`${l.name}
    ${e}: ${l.value}`;return l.source&&(t+=`
    ${game.i18n.localize("source")}: ${l.source}`),t},grouped_each:(l,e,t)=>{let a="",s=[],i;if(e&&e.length>0){for(i=0;i0&&i%l===0&&(a+=t.fn(s),s=[]),s.push(e[i]);a+=t.fn(s)}return a},plantify:l=>game.i18n.localize(`PLANT.avLevels.${l||0}`),oddLength:l=>l.length%2==1})}u(ii,"default");function ni(){Hooks.once("init",()=>{game.dsa5.apps.DiceSoNiceCustomization=new _e}),Hooks.once("diceSoNiceReady",(l,e,t,a)=>{l.addColorset({name:"mu",description:"DSA5.mu",category:"DSA5.dies",foreground:"#FFFFFF",background:"#b3241a",edge:"#b3241a",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"kl",description:"DSA5.kl",category:"DSA5.dies",foreground:"#FFFFFF",background:"#8259a3",edge:"#8259a3",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"in",description:"DSA5.in",category:"DSA5.dies",foreground:"#FFFFFF",background:"#388834",edge:"#388834",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ch",description:"DSA5.ch",category:"DSA5.dies",foreground:"#FFFFFF",background:"#0d0d0d",edge:"#0d0d0d",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ff",description:"DSA5.ff",category:"DSA5.dies",foreground:"#000000",background:"#d5b467",edge:"#d5b467",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ge",description:"DSA5.ge",category:"DSA5.dies",foreground:"#000000",background:"#688ec4",edge:"#688ec4",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"ko",description:"DSA5.ko",category:"DSA5.dies",foreground:"#000000",background:"#a3a3a3",edge:"#a3a3a3",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"kk",description:"DSA5.kk",category:"DSA5.dies",foreground:"#000000",background:"#d6a878",edge:"#d6a878",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"attack",description:"DSA5.attack",category:"DSA5.dies",foreground:"#FFFFFF",background:"#b3241a",edge:"#b3241a",outline:"#b3241a",texture:"none"}),l.addColorset({name:"dodge",description:"DSA5.dodge",category:"DSA5.dies",foreground:"#FFFFFF",background:"#388834",edge:"#388834",outline:"#FFFFFF",texture:"none"}),l.addColorset({name:"parry",description:"DSA5.parry",category:"DSA5.dies",foreground:"#FFFFFF",background:"#388834",edge:"#388834",outline:"#FFFFFF",texture:"none"}),game.dsa5.apps.DiceSoNiceCustomization.initConfigs(),_e.onConnect()})}u(ni,"default");var at=class extends Application{initConfigs(){let e=game.dice3d.exports.Utils.prepareColorsetList();this.choices={};for(let[a,s]of Object.entries(e))mergeObject(this.choices,s);let t={damage:"black"};delete this.choices.custom,game.settings.registerMenu("dsa5","dicesonicesettings",{name:"DiceSoNiceSettings",label:"DiceSoNice Settings",hint:game.i18n.localize("DSASETTINGS.dicesonicesettings"),type:Ls,restricted:!1});for(let a of at.attrs)game.settings.register("dsa5",`dice3d_${a}`,{name:`CHAR.${a.toUpperCase()}`,scope:"client",config:!1,default:t[a]||a,type:String}),game.settings.register("dsa5",`dice3d_system_${a}`,{name:`CHAR.${a.toUpperCase()}`,scope:"client",config:!1,default:"standard",type:String})}getAttributeConfiguration(e){return f.moduleEnabled("dice-so-nice")&&game.dice3d?{colorset:game.settings.get("dsa5",`dice3d_${e}`),appearance:{colorset:game.settings.get("dsa5",`dice3d_${e}`),system:game.settings.get("dsa5",`dice3d_system_${e}`)}}:{colorset:e}}activateListeners(e){super.activateListeners(),e.find('[name="entryselection"]').change(async t=>{await game.settings.set("dsa5",`dice3d_${t.currentTarget.dataset.attr}`,t.currentTarget.value)}),e.find('[name="systemselection"]').change(async t=>{await game.settings.set("dsa5",`dice3d_system_${t.currentTarget.dataset.attr}`,t.currentTarget.value),at.preloadDiceAssets([t.currentTarget.value]),game.socket.emit("system.dsa5",{type:"preloadDice3d",payload:{toPreload:[t.currentTarget.value]}})})}static onConnect(){game.socket.on("system.dsa5",e=>{switch(e.type){case"preloadDice3d":console.warn("Preloading forced DSA dice assets"),at.preloadDiceAssets(e.payload);break;case"getPreloadDice3d":at.requestDicePreloads();break}}),this.collectPreloads(),game.socket.emit("system.dsa5",{type:"getPreloadDice3d"})}static collectPreloads(e=!0){let t=new Set;for(let a of at.attrs)t.add(game.settings.get("dsa5",`dice3d_system_${a}`));t=Array.from(t),e&&this.preloadDiceAssets(t),game.socket.emit("system.dsa5",{type:"preloadDice3d",payload:t})}static requestDicePreloads(){this.collectPreloads(!1)}static async preloadDiceAssets(e,t=[]){console.warn("loading",e);for(let a of e){let s=game.dice3d.DiceFactory.systems[a];if(!s){this.unloadedModels.push(a);continue}let i=s.dice.filter(n=>t.length==0||t.includes(n.type));for(let n of i)try{n.modelFile?await n.loadModel(game.dice3d.DiceFactory.loaderGLTF):await n.loadTextures()}catch{console.warn("Unable to load dice model",a,n)}}this.unloadedModels.length&&this.retries<6&&!this.retrying&&(this.retrying=!0,setTimeout(()=>{this.retries+=1;let a=new Set(this.unloadedModels);this.unloadedModels=[],this.retrying=!1,this.preloadDiceAssets(a)},1e4))}async getData(e){let t=await super.getData(e);t.choices=this.choices,t.systems=game.dice3d.DiceFactory.systems,t.selections={};for(let a of at.attrs)t.selections[a]={color:game.settings.get("dsa5",`dice3d_${a}`),system:game.settings.get("dsa5",`dice3d_system_${a}`)};return t}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{template:"systems/dsa5/templates/wizard/dicesonice-configuration.html",title:game.i18n.localize("DSASETTINGS.dicesonicesettings"),width:600}),e}},_e=at;u(_e,"DiceSoNiceCustomization"),L(_e,"unloadedModels",[]),L(_e,"retries",0),L(_e,"retrying",!1),L(_e,"attrs",["mu","kl","in","ch","ff","ge","ko","kk","attack","dodge","parry","damage"]);var Ls=class extends FormApplication{render(){game.dsa5.apps.DiceSoNiceCustomization.render(!0)}};u(Ls,"DiceSoNiceForm");function ri(){Hooks.on("preDeleteActiveEffect",(n,r,o)=>{if(r.noHook)return;let c=n.parent;if(c&&c.documentName=="Actor"&&getProperty(n,"flags.dsa5.maintain")){let m=[n._id],d=n.name.replace("("+game.i18n.localize("maintainCost")+")","").trim(),p=c.effects.filter(y=>y.name.startsWith(d)&&!y.origin&&y.id!=n._id),g=game.i18n.format("DIALOG.updateMaintainSpell",{actor:c.name});return p&&(g+=`

    ${game.i18n.localize("DIALOG.dependentMaintainEffects")}

    `,g+=p.map(y=>`

    `).join("")),new Dialog({title:n.name,content:g,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("HELP.pay"),callback:async()=>{if(await c.applyMana(Number(getProperty(n,"flags.dsa5.maintain")),getProperty(n,"flags.dsa5.payType"))){let h={startTime:game.time.worldTime};game.combat&&(h.startRound=game.combat.round,h.startTurn=game.combat.turn),c.updateEmbeddedDocuments("ActiveEffect",[{_id:n._id,duration:h}])}}},delete:{icon:'',label:game.i18n.localize("delete"),callback:y=>{for(let h of y.find(".effectRemoveSelector:checked"))m.push($(h).val());c.deleteEmbeddedDocuments("ActiveEffect",m,{noHook:!0})}}}}).render(!0),!1}}),Hooks.on("updateActor",(n,r)=>{!game.user.isGM&&n.limited&&hasProperty(r,"system.merchant.hidePlayer")&&ui.sidebar.render(!0)}),Hooks.on("deleteActiveEffect",(n,r)=>{if(!f.isActiveGM()||r.noHook)return;let o=n.parent;if(o&&o.documentName=="Actor"){let c=[...n.statuses][0];if(c=="bloodrush")return o.addCondition("stunned",2,!1,!1),!1;if(c=="dead"&&game.combat)return o.markDead(!1),!1;if(Q.onEffectRemove(o,n),Hooks.call("deleteActorActiveEffect",o,n)===!1)return!1}}),Hooks.on("dropActorSheetData",(n,r,o)=>{switch(o.data?.type){case"condition":return n.addCondition(o.data.payload.id,1,!1,!1),!1;case"lookup":return r._handleLookup(o.data),!1;case"fullpack":return r._addFullPack(o.data),!1}}),Hooks.on("createActiveEffect",(n,r,o)=>{!f.isActiveGM()||(l(n),e(n))}),Hooks.on("deleteActiveEffect",(n,r,o)=>{!f.isActiveGM()||l(n)}),Hooks.on("updateActiveEffect",(n,r,o)=>{!f.isActiveGM()||(l(n),t(n))});function l(n){if(game.combat&&n.changes.some(r=>/(system\.status\.initiative|system\.characteristics.mu|system\.characteristics\.ge)/.test(r.key))){let r=n.parent.id,o=game.combat.combatants.find(c=>c.actor.id==r);o&&o.recalcInitiative()}}u(l,"checkIniChange");let e=u(async n=>{let r=n.parent;if(!r)return;await t(n,{},r);let o=[...n.statuses][0];o=="dead"&&game.combat?await r.markDead(!0):o=="unconscious"&&await r.addCondition("prone")},"createEffects"),t=u(async(n,r={},o)=>{if(o||(o=n.parent),!o||o.documentName!="Actor")return;let c=/^system\.condition\./;for(let m of n.changes||[])c.test(m.key)&&m.mode==2&&(r[m.key.split(".")[2]]=Number(m.value));for(let m of Object.keys(r))if(o.system.condition[m]>=4&&(m=="inpain"?await o.initResistPainRoll(n):["encumbered","stunned","feared","confused","trance"].includes(m)?await o.addCondition("incapacitated"):m=="paralysed"?await o.addCondition("rooted"):["drunken","exhaustion"].includes(m)&&(await o.addCondition("stunned"),await o.removeCondition(m))),(Number(r.inpain)||0)>0&&!o.hasCondition("bloodrush")&&o.system.condition.inpain>0&&O.hasVantage(o,game.i18n.localize("LocalizedIDs.frenzy"))){await o.addCondition("bloodrush");let d=f.replaceConditions(`${game.i18n.format("CHATNOTIFICATION.gainsBloodrush",{character:""+o.name+""})}`);ChatMessage.create(f.chatDataSetup(d))}},"countableDependentEffects"),a=u(async(n,r)=>{(game.dsa5.apps.AskForNameDialog||Rs).getDialog(n,r)},"askForName"),s=u(async n=>{if(!!f.isActiveGM()&&game.settings.get("dsa5","randomWeaponSelection")&&n.actor.type!="character"){let r=[],o=[],c=[];for(let d of n.actor.items)d.type=="meleeweapon"&&d.system.worn.value?P.isShield(d)?o.push(d):r.push(d):d.type=="rangeweapon"&&d.system.worn.value&&c.push(d);let m=[];if(r.length){let d=r[Math.floor(Math.random()*r.length)],p=d._id,g;!P.regex2h.test(d.name)&&o.length&&(g=o[Math.floor(Math.random()*o.length)]._id);for(let y of r)y._id!=p&&m.push({_id:y._id,system:{worn:{value:!1}}});for(let y of o)y._id!=g&&m.push({_id:y._id,system:{worn:{value:!1}}})}if(c.length){let d=c[Math.floor(Math.random()*c.length)]._id;for(let p of c)p._id!=d&&m.push({_id:p._id,system:{worn:{value:!1}}})}m.length&&n.actor.updateEmbeddedDocuments("Item",m)}},"randomWeaponSelection"),i=u(async(n,r)=>{if(!f.isActiveGM())return;let o=n.actor;if(o.hasPlayerOwner)return;let c=Number(game.settings.get("dsa5","obfuscateTokenNames"));if(c==0||getProperty(o,"merchant.merchantType")=="loot")return;let m=canvas.scene.tokens.filter(p=>p.actor&&p.actor.id===o.id),d=game.i18n.localize("unknown");if([2,4].includes(c)){if(!(n.id||n._id))return;a(n,c);return}if(m.length>0&&c<3){let p=m.length;for(let g of m){let y=g.name.match(/\d+$/);y&&Number(y[0])>p&&(p=Number(y[0]))}d=`${m[0].name.replace(/ \d{1,}$/,"")} ${p+1}`}r.name=d},"obfuscateName");Hooks.on("updateToken",(n,r,o)=>{H.updateTokenHook(n,r,o)}),Hooks.on("deleteToken",n=>{H.deleteTokenHook(n),st.hide(n)}),Hooks.on("preCreateToken",(n,r,o,c)=>{let m=n.actor;if(!m)return;let d={};getProperty(m,"system.merchant.merchantType")=="loot"?mergeObject(d,{displayBars:0}):getProperty(m,"system.config.autoBar")&&(mergeObject(d,{bar1:{attribute:"status.wounds"}}),m.system.isMage?mergeObject(d,{bar2:{attribute:"status.astralenergy"}}):m.system.isPriest?mergeObject(d,{bar2:{attribute:"status.karmaenergy"}}):mergeObject(d,{bar2:{attribute:"tbd"}})),getProperty(m,"system.config.autoSize")&&f.calcTokenSize(m,d),i(n,d),n.updateSource(d)}),Hooks.on("createToken",(n,r,o)=>{r.noHook||(i(n,{}),s(n),H.createTokenHook(n,r,o))}),Hooks.on("hoverToken",(n,r)=>{!game.settings.get("dsa5","showWeaponsOnHover")||(r?st.show(n):st.hide(n))})}u(ri,"default");var st=class{static show(e){if(!game.combat||canvas.hud?.token?.rendered)return;let t=e.actor.items.filter(a=>a.type=="meleeweapon"||a.type=="rangeweapon"?a.system.worn.value:!1);if(t.length){let a=t.map(i=>``).join(" "),s=$(`
    ${a}
    `);$("#hud").append(s),this.position(s,e,t.length)}}static position(e,t,a){let s=t.document,i=canvas.dimensions.size/100,n=a*43,r={width:n,height:42,left:t.center.x-n/2*i,top:t.y+s.height*canvas.dimensions.size+32};i!==1&&(r.transform=`scale(${i})`),e.css(r)}static hide(e){$(`#hoverhud_${e.id}`).remove()}};u(st,"TokenHoverHud");var Rs=class extends Dialog{static async getDialog(e,t){new Dialog({title:game.i18n.localize("DSASETTINGS.obfuscateTokenNames"),content:` `,default:"Yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:async a=>{let s=e.id||e._id,i=a.find('[name="name"]').val();if(t==2){let r=canvas.scene.tokens.filter(o=>o.name===i);if(r.length>0){let o=r.length;for(let c of r){let m=c.name.match(/\d+$/);m&&Number(m[0])>o&&(o=Number(m[0]))}i=`${r[0].name.replace(/ \d{1,}$/,"")} ${o+1}`}}await canvas.scene.tokens.get(s).update({name:i})}},unknown:{icon:'',label:game.i18n.localize("unknown"),callback:async()=>{let a=e.id||e._id;await canvas.scene.tokens.get(a).update({name:game.i18n.localize("unknown")})}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}};u(Rs,"AskForNameDialog");function oi(){Hooks.on("hotbarDrop",(l,e,t)=>{if(e.mod=="dodge"){let a={name:game.i18n.localize(e.mod),img:"systems/dsa5/icons/categories/Dodge.webp"},s;return game.user.isGM||e.actorId==null?s=`game.dsa5.macro.charMacro("${e.mod}")`:s=`game.dsa5.macro.charMacroById("${e.mod}", "${e.actorId}")`,_s(s,a.name,a.img,t)}else if(e.mod=="attackWeaponless"||e.mod=="parryWeaponless"){let a={name:game.i18n.localize(e.mod),img:"systems/dsa5/icons/categories/attack_weaponless.webp"},s;return game.user.isGM||e.actorId==null?s=`game.dsa5.macro.weaponLessMacro("${e.mod}")`:s=`game.dsa5.macro.weaponLessMacroId("${e.mod}", "${e.actorId}")`,_s(s,a.name,a.img,t)}else if(e.type=="Item"){let a=fromUuidSync(e.uuid);if(!["ritual","ceremony","meleeweapon","rangeweapon","skill","combatskill","spell","liturgy","char","trait"].includes(a.type)||(a.type=="meleeweapon"||a.type=="combatskill")&&!["attack","parry"].includes(e.mod))return;if((a.type=="rangeweapon"||a.type=="trait")&&!["attack"].includes(e.mod))return;let i=`{mod: "${e.mod}"}`,n;game.user.isGM||e.actorId==null?n=`game.dsa5.macro.itemMacro("${a.name}", "${a.type}", ${i});`:n=`game.dsa5.macro.itemMacroById("${e.actorId}", "${a.name}", "${a.type}", ${i})`;let r=e.mod==null?a.name:`${a.name} - ${game.i18n.localize("CHAR."+e.mod.toUpperCase())}`;return _s(n,r,a.img,t)}else if(e.type=="Actor"||e.type=="JournalEntry"){let a=fromUuidSync(e.uuid),s=`(await fromUuid('${e.uuid}')).sheet.render(true)`;return _s(s,a.name,a.img,t)}})}u(oi,"default");function _s(l,e,t,a){let s=game.macros.contents.find(i=>i.name===e&&i.command===l);return s?game.user.assignHotbarMacro(s,a):Macro.create({name:e,type:"script",img:t,command:l},{displaySheet:!1}).then(i=>game.user.assignHotbarMacro(i,a)),!1}u(_s,"createHotBarMacro");function li(){Hooks.on("renderChatLog",(l,e,t)=>{j.chatListeners(e),_DiceDSA5.chatListeners(e),B.chatListeners(e);let a=new se;Hooks.call("startDSA5ChatAutoCompletion",a),a.chatListeners(e),ae.chatListeners(e)}),Hooks.on("renderChatMessage",(l,e,t)=>{if(game.user.isGM)e.find(".chat-button-player").remove();else{e.find(".chat-button-gm").remove();let a,s=e.find(".chat-button-target");s.length&&(a=ce.getTargetActor(t.message),a&&a.actor&&!a.actor.isOwner&&s.remove());let i=f.getSpeaker(t.message.speaker);i&&!i.isOwner&&(e.find(".selfButton").remove(),e.find(".d20").attr("data-tooltip",""));let n=e.find(".onlyTarget");n.length&&(a=f.getSpeaker({token:n.attr("data-token"),actor:n.attr("data-actor"),scene:canvas.scene?canvas.scene.id:null}),a&&!a.isOwner&&n.remove()),e.find(".hideData").remove(),getProperty(t.message,`flags.dsa5.userHidden.${game.user.id}`)&&e.find(".payButton").remove()}game.settings.get("dsa5","expandChatModifierlist")&&(e.find(".expand-mods i").toggleClass("fa-minus fa-plus"),e.find(".expand-mods + ul").css({display:"block"})),E.bindButtons(e),e.find(".embeddedItemDrag").each(function(a,s){s.setAttribute("draggable",!0),s.addEventListener("dragstart",i=>nn(i))})}),Hooks.on("chatMessage",(l,e,t)=>{let a=e.match(/^\/(pay|getPaid|help$|conditions$|tables)/);switch(a=a?a[0]:"",a){case"/pay":return game.user.isGM?B.createPayChatMessage(e):B.payMoney(f.getSpeaker(t.speaker),e),!1;case"/getPaid":return game.user.isGM?B.createGetPaidChatMessage(e):B.getMoney(f.getSpeaker(t.speaker),e),!1;case"/help":return ae.getHelp(),!1;case"/conditions":return ae.showConditions(),!1;case"/tables":return ae.showTables(),!1}}),Hooks.on("preCreateChatMessage",(l,e,t,a)=>{if(getProperty(l,"flags.core.initiativeRoll")){let s=l.rolls[0].terms,i=`${s[0].number}`.split(".")[0],n=`${game.i18n.localize("baseValue")}: ${i}, ${game.i18n.localize("randomValue")}: ${s.at(-3).values[0]}")}`,r=[];for(let m of s)if(m.faces&&m.faces==6)for(let d=0;d${m.results[d].result}
    `);let c={content:`
    - ${game.i18n.localize("Roll")}: ${n.join("")} + ${game.i18n.localize("Roll")}: ${r.join("")}
    -
    +
    ${game.i18n.localize("initiative")}: ${Math.floor(l.rolls[0]._total*100)/100}
    -
    `,flavor:void 0};l.updateSource(c)}})}u(li,"default");function sr(l){let e=$(l.currentTarget).parents(".message").attr("data-message-id"),a=game.messages.get(e).getFlag("dsa5","embeddedItem"),s={type:"Item",data:a};l.dataTransfer.setData("text/plain",JSON.stringify(s))}u(sr,"embeddedDragStart");var ze=class{static async firstTimeMessage(){if(!await game.settings.get("dsa5","firstTimeStart")){await ze.setupDefaultOptions();let e=game.i18n.localize("WELCOME");ChatMessage.create(f.chatDataSetup(e)),ze.firstTimeLanguage(),await game.settings.set("dsa5","firstTimeStart",!0)}}static firstTimeLanguage(){let e=["de","en"],t={title:game.i18n.localize("DIALOG.firstTime"),content:game.i18n.localize("DIALOG.firstTimeWarning"),default:"de",buttons:{}};for(let a of e)t.buttons[a]={label:game.i18n.localize(a),callback:()=>ze.setLanguage(a)};new Dialog(t).render(!0)}static async setLanguage(e){await game.settings.set("dsa5","firstTimeStart",!0),await game.settings.set("dsa5","forceLanguage",e),await game.settings.set("core","language",e),foundry.utils.debouncedReload()}static async setupDefaultOptions(){let e=game.settings.get("core",Combat.CONFIG_SETTING);e.skipDefeated=!0,await game.settings.set("core",Combat.CONFIG_SETTING,e),await game.settings.set("core","leftClickRelease",!0)}};u(ze,"DSA5Tutorial");var Dt=class{static async stopFade(e){e.stopPropagation(),e.preventDefault(),this.fadeOut?(this.fadeOut=!1,$(e.currentTarget).find("i").removeClass("fa-stop").addClass("fa-angle-right"),$(".didYouKnow").off("click"),$(".didYouKnow .closeDidYou").click(()=>$(".didYouKnow").remove())):fetch(`systems/dsa5/lazy/didyouknow/${game.i18n.lang}.json`).then(async t=>t.json()).then(async t=>{let a=t.data[Math.floor(Math.random()*t.data.length)],s=await renderTemplate("systems/dsa5/templates/system/didyouknow.html",{msg:a,fadeOut:Dt.fadeOut});$("body").find(".didYouKnow").replaceWith(s),Dt.activateListeners()})}static activateListeners(){$(".didYouKnow .stopFade").click(async e=>await this.stopFade(e)),$(".didYouKnow").click(()=>$(".didYouKnow").remove()),$(".didYouKnow").fadeIn()}static async showOneMessage(e=8e3){game.settings.get("dsa5","disableDidYouKnow")||fetch(`systems/dsa5/lazy/didyouknow/${game.i18n.lang}.json`).then(async t=>t.json()).then(async t=>{let a=t.data[Math.floor(Math.random()*t.data.length)],s=await renderTemplate("systems/dsa5/templates/system/didyouknow.html",{msg:a,fadeOut:Dt.fadeOut});$("body").append(s),this.activateListeners(),setTimeout(function(){Dt.fadeOut&&$(".didYouKnow").fadeOut(1e3,()=>$(".didYouKnow").remove())},e)})}},Fe=Dt;u(Fe,"DidYouKnow"),L(Fe,"fadeOut",!0);var Ce=class extends CombatTracker{static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{template:"/systems/dsa5/templates/system/combattracker.html"})}activateListeners(e){super.activateListeners(e),e.find(".combatant.actor .aggroButton").click(t=>{t.preventDefault(),t.stopPropagation(),Ce.runActAttackDialog()}),e.find("#combat-tracker").on("scroll.combattracker",debounce(function(t){let a=$(t.target),s=e.find(".combatant.active")[0].offsetTop;e.find(".aggroButton").animate({top:s-a.scrollTop()},50)},50)),e.find(".convertToBrawl").click(()=>game.combat.convertToBrawl())}static runActAttackDialog(){if(!game.combat)return;let e=game.combat.combatant;(game.user.isGM||e.isOwner)&&Re.showDialog(e.actor,e.tokenId)}async getData(e){let t=await super.getData(e);for(let a of t.turns){let s=t.combat.turns.find(n=>n.id==a.id),i=game.user.isGM||s.actor&&s.actor.testUserPermission(game.user,"OBSERVER")||!game.settings.get("dsa5","hideEffects");a.defenseCount=s.getFlag("dsa5","defenseCount")||0,a.actionCount=Number(getProperty(s,"actor.system.actionCount.value"))||0,a.actionCounts=`${a.actionCount} ${game.i18n.localize("actionCount")}`;let r=[];if(s.actor){for(let n of s.actor.items)if(n.type=="rangeweapon"&&n.system.worn.value&&n.system.reloadTime.progress>0){let o={name:n.name,remaining:T.calcLZ(n,s.actor)-n.system.reloadTime.progress};o.remaining>0&&r.push(o)}else if(["spell","liturgy"].includes(n.type)&&n.system.castingTime.modified>0){let o={name:n.name,remaining:n.system.castingTime.modified-n.system.castingTime.progress};o.remaining>0&&r.push(o)}}r=r.sort((n,o)=>n.remaining-o.remaining),r.length>0&&(a.ongoings=`${game.i18n.localize("COMBATTRACKER.ongoing")}
    ${r.map(n=>`${n.name} - ${n.remaining}`).join("
    ")}`,a.ongoing=r[0].remaining),a.effects=new Set,s.token&&(s.token.effects.forEach(n=>a.effects.add(n)),s.token.overlayEffect&&a.effects.add(s.token.overlayEffect)),s.actor&&s.actor.temporaryEffects.forEach(n=>{n.statuses.has(CONFIG.Combat.defeatedStatusId)?a.defeated=!0:n.icon&&i&&!n.notApplicable&&(game.user.isGM||!n.getFlag("dsa5","hidePlayers"))&&!n.getFlag("dsa5","hideOnToken")&&a.effects.add(n.icon)})}return t.isBrawling=game.combat?.isBrawling,t}};u(Ce,"DSA5CombatTracker");var He=class extends Combat{constructor(e,t){super(e,t)}async refreshTokenbars(){game.dsa5.apps.tokenHotbar&&game.dsa5.apps.tokenHotbar.updateDSA5Hotbar()}get isBrawling(){return this.getFlag("dsa5","isBrawling")}_onCreate(e,t,a){super._onCreate(e,t,a),this.refreshTokenbars()}_onDelete(e,t){super._onDelete(e,t),this.refreshTokenbars()}async brawlingDialog(){return new Promise((e,t)=>{new Dialog({title:game.i18n.localize("BRAWLING.unarmEveryone"),content:`

    ${game.i18n.localize("BRAWLING.unarmEveryoneText")}

    `,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{e(!0)}},No:{icon:'',label:game.i18n.localize("no"),callback:()=>{e(!1)}}}}).render(!0)})}async convertToBrawl(e=void 0){let t=e??!this.isBrawling,a=[],s=[],i=[];if(t){await this.setFlag("dsa5","unarmEveryone",await this.brawlingDialog());for(let r of this.combatants){if(!r.actor)return{};let n=await r.brawlingChange();r.actor.isToken?await r.actor.update(n.actorChange):a.push(n.actorChange),s.push(...n.tokenChange),He.brawlStart()}}else for(let r of this.combatants){if(!r.actor)return{};let n=await r.undoBrawlingChange();r.actor.isToken?await r.actor.update(n.actorChange):a.push(n.actorChange),s.push(...n.tokenChange),n.damage.brawlDamage>0&&i.push({name:r.token.name,id:r.token.id,data:n.damage})}await T.updateDocuments(a),await game.canvas.scene.updateEmbeddedDocuments("Token",s),await this.setFlag("dsa5","isBrawling",t),i.length&&await this.showBrawlingDamage(i)}async showBrawlingDamage(e){let t=await renderTemplate("systems/dsa5/templates/chat/brawling-damage.html",{messages:e});ChatMessage.create(f.chatDataSetup(t))}static async brawlStart(e=2e3,t=!0){t&&f.isActiveGM()&&await game.socket.emit("system.dsa5",{type:"brawlStart",payload:{}}),$(".bumFight").remove();let a=await renderTemplate("systems/dsa5/templates/system/bumFight/animation.html",{});$("body").append(a);let s=$(".bumFight");s.on("click",()=>s.remove()),s.addClass("fight"),setTimeout(function(){s.fadeOut(1e3,()=>s.remove())},e)}async nextRound(){if(game.user.isGM)for(let e of this.turns)await e.setFlag("dsa5","defenseCount",0);else await game.socket.emit("system.dsa5",{type:"clearCombat",payload:{}});return await super.nextRound()}async getDefenseCount(e){let t=this.getCombatantFromActor(e);return t&&t.getFlag("dsa5","defenseCount")||0}getCombatantFromActor(e){let t;return e.token?t=Array.from(this.combatants).find(a=>a.tokenId==e.token):t=Array.from(this.combatants).find(a=>a.actorId==e.actor),t?this.combatants.get(t.id):void 0}async updateDefenseCount(e){if(game.user.isGM){let t=this.getCombatantFromActor(e);t&&!getProperty(t.actor,"system.config.defense")&&await t.setFlag("dsa5","defenseCount",(t.getFlag("dsa5","defenseCount")||0)+1)}else await game.socket.emit("system.dsa5",{type:"updateDefenseCount",payload:{speaker:e}})}};u(He,"DSA5Combat");var Jt=class extends Combatant{constructor(e,t){e.flags==null&&(e.flags={}),mergeObject(e.flags,{dsa5:{defenseCount:0}}),super(e,t)}brawlingChange(){let e=f.getSpeaker({actor:this.actor.id,scene:this.sceneId,token:this.token.id}),t=this.combat.getFlag("dsa5","unarmEveryone"),a=getProperty(e,"system.config.autoBar")?e.getActiveTokens().map(i=>({_id:i.id,bar1:{attribute:"status.temporaryLeP"}})):[],s={_id:e.id,system:{status:{temporaryLeP:{value:e.system.status.wounds.value,max:e.system.status.wounds.value}}}};if(t){let i=this.actor.items.filter(r=>r.type=="meleeweapon"&&r.system.worn.value&&P.improvisedWeapon.test(r.name));i.length&&(s.items=i.map(r=>({_id:r.id,"system.worn.value":!1})))}return{tokenChange:a,actorChange:s}}async getBrawlingTable(){if(!this.brawlingTable){let t=(await game.packs.get(game.i18n.lang=="de"?"dsa5.patzer":"dsa5.botch").getDocuments({name__in:[game.i18n.lang=="de"?"Pr\xFCgelei - Verletzungen":"Brawling - Injuries"]}))[0];this.brawlingTable=t}return this.brawlingTable}async undoBrawlingChange(){let e=f.getSpeaker({actor:this.actor.id,scene:this.sceneId,token:this.token.id}),t=getProperty(e,"system.config.autoBar")?e.getActiveTokens().map(n=>({_id:n.id,bar1:{attribute:"status.wounds"}})):[],a=Math.max(0,e.system.status.temporaryLeP.max-e.system.status.temporaryLeP.value),s=0,i;if(a>0){i=await(await this.getBrawlingTable()).draw({displayChat:!1}),i=i.results[0];let n=i.getFlag("dsa5","brawlDamage");s=Math.round(a*n)}let r={_id:e.id,system:{status:{temporaryLeP:{value:0,max:0},wounds:{value:e.system.status.wounds.value-s}}}};return{tokenChange:t,actorChange:r,damage:{brawlDamage:s,result:i}}}async recalcInitiative(){if(this.initiative){let t={initiative:(await this.getFlag("dsa5","baseRoll")||0)+this.actor.system.status.initiative.value};await this.update(t)}}};u(Jt,"DSA5Combatant");Hooks.on("preCreateCombatant",(l,e,t)=>{let a=f.getSpeaker({actor:l.actorId,scene:l.sceneId,token:l.tokenId});if(getProperty(a.system,"merchant.merchantType")=="loot")return!1;if(l.combat.isBrawling){let s=l.brawlingChange();delete s.actorChange._id,a.update(s.actorChange).then(()=>{game.canvas.scene.updateEmbeddedDocuments("Token",s.tokenChange)})}});Hooks.on("deleteCombatant",(l,e,t)=>{let a=f.getSpeaker({actor:l.actorId,scene:l.sceneId,token:l.tokenId});if(getProperty(a.system,"merchant.merchantType")=="loot")return!1;l.combat.isBrawling&&l.undoBrawlingChange().then(async s=>{!l.token||(delete s.actorChange._id,await a.update(s.actorChange),await game.canvas.scene.updateEmbeddedDocuments("Token",s.tokenChange),s.damage.brawlDamage>0&&l.combat.showBrawlingDamage([{name:l.token.name,id:l.token.id,data:s.damage}]))})});Hooks.on("preDeleteCombat",(l,e,t)=>{if(!e.noHook&&l.isBrawling)return l.convertToBrawl(!1).then(()=>{l.delete({noHook:!0})}),!1});Hooks.on("updateCombatant",(l,e,t)=>{if(!!game.user.isGM)if(e.initiative){if(!l.getFlag("dsa5","baseRoll")){let s=`${e.initiative}`.split("."),i=Number(s[0])-Math.round(l.actor.system.status.initiative.value);l.setFlag("dsa5","baseRoll",i)}}else"initiative"in e&&e.initiative==null&&l.update({["flags.dsa5.-=baseRoll"]:null})});var Mt=class{static async updateCombatHook(e,t,a,s){!t.round&&!t.turn||e.round!=0&&e.turns&&e.active&&e.previous.rounda.active&&a.isGM);if(!!(t&&game.user.id==t.id)){for(let a of e.turns)if(!a.defeated){for(let s of a.actor.effects){if(s.disabled)continue;let i=[...s.statuses][0];i=="bleeding"?await this.applyBleeding(a,e):i=="burning"&&await this.applyBurning(a,s,e)}await this.startOfRoundEffects(a,e)}}}static async startOfRoundEffects(e,t){let a=["wounds","astralenergy","karmaenergy"];for(let s of a){if(getProperty(e.actor.system.repeatingEffects,`disabled.${s}`))continue;let i=e.actor.system.repeatingEffects.startOfRound[s].map(m=>m.value).join("+");if(!i)continue;let r=await new Roll(i).evaluate({async:!0}),n=await r.render(),o=game.i18n.localize(r.total>0?"CHATNOTIFICATION.regenerates":"CHATNOTIFICATION.getsHurt"),c=`${this.buildActorName(e)} ${o} ${game.i18n.localize(s)} ${n}`;await this.sendEventMessage(c,t,e),s=="wounds"?await e.actor.applyDamage(r.total*-1):await e.actor.applyMana(r.total*-1,s=="astralenergy"?"AsP":"KaP")}}static async applyBleeding(e,t){if(e.actor.system.status.wounds.value<1)return;let a=game.i18n.format("CHATNOTIFICATION.bleeding",{actor:this.buildActorName(e)});await this.sendEventMessage(a,t,e),await e.actor.applyDamage(1)}static async applyBurning(e,t,a){if(e.actor.system.status.wounds.value<1)return;let s=Number(t.getFlag("dsa5","value")),i=E.resistantToEffect(e.actor,t),r={0:"1",1:"1d3",2:"1d6",3:"2d6"}[s-i]||"1",n=await new Roll(r).evaluate({async:!0}),o=await n.render(),c=game.i18n.format(`CHATNOTIFICATION.burning.${s}`,{actor:this.buildActorName(e),damage:o});await this.sendEventMessage(c,a,e),await e.actor.applyDamage(n.total)}static buildActorName(e){let t=e.token.name;return game.settings.get("dsa5","hideRegenerationToOwner")&&e.token.name!=e.token.actor.name&&(t+=` (${e.token.actor.name})`),e.token.actor.toAnchor({name:t}).outerHTML}static async sendEventMessage(e,t,a){if(game.settings.get("dsa5","hideRegenerationToOwner")){let s=t.combatants.get(a.id).players;s.push(...game.users.filter(r=>r.isGM).map(r=>r.id));let i=f.chatDataSetup(e,void 0,void 0,s);delete i.speaker,await ChatMessage.create(i)}else await ChatMessage.create(f.chatDataSetup(e))}};u(Mt,"RepeatingEffectsHelper");Hooks.on("updateCombat",Mt.updateCombatHook);var Pe=class extends Application{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","initTracker"]),template:"systems/dsa5/templates/system/initracker.html",dragDrop:[{dragSelector:".iniItem",dropSelector:[".iniTrackerList"]}],top:100,left:170,title:"DSAIniTracker",itemWidth:game.settings.get("dsa5","iniTrackerSize"),actorCount:game.settings.get("dsa5","iniTrackerCount"),position:game.settings.get("dsa5","iniTrackerPosition")}),e}setPosition({left:e,top:t,width:a,height:s,scale:i}={}){let r=super.setPosition({left:e,top:t,width:a,height:s,scale:i}),n=this.element[0];if(!n.style.width||a){let o=a||n.offsetWidth,c=n.style.maxWidth||window.innerWidth;r.width=a=Math.clamped(o,0,c),n.style.width=a+"px",a+r.left>window.innerWidth&&(e=r.left)}return game.settings.set("dsa5","iniTrackerPosition",{left:r.left,top:r.top}),r}static connectHooks(){Hooks.on("renderDSA5CombatTracker",(e,t,a)=>{!game.settings.get("dsa5","enableCombatFlow")||(game.combat?(game.dsa5.apps.initTracker||(game.dsa5.apps.initTracker=new Pe),game.dsa5.apps.initTracker.updateTracker(a)):game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.close(),game.dsa5.apps.initTracker=void 0))})}updateTracker(e){this.combatData=e,this.render(!0,{focus:!1})}async getData(e){let t=this.combatData,a=Pe.defaultOptions.itemWidth,s=Pe.defaultOptions.actorCount,i=t.round,r=t.turns,n=[],o=game.settings.get("core",Combat.CONFIG_SETTING).skipDefeated,c=r.some(d=>d.active),m=t.turns.some(d=>d.owner&&!d.hasRolled&&(!game.user.isGM||t.combat.combatants.get(d.id).isNPC));if(r.length){let d=[],p=s,g=!1,y=-1,h=0,w=0,x;for(;!(p==0||w==s);){let v=duplicate(r[h]),S=t.combat.combatants.get(v.id);g&&h==y&&(v.css=v.css.replace("active","")),!i||v.active&&!g||!c&&!g?(g=!0,y=h):S.getFlag("dsa5","waitInit")==t.round+w&&!S.defeated&&(game.user.isGM||!S.hidden)&&n.push(v),g&&!(o&&S.defeated)&&(game.user.isGM||!S.hidden)&&(v.round=t.round+w,v.owner&&S.token?.actor&&(v.maxLP=S.token.actor.system.status.wounds.max,v.currentLP=S.token.actor.system.status.wounds.value),x&&x!=v.round&&(v.newRound="newRound"),x=v.round,d.push(v),p--),h++,h>=r.length&&(h=0,w++)}t.turns=d}return t.isLastRound=t.turns[1]?.newRound,this.position.width=a*s+s*3+80,this.position.height=a+10,mergeObject(t,{itemWidth:a,unRolled:m,waitingTurns:n}),this.conditionalPanToCurrentCombatant(t),t}hasChangedTurn(e){let t=e.turn!=this.lastTurnUpdate||e.round!=this.lastRoundUpdate;return this.lastTurnUpdate=e.turn,this.lastRoundUpdate=e.round,t}async conditionalPanToCurrentCombatant(e){if(!game.settings.get("dsa5","enableCombatPan"))return;let t=e.turns[0];if(!t)return;let a=e.combat.combatants.get(t.id);!a||!this.hasChangedTurn(e)||setTimeout(()=>{let s=a.token;!s||!s.object||!s.object.isVisible||(canvas.animatePan({x:s.x,y:s.y}),!(!a.actor||!a.actor.isOwner)&&s.object.control({releaseOthers:!0}))},300)}async _onWheelResize(e){let t=game.settings.get("dsa5","iniTrackerSize");e.originalEvent.deltaY>0?t=Math.min(140,t+5):t=Math.max(30,t-5),await game.settings.set("dsa5","iniTrackerSize",t),await this.render(!0)}activateListeners(e){super.activateListeners(e);let t=e.find(".dragHandler");new Draggable(this,e,t[0],this.options.resizable),t.on("wheel",async s=>(s.stopPropagation(),s.preventDefault(),await this._onWheelResize(s),!1)),e.find(".toggleTracker").click(()=>{let s=ui.combat;s.renderPopout(s)}),e.find(".combat-control").click(s=>this._onCombatControl(s)),e.find(".convertToBrawl").click(s=>{game.combat?.convertToBrawl()});let a=e.find(".iniItem");a.hover(this._onCombatantHoverIn.bind(this),this._onCombatantHoverOut.bind(this)),a.click(this._onCombatantMouseDown.bind(this)),e.find(".waitingTackerList .iniItem").mousedown(s=>this._onRightClick(s)),e.find(".combatant-control").click(s=>this._onCombatantControl(s)),e.find(".combatant .aggroButton").click(s=>{s.preventDefault(),s.stopPropagation(),Ce.runActAttackDialog()}),e.find(".rollMine").click(s=>this.rollMyChars()),game.user.isGM&&e.find(".rolledInit").click(s=>this.editCombatant(s))}rollMyChars(){game.user.isGM?this._getCombatApp().viewed.rollNPC({}):this._getCombatApp().viewed.rollAll({})}_onRightClick(e){if(e.button==2){let t=game.combat.combatants.get(e.currentTarget.dataset.combatantId);t.isOwner&&t.unsetFlag("dsa5","waitInit")}}editCombatant(e){this._getCombatApp()._onConfigureCombatant($(e.currentTarget))}_onCombatantControl(e){this._getCombatApp()._onCombatantControl(e)}_onCombatControl(e){e.currentTarget.dataset.control=="waitInit"?this.waitInit(e):this._getCombatApp()._onCombatControl(e)}async waitInit(e){await game.combat.combatants.get(game.combat.current.combatantId).setFlag("dsa5","waitInit",game.combat.current.round),e.currentTarget.dataset.control="nextTurn",this._getCombatApp()._onCombatControl(e)}_onCombatantHoverOut(e){this._getCombatApp()._onCombatantHoverOut(e)}_onCombatantHoverIn(e){this._getCombatApp()._onCombatantHoverIn(e)}_onCombatantMouseDown(e){this._getCombatApp()._onCombatantMouseDown(e)}_getCombatApp(){return game.combats.apps[0]}_canDragStart(e){return!1}_canDragDrop(e){return!1}_onDragStart(e){let t=$(e.currentTarget).closestData("combatant-id");e.dataTransfer.setData("text/plain",JSON.stringify({type:"IniChange",combatantId:t}))}_onDrop(e){JSON.parse(e.dataTransfer.getData("text/plain")).type=="IniChange"}};u(Pe,"DSAIniTracker");var Ne=class extends Tour{static async travelAgency(){let e=game.i18n.lang=="de"?"de":"en";console.log("Adding DSA/TDE Tours");for(let t of this.tours){let a=await game.dsa5.apps.DSATour.fromJSON(`${t.replace("/lang/",`/${e}/`)}.json`);game.tours.register(a.config.module,a.id,a)}if(!!game.user.isGM)for(let t of this.gmTours){let a=await game.dsa5.apps.DSATour.fromJSON(`${t.replace("/lang/",`/${e}/`)}.json`);game.tours.register(a.config.module,a.id,a)}}async _preStep(){this.currentStep.activateTab?ui.sidebar.activateTab(this.currentStep.activateTab):this.currentStep.activateLayer&&canvas.activeLayer.options.name!=this.currentStep.activateLayer?(await canvas[this.currentStep.activateLayer].activate(),await ra(100)):this.currentStep.appTab&&this.app.activateTab(this.currentStep.appTab)}exit(){super.exit()}async start(){if(this.config.preCommand){let t=Object.getPrototypeOf(async function(){}).constructor;await new t(this.config.preCommand).call(this)}if(this.app)for(await this.app.render(!0,{focus:!0});!this.app.rendered;)await ra(50);if(this.app||this.config.preCommand)for(;!$(this.steps[this.stepIndex+1].selector+":visible").length;)await ra(50);let e=await super.start();return $("#tooltip").show(),e}};u(Ne,"DSATour"),L(Ne,"tours",["systems/dsa5/modules/tours/lang/initial","systems/dsa5/modules/tours/lang/library","systems/dsa5/modules/tours/lang/actor"]),L(Ne,"gmTours",["systems/dsa5/modules/tours/lang/mastermenu"]);var ut=class{async _getData(e){return{}}activateListeners(e){}async _renderData(e){let t=await this._getData(e);return mergeObject(t,e),await renderTemplate(this.constructor.template,t)}async prepareApp(e){return{name:game.i18n.localize(`PLAYER.${this.constructor.name}`),view:await this._renderData(e)}}async render(){await game.dsa5.apps.playerMenu.render(!0)}async activateTab(){await game.dsa5.apps.playerMenu.activateTab(game.i18n.localize(`PLAYER.${this.constructor.name}`))}get actor(){return game.dsa5.apps.playerMenu.actor}async _onDrop(e){}};u(ut,"PlayerMenuSubApp"),L(ut,"template",""),L(ut,"rulePath",{});var Le=class extends Application{constructor(e){super(e),this.entityAbilities=[],game.dsa5.apps.PlayerMenuSubApp=ut,this.summoningModifiers=[{id:1,name:"CONJURATION.offensiveImprovement",descr:"CONJURATION.offensiveImprovementDescr",changes:[{key:"system.meleeStats.attack",mode:2,value:2},{key:"system.meleeStats.damage",mode:2,value:4},{key:"system.rangeStats.attack",mode:2,value:2},{key:"system.rangeStats.damage",mode:2,value:4}]},{id:2,name:"CONJURATION.defensiveImprovement",descr:"CONJURATION.defensiveImprovementDescr",changes:[{key:"system.meleeStats.parry",mode:2,value:2},{key:"system.totalArmor",mode:2,value:2},{key:"system.status.wounds.gearmodifier",mode:2,value:10}]},{id:3,name:"CONJURATION.speedImprovement",descr:"CONJURATION.speedImprovementDescr",changes:[{key:"system.status.speed.gearmodifier",mode:2,value:2},{key:"system.status.dodge.gearmodifier",mode:2,value:2}]},{id:4,name:"CONJURATION.magicalImprovement",descr:"CONJURATION.magicalImprovementDescr",changes:[],fun:P.magicalImprovement},{id:5,name:"CONJURATION.resistanceImprovement",descr:"CONJURATION.resistanceImprovementDescr",changes:[{key:"system.status.soulpower.gearmodifier",mode:2,value:2},{key:"system.status.toughness.gearmodifier",mode:2,value:2}]},{id:6,name:"CONJURATION.mentalImprovement",descr:"CONJURATION.mentalImprovementDescr",changes:[{key:"system.characteristics.mu.gearmodifier",mode:2,value:2},{key:"system.characteristics.kl.gearmodifier",mode:2,value:2},{key:"system.characteristics.in.gearmodifier",mode:2,value:2},{key:"system.characteristics.ch.gearmodifier",mode:2,value:2}]},{id:7,name:"CONJURATION.physicalImprovement",descr:"CONJURATION.physicalImprovementDescr",changes:[{key:"system.characteristics.ff.gearmodifier",mode:2,value:2},{key:"system.characteristics.ge.gearmodifier",mode:2,value:2},{key:"system.characteristics.ko.gearmodifier",mode:2,value:2},{key:"system.characteristics.kk.gearmodifier",mode:2,value:2}]}],this.conjurationData={qs:0,consumedQS:0,packageModifier:0,selectedIds:[],selectedEntityIds:[],selectedPackageIds:[],conjurationTypes:{1:game.i18n.localize("CONJURATION.demon"),2:game.i18n.localize("CONJURATION.elemental")},rules:{1:{de:{pack:"dsa5-core.corerules",name:"Beschw\xF6rungen"},en:{pack:"dsa5-core.coreenrules",name:"Summoning"}},2:{de:{pack:"dsa5-core.corerules",name:"Beschw\xF6rungen"},en:{pack:"dsa5-core.coreenrules",name:"Summoning"}}},conjurationType:1,skills:{1:["invocatioMinima","invocatioMinor","invocatioMaior"].map(t=>game.i18n.localize(`LocalizedIDs.${t}`)),2:["manifesto","elementalServant","callDjinn","servantEarth","servantFlame","servantCold","servantWave","servantCloud","servantOre"].map(t=>game.i18n.localize(`LocalizedIDs.${t}`))},modifiers:{1:this.summoningModifiers,2:this.summoningModifiers},moreModifiers:{2:[{name:game.i18n.localize("CONJURATION.groupSummoning"),options:[1,2,3,4,5,6,7,8].map(t=>({name:t,val:t*-2+2}))}]},postFunction:{}},this.subApps=[]}registerSubApp(e){this.subApps.push(e)}async rollConjuration(e){if(!this.conjuration)return ui.notifications.warn(game.i18n.localize("CONJURATION.dragConjuration"));let t=$(e.currentTarget).closest(".item").attr("data-item-id"),a=this.actor.items.get(t),s=[{name:game.i18n.localize("conjuringDifficulty"),value:getProperty(this.conjuration,"system.conjuringDifficulty.value")||0,selected:!0}];if(this.conjurationData.packageModifier&&s.push({name:game.i18n.localize("summoningPackage"),value:this.conjurationData.packageModifier,selected:!0}),this.conjurationData.moreModifiers[this.conjurationData.conjurationType]){let i=this.conjurationData.moreModifiers[this.conjurationData.conjurationType].filter(r=>r.selected);for(let r of i)s.push({name:r.name,value:Number(r.selected),selected:!0})}this.actor.setupSkill(a,{moreModifiers:s,subtitle:` (${this.conjuration.name})`},void 0).then(async i=>{let r=await this.actor.basicTest(i);this.conjurationData.qs=r.result.qualityStep||0,this.render(!0)})}activateListeners(e){super.activateListeners(e),oe(e),e.find(".conjurationData").change(t=>{let a=$(t.currentTarget);setProperty(this.conjurationData,a.attr("name"),a.val()),a.attr("data-refresh")&&this.render()}),e.find(".skill-select").click(t=>this.rollConjuration(t)),e.find(".initLibrary").click(async t=>{$(t.currentTarget).html(''),await game.dsa5.itemLibrary.buildEquipmentIndex(),this.render()}),e.find(".item-edit").click(t=>{let a=$(t.currentTarget).closest(".item").attr("data-item-id");this.actor.items.get(a).sheet.render(!0)}),e.find(".selectableRow").click(t=>this.selectImprovement(t)),e.find(".finalizeConjuration").click(()=>this.finalizeConjuration()),e.find(".ruleLink").click(t=>this.openRules(t)),e.find(".openChar").click(()=>{this.actor?.sheet.render(!0)}),e.find(".showEntity").click(t=>{t.stopPropagation(),u(async()=>{(await fromUuid(t.currentTarget.dataset.uuid)).sheet.render(!0)},"fun")()}),e.find(".moreModifiers").change(t=>{let a=this.conjurationData.moreModifiers[this.conjurationData.conjurationType].find(s=>s.name==t.currentTarget.dataset.name);a.selected=$(t.currentTarget).val()});for(let t of this.subApps)t.activateListeners(e)}async openRules(e){let t=e.currentTarget.dataset.subapp,a=(t?this.subApps.find(i=>i.constructor.name==t).constructor.rulePath:this.conjurationData.rules[this.conjurationData.conjurationType])[game.i18n.lang];u(async()=>{let r=await game.packs.get(a.pack).getDocuments({name:a.name});for(let n of r)n.sheet.render(!0)},"fun")()}finalizeConjuration(){if(!this.conjurationData)return;if(!this.conjuration)return ui.notifications.warn(game.i18n.localize("DSAError.noConjurationActive"));let e=[];for(let a of this.conjurationData.selectedIds)e.push(this.conjurationData.modifiers[this.conjurationData.conjurationType].find(s=>s.id==a));let t={source:this.conjuration.toObject(),creationData:{type:this.conjurationData.conjurationType,typeName:this.conjurationData.conjurationTypes[this.conjurationData.conjurationType],qs:this.conjurationData.qs,consumedQS:this.conjurationData.consumedQS,modifiers:e,entityIds:this.conjurationData.selectedEntityIds,packageIds:this.conjurationData.selectedPackageIds},summoner:{name:this.actor.name,img:this.actor.img}};game.user.isGM?Le.createConjuration(t):(game.socket.emit("system.dsa5",{type:"summonCreature",payload:t}),ui.notifications.notify(game.i18n.localize("CONJURATION.requestSend")))}static createConjuration({source:e,creationData:t,summoner:a}){new Fs(e,a,t).render(!0)}selectImprovement(e){let t=Number(e.currentTarget.dataset.max)||1,a=Number(e.currentTarget.dataset.selected)||0;a>=t?$(e.currentTarget).removeClass("selected"):($(e.currentTarget).addClass("selected"),e.currentTarget.dataset.selected=a+1);let s=[],i=[],r=[],n=0,o=0;$(this._element).find(".selectableRow.selected").each((c,m)=>{for(let d=0;d0){if(this.conjuration=a,this.conjurationData.selectedIds=[],this.conjurationData.selectedEntityIds=[],this.conjurationData.selectedPackageIds=[],a.type=="creature"){for(let s of Object.keys(this.conjurationData.conjurationTypes))if(a.system.creatureClass.value.includes(this.conjurationData.conjurationTypes[s])){this.conjurationData.conjurationType=s;break}}}else this.trackedId=t.id,this.actor=a;this.render(!0)}else for(let a of this.subApps)if(await a._onDrop(t)===!0)break}async prepareEntityAbilities(){let e={entityAbilities:[],entityPackages:[]};if(game.dsa5.itemLibrary.equipmentBuild){let t=[game.i18n.localize("LocalizedIDs.all"),this.conjurationData.conjurationTypes[this.conjurationData.conjurationType]],a=await Promise.all((await game.dsa5.itemLibrary.getCategoryItems("trait",!1)).map(r=>r.getItem())),s=new Set,i=new Set;for(let r of a)r.system.distribution&&t.some(n=>r.system.distribution.includes(n))&&(r.system.traitType.value=="entity"&&!s.has(r.name)?(s.add(r.name),e.entityAbilities.push(r),r.count=this.conjurationData.selectedEntityIds.filter(n=>n==r.uuid).length,r.max=r.system.at.value||1):r.system.traitType.value=="summoning"&&!i.has(r.name)&&(i.add(r.name),r.count=this.conjurationData.selectedPackageIds.filter(n=>n==r.uuid).length,e.entityPackages.push(r)))}return e}async getData(e){let t=await super.getData(e);if(!game.user.isGM&&!this.actor&&(this.actor=game.user.character),this.actor){let a=this.conjurationData.qs-this.conjurationData.consumedQS+1,s=game.dsa5.itemLibrary.equipmentBuild,{entityAbilities:i,entityPackages:r}=await this.prepareEntityAbilities(),n=this.actor.items.filter(p=>this.conjurationData.skills[this.conjurationData.conjurationType].includes(p.name)&&["liturgy","ceremony","spell","ritual"].includes(p.type)).map(p=>p.toObject()),o=!1;for(let p of n)p.hasMighty=this.actor.items.find(g=>g.name==`${p.name} - ${game.i18n.localize("CONJURATION.powerfulCreature")}`),o||(o=p.hasMighty);let c=this.conjurationData.modifiers[this.conjurationData.conjurationType],m=o?2:1;for(let p of c)p.max=m,p.count=this.conjurationData.selectedIds.filter(g=>g==p.id).length;let d=await renderTemplate("systems/dsa5/templates/system/conjuration/summoning.html",{actor:this.actor,conjuration:this.conjuration||{name:game.i18n.localize("CONJURATION.dragConjuration"),img:"icons/svg/mystery-man-black.svg"},conjurationData:this.conjurationData,services:a,conjurationModifiers:c,equipmentIndexLoaded:s,entityAbilities:i,entityPackages:r,moreModifiers:this.conjurationData.moreModifiers[this.conjurationData.conjurationType],hasMighty:o});mergeObject(t,{conjurationSheet:d,conjurationskills:n})}return mergeObject(t,{actor:this.actor||{name:game.i18n.localize("CONJURATION.dragActor"),img:"icons/svg/mystery-man-black.svg"},conjurationData:this.conjurationData,conjurationTypes:this.conjurationData.conjurationTypes}),await this.prepareSubApps(t),t}async prepareSubApps(e){e.subApps=[];for(let t of this.subApps)e.subApps.push(await t.prepareApp(e))}};u(Le,"PlayerMenu");var Fs=class extends ee{constructor(e,t,a){super({title:`${game.i18n.localize("CONJURATION.request")} (${t.name})`,default:"ok",buttons:{}}),this.conjuration=e,this.summoner=t,this.creationData=a,this.confirmed=!1}async getData(e){let t=await super.getData(e),a=this.uniqueCountIds(this.creationData.entityIds);return mergeObject(t,{conjuration:this.conjuration,summoner:this.summoner,confirmed:this.confirmed,services:this.creationData.qs-this.creationData.consumedQS+1,creationData:this.creationData,conjurationModifiers:this.creationData.modifiers,entityModifiers:await Promise.all(Object.keys(a).map(async s=>{let i=(await fromUuid(s)).toObject(!1);return i.uuid=s,i.count=a[s],i.cost=Number(i.system.AsPCost.value)*a[s],i})),packageModifiers:await Promise.all(this.creationData.packageIds.map(s=>fromUuid(s))),actor:this.actor}),t}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"main"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog"]),width:470}),e.template="systems/dsa5/templates/system/conjuration/request.html",e}uniqueCountIds(e){return e.reduce((t,a)=>(t[a]?++t[a]:t[a]=1,t),{})}async createActor(){this.confirmed=!0;let e=await f.getFolderForType("Actor",null,game.i18n.localize("PLAYER.conjuration")),t=await f.getFolderForType("Actor",e.id,this.creationData.typeName),a=this.creationData.qs-this.creationData.consumedQS+1;this.conjuration.folder=t.id,this.conjuration.effects||(this.conjuration.effects=[]);for(let c of this.creationData.modifiers)this.conjuration.effects.push({changes:c.changes,duration:{},icon:"icons/svg/aura.svg",label:game.i18n.localize(c.name),flags:{dsa5:{description:`${game.i18n.localize("PLAYER.conjuration")} ${game.i18n.localize("extensions")}`,hideOnToken:!0,hidePlayers:!1}}}),c.fun&&c.fun(this.conjuration,this.creationData);let s=this.uniqueCountIds(this.creationData.entityIds),i=(await Promise.all(Object.keys(s).map(c=>fromUuid(c)))).map(c=>{let m=c.toObject(!1);return s[c.uuid]>1&&(m.system.step={value:s[c.uuid]}),m}),r=(await Promise.all(this.creationData.packageIds.map(c=>fromUuid(c)))).map(c=>c.toObject(!1));this.conjuration.effects.push({changes:[],duration:{},icon:"icons/svg/aura.svg",id:"services",name:game.i18n.localize("PLAYER.services"),flags:{dsa5:{value:a,max:500,description:`${game.i18n.localize("PLAYER.conjuration")} ${game.i18n.localize("PLAYER.services")}`,manual:a,auto:0,hideOnToken:!0,hidePlayers:!1}}}),game.dsa5.apps.playerMenu.conjurationData.postFunction[this.creationData.type]&&await game.dsa5.apps.playerMenu.conjurationData.postFunction[this.creationData.type](this.conjuration,this.creationData.qs-this.creationData.consumedQS,this.creationData.type),this.conjuration.type=="creature"&&!this.conjuration.system.creatureClass.value.includes(this.creationData.typeName)&&(this.conjuration.system.creatureClass.value+=`, ${this.creationData.typeName}`),this.actor=await T.create(this.conjuration);let n=[...i,...r].filter(c=>!this.conjuration.items.find(m=>m.type==c.type&&c.name==m.name));await this.actor.createEmbeddedDocuments("Item",n);for(let c of r)await ue.traitAdded(this.actor,c);for(let c of i)await ue.traitAdded(this.actor,c);await this.actor.update({"system.status.wounds.value":this.actor.system.status.wounds.max});let o=await renderTemplate("systems/dsa5/templates/system/conjuration/chat.html",{actor:this.actor,modifiers:this.creationData.modifiers,summoner:this.summoner,summonerImg:j.videoOrImgTag(this.summoner.img),conjureImg:j.videoOrImgTag(this.actor.img),services:a});await ChatMessage.create(f.chatDataSetup(o)),this.render()}activateListeners(e){super.activateListeners(e),e.find(".createActor").click(()=>{this.createActor()}),e.on("mousedown",".newNPC",async t=>{let a=t.currentTarget.dataset.id;t.button==2&&(game.actors.get(a).delete(),$(t.currentTarget).remove())}),e.on("click",".newNPC",async t=>{let a=t.currentTarget.dataset.id;game.actors.get(a).sheet.render(!0)}),e.on("dragstart",".newNPC",t=>{t.stopPropagation();let a=t.currentTarget,s={type:"Actor",uuid:a.dataset.uuid};t.originalEvent.dataTransfer.setData("text/plain",JSON.stringify(s))}),e.find(".showEntity").click(t=>{t.stopPropagation(),u(async()=>{(await fromUuid(t.currentTarget.dataset.uuid)).sheet.render(!0)},"fun")()})}};u(Fs,"ConjurationRequest");var it=u(l=>class extends l{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["merchant-sheet"])}),e}static get merchantTemplate(){return"systems/dsa5/templates/actors/merchant/merchant-sheet.html"}get template(){if(this.merchantSheetActivated())switch(getProperty(this.actor.system,"merchant.merchantType")){case"merchant":return"systems/dsa5/templates/actors/merchant/merchant-limited.html";case"loot":return"systems/dsa5/templates/actors/merchant/merchant-limited-loot.html";case"epic":return"systems/dsa5/templates/actors/merchant/merchant-epic.html";default:return super.template}return this.constructor.merchantTemplate}merchantSheetActivated(){return this.showLimited()||this.playerViewEnabled()&&["merchant","loot","epic"].includes(getProperty(this.actor.system,"merchant.merchantType"))}async allowMerchant(e,t){let a=duplicate(this.actor.ownership),s=t?1:0;for(let i of e)a[i]=s;await this.actor.update({ownership:a},{diff:!1,recursive:!1,noHook:!0})}activateListeners(e){super.activateListeners(e),e.find(".allowMerchant").click(async t=>{let a=t.currentTarget.dataset.userId,s=$(t.currentTarget).find("i");await this.allowMerchant([a],!s.hasClass("fa-check-circle")),s.toggleClass("fa-circle fa-check-circle")}),e.find(".toggleAllAllowMerchant").click(async t=>{let a=game.users.filter(i=>!i.isGM).map(i=>i.id),s=t.currentTarget.dataset.lock=="true";await this.allowMerchant(a,s),this.render()}),e.find(".lockTradeSection").click(t=>this.lockTradeSection(t)),e.find(".item-tradeLock").click(t=>this.toggleTradeLock(t)),e.find(".randomGoods").click(t=>this.randomGoods(t)),e.find(".clearInventory").click(t=>this.clearInventory(t)),e.find(".removeOtherTradeFriend").click(()=>this.removeOtherTradeFriend()),e.find(".choseTradefriend").click(()=>this.choseTradefriend()),e.find(".setCustomPrice").click(t=>$(t.currentTarget).addClass("edit")),e.find(".customPriceTag").change(async t=>this.setCustomPrice(t)).blur(t=>$(t.currentTarget).closest(".setCustomPrice").removeClass("edit")),e.find(".buy-item").click(t=>{this.advanceWrapper(t,"buyItem",t),K.playMoneySound()}),e.find(".sell-item").click(t=>{this.advanceWrapper(t,"sellItem",t),K.playMoneySound()}),e.find(".item-external-edit").click(t=>{t.preventDefault();let a=this._getItemId(t);this.getTradeFriend().items.get(a).sheet.render(!0)}),e.find(".changeAmountAllItems").mousedown(t=>this.changeAmountAllItems(t)),e.find(".gearSearch").prop("disabled",!1)}_canDragStart(e){return!this.merchantSheetActivated()&&this.isEditable}async toggleTradeLock(e){let t=this._getItemId(e),a=this.actor.items.get(t);this.actor.updateEmbeddedDocuments("Item",[{_id:a.id,"system.tradeLocked":!a.system.tradeLocked}])}async setCustomPrice(e){e.stopPropagation(),e.preventDefault();let t=this._getItemId(e);await this.actor.updateEmbeddedDocuments("Item",[{_id:t,"flags.dsa5.customPriceTag":Number(e.target.value)}])}removeOtherTradeFriend(){this.otherTradeFriend=void 0,this.render(!0)}async choseTradefriend(){(await It.getDialog(this)).render(!0)}async lockTradeSection(e){let t=[],a=this.filterRule(e),s;for(let i of this.actor.items)if(a(i)){let r=i.toObject();s===void 0&&(s=!r.system.tradeLocked),r.system.tradeLocked=s,t.push(r)}this.actor.updateEmbeddedDocuments("Item",t)}filterRule(e){let t=e.currentTarget.dataset.type;return b.equipmentTypes[t]?a=>a.type=="equipment"&&a.system.equipmentType.value==t:a=>a.type==t&&b.equipmentCategories.has(a.type)}async changeAmountAllItems(e){let t=[],a=this.filterRule(e);for(let s of this.actor.items)if(a(s)){let i=s.toObject();P.increment(e,i,"system.quantity.value",0),t.push(i)}this.actor.updateEmbeddedDocuments("Item",t)}async buyItem(e){await this.transferItem(this.actor,this.getTradeFriend(),e,!0)}async sellItem(e){await this.transferItem(this.getTradeFriend(),this.actor,e,!1)}async transferItem(e,t,a,s=!0){let i=this._getItemId(a),r=a.currentTarget.dataset.price,n=a.ctrlKey?10:1;game.user.isGM?await this.constructor.finishTransaction(e,t,r,i,s,n):(this.constructor.noNeedToPay(t,e,r)||B.canPay(t,r,!0))&&game.socket.emit("system.dsa5",{type:"trade",payload:{target:this.constructor.transferTokenData(t),source:this.constructor.transferTokenData(e),price:r,itemId:i,buy:s,amount:n}})}static transferTokenData(e){let t={actor:e.id};return e.token&&(t.token=e.token.id),t}static async finishTransaction(e,t,a,s,i,r){let n=e.items.get(s).toObject();if(r=Math.min(Number(n.system.quantity.value),r),Number(n.system.quantity.value)>0){let o=this.noNeedToPay(t,e,a);if(o||await B.payMoney(t,a,!0))if(getProperty(n,"system.worn.value")&&(n.system.worn.value=!1),i){let m=await this.updateTargetTransaction(t,n,r,e,a);await this.updateSourceTransaction(e,t,n,a,s,r),await this.transferNotification(n,t,e,i,a,r,o,m),await this.selfDestruction(e)}else{await this.updateSourceTransaction(e,t,n,a,s,r);let m=await this.updateTargetTransaction(t,n,r,e,a);await this.transferNotification(n,e,t,i,a,r,o,m)}}}static isTemporaryToken(e){return getProperty(e.system,"merchant.merchantType")=="loot"&&getProperty(e.system,"merchant.temporary")}static async selfDestruction(e){if(this.isTemporaryToken(e)&&!e.items.some(a=>b.equipmentCategories.has(a.type)||a.type=="money"&&a.system.quantity.value>0)){game.socket.emit("system.dsa5",{type:"hideDeletedSheet",payload:{target:this.transferTokenData(e)}});let a=e.getActiveTokens().map(s=>s.id);await canvas.scene.deleteEmbeddedDocuments("Token",a),await game.actors.get(e.id).delete(),this.hideDeletedSheet(e)}}static async hideDeletedSheet(e){e.sheet.close(!0)}static async transferNotification(e,t,a,s,i,r,n,o){let c=game.settings.get("dsa5","merchantNotification");if(c==0||getProperty(e,"system.equipmentType.value")=="service")return;let m="MERCHANT."+(s?"buy":"sell")+(n?"Loot":"")+"Notification",d=e.type=="money"?game.i18n.localize(e.name):o.toAnchor().outerHTML,p=game.i18n.format(m,{item:d,source:t.name,target:a.name,amount:r,price:i,buy:s}),g=f.chatDataSetup(p);c==2&&(g.whisper=ChatMessage.getWhisperRecipients("GM").map(y=>y.id)),await ChatMessage.create(g)}static noNeedToPay(e,t,a){return a==0||getProperty(e.system,"merchant.merchantType")=="loot"||getProperty(t.system,"merchant.merchantType")=="loot"}static async updateSourceTransaction(e,t,a,s,i,r){let n=duplicate(a);Number(n.system.quantity.value)>r||n.type=="money"?(n.system.quantity.value=Number(n.system.quantity.value)-r,await e.updateEmbeddedDocuments("Item",[n])):await e.deleteEmbeddedDocuments("Item",[i]),this.noNeedToPay(e,t,s)||await B.getMoney(e,s,!0)}static async updateTargetTransaction(e,t,a,s,i){let r=duplicate(t);if(getProperty(r,"system.equipmentType.value")=="service"){let o=game.i18n.format("MERCHANT.buyNotification",{item:r.name,amount:a,source:e.name,target:s.name,price:i});ChatMessage.create(f.chatDataSetup(o))}else{let o=e.items.find(c=>A.areEquals(r,c));return r.system.quantity.value=a,o?(await A.stackItems(o,r,e),o):(await e.createEmbeddedDocuments("Item",[r]))[0]}}getTradeFriend(){return this.otherTradeFriend||game.user.character}async _manageDragItems(e,t){switch(t){case"creature":case"npc":case"character":this.setTradeFriend(e);break;default:return super._manageDragItems(e,t)}}async _onDropActor(e,t){let a=this.actor.limited,s=this.actor.isOwner;if(!(a||s))return!1;let{item:i,typeClass:r,selfTarget:n}=await Ge(t,this.id,!1);if(!n&&(s||a&&i.documentName=="Actor"))return await this._manageDragItems(i,r)}setTradeFriend(e){let t=game.actors.get(e._id);t.isOwner&&(this.otherTradeFriend=t,this.render(!0))}async _render(e=!1,t={}){if(!game.user.isGM&&getProperty(this.actor.system,"merchant.merchantType")=="loot"&&getProperty(this.actor.system,"merchant.locked")){AudioHelper.play({src:"sounds/lock.wav",loop:!1},!1);return}await super._render(e,t)}_togglePlayerview(e){this.actor.update({"system.merchant.playerView":!getProperty(this.actor.system,"merchant.playerView")})}playerViewEnabled(){return getProperty(this.actor.system,"merchant.playerView")}async randomGoods(e){let t=await renderTemplate("systems/dsa5/templates/dialog/randomGoods-dialog.html",{categories:Array.from(b.equipmentCategories)});new Dialog({title:game.i18n.localize("MERCHANT.randomGoods"),content:t,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:a=>this.addRandomGoods(this.actor,a,e)},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}async clearInventory(e){new Dialog({title:game.i18n.localize("MERCHANT.clearInventory"),content:game.i18n.localize("MERCHANT.deleteAllGoods"),default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{this.removeAllGoods(this.actor,e)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}async addRandomGoods(e,t,a){let s=$(a.currentTarget).text();$(a.currentTarget).html(' ');let i=[];t.find('input[type="checkbox"]:checked').each(function(){let c=$(this).val();i.push({name:c,count:Number(t.find(`input[name="each_${c}"]`).val()),number:Number(t.find(`input[name="number_${c}"]`).val())})});let r=game.dsa5.itemLibrary;r.equipmentBuild||await r.buildEquipmentIndex();let n=[];for(let c of i){let m=(await r.getRandomItems(c.name,c.number)).map(d=>{let p=d.toObject();return p.system.quantity.value=c.count,p});n.push(...m)}let o={};n=n.filter(function(c){let m=getProperty(c,"system.effect");m=typeof m=="object"&&m!==null&&getProperty(m,"attributes")||"";let d=Number(getProperty(c,"system.price.value"))||0;if(m!=""||d>1e4)return!1;let p=`${c.type}_${c.name}`;return(o.hasOwnProperty(p)?!1:o[p]=!0)&&e.items.filter(function(g){return g.type==c.type&&g.name==c.name}).length==0}),await e.createEmbeddedDocuments("Item",n),$(a.currentTarget).text(s)}async removeAllGoods(e,t){let a=$(t.currentTarget).text();$(t.currentTarget).html(' ');let s=e.items.filter(i=>b.equipmentCategories.has(i.type)&&!getProperty(i,"worn.value")).map(i=>i.id);await e.deleteEmbeddedDocuments("Item",s),$(t.currentTarget).text(a)}async getData(e){let t=await super.getData(e);return t.merchantType=getProperty(this.actor.system,"merchant.merchantType")||"none",t.merchantTypes={none:game.i18n.localize("MERCHANT.typeNone"),merchant:game.i18n.localize("MERCHANT.typeMerchant"),loot:game.i18n.localize("MERCHANT.typeLoot"),epic:game.i18n.localize("MERCHANT.typeEpic")},t.invName=t.merchantTypes[t.merchantType],t.players=game.users.filter(a=>!a.isGM).map(a=>(a.allowedMerchant=this.actor.testUserPermission(a,"LIMITED",!1),a.buyingFactor=getProperty(this.actor.system,`merchant.factors.buyingFactor.${a.id}`),a.sellingFactor=getProperty(this.actor.system,`merchant.factors.sellingFactor.${a.id}`),a)),t.merchantType!="epic"?(this.prepareStorage(t),this.merchantSheetActivated()&&(this.filterWornEquipment(t),this.prepareTradeFriend(t),t.prepare.inventory.misc.items.length==0&&(t.prepare.inventory.misc.show=!1))):(this.prepareStorage(t),t.garadanOptions={1:game.i18n.localize("GARADAN.1"),2:game.i18n.localize("GARADAN.2"),3:game.i18n.localize("GARADAN.3"),4:game.i18n.localize("GARADAN.4"),6:game.i18n.localize("GARADAN.6")}),t.hasOtherTradeFriend=!!this.otherTradeFriend,t}filterWornEquipment(e){for(let[t,a]of Object.entries(e.prepare.inventory))a.items=a.items.filter(s=>!getProperty(s,"system.worn.value"))}prepareStorage(e){if(e.merchantType=="merchant")for(let[t,a]of Object.entries(e.prepare.inventory))for(let s of a.items)s.defaultPrice=this.getItemPrice(s),s.calculatedPrice=Number(parseFloat(`${s.defaultPrice*(getProperty(this.actor.system,"merchant.sellingFactor")||1)}`).toFixed(2))*(getProperty(this.actor.system,`merchant.factors.sellingFactor.${game.user.id}`)||1),s.priceTag=` / ${s.calculatedPrice}`;else if(e.merchantType=="loot"){for(let[a,s]of Object.entries(e.prepare.inventory))for(let i of s.items)i.calculatedPrice=this.getItemPrice(i);let t={items:e.prepare.money.coins.map(a=>(a.name=game.i18n.localize(a.name),a)),show:!0,dataType:"money"};t.items.length&&(e.prepare.inventory.money=t)}}getItemPrice(e){return Number(getProperty(e,"flags.dsa5.customPriceTag"))||(e.type=="consumable"?A.getSubClass(e.type).consumablePrice(e):Number(e.system.price.value))}prepareTradeFriend(e){let t=this.getTradeFriend();if(t){let a=t.prepareItems({details:[]}),s=getProperty(this.actor.system,"merchant.merchantType")=="loot"?1:(getProperty(this.actor.system,"merchant.buyingFactor")||1)*(getProperty(this.actor.system,`merchant.factors.buyingFactor.${game.user.id}`)||1),i=this.prepareSellPrices(a.inventory,s);i.misc.items.length==0&&(i.misc.show=!1),e.merchantType=="loot"&&(i.money={items:a.money.coins.map(r=>(r.name=game.i18n.localize(r.name),r)),show:!0,dataType:"money"}),mergeObject(e,{tradeFriend:{img:t.img,name:t.name,inventory:i,money:a.money}})}else mergeObject(e,{tradeFriend:{inventory:[],money:{coins:[]}}})}prepareSellPrices(e,t){for(let[a,s]of Object.entries(e))for(let i of s.items)i.calculatedPrice=Number(parseFloat(`${this.getItemPrice(i)*t}`).toFixed(2));return e}},"MerchantSheetMixin"),It=class extends Dialog{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{}),e}static async getDialog(e){let t=game.user.isGM?await game.dsa5.apps.gameMasterMenu.getTrackedHeros():game.actors.filter(s=>s.isOwner),a=new It({title:game.i18n.localize("DIALOG.setTargetToUser"),content:await renderTemplate("systems/dsa5/templates/dialog/selectTradeFriend.html",{users:t}),default:"yes",buttons:{}});return a.actor=e,a}activateListeners(e){super.activateListeners(e),e.find(".combatant").click(t=>this.setTargetToUser(t))}setTargetToUser(e){this.actor.setTradeFriend({_id:e.currentTarget.dataset.id}),this.close()}};u(It,"SelectTradefriendDialog");var Ae=class extends it(xe){};u(Ae,"MerchantSheetDSA5");function zi(){game.socket.on("system.dsa5",l=>{switch(l.type){case"brawlStart":He.brawlStart(2e3,!1);return;case"hideDeletedSheet":let e=l.payload.target.token?game.actors.tokens[l.payload.target.token]:game.actors.get(l.payload.target.actor);Ae.hideDeletedSheet(e);return;default:if(pe.socketListeners(l))return}if(!!f.isActiveGM())switch(l.type){case"updateKeepField":b.allowedforeignfields.includes(l.payload.field)&&game.actors.get(l.payload.actorId).update({[l.payload.field]:l.payload.updateData});break;case"target":{let e=game.scenes.get(l.payload.scene);new Token(e.getEmbeddedDocument("Token",l.payload.target)).actor.update({"flags.oppose":l.payload.opposeFlag})}break;case"addEffect":Q.applyEffect(l.payload.id,l.payload.mode,l.payload.actors);break;case"updateMsg":game.messages.get(l.payload.id).update(l.payload.updateData);break;case"deleteMsg":game.messages.get(l.payload.id).delete();break;case"showDamage":j.showDamage(game.messages.get(l.payload.id),l.payload.hide);break;case"hideQueryButton":j.hideReactionButton(l.payload.id);break;case"updateGroupCheck":q.rerenderGC(game.messages.get(l.payload.messageId),l.payload.data);break;case"apTracker":_.receiveSocketEvent(l);break;case"updateAttackMessage":game.messages.get(l.payload.messageId).update({"flags.data.unopposedStartMessage":l.payload.startMessageId});break;case"clearCombat":game.combat&&game.combat.nextRound();break;case"clearOpposed":j.clearOpposed(game.actors.get(l.payload.actorId));break;case"updateDefenseCount":game.combat&&game.combat.updateDefenseCount(l.payload.speaker);break;case"trade":{let e=l.payload.source.token?game.actors.tokens[l.payload.source.token]:game.actors.get(l.payload.source.actor),t=l.payload.target.token?game.actors.tokens[l.payload.target.token]:game.actors.get(l.payload.target.actor);Ae.finishTransaction(e,t,l.payload.price,l.payload.itemId,l.payload.buy,l.payload.amount)}break;case"playWhisperSound":l.payload.whisper.includes(game.user.id)&&AudioHelper.play({src:l.payload.soundPath,volume:.8,loop:!1},!1);break;case"socketedConditionAddActor":fromUuid(l.payload.id).then(e=>{new X(e).socketedConditionAddActor(l.payload.actors.map(a=>game.actors.get(a)),l.payload.data)});break;case"socketedConditionAdd":fromUuid(l.payload.id).then(e=>{new X(e).socketedConditionAdd(l.payload.targets,l.payload.data)});break;case"socketedRemoveCondition":fromUuid(l.payload.id).then(e=>{new X(e).socketedRemoveCondition(l.payload.targets,l.payload.coreId)});break;case"socketedActorTransformation":fromUuid(l.payload.id).then(e=>{new X(e).socketedActorTransformation(l.payload.targets,l.payload.update)});break;case"itemDrop":{let e=l.payload.sourceActorId?game.actors.get(l.payload.sourceActorId):void 0;fromUuid(l.payload.itemId).then(t=>{si(e,t,l.payload.data,l.payload.amount)})}break;case"finalizeFoodContribution":case"finalizeidentification":case"updateHits":case"hideResistButton":break;case"reduceGroupSchip":T.reduceGroupSchip();break;case"summonCreature":Le.createConjuration(l.payload);break;default:console.warn(`Unhandled socket data type ${l.type}`)}})}u(zi,"connectSocket");function ci(){Hooks.on("ready",async()=>{zi(),f.moduleEnabled("vtta-tokenizer")&&!await game.settings.get("dsa5","tokenizerSetup")&&game.user.isGM&&(await game.settings.set("vtta-tokenizer","default-frame-pc","[data] systems/dsa5/icons/backgrounds/token_green.webp"),await game.settings.set("vtta-tokenizer","default-frame-npc","[data] systems/dsa5/icons/backgrounds/token_black.webp"),await game.settings.set("vtta-tokenizer","default-frame-neutral","[data] systems/dsa5/icons/backgrounds/token_blue.webp"),await game.settings.set("dsa5","tokenizerSetup",!0)),f.moduleEnabled("dice-so-nice")&&!await game.settings.get("dsa5","diceSetup")&&game.user.isGM&&(await game.settings.set("dice-so-nice","immediatelyDisplayChatMessages",!0),await game.settings.set("dsa5","diceSetup",!0)),await ze.firstTimeMessage(),A.setupSubClasses(),Fe.showOneMessage(),Se.registerTokenHotbar(),$i(),Pe.connectHooks();let l=u(e=>{e.tabName=="settings"&&(Ne.travelAgency(),Hooks.off("changeSidebarTab",l))},"hook");Hooks.on("changeSidebarTab",l),Ei(),Ai()})}u(ci,"default");function di(){Token.prototype.drawEffects=async function(){this.effects.removeChildren().forEach(i=>i.destroy()),this.effects.bg=this.effects.addChild(new PIXI.Graphics),this.effects.overlay=null;let t=this.document.effects,a=[];this.actor&&(a=await this.actor.actorEffects(),this.actor.isSwarm()&&a.push(new ActiveEffect({icon:"systems/dsa5/icons/thirdparty/bee.svg",id:"swarm",name:"swarm.name",flags:{dsa5:{value:this.actor.system.swarm?.effectiveCount||1}}})));let s={src:this.document.overlayEffect,tint:null};if(t.length||a.length){let i=[];for(let r of a){if(!r.icon)continue;let n=Color.from(r.tint??null);if(r.getFlag("core","overlay")){s={src:r.icon,tint:n};continue}i.push(this._drawEffect(r.icon,n,getProperty(r,"flags.dsa5.value")))}for(let r of t)i.push(this._drawEffect(r,null));await Promise.all(i)}this.effects.overlay=await this._drawOverlay(s.src,s.tint),this._refreshEffects()},Token.prototype._refreshEffects=function(){let t=0,a=Math.round(canvas.dimensions.size/2/5)*2,s=Math.floor(this.document.height*5),i=this.effects.bg.clear().beginFill(0,.4).lineStyle(1,0);for(let r of this.effects.children)if(r!==i&&!r.isCounter)if(r===this.effects.overlay){let n=Math.min(this.w*.6,this.h*.6);r.width=r.height=n,r.position.set((this.w-n)/2,(this.h-n)/2)}else{if(r.width=r.height=a,r.x=Math.floor(t/s)*a,r.y=t%s*a,i.drawRoundedRect(r.x+1,r.y+1,a-2,a-2,2),r.counter>1&&!r.counterDrawn){let n=game.dsa5.config.effectTextStyle,o=game.settings.get("dsa5","statusEffectCounterColor");n._fill=/^#[0-9A-F]+$/.test(o)?o:"#000000";let c=this.effects.addChild(new PreciseText(r.counter,n));c.x=r.x,c.y=r.y,c.isCounter=!0,r.counterDrawn=!0}t++}},Token.prototype._drawEffect=async function(t,a,s){if(!t)return;let i=await loadTexture(t,{fallback:"icons/svg/hazard.svg"}),r=new PIXI.Sprite(i);return a&&(r.tint=a),r.counter=s,this.effects.addChild(r)},TokenHUD.prototype._onToggleEffect=function(t,{overlay:a=!1}={}){t.preventDefault();let s=t.currentTarget,i=s.dataset.statusId&&this.object.actor?CONFIG.statusEffects.find(r=>r.id===s.dataset.statusId):s.getAttribute("src");if(t.button==0)return this.object.incrementCondition(i);if(t.button==2)return this.object.decrementCondition(i)},Token.prototype.incrementCondition=async function(t,{active:a,overlay:s=!1}={}){let i=this.actor.effects.find(r=>r.statuses.has(t.id));return!i||Number.isNumeric(getProperty(i,"flags.dsa5.value"))?await this.actor.addCondition(t.id,1,!1,!1):i&&await this.actor.removeCondition(t.id,1,!1),this.hasActiveHUD&&canvas.tokens.hud.refreshStatusIcons(),a},Token.prototype.decrementCondition=async function(t,{active:a,overlay:s=!1}={}){return this.actor.removeCondition(t.id,1,!1),this.hasActiveHUD&&canvas.tokens.hud.refreshStatusIcons(),a};let l=Token.prototype._onClickLeft2,e=u(t=>t?["merchant","loot"].includes(getProperty(t.system,"merchant.merchantType")):!1,"isMerchant");Token.prototype._onClickLeft2=function(t){if(!(game.user.isGM||!J.isEnabled||!e(this.actor)||J.inDistance(this)))return ui.notifications.warn(game.i18n.localize("DSAError.notInRangeToLoot"));l.call(this,t)}}u(di,"default");function mi(){Hooks.on("renderSettings",(l,e,t)=>{let a=$(``);a.on("click",()=>{window.open("https://github.com/Plushtoast/dsa5-foundryVTT/issues","_blank")}),e.find("#settings-documentation").append(a),a=$(``),a.on("click",()=>{window.open("https://github.com/Plushtoast/dsa5-foundryVTT/wiki","_blank")}),e.find("#settings-documentation").append(a),a=$(''),a.on("click",()=>{window.open(game.i18n.localize("fshopLink"),"_blank")}),e.find("#settings-documentation").append(a);let s=game.system.title.split("/")[game.i18n.lang=="de"?0:1],i=e.find("#game-details .system .system-info").html();e.find("#game-details .system").html(`${s}${i}`)}),Hooks.on("renderCompendiumDirectory",(l,e,t)=>{let a=$(``);e.find(".header-actions").append(a),a.on("click",()=>{game.dsa5.itemLibrary.render(!0)}),e.find('li[data-pack="dsa5.money"]').remove()}),Hooks.once("renderCompendiumDirectory",(l,e,t)=>{let a=game.i18n.lang=="de"?"en":"de",s=game.packs.filter(i=>getProperty(i.metadata,"flags.dsalang")==a);for(let i of s){let r=`${i.metadata.packageName}.${i.metadata.name}`;game.packs.delete(r),game.data.packs=game.data.packs.filter(n=>n.id!=r),e.find(`li[data-pack="${r}"]`).remove()}}),Hooks.on("renderActorDirectory",(l,e,t)=>{if(!game.user.isGM)for(let a of l.documents.filter(s=>s.isMerchant()&&getProperty(s,"system.merchant.hidePlayer")))e.find(`[data-document-id="${a.id}"]`).remove()})}u(mi,"default");function Pi(){game.settings.register("dsa5","meleeBotchTableEnabled",{name:"DSASETTINGS.meleeBotchTableEnabled",hint:"DSASETTINGS.meleeBotchTableEnabledHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","rangeBotchTableEnabled",{name:"DSASETTINGS.rangeBotchTableEnabled",hint:"DSASETTINGS.rangeBotchTableEnabledHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","applyDamageInChat",{name:"DSASETTINGS.applyDamageInChat",hint:"DSASETTINGS.applyDamageInChatHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","doubleDamageOptions",{name:"DSASETTINGS.doubleDamageOptions",hint:"DSASETTINGS.doubleDamageOptionsHint",scope:"client",config:!0,default:!1,type:Boolean,requiresReload:!0}),game.settings.register("dsa5","defenseBotchTableEnabled",{name:"DSASETTINGS.defenseBotchTableEnabled",hint:"DSASETTINGS.defenseBotchTableEnabledHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","higherDefense",{name:"DSASETTINGS.higherDefense",hint:"DSASETTINGS.higherDefenseHint",scope:"world",config:!0,default:"0",type:String,choices:{0:"0",2:"+2",4:"+4"}}),game.settings.register("dsa5","informationDistribution",{name:"DSASETTINGS.informationDistribution",hint:"DSASETTINGS.informationDistributionHint",scope:"world",config:!0,default:"0",type:String,choices:{0:game.i18n.localize("DSASETTINGS.information0"),1:game.i18n.localize("DSASETTINGS.information1"),2:game.i18n.localize("DSASETTINGS.information2")}}),game.settings.register("dsa5","enableItemDropToCanvas",{name:"DSASETTINGS.enableItemDropToCanvas",hint:"DSASETTINGS.enableItemDropToCanvasHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","statusEffectCounterColor",{name:"DSASETTINGS.statusEffectCounterColor",hint:"DSASETTINGS.statusEffectCounterColorHint",scope:"client",config:!0,default:"#FFFFFF",type:String}),game.settings.register("dsa5","migrationVersion",{name:"migrationVersion",hint:"migrationVersion",scope:"world",config:!1,default:25,type:Number}),game.settings.register("dsa5","journalFontSizeIndex",{name:"journalFontSizeIndex",hint:"journalFontSizeIndex",scope:"client",config:!1,default:5,type:Number}),game.settings.register("dsa5","firstTimeStart",{name:"firstTimeStart",hint:"firstTimeStart",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","defaultConfigFinished",{name:"defaultConfigFinished",hint:"defaultConfigFinished",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","tokenizerSetup",{name:"tokenizerSetup",hint:"tokenizerSetup",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","diceSetup",{name:"diceSetup",hint:"diceSetup",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","capQSat",{name:"DSASETTINGS.capQSat",hint:"DSASETTINGS.capQSatHint",scope:"world",config:!0,default:6,type:Number}),game.settings.register("dsa5","hideEffects",{name:"DSASETTINGS.hideEffects",hint:"DSASETTINGS.hideEffectsHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","inventorySound",{name:"DSASETTINGS.inventorySound",hint:"DSASETTINGS.inventorySoundHint",scope:"client",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","talentModifierEnabled",{name:"DSASETTINGS.talentModifierEnabled",hint:"DSASETTINGS.talentModifierEnabledHint",scope:"client",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","noConfirmationRoll",{name:"DSASETTINGS.noConfirmationRoll",hint:"DSASETTINGS.noConfirmationRollHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","lessRegeneration",{name:"DSASETTINGS.lessRegeneration",hint:"DSASETTINGS.lessRegenerationHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","limitCombatSpecAbs",{name:"DSASETTINGS.limitCombatSpecAbs",hint:"DSASETTINGS.limitCombatSpecAbsHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","allowPhysicalDice",{name:"DSASETTINGS.allowPhysicalDice",hint:"DSASETTINGS.allowPhysicalDiceHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","hideOpposedDamage",{name:"DSASETTINGS.hideOpposedDamage",hint:"DSASETTINGS.hideOpposedDamageHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","enableForeignSpellModifer",{name:"DSASETTINGS.enableForeignSpellModifer",hint:"DSASETTINGS.enableForeignSpellModiferHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","playerCanEditSpellMacro",{name:"DSASETTINGS.playerCanEditSpellMacro",hint:"DSASETTINGS.playerCanEditSpellMacroHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","enableDPS",{name:"DSASETTINGS.enableDPS",hint:"DSASETTINGS.enableDPSHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","iniTrackerSize",{name:"DSASETTINGS.iniTrackerSize",hint:"DSASETTINGS.iniTrackerSizeHint",scope:"client",config:!0,default:70,type:Number,range:{min:30,max:140,step:5},onChange:async e=>{game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.constructor.defaultOptions.itemWidth=e)}}),game.settings.register("dsa5","iniTrackerCount",{name:"DSASETTINGS.iniTrackerCount",hint:"DSASETTINGS.iniTrackerCountHint",scope:"client",config:!0,default:5,type:Number,range:{min:3,max:25,step:1},onChange:async e=>{game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.constructor.defaultOptions.actorCount=e)}}),game.settings.register("dsa5","tokenhotbarSize",{name:"DSASETTINGS.tokenhotbarSize",hint:"DSASETTINGS.tokenhotbarSizeHint",scope:"client",config:!1,default:35,type:Number,range:{min:15,max:100,step:5},onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","tokenhotbarLayout",{name:"DSASETTINGS.tokenhotbarLayout",hint:"DSASETTINGS.tokenhotbarLayoutHint",scope:"client",config:!1,default:0,type:Number,choices:{0:game.i18n.localize("DSASETTINGS.tokenhotbarLayout0"),2:game.i18n.localize("DSASETTINGS.tokenhotbarLayout1"),1:game.i18n.localize("DSASETTINGS.tokenhotbarLayout2"),3:game.i18n.localize("DSASETTINGS.tokenhotbarLayout3")},onChange:async e=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}});let l=duplicate(b.styles);for(let e of Object.keys(l))l[e]=game.i18n.localize(l[e]);game.settings.register("dsa5","globalStyle",{name:"DSASETTINGS.globalStyle",hint:"DSASETTINGS.globalStyleHint",scope:"client",config:!0,default:"dsa5-immersive",type:String,choices:l,onChange:async e=>{$("body").removeClass(Object.keys(l).join(" ")).addClass(e)}}),game.settings.register("dsa5","selfControlOnPain",{name:"DSASETTINGS.selfControlOnPain",hint:"DSASETTINGS.selfControlOnPainHint",scope:"world",config:!0,default:1,type:Number,choices:{0:game.i18n.localize("DSASETTINGS.selfControlOnPain0"),1:game.i18n.localize("DSASETTINGS.selfControlOnPain1"),2:game.i18n.localize("DSASETTINGS.selfControlOnPain2")}}),game.settings.register("dsa5","forceLanguage",{name:"DSASETTINGS.forceLanguage",hint:"DSASETTINGS.forceLanguageHint",scope:"world",config:!0,default:"none",type:String,choices:{none:"-",de:"German",en:"English"}}),game.settings.register("dsa5","hotbarv3",{name:"DSASETTINGS.hotbarv3",hint:"DSASETTINGS.hotbarv3Hint",scope:"client",config:!1,default:!0,type:Boolean,onChange:()=>{ui.hotbar.render(!0)}}),game.settings.register("dsa5","tokenhotbarPosition",{name:"tokenhotbarPosition",scope:"client",config:!1,default:{},type:Object}),game.settings.register("dsa5","masterSettings",{name:"masterSettings",scope:"world",config:!1,default:{},type:Object}),game.settings.register("dsa5","iniTrackerPosition",{name:"iniTrackerPosition",scope:"client",config:!1,default:{},type:Object}),game.settings.register("dsa5","soundConfig",{name:"DSASETTINGS.soundConfig",hint:"DSASETTINGS.soundConfigHint",scope:"world",config:!0,default:"",type:String,onChange:async()=>{K.loadSoundConfig()}}),game.settings.registerMenu("dsa5","changelog",{name:"Changelog",label:"Changelog",hint:game.i18n.localize("DSASETTINGS.changelog"),type:Hs,restricted:!1}),game.settings.registerMenu("dsa5","exportConfiguration",{name:"Export/Import Configuration",label:"Export/Import Configuration",hint:game.i18n.localize("DSASETTINGS.exportConfiguration"),type:js,restricted:!0}),game.settings.registerMenu("dsa5","configureTokenbar",{name:game.i18n.localize("DSASETTINGS.configureTokenbar"),label:game.i18n.localize("DSASETTINGS.configureTokenbar"),hint:game.i18n.localize("DSASETTINGS.configureTokenbarHint"),type:Gs,restricted:!1}),game.settings.register("dsa5",`breadcrumbs_${game.world.id}`,{name:"DSASETTINGS.breadcrumbs",hint:"DSASETTINGS.breadcrumbsHint",scope:"client",config:!1,default:"",type:String}),game.settings.register("dsa5","groupschips",{name:"DSASETTINGS.groupschips",hint:"DSASETTINGS.groupschips",scope:"world",config:!1,default:"0/0",type:String,onChange:async()=>{game.user.isGM&&game.dsa5.apps.gameMasterMenu.render()}}),game.settings.register("dsa5","expandChatModifierlist",{name:"DSASETTINGS.expandChatModifierlist",hint:"DSASETTINGS.expandChatModifierlistHint",scope:"client",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","indexWorldItems",{name:"DSASETTINGS.indexWorldItems",scope:"client",config:!1,default:!0,type:Boolean}),game.settings.register("dsa5","filterDuplicateItems",{name:"DSASETTINGS.filterDuplicateItems",scope:"client",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","enableCombatFlow",{name:"DSASETTINGS.enableCombatFlow",hint:"DSASETTINGS.enableCombatFlowHint",scope:"client",config:!0,default:!0,type:Boolean,onchange:()=>{game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.close(),game.dsa5.apps.initTracker=void 0)}}),game.settings.register("dsa5","enableCombatPan",{name:"DSASETTINGS.enableCombatPan",hint:"DSASETTINGS.enableCombatPanHint",scope:"client",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","enableAPTracking",{name:"DSASETTINGS.enableAPTracking",hint:"DSASETTINGS.enableAPTrackingHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","sightAutomationEnabled",{name:"sightAutomationEnabled",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","lightSightCompensationEnabled",{name:"lightSightCompensationEnabled",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","randomWeaponSelection",{name:"DSASETTINGS.randomWeaponSelection",hint:"DSASETTINGS.randomWeaponSelection",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","showWeaponsOnHover",{name:"DSASETTINGS.showWeaponsOnHover",hint:"DSASETTINGS.showWeaponsOnHover",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","disableDidYouKnow",{name:"DSASETTINGS.disableDidYouKnow",hint:"DSASETTINGS.disableDidYouKnowHint",scope:"client",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","disableTokenhotbar",{name:"DSASETTINGS.disableTokenhotbar",hint:"DSASETTINGS.disableTokenhotbarHint",scope:"client",config:!1,default:!0,type:Boolean,onChange:e=>{e?game.dsa5.apps.tokenHotbar?.close():game.dsa5.apps.tokenHotbar?.render(!0)}}),game.settings.register("dsa5","disableTokenhotbarMaster",{name:"DSASETTINGS.disableTokenhotbarMaster",hint:"DSASETTINGS.disableTokenhotbarMasterHint",scope:"client",config:!1,default:!1,type:Boolean,onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","scrollingFontsize",{name:"DSASETTINGS.scrollingFontsize",hint:"DSASETTINGS.scrollingFontsizeHint",scope:"client",config:!0,default:16,type:Number,range:{min:6,max:50,step:1}}),game.settings.register("dsa5","tokenhotbaropacity",{name:"DSASETTINGS.tokenhotbaropacity",hint:"DSASETTINGS.tokenhotbaropacityHint",scope:"client",config:!1,default:.75,type:Number,range:{min:0,max:1,step:.05},onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","armorAndWeaponDamage",{name:"DSASETTINGS.armorAndWeaponDamage",hint:"DSASETTINGS.armorAndWeaponDamageHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","hideRegenerationToOwner",{name:"DSASETTINGS.hideRegenerationToOwner",hint:"DSASETTINGS.hideRegenerationToOwnerHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","indexDescription",{name:"DSASETTINGS.indexDescription",scope:"client",config:!1,default:!0,type:Boolean}),game.settings.register("dsa5","encumbranceForRange",{name:"DSASETTINGS.encumbranceForRange",hint:"DSASETTINGS.encumbranceForRangeHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","obfuscateTokenNames",{name:"DSASETTINGS.obfuscateTokenNames",hint:"DSASETTINGS.obfuscateTokenNamesHint",scope:"world",config:!0,default:"0",type:String,choices:{0:game.i18n.localize("no"),1:game.i18n.localize("DSASETTINGS.yesNumbered"),2:game.i18n.localize("DSASETTINGS.renameNumbered"),3:game.i18n.localize("yes"),4:game.i18n.localize("DSASETTINGS.rename")}}),game.settings.register("dsa5","merchantNotification",{name:"DSASETTINGS.merchantNotification",hint:"DSASETTINGS.merchantNotificationHint",scope:"world",config:!0,default:"0",type:String,choices:{0:game.i18n.localize("no"),1:game.i18n.localize("yes"),2:game.i18n.localize("MERCHANT.onlyGM")}}),game.settings.register("dsa5","sightOptions",{name:"sightOptions",scope:"world",config:!1,default:"0.5|0.7|0.85|0.95",type:String}),game.settings.register("dsa5","trackedActors",{name:"sightOptions",scope:"world",config:!1,default:{},type:Object}),game.settings.register("dsa5","enableMasterTokenFunctions",{name:"enableMasterTokenFunctions",scope:"world",config:!1,default:{},type:Object,onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","selectedActors",{name:"selectedActors",scope:"world",config:!1,default:{},type:Object}),game.settings.register("dsa5","expansionPermissions",{name:"expansionPermissions",scope:"world",config:!1,default:{},type:Object})}u(Pi,"setupConfiguration");var lr=u(l=>{let e=Array.from(game.settings.settings);l.find('[name="exportOnlyDSA"]').is(":checked")&&(e=e.filter(r=>/^dsa5\./.test(r[0])));let a={},s=/(^dsa5\.(selectedActors|trackedActors|groupschips|tokenhotbarPosition|iniTrackerPosition|migrationVersion)$|^dsa5\.breadcrumbs_)/;for(let r of e){if(s.test(r[0]))continue;let n=r[0].split("."),o=n.shift(),c=n.join(".");a[r[0]]=game.settings.get(o,c)}let i="fvtt-DSA5-Configuration.json";saveDataToFile(JSON.stringify(a,null,2),"text/json",i)},"exportSetting"),cr=u(async l=>{let e=l.find("form")[0];if(!e.data.files.length)return ui.notifications?.error("You did not upload a data file!");readTextFromFile(e.data.files[0]).then(async t=>{let a=JSON.parse(t),s=Array.from(game.settings.settings).map(i=>i[0]);for(let i of Object.keys(a))if(s.includes(i)){let r=i.split("."),n=r.shift(),o=r.join(".");await game.settings.set(n,o,a[i])}game.settings.sheet.render(!0)})},"importSettings"),Hs=class extends FormApplication{render(){Gt()}};u(Hs,"ChangelogForm");var js=class extends FormApplication{async render(){let e=await renderTemplate("systems/dsa5/templates/dialog/exportConfiguration-dialog.html",{});new Dialog({title:"Export configuration",content:e,default:"yes",buttons:{export:{icon:'',label:game.i18n.localize("Export"),callback:t=>lr(t)},import:{icon:'',label:game.i18n.localize("Import"),callback:t=>cr(t)}}}).render(!0)}};u(js,"ExportForm");var Gs=class extends FormApplication{get template(){return"systems/dsa5/templates/dialog/configureTokenhotbar.html"}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{title:game.i18n.localize("DSASETTINGS.configureTokenbar"),width:500}),e}activateListeners(e){super.activateListeners(e),e.find(".resetTokenhotbar").click(t=>this.resetTokenHotbar(t)),e.find("select, input").change(async t=>{let a=t.currentTarget.name.split("."),s=t.currentTarget.dataset.dtype=="Number"?Number(t.currentTarget.value):t.currentTarget.value;t.currentTarget.type=="checkbox"&&(s=t.currentTarget.checked),await game.settings.set(a[0],a[1],s),this.render()}),e.find(".bags .slot").click(t=>this._onMasterFunctionClicked(t))}async _onMasterFunctionClicked(e){let t=e.currentTarget.dataset.id,a=game.settings.get("dsa5","enableMasterTokenFunctions");a[t]=!a[t],$(e.currentTarget).toggleClass("deactivated",a[t]),game.dsa5.apps.tokenHotbar.gmItems.find(s=>s.id==t).disabled=a[t],await game.settings.set("dsa5","enableMasterTokenFunctions",a)}async getData(e){let t=await super.getData(e);return mergeObject(t,{tokenhotbarSize:game.settings.get("dsa5","tokenhotbarSize"),tokenhotbarLayout:game.settings.get("dsa5","tokenhotbarLayout"),disableTokenhotbarMaster:game.settings.get("dsa5","disableTokenhotbarMaster"),disableTokenhotbar:game.settings.get("dsa5","disableTokenhotbar"),tokenhotbaropacity:game.settings.get("dsa5","tokenhotbaropacity"),hotbarv3:game.settings.get("dsa5","hotbarv3"),isGM:game.user.isGM,gmButtons:game.dsa5.apps.tokenHotbar?.gmItems}),t}async resetTokenHotbar(e){e.preventDefault(),e.stopPropagation(),await game.settings.set("dsa5","tokenhotbarPosition",{}),await game.settings.set("dsa5","tokenhotbarLayout",0),await game.settings.set("dsa5","tokenhotbarSize",35),game.dsa5.apps.tokenHotbar?.resetPosition(),game.dsa5.apps.tokenHotbar?.render(!0)}};u(Gs,"ConfigureTokenHotbar");function pi(){Hooks.on("renderJournalSheet",(l,e,t)=>{e.find(".close").attr("data-tooltip","SHEET.Close"),e.find(".entry-image").attr("data-tooltip","SHEET.imageView"),e.find(".entry-text").attr("data-tooltip","SHEET.textView"),e.find(".share-image").attr("data-tooltip","SHEET.showToPlayers"),e.find(".import").attr("data-tooltip","SHEET.import"),e.find(".panMapNote").attr("data-tooltip","SHEET.panMapNote"),e.find(".increaseFontSize").attr("data-tooltip","SHEET.increaseFontSize")}),Hooks.on("renderJournalPageSheet",(l,e,t)=>{se.bindRollCommands(e),E.bindButtons(e),e.find("img").mousedown(a=>{a.button==2&&game.dsa5.apps.DSA5_Utility.showArtwork({name:l.name,uuid:"",img:$(a.currentTarget).attr("src")})}),mt(e)}),Hooks.on("getJournalSheetHeaderButtons",(l,e)=>{e.unshift({class:"increaseFontSize",icon:"fas fa-arrows-up-down",onclick:async()=>gi($(l._element).find(".journal-page-content"))}),!(!l.document.sceneNote&&!l.document.pages.some(t=>t.sceneNote))&&e.unshift({class:"panMapNote",icon:"fas fa-map-pin",onclick:async()=>{let t=l._getCurrentPage(),a=Array.from(l.document.pages),s;if(a[t].sceneNote)s=a[t];else if(l.document.sceneNote)s=l.document;else if(s=a.find(i=>i.sceneNote),!s)return;canvas.notes.panToNote(s.sceneNote)}})})}u(pi,"default");async function gi(l){let t=game.settings.get("dsa5","journalFontSizeIndex")+1;t==b.journalFontSizes.length+1?(t=0,await game.settings.set("dsa5","journalFontSizeIndex",t),l.css("fontSize",""),de(game.i18n.format("CHATNOTIFICATION.fontsize",{size:"Default "}))):(await game.settings.set("dsa5","journalFontSizeIndex",t),dr(l))}u(gi,"increaseFontSize");function dr(l){let e=game.settings.get("dsa5","journalFontSizeIndex"),t=b.journalFontSizes[e-1]||14;de(game.i18n.format("CHATNOTIFICATION.fontsize",{size:t})),l.css("fontSize",`${t}px`)}u(dr,"setOuterFontSize");function ur(l,e,t){if(e.system.isPriest&&e.system.isMage){let s=`
    `;l.find(".col.middle").prepend(s),l.find(".bar3 input").change(async i=>{let r=i.currentTarget,n=r.value.trim(),o=n.startsWith("+")||n.startsWith("-");n.startsWith("=")&&(n=n.slice(1));let c=Number(n),m=r.name.split(".").reduce((d,p)=>d[p],e);await e.update({[r.name]:o?m+c:c}),t.clear()})}}u(ur,"addThirdBarToHUD");function pr(l,e,t){if(!game.user.isGM)return;let a=l.object.actor;if(!!a.isToken){if(canvas.tokens.controlled.length>=2){let s=a._id;if(!canvas.tokens.controlled.every(r=>r.actor?._id==s))return;e.find(".col.left").prepend(Ni("swarm.combine"));let i=e.find('.control-icon[data-action="swarm"]');i.click(()=>{fr(a,l.object.document),i.remove()})}else if(a.isSwarm()){e.find(".col.left").prepend(Ni("swarm.split"));let s=e.find('.control-icon[data-action="swarm"]');s.click(()=>{gr(a,l.object.document),s.remove()})}}}u(pr,"swarmButtons");var Bs=class extends Dialog{activateListeners(e){super.activateListeners(e),e.find('input[type="range"]').change(t=>{$(t.currentTarget).closest(".row-section").find(".range-value").html($(t.currentTarget).val())})}};u(Bs,"SwarmDialog");function Ni(l){return`
    `}u(Ni,"swarmHud");async function gr(l,e){let t=Number(l.system.swarm.count)-1,a=await renderTemplate("systems/dsa5/templates/dialog/swarm-split-dialog.html",{actor:l,maxSplitsize:t});new Bs({title:game.i18n.localize("swarm.split"),content:a,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("ok"),callback:async s=>{let i=Number(s.find('input[type="range"]').val()),r=deepClone(e),n=Math.floor(l.system.status.wounds.value/l.system.swarm.count*i),o=l.system.status.wounds.value-n;await l.update({"system.swarm.count":l.system.swarm.count-i,"system.status.wounds.value":o},{skipSwarmUpdate:!0}),await canvas.scene.createEmbeddedDocuments("Token",[r]),await r.actor.update({"system.swarm.count":i,"system.status.wounds.value":n},{skipSwarmUpdate:!0});let c=["x","y"][Math.floor(Math.random()*2)],m=Math.random()>.5?1:-1;await canvas.scene.updateEmbeddedDocuments("Token",[{_id:r.id,[c]:e[c]+canvas.scene.grid.size*m}])}},delete:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}u(gr,"splitSwarm");async function fr(l,e){let t=0,a=0;for(let i of canvas.tokens.controlled)t+=Number(i.actor.system.swarm?.count)||1,a+=Number(i.actor.system.status.wounds.value);await e.actor.update({"system.swarm.count":t,"system.status.wounds.value":a},{skipSwarmUpdate:!0});let s=canvas.tokens.controlled.map(i=>i.id).filter(i=>i!=e.id);await canvas.scene.updateEmbeddedDocuments("Token",s.map(i=>({_id:i,x:e.x,y:e.y}))),await canvas.scene.deleteEmbeddedDocuments("Token",s)}u(fr,"combineSwarm");function fi(){Hooks.on("renderTokenHUD",(l,e,t)=>{st.hide(l.object);let a=l.object.actor;a&&(ur(e,a,l),game.dsa5.apps.LightDialog&&game.dsa5.apps.LightDialog.lightHud(e,a,t),pr(l,e,t)),e.find('.control-icon[data-action="target"]').mousedown(s=>{s.button==2&&(game.user.updateTokenTargets([]),$(s.currentTarget).trigger("click"),s.preventDefault())}),e.find(".attribute input").off("change"),H.renderTokenHUD(l,e,t)}),Hooks.on("renderTokenConfig",(l,e,t)=>{if(t.isPrototype){let a=getProperty(l.actor,"system.config.autoBar"),s=e.find(".bar2-max").closest(".form-group"),i=$(`
    +
    `,flavor:void 0};l.updateSource(c)}})}u(li,"default");function nn(l){let e=$(l.currentTarget).parents(".message").attr("data-message-id"),a=game.messages.get(e).getFlag("dsa5","embeddedItem"),s={type:"Item",data:a};l.dataTransfer.setData("text/plain",JSON.stringify(s))}u(nn,"embeddedDragStart");var xe=class{static async firstTimeMessage(){if(!await game.settings.get("dsa5","firstTimeStart")){await xe.setupDefaultOptions();let e=game.i18n.localize("WELCOME");ChatMessage.create(f.chatDataSetup(e)),xe.firstTimeLanguage(),await game.settings.set("dsa5","firstTimeStart",!0)}}static firstTimeLanguage(){let e=["de","en"],t={title:game.i18n.localize("DIALOG.firstTime"),content:game.i18n.localize("DIALOG.firstTimeWarning"),default:"de",buttons:{}};for(let a of e)t.buttons[a]={label:game.i18n.localize(a),callback:()=>xe.setLanguage(a)};new Dialog(t).render(!0)}static async setLanguage(e){await game.settings.set("dsa5","firstTimeStart",!0),await game.settings.set("dsa5","forceLanguage",e),await game.settings.set("core","language",e),foundry.utils.debouncedReload()}static async setupDefaultOptions(){let e=game.settings.get("core",Combat.CONFIG_SETTING);e.skipDefeated=!0,await game.settings.set("core",Combat.CONFIG_SETTING,e),await game.settings.set("core","leftClickRelease",!0)}};u(xe,"DSA5Tutorial");var Dt=class{static async stopFade(e){e.stopPropagation(),e.preventDefault(),this.fadeOut?(this.fadeOut=!1,$(e.currentTarget).find("i").removeClass("fa-stop").addClass("fa-angle-right"),$(".didYouKnow").off("click"),$(".didYouKnow .closeDidYou").click(()=>$(".didYouKnow").remove())):fetch(`systems/dsa5/lazy/didyouknow/${game.i18n.lang}.json`).then(async t=>t.json()).then(async t=>{let a=t.data[Math.floor(Math.random()*t.data.length)],s=await renderTemplate("systems/dsa5/templates/system/didyouknow.html",{msg:a,fadeOut:Dt.fadeOut});$("body").find(".didYouKnow").replaceWith(s),Dt.activateListeners()})}static activateListeners(){$(".didYouKnow .stopFade").click(async e=>await this.stopFade(e)),$(".didYouKnow").click(()=>$(".didYouKnow").remove()),$(".didYouKnow").fadeIn()}static async showOneMessage(e=8e3){game.settings.get("dsa5","disableDidYouKnow")||fetch(`systems/dsa5/lazy/didyouknow/${game.i18n.lang}.json`).then(async t=>t.json()).then(async t=>{let a=t.data[Math.floor(Math.random()*t.data.length)],s=await renderTemplate("systems/dsa5/templates/system/didyouknow.html",{msg:a,fadeOut:Dt.fadeOut});$("body").append(s),this.activateListeners(),setTimeout(function(){Dt.fadeOut&&$(".didYouKnow").fadeOut(1e3,()=>$(".didYouKnow").remove())},e)})}},Fe=Dt;u(Fe,"DidYouKnow"),L(Fe,"fadeOut",!0);var Ce=class extends CombatTracker{static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{template:"/systems/dsa5/templates/system/combattracker.html"})}activateListeners(e){super.activateListeners(e),e.find(".combatant.actor .aggroButton").click(t=>{t.preventDefault(),t.stopPropagation(),Ce.runActAttackDialog()}),e.find("#combat-tracker").on("scroll.combattracker",debounce(function(t){let a=$(t.target),s=e.find(".combatant.active")[0].offsetTop;e.find(".aggroButton").animate({top:s-a.scrollTop()},50)},50)),e.find(".convertToBrawl").click(()=>game.combat.convertToBrawl())}static runActAttackDialog(){if(!game.combat)return;let e=game.combat.combatant;(game.user.isGM||e.isOwner)&&Re.showDialog(e.actor,e.tokenId)}async getData(e){let t=await super.getData(e);for(let a of t.turns){let s=t.combat.turns.find(r=>r.id==a.id),i=game.user.isGM||s.actor&&s.actor.testUserPermission(game.user,"OBSERVER")||!game.settings.get("dsa5","hideEffects");a.defenseCount=s.getFlag("dsa5","defenseCount")||0,a.actionCount=Number(getProperty(s,"actor.system.actionCount.value"))||0,a.actionCounts=`${a.actionCount} ${game.i18n.localize("actionCount")}`;let n=[];if(s.actor){for(let r of s.actor.items)if(r.type=="rangeweapon"&&r.system.worn.value&&r.system.reloadTime.progress>0){let o={name:r.name,remaining:T.calcLZ(r,s.actor)-r.system.reloadTime.progress};o.remaining>0&&n.push(o)}else if(["spell","liturgy"].includes(r.type)&&r.system.castingTime.modified>0){let o={name:r.name,remaining:r.system.castingTime.modified-r.system.castingTime.progress};o.remaining>0&&n.push(o)}}n=n.sort((r,o)=>r.remaining-o.remaining),n.length>0&&(a.ongoings=`${game.i18n.localize("COMBATTRACKER.ongoing")}
    ${n.map(r=>`${r.name} - ${r.remaining}`).join("
    ")}`,a.ongoing=n[0].remaining),a.effects=new Set,s.token&&(s.token.effects.forEach(r=>a.effects.add(r)),s.token.overlayEffect&&a.effects.add(s.token.overlayEffect)),s.actor&&s.actor.temporaryEffects.forEach(r=>{r.statuses.has(CONFIG.Combat.defeatedStatusId)?a.defeated=!0:r.icon&&i&&!r.notApplicable&&(game.user.isGM||!r.getFlag("dsa5","hidePlayers"))&&!r.getFlag("dsa5","hideOnToken")&&a.effects.add(r.icon)})}return t.isBrawling=game.combat?.isBrawling,t}};u(Ce,"DSA5CombatTracker");var He=class extends Combat{constructor(e,t){super(e,t)}async refreshTokenbars(){game.dsa5.apps.tokenHotbar&&game.dsa5.apps.tokenHotbar.updateDSA5Hotbar()}get isBrawling(){return this.getFlag("dsa5","isBrawling")}_onCreate(e,t,a){super._onCreate(e,t,a),this.refreshTokenbars()}_onDelete(e,t){super._onDelete(e,t),this.refreshTokenbars()}async brawlingDialog(){return new Promise((e,t)=>{new Dialog({title:game.i18n.localize("BRAWLING.unarmEveryone"),content:`

    ${game.i18n.localize("BRAWLING.unarmEveryoneText")}

    `,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{e(!0)}},No:{icon:'',label:game.i18n.localize("no"),callback:()=>{e(!1)}}}}).render(!0)})}async convertToBrawl(e=void 0){let t=e??!this.isBrawling,a=[],s=[],i=[];if(t){await this.setFlag("dsa5","unarmEveryone",await this.brawlingDialog());for(let n of this.combatants){if(!n.actor)return{};let r=await n.brawlingChange();n.actor.isToken?await n.actor.update(r.actorChange):a.push(r.actorChange),s.push(...r.tokenChange),He.brawlStart()}}else for(let n of this.combatants){if(!n.actor)return{};let r=await n.undoBrawlingChange();n.actor.isToken?await n.actor.update(r.actorChange):a.push(r.actorChange),s.push(...r.tokenChange),r.damage.brawlDamage>0&&i.push({name:n.token.name,id:n.token.id,data:r.damage})}await T.updateDocuments(a),await game.canvas.scene.updateEmbeddedDocuments("Token",s),await this.setFlag("dsa5","isBrawling",t),i.length&&await this.showBrawlingDamage(i)}async showBrawlingDamage(e){let t=await renderTemplate("systems/dsa5/templates/chat/brawling-damage.html",{messages:e});ChatMessage.create(f.chatDataSetup(t))}static async brawlStart(e=2e3,t=!0){t&&f.isActiveGM()&&await game.socket.emit("system.dsa5",{type:"brawlStart",payload:{}}),$(".bumFight").remove();let a=await renderTemplate("systems/dsa5/templates/system/bumFight/animation.html",{});$("body").append(a);let s=$(".bumFight");s.on("click",()=>s.remove()),s.addClass("fight"),setTimeout(function(){s.fadeOut(1e3,()=>s.remove())},e)}async nextRound(){if(game.user.isGM)for(let e of this.turns)await e.setFlag("dsa5","defenseCount",0);else await game.socket.emit("system.dsa5",{type:"clearCombat",payload:{}});return await super.nextRound()}async getDefenseCount(e){let t=this.getCombatantFromActor(e);return t&&t.getFlag("dsa5","defenseCount")||0}getCombatantFromActor(e){let t;return e.token?t=Array.from(this.combatants).find(a=>a.tokenId==e.token):t=Array.from(this.combatants).find(a=>a.actorId==e.actor),t?this.combatants.get(t.id):void 0}async updateDefenseCount(e){if(game.user.isGM){let t=this.getCombatantFromActor(e);t&&!getProperty(t.actor,"system.config.defense")&&await t.setFlag("dsa5","defenseCount",(t.getFlag("dsa5","defenseCount")||0)+1)}else await game.socket.emit("system.dsa5",{type:"updateDefenseCount",payload:{speaker:e}})}};u(He,"DSA5Combat");var Jt=class extends Combatant{constructor(e,t){e.flags==null&&(e.flags={}),mergeObject(e.flags,{dsa5:{defenseCount:0}}),super(e,t)}brawlingChange(){let e=f.getSpeaker({actor:this.actor.id,scene:this.sceneId,token:this.token.id}),t=this.combat.getFlag("dsa5","unarmEveryone"),a=getProperty(e,"system.config.autoBar")?e.getActiveTokens().map(i=>({_id:i.id,bar1:{attribute:"status.temporaryLeP"}})):[],s={_id:e.id,system:{status:{temporaryLeP:{value:e.system.status.wounds.value,max:e.system.status.wounds.value}}}};if(t){let i=this.actor.items.filter(n=>n.type=="meleeweapon"&&n.system.worn.value&&P.improvisedWeapon.test(n.name));i.length&&(s.items=i.map(n=>({_id:n.id,"system.worn.value":!1})))}return{tokenChange:a,actorChange:s}}async getBrawlingTable(){if(!this.brawlingTable){let t=(await game.packs.get(game.i18n.lang=="de"?"dsa5.patzer":"dsa5.botch").getDocuments({name__in:[game.i18n.lang=="de"?"Pr\xFCgelei - Verletzungen":"Brawling - Injuries"]}))[0];this.brawlingTable=t}return this.brawlingTable}async undoBrawlingChange(){let e=f.getSpeaker({actor:this.actor.id,scene:this.sceneId,token:this.token.id}),t=getProperty(e,"system.config.autoBar")?e.getActiveTokens().map(r=>({_id:r.id,bar1:{attribute:"status.wounds"}})):[],a=Math.max(0,e.system.status.temporaryLeP.max-e.system.status.temporaryLeP.value),s=0,i;if(a>0){i=await(await this.getBrawlingTable()).draw({displayChat:!1}),i=i.results[0];let r=i.getFlag("dsa5","brawlDamage");s=Math.round(a*r)}let n={_id:e.id,system:{status:{temporaryLeP:{value:0,max:0},wounds:{value:e.system.status.wounds.value-s}}}};return{tokenChange:t,actorChange:n,damage:{brawlDamage:s,result:i}}}async recalcInitiative(){if(this.initiative){let t={initiative:(await this.getFlag("dsa5","baseRoll")||0)+this.actor.system.status.initiative.value};await this.update(t)}}};u(Jt,"DSA5Combatant");Hooks.on("preCreateCombatant",(l,e,t)=>{let a=f.getSpeaker({actor:l.actorId,scene:l.sceneId,token:l.tokenId});if(getProperty(a.system,"merchant.merchantType")=="loot")return!1;if(l.combat.isBrawling){let s=l.brawlingChange();delete s.actorChange._id,a.update(s.actorChange).then(()=>{game.canvas.scene.updateEmbeddedDocuments("Token",s.tokenChange)})}});Hooks.on("deleteCombatant",(l,e,t)=>{let a=f.getSpeaker({actor:l.actorId,scene:l.sceneId,token:l.tokenId});if(getProperty(a.system,"merchant.merchantType")=="loot")return!1;l.combat.isBrawling&&l.undoBrawlingChange().then(async s=>{!l.token||(delete s.actorChange._id,await a.update(s.actorChange),await game.canvas.scene.updateEmbeddedDocuments("Token",s.tokenChange),s.damage.brawlDamage>0&&l.combat.showBrawlingDamage([{name:l.token.name,id:l.token.id,data:s.damage}]))})});Hooks.on("preDeleteCombat",(l,e,t)=>{if(!e.noHook&&l.isBrawling)return l.convertToBrawl(!1).then(()=>{l.delete({noHook:!0})}),!1});Hooks.on("updateCombatant",(l,e,t)=>{if(!!game.user.isGM)if(e.initiative){if(!l.getFlag("dsa5","baseRoll")){let s=`${e.initiative}`.split("."),i=Number(s[0])-Math.round(l.actor.system.status.initiative.value);l.setFlag("dsa5","baseRoll",i)}}else"initiative"in e&&e.initiative==null&&l.update({["flags.dsa5.-=baseRoll"]:null})});var Mt=class{static async updateCombatHook(e,t,a,s){!t.round&&!t.turn||e.round!=0&&e.turns&&e.active&&e.previous.rounda.active&&a.isGM);if(!!(t&&game.user.id==t.id)){for(let a of e.turns)if(!a.defeated){for(let s of a.actor.effects){if(s.disabled)continue;let i=[...s.statuses][0];i=="bleeding"?await this.applyBleeding(a,e):i=="burning"&&await this.applyBurning(a,s,e)}await this.startOfRoundEffects(a,e)}}}static async startOfRoundEffects(e,t){let a=["wounds","astralenergy","karmaenergy"];for(let s of a){if(getProperty(e.actor.system.repeatingEffects,`disabled.${s}`))continue;let i=e.actor.system.repeatingEffects.startOfRound[s].map(m=>m.value).join("+");if(!i)continue;let n=await new Roll(i).evaluate({async:!0}),r=await n.render(),o=game.i18n.localize(n.total>0?"CHATNOTIFICATION.regenerates":"CHATNOTIFICATION.getsHurt"),c=`${this.buildActorName(e)} ${o} ${game.i18n.localize(s)} ${r}`;await this.sendEventMessage(c,t,e),s=="wounds"?await e.actor.applyDamage(n.total*-1):await e.actor.applyMana(n.total*-1,s=="astralenergy"?"AsP":"KaP")}}static async applyBleeding(e,t){if(e.actor.system.status.wounds.value<1)return;let a=game.i18n.format("CHATNOTIFICATION.bleeding",{actor:this.buildActorName(e)});await this.sendEventMessage(a,t,e),await e.actor.applyDamage(1)}static async applyBurning(e,t,a){if(e.actor.system.status.wounds.value<1)return;let s=Number(t.getFlag("dsa5","value")),i=E.resistantToEffect(e.actor,t),n={0:"1",1:"1d3",2:"1d6",3:"2d6"}[s-i]||"1",r=await new Roll(n).evaluate({async:!0}),o=await r.render(),c=game.i18n.format(`CHATNOTIFICATION.burning.${s}`,{actor:this.buildActorName(e),damage:o});await this.sendEventMessage(c,a,e),await e.actor.applyDamage(r.total)}static buildActorName(e){let t=e.token.name;return game.settings.get("dsa5","hideRegenerationToOwner")&&e.token.name!=e.token.actor.name&&(t+=` (${e.token.actor.name})`),e.token.actor.toAnchor({name:t}).outerHTML}static async sendEventMessage(e,t,a){if(game.settings.get("dsa5","hideRegenerationToOwner")){let s=t.combatants.get(a.id).players;s.push(...game.users.filter(n=>n.isGM).map(n=>n.id));let i=f.chatDataSetup(e,void 0,void 0,s);delete i.speaker,await ChatMessage.create(i)}else await ChatMessage.create(f.chatDataSetup(e))}};u(Mt,"RepeatingEffectsHelper");Hooks.on("updateCombat",Mt.updateCombatHook);var Pe=class extends Application{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","initTracker"]),template:"systems/dsa5/templates/system/initracker.html",dragDrop:[{dragSelector:".iniItem",dropSelector:[".iniTrackerList"]}],top:100,left:170,title:"DSAIniTracker",itemWidth:game.settings.get("dsa5","iniTrackerSize"),actorCount:game.settings.get("dsa5","iniTrackerCount"),position:game.settings.get("dsa5","iniTrackerPosition")}),e}setPosition({left:e,top:t,width:a,height:s,scale:i}={}){let n=super.setPosition({left:e,top:t,width:a,height:s,scale:i}),r=this.element[0];if(!r.style.width||a){let o=a||r.offsetWidth,c=r.style.maxWidth||window.innerWidth;n.width=a=Math.clamped(o,0,c),r.style.width=a+"px",a+n.left>window.innerWidth&&(e=n.left)}return game.settings.set("dsa5","iniTrackerPosition",{left:n.left,top:n.top}),n}static connectHooks(){Hooks.on("renderDSA5CombatTracker",(e,t,a)=>{!game.settings.get("dsa5","enableCombatFlow")||(game.combat?(game.dsa5.apps.initTracker||(game.dsa5.apps.initTracker=new Pe),game.dsa5.apps.initTracker.updateTracker(a)):game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.close(),game.dsa5.apps.initTracker=void 0))})}updateTracker(e){this.combatData=e,this.render(!0,{focus:!1})}async getData(e){let t=this.combatData,a=Pe.defaultOptions.itemWidth,s=Pe.defaultOptions.actorCount,i=t.round,n=t.turns,r=[],o=game.settings.get("core",Combat.CONFIG_SETTING).skipDefeated,c=n.some(d=>d.active),m=t.turns.some(d=>d.owner&&!d.hasRolled&&(!game.user.isGM||t.combat.combatants.get(d.id).isNPC));if(n.length){let d=[],p=s,g=!1,y=-1,h=0,w=0,z;for(;!(p==0||w==s);){let v=duplicate(n[h]),S=t.combat.combatants.get(v.id);g&&h==y&&(v.css=v.css.replace("active","")),!i||v.active&&!g||!c&&!g?(g=!0,y=h):S.getFlag("dsa5","waitInit")==t.round+w&&!S.defeated&&(game.user.isGM||!S.hidden)&&r.push(v),g&&!(o&&S.defeated)&&(game.user.isGM||!S.hidden)&&(v.round=t.round+w,v.owner&&S.token?.actor&&(v.maxLP=S.token.actor.system.status.wounds.max,v.currentLP=S.token.actor.system.status.wounds.value),z&&z!=v.round&&(v.newRound="newRound"),z=v.round,d.push(v),p--),h++,h>=n.length&&(h=0,w++)}t.turns=d}return t.isLastRound=t.turns[1]?.newRound,this.position.width=a*s+s*3+80,this.position.height=a+10,mergeObject(t,{itemWidth:a,unRolled:m,waitingTurns:r}),this.conditionalPanToCurrentCombatant(t),t}hasChangedTurn(e){let t=e.turn!=this.lastTurnUpdate||e.round!=this.lastRoundUpdate;return this.lastTurnUpdate=e.turn,this.lastRoundUpdate=e.round,t}async conditionalPanToCurrentCombatant(e){if(!game.settings.get("dsa5","enableCombatPan"))return;let t=e.turns[0];if(!t)return;let a=e.combat.combatants.get(t.id);!a||!this.hasChangedTurn(e)||setTimeout(()=>{let s=a.token;!s||!s.object||!s.object.isVisible||(canvas.animatePan({x:s.x,y:s.y}),!(!a.actor||!a.actor.isOwner)&&s.object.control({releaseOthers:!0}))},300)}async _onWheelResize(e){let t=game.settings.get("dsa5","iniTrackerSize");e.originalEvent.deltaY>0?t=Math.min(140,t+5):t=Math.max(30,t-5),await game.settings.set("dsa5","iniTrackerSize",t),await this.render(!0)}activateListeners(e){super.activateListeners(e);let t=e.find(".dragHandler");new Draggable(this,e,t[0],this.options.resizable),t.on("wheel",async s=>(s.stopPropagation(),s.preventDefault(),await this._onWheelResize(s),!1)),e.find(".toggleTracker").click(()=>{let s=ui.combat;s.renderPopout(s)}),e.find(".combat-control").click(s=>this._onCombatControl(s)),e.find(".convertToBrawl").click(s=>{game.combat?.convertToBrawl()});let a=e.find(".iniItem");a.hover(this._onCombatantHoverIn.bind(this),this._onCombatantHoverOut.bind(this)),a.click(this._onCombatantMouseDown.bind(this)),e.find(".waitingTackerList .iniItem").mousedown(s=>this._onRightClick(s)),e.find(".combatant-control").click(s=>this._onCombatantControl(s)),e.find(".combatant .aggroButton").click(s=>{s.preventDefault(),s.stopPropagation(),Ce.runActAttackDialog()}),e.find(".rollMine").click(s=>this.rollMyChars()),game.user.isGM&&e.find(".rolledInit").click(s=>this.editCombatant(s))}rollMyChars(){game.user.isGM?this._getCombatApp().viewed.rollNPC({}):this._getCombatApp().viewed.rollAll({})}_onRightClick(e){if(e.button==2){let t=game.combat.combatants.get(e.currentTarget.dataset.combatantId);t.isOwner&&t.unsetFlag("dsa5","waitInit")}}editCombatant(e){this._getCombatApp()._onConfigureCombatant($(e.currentTarget))}_onCombatantControl(e){this._getCombatApp()._onCombatantControl(e)}_onCombatControl(e){e.currentTarget.dataset.control=="waitInit"?this.waitInit(e):this._getCombatApp()._onCombatControl(e)}async waitInit(e){await game.combat.combatants.get(game.combat.current.combatantId).setFlag("dsa5","waitInit",game.combat.current.round),e.currentTarget.dataset.control="nextTurn",this._getCombatApp()._onCombatControl(e)}_onCombatantHoverOut(e){this._getCombatApp()._onCombatantHoverOut(e)}_onCombatantHoverIn(e){this._getCombatApp()._onCombatantHoverIn(e)}_onCombatantMouseDown(e){this._getCombatApp()._onCombatantMouseDown(e)}_getCombatApp(){return game.combats.apps[0]}_canDragStart(e){return!1}_canDragDrop(e){return!1}_onDragStart(e){let t=$(e.currentTarget).closestData("combatant-id");e.dataTransfer.setData("text/plain",JSON.stringify({type:"IniChange",combatantId:t}))}_onDrop(e){JSON.parse(e.dataTransfer.getData("text/plain")).type=="IniChange"}};u(Pe,"DSAIniTracker");var Ne=class extends Tour{static async travelAgency(){let e=game.i18n.lang=="de"?"de":"en";console.log("Adding DSA/TDE Tours");for(let t of this.tours){let a=await game.dsa5.apps.DSATour.fromJSON(`${t.replace("/lang/",`/${e}/`)}.json`);game.tours.register(a.config.module,a.id,a)}if(!!game.user.isGM)for(let t of this.gmTours){let a=await game.dsa5.apps.DSATour.fromJSON(`${t.replace("/lang/",`/${e}/`)}.json`);game.tours.register(a.config.module,a.id,a)}}async _preStep(){this.currentStep.activateTab?ui.sidebar.activateTab(this.currentStep.activateTab):this.currentStep.activateLayer&&canvas.activeLayer.options.name!=this.currentStep.activateLayer?(await canvas[this.currentStep.activateLayer].activate(),await na(100)):this.currentStep.appTab&&this.app.activateTab(this.currentStep.appTab)}exit(){super.exit()}async start(){if(this.config.preCommand){let t=Object.getPrototypeOf(async function(){}).constructor;await new t(this.config.preCommand).call(this)}if(this.app)for(await this.app.render(!0,{focus:!0});!this.app.rendered;)await na(50);if(this.app||this.config.preCommand)for(;!$(this.steps[this.stepIndex+1].selector+":visible").length;)await na(50);let e=await super.start();return $("#tooltip").show(),e}};u(Ne,"DSATour"),L(Ne,"tours",["systems/dsa5/modules/tours/lang/initial","systems/dsa5/modules/tours/lang/library","systems/dsa5/modules/tours/lang/actor"]),L(Ne,"gmTours",["systems/dsa5/modules/tours/lang/mastermenu"]);var ut=class{async _getData(e){return{}}activateListeners(e){}async _renderData(e){let t=await this._getData(e);return mergeObject(t,e),await renderTemplate(this.constructor.template,t)}async prepareApp(e){return{name:game.i18n.localize(`PLAYER.${this.constructor.name}`),view:await this._renderData(e)}}async render(){await game.dsa5.apps.playerMenu.render(!0)}async activateTab(){await game.dsa5.apps.playerMenu.activateTab(game.i18n.localize(`PLAYER.${this.constructor.name}`))}get actor(){return game.dsa5.apps.playerMenu.actor}async _onDrop(e){}};u(ut,"PlayerMenuSubApp"),L(ut,"template",""),L(ut,"rulePath",{});var Le=class extends Application{constructor(e){super(e),this.entityAbilities=[],game.dsa5.apps.PlayerMenuSubApp=ut,this.summoningModifiers=[{id:1,name:"CONJURATION.offensiveImprovement",descr:"CONJURATION.offensiveImprovementDescr",changes:[{key:"system.meleeStats.attack",mode:2,value:2},{key:"system.meleeStats.damage",mode:2,value:4},{key:"system.rangeStats.attack",mode:2,value:2},{key:"system.rangeStats.damage",mode:2,value:4}]},{id:2,name:"CONJURATION.defensiveImprovement",descr:"CONJURATION.defensiveImprovementDescr",changes:[{key:"system.meleeStats.parry",mode:2,value:2},{key:"system.totalArmor",mode:2,value:2},{key:"system.status.wounds.gearmodifier",mode:2,value:10}]},{id:3,name:"CONJURATION.speedImprovement",descr:"CONJURATION.speedImprovementDescr",changes:[{key:"system.status.speed.gearmodifier",mode:2,value:2},{key:"system.status.dodge.gearmodifier",mode:2,value:2}]},{id:4,name:"CONJURATION.magicalImprovement",descr:"CONJURATION.magicalImprovementDescr",changes:[],fun:P.magicalImprovement},{id:5,name:"CONJURATION.resistanceImprovement",descr:"CONJURATION.resistanceImprovementDescr",changes:[{key:"system.status.soulpower.gearmodifier",mode:2,value:2},{key:"system.status.toughness.gearmodifier",mode:2,value:2}]},{id:6,name:"CONJURATION.mentalImprovement",descr:"CONJURATION.mentalImprovementDescr",changes:[{key:"system.characteristics.mu.gearmodifier",mode:2,value:2},{key:"system.characteristics.kl.gearmodifier",mode:2,value:2},{key:"system.characteristics.in.gearmodifier",mode:2,value:2},{key:"system.characteristics.ch.gearmodifier",mode:2,value:2}]},{id:7,name:"CONJURATION.physicalImprovement",descr:"CONJURATION.physicalImprovementDescr",changes:[{key:"system.characteristics.ff.gearmodifier",mode:2,value:2},{key:"system.characteristics.ge.gearmodifier",mode:2,value:2},{key:"system.characteristics.ko.gearmodifier",mode:2,value:2},{key:"system.characteristics.kk.gearmodifier",mode:2,value:2}]}],this.conjurationData={qs:0,consumedQS:0,packageModifier:0,selectedIds:[],selectedEntityIds:[],selectedPackageIds:[],conjurationTypes:{1:game.i18n.localize("CONJURATION.demon"),2:game.i18n.localize("CONJURATION.elemental")},rules:{1:{de:{pack:"dsa5-core.corerules",name:"Beschw\xF6rungen"},en:{pack:"dsa5-core.coreenrules",name:"Summoning"}},2:{de:{pack:"dsa5-core.corerules",name:"Beschw\xF6rungen"},en:{pack:"dsa5-core.coreenrules",name:"Summoning"}}},conjurationType:1,skills:{1:["invocatioMinima","invocatioMinor","invocatioMaior"].map(t=>game.i18n.localize(`LocalizedIDs.${t}`)),2:["manifesto","elementalServant","callDjinn","servantEarth","servantFlame","servantCold","servantWave","servantCloud","servantOre"].map(t=>game.i18n.localize(`LocalizedIDs.${t}`))},modifiers:{1:this.summoningModifiers,2:this.summoningModifiers},moreModifiers:{2:[{name:game.i18n.localize("CONJURATION.groupSummoning"),options:[1,2,3,4,5,6,7,8].map(t=>({name:t,val:t*-2+2}))}]},postFunction:{}},this.subApps=[]}registerSubApp(e){this.subApps.push(e)}async rollConjuration(e){if(!this.conjuration)return ui.notifications.warn(game.i18n.localize("CONJURATION.dragConjuration"));let t=$(e.currentTarget).closest(".item").attr("data-item-id"),a=this.actor.items.get(t),s=[{name:game.i18n.localize("conjuringDifficulty"),value:getProperty(this.conjuration,"system.conjuringDifficulty.value")||0,selected:!0}];if(this.conjurationData.packageModifier&&s.push({name:game.i18n.localize("summoningPackage"),value:this.conjurationData.packageModifier,selected:!0}),this.conjurationData.moreModifiers[this.conjurationData.conjurationType]){let i=this.conjurationData.moreModifiers[this.conjurationData.conjurationType].filter(n=>n.selected);for(let n of i)s.push({name:n.name,value:Number(n.selected),selected:!0})}this.actor.setupSkill(a,{moreModifiers:s,subtitle:` (${this.conjuration.name})`},void 0).then(async i=>{let n=await this.actor.basicTest(i);this.conjurationData.qs=n.result.qualityStep||0,this.render(!0)})}activateListeners(e){super.activateListeners(e),oe(e),e.find(".conjurationData").change(t=>{let a=$(t.currentTarget);setProperty(this.conjurationData,a.attr("name"),a.val()),a.attr("data-refresh")&&this.render()}),e.find(".skill-select").click(t=>this.rollConjuration(t)),e.find(".initLibrary").click(async t=>{$(t.currentTarget).html(''),await game.dsa5.itemLibrary.buildEquipmentIndex(),this.render()}),e.find(".item-edit").click(t=>{let a=$(t.currentTarget).closest(".item").attr("data-item-id");this.actor.items.get(a).sheet.render(!0)}),e.find(".selectableRow").click(t=>this.selectImprovement(t)),e.find(".finalizeConjuration").click(()=>this.finalizeConjuration()),e.find(".ruleLink").click(t=>this.openRules(t)),e.find(".openChar").click(()=>{this.actor?.sheet.render(!0)}),e.find(".showEntity").click(t=>{t.stopPropagation(),u(async()=>{(await fromUuid(t.currentTarget.dataset.uuid)).sheet.render(!0)},"fun")()}),e.find(".moreModifiers").change(t=>{let a=this.conjurationData.moreModifiers[this.conjurationData.conjurationType].find(s=>s.name==t.currentTarget.dataset.name);a.selected=$(t.currentTarget).val()});for(let t of this.subApps)t.activateListeners(e)}async openRules(e){let t=e.currentTarget.dataset.subapp,a=(t?this.subApps.find(i=>i.constructor.name==t).constructor.rulePath:this.conjurationData.rules[this.conjurationData.conjurationType])[game.i18n.lang];u(async()=>{let n=await game.packs.get(a.pack).getDocuments({name:a.name});for(let r of n)r.sheet.render(!0)},"fun")()}finalizeConjuration(){if(!this.conjurationData)return;if(!this.conjuration)return ui.notifications.warn(game.i18n.localize("DSAError.noConjurationActive"));let e=[];for(let a of this.conjurationData.selectedIds)e.push(this.conjurationData.modifiers[this.conjurationData.conjurationType].find(s=>s.id==a));let t={source:this.conjuration.toObject(),creationData:{type:this.conjurationData.conjurationType,typeName:this.conjurationData.conjurationTypes[this.conjurationData.conjurationType],qs:this.conjurationData.qs,consumedQS:this.conjurationData.consumedQS,modifiers:e,entityIds:this.conjurationData.selectedEntityIds,packageIds:this.conjurationData.selectedPackageIds},summoner:{name:this.actor.name,img:this.actor.img}};game.user.isGM?Le.createConjuration(t):(game.socket.emit("system.dsa5",{type:"summonCreature",payload:t}),ui.notifications.notify(game.i18n.localize("CONJURATION.requestSend")))}static createConjuration({source:e,creationData:t,summoner:a}){new Fs(e,a,t).render(!0)}selectImprovement(e){let t=Number(e.currentTarget.dataset.max)||1,a=Number(e.currentTarget.dataset.selected)||0;a>=t?$(e.currentTarget).removeClass("selected"):($(e.currentTarget).addClass("selected"),e.currentTarget.dataset.selected=a+1);let s=[],i=[],n=[],r=0,o=0;$(this._element).find(".selectableRow.selected").each((c,m)=>{for(let d=0;d0){if(this.conjuration=a,this.conjurationData.selectedIds=[],this.conjurationData.selectedEntityIds=[],this.conjurationData.selectedPackageIds=[],a.type=="creature"){for(let s of Object.keys(this.conjurationData.conjurationTypes))if(a.system.creatureClass.value.includes(this.conjurationData.conjurationTypes[s])){this.conjurationData.conjurationType=s;break}}}else this.trackedId=t.id,this.actor=a;this.render(!0)}else for(let a of this.subApps)if(await a._onDrop(t)===!0)break}async prepareEntityAbilities(){let e={entityAbilities:[],entityPackages:[]};if(game.dsa5.itemLibrary.equipmentBuild){let t=[game.i18n.localize("LocalizedIDs.all"),this.conjurationData.conjurationTypes[this.conjurationData.conjurationType]],a=await Promise.all((await game.dsa5.itemLibrary.getCategoryItems("trait",!1)).map(n=>n.getItem())),s=new Set,i=new Set;for(let n of a)n.system.distribution&&t.some(r=>n.system.distribution.includes(r))&&(n.system.traitType.value=="entity"&&!s.has(n.name)?(s.add(n.name),e.entityAbilities.push(n),n.count=this.conjurationData.selectedEntityIds.filter(r=>r==n.uuid).length,n.max=n.system.at.value||1):n.system.traitType.value=="summoning"&&!i.has(n.name)&&(i.add(n.name),n.count=this.conjurationData.selectedPackageIds.filter(r=>r==n.uuid).length,e.entityPackages.push(n)))}return e}async getData(e){let t=await super.getData(e);if(!game.user.isGM&&!this.actor&&(this.actor=game.user.character),this.actor){let a=this.conjurationData.qs-this.conjurationData.consumedQS+1,s=game.dsa5.itemLibrary.equipmentBuild,{entityAbilities:i,entityPackages:n}=await this.prepareEntityAbilities(),r=this.actor.items.filter(p=>this.conjurationData.skills[this.conjurationData.conjurationType].includes(p.name)&&["liturgy","ceremony","spell","ritual"].includes(p.type)).map(p=>p.toObject()),o=!1;for(let p of r)p.hasMighty=this.actor.items.find(g=>g.name==`${p.name} - ${game.i18n.localize("CONJURATION.powerfulCreature")}`),o||(o=p.hasMighty);let c=this.conjurationData.modifiers[this.conjurationData.conjurationType],m=o?2:1;for(let p of c)p.max=m,p.count=this.conjurationData.selectedIds.filter(g=>g==p.id).length;let d=await renderTemplate("systems/dsa5/templates/system/conjuration/summoning.html",{actor:this.actor,conjuration:this.conjuration||{name:game.i18n.localize("CONJURATION.dragConjuration"),img:"icons/svg/mystery-man-black.svg"},conjurationData:this.conjurationData,services:a,conjurationModifiers:c,equipmentIndexLoaded:s,entityAbilities:i,entityPackages:n,moreModifiers:this.conjurationData.moreModifiers[this.conjurationData.conjurationType],hasMighty:o});mergeObject(t,{conjurationSheet:d,conjurationskills:r})}return mergeObject(t,{actor:this.actor||{name:game.i18n.localize("CONJURATION.dragActor"),img:"icons/svg/mystery-man-black.svg"},conjurationData:this.conjurationData,conjurationTypes:this.conjurationData.conjurationTypes}),await this.prepareSubApps(t),t}async prepareSubApps(e){e.subApps=[];for(let t of this.subApps)e.subApps.push(await t.prepareApp(e))}};u(Le,"PlayerMenu");var Fs=class extends ee{constructor(e,t,a){super({title:`${game.i18n.localize("CONJURATION.request")} (${t.name})`,default:"ok",buttons:{}}),this.conjuration=e,this.summoner=t,this.creationData=a,this.confirmed=!1}async getData(e){let t=await super.getData(e),a=this.uniqueCountIds(this.creationData.entityIds);return mergeObject(t,{conjuration:this.conjuration,summoner:this.summoner,confirmed:this.confirmed,services:this.creationData.qs-this.creationData.consumedQS+1,creationData:this.creationData,conjurationModifiers:this.creationData.modifiers,entityModifiers:await Promise.all(Object.keys(a).map(async s=>{let i=(await fromUuid(s)).toObject(!1);return i.uuid=s,i.count=a[s],i.cost=Number(i.system.AsPCost.value)*a[s],i})),packageModifiers:await Promise.all(this.creationData.packageIds.map(s=>fromUuid(s))),actor:this.actor}),t}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"main"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog"]),width:470}),e.template="systems/dsa5/templates/system/conjuration/request.html",e}uniqueCountIds(e){return e.reduce((t,a)=>(t[a]?++t[a]:t[a]=1,t),{})}async createActor(){this.confirmed=!0;let e=await f.getFolderForType("Actor",null,game.i18n.localize("PLAYER.conjuration")),t=await f.getFolderForType("Actor",e.id,this.creationData.typeName),a=this.creationData.qs-this.creationData.consumedQS+1;this.conjuration.folder=t.id,this.conjuration.effects||(this.conjuration.effects=[]);for(let c of this.creationData.modifiers)this.conjuration.effects.push({changes:c.changes,duration:{},icon:"icons/svg/aura.svg",label:game.i18n.localize(c.name),flags:{dsa5:{description:`${game.i18n.localize("PLAYER.conjuration")} ${game.i18n.localize("extensions")}`,hideOnToken:!0,hidePlayers:!1}}}),c.fun&&c.fun(this.conjuration,this.creationData);let s=this.uniqueCountIds(this.creationData.entityIds),i=(await Promise.all(Object.keys(s).map(c=>fromUuid(c)))).map(c=>{let m=c.toObject(!1);return s[c.uuid]>1&&(m.system.step={value:s[c.uuid]}),m}),n=(await Promise.all(this.creationData.packageIds.map(c=>fromUuid(c)))).map(c=>c.toObject(!1));this.conjuration.effects.push({changes:[],duration:{},icon:"icons/svg/aura.svg",id:"services",name:game.i18n.localize("PLAYER.services"),flags:{dsa5:{value:a,max:500,description:`${game.i18n.localize("PLAYER.conjuration")} ${game.i18n.localize("PLAYER.services")}`,manual:a,auto:0,hideOnToken:!0,hidePlayers:!1}}}),game.dsa5.apps.playerMenu.conjurationData.postFunction[this.creationData.type]&&await game.dsa5.apps.playerMenu.conjurationData.postFunction[this.creationData.type](this.conjuration,this.creationData.qs-this.creationData.consumedQS,this.creationData.type),this.conjuration.type=="creature"&&!this.conjuration.system.creatureClass.value.includes(this.creationData.typeName)&&(this.conjuration.system.creatureClass.value+=`, ${this.creationData.typeName}`),this.actor=await T.create(this.conjuration);let r=[...i,...n].filter(c=>!this.conjuration.items.find(m=>m.type==c.type&&c.name==m.name));await this.actor.createEmbeddedDocuments("Item",r);for(let c of n)await ue.traitAdded(this.actor,c);for(let c of i)await ue.traitAdded(this.actor,c);await this.actor.update({"system.status.wounds.value":this.actor.system.status.wounds.max});let o=await renderTemplate("systems/dsa5/templates/system/conjuration/chat.html",{actor:this.actor,modifiers:this.creationData.modifiers,summoner:this.summoner,summonerImg:j.videoOrImgTag(this.summoner.img),conjureImg:j.videoOrImgTag(this.actor.img),services:a});await ChatMessage.create(f.chatDataSetup(o)),this.render()}activateListeners(e){super.activateListeners(e),e.find(".createActor").click(()=>{this.createActor()}),e.on("mousedown",".newNPC",async t=>{let a=t.currentTarget.dataset.id;t.button==2&&(game.actors.get(a).delete(),$(t.currentTarget).remove())}),e.on("click",".newNPC",async t=>{let a=t.currentTarget.dataset.id;game.actors.get(a).sheet.render(!0)}),e.on("dragstart",".newNPC",t=>{t.stopPropagation();let a=t.currentTarget,s={type:"Actor",uuid:a.dataset.uuid};t.originalEvent.dataTransfer.setData("text/plain",JSON.stringify(s))}),e.find(".showEntity").click(t=>{t.stopPropagation(),u(async()=>{(await fromUuid(t.currentTarget.dataset.uuid)).sheet.render(!0)},"fun")()})}};u(Fs,"ConjurationRequest");var it=u(l=>class extends l{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["merchant-sheet"])}),e}static get merchantTemplate(){return"systems/dsa5/templates/actors/merchant/merchant-sheet.html"}get template(){if(this.merchantSheetActivated())switch(getProperty(this.actor.system,"merchant.merchantType")){case"merchant":return"systems/dsa5/templates/actors/merchant/merchant-limited.html";case"loot":return"systems/dsa5/templates/actors/merchant/merchant-limited-loot.html";case"epic":return"systems/dsa5/templates/actors/merchant/merchant-epic.html";default:return super.template}return this.constructor.merchantTemplate}merchantSheetActivated(){return this.showLimited()||this.playerViewEnabled()&&["merchant","loot","epic"].includes(getProperty(this.actor.system,"merchant.merchantType"))}async allowMerchant(e,t){let a=duplicate(this.actor.ownership),s=t?1:0;for(let i of e)a[i]=s;await this.actor.update({ownership:a},{diff:!1,recursive:!1,noHook:!0})}activateListeners(e){super.activateListeners(e),e.find(".allowMerchant").click(async t=>{let a=t.currentTarget.dataset.userId,s=$(t.currentTarget).find("i");await this.allowMerchant([a],!s.hasClass("fa-check-circle")),s.toggleClass("fa-circle fa-check-circle")}),e.find(".toggleAllAllowMerchant").click(async t=>{let a=game.users.filter(i=>!i.isGM).map(i=>i.id),s=t.currentTarget.dataset.lock=="true";await this.allowMerchant(a,s),this.render()}),e.find(".lockTradeSection").click(t=>this.lockTradeSection(t)),e.find(".item-tradeLock").click(t=>this.toggleTradeLock(t)),e.find(".randomGoods").click(t=>this.randomGoods(t)),e.find(".clearInventory").click(t=>this.clearInventory(t)),e.find(".removeOtherTradeFriend").click(()=>this.removeOtherTradeFriend()),e.find(".choseTradefriend").click(()=>this.choseTradefriend()),e.find(".setCustomPrice").click(t=>$(t.currentTarget).addClass("edit")),e.find(".customPriceTag").change(async t=>this.setCustomPrice(t)).blur(t=>$(t.currentTarget).closest(".setCustomPrice").removeClass("edit")),e.find(".buy-item").click(t=>{this.advanceWrapper(t,"buyItem",t),K.playMoneySound()}),e.find(".sell-item").click(t=>{this.advanceWrapper(t,"sellItem",t),K.playMoneySound()}),e.find(".item-external-edit").click(t=>{t.preventDefault();let a=this._getItemId(t);this.getTradeFriend().items.get(a).sheet.render(!0)}),e.find(".changeAmountAllItems").mousedown(t=>this.changeAmountAllItems(t)),e.find(".gearSearch").prop("disabled",!1)}_canDragStart(e){return!this.merchantSheetActivated()&&this.isEditable}async toggleTradeLock(e){let t=this._getItemId(e),a=this.actor.items.get(t);this.actor.updateEmbeddedDocuments("Item",[{_id:a.id,"system.tradeLocked":!a.system.tradeLocked}])}async setCustomPrice(e){e.stopPropagation(),e.preventDefault();let t=this._getItemId(e);await this.actor.updateEmbeddedDocuments("Item",[{_id:t,"flags.dsa5.customPriceTag":Number(e.target.value)}])}removeOtherTradeFriend(){this.otherTradeFriend=void 0,this.render(!0)}async choseTradefriend(){(await It.getDialog(this)).render(!0)}async lockTradeSection(e){let t=[],a=this.filterRule(e),s;for(let i of this.actor.items)if(a(i)){let n=i.toObject();s===void 0&&(s=!n.system.tradeLocked),n.system.tradeLocked=s,t.push(n)}this.actor.updateEmbeddedDocuments("Item",t)}filterRule(e){let t=e.currentTarget.dataset.type;return b.equipmentTypes[t]?a=>a.type=="equipment"&&a.system.equipmentType.value==t:a=>a.type==t&&b.equipmentCategories.has(a.type)}async changeAmountAllItems(e){let t=[],a=this.filterRule(e);for(let s of this.actor.items)if(a(s)){let i=s.toObject();P.increment(e,i,"system.quantity.value",0),t.push(i)}this.actor.updateEmbeddedDocuments("Item",t)}async buyItem(e){await this.transferItem(this.actor,this.getTradeFriend(),e,!0)}async sellItem(e){await this.transferItem(this.getTradeFriend(),this.actor,e,!1)}async transferItem(e,t,a,s=!0){let i=this._getItemId(a),n=a.currentTarget.dataset.price,r=a.ctrlKey?10:1;game.user.isGM?await this.constructor.finishTransaction(e,t,n,i,s,r):(this.constructor.noNeedToPay(t,e,n)||B.canPay(t,n,!0))&&game.socket.emit("system.dsa5",{type:"trade",payload:{target:this.constructor.transferTokenData(t),source:this.constructor.transferTokenData(e),price:n,itemId:i,buy:s,amount:r}})}static transferTokenData(e){let t={actor:e.id};return e.token&&(t.token=e.token.id),t}static async finishTransaction(e,t,a,s,i,n){let r=e.items.get(s).toObject();if(n=Math.min(Number(r.system.quantity.value),n),Number(r.system.quantity.value)>0){let o=this.noNeedToPay(t,e,a);if(o||await B.payMoney(t,a,!0))if(getProperty(r,"system.worn.value")&&(r.system.worn.value=!1),i){let m=await this.updateTargetTransaction(t,r,n,e,a);await this.updateSourceTransaction(e,t,r,a,s,n),await this.transferNotification(r,t,e,i,a,n,o,m),await this.selfDestruction(e)}else{await this.updateSourceTransaction(e,t,r,a,s,n);let m=await this.updateTargetTransaction(t,r,n,e,a);await this.transferNotification(r,e,t,i,a,n,o,m)}}}static isTemporaryToken(e){return getProperty(e.system,"merchant.merchantType")=="loot"&&getProperty(e.system,"merchant.temporary")}static async selfDestruction(e){if(this.isTemporaryToken(e)&&!e.items.some(a=>b.equipmentCategories.has(a.type)||a.type=="money"&&a.system.quantity.value>0)){game.socket.emit("system.dsa5",{type:"hideDeletedSheet",payload:{target:this.transferTokenData(e)}});let a=e.getActiveTokens().map(s=>s.id);await canvas.scene.deleteEmbeddedDocuments("Token",a),await game.actors.get(e.id).delete(),this.hideDeletedSheet(e)}}static async hideDeletedSheet(e){e.sheet.close(!0)}static async transferNotification(e,t,a,s,i,n,r,o){let c=game.settings.get("dsa5","merchantNotification");if(c==0||getProperty(e,"system.equipmentType.value")=="service")return;let m="MERCHANT."+(s?"buy":"sell")+(r?"Loot":"")+"Notification",d=e.type=="money"?game.i18n.localize(e.name):o.toAnchor().outerHTML,p=game.i18n.format(m,{item:d,source:t.name,target:a.name,amount:n,price:i,buy:s}),g=f.chatDataSetup(p);c==2&&(g.whisper=ChatMessage.getWhisperRecipients("GM").map(y=>y.id)),await ChatMessage.create(g)}static noNeedToPay(e,t,a){return a==0||getProperty(e.system,"merchant.merchantType")=="loot"||getProperty(t.system,"merchant.merchantType")=="loot"}static async updateSourceTransaction(e,t,a,s,i,n){let r=duplicate(a);Number(r.system.quantity.value)>n||r.type=="money"?(r.system.quantity.value=Number(r.system.quantity.value)-n,await e.updateEmbeddedDocuments("Item",[r])):await e.deleteEmbeddedDocuments("Item",[i]),this.noNeedToPay(e,t,s)||await B.getMoney(e,s,!0)}static async updateTargetTransaction(e,t,a,s,i){let n=duplicate(t);if(getProperty(n,"system.equipmentType.value")=="service"){let o=game.i18n.format("MERCHANT.buyNotification",{item:n.name,amount:a,source:e.name,target:s.name,price:i});ChatMessage.create(f.chatDataSetup(o))}else{let o=e.items.find(c=>C.areEquals(n,c));return n.system.quantity.value=a,o?(await C.stackItems(o,n,e),o):(await e.createEmbeddedDocuments("Item",[n]))[0]}}getTradeFriend(){return this.otherTradeFriend||game.user.character}async _manageDragItems(e,t){switch(t){case"creature":case"npc":case"character":this.setTradeFriend(e);break;default:return super._manageDragItems(e,t)}}async _onDropActor(e,t){let a=this.actor.limited,s=this.actor.isOwner;if(!(a||s))return!1;let{item:i,typeClass:n,selfTarget:r}=await Ge(t,this.id,!1);if(!r&&(s||a&&i.documentName=="Actor"))return await this._manageDragItems(i,n)}setTradeFriend(e){let t=game.actors.get(e._id);t.isOwner&&(this.otherTradeFriend=t,this.render(!0))}async _render(e=!1,t={}){if(!game.user.isGM&&getProperty(this.actor.system,"merchant.merchantType")=="loot"&&getProperty(this.actor.system,"merchant.locked")){AudioHelper.play({src:"sounds/lock.wav",loop:!1},!1);return}await super._render(e,t)}_togglePlayerview(e){this.actor.update({"system.merchant.playerView":!getProperty(this.actor.system,"merchant.playerView")})}playerViewEnabled(){return getProperty(this.actor.system,"merchant.playerView")}async randomGoods(e){let t=await renderTemplate("systems/dsa5/templates/dialog/randomGoods-dialog.html",{categories:Array.from(b.equipmentCategories)});new Dialog({title:game.i18n.localize("MERCHANT.randomGoods"),content:t,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:a=>this.addRandomGoods(this.actor,a,e)},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}async clearInventory(e){new Dialog({title:game.i18n.localize("MERCHANT.clearInventory"),content:game.i18n.localize("MERCHANT.deleteAllGoods"),default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{this.removeAllGoods(this.actor,e)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}async addRandomGoods(e,t,a){let s=$(a.currentTarget).text();$(a.currentTarget).html(' ');let i=[];t.find('input[type="checkbox"]:checked').each(function(){let c=$(this).val();i.push({name:c,count:Number(t.find(`input[name="each_${c}"]`).val()),number:Number(t.find(`input[name="number_${c}"]`).val())})});let n=game.dsa5.itemLibrary;n.equipmentBuild||await n.buildEquipmentIndex();let r=[];for(let c of i){let m=(await n.getRandomItems(c.name,c.number)).map(d=>{let p=d.toObject();return p.system.quantity.value=c.count,p});r.push(...m)}let o={};r=r.filter(function(c){let m=getProperty(c,"system.effect");m=typeof m=="object"&&m!==null&&getProperty(m,"attributes")||"";let d=Number(getProperty(c,"system.price.value"))||0;if(m!=""||d>1e4)return!1;let p=`${c.type}_${c.name}`;return(o.hasOwnProperty(p)?!1:o[p]=!0)&&e.items.filter(function(g){return g.type==c.type&&g.name==c.name}).length==0}),await e.createEmbeddedDocuments("Item",r),$(a.currentTarget).text(s)}async removeAllGoods(e,t){let a=$(t.currentTarget).text();$(t.currentTarget).html(' ');let s=e.items.filter(i=>b.equipmentCategories.has(i.type)&&!getProperty(i,"worn.value")).map(i=>i.id);await e.deleteEmbeddedDocuments("Item",s),$(t.currentTarget).text(a)}async getData(e){let t=await super.getData(e);return t.merchantType=getProperty(this.actor.system,"merchant.merchantType")||"none",t.merchantTypes={none:game.i18n.localize("MERCHANT.typeNone"),merchant:game.i18n.localize("MERCHANT.typeMerchant"),loot:game.i18n.localize("MERCHANT.typeLoot"),epic:game.i18n.localize("MERCHANT.typeEpic")},t.invName=t.merchantTypes[t.merchantType],t.players=game.users.filter(a=>!a.isGM).map(a=>(a.allowedMerchant=this.actor.testUserPermission(a,"LIMITED",!1),a.buyingFactor=getProperty(this.actor.system,`merchant.factors.buyingFactor.${a.id}`),a.sellingFactor=getProperty(this.actor.system,`merchant.factors.sellingFactor.${a.id}`),a)),t.merchantType!="epic"?(this.prepareStorage(t),this.merchantSheetActivated()&&(this.filterWornEquipment(t),this.prepareTradeFriend(t),t.prepare.inventory.misc.items.length==0&&(t.prepare.inventory.misc.show=!1))):(this.prepareStorage(t),t.garadanOptions={1:game.i18n.localize("GARADAN.1"),2:game.i18n.localize("GARADAN.2"),3:game.i18n.localize("GARADAN.3"),4:game.i18n.localize("GARADAN.4"),6:game.i18n.localize("GARADAN.6")}),t.hasOtherTradeFriend=!!this.otherTradeFriend,t}filterWornEquipment(e){for(let[t,a]of Object.entries(e.prepare.inventory))a.items=a.items.filter(s=>!getProperty(s,"system.worn.value"))}prepareStorage(e){if(e.merchantType=="merchant")for(let[t,a]of Object.entries(e.prepare.inventory))for(let s of a.items)s.defaultPrice=this.getItemPrice(s),s.calculatedPrice=Number(parseFloat(`${s.defaultPrice*(getProperty(this.actor.system,"merchant.sellingFactor")||1)}`).toFixed(2))*(getProperty(this.actor.system,`merchant.factors.sellingFactor.${game.user.id}`)||1),s.priceTag=` / ${s.calculatedPrice}`;else if(e.merchantType=="loot"){for(let[a,s]of Object.entries(e.prepare.inventory))for(let i of s.items)i.calculatedPrice=this.getItemPrice(i);let t={items:e.prepare.money.coins.map(a=>(a.name=game.i18n.localize(a.name),a)),show:!0,dataType:"money"};t.items.length&&(e.prepare.inventory.money=t)}}getItemPrice(e){return Number(getProperty(e,"flags.dsa5.customPriceTag"))||(e.type=="consumable"?C.getSubClass(e.type).consumablePrice(e):Number(e.system.price.value))}prepareTradeFriend(e){let t=this.getTradeFriend();if(t){let a=t.prepareItems({details:[]}),s=getProperty(this.actor.system,"merchant.merchantType")=="loot"?1:(getProperty(this.actor.system,"merchant.buyingFactor")||1)*(getProperty(this.actor.system,`merchant.factors.buyingFactor.${game.user.id}`)||1),i=this.prepareSellPrices(a.inventory,s);i.misc.items.length==0&&(i.misc.show=!1),e.merchantType=="loot"&&(i.money={items:a.money.coins.map(n=>(n.name=game.i18n.localize(n.name),n)),show:!0,dataType:"money"}),mergeObject(e,{tradeFriend:{img:t.img,name:t.name,inventory:i,money:a.money}})}else mergeObject(e,{tradeFriend:{inventory:[],money:{coins:[]}}})}prepareSellPrices(e,t){for(let[a,s]of Object.entries(e))for(let i of s.items)i.calculatedPrice=Number(parseFloat(`${this.getItemPrice(i)*t}`).toFixed(2));return e}},"MerchantSheetMixin"),It=class extends Dialog{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{}),e}static async getDialog(e){let t=game.user.isGM?await game.dsa5.apps.gameMasterMenu.getTrackedHeros():game.actors.filter(s=>s.isOwner),a=new It({title:game.i18n.localize("DIALOG.setTargetToUser"),content:await renderTemplate("systems/dsa5/templates/dialog/selectTradeFriend.html",{users:t}),default:"yes",buttons:{}});return a.actor=e,a}activateListeners(e){super.activateListeners(e),e.find(".combatant").click(t=>this.setTargetToUser(t))}setTargetToUser(e){this.actor.setTradeFriend({_id:e.currentTarget.dataset.id}),this.close()}};u(It,"SelectTradefriendDialog");var Ae=class extends it(ze){};u(Ae,"MerchantSheetDSA5");function xi(){game.socket.on("system.dsa5",l=>{switch(l.type){case"brawlStart":He.brawlStart(2e3,!1);return;case"hideDeletedSheet":let e=l.payload.target.token?game.actors.tokens[l.payload.target.token]:game.actors.get(l.payload.target.actor);Ae.hideDeletedSheet(e);return;default:if(pe.socketListeners(l))return}if(!!f.isActiveGM())switch(l.type){case"updateKeepField":b.allowedforeignfields.includes(l.payload.field)&&game.actors.get(l.payload.actorId).update({[l.payload.field]:l.payload.updateData});break;case"target":{let e=game.scenes.get(l.payload.scene);new Token(e.getEmbeddedDocument("Token",l.payload.target)).actor.update({"flags.oppose":l.payload.opposeFlag})}break;case"addEffect":Q.applyEffect(l.payload.id,l.payload.mode,l.payload.actors);break;case"updateMsg":game.messages.get(l.payload.id).update(l.payload.updateData);break;case"deleteMsg":game.messages.get(l.payload.id).delete();break;case"showDamage":j.showDamage(game.messages.get(l.payload.id),l.payload.hide);break;case"hideQueryButton":j.hideReactionButton(l.payload.id);break;case"updateGroupCheck":q.rerenderGC(game.messages.get(l.payload.messageId),l.payload.data);break;case"apTracker":_.receiveSocketEvent(l);break;case"updateAttackMessage":game.messages.get(l.payload.messageId).update({"flags.data.unopposedStartMessage":l.payload.startMessageId});break;case"clearCombat":game.combat&&game.combat.nextRound();break;case"clearOpposed":j.clearOpposed(game.actors.get(l.payload.actorId));break;case"updateDefenseCount":game.combat&&game.combat.updateDefenseCount(l.payload.speaker);break;case"trade":{let e=l.payload.source.token?game.actors.tokens[l.payload.source.token]:game.actors.get(l.payload.source.actor),t=l.payload.target.token?game.actors.tokens[l.payload.target.token]:game.actors.get(l.payload.target.actor);Ae.finishTransaction(e,t,l.payload.price,l.payload.itemId,l.payload.buy,l.payload.amount)}break;case"playWhisperSound":l.payload.whisper.includes(game.user.id)&&AudioHelper.play({src:l.payload.soundPath,volume:.8,loop:!1},!1);break;case"socketedConditionAddActor":fromUuid(l.payload.id).then(e=>{new X(e).socketedConditionAddActor(l.payload.actors.map(a=>game.actors.get(a)),l.payload.data)});break;case"socketedConditionAdd":fromUuid(l.payload.id).then(e=>{new X(e).socketedConditionAdd(l.payload.targets,l.payload.data)});break;case"socketedRemoveCondition":fromUuid(l.payload.id).then(e=>{new X(e).socketedRemoveCondition(l.payload.targets,l.payload.coreId)});break;case"socketedActorTransformation":fromUuid(l.payload.id).then(e=>{new X(e).socketedActorTransformation(l.payload.targets,l.payload.update)});break;case"itemDrop":{let e=l.payload.sourceActorId?game.actors.get(l.payload.sourceActorId):void 0;fromUuid(l.payload.itemId).then(t=>{si(e,t,l.payload.data,l.payload.amount)})}break;case"finalizeFoodContribution":case"finalizeidentification":case"updateHits":case"hideResistButton":break;case"reduceGroupSchip":T.reduceGroupSchip();break;case"summonCreature":Le.createConjuration(l.payload);break;default:console.warn(`Unhandled socket data type ${l.type}`)}})}u(xi,"connectSocket");function ci(){Hooks.on("ready",async()=>{xi(),f.moduleEnabled("vtta-tokenizer")&&!await game.settings.get("dsa5","tokenizerSetup")&&game.user.isGM&&(await game.settings.set("vtta-tokenizer","default-frame-pc","[data] systems/dsa5/icons/backgrounds/token_green.webp"),await game.settings.set("vtta-tokenizer","default-frame-npc","[data] systems/dsa5/icons/backgrounds/token_black.webp"),await game.settings.set("vtta-tokenizer","default-frame-neutral","[data] systems/dsa5/icons/backgrounds/token_blue.webp"),await game.settings.set("dsa5","tokenizerSetup",!0)),f.moduleEnabled("dice-so-nice")&&!await game.settings.get("dsa5","diceSetup")&&game.user.isGM&&(await game.settings.set("dice-so-nice","immediatelyDisplayChatMessages",!0),await game.settings.set("dsa5","diceSetup",!0)),await xe.firstTimeMessage(),C.setupSubClasses(),Fe.showOneMessage(),Se.registerTokenHotbar(),$i(),Pe.connectHooks();let l=u(e=>{e.tabName=="settings"&&(Ne.travelAgency(),Hooks.off("changeSidebarTab",l))},"hook");Hooks.on("changeSidebarTab",l),Ei(),Ai()})}u(ci,"default");function di(){Token.prototype.drawEffects=async function(){this.effects.removeChildren().forEach(i=>i.destroy()),this.effects.bg=this.effects.addChild(new PIXI.Graphics),this.effects.overlay=null;let t=this.document.effects,a=[];this.actor&&(a=await this.actor.actorEffects(),this.actor.isSwarm()&&a.push(new ActiveEffect({icon:"systems/dsa5/icons/thirdparty/bee.svg",id:"swarm",name:"swarm.name",flags:{dsa5:{value:this.actor.system.swarm?.effectiveCount||1}}})));let s={src:this.document.overlayEffect,tint:null};if(t.length||a.length){let i=[];for(let n of a){if(!n.icon)continue;let r=Color.from(n.tint??null);if(n.getFlag("core","overlay")){s={src:n.icon,tint:r};continue}i.push(this._drawEffect(n.icon,r,getProperty(n,"flags.dsa5.value")))}for(let n of t)i.push(this._drawEffect(n,null));await Promise.all(i)}this.effects.overlay=await this._drawOverlay(s.src,s.tint),this._refreshEffects()},Token.prototype._refreshEffects=function(){let t=0,a=Math.round(canvas.dimensions.size/2/5)*2,s=Math.floor(this.document.height*5),i=this.effects.bg.clear().beginFill(0,.4).lineStyle(1,0);for(let n of this.effects.children)if(n!==i&&!n.isCounter)if(n===this.effects.overlay){let r=Math.min(this.w*.6,this.h*.6);n.width=n.height=r,n.position.set((this.w-r)/2,(this.h-r)/2)}else{if(n.width=n.height=a,n.x=Math.floor(t/s)*a,n.y=t%s*a,i.drawRoundedRect(n.x+1,n.y+1,a-2,a-2,2),n.counter>1&&!n.counterDrawn){let r=game.dsa5.config.effectTextStyle,o=game.settings.get("dsa5","statusEffectCounterColor");r._fill=/^#[0-9A-F]+$/.test(o)?o:"#000000";let c=this.effects.addChild(new PreciseText(n.counter,r));c.x=n.x,c.y=n.y,c.isCounter=!0,n.counterDrawn=!0}t++}},Token.prototype._drawEffect=async function(t,a,s){if(!t)return;let i=await loadTexture(t,{fallback:"icons/svg/hazard.svg"}),n=new PIXI.Sprite(i);return a&&(n.tint=a),n.counter=s,this.effects.addChild(n)},TokenHUD.prototype._onToggleEffect=function(t,{overlay:a=!1}={}){t.preventDefault();let s=t.currentTarget,i=s.dataset.statusId&&this.object.actor?CONFIG.statusEffects.find(n=>n.id===s.dataset.statusId):s.getAttribute("src");if(t.button==0)return this.object.incrementCondition(i);if(t.button==2)return this.object.decrementCondition(i)},Token.prototype.incrementCondition=async function(t,{active:a,overlay:s=!1}={}){let i=this.actor.effects.find(n=>n.statuses.has(t.id));return!i||Number.isNumeric(getProperty(i,"flags.dsa5.value"))?await this.actor.addCondition(t.id,1,!1,!1):i&&await this.actor.removeCondition(t.id,1,!1),this.hasActiveHUD&&canvas.tokens.hud.refreshStatusIcons(),a},Token.prototype.decrementCondition=async function(t,{active:a,overlay:s=!1}={}){return this.actor.removeCondition(t.id,1,!1),this.hasActiveHUD&&canvas.tokens.hud.refreshStatusIcons(),a};let l=Token.prototype._onClickLeft2,e=u(t=>t?["merchant","loot"].includes(getProperty(t.system,"merchant.merchantType")):!1,"isMerchant");Token.prototype._onClickLeft2=function(t){if(!(game.user.isGM||!J.isEnabled||!e(this.actor)||J.inDistance(this)))return ui.notifications.warn(game.i18n.localize("DSAError.notInRangeToLoot"));l.call(this,t)}}u(di,"default");function mi(){Hooks.on("renderSettings",(l,e,t)=>{let a=$(``);a.on("click",()=>{window.open("https://github.com/Plushtoast/dsa5-foundryVTT/issues","_blank")}),e.find("#settings-documentation").append(a),a=$(``),a.on("click",()=>{window.open("https://github.com/Plushtoast/dsa5-foundryVTT/wiki","_blank")}),e.find("#settings-documentation").append(a),a=$(''),a.on("click",()=>{window.open(game.i18n.localize("fshopLink"),"_blank")}),e.find("#settings-documentation").append(a);let s=game.system.title.split("/")[game.i18n.lang=="de"?0:1],i=e.find("#game-details .system .system-info").html();e.find("#game-details .system").html(`${s}${i}`)}),Hooks.on("renderCompendiumDirectory",(l,e,t)=>{let a=$(``);e.find(".header-actions").append(a),a.on("click",()=>{game.dsa5.itemLibrary.render(!0)}),e.find('li[data-pack="dsa5.money"]').remove()}),Hooks.once("renderCompendiumDirectory",(l,e,t)=>{let a=game.i18n.lang=="de"?"en":"de",s=game.packs.filter(i=>getProperty(i.metadata,"flags.dsalang")==a);for(let i of s){let n=`${i.metadata.packageName}.${i.metadata.name}`;game.packs.delete(n),game.data.packs=game.data.packs.filter(r=>r.id!=n),e.find(`li[data-pack="${n}"]`).remove()}}),Hooks.on("renderActorDirectory",(l,e,t)=>{if(!game.user.isGM)for(let a of l.documents.filter(s=>s.isMerchant()&&getProperty(s,"system.merchant.hidePlayer")))e.find(`[data-document-id="${a.id}"]`).remove()})}u(mi,"default");function Pi(){game.settings.register("dsa5","meleeBotchTableEnabled",{name:"DSASETTINGS.meleeBotchTableEnabled",hint:"DSASETTINGS.meleeBotchTableEnabledHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","rangeBotchTableEnabled",{name:"DSASETTINGS.rangeBotchTableEnabled",hint:"DSASETTINGS.rangeBotchTableEnabledHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","applyDamageInChat",{name:"DSASETTINGS.applyDamageInChat",hint:"DSASETTINGS.applyDamageInChatHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","doubleDamageOptions",{name:"DSASETTINGS.doubleDamageOptions",hint:"DSASETTINGS.doubleDamageOptionsHint",scope:"client",config:!0,default:!1,type:Boolean,requiresReload:!0}),game.settings.register("dsa5","defenseBotchTableEnabled",{name:"DSASETTINGS.defenseBotchTableEnabled",hint:"DSASETTINGS.defenseBotchTableEnabledHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","higherDefense",{name:"DSASETTINGS.higherDefense",hint:"DSASETTINGS.higherDefenseHint",scope:"world",config:!0,default:"0",type:String,choices:{0:"0",2:"+2",4:"+4"}}),game.settings.register("dsa5","informationDistribution",{name:"DSASETTINGS.informationDistribution",hint:"DSASETTINGS.informationDistributionHint",scope:"world",config:!0,default:"0",type:String,choices:{0:game.i18n.localize("DSASETTINGS.information0"),1:game.i18n.localize("DSASETTINGS.information1"),2:game.i18n.localize("DSASETTINGS.information2")}}),game.settings.register("dsa5","enableItemDropToCanvas",{name:"DSASETTINGS.enableItemDropToCanvas",hint:"DSASETTINGS.enableItemDropToCanvasHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","statusEffectCounterColor",{name:"DSASETTINGS.statusEffectCounterColor",hint:"DSASETTINGS.statusEffectCounterColorHint",scope:"client",config:!0,default:"#FFFFFF",type:String}),game.settings.register("dsa5","migrationVersion",{name:"migrationVersion",hint:"migrationVersion",scope:"world",config:!1,default:26,type:Number}),game.settings.register("dsa5","journalFontSizeIndex",{name:"journalFontSizeIndex",hint:"journalFontSizeIndex",scope:"client",config:!1,default:5,type:Number}),game.settings.register("dsa5","firstTimeStart",{name:"firstTimeStart",hint:"firstTimeStart",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","defaultConfigFinished",{name:"defaultConfigFinished",hint:"defaultConfigFinished",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","tokenizerSetup",{name:"tokenizerSetup",hint:"tokenizerSetup",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","diceSetup",{name:"diceSetup",hint:"diceSetup",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","capQSat",{name:"DSASETTINGS.capQSat",hint:"DSASETTINGS.capQSatHint",scope:"world",config:!0,default:6,type:Number}),game.settings.register("dsa5","hideEffects",{name:"DSASETTINGS.hideEffects",hint:"DSASETTINGS.hideEffectsHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","inventorySound",{name:"DSASETTINGS.inventorySound",hint:"DSASETTINGS.inventorySoundHint",scope:"client",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","talentModifierEnabled",{name:"DSASETTINGS.talentModifierEnabled",hint:"DSASETTINGS.talentModifierEnabledHint",scope:"client",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","noConfirmationRoll",{name:"DSASETTINGS.noConfirmationRoll",hint:"DSASETTINGS.noConfirmationRollHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","lessRegeneration",{name:"DSASETTINGS.lessRegeneration",hint:"DSASETTINGS.lessRegenerationHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","limitCombatSpecAbs",{name:"DSASETTINGS.limitCombatSpecAbs",hint:"DSASETTINGS.limitCombatSpecAbsHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","allowPhysicalDice",{name:"DSASETTINGS.allowPhysicalDice",hint:"DSASETTINGS.allowPhysicalDiceHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","hideOpposedDamage",{name:"DSASETTINGS.hideOpposedDamage",hint:"DSASETTINGS.hideOpposedDamageHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","enableForeignSpellModifer",{name:"DSASETTINGS.enableForeignSpellModifer",hint:"DSASETTINGS.enableForeignSpellModiferHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","playerCanEditSpellMacro",{name:"DSASETTINGS.playerCanEditSpellMacro",hint:"DSASETTINGS.playerCanEditSpellMacroHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","enableDPS",{name:"DSASETTINGS.enableDPS",hint:"DSASETTINGS.enableDPSHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","iniTrackerSize",{name:"DSASETTINGS.iniTrackerSize",hint:"DSASETTINGS.iniTrackerSizeHint",scope:"client",config:!0,default:70,type:Number,range:{min:30,max:140,step:5},onChange:async e=>{game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.constructor.defaultOptions.itemWidth=e)}}),game.settings.register("dsa5","iniTrackerCount",{name:"DSASETTINGS.iniTrackerCount",hint:"DSASETTINGS.iniTrackerCountHint",scope:"client",config:!0,default:5,type:Number,range:{min:3,max:25,step:1},onChange:async e=>{game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.constructor.defaultOptions.actorCount=e)}}),game.settings.register("dsa5","tokenhotbarSize",{name:"DSASETTINGS.tokenhotbarSize",hint:"DSASETTINGS.tokenhotbarSizeHint",scope:"client",config:!1,default:35,type:Number,range:{min:15,max:100,step:5},onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","tokenhotbarLayout",{name:"DSASETTINGS.tokenhotbarLayout",hint:"DSASETTINGS.tokenhotbarLayoutHint",scope:"client",config:!1,default:0,type:Number,choices:{0:game.i18n.localize("DSASETTINGS.tokenhotbarLayout0"),2:game.i18n.localize("DSASETTINGS.tokenhotbarLayout1"),1:game.i18n.localize("DSASETTINGS.tokenhotbarLayout2"),3:game.i18n.localize("DSASETTINGS.tokenhotbarLayout3")},onChange:async e=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}});let l=duplicate(b.styles);for(let e of Object.keys(l))l[e]=game.i18n.localize(l[e]);game.settings.register("dsa5","globalStyle",{name:"DSASETTINGS.globalStyle",hint:"DSASETTINGS.globalStyleHint",scope:"client",config:!0,default:"dsa5-immersive",type:String,choices:l,onChange:async e=>{$("body").removeClass(Object.keys(l).join(" ")).addClass(e)}}),game.settings.register("dsa5","selfControlOnPain",{name:"DSASETTINGS.selfControlOnPain",hint:"DSASETTINGS.selfControlOnPainHint",scope:"world",config:!0,default:1,type:Number,choices:{0:game.i18n.localize("DSASETTINGS.selfControlOnPain0"),1:game.i18n.localize("DSASETTINGS.selfControlOnPain1"),2:game.i18n.localize("DSASETTINGS.selfControlOnPain2")}}),game.settings.register("dsa5","forceLanguage",{name:"DSASETTINGS.forceLanguage",hint:"DSASETTINGS.forceLanguageHint",scope:"world",config:!0,default:"none",type:String,choices:{none:"-",de:"German",en:"English"}}),game.settings.register("dsa5","hotbarv3",{name:"DSASETTINGS.hotbarv3",hint:"DSASETTINGS.hotbarv3Hint",scope:"client",config:!1,default:!0,type:Boolean,onChange:()=>{ui.hotbar.render(!0)}}),game.settings.register("dsa5","tokenhotbarPosition",{name:"tokenhotbarPosition",scope:"client",config:!1,default:{},type:Object}),game.settings.register("dsa5","masterSettings",{name:"masterSettings",scope:"world",config:!1,default:{},type:Object}),game.settings.register("dsa5","iniTrackerPosition",{name:"iniTrackerPosition",scope:"client",config:!1,default:{},type:Object}),game.settings.register("dsa5","soundConfig",{name:"DSASETTINGS.soundConfig",hint:"DSASETTINGS.soundConfigHint",scope:"world",config:!0,default:"",type:String,onChange:async()=>{K.loadSoundConfig()}}),game.settings.registerMenu("dsa5","changelog",{name:"Changelog",label:"Changelog",hint:game.i18n.localize("DSASETTINGS.changelog"),type:Hs,restricted:!1}),game.settings.registerMenu("dsa5","exportConfiguration",{name:"Export/Import Configuration",label:"Export/Import Configuration",hint:game.i18n.localize("DSASETTINGS.exportConfiguration"),type:js,restricted:!0}),game.settings.registerMenu("dsa5","configureTokenbar",{name:game.i18n.localize("DSASETTINGS.configureTokenbar"),label:game.i18n.localize("DSASETTINGS.configureTokenbar"),hint:game.i18n.localize("DSASETTINGS.configureTokenbarHint"),type:Gs,restricted:!1}),game.settings.register("dsa5",`breadcrumbs_${game.world.id}`,{name:"DSASETTINGS.breadcrumbs",hint:"DSASETTINGS.breadcrumbsHint",scope:"client",config:!1,default:"",type:String}),game.settings.register("dsa5","groupschips",{name:"DSASETTINGS.groupschips",hint:"DSASETTINGS.groupschips",scope:"world",config:!1,default:"0/0",type:String,onChange:async()=>{game.user.isGM&&game.dsa5.apps.gameMasterMenu.render()}}),game.settings.register("dsa5","expandChatModifierlist",{name:"DSASETTINGS.expandChatModifierlist",hint:"DSASETTINGS.expandChatModifierlistHint",scope:"client",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","indexWorldItems",{name:"DSASETTINGS.indexWorldItems",scope:"client",config:!1,default:!0,type:Boolean}),game.settings.register("dsa5","filterDuplicateItems",{name:"DSASETTINGS.filterDuplicateItems",scope:"client",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","enableCombatFlow",{name:"DSASETTINGS.enableCombatFlow",hint:"DSASETTINGS.enableCombatFlowHint",scope:"client",config:!0,default:!0,type:Boolean,onchange:()=>{game.dsa5.apps.initTracker&&(game.dsa5.apps.initTracker.close(),game.dsa5.apps.initTracker=void 0)}}),game.settings.register("dsa5","enableCombatPan",{name:"DSASETTINGS.enableCombatPan",hint:"DSASETTINGS.enableCombatPanHint",scope:"client",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","enableAPTracking",{name:"DSASETTINGS.enableAPTracking",hint:"DSASETTINGS.enableAPTrackingHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","sightAutomationEnabled",{name:"sightAutomationEnabled",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","lightSightCompensationEnabled",{name:"lightSightCompensationEnabled",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("dsa5","randomWeaponSelection",{name:"DSASETTINGS.randomWeaponSelection",hint:"DSASETTINGS.randomWeaponSelection",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","showWeaponsOnHover",{name:"DSASETTINGS.showWeaponsOnHover",hint:"DSASETTINGS.showWeaponsOnHover",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","disableDidYouKnow",{name:"DSASETTINGS.disableDidYouKnow",hint:"DSASETTINGS.disableDidYouKnowHint",scope:"client",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","disableTokenhotbar",{name:"DSASETTINGS.disableTokenhotbar",hint:"DSASETTINGS.disableTokenhotbarHint",scope:"client",config:!1,default:!0,type:Boolean,onChange:e=>{e?game.dsa5.apps.tokenHotbar?.close():game.dsa5.apps.tokenHotbar?.render(!0)}}),game.settings.register("dsa5","disableTokenhotbarMaster",{name:"DSASETTINGS.disableTokenhotbarMaster",hint:"DSASETTINGS.disableTokenhotbarMasterHint",scope:"client",config:!1,default:!1,type:Boolean,onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","scrollingFontsize",{name:"DSASETTINGS.scrollingFontsize",hint:"DSASETTINGS.scrollingFontsizeHint",scope:"client",config:!0,default:16,type:Number,range:{min:6,max:50,step:1}}),game.settings.register("dsa5","tokenhotbaropacity",{name:"DSASETTINGS.tokenhotbaropacity",hint:"DSASETTINGS.tokenhotbaropacityHint",scope:"client",config:!1,default:.75,type:Number,range:{min:0,max:1,step:.05},onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","armorAndWeaponDamage",{name:"DSASETTINGS.armorAndWeaponDamage",hint:"DSASETTINGS.armorAndWeaponDamageHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","hideRegenerationToOwner",{name:"DSASETTINGS.hideRegenerationToOwner",hint:"DSASETTINGS.hideRegenerationToOwnerHint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("dsa5","indexDescription",{name:"DSASETTINGS.indexDescription",scope:"client",config:!1,default:!0,type:Boolean}),game.settings.register("dsa5","encumbranceForRange",{name:"DSASETTINGS.encumbranceForRange",hint:"DSASETTINGS.encumbranceForRangeHint",scope:"world",config:!0,default:!1,type:Boolean}),game.settings.register("dsa5","obfuscateTokenNames",{name:"DSASETTINGS.obfuscateTokenNames",hint:"DSASETTINGS.obfuscateTokenNamesHint",scope:"world",config:!0,default:"0",type:String,choices:{0:game.i18n.localize("no"),1:game.i18n.localize("DSASETTINGS.yesNumbered"),2:game.i18n.localize("DSASETTINGS.renameNumbered"),3:game.i18n.localize("yes"),4:game.i18n.localize("DSASETTINGS.rename")}}),game.settings.register("dsa5","merchantNotification",{name:"DSASETTINGS.merchantNotification",hint:"DSASETTINGS.merchantNotificationHint",scope:"world",config:!0,default:"0",type:String,choices:{0:game.i18n.localize("no"),1:game.i18n.localize("yes"),2:game.i18n.localize("MERCHANT.onlyGM")}}),game.settings.register("dsa5","sightOptions",{name:"sightOptions",scope:"world",config:!1,default:"0.5|0.7|0.85|0.95",type:String}),game.settings.register("dsa5","trackedActors",{name:"sightOptions",scope:"world",config:!1,default:{},type:Object}),game.settings.register("dsa5","enableMasterTokenFunctions",{name:"enableMasterTokenFunctions",scope:"world",config:!1,default:{},type:Object,onChange:()=>{game.dsa5.apps.tokenHotbar?.updateDSA5Hotbar()}}),game.settings.register("dsa5","selectedActors",{name:"selectedActors",scope:"world",config:!1,default:{},type:Object}),game.settings.register("dsa5","expansionPermissions",{name:"expansionPermissions",scope:"world",config:!1,default:{},type:Object})}u(Pi,"setupConfiguration");var dn=u(l=>{let e=Array.from(game.settings.settings);l.find('[name="exportOnlyDSA"]').is(":checked")&&(e=e.filter(n=>/^dsa5\./.test(n[0])));let a={},s=/(^dsa5\.(selectedActors|trackedActors|groupschips|tokenhotbarPosition|iniTrackerPosition|migrationVersion)$|^dsa5\.breadcrumbs_)/;for(let n of e){if(s.test(n[0]))continue;let r=n[0].split("."),o=r.shift(),c=r.join(".");a[n[0]]=game.settings.get(o,c)}let i="fvtt-DSA5-Configuration.json";saveDataToFile(JSON.stringify(a,null,2),"text/json",i)},"exportSetting"),mn=u(async l=>{let e=l.find("form")[0];if(!e.data.files.length)return ui.notifications?.error("You did not upload a data file!");readTextFromFile(e.data.files[0]).then(async t=>{let a=JSON.parse(t),s=Array.from(game.settings.settings).map(i=>i[0]);for(let i of Object.keys(a))if(s.includes(i)){let n=i.split("."),r=n.shift(),o=n.join(".");await game.settings.set(r,o,a[i])}game.settings.sheet.render(!0)})},"importSettings"),Hs=class extends FormApplication{render(){Gt()}};u(Hs,"ChangelogForm");var js=class extends FormApplication{async render(){let e=await renderTemplate("systems/dsa5/templates/dialog/exportConfiguration-dialog.html",{});new Dialog({title:"Export configuration",content:e,default:"yes",buttons:{export:{icon:'',label:game.i18n.localize("Export"),callback:t=>dn(t)},import:{icon:'',label:game.i18n.localize("Import"),callback:t=>mn(t)}}}).render(!0)}};u(js,"ExportForm");var Gs=class extends FormApplication{get template(){return"systems/dsa5/templates/dialog/configureTokenhotbar.html"}static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{title:game.i18n.localize("DSASETTINGS.configureTokenbar"),width:500}),e}activateListeners(e){super.activateListeners(e),e.find(".resetTokenhotbar").click(t=>this.resetTokenHotbar(t)),e.find("select, input").change(async t=>{let a=t.currentTarget.name.split("."),s=t.currentTarget.dataset.dtype=="Number"?Number(t.currentTarget.value):t.currentTarget.value;t.currentTarget.type=="checkbox"&&(s=t.currentTarget.checked),await game.settings.set(a[0],a[1],s),this.render()}),e.find(".bags .slot").click(t=>this._onMasterFunctionClicked(t))}async _onMasterFunctionClicked(e){let t=e.currentTarget.dataset.id,a=game.settings.get("dsa5","enableMasterTokenFunctions");a[t]=!a[t],$(e.currentTarget).toggleClass("deactivated",a[t]),game.dsa5.apps.tokenHotbar.gmItems.find(s=>s.id==t).disabled=a[t],await game.settings.set("dsa5","enableMasterTokenFunctions",a)}async getData(e){let t=await super.getData(e);return mergeObject(t,{tokenhotbarSize:game.settings.get("dsa5","tokenhotbarSize"),tokenhotbarLayout:game.settings.get("dsa5","tokenhotbarLayout"),disableTokenhotbarMaster:game.settings.get("dsa5","disableTokenhotbarMaster"),disableTokenhotbar:game.settings.get("dsa5","disableTokenhotbar"),tokenhotbaropacity:game.settings.get("dsa5","tokenhotbaropacity"),hotbarv3:game.settings.get("dsa5","hotbarv3"),isGM:game.user.isGM,gmButtons:game.dsa5.apps.tokenHotbar?.gmItems}),t}async resetTokenHotbar(e){e.preventDefault(),e.stopPropagation(),await game.settings.set("dsa5","tokenhotbarPosition",{}),await game.settings.set("dsa5","tokenhotbarLayout",0),await game.settings.set("dsa5","tokenhotbarSize",35),game.dsa5.apps.tokenHotbar?.resetPosition(),game.dsa5.apps.tokenHotbar?.render(!0)}};u(Gs,"ConfigureTokenHotbar");function pi(){Hooks.on("renderJournalSheet",(l,e,t)=>{e.find(".close").attr("data-tooltip","SHEET.Close"),e.find(".entry-image").attr("data-tooltip","SHEET.imageView"),e.find(".entry-text").attr("data-tooltip","SHEET.textView"),e.find(".share-image").attr("data-tooltip","SHEET.showToPlayers"),e.find(".import").attr("data-tooltip","SHEET.import"),e.find(".panMapNote").attr("data-tooltip","SHEET.panMapNote"),e.find(".increaseFontSize").attr("data-tooltip","SHEET.increaseFontSize")}),Hooks.on("renderJournalPageSheet",(l,e,t)=>{se.bindRollCommands(e),E.bindButtons(e),e.find("img").mousedown(a=>{a.button==2&&game.dsa5.apps.DSA5_Utility.showArtwork({name:l.name,uuid:"",img:$(a.currentTarget).attr("src")})}),mt(e)}),Hooks.on("getJournalSheetHeaderButtons",(l,e)=>{e.unshift({class:"increaseFontSize",icon:"fas fa-arrows-up-down",onclick:async()=>gi($(l._element).find(".journal-page-content"))}),!(!l.document.sceneNote&&!l.document.pages.some(t=>t.sceneNote))&&e.unshift({class:"panMapNote",icon:"fas fa-map-pin",onclick:async()=>{let t=l._getCurrentPage(),a=Array.from(l.document.pages),s;if(a[t].sceneNote)s=a[t];else if(l.document.sceneNote)s=l.document;else if(s=a.find(i=>i.sceneNote),!s)return;canvas.notes.panToNote(s.sceneNote)}})})}u(pi,"default");async function gi(l){let t=game.settings.get("dsa5","journalFontSizeIndex")+1;t==b.journalFontSizes.length+1?(t=0,await game.settings.set("dsa5","journalFontSizeIndex",t),l.css("fontSize",""),de(game.i18n.format("CHATNOTIFICATION.fontsize",{size:"Default "}))):(await game.settings.set("dsa5","journalFontSizeIndex",t),un(l))}u(gi,"increaseFontSize");function un(l){let e=game.settings.get("dsa5","journalFontSizeIndex"),t=b.journalFontSizes[e-1]||14;de(game.i18n.format("CHATNOTIFICATION.fontsize",{size:t})),l.css("fontSize",`${t}px`)}u(un,"setOuterFontSize");function gn(l,e,t){if(e.system.isPriest&&e.system.isMage){let s=`
    `;l.find(".col.middle").prepend(s),l.find(".bar3 input").change(async i=>{let n=i.currentTarget,r=n.value.trim(),o=r.startsWith("+")||r.startsWith("-");r.startsWith("=")&&(r=r.slice(1));let c=Number(r),m=n.name.split(".").reduce((d,p)=>d[p],e);await e.update({[n.name]:o?m+c:c}),t.clear()})}}u(gn,"addThirdBarToHUD");function fn(l,e,t){if(!game.user.isGM)return;let a=l.object.actor;if(!!a.isToken){if(canvas.tokens.controlled.length>=2){let s=a._id;if(!canvas.tokens.controlled.every(n=>n.actor?._id==s))return;e.find(".col.left").prepend(Ni("swarm.combine"));let i=e.find('.control-icon[data-action="swarm"]');i.click(()=>{yn(a,l.object.document),i.remove()})}else if(a.isSwarm()){e.find(".col.left").prepend(Ni("swarm.split"));let s=e.find('.control-icon[data-action="swarm"]');s.click(()=>{hn(a,l.object.document),s.remove()})}}}u(fn,"swarmButtons");var Bs=class extends Dialog{activateListeners(e){super.activateListeners(e),e.find('input[type="range"]').change(t=>{$(t.currentTarget).closest(".row-section").find(".range-value").html($(t.currentTarget).val())})}};u(Bs,"SwarmDialog");function Ni(l){return`
    `}u(Ni,"swarmHud");async function hn(l,e){let t=Number(l.system.swarm.count)-1,a=await renderTemplate("systems/dsa5/templates/dialog/swarm-split-dialog.html",{actor:l,maxSplitsize:t});new Bs({title:game.i18n.localize("swarm.split"),content:a,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("ok"),callback:async s=>{let i=Number(s.find('input[type="range"]').val()),n=deepClone(e),r=Math.floor(l.system.status.wounds.value/l.system.swarm.count*i),o=l.system.status.wounds.value-r;await l.update({"system.swarm.count":l.system.swarm.count-i,"system.status.wounds.value":o},{skipSwarmUpdate:!0}),await canvas.scene.createEmbeddedDocuments("Token",[n]),await n.actor.update({"system.swarm.count":i,"system.status.wounds.value":r},{skipSwarmUpdate:!0});let c=["x","y"][Math.floor(Math.random()*2)],m=Math.random()>.5?1:-1;await canvas.scene.updateEmbeddedDocuments("Token",[{_id:n.id,[c]:e[c]+canvas.scene.grid.size*m}])}},delete:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}u(hn,"splitSwarm");async function yn(l,e){let t=0,a=0;for(let i of canvas.tokens.controlled)t+=Number(i.actor.system.swarm?.count)||1,a+=Number(i.actor.system.status.wounds.value);await e.actor.update({"system.swarm.count":t,"system.status.wounds.value":a},{skipSwarmUpdate:!0});let s=canvas.tokens.controlled.map(i=>i.id).filter(i=>i!=e.id);await canvas.scene.updateEmbeddedDocuments("Token",s.map(i=>({_id:i,x:e.x,y:e.y}))),await canvas.scene.deleteEmbeddedDocuments("Token",s)}u(yn,"combineSwarm");function fi(){Hooks.on("renderTokenHUD",(l,e,t)=>{st.hide(l.object);let a=l.object.actor;a&&(gn(e,a,l),game.dsa5.apps.LightDialog&&game.dsa5.apps.LightDialog.lightHud(e,a,t),fn(l,e,t)),e.find('.control-icon[data-action="target"]').mousedown(s=>{s.button==2&&(game.user.updateTokenTargets([]),$(s.currentTarget).trigger("click"),s.preventDefault())}),e.find(".attribute input").off("change"),H.renderTokenHUD(l,e,t)}),Hooks.on("renderTokenConfig",(l,e,t)=>{if(t.isPrototype){let a=getProperty(l.actor,"system.config.autoBar"),s=e.find(".bar2-max").closest(".form-group"),i=$(`

    ${game.i18n.localize("ActorConfig.AutoBarHint")}

    -
    `);s.after(i),i.find(".autoBar").on("change",n=>{l.actor.update({"system.config.autoBar":n.currentTarget.checked})});let r=getProperty(l.actor,"system.config.autoSize");s=e.find('input[name="height"]').closest(".form-group"),i=$(`
    +
    `);s.after(i),i.find(".autoBar").on("change",r=>{l.actor.update({"system.config.autoBar":r.currentTarget.checked})});let n=getProperty(l.actor,"system.config.autoSize");s=e.find('input[name="height"]').closest(".form-group"),i=$(`
    - +

    ${game.i18n.localize("ActorConfig.AutoSizeHint")}

    -
    `),s.after(i),i.find(".autoSize").on("change",n=>{l.actor.update({"system.config.autoSize":n.currentTarget.checked})})}})}u(fi,"default");function hi(){Hooks.on("preCreateScene",function(l,e,t,a){e.grid?.units||l.updateSource({grid:{units:game.i18n.localize("gridUnits")}}),!t.dsaInit&&e.notes?.some(s=>getProperty(s,"flags.dsa5.initName"))&&ui.notifications.warn(game.i18n.localize("DSAError.mapsViaJournalbrowser"))}),Hooks.on("preCreateActiveEffect",function(l,e,t,a){if(l.parent.documentName!="Actor")return;let s={duration:{startTime:game.time.worldTime}};if(!game.combat){l.updateSource(s);return}s.duration.combat=game.combat.id,s.duration.startRound=game.combat.round,s.duration.startTurn=game.combat.turn,!l.duration.rounds&&l.duration.seconds&&(s.duration.rounds=l.duration.seconds/5),l.updateSource(s)})}u(hi,"default");function yi(){game.keybindings.register("dsa5","masterMenu",{name:"gmMenu",hint:game.i18n.localize("KEYBINDINGS.masterMenu"),editable:[{key:"KeyM"}],onDown:()=>f.renderToggle(game.dsa5.apps.gameMasterMenu),restricted:!0}),game.keybindings.register("dsa5","journalBrowser",{name:"Book.Wizard",hint:game.i18n.localize("KEYBINDINGS.journalBrowser"),editable:[{key:"KeyJ"}],onDown:()=>f.renderToggle(game.dsa5.apps.journalBrowser)}),game.keybindings.register("dsa5","library",{name:"ItemLibrary",hint:game.i18n.localize("KEYBINDINGS.library"),editable:[{key:"KeyL"}],onDown:()=>f.renderToggle(game.dsa5.itemLibrary)}),game.keybindings.register("dsa5","attacktest",{name:"attacktest",hint:game.i18n.localize("KEYBINDINGS.attack"),editable:[{key:"KeyB"}],onDown:()=>Ce.runActAttackDialog()}),game.keybindings.register("dsa5","combatTrackerNext",{name:"COMBAT.TurnNext",hint:game.i18n.localize("COMBAT.TurnNext"),editable:[{key:"KeyN"}],onDown:()=>Li("nextTurn")}),game.keybindings.register("dsa5","combatTrackerPrevious",{name:"COMBAT.TurnPrev",hint:game.i18n.localize("COMBAT.TurnPrev"),editable:[{key:"KeyV"}],onDown:()=>Li("previousTurn")}),game.keybindings.register("dsa5","setTargetToUser",{name:"DIALOG.setTargetToUser",hint:game.i18n.localize("DIALOG.setTargetToUserHint"),editable:[],onDown:async()=>(await De.getDialog()).render(!0),restricted:!0})}u(yi,"default");var Li=u(l=>{game.combat?.combatant?.isOwner&&game.combat[l]()},"combatTurn");function bi(){Roll.prototype.editRollAtIndex=function(l){let e=[];for(let t of l){let{index:a,val:s}=t,i=0;for(let r of this.terms){let n=r instanceof DiceTerm||r.class=="DiceTerm"||r instanceof Die||r.class=="Die",o=r instanceof OperatorTerm;if(n||r.faces){if(r.results[a-i]){let c=r.results[a-i].result;r.results[a-i].result=s,e.push(c)}n||(r.total=r.results.reduce((c,m)=>c+m.result,0)),i+=r.results.length}else!o&&(r.class=="OperatorTerm"||r.operator)&&(r.total=r.operator)}e.push(0)}return this._total=this._evaluateTotal(),e}}u(bi,"default");var Et=class extends Application{constructor(e){super(e),this.adventures=[],this.books=[],this.rshs=[],this.fulltextsearch=!0}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"description"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog","noscrollWizard","bookWizardsheet"]),width:800,height:880,scrollY:[".pages-list .scrollable"],template:"systems/dsa5/templates/wizard/adventure/adventure_wizard.html",title:game.i18n.localize("Book.Wizard"),resizable:!0,dragDrop:[{dragSelector:".item-list .item",dropSelector:null}]}),e}static initHook(){Et.wizard=new Et,game.dsa5.apps.journalBrowser=Et.wizard,Hooks.on("renderJournalDirectory",(e,t)=>{let a=$('
    '),s=$(``);s.on("click",()=>{Et.wizard.render(!0)}),a.append(s),t.find(".header-actions:first-child").after(a)})}_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"increaseFontSize",icon:"fas fa-arrows-up-down",onclick:async()=>gi($(this._element).find(".chapter"))}),e.unshift({label:"Library",class:"library",icon:"fas fa-book",onclick:async t=>this._showBooks()}),e}async _render(e=!1,t={}){await super._render(e,t),$(this._element).find(".library").attr("data-tooltip","Book.home"),$(this._element).find(".increaseFontSize").attr("data-tooltip","SHEET.increaseFontSize")}_showBooks(){this.book=null,this.bookData=null,this.selectedChapter=null,this.selectedType=null,this.journals=null,this.actors=null,this.scenes=null,this.content=void 0,this.journalIndex=null,this.fulltextsearch=!0,this.searchString=void 0,this.currentType=void 0,this.pageTocs=void 0,this.selectedSubChapter=void 0,this.loadPage(this._element)}async toggleBookVisibility(e,t,a){let s=game.settings.get("dsa5","expansionPermissions");s[e]=a,await game.settings.set("dsa5","expansionPermissions",s);let i=this[t].find(o=>o.id==e),r=await(await fetch(i.path)).json(),n=["actors","journal","scenes"];for(let o of n){if(!r[o])continue;let c=game.packs.get(r[o]),m=a?"OBSERVER":"NONE",d={ownership:{PLAYER:m,TRUSTED:m}};await c.configure(d)}this.render()}activateListeners(e){super.activateListeners(e),e.on("click",".toggleVisibility",async t=>{let a=t.currentTarget.dataset.itemid,s=t.currentTarget.dataset.type,i=$(t.currentTarget).find("i").hasClass("fa-toggle-off");this.toggleBookVisibility(a,s,i)}),e.on("click",".showMapNote",t=>{game.journal.get(t.currentTarget.dataset.entryid).panToNote()}),e.on("search keyup",".filterJournals",t=>{this.filterToc(t.currentTarget.value)}),e.on("click",".heading-link",t=>this._onClickPageLink(t)),e.on("click",".show-item",async t=>{let a=t.currentTarget.dataset.uuid;(await fromUuid(a)).sheet.render(!0)}),e.on("click",".movePage",async t=>this.movePage(t)),e.on("click",".loadBook",t=>{this.selectedChapter=void 0,this.selectedType=void 0,this.content=void 0,this.loadBook($(t.currentTarget).text(),e,t.currentTarget.dataset.type)}),e.on("click",".getChapter",t=>{this.selectedType=$(t.currentTarget).closest(".toc").attr("data-type"),this.selectedChapter=t.currentTarget.dataset.id,this.content=void 0,this.pageTocs=void 0,this.loadPage(e)}),e.on("click",".subChapter",async t=>{let a=$(t.currentTarget).text(),s=t.currentTarget.dataset.jid;s?await this.loadJournalById(s):($(this._element).find(".subChapter").removeClass("selected"),$(this._element).find(`[data-id="${a}"]`).addClass("selected"),await this.loadJournal(a)),this._saveScrollPositions(e),e.find(".toc").html(await this.getToc()),this._restoreScrollPositions(e),this.searchString&&this.filterToc(this.searchString)}),se.bindRollCommands(e),e.find(".tocCollapser").click(t=>{$(t.currentTarget).find("i").toggleClass("fa-chevron-right fa-chevron-left"),e.find(".tocCollapsing").toggleClass("expanded")}),e.on("mousedown",".openPin",async t=>{let a=t.currentTarget.dataset.uuid;t.button==0?this.showJournal(await fromUuid(a)):t.button==2&&this.unpinJournal(a)}),e.on("click",".showJournal",t=>{this.popJournal($(t.currentTarget).closest("h1").attr("data-uuid"))}),e.on("click",".pinJournal",t=>{let a=$(t.currentTarget).closest("h1"),s=a.attr("data-uuid"),i=a.text();this.pinJournal(s,i)}),e.on("click",".activateScene",t=>{this.showSzene(t.currentTarget.dataset.id,t.currentTarget.dataset.mode)}),e.on("click",".fulltextsearch",t=>{this.fulltextsearch=!this.fulltextsearch,$(t.currentTarget).toggleClass("on"),this.filterToc(e.find(".filterJournals").val())}),e.on("mousedown",".chapter img",t=>{let a=this.book.id;t.button==2&&game.dsa5.apps.DSA5_Utility.showArtwork({name:a,uuid:"",img:$(t.currentTarget).attr("src")})}),E.bindButtons(e),e.on("click",".importBook",async()=>this.importBook()),mt(e),na(e,".breadcrumbs",this.resaveBreadCrumbs)}async getPagy(e,t){let a=this.journals.filter(i=>i.flags.dsa5.parent==e).sort((i,r)=>i.flags.dsa5.sort>r.flags.dsa5.sort?1:-1),s=a.findIndex(i=>i._id==t);return{journals:a,targetindex:s}}async movePage(e){let t=e.currentTarget.dataset.action,{journals:a,targetindex:s}=await this.getPagy(this.selectedChapter,this.selectedSubChapter),i=[];for(let c of this.bookData.chapters)for(let m of c.content)i.push(m.name);let r=i.findIndex(c=>c==this.selectedChapter);if(this.bookData.chapters.findIndex(c=>c.name==this.selectedChapter),t=="next"?s++:s--,s<0){if(this.selectedChapter=i[r-1],!this.selectedChapter)return;a=(await this.getPagy(this.selectedChapter,void 0)).journals,s=0}else if(s>=a.length){if(this.selectedChapter=i[r+1],!this.selectedChapter)return;a=(await this.getPagy(this.selectedChapter,void 0)).journals,s=0}if(["prep","foundryUsage"].includes(this.selectedChapter))return;let n=a[s];n&&await this.loadJournalById(n.id);let o=await this.getToc();this._saveScrollPositions(this._element),this._element.find(".toc").html(o),this._restoreScrollPositions(this._element)}async loadJournal(e){await this.showJournal(this.journals.find(t=>t.name==e&&t.flags.dsa5.parent==this.selectedChapter))}async loadJournalById(e){await this.showJournal(this.journals.find(t=>t.id==e))}async resaveBreadCrumbs(e){let t={};for(let a of e.getElementsByTagName("div"))t[a.dataset.uuid]=a.innerText;await game.settings.set("dsa5",`breadcrumbs_${game.world.id}`,JSON.stringify(t))}markFindings(e){let t=e.closest(".tocCollapsing");t.find(".searchLines").remove();let a=e.find(".searchMatch");if(a.length==0)return;let s=[],i=e.find("> div")[0].getBoundingClientRect();for(let n of a){let o=n.getBoundingClientRect();s.push(`
    `)}let r=$(`
    ${s.join("")}
    `);t.append(r)}async filterToc(e){if(this.searchString=e,e!=null)if(e=e.toLowerCase().trim(),e!=""){let s=[];this.fulltextsearch?(this.journalIndex||(this.journalIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data"]}}),await this.journalIndex.add(this.journals.map(i=>new Ws(i)))),s=await this.journalIndex.search(e)):s=this.journals.filter(i=>i.name.toLowerCase().trim().indexOf(e)!=-1),s=s.map(i=>`
  • ${i.name}
  • `),$(this._element).find(".tocContent").html(`
      ${s.join(` -`)}
    `)}else{let s=await this.getToc();$(this._element).find(".toc").html(s).find(".filterJournals").trigger("focus")}let t=await this.getChapter(),a=$(this._element).find(".chapter");a.html(t),this.markFindings(a)}showSearchResults(e){this.searchString&&TextEditor._replaceTextContent(TextEditor._getTextNodes(e),new RegExp(this.searchString,"ig"),(t,a)=>$(`${t[0]}`)[0])}_onClickPageLink(e){let t=e.currentTarget.closest("[data-anchor]")?.dataset.anchor;if(t){let s=this.element[0].querySelector(`.chapter [data-anchor="${t}"]`);if(s){s.scrollIntoView({behavior:"smooth"});return}}this.element[0].querySelector(".journalHeader")?.scrollIntoView({behavior:"smooth"})}async _renderHeadings(e){let t=Object.values(e);t.shift();let a=Math.min(...t.map(s=>s.level));return await renderTemplate("templates/journal/journal-page-toc.html",{headings:t.reduce((s,{text:i,level:r,slug:n,element:o})=>(o&&(o.dataset.anchor=n),r${d}
    `),e.name!=r.name&&(d=`

    ${r.name}

    ${d}`),t+=d}this.pageTocs=a.join("");let s=this.findSceneNote(e.getFlag("dsa5","initId")),i=await TextEditor.enrichHTML(t,{secrets:game.user.isGM,async:!0});return`

    ${e.name}
    ${s}

    ${i}`}async showJournal(e){let t=$(this._element).find(".chapter");t.html(await this.renderContent(e)),this.selectedSubChapter=e.id,$(this._element).find(".subChapter").removeClass("selected"),$(this._element).find(`[data-jid="${e.id}"]`).addClass("selected"),mt(t),this.markFindings(t),t.find(".documentName-link, .entity-link, .content-link").on("click",a=>{let s=a.currentTarget.dataset;this.bookData&&s.pack==this.bookData.journal&&s.type!="JournalEntryPage"&&(a.stopPropagation(),this.loadJournalById(s.id))})}findSceneNote(e){if(e){let t=game.journal.find(a=>a.getFlag("dsa5","initId")==e);if(t&&t.sceneNote)return``}return""}async importBook(){game.user.isGM&&new qs().render(this.bookData.moduleName)}async loadBook(e,t,a){a||(a=this.currentType),this.currentType=a,this.book=this[a].find(s=>s.id==e),await fetch(this.book.path).then(async s=>s.json()).then(async s=>{this.bookData=s;let i=game.packs.get(s.journal);await i.getIndex();let r=await i.getDocuments();this.journals=r,s.actors&&(i=game.packs.get(s.actors),r=await i.getIndex(),this.actors=r),s.scenes&&(i=game.packs.get(s.scenes),r=await i.getIndex(),this.scenes=r),this.checkChapters(i),this.loadPage(t)})}checkChapters(e){this.bookData.chapters||(this.bookData.isDynamic=!0,this.bookData.chapters=[{name:game.i18n.localize(`${this.bookData.moduleName}.name`),content:e.folders.map(t=>({name:t.name,id:t.id}))}])}async prefillActors(e){if(!e.actors)return[];let t=[],a=await game.folders.contents.find(i=>i.name==game.i18n.localize(`${this.bookData.moduleName}.name`)&&i.type=="Actor"&&i.folder==null),s=a?await game.folders.contents.filter(i=>i.type=="Actor"&&i.folder?.id==a.id).map(i=>i.id):void 0;for(let i of e.actors){let r=s?.length?game.actors.contents.find(m=>m.name==i&&s.includes(m.folder?.id)):void 0,n,o=r?.id,c=r?.uuid;r||(r=this.actors.find(m=>m.name==i),n=this.bookData.actors,o=r?._id,c=r?`Compendium.${n}.${o}`:void 0),t.push({name:i,actor:r,pack:n,id:o,uuid:c})}return t}async popJournal(e){(await fromUuid(e)).sheet.render(!0)}async showSzene(e,t="activate"){let a=game.scenes.contents.find(s=>s.name==e);if(!a)return ui.notifications.error(game.i18n.localize("DSAError.sceneNotInitialized"));switch(t){case"activate":a.activate();break;case"view":a.view();break;case"toggle":a.update({navigation:!a.navigation});break}}async getChapter(){if(this.book){if(this.content){let e=this.journals.find(t=>t.id==this.content);return await this.renderContent(e)}if(this.selectedChapter){if(this.selectedChapter=="prep"){let a={initDescr:game.i18n.format(`${this.bookData.moduleName}.importContent`,{defaultText:game.i18n.localize("importDefault")})},s=this.bookData.modules;for(let i of s)i.enabled=this.moduleEnabled(i.id);return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_preparation.html",{modules:s,info:a})}else if(this.selectedChapter=="foundryUsage")return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_foundry.html");let e=this.bookData.chapters.find(a=>a.name==this.selectedType).content.find(a=>a.id==this.selectedChapter),t=this.getSubChapters();return e.scenes||e.actors||t.length==0?await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_chapter.html",{chapter:e,subChapters:this.getSubChapters(),actors:await this.prefillActors(e)}):(this.selectedSubChapter=t[0].id,await this.loadJournalById(t[0].id))}return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_cover.html",{book:this.book,bookData:this.bookData})}else return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_intro.html",{rshs:this.filterBooks(this.rshs),rules:this.filterBooks(this.books),adventures:this.filterBooks(this.adventures),isGM:game.user.isGM})}filterBooks(e){let t=game.settings.get("dsa5","expansionPermissions");for(let a of e)t[a.id]!=null&&(a.visible=t[a.id]);return game.user.isGM?e:e.filter(a=>a.visible==null||a.visible).sort((a,s)=>a.id.localeCompare(s.id))}getSubChapters(){let e;return this.bookData.isDynamic?e=this.journals.filter(t=>t.folder.id==this.selectedChapter).sort((t,a)=>t.sort>a.sort?1:-1):e=this.journals.filter(t=>t.flags.dsa5.parent==this.selectedChapter).sort((t,a)=>t.flags.dsa5.sort>a.flags.dsa5.sort?1:-1),e.map(t=>{let a=this.selectedSubChapter==t.id;return{name:t.name,id:t.id,selected:a,cssClass:a?"selected":""}})}async getToc(){let e=[];if(this.book){if(e.push(...duplicate(this.bookData.chapters)),this.selectedChapter){let t;for(let a of e)if(t=a.content.find(s=>s.id==this.selectedChapter),t)break;t&&(t.cssClass="selected",t.subChapters=this.getSubChapters())}return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_toc.html",{chapters:e,searchString:this.searchString,book:this.book,pageTocs:this.pageTocs,fulltextsearch:this.fulltextsearch?"on":""})}else return'
    '}async loadPage(e){let t=await this.getChapter(),a=await this.getToc();this._saveScrollPositions(e),e.find(".toc").html(a);let s=e.find(".chapter");s.html(t),this.markFindings(s),this._restoreScrollPositions(e)}async getData(e){let t=await super.getData(e),a=await this.getChapter(),s=await this.getToc(),i=game.settings.get("dsa5","journalFontSizeIndex"),r=b.journalFontSizes[i-1]||14;return mergeObject(t,{adventure:this.bookData,currentChapter:a,breadcrumbs:this.renderBreadcrumbs(),toc:s,fontSize:r}),t}async pinJournal(e,t=void 0){let a=this.readBreadCrumbs();t||(t=(await fromUuid(e))?.name||""),a[e]=t,game.settings.set("dsa5",`breadcrumbs_${game.world.id}`,JSON.stringify(a)),this.render(!0)}unpinJournal(e){let t=this.readBreadCrumbs();delete t[e],game.settings.set("dsa5",`breadcrumbs_${game.world.id}`,JSON.stringify(t)),this.render(!0)}_canDragDrop(e){return!0}async _onDrop(e){let t;try{t=JSON.parse(e.dataTransfer.getData("text/plain"))}catch{return!1}t.type=="JournalEntry"&&this.pinJournal(t.pack?`Compendium.${t.pack}.${t.id}`:`JournalEntry.${t.id}`)}readBreadCrumbs(){let e={};try{e=JSON.parse(game.settings.get("dsa5",`breadcrumbs_${game.world.id}`))}catch{console.log("No Journalbrowser notes found")}return e}renderBreadcrumbs(){let e=this.readBreadCrumbs(),t=Object.entries(e).map(a=>`
    ${a[1]}
    `);return t.length>0?``:""}moduleEnabled(e){return game.modules.get(e)?game.modules.get(e).active?"fa-check":"fa-dash":"fa-times"}},pt=Et;u(pt,"BookWizard"),L(pt,"wizard");var qs=class extends FormApplication{render(e){new game.dsa5.apps.DSA5Initializer("DSA5 Module Initialization",game.i18n.format(`${e}.importContent`,{defaultText:game.i18n.localize("importDefault")}),e,game.i18n.lang).render(!0)}};u(qs,"InitializerForm");var Ws=class{constructor(e){let t=e.pages.find(a=>!0).text.content;this.document={name:e.name,data:$("
    ").html(t).text(),id:e.id}}get name(){return this.document.name}get data(){return this.document.data}get id(){return this.document.id}};u(Ws,"JournalSearch");var $t=class{static registerButtons(){game.dsa5.apps.playerMenu=new Le,CONFIG.Canvas.layers.dsamenu={layerClass:Us,group:"interface"},Hooks.on("getSceneControlButtons",e=>{let t=[{name:"JournalBrowser",title:game.i18n.localize("Book.Wizard"),icon:"fa fa-book",button:!0,onClick:()=>{f.renderToggle(game.dsa5.apps.journalBrowser)}},{name:"Library",title:game.i18n.localize("SHEET.Library"),icon:"fas fa-university",button:!0,onClick:()=>{f.renderToggle(game.dsa5.itemLibrary)}},{name:"PlayerMenu",title:game.i18n.localize("PLAYER.title"),icon:"fas fa-dsa5-player",button:!0,onClick:()=>{f.renderToggle(game.dsa5.apps.playerMenu)}}];game.user.isGM&&(game.dsa5.apps.gameMasterMenu||(game.dsa5.apps.gameMasterMenu=new Vs),t.push({name:"mastersMenu",title:game.i18n.localize("gmMenu"),icon:"fa fa-dsa5",button:!0,onClick:()=>{f.renderToggle(game.dsa5.apps.gameMasterMenu)}})),e.push({name:"GM Menu",title:game.i18n.localize("gmMenu"),icon:"fas fa-dsa5",layer:"dsamenu",tools:t})})}};u($t,"MastersMenu");var Us=class extends InteractionLayer{static get layerOptions(){return foundry.utils.mergeObject(super.layerOptions,{name:"dsamenu",canDragCreate:!1,controllableObjects:!0,rotatableObjects:!0,zIndex:666})}selectObjects(e){canvas.tokens.selectObjects(e)}};u(Us,"DSAMenuLayer");var Vs=class extends Application{constructor(e){super(e),this.heros=[],this.lastSkill=`${game.i18n.localize("LocalizedIDs.perception")}|skill`,this.randomCreation=[],game.user.isGM&&(Hooks.on("updateActor",async(t,a,s,i)=>{if(!this.rendered)return;let r=["system.status.fatePoints","system.status.wounds","system.status.karmaenergy","system.status.astralenergy"];this.heros.some(n=>n.id==t.id)&&r.reduce((n,o)=>n||hasProperty(a,o),!1)&&this.render()}),Hooks.on("updateScene",async(t,a,s,i)=>{let r=["darkness"];if(game.canvas.id==t.id&&r.reduce((n,o)=>n||hasProperty(a,o),!1)){if(game.dsa5.apps.LightDialog&&game.dsa5.apps.LightDialog.onDarknessChange(),!this.rendered)return;this.render()}}),Hooks.on("canvasInit",()=>{!this.rendered||this.render()}))}async _render(e=!1,t={}){if(!game.user.isGM)return ui.notifications.error("DSAError.onlyGMallowed");await super._render(e,t)}getSelectedActors(){let e=game.settings.get("dsa5","selectedActors"),t=game.settings.get("dsa5","trackedActors"),a={};for(let s of Object.keys(e))t.actors?.includes(s)&&(a[s]=e[s]);return a}activateListeners(e){super.activateListeners(e),e.find("select.select2").select2(),oe(e),e.find(".heroLink").click(a=>{a.stopPropagation(),game.actors.get(this.getID(a)).sheet.render(!0)}),e.find(".addGlobalMod").click(()=>this.addGlobalMod()),e.find(".globalModEnable").change(a=>this.toggleGlobalMod(a)),e.find(".removeGlobalMod").click(a=>this.removeGlobalMod(a)),e.find(".editGlobalMod").click(a=>this.editGlobalMod(a)),e.find(".heroSelector").change(a=>{a.stopPropagation();let s=this.getSelectedActors();s[this.getID(a)]=$(a.currentTarget).is(":checked"),game.settings.set("dsa5","selectedActors",s)}),e.find(".skillSelektor").change(a=>{a.stopPropagation(),this.lastSkill=$(a.currentTarget).val()}),e.find(".rollChar").click(a=>{a.stopPropagation(),this.rollAbility([this.getID(a)])}),e.find(".rollAll").click(a=>{a.stopPropagation(),this.rollAbility(this.selectedIDs())}),e.find(".pay").click(a=>{a.stopPropagation(),this.doPayment([this.getID(a)],!0)}),e.find(".actorItem").click(async a=>{a.stopPropagation();let s=a.currentTarget.dataset.uuid;(await fromUuid(s)).sheet.render(!0)}),e.find(".getPaid").click(a=>{a.stopPropagation(),this.doPayment([this.getID(a)],!1)}),e.find(".resetSightThresholds").click(()=>this.resetSightThresholds()),e.find(".payAll").click(a=>{a.stopPropagation(),this.doPayment(this.selectedIDs(a),!0)}),e.find(".getPaidAll").click(a=>{a.stopPropagation(),this.doPayment(this.selectedIDs(a),!1)}),e.find(".selectAll").change(a=>this._selectAll(a,e)),e.find(".exp").click(a=>{a.stopPropagation(),this.getExp([this.getID(a)])}),e.find(".expAll").click(a=>{a.stopPropagation(),this.getExp(this.selectedIDs())}),e.find(".randomPlayer").mousedown(a=>{a.stopPropagation(),this._randomPlayer(e,a)}),e.find(".requestRoll").click(a=>{a.stopPropagation(),this.rollRequest()}),e.find(".heroSelector").click(a=>a.stopPropagation()),e.find(".hero").click(a=>{a.stopPropagation(a),$(a.currentTarget).find(".expandDetails").fadeToggle()});let t=u(a=>this._deleteHero(a),"deletehand");e.find(".hero").mouseenter(a=>{if(a.currentTarget.getElementsByClassName("hovermenu").length==0){let s=document.createElement("div");s.classList.add("hovermenu");let i=document.createElement("i");i.classList.add("fas","fa-times"),i.title=game.i18n.localize("SHEET.DeleteItem"),i.addEventListener("click",t,!1),s.appendChild(i),a.currentTarget.appendChild(s)}}),e.find(".hero").mouseleave(a=>{let s=a.toElement||a.relatedTarget;!s||s.parentNode==this||s==this||a.currentTarget.querySelectorAll(".hovermenu").forEach(i=>i.remove())}),e.find(".addGroupSchip").click(async a=>{await this.changeGroupSchipCount(Number(a.currentTarget.dataset.value))}),e.find(".groupschip").click(a=>{this.changeGroupSchip(a)}),e.find(".addFolder").click(async a=>this.editFolder(a)),e.find(".editFolder").change(async a=>this._editFolder(a)),e.find(".heroschip").click(a=>{a.stopPropagation(),a.preventDefault();let s=Number(a.currentTarget.getAttribute("data-val"));s==1&&$(a.currentTarget).closest(".hero").find(".fullSchip").length==1&&(s=0),game.actors.get(this.getID(a)).update({"system.status.fatePoints.value":s})}),e.find(".groupCheck").click(a=>{a.stopPropagation(),this.doGroupCheck()}),e.find(".changeSetting").change(async a=>{await game.settings.set("dsa5",a.currentTarget.name,a.currentTarget.checked)}),e.find(".changeSightTreshold").change(async a=>{$(a.currentTarget).closest(".row-section").find(".range-value").text(a.currentTarget.value),this.updateSightThreshold(a)}),e.find(".updateDarkness").change(async a=>{$(a.currentTarget).closest(".row-section").find(".range-value").text(a.currentTarget.value),this.updateDarkness(a)});for(let a of this.randomCreation)a.activateListeners(e);na(e,".heros",this.updateHeroOrder,".hero"),e.on("dragstart",".hero",a=>{a.stopPropagation();let s=a.currentTarget,i={type:"Actor",uuid:s.dataset.uuid};a.originalEvent.dataTransfer.setData("text/plain",JSON.stringify(i))}),e.find(".dragEveryone").each(function(a,s){s.setAttribute("draggable",!0)}),e.on("dragstart",".dragEveryone",a=>this._dragEveryone(a)),game.dsa5.apps.LightDialog&&game.dsa5.apps.LightDialog.activateButtonListener(e)}async _dragEveryone(e){e.stopPropagation();let t;e.currentTarget.dataset.folder?t=expandObject(game.settings.get("dsa5","masterSettings")).folders.find(i=>i.id==e.currentTarget.dataset.folder).content:t=this.selectedIDs();let a={type:"GroupDrop",ids:t};e.originalEvent.dataTransfer.setData("text/plain",JSON.stringify(a))}async _selectAll(e,t){e.stopPropagation();let a=".heroSelector";e.currentTarget.dataset.folder&&(a=`[data-id="${e.currentTarget.dataset.folder}"] .heroSelector`);let s=t.find(a);s.prop("checked",$(e.currentTarget).is(":checked")),s.change()}async _deleteHero(e){e.stopPropagation(),e.preventDefault();let t=$(e.currentTarget).closest(".hero").attr("data-id"),a=game.settings.get("dsa5","trackedActors").actors||[],s=a.indexOf(t);s>-1&&(a.splice(s,1),await game.settings.set("dsa5","trackedActors",{actors:a}),this.render(!0))}async updateHeroOrder(e){let t=[];for(let a of e.querySelectorAll(".hero"))t.push(a.dataset.id);await game.settings.set("dsa5","trackedActors",{actors:t})}async updateDarkness(e){canvas.scene&&canvas.scene.update({darkness:Number(e.currentTarget.value)},{animateDarkness:3e3})}async updateSightThreshold(e){let t=Number(e.currentTarget.dataset.index),a=Number(e.currentTarget.value),s=game.settings.get("dsa5","sightOptions").split("|");s[t]=a,await game.settings.set("dsa5","sightOptions",s.join("|"))}async resetSightThresholds(){await game.settings.set("dsa5","sightOptions",game.settings.settings.get("dsa5.sightOptions").default),this.render(!0)}getGroupSchipSetting(){return game.settings.get("dsa5","groupschips").split("/").map(e=>Number(e))}async changeGroupSchipCount(e){let t=this.getGroupSchipSetting();t[1]=Math.max(0,t[1]+e),t[0]=Math.min(t[1],t[0]),await game.settings.set("dsa5","groupschips",t.join("/"))}async changeGroupSchip(e){let t=Number(e.currentTarget.getAttribute("data-val"));t==1&&$(e.currentTarget).closest(".col").find(".fullSchip").length==1&&(t=0);let a=this.getGroupSchipSetting();a[0]=t,await game.settings.set("dsa5","groupschips",a.join("/"))}async _createFolder(){let e=expandObject(game.settings.get("dsa5","masterSettings"));e.folders||(e.folders=[]),e.folders.push({id:randomID(),name:game.i18n.localize("FOLDER.ExportNewFolder"),content:[]}),await game.settings.set("dsa5","masterSettings",e),await this.render(!0)}async _deleteFolder(e){let t=e.currentTarget.dataset.id,a=expandObject(game.settings.get("dsa5","masterSettings"));a.folders=a.folders.filter(s=>s.id!=t),await game.settings.set("dsa5","masterSettings",a),await this.render(!0)}async _editFolder(e){let t=e.currentTarget.dataset.id,a=expandObject(game.settings.get("dsa5","masterSettings"));a.folders.find(s=>s.id==t).name=e.currentTarget.value,await game.settings.set("dsa5","masterSettings",a)}async editFolder(e){switch(e.currentTarget.dataset.action){case"create":this._createFolder();break;case"delete":this._deleteFolder(e);break}}async addGlobalMod(){new Qt().render(!0)}async editGlobalMod(e){let t=e.currentTarget.dataset.key;new Qt(t).render(!0)}async toggleGlobalMod(e){let t=game.settings.get("dsa5","masterSettings");t.globalMods[e.currentTarget.dataset.key].enabled=e.currentTarget.checked,await game.settings.set("dsa5","masterSettings",t)}async removeGlobalMod(e){let t=game.settings.get("dsa5","masterSettings");delete t.globalMods[e.currentTarget.dataset.key],await game.settings.set("dsa5","masterSettings",t),this.render()}async _randomPlayer(e,t){let a=e.find(".hero"),s=await this.rollRandomPlayer(t.button==2);$(t.currentTarget).find("i").addClass("fa-spin"),a.removeClass("victim"),setTimeout(()=>{$(this._element).find(`.hero[data-id="${s}"]`).addClass("victim"),$(t.currentTarget).find("i").removeClass("fa-spin")},500)}async rollRandomPlayer(e){let t={},a=1,s=this.getSelectedActors(),i=Object.values(s).filter(o=>o).length!=0,r=this.heros.length?this.heros:await this.getTrackedHeros();if(r.length==0){ui.notifications.warn(game.i18n.localize("DIALOG.noTarget"));return}for(let o of r)!s[o.id]&&i||(t[a]=o.id,a++,e&&O.hasVantage(o,game.i18n.localize("LocalizedIDs.misfortune"))&&(t[a]=o.id,a++),e&&o.hasCondition("badluck")&&(t[a]=o.id,a++));let n=(await new Roll(`1d${a-1}`).evaluate({async:!0})).total;return t[n]}async doPayment(e,t,a=0){let s=game.actors.filter(o=>e.includes(o.id)),i=this.getNames(s),r=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:a,text:game.i18n.localize(game.i18n.format(t?"MASTER.payText":"MASTER.getPaidText",{heros:i}))}),n=u(o=>{let c=o.find(".input-text").val();for(let m of s)B.handlePayAction(void 0,t,c,m)},"callback");this.buildDialog(game.i18n.localize(t?"MASTER.payTT":"PAYMENT.payButton"),r,n)}async getPaid(e){this.doPayment(e,!1)}async getExp(e,t=0){let a=game.actors.filter(r=>e.includes(r.id)),s=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:t,text:game.i18n.localize(game.i18n.format("MASTER.awardXPText",{heros:this.getNames(a)}))}),i=u(async r=>{let n=Number(r.find(".input-text").val()),o=Math.max(1,Math.round(n*.25)),c=[],m=[];if(!isNaN(n)){for(let d of a){let p=n;d.system.isFamiliar||d.system.isPet?(p=o,m.push(d)):c.push(d),await d.update({"system.details.experience.total":d.system.details.experience.total+p})}c.length>0&&await ChatMessage.create(f.chatDataSetup(game.i18n.format("MASTER.xpMessage",{heros:this.getNames(c),number:n}))),m.length>0&&await ChatMessage.create(f.chatDataSetup(game.i18n.format("MASTER.xpMessage",{heros:this.getNames(m),number:n}))),this.rendered&&this.render(!0)}},"callback");this.buildDialog(game.i18n.localize("MASTER.awardXP"),s,i)}getNames(e){return e.map(t=>t.name).join(", ")}buildDialog(e,t,a){new ie({title:e,content:t,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:s=>{a(s)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}_canDragDrop(e){return!0}async _onDrop(e){let t;try{t=JSON.parse(e.dataTransfer.getData("text/plain")),t=await Actor.implementation.fromDropData(t)}catch{return!1}if(t.documentName=="Actor"){let a=game.settings.get("dsa5","trackedActors");a=a.actors||[],a.indexOf(t.id)==-1&&!t.pack&&(a.push(t.id),await game.settings.set("dsa5","trackedActors",{actors:a}),this.render(!0));let s=$(e.target).closest(".isFolder"),i=expandObject(game.settings.get("dsa5","masterSettings"));s.length?i.folders=i.folders.map(r=>(r.content=r.content.filter(n=>n!=t.id),r.id==s[0].dataset.id&&r.content.push(t.id),r)):i.folders=i.folders.map(r=>(r.content=r.content.filter(n=>n!=t.id),r)),await game.settings.set("dsa5","masterSettings",i),this.render(!0)}}selectedIDs(){let e=[],t=this.getSelectedActors();for(let[a,s]of Object.entries(t))s&&e.push(a);return e.length?e:game.settings.get("dsa5","trackedActors").actors||[]}async doGroupCheck(e=0){let[t,a]=this.lastSkill.split("|");if(a!="skill")return;let s=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:e,text:game.i18n.localize(game.i18n.format("MASTER.doGroupCheck",{skill:t}))}),i=u(r=>{let n=Number(r.find(".input-text").val()),[o,c]=this.lastSkill.split("|");c=="skill"&&q.showGCMessage(o,n)},"callback");this.buildDialog(game.i18n.localize("HELP.groupcheck"),s,i)}async rollRequest(e=0){let[t,a]=this.lastSkill.split("|");if(a!="skill")return;let s=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:e,text:game.i18n.localize(game.i18n.format("MASTER.doRequestRoll",{skill:t}))}),i=u(r=>{let n=Number(r.find(".input-text").val()),[o,c]=this.lastSkill.split("|");c=="skill"&&q.showRQMessage(o,n)},"callback");this.buildDialog(game.i18n.localize("HELP.request"),s,i)}rollAbility(e){let[t,a]=this.lastSkill.split("|");switch(a){case"skill":this.rollSkill(e,t);break;case"attribute":this.rollAttribute(e,t);break;case"regeneration":this.rollRegeneration(e);break}}rollRegeneration(e){let t=game.actors.filter(a=>e.includes(a.id));for(let a of t)a.setupRegeneration("regenerate",{rollMode:"blindroll",subtitle:` (${a.name})`},void 0).then(s=>{a.basicTest(s)})}rollAttribute(e,t){let a=game.actors.filter(i=>e.includes(i.id)),s=Object.keys(game.dsa5.config.characteristics).find(i=>game.i18n.localize(game.dsa5.config.characteristics[i])==t);for(let i of a)i.setupCharacteristic(s,{rollMode:"blindroll",subtitle:` (${i.name})`},void 0).then(r=>{i.basicTest(r)})}rollSkill(e,t){let a=game.actors.filter(s=>e.includes(s.id));for(let s of a){let i=s.items.find(r=>r.name==t&&r.type=="skill");s.setupSkill(i,{rollMode:"blindroll",subtitle:` (${s.name})`},void 0).then(r=>{s.basicTest(r)})}}getID(e){return $(e.currentTarget).closest(".hero").attr("data-id")}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"main"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog","masterMenu","sheet"]),width:470,height:740,title:game.i18n.localize("gmMenu"),dragDrop:[{dragSelector:null,dropSelector:null}]}),e.template="systems/dsa5/templates/system/mastermenu.html",e.resizable=!0,e}async getTrackedHeros(){let e=game.settings.get("dsa5","trackedActors"),t=[];return e.actors&&e.actors.length>0?t=game.actors.filter(a=>e.actors.includes(a.id)).sort((a,s)=>e.actors.indexOf(a.id)-e.actors.indexOf(s.id)):(t=game.actors.filter(a=>a.hasPlayerOwner),await game.settings.set("dsa5","trackedActors",{actors:t.map(a=>a.id)})),t}async getData(e){let t=await super.getData(e),a=await this.getTrackedHeros(),s=P.getGroupSchips(),i=game.settings.get("dsa5","sightOptions").split("|"),r=/ \[[a-zA-Zäöü\d-]+\]/,n=[1,2,3,4].map(p=>({label:game.i18n.localize(`VisionDisruption.step${p}`).replace(r,""),value:i[p-1]}));t.sceneConfig={sceneAutomationEnabled:game.settings.get("dsa5","sightAutomationEnabled"),enableDPS:game.settings.get("dsa5","enableDPS"),lightSightCompensationEnabled:game.settings.get("dsa5","lightSightCompensationEnabled"),visions:n,darkness:canvas.scene?.darkness||0},this.heros=a;let o=this.getSelectedActors(),c=expandObject(game.settings.get("dsa5","masterSettings")),m=[],d=(c.folders||[]).map(p=>(p.contents=[],p.content=new Set(p.content),p));for(let p of a){let g=duplicate(p),y=[],h=[],w=[];for(let v of g.items)switch(v.type){case"disadvantage":y.push({name:v.name,uuid:v.uuid});break;case"advantage":h.push({name:v.name,uuid:v.uuid});break;case"money":w.push(v);break}mergeObject(g,{id:p.id,uuid:p.uuid,selected:o[p.id],schips:p.schipshtml(),purse:w.sort((v,S)=>S.system.price.value-v.system.price.value).map(v=>`${v.system.quantity.value}`).join(" - "),advantages:h,disadvantages:y,system:{status:{wounds:{max:p.system.status.wounds.max},astralenergy:{max:p.system.status.astralenergy.max},karmaenergy:{max:p.system.status.karmaenergy.max}},isMage:p.system.isMage,isPriest:p.system.isPriest}});let x=!1;for(let v of d)if(v.content.has(p.id)){v.contents.push(g),x=!0;break}x||m.push(g)}if(!this.abilities){let p=await f.allSkillsList();this.abilities=p.map(g=>({name:g,type:"skill"})).concat(Object.values(game.dsa5.config.characteristics).map(g=>({name:game.i18n.localize(g),type:"attribute"})).concat({name:game.i18n.localize("regenerate"),type:"regeneration"})).sort((g,y)=>g.name.localeCompare(y.name))}return mergeObject(t,{hasHeros:a.length>0,heros:m,folders:d,abilities:this.abilities,groupschips:s,masterSettings:c,lastSkill:this.lastSkill,randomCreation:this.randomCreation.map(p=>p.template),lightButton:game.dsa5.apps.LightDialog?await game.dsa5.apps.LightDialog.getButtonHTML():""}),t}registerRandomCreation(e){this.randomCreation.push(e)}};u(Vs,"GameMasterMenu");var Qt=class extends FormApplication{constructor(e){super(),this.mod_id=e}static get defaultOptions(){let e=super.defaultOptions;return e.template="systems/dsa5/templates/system/global-mod-addition.html",e.title=game.i18n.localize("MASTER.addGlobalMod"),e.width=400,e.resizable=!0,e}activateListeners(e){super.activateListeners(e),e.find(".addGlobalMod").click(t=>this.addGlobalMod(t))}async getData(e){let t=await super.getData(e);return this.mod_id?t.config=expandObject(game.settings.get("dsa5","masterSettings").globalMods[this.mod_id]):t.config={value:0,victim:{npc:!0,player:!0}},t.categories=["skill","spell","meleeweapon","rangeweapon","ritual","ceremony","liturgy","trait"],t}async addGlobalMod(e){e.preventDefault();let t=expandObject(game.settings.get("dsa5","masterSettings")),a=expandObject(new FormDataExtended($(this._element).find("form")[0]).object);a.enabled=!0,a.name&&(this.mod_id?t.globalMods[this.mod_id]=a:mergeObject(t,{globalMods:{[randomID()]:a}}),await game.settings.set("dsa5","masterSettings",t),game.dsa5.apps.gameMasterMenu.render(),this.close())}};u(Qt,"GlobalModAddition");var Ot=class extends it(Oe){static get merchantTemplate(){return"systems/dsa5/templates/actors/merchant/creature-merchant-sheet.html"}};u(Ot,"CreatureMerchantSheetDSA5");var xt=class extends it(be){static get merchantTemplate(){return"systems/dsa5/templates/actors/merchant/character-merchant-sheet.html"}};u(xt,"CharacterMerchantSheetDSA5");var zt=class extends JournalSheet{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","dsajournal"])}),e}};u(zt,"DSAJournalSheet");function ki(){ii(),ri(),ni(),oi(),li(),ci(),Ii(),di(),mi(),pi(),fi(),Xs(),hi(),bi()}u(ki,"default");Hooks.once("init",()=>{loadTemplates(["systems/dsa5/templates/actors/actor-main.html","systems/dsa5/templates/actors/actor-talents.html","systems/dsa5/templates/items/item-description.html","systems/dsa5/templates/dialog/default-dialog.html","systems/dsa5/templates/dialog/parts/targets.html","systems/dsa5/templates/dialog/enhanced-default-dialog.html","systems/dsa5/templates/dialog/default-combat-dialog.html","systems/dsa5/templates/chat/roll/test-card.html","systems/dsa5/templates/items/item-equipment.html","systems/dsa5/templates/items/item-enchantment.html","systems/dsa5/templates/actors/actor-combat.html","systems/dsa5/templates/actors/actor-equipment.html","systems/dsa5/templates/actors/actor-notes.html","systems/dsa5/templates/dialog/parts/spellmodifiers.html","systems/dsa5/templates/dialog/parts/canChangeCastingTime.html","systems/dsa5/templates/actors/parts/schipspart.html","systems/dsa5/templates/chat/post-item.html","systems/dsa5/templates/items/item-stat.html","systems/dsa5/templates/items/item-extension.html","systems/dsa5/templates/actors/creature/creature-main.html","systems/dsa5/templates/actors/creature/creature-loot.html","systems/dsa5/templates/actors/creature/creature-notes.html","systems/dsa5/templates/actors/creature/creature-magic.html","systems/dsa5/templates/system/masterHeros.html","systems/dsa5/templates/actors/creature/creature-religion.html","systems/dsa5/templates/actors/parts/characteristics-large.html","systems/dsa5/templates/actors/parts/gearSearch.html","systems/dsa5/templates/actors/parts/magicalSigns.html","systems/dsa5/templates/actors/parts/containerContent.html","systems/dsa5/templates/actors/npc/npc-main.html","systems/dsa5/templates/actors/character/actor-magic.html","systems/dsa5/templates/actors/character/actor-religion.html","systems/dsa5/templates/actors/character/actor-aggregatedtests.html","systems/dsa5/templates/actors/parts/creature-derived-attributes-small.html","systems/dsa5/templates/actors/parts/creature-derived-attributes-large.html","systems/dsa5/templates/actors/parts/status_effects.html","systems/dsa5/templates/actors/parts/purse.html","systems/dsa5/templates/actors/parts/horse.html","systems/dsa5/templates/actors/parts/healthbar.html","systems/dsa5/templates/actors/merchant/merchant-commerce.html","systems/dsa5/templates/items/item-header.html","systems/dsa5/templates/items/item-effects.html","systems/dsa5/templates/items/item-aoe.html","systems/dsa5/templates/items/traditionArtifact.html","systems/dsa5/templates/status/advanced_functions.html","systems/dsa5/templates/actors/parts/information.html","systems/dsa5/templates/actors/parts/personaltrait.html","systems/dsa5/templates/actors/parts/combatskills.html","systems/dsa5/templates/actors/parts/attributes.html","systems/dsa5/templates/actors/parts/swarm.html","systems/dsa5/templates/actors/parts/carryandpurse.html","systems/dsa5/templates/actors/parts/specialabilities.html","systems/dsa5/templates/actors/parts/experienceBox.html","systems/dsa5/templates/actors/parts/temperature.html","systems/dsa5/templates/actors/parts/temperatureSmall.html","systems/dsa5/templates/actors/parts/spells.html","systems/dsa5/templates/dialog/parts/expChoices.html","systems/dsa5/templates/actors/parts/liturgies.html","systems/dsa5/templates/items/browse/actor.html","systems/dsa5/templates/items/browse/garadan.html","systems/dsa5/templates/items/browse/culture.html","systems/dsa5/templates/items/browse/species.html","systems/dsa5/templates/items/browse/career.html","systems/dsa5/templates/actors/parts/specblock.html"]),Actors.unregisterSheet("core",ActorSheet),Actors.registerSheet("dsa5",be,{types:["character"],makeDefault:!0}),Actors.registerSheet("dsa5",Oe,{types:["creature"],makeDefault:!0}),Actors.registerSheet("dsa5",xe,{types:["npc"],makeDefault:!0}),Actors.registerSheet("dsa5",Ae,{types:["npc"]}),Actors.registerSheet("dsa5",Ot,{types:["creature"]}),Actors.registerSheet("dsa5",xt,{types:["character"]}),DocumentSheetConfig.registerSheet(ActiveEffect,"dsa5",Q,{makeDefault:!0}),Journal.registerSheet("dsa5",zt,{makeDefault:!0}),Y.setupSheets(),Hooks.call("registerDSAstyle",b.styles),Pi(),J.initDoorMinDistance(),mergeObject(CONFIG.JournalEntry.noteIcons,b.noteIcons),K.prepareSoundEffects(),$("body").addClass(game.settings.get("dsa5","globalStyle"))});Hooks.once("setup",()=>{if(!["de","en"].includes(game.i18n.lang))console.warn(`DSA5 - ${game.i18n.lang} is not a supported language. Falling back to default language.`),wr();else{let l=game.settings.get("dsa5","forceLanguage");["de","en"].includes(l)&&game.i18n.lang!=l&&vr(l)}pt.initHook(),yi(),$t.registerButtons(),De.registerButtons(),CONFIG.Canvas.lightAnimations.daylight={label:"LIGHT.daylight",illuminationShader:Xt},O.setupFunctions(),R.setupFunctions()});Hooks.once("i18nInit",()=>{Tr()});var Ks=class extends Dialog{async close(e={}){if(!!["de","en"].includes(game.i18n.lang))return super.close(e)}};u(Ks,"ForbiddenLanguageDialog");var wr=u(()=>{let l={title:game.i18n.localize("language"),content:"

    Your foundry language is not supported by this system. Due to technical reasons your foundry language setting has to be switched to either english or german.

    ",buttons:{de:{icon:'',label:"en",callback:async()=>{await game.settings.set("core","language","de"),foundry.utils.debouncedReload()}},en:{icon:'',label:"de",callback:async()=>{await game.settings.set("core","language","en"),foundry.utils.debouncedReload()}},logout:{icon:'',label:game.i18n.localize("SETTINGS.Logout"),callback:async()=>{ui.menu.items.logout.onClick()}}}};new Ks(l).render(!0)},"showForbiddenLanguageDialog"),vr=u(l=>{let e={title:game.i18n.localize("DSASETTINGS.forceLanguage"),content:game.i18n.format("DSAError.wrongLanguage",{lang:l}),buttons:{ok:{icon:'',label:game.i18n.localize("ok"),callback:async()=>{await game.settings.set("core","language",l),foundry.utils.debouncedReload()}},cancel:{icon:'',label:game.i18n.localize("cancel")}}};new Dialog(e).render(!0)},"showWrongLanguageDialog");function Tr(){game.dsa5.config.knownShortcuts={[game.i18n.localize("CHARAbbrev.INI").toLowerCase()]:["status","initiative","gearmodifier"],[game.i18n.localize("CHARAbbrev.GS").toLowerCase()]:["status","speed","gearmodifier"],[game.i18n.localize("CHARAbbrev.AsP").toLowerCase()]:["status","astralenergy","gearmodifier"],[game.i18n.localize("CHARAbbrev.LeP").toLowerCase()]:["status","wounds","gearmodifier"],[game.i18n.localize("CHARAbbrev.KaP").toLowerCase()]:["status","karmaenergy","gearmodifier"],[game.i18n.localize("CHARAbbrev.AW").toLowerCase()]:["status","dodge","gearmodifier"],[game.i18n.localize("CHARAbbrev.SK").toLowerCase()]:["status","soulpower","gearmodifier"],[game.i18n.localize("CHARAbbrev.ZK").toLowerCase()]:["status","toughness","gearmodifier"],[game.i18n.localize("CHARAbbrev.FtP").toLowerCase()]:["status","fatePoints","gearmodifier"]};for(let l of Object.keys(b.characteristics))game.dsa5.config.knownShortcuts[game.i18n.localize(`CHARAbbrev.${l.toUpperCase()}`).toLowerCase()]=["characteristics",l.toLowerCase(),"gearmodifier"]}u(Tr,"setupKnownEquipmentModifiers");var Pt=class extends AdaptiveIlluminationShader{},Xt=Pt;u(Xt,"DaylightIlluminationShader"),L(Xt,"fragmentShader",` +
    `),s.after(i),i.find(".autoSize").on("change",r=>{l.actor.update({"system.config.autoSize":r.currentTarget.checked})})}})}u(fi,"default");function hi(){Hooks.on("preCreateScene",function(l,e,t,a){e.grid?.units||l.updateSource({grid:{units:game.i18n.localize("gridUnits")}}),!t.dsaInit&&e.notes?.some(s=>getProperty(s,"flags.dsa5.initName"))&&ui.notifications.warn(game.i18n.localize("DSAError.mapsViaJournalbrowser"))}),Hooks.on("preCreateActiveEffect",function(l,e,t,a){if(l.parent.documentName!="Actor")return;let s={duration:{startTime:game.time.worldTime}};if(!game.combat){l.updateSource(s);return}s.duration.combat=game.combat.id,s.duration.startRound=game.combat.round,s.duration.startTurn=game.combat.turn,!l.duration.rounds&&l.duration.seconds&&(s.duration.rounds=l.duration.seconds/5),l.updateSource(s)})}u(hi,"default");function yi(){game.keybindings.register("dsa5","masterMenu",{name:"gmMenu",hint:game.i18n.localize("KEYBINDINGS.masterMenu"),editable:[{key:"KeyM"}],onDown:()=>f.renderToggle(game.dsa5.apps.gameMasterMenu),restricted:!0}),game.keybindings.register("dsa5","journalBrowser",{name:"Book.Wizard",hint:game.i18n.localize("KEYBINDINGS.journalBrowser"),editable:[{key:"KeyJ"}],onDown:()=>f.renderToggle(game.dsa5.apps.journalBrowser)}),game.keybindings.register("dsa5","library",{name:"ItemLibrary",hint:game.i18n.localize("KEYBINDINGS.library"),editable:[{key:"KeyL"}],onDown:()=>f.renderToggle(game.dsa5.itemLibrary)}),game.keybindings.register("dsa5","attacktest",{name:"attacktest",hint:game.i18n.localize("KEYBINDINGS.attack"),editable:[{key:"KeyB"}],onDown:()=>Ce.runActAttackDialog()}),game.keybindings.register("dsa5","combatTrackerNext",{name:"COMBAT.TurnNext",hint:game.i18n.localize("COMBAT.TurnNext"),editable:[{key:"KeyN"}],onDown:()=>Li("nextTurn")}),game.keybindings.register("dsa5","combatTrackerPrevious",{name:"COMBAT.TurnPrev",hint:game.i18n.localize("COMBAT.TurnPrev"),editable:[{key:"KeyV"}],onDown:()=>Li("previousTurn")}),game.keybindings.register("dsa5","setTargetToUser",{name:"DIALOG.setTargetToUser",hint:game.i18n.localize("DIALOG.setTargetToUserHint"),editable:[],onDown:async()=>(await De.getDialog()).render(!0),restricted:!0})}u(yi,"default");var Li=u(l=>{game.combat?.combatant?.isOwner&&game.combat[l]()},"combatTurn");function bi(){Roll.prototype.editRollAtIndex=function(l){let e=[];for(let t of l){let{index:a,val:s}=t,i=0;for(let n of this.terms){let r=n instanceof DiceTerm||n.class=="DiceTerm"||n instanceof Die||n.class=="Die",o=n instanceof OperatorTerm;if(r||n.faces){if(n.results[a-i]){let c=n.results[a-i].result;n.results[a-i].result=s,e.push(c)}r||(n.total=n.results.reduce((c,m)=>c+m.result,0)),i+=n.results.length}else!o&&(n.class=="OperatorTerm"||n.operator)&&(n.total=n.operator)}e.push(0)}return this._total=this._evaluateTotal(),e}}u(bi,"default");var Et=class extends Application{constructor(e){super(e),this.adventures=[],this.books=[],this.rshs=[],this.fulltextsearch=!0}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"description"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog","noscrollWizard","bookWizardsheet"]),width:800,height:880,scrollY:[".pages-list .scrollable"],template:"systems/dsa5/templates/wizard/adventure/adventure_wizard.html",title:game.i18n.localize("Book.Wizard"),resizable:!0,dragDrop:[{dragSelector:".item-list .item",dropSelector:null}]}),e}static initHook(){Et.wizard=new Et,game.dsa5.apps.journalBrowser=Et.wizard,Hooks.on("renderJournalDirectory",(e,t)=>{let a=$('
    '),s=$(``);s.on("click",()=>{Et.wizard.render(!0)}),a.append(s),t.find(".header-actions:first-child").after(a)})}_getHeaderButtons(){let e=super._getHeaderButtons();return e.unshift({class:"increaseFontSize",icon:"fas fa-arrows-up-down",onclick:async()=>gi($(this._element).find(".chapter"))}),e.unshift({label:"Library",class:"library",icon:"fas fa-book",onclick:async t=>this._showBooks()}),e}async _render(e=!1,t={}){await super._render(e,t),$(this._element).find(".library").attr("data-tooltip","Book.home"),$(this._element).find(".increaseFontSize").attr("data-tooltip","SHEET.increaseFontSize")}_showBooks(){this.book=null,this.bookData=null,this.selectedChapter=null,this.selectedType=null,this.journals=null,this.actors=null,this.scenes=null,this.content=void 0,this.journalIndex=null,this.fulltextsearch=!0,this.searchString=void 0,this.currentType=void 0,this.pageTocs=void 0,this.selectedSubChapter=void 0,this.loadPage(this._element)}async toggleBookVisibility(e,t,a){let s=game.settings.get("dsa5","expansionPermissions");s[e]=a,await game.settings.set("dsa5","expansionPermissions",s);let i=this[t].find(o=>o.id==e),n=await(await fetch(i.path)).json(),r=["actors","journal","scenes"];for(let o of r){if(!n[o])continue;let c=game.packs.get(n[o]),m=a?"OBSERVER":"NONE",d={ownership:{PLAYER:m,TRUSTED:m}};await c.configure(d)}this.render()}activateListeners(e){super.activateListeners(e),e.on("click",".toggleVisibility",async t=>{let a=t.currentTarget.dataset.itemid,s=t.currentTarget.dataset.type,i=$(t.currentTarget).find("i").hasClass("fa-toggle-off");this.toggleBookVisibility(a,s,i)}),e.on("click",".showMapNote",t=>{game.journal.get(t.currentTarget.dataset.entryid).panToNote()}),e.on("search keyup",".filterJournals",t=>{this.filterToc(t.currentTarget.value)}),e.on("click",".heading-link",t=>this._onClickPageLink(t)),e.on("click",".show-item",async t=>{let a=t.currentTarget.dataset.uuid;(await fromUuid(a)).sheet.render(!0)}),e.on("click",".movePage",async t=>this.movePage(t)),e.on("click",".loadBook",t=>{this.selectedChapter=void 0,this.selectedType=void 0,this.content=void 0,this.loadBook($(t.currentTarget).text(),e,t.currentTarget.dataset.type)}),e.on("click",".getChapter",t=>{this.selectedType=$(t.currentTarget).closest(".toc").attr("data-type"),this.selectedChapter=t.currentTarget.dataset.id,this.content=void 0,this.pageTocs=void 0,this.loadPage(e)}),e.on("click",".subChapter",async t=>{let a=$(t.currentTarget).text(),s=t.currentTarget.dataset.jid;s?await this.loadJournalById(s):($(this._element).find(".subChapter").removeClass("selected"),$(this._element).find(`[data-id="${a}"]`).addClass("selected"),await this.loadJournal(a)),this._saveScrollPositions(e),e.find(".toc").html(await this.getToc()),this._restoreScrollPositions(e),this.searchString&&this.filterToc(this.searchString)}),se.bindRollCommands(e),e.find(".tocCollapser").click(t=>{$(t.currentTarget).find("i").toggleClass("fa-chevron-right fa-chevron-left"),e.find(".tocCollapsing").toggleClass("expanded")}),e.on("mousedown",".openPin",async t=>{let a=t.currentTarget.dataset.uuid;t.button==0?this.showJournal(await fromUuid(a)):t.button==2&&this.unpinJournal(a)}),e.on("click",".showJournal",t=>{this.popJournal($(t.currentTarget).closest("h1").attr("data-uuid"))}),e.on("click",".pinJournal",t=>{let a=$(t.currentTarget).closest("h1"),s=a.attr("data-uuid"),i=a.text();this.pinJournal(s,i)}),e.on("click",".activateScene",t=>{this.showSzene(t.currentTarget.dataset.id,t.currentTarget.dataset.mode)}),e.on("click",".fulltextsearch",t=>{this.fulltextsearch=!this.fulltextsearch,$(t.currentTarget).toggleClass("on"),this.filterToc(e.find(".filterJournals").val())}),e.on("mousedown",".chapter img",t=>{let a=this.book.id;t.button==2&&game.dsa5.apps.DSA5_Utility.showArtwork({name:a,uuid:"",img:$(t.currentTarget).attr("src")})}),E.bindButtons(e),e.on("click",".importBook",async()=>this.importBook()),mt(e),ra(e,".breadcrumbs",this.resaveBreadCrumbs)}async getPagy(e,t){let a=this.journals.filter(i=>i.flags.dsa5.parent==e).sort((i,n)=>i.flags.dsa5.sort>n.flags.dsa5.sort?1:-1),s=a.findIndex(i=>i._id==t);return{journals:a,targetindex:s}}async movePage(e){let t=e.currentTarget.dataset.action,{journals:a,targetindex:s}=await this.getPagy(this.selectedChapter,this.selectedSubChapter),i=[];for(let c of this.bookData.chapters)for(let m of c.content)i.push(m.name);let n=i.findIndex(c=>c==this.selectedChapter);if(this.bookData.chapters.findIndex(c=>c.name==this.selectedChapter),t=="next"?s++:s--,s<0){if(this.selectedChapter=i[n-1],!this.selectedChapter)return;a=(await this.getPagy(this.selectedChapter,void 0)).journals,s=0}else if(s>=a.length){if(this.selectedChapter=i[n+1],!this.selectedChapter)return;a=(await this.getPagy(this.selectedChapter,void 0)).journals,s=0}if(["prep","foundryUsage"].includes(this.selectedChapter))return;let r=a[s];r&&await this.loadJournalById(r.id);let o=await this.getToc();this._saveScrollPositions(this._element),this._element.find(".toc").html(o),this._restoreScrollPositions(this._element)}async loadJournal(e){await this.showJournal(this.journals.find(t=>t.name==e&&t.flags.dsa5.parent==this.selectedChapter))}async loadJournalById(e){await this.showJournal(this.journals.find(t=>t.id==e))}async resaveBreadCrumbs(e){let t={};for(let a of e.getElementsByTagName("div"))t[a.dataset.uuid]=a.innerText;await game.settings.set("dsa5",`breadcrumbs_${game.world.id}`,JSON.stringify(t))}markFindings(e){let t=e.closest(".tocCollapsing");t.find(".searchLines").remove();let a=e.find(".searchMatch");if(a.length==0)return;let s=[],i=e.find("> div")[0].getBoundingClientRect();for(let r of a){let o=r.getBoundingClientRect();s.push(`
    `)}let n=$(`
    ${s.join("")}
    `);t.append(n)}async filterToc(e){if(this.searchString=e,e!=null)if(e=e.toLowerCase().trim(),e!=""){let s=[];this.fulltextsearch?(this.journalIndex||(this.journalIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data"]}}),await this.journalIndex.add(this.journals.map(i=>new Ws(i)))),s=await this.journalIndex.search(e)):s=this.journals.filter(i=>i.name.toLowerCase().trim().indexOf(e)!=-1),s=s.map(i=>`
  • ${i.name}
  • `),$(this._element).find(".tocContent").html(`
      ${s.join(` +`)}
    `)}else{let s=await this.getToc();$(this._element).find(".toc").html(s).find(".filterJournals").trigger("focus")}let t=await this.getChapter(),a=$(this._element).find(".chapter");a.html(t),this.markFindings(a)}showSearchResults(e){this.searchString&&TextEditor._replaceTextContent(TextEditor._getTextNodes(e),new RegExp(this.searchString,"ig"),(t,a)=>$(`${t[0]}`)[0])}_onClickPageLink(e){let t=e.currentTarget.closest("[data-anchor]")?.dataset.anchor;if(t){let s=this.element[0].querySelector(`.chapter [data-anchor="${t}"]`);if(s){s.scrollIntoView({behavior:"smooth"});return}}this.element[0].querySelector(".journalHeader")?.scrollIntoView({behavior:"smooth"})}async _renderHeadings(e){let t=Object.values(e);t.shift();let a=Math.min(...t.map(s=>s.level));return await renderTemplate("templates/journal/journal-page-toc.html",{headings:t.reduce((s,{text:i,level:n,slug:r,element:o})=>(o&&(o.dataset.anchor=r),n${d}
    `),e.name!=n.name&&(d=`

    ${n.name}

    ${d}`),t+=d}this.pageTocs=a.join("");let s=this.findSceneNote(e.getFlag("dsa5","initId")),i=await TextEditor.enrichHTML(t,{secrets:game.user.isGM,async:!0});return`

    ${e.name}
    ${s}

    ${i}`}async showJournal(e){let t=$(this._element).find(".chapter");t.html(await this.renderContent(e)),this.selectedSubChapter=e.id,$(this._element).find(".subChapter").removeClass("selected"),$(this._element).find(`[data-jid="${e.id}"]`).addClass("selected"),mt(t),this.markFindings(t),t.find(".documentName-link, .entity-link, .content-link").on("click",a=>{let s=a.currentTarget.dataset;this.bookData&&s.pack==this.bookData.journal&&s.type!="JournalEntryPage"&&(a.stopPropagation(),this.loadJournalById(s.id))})}findSceneNote(e){if(e){let t=game.journal.find(a=>a.getFlag("dsa5","initId")==e);if(t&&t.sceneNote)return``}return""}async importBook(){game.user.isGM&&new qs().render(this.bookData.moduleName)}async loadBook(e,t,a){a||(a=this.currentType),this.currentType=a,this.book=this[a].find(s=>s.id==e),await fetch(this.book.path).then(async s=>s.json()).then(async s=>{this.bookData=s;let i=game.packs.get(s.journal);await i.getIndex();let n=await i.getDocuments();this.journals=n,s.actors&&(i=game.packs.get(s.actors),n=await i.getIndex(),this.actors=n),s.scenes&&(i=game.packs.get(s.scenes),n=await i.getIndex(),this.scenes=n),this.checkChapters(i),this.loadPage(t)})}checkChapters(e){this.bookData.chapters||(this.bookData.isDynamic=!0,this.bookData.chapters=[{name:game.i18n.localize(`${this.bookData.moduleName}.name`),content:e.folders.map(t=>({name:t.name,id:t.id}))}])}async prefillActors(e){if(!e.actors)return[];let t=[],a=await game.folders.contents.find(i=>i.name==game.i18n.localize(`${this.bookData.moduleName}.name`)&&i.type=="Actor"&&i.folder==null),s=a?await game.folders.contents.filter(i=>i.type=="Actor"&&i.folder?.id==a.id).map(i=>i.id):void 0;for(let i of e.actors){let n=s?.length?game.actors.contents.find(m=>m.name==i&&s.includes(m.folder?.id)):void 0,r,o=n?.id,c=n?.uuid;n||(n=this.actors.find(m=>m.name==i),r=this.bookData.actors,o=n?._id,c=n?`Compendium.${r}.${o}`:void 0),t.push({name:i,actor:n,pack:r,id:o,uuid:c})}return t}async popJournal(e){(await fromUuid(e)).sheet.render(!0)}async showSzene(e,t="activate"){let a=game.scenes.contents.find(s=>s.name==e);if(!a)return ui.notifications.error(game.i18n.localize("DSAError.sceneNotInitialized"));switch(t){case"activate":a.activate();break;case"view":a.view();break;case"toggle":a.update({navigation:!a.navigation});break}}async getChapter(){if(this.book){if(this.content){let e=this.journals.find(t=>t.id==this.content);return await this.renderContent(e)}if(this.selectedChapter){if(this.selectedChapter=="prep"){let a={initDescr:game.i18n.format(`${this.bookData.moduleName}.importContent`,{defaultText:game.i18n.localize("importDefault")})},s=this.bookData.modules;for(let i of s)i.enabled=this.moduleEnabled(i.id);return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_preparation.html",{modules:s,info:a})}else if(this.selectedChapter=="foundryUsage")return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_foundry.html");let e=this.bookData.chapters.find(a=>a.name==this.selectedType).content.find(a=>a.id==this.selectedChapter),t=this.getSubChapters();return e.scenes||e.actors||t.length==0?await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_chapter.html",{chapter:e,subChapters:this.getSubChapters(),actors:await this.prefillActors(e)}):(this.selectedSubChapter=t[0].id,await this.loadJournalById(t[0].id))}return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_cover.html",{book:this.book,bookData:this.bookData})}else return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_intro.html",{rshs:this.filterBooks(this.rshs),rules:this.filterBooks(this.books),adventures:this.filterBooks(this.adventures),isGM:game.user.isGM})}filterBooks(e){let t=game.settings.get("dsa5","expansionPermissions");for(let a of e)t[a.id]!=null&&(a.visible=t[a.id]);return game.user.isGM?e:e.filter(a=>a.visible==null||a.visible).sort((a,s)=>a.id.localeCompare(s.id))}getSubChapters(){let e;return this.bookData.isDynamic?e=this.journals.filter(t=>t.folder.id==this.selectedChapter).sort((t,a)=>t.sort>a.sort?1:-1):e=this.journals.filter(t=>t.flags.dsa5.parent==this.selectedChapter).sort((t,a)=>t.flags.dsa5.sort>a.flags.dsa5.sort?1:-1),e.map(t=>{let a=this.selectedSubChapter==t.id;return{name:t.name,id:t.id,selected:a,cssClass:a?"selected":""}})}async getToc(){let e=[];if(this.book){if(e.push(...duplicate(this.bookData.chapters)),this.selectedChapter){let t;for(let a of e)if(t=a.content.find(s=>s.id==this.selectedChapter),t)break;t&&(t.cssClass="selected",t.subChapters=this.getSubChapters())}return await renderTemplate("systems/dsa5/templates/wizard/adventure/adventure_toc.html",{chapters:e,searchString:this.searchString,book:this.book,pageTocs:this.pageTocs,fulltextsearch:this.fulltextsearch?"on":""})}else return'
    '}async loadPage(e){let t=await this.getChapter(),a=await this.getToc();this._saveScrollPositions(e),e.find(".toc").html(a);let s=e.find(".chapter");s.html(t),this.markFindings(s),this._restoreScrollPositions(e)}async getData(e){let t=await super.getData(e),a=await this.getChapter(),s=await this.getToc(),i=game.settings.get("dsa5","journalFontSizeIndex"),n=b.journalFontSizes[i-1]||14;return mergeObject(t,{adventure:this.bookData,currentChapter:a,breadcrumbs:this.renderBreadcrumbs(),toc:s,fontSize:n}),t}async pinJournal(e,t=void 0){let a=this.readBreadCrumbs();t||(t=(await fromUuid(e))?.name||""),a[e]=t,game.settings.set("dsa5",`breadcrumbs_${game.world.id}`,JSON.stringify(a)),this.render(!0)}unpinJournal(e){let t=this.readBreadCrumbs();delete t[e],game.settings.set("dsa5",`breadcrumbs_${game.world.id}`,JSON.stringify(t)),this.render(!0)}_canDragDrop(e){return!0}async _onDrop(e){let t;try{t=JSON.parse(e.dataTransfer.getData("text/plain"))}catch{return!1}t.type=="JournalEntry"&&this.pinJournal(t.pack?`Compendium.${t.pack}.${t.id}`:`JournalEntry.${t.id}`)}readBreadCrumbs(){let e={};try{e=JSON.parse(game.settings.get("dsa5",`breadcrumbs_${game.world.id}`))}catch{console.log("No Journalbrowser notes found")}return e}renderBreadcrumbs(){let e=this.readBreadCrumbs(),t=Object.entries(e).map(a=>`
    ${a[1]}
    `);return t.length>0?``:""}moduleEnabled(e){return game.modules.get(e)?game.modules.get(e).active?"fa-check":"fa-dash":"fa-times"}},pt=Et;u(pt,"BookWizard"),L(pt,"wizard");var qs=class extends FormApplication{render(e){new game.dsa5.apps.DSA5Initializer("DSA5 Module Initialization",game.i18n.format(`${e}.importContent`,{defaultText:game.i18n.localize("importDefault")}),e,game.i18n.lang).render(!0)}};u(qs,"InitializerForm");var Ws=class{constructor(e){let t=e.pages.find(a=>!0).text.content;this.document={name:e.name,data:$("
    ").html(t).text(),id:e.id}}get name(){return this.document.name}get data(){return this.document.data}get id(){return this.document.id}};u(Ws,"JournalSearch");var $t=class{static registerButtons(){game.dsa5.apps.playerMenu=new Le,CONFIG.Canvas.layers.dsamenu={layerClass:Us,group:"interface"},Hooks.on("getSceneControlButtons",e=>{let t=[{name:"JournalBrowser",title:game.i18n.localize("Book.Wizard"),icon:"fa fa-book",button:!0,onClick:()=>{f.renderToggle(game.dsa5.apps.journalBrowser)}},{name:"Library",title:game.i18n.localize("SHEET.Library"),icon:"fas fa-university",button:!0,onClick:()=>{f.renderToggle(game.dsa5.itemLibrary)}},{name:"PlayerMenu",title:game.i18n.localize("PLAYER.title"),icon:"fas fa-dsa5-player",button:!0,onClick:()=>{f.renderToggle(game.dsa5.apps.playerMenu)}}];game.user.isGM&&(game.dsa5.apps.gameMasterMenu||(game.dsa5.apps.gameMasterMenu=new Vs),t.push({name:"mastersMenu",title:game.i18n.localize("gmMenu"),icon:"fa fa-dsa5",button:!0,onClick:()=>{f.renderToggle(game.dsa5.apps.gameMasterMenu)}})),e.push({name:"GM Menu",title:game.i18n.localize("gmMenu"),icon:"fas fa-dsa5",layer:"dsamenu",tools:t})})}};u($t,"MastersMenu");var Us=class extends InteractionLayer{static get layerOptions(){return foundry.utils.mergeObject(super.layerOptions,{name:"dsamenu",canDragCreate:!1,controllableObjects:!0,rotatableObjects:!0,zIndex:666})}selectObjects(e){canvas.tokens.selectObjects(e)}};u(Us,"DSAMenuLayer");var Vs=class extends Application{constructor(e){super(e),this.heros=[],this.lastSkill=`${game.i18n.localize("LocalizedIDs.perception")}|skill`,this.randomCreation=[],game.user.isGM&&(Hooks.on("updateActor",async(t,a,s,i)=>{if(!this.rendered)return;let n=["system.status.fatePoints","system.status.wounds","system.status.karmaenergy","system.status.astralenergy"];this.heros.some(r=>r.id==t.id)&&n.reduce((r,o)=>r||hasProperty(a,o),!1)&&this.render()}),Hooks.on("updateScene",async(t,a,s,i)=>{let n=["darkness"];if(game.canvas.id==t.id&&n.reduce((r,o)=>r||hasProperty(a,o),!1)){if(game.dsa5.apps.LightDialog&&game.dsa5.apps.LightDialog.onDarknessChange(),!this.rendered)return;this.render()}}),Hooks.on("canvasInit",()=>{!this.rendered||this.render()}))}async _render(e=!1,t={}){if(!game.user.isGM)return ui.notifications.error("DSAError.onlyGMallowed");await super._render(e,t)}getSelectedActors(){let e=game.settings.get("dsa5","selectedActors"),t=game.settings.get("dsa5","trackedActors"),a={};for(let s of Object.keys(e))t.actors?.includes(s)&&(a[s]=e[s]);return a}activateListeners(e){super.activateListeners(e),e.find("select.select2").select2(),oe(e),e.find(".heroLink").click(a=>{a.stopPropagation(),game.actors.get(this.getID(a)).sheet.render(!0)}),e.find(".addGlobalMod").click(()=>this.addGlobalMod()),e.find(".globalModEnable").change(a=>this.toggleGlobalMod(a)),e.find(".removeGlobalMod").click(a=>this.removeGlobalMod(a)),e.find(".editGlobalMod").click(a=>this.editGlobalMod(a)),e.find(".heroSelector").change(a=>{a.stopPropagation();let s=this.getSelectedActors();s[this.getID(a)]=$(a.currentTarget).is(":checked"),game.settings.set("dsa5","selectedActors",s)}),e.find(".skillSelektor").change(a=>{a.stopPropagation(),this.lastSkill=$(a.currentTarget).val()}),e.find(".rollChar").click(a=>{a.stopPropagation(),this.rollAbility([this.getID(a)])}),e.find(".rollAll").click(a=>{a.stopPropagation(),this.rollAbility(this.selectedIDs())}),e.find(".pay").click(a=>{a.stopPropagation(),this.doPayment([this.getID(a)],!0)}),e.find(".actorItem").click(async a=>{a.stopPropagation();let s=a.currentTarget.dataset.uuid;(await fromUuid(s)).sheet.render(!0)}),e.find(".getPaid").click(a=>{a.stopPropagation(),this.doPayment([this.getID(a)],!1)}),e.find(".resetSightThresholds").click(()=>this.resetSightThresholds()),e.find(".payAll").click(a=>{a.stopPropagation(),this.doPayment(this.selectedIDs(a),!0)}),e.find(".getPaidAll").click(a=>{a.stopPropagation(),this.doPayment(this.selectedIDs(a),!1)}),e.find(".selectAll").change(a=>this._selectAll(a,e)),e.find(".exp").click(a=>{a.stopPropagation(),this.getExp([this.getID(a)])}),e.find(".expAll").click(a=>{a.stopPropagation(),this.getExp(this.selectedIDs())}),e.find(".randomPlayer").mousedown(a=>{a.stopPropagation(),this._randomPlayer(e,a)}),e.find(".requestRoll").click(a=>{a.stopPropagation(),this.rollRequest()}),e.find(".heroSelector").click(a=>a.stopPropagation()),e.find(".hero").click(a=>{a.stopPropagation(a),$(a.currentTarget).find(".expandDetails").fadeToggle()});let t=u(a=>this._deleteHero(a),"deletehand");e.find(".hero").mouseenter(a=>{if(a.currentTarget.getElementsByClassName("hovermenu").length==0){let s=document.createElement("div");s.classList.add("hovermenu");let i=document.createElement("i");i.classList.add("fas","fa-times"),i.title=game.i18n.localize("SHEET.DeleteItem"),i.addEventListener("click",t,!1),s.appendChild(i),a.currentTarget.appendChild(s)}}),e.find(".hero").mouseleave(a=>{let s=a.toElement||a.relatedTarget;!s||s.parentNode==this||s==this||a.currentTarget.querySelectorAll(".hovermenu").forEach(i=>i.remove())}),e.find(".addGroupSchip").click(async a=>{await this.changeGroupSchipCount(Number(a.currentTarget.dataset.value))}),e.find(".groupschip").click(a=>{this.changeGroupSchip(a)}),e.find(".addFolder").click(async a=>this.editFolder(a)),e.find(".editFolder").change(async a=>this._editFolder(a)),e.find(".heroschip").click(a=>{a.stopPropagation(),a.preventDefault();let s=Number(a.currentTarget.getAttribute("data-val"));s==1&&$(a.currentTarget).closest(".hero").find(".fullSchip").length==1&&(s=0),game.actors.get(this.getID(a)).update({"system.status.fatePoints.value":s})}),e.find(".groupCheck").click(a=>{a.stopPropagation(),this.doGroupCheck()}),e.find(".changeSetting").change(async a=>{await game.settings.set("dsa5",a.currentTarget.name,a.currentTarget.checked)}),e.find(".changeSightTreshold").change(async a=>{$(a.currentTarget).closest(".row-section").find(".range-value").text(a.currentTarget.value),this.updateSightThreshold(a)}),e.find(".updateDarkness").change(async a=>{$(a.currentTarget).closest(".row-section").find(".range-value").text(a.currentTarget.value),this.updateDarkness(a)});for(let a of this.randomCreation)a.activateListeners(e);ra(e,".heros",this.updateHeroOrder,".hero"),e.on("dragstart",".hero",a=>{a.stopPropagation();let s=a.currentTarget,i={type:"Actor",uuid:s.dataset.uuid};a.originalEvent.dataTransfer.setData("text/plain",JSON.stringify(i))}),e.find(".dragEveryone").each(function(a,s){s.setAttribute("draggable",!0)}),e.on("dragstart",".dragEveryone",a=>this._dragEveryone(a)),game.dsa5.apps.LightDialog&&game.dsa5.apps.LightDialog.activateButtonListener(e)}async _dragEveryone(e){e.stopPropagation();let t;e.currentTarget.dataset.folder?t=expandObject(game.settings.get("dsa5","masterSettings")).folders.find(i=>i.id==e.currentTarget.dataset.folder).content:t=this.selectedIDs();let a={type:"GroupDrop",ids:t};e.originalEvent.dataTransfer.setData("text/plain",JSON.stringify(a))}async _selectAll(e,t){e.stopPropagation();let a=".heroSelector";e.currentTarget.dataset.folder&&(a=`[data-id="${e.currentTarget.dataset.folder}"] .heroSelector`);let s=t.find(a);s.prop("checked",$(e.currentTarget).is(":checked")),s.change()}async _deleteHero(e){e.stopPropagation(),e.preventDefault();let t=$(e.currentTarget).closest(".hero").attr("data-id"),a=game.settings.get("dsa5","trackedActors").actors||[],s=a.indexOf(t);s>-1&&(a.splice(s,1),await game.settings.set("dsa5","trackedActors",{actors:a}),this.render(!0))}async updateHeroOrder(e){let t=[];for(let a of e.querySelectorAll(".hero"))t.push(a.dataset.id);await game.settings.set("dsa5","trackedActors",{actors:t})}async updateDarkness(e){canvas.scene&&canvas.scene.update({darkness:Number(e.currentTarget.value)},{animateDarkness:3e3})}async updateSightThreshold(e){let t=Number(e.currentTarget.dataset.index),a=Number(e.currentTarget.value),s=game.settings.get("dsa5","sightOptions").split("|");s[t]=a,await game.settings.set("dsa5","sightOptions",s.join("|"))}async resetSightThresholds(){await game.settings.set("dsa5","sightOptions",game.settings.settings.get("dsa5.sightOptions").default),this.render(!0)}getGroupSchipSetting(){return game.settings.get("dsa5","groupschips").split("/").map(e=>Number(e))}async changeGroupSchipCount(e){let t=this.getGroupSchipSetting();t[1]=Math.max(0,t[1]+e),t[0]=Math.min(t[1],t[0]),await game.settings.set("dsa5","groupschips",t.join("/"))}async changeGroupSchip(e){let t=Number(e.currentTarget.getAttribute("data-val"));t==1&&$(e.currentTarget).closest(".col").find(".fullSchip").length==1&&(t=0);let a=this.getGroupSchipSetting();a[0]=t,await game.settings.set("dsa5","groupschips",a.join("/"))}async _createFolder(){let e=expandObject(game.settings.get("dsa5","masterSettings"));e.folders||(e.folders=[]),e.folders.push({id:randomID(),name:game.i18n.localize("FOLDER.ExportNewFolder"),content:[]}),await game.settings.set("dsa5","masterSettings",e),await this.render(!0)}async _deleteFolder(e){let t=e.currentTarget.dataset.id,a=expandObject(game.settings.get("dsa5","masterSettings"));a.folders=a.folders.filter(s=>s.id!=t),await game.settings.set("dsa5","masterSettings",a),await this.render(!0)}async _editFolder(e){let t=e.currentTarget.dataset.id,a=expandObject(game.settings.get("dsa5","masterSettings"));a.folders.find(s=>s.id==t).name=e.currentTarget.value,await game.settings.set("dsa5","masterSettings",a)}async editFolder(e){switch(e.currentTarget.dataset.action){case"create":this._createFolder();break;case"delete":this._deleteFolder(e);break}}async addGlobalMod(){new Qt().render(!0)}async editGlobalMod(e){let t=e.currentTarget.dataset.key;new Qt(t).render(!0)}async toggleGlobalMod(e){let t=game.settings.get("dsa5","masterSettings");t.globalMods[e.currentTarget.dataset.key].enabled=e.currentTarget.checked,await game.settings.set("dsa5","masterSettings",t)}async removeGlobalMod(e){let t=game.settings.get("dsa5","masterSettings");delete t.globalMods[e.currentTarget.dataset.key],await game.settings.set("dsa5","masterSettings",t),this.render()}async _randomPlayer(e,t){let a=e.find(".hero"),s=await this.rollRandomPlayer(t.button==2);$(t.currentTarget).find("i").addClass("fa-spin"),a.removeClass("victim"),setTimeout(()=>{$(this._element).find(`.hero[data-id="${s}"]`).addClass("victim"),$(t.currentTarget).find("i").removeClass("fa-spin")},500)}async rollRandomPlayer(e){let t={},a=1,s=this.getSelectedActors(),i=Object.values(s).filter(o=>o).length!=0,n=this.heros.length?this.heros:await this.getTrackedHeros();if(n.length==0){ui.notifications.warn(game.i18n.localize("DIALOG.noTarget"));return}for(let o of n)!s[o.id]&&i||(t[a]=o.id,a++,e&&O.hasVantage(o,game.i18n.localize("LocalizedIDs.misfortune"))&&(t[a]=o.id,a++),e&&o.hasCondition("badluck")&&(t[a]=o.id,a++));let r=(await new Roll(`1d${a-1}`).evaluate({async:!0})).total;return t[r]}async doPayment(e,t,a=0){let s=game.actors.filter(o=>e.includes(o.id)),i=this.getNames(s),n=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:a,text:game.i18n.localize(game.i18n.format(t?"MASTER.payText":"MASTER.getPaidText",{heros:i}))}),r=u(o=>{let c=o.find(".input-text").val();for(let m of s)B.handlePayAction(void 0,t,c,m)},"callback");this.buildDialog(game.i18n.localize(t?"MASTER.payTT":"PAYMENT.payButton"),n,r)}async getPaid(e){this.doPayment(e,!1)}async getExp(e,t=0){let a=game.actors.filter(n=>e.includes(n.id)),s=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:t,text:game.i18n.localize(game.i18n.format("MASTER.awardXPText",{heros:this.getNames(a)}))}),i=u(async n=>{let r=Number(n.find(".input-text").val()),o=Math.max(1,Math.round(r*.25)),c=[],m=[];if(!isNaN(r)){for(let d of a){let p=r;d.system.isFamiliar||d.system.isPet?(p=o,m.push(d)):c.push(d),await d.update({"system.details.experience.total":d.system.details.experience.total+p})}c.length>0&&await ChatMessage.create(f.chatDataSetup(game.i18n.format("MASTER.xpMessage",{heros:this.getNames(c),number:r}))),m.length>0&&await ChatMessage.create(f.chatDataSetup(game.i18n.format("MASTER.xpMessage",{heros:this.getNames(m),number:r}))),this.rendered&&this.render(!0)}},"callback");this.buildDialog(game.i18n.localize("MASTER.awardXP"),s,i)}getNames(e){return e.map(t=>t.name).join(", ")}buildDialog(e,t,a){new ie({title:e,content:t,default:"yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:s=>{a(s)}},cancel:{icon:'',label:game.i18n.localize("cancel")}}}).render(!0)}_canDragDrop(e){return!0}async _onDrop(e){let t;try{t=JSON.parse(e.dataTransfer.getData("text/plain")),t=await Actor.implementation.fromDropData(t)}catch{return!1}if(t.documentName=="Actor"){let a=game.settings.get("dsa5","trackedActors");a=a.actors||[],a.indexOf(t.id)==-1&&!t.pack&&(a.push(t.id),await game.settings.set("dsa5","trackedActors",{actors:a}),this.render(!0));let s=$(e.target).closest(".isFolder"),i=expandObject(game.settings.get("dsa5","masterSettings"));s.length?i.folders=i.folders.map(n=>(n.content=n.content.filter(r=>r!=t.id),n.id==s[0].dataset.id&&n.content.push(t.id),n)):i.folders=i.folders.map(n=>(n.content=n.content.filter(r=>r!=t.id),n)),await game.settings.set("dsa5","masterSettings",i),this.render(!0)}}selectedIDs(){let e=[],t=this.getSelectedActors();for(let[a,s]of Object.entries(t))s&&e.push(a);return e.length?e:game.settings.get("dsa5","trackedActors").actors||[]}async doGroupCheck(e=0){let[t,a]=this.lastSkill.split("|");if(a!="skill")return;let s=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:e,text:game.i18n.localize(game.i18n.format("MASTER.doGroupCheck",{skill:t}))}),i=u(n=>{let r=Number(n.find(".input-text").val()),[o,c]=this.lastSkill.split("|");c=="skill"&&q.showGCMessage(o,r)},"callback");this.buildDialog(game.i18n.localize("HELP.groupcheck"),s,i)}async rollRequest(e=0){let[t,a]=this.lastSkill.split("|");if(a!="skill")return;let s=await renderTemplate("systems/dsa5/templates/dialog/master-dialog-award.html",{amount:e,text:game.i18n.localize(game.i18n.format("MASTER.doRequestRoll",{skill:t}))}),i=u(n=>{let r=Number(n.find(".input-text").val()),[o,c]=this.lastSkill.split("|");c=="skill"&&q.showRQMessage(o,r)},"callback");this.buildDialog(game.i18n.localize("HELP.request"),s,i)}rollAbility(e){let[t,a]=this.lastSkill.split("|");switch(a){case"skill":this.rollSkill(e,t);break;case"attribute":this.rollAttribute(e,t);break;case"regeneration":this.rollRegeneration(e);break}}rollRegeneration(e){let t=game.actors.filter(a=>e.includes(a.id));for(let a of t)a.setupRegeneration("regenerate",{rollMode:"blindroll",subtitle:` (${a.name})`},void 0).then(s=>{a.basicTest(s)})}rollAttribute(e,t){let a=game.actors.filter(i=>e.includes(i.id)),s=Object.keys(game.dsa5.config.characteristics).find(i=>game.i18n.localize(game.dsa5.config.characteristics[i])==t);for(let i of a)i.setupCharacteristic(s,{rollMode:"blindroll",subtitle:` (${i.name})`},void 0).then(n=>{i.basicTest(n)})}rollSkill(e,t){let a=game.actors.filter(s=>e.includes(s.id));for(let s of a){let i=s.items.find(n=>n.name==t&&n.type=="skill");s.setupSkill(i,{rollMode:"blindroll",subtitle:` (${s.name})`},void 0).then(n=>{s.basicTest(n)})}}getID(e){return $(e.currentTarget).closest(".hero").attr("data-id")}static get defaultOptions(){let e=super.defaultOptions;return e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"main"}],mergeObject(e,{classes:e.classes.concat(["dsa5","largeDialog","masterMenu","sheet"]),width:470,height:740,title:game.i18n.localize("gmMenu"),dragDrop:[{dragSelector:null,dropSelector:null}]}),e.template="systems/dsa5/templates/system/mastermenu.html",e.resizable=!0,e}async getTrackedHeros(){let e=game.settings.get("dsa5","trackedActors"),t=[];return e.actors&&e.actors.length>0?t=game.actors.filter(a=>e.actors.includes(a.id)).sort((a,s)=>e.actors.indexOf(a.id)-e.actors.indexOf(s.id)):(t=game.actors.filter(a=>a.hasPlayerOwner),await game.settings.set("dsa5","trackedActors",{actors:t.map(a=>a.id)})),t}async getData(e){let t=await super.getData(e),a=await this.getTrackedHeros(),s=P.getGroupSchips(),i=game.settings.get("dsa5","sightOptions").split("|"),n=/ \[[a-zA-Zäöü\d-]+\]/,r=[1,2,3,4].map(p=>({label:game.i18n.localize(`VisionDisruption.step${p}`).replace(n,""),value:i[p-1]}));t.sceneConfig={sceneAutomationEnabled:game.settings.get("dsa5","sightAutomationEnabled"),enableDPS:game.settings.get("dsa5","enableDPS"),lightSightCompensationEnabled:game.settings.get("dsa5","lightSightCompensationEnabled"),visions:r,darkness:canvas.scene?.darkness||0},this.heros=a;let o=this.getSelectedActors(),c=expandObject(game.settings.get("dsa5","masterSettings")),m=[],d=(c.folders||[]).map(p=>(p.contents=[],p.content=new Set(p.content),p));for(let p of a){let g=duplicate(p),y=[],h=[],w=[];for(let v of g.items)switch(v.type){case"disadvantage":y.push({name:v.name,uuid:v.uuid});break;case"advantage":h.push({name:v.name,uuid:v.uuid});break;case"money":w.push(v);break}mergeObject(g,{id:p.id,uuid:p.uuid,selected:o[p.id],schips:p.schipshtml(),purse:w.sort((v,S)=>S.system.price.value-v.system.price.value).map(v=>`${v.system.quantity.value}`).join(" - "),advantages:h,disadvantages:y,system:{status:{wounds:{max:p.system.status.wounds.max},astralenergy:{max:p.system.status.astralenergy.max},karmaenergy:{max:p.system.status.karmaenergy.max}},isMage:p.system.isMage,isPriest:p.system.isPriest}});let z=!1;for(let v of d)if(v.content.has(p.id)){v.contents.push(g),z=!0;break}z||m.push(g)}if(!this.abilities){let p=await f.allSkillsList();this.abilities=p.map(g=>({name:g,type:"skill"})).concat(Object.values(game.dsa5.config.characteristics).map(g=>({name:game.i18n.localize(g),type:"attribute"})).concat({name:game.i18n.localize("regenerate"),type:"regeneration"})).sort((g,y)=>g.name.localeCompare(y.name))}return mergeObject(t,{hasHeros:a.length>0,heros:m,folders:d,abilities:this.abilities,groupschips:s,masterSettings:c,lastSkill:this.lastSkill,randomCreation:this.randomCreation.map(p=>p.template),lightButton:game.dsa5.apps.LightDialog?await game.dsa5.apps.LightDialog.getButtonHTML():""}),t}registerRandomCreation(e){this.randomCreation.push(e)}};u(Vs,"GameMasterMenu");var Qt=class extends FormApplication{constructor(e){super(),this.mod_id=e}static get defaultOptions(){let e=super.defaultOptions;return e.template="systems/dsa5/templates/system/global-mod-addition.html",e.title=game.i18n.localize("MASTER.addGlobalMod"),e.width=400,e.resizable=!0,e}activateListeners(e){super.activateListeners(e),e.find(".addGlobalMod").click(t=>this.addGlobalMod(t))}async getData(e){let t=await super.getData(e);return this.mod_id?t.config=expandObject(game.settings.get("dsa5","masterSettings").globalMods[this.mod_id]):t.config={value:0,victim:{npc:!0,player:!0}},t.categories=["skill","spell","meleeweapon","rangeweapon","ritual","ceremony","liturgy","trait"],t}async addGlobalMod(e){e.preventDefault();let t=expandObject(game.settings.get("dsa5","masterSettings")),a=expandObject(new FormDataExtended($(this._element).find("form")[0]).object);a.enabled=!0,a.name&&(this.mod_id?t.globalMods[this.mod_id]=a:mergeObject(t,{globalMods:{[randomID()]:a}}),await game.settings.set("dsa5","masterSettings",t),game.dsa5.apps.gameMasterMenu.render(),this.close())}};u(Qt,"GlobalModAddition");var Ot=class extends it(Oe){static get merchantTemplate(){return"systems/dsa5/templates/actors/merchant/creature-merchant-sheet.html"}};u(Ot,"CreatureMerchantSheetDSA5");var zt=class extends it(be){static get merchantTemplate(){return"systems/dsa5/templates/actors/merchant/character-merchant-sheet.html"}};u(zt,"CharacterMerchantSheetDSA5");var xt=class extends JournalSheet{static get defaultOptions(){let e=super.defaultOptions;return mergeObject(e,{classes:e.classes.concat(["dsa5","dsajournal"])}),e}};u(xt,"DSAJournalSheet");function ki(){ii(),ni(),ri(),oi(),li(),ci(),Ii(),di(),mi(),pi(),fi(),Xs(),hi(),bi()}u(ki,"default");Hooks.once("init",()=>{loadTemplates(["systems/dsa5/templates/actors/actor-main.html","systems/dsa5/templates/actors/actor-talents.html","systems/dsa5/templates/items/item-description.html","systems/dsa5/templates/dialog/default-dialog.html","systems/dsa5/templates/dialog/parts/targets.html","systems/dsa5/templates/dialog/enhanced-default-dialog.html","systems/dsa5/templates/dialog/default-combat-dialog.html","systems/dsa5/templates/chat/roll/test-card.html","systems/dsa5/templates/items/item-equipment.html","systems/dsa5/templates/items/item-enchantment.html","systems/dsa5/templates/actors/actor-combat.html","systems/dsa5/templates/actors/actor-equipment.html","systems/dsa5/templates/actors/actor-notes.html","systems/dsa5/templates/dialog/parts/spellmodifiers.html","systems/dsa5/templates/dialog/parts/canChangeCastingTime.html","systems/dsa5/templates/actors/parts/schipspart.html","systems/dsa5/templates/chat/post-item.html","systems/dsa5/templates/items/item-stat.html","systems/dsa5/templates/items/item-extension.html","systems/dsa5/templates/actors/creature/creature-main.html","systems/dsa5/templates/actors/creature/creature-loot.html","systems/dsa5/templates/actors/creature/creature-notes.html","systems/dsa5/templates/actors/creature/creature-magic.html","systems/dsa5/templates/system/masterHeros.html","systems/dsa5/templates/actors/creature/creature-religion.html","systems/dsa5/templates/actors/parts/characteristics-large.html","systems/dsa5/templates/actors/parts/gearSearch.html","systems/dsa5/templates/actors/parts/magicalSigns.html","systems/dsa5/templates/actors/parts/containerContent.html","systems/dsa5/templates/actors/npc/npc-main.html","systems/dsa5/templates/actors/character/actor-magic.html","systems/dsa5/templates/actors/character/actor-religion.html","systems/dsa5/templates/actors/character/actor-aggregatedtests.html","systems/dsa5/templates/actors/parts/creature-derived-attributes-small.html","systems/dsa5/templates/actors/parts/creature-derived-attributes-large.html","systems/dsa5/templates/actors/parts/status_effects.html","systems/dsa5/templates/actors/parts/purse.html","systems/dsa5/templates/actors/parts/horse.html","systems/dsa5/templates/actors/parts/healthbar.html","systems/dsa5/templates/actors/merchant/merchant-commerce.html","systems/dsa5/templates/items/item-header.html","systems/dsa5/templates/items/item-effects.html","systems/dsa5/templates/items/item-aoe.html","systems/dsa5/templates/items/traditionArtifact.html","systems/dsa5/templates/status/advanced_functions.html","systems/dsa5/templates/actors/parts/information.html","systems/dsa5/templates/actors/parts/personaltrait.html","systems/dsa5/templates/actors/parts/combatskills.html","systems/dsa5/templates/actors/parts/attributes.html","systems/dsa5/templates/actors/parts/swarm.html","systems/dsa5/templates/actors/parts/carryandpurse.html","systems/dsa5/templates/actors/parts/specialabilities.html","systems/dsa5/templates/actors/parts/experienceBox.html","systems/dsa5/templates/actors/parts/temperature.html","systems/dsa5/templates/actors/parts/temperatureSmall.html","systems/dsa5/templates/actors/parts/spells.html","systems/dsa5/templates/dialog/parts/expChoices.html","systems/dsa5/templates/actors/parts/liturgies.html","systems/dsa5/templates/items/browse/actor.html","systems/dsa5/templates/items/browse/garadan.html","systems/dsa5/templates/items/browse/culture.html","systems/dsa5/templates/items/browse/species.html","systems/dsa5/templates/items/browse/career.html","systems/dsa5/templates/actors/parts/specblock.html"]),Actors.unregisterSheet("core",ActorSheet),Actors.registerSheet("dsa5",be,{types:["character"],makeDefault:!0}),Actors.registerSheet("dsa5",Oe,{types:["creature"],makeDefault:!0}),Actors.registerSheet("dsa5",ze,{types:["npc"],makeDefault:!0}),Actors.registerSheet("dsa5",Ae,{types:["npc"]}),Actors.registerSheet("dsa5",Ot,{types:["creature"]}),Actors.registerSheet("dsa5",zt,{types:["character"]}),DocumentSheetConfig.registerSheet(ActiveEffect,"dsa5",Q,{makeDefault:!0}),Journal.registerSheet("dsa5",xt,{makeDefault:!0}),Y.setupSheets(),Hooks.call("registerDSAstyle",b.styles),Pi(),J.initDoorMinDistance(),mergeObject(CONFIG.JournalEntry.noteIcons,b.noteIcons),K.prepareSoundEffects(),$("body").addClass(game.settings.get("dsa5","globalStyle"))});Hooks.once("setup",()=>{if(!["de","en"].includes(game.i18n.lang))console.warn(`DSA5 - ${game.i18n.lang} is not a supported language. Falling back to default language.`),Tn();else{let l=game.settings.get("dsa5","forceLanguage");["de","en"].includes(l)&&game.i18n.lang!=l&&Sn(l)}pt.initHook(),yi(),$t.registerButtons(),De.registerButtons(),CONFIG.Canvas.lightAnimations.daylight={label:"LIGHT.daylight",illuminationShader:Xt},O.setupFunctions(),R.setupFunctions()});Hooks.once("i18nInit",()=>{Cn()});var Ks=class extends Dialog{async close(e={}){if(!!["de","en"].includes(game.i18n.lang))return super.close(e)}};u(Ks,"ForbiddenLanguageDialog");var Tn=u(()=>{let l={title:game.i18n.localize("language"),content:"

    Your foundry language is not supported by this system. Due to technical reasons your foundry language setting has to be switched to either english or german.

    ",buttons:{de:{icon:'',label:"en",callback:async()=>{await game.settings.set("core","language","de"),foundry.utils.debouncedReload()}},en:{icon:'',label:"de",callback:async()=>{await game.settings.set("core","language","en"),foundry.utils.debouncedReload()}},logout:{icon:'',label:game.i18n.localize("SETTINGS.Logout"),callback:async()=>{ui.menu.items.logout.onClick()}}}};new Ks(l).render(!0)},"showForbiddenLanguageDialog"),Sn=u(l=>{let e={title:game.i18n.localize("DSASETTINGS.forceLanguage"),content:game.i18n.format("DSAError.wrongLanguage",{lang:l}),buttons:{ok:{icon:'',label:game.i18n.localize("ok"),callback:async()=>{await game.settings.set("core","language",l),foundry.utils.debouncedReload()}},cancel:{icon:'',label:game.i18n.localize("cancel")}}};new Dialog(e).render(!0)},"showWrongLanguageDialog");function Cn(){game.dsa5.config.knownShortcuts={[game.i18n.localize("CHARAbbrev.INI").toLowerCase()]:["status","initiative","gearmodifier"],[game.i18n.localize("CHARAbbrev.GS").toLowerCase()]:["status","speed","gearmodifier"],[game.i18n.localize("CHARAbbrev.AsP").toLowerCase()]:["status","astralenergy","gearmodifier"],[game.i18n.localize("CHARAbbrev.LeP").toLowerCase()]:["status","wounds","gearmodifier"],[game.i18n.localize("CHARAbbrev.KaP").toLowerCase()]:["status","karmaenergy","gearmodifier"],[game.i18n.localize("CHARAbbrev.AW").toLowerCase()]:["status","dodge","gearmodifier"],[game.i18n.localize("CHARAbbrev.SK").toLowerCase()]:["status","soulpower","gearmodifier"],[game.i18n.localize("CHARAbbrev.ZK").toLowerCase()]:["status","toughness","gearmodifier"],[game.i18n.localize("CHARAbbrev.FtP").toLowerCase()]:["status","fatePoints","gearmodifier"]};for(let l of Object.keys(b.characteristics))game.dsa5.config.knownShortcuts[game.i18n.localize(`CHARAbbrev.${l.toUpperCase()}`).toLowerCase()]=["characteristics",l.toLowerCase(),"gearmodifier"]}u(Cn,"setupKnownEquipmentModifiers");var Pt=class extends AdaptiveIlluminationShader{},Xt=Pt;u(Xt,"DaylightIlluminationShader"),L(Xt,"fragmentShader",` ${Pt.SHADER_HEADER} ${Pt.PERCEIVED_BRIGHTNESS} @@ -94,7 +94,7 @@ var vi=Object.defineProperty;var Fi=(l,e,t)=>e in l?vi(l,e,{enumerable:!0,config finalColor = mix(finalColor, max(finalColor, smoothstep( 0.1, 1.0, finalColor ) * 10.0), 1.0) * depth; // Final gl_FragColor = vec4(finalColor, 1.0); - }`);var Nt=class{static weaponLessMacro(e){let t=ChatMessage.getSpeaker(),a;t.token&&(a=game.actors.tokens[t.token]),a||(a=game.actors.get(t.actor)),this.runWeaponless(a,e,t.token)}static weaponLessMacroId(e,t){let a=game.actors.get(t);this.runWeaponless(a,e)}static requestRoll(e,t=0){q.showRQMessage(e,t)}static requestGC(e,t=0,a={}){q.showGCMessage(e,t,a)}static rollCh(e,t={}){ae.check3D20(void 0,e,t)}static itemMacroById(e,t,a,s){let i=game.actors.get(e),r=i?i.items.find(n=>n.name===t&&n.type==a):null;this.runItem(i,r,t,s)}static itemMacro(e,t,a){let s=ChatMessage.getSpeaker(),i;s.token&&(i=game.actors.tokens[s.token]),i||(i=game.actors.get(s.actor));let r=i?i.items.find(n=>n.name===e&&n.type==t):null;this.runItem(i,r,e,a,s.token)}static charMacroById(e,t){let a=game.actors.get(t);this.runChar(a,e)}static charMacro(e){let t=ChatMessage.getSpeaker(),a;t.token&&(a=game.actors.tokens[t.token]),a||(a=game.actors.get(t.actor)),this.runChar(a,e,t.token)}static runWeaponless(e,t,a){if(!e)return ui.notifications.error(game.i18n.format("DSAError.MacroItemMissing",{item:t}));let s=t.split("Weaponless")[0];e.setupWeaponless(s,{},a).then(i=>{e.basicTest(i)})}static runChar(e,t,a){if(!e)return ui.notifications.error(game.i18n.format("DSAError.MacroItemMissing",{item:t}));e.setupDodge({},a).then(s=>{e.basicTest(s)})}static runItem(e,t,a,s,i){if(!e)return ui.notifications.error(game.i18n.format("DSAError.MacroItemMissing",{item:a}));switch(t.type){case"combatskill":case"trait":case"meleeweapon":return e.setupWeapon(t,s.mod,s,i).then(r=>{e.basicTest(r)});case"rangeweapon":return e.setupWeapon(t,"attack",s,i).then(r=>{e.basicTest(r)});case"skill":return e.setupSkill(t,s,i).then(r=>{e.basicTest(r)});case"ceremony":case"ritual":case"spell":case"liturgy":return e.setupSpell(t,s,i).then(r=>{e.basicTest(r)})}}};u(Nt,"MacroDSA5");var Ri={};Hooks.once("ready",()=>{Promise.all([f.allSkillsList(),f.allCombatSkills()]).then(l=>{let e=l[0].reduce((n,o)=>({...n,[o]:o}),{}),t=l[1].filter(n=>n.system.weapontype.value=="range").sort((n,o)=>n.name.localeCompare(o.name)).reduce((n,o)=>({...n,[o.name]:o.name}),{}),a=l[1].filter(n=>n.system.weapontype.value=="melee").sort((n,o)=>n.name.localeCompare(o.name)).reduce((n,o)=>({...n,[o.name]:o.name}),{}),s=l[1].concat([{name:game.i18n.localize("LocalizedIDs.all")}]).sort((n,o)=>n.name.localeCompare(o.name)).reduce((n,o)=>({...n,[o.name]:o.name}),{}),i=[];for(let[n,o]of Object.entries(b.specialAbilityCategories))n=="clerical"?i.push(``):n=="magical"&&i.push(``),i.push(``);let r=`
    + }`);var Nt=class{static weaponLessMacro(e){let t=ChatMessage.getSpeaker(),a;t.token&&(a=game.actors.tokens[t.token]),a||(a=game.actors.get(t.actor)),this.runWeaponless(a,e,t.token)}static weaponLessMacroId(e,t){let a=game.actors.get(t);this.runWeaponless(a,e)}static requestRoll(e,t=0){q.showRQMessage(e,t)}static requestGC(e,t=0,a={}){q.showGCMessage(e,t,a)}static rollCh(e,t={}){ae.check3D20(void 0,e,t)}static itemMacroById(e,t,a,s){let i=game.actors.get(e),n=i?i.items.find(r=>r.name===t&&r.type==a):null;this.runItem(i,n,t,s)}static itemMacro(e,t,a){let s=ChatMessage.getSpeaker(),i;s.token&&(i=game.actors.tokens[s.token]),i||(i=game.actors.get(s.actor));let n=i?i.items.find(r=>r.name===e&&r.type==t):null;this.runItem(i,n,e,a,s.token)}static charMacroById(e,t){let a=game.actors.get(t);this.runChar(a,e)}static charMacro(e){let t=ChatMessage.getSpeaker(),a;t.token&&(a=game.actors.tokens[t.token]),a||(a=game.actors.get(t.actor)),this.runChar(a,e,t.token)}static runWeaponless(e,t,a){if(!e)return ui.notifications.error(game.i18n.format("DSAError.MacroItemMissing",{item:t}));let s=t.split("Weaponless")[0];e.setupWeaponless(s,{},a).then(i=>{e.basicTest(i)})}static runChar(e,t,a){if(!e)return ui.notifications.error(game.i18n.format("DSAError.MacroItemMissing",{item:t}));e.setupDodge({},a).then(s=>{e.basicTest(s)})}static runItem(e,t,a,s,i){if(!e)return ui.notifications.error(game.i18n.format("DSAError.MacroItemMissing",{item:a}));switch(t.type){case"combatskill":case"trait":case"meleeweapon":return e.setupWeapon(t,s.mod,s,i).then(n=>{e.basicTest(n)});case"rangeweapon":return e.setupWeapon(t,"attack",s,i).then(n=>{e.basicTest(n)});case"skill":return e.setupSkill(t,s,i).then(n=>{e.basicTest(n)});case"ceremony":case"ritual":case"spell":case"liturgy":return e.setupSpell(t,s,i).then(n=>{e.basicTest(n)})}}};u(Nt,"MacroDSA5");var Ri={};Hooks.once("ready",()=>{Promise.all([f.allSkillsList(),f.allCombatSkills()]).then(l=>{let e=l[0].reduce((r,o)=>({...r,[o]:o}),{}),t=l[1].filter(r=>r.system.weapontype.value=="range").sort((r,o)=>r.name.localeCompare(o.name)).reduce((r,o)=>({...r,[o.name]:o.name}),{}),a=l[1].filter(r=>r.system.weapontype.value=="melee").sort((r,o)=>r.name.localeCompare(o.name)).reduce((r,o)=>({...r,[o.name]:o.name}),{}),s=l[1].concat([{name:game.i18n.localize("LocalizedIDs.all")}]).sort((r,o)=>r.name.localeCompare(o.name)).reduce((r,o)=>({...r,[o.name]:o.name}),{}),i=[];for(let[r,o]of Object.entries(b.specialAbilityCategories))r=="clerical"?i.push(``):r=="magical"&&i.push(``),i.push(``);let n=`
    -
    `;mergeObject(Ri,{ammunition:[{label:"ammunitiongroup",attr:"ammunitiongroup.value",type:"select",options:b.ammunitiongroups}],equipment:[{label:"equipmentType",attr:"equipmentType.value",type:"select",options:b.equipmentTypes}],rangeweapon:[{label:"TYPES.Item.combatskill",attr:"combatskill.value",type:"select",options:t},{label:"ammunitiongroup",attr:"ammunitiongroup.value",type:"select",options:b.ammunitiongroups}],meleeweapon:[{label:"TYPES.Item.combatskill",attr:"combatskill.value",type:"select",options:a},{label:"guidevalue",attr:"guidevalue.value",type:"select",options:b.combatskillsGuidevalues},{label:"reach",attr:"reach.value",type:"select",options:b.meleeRanges}],poison:[{label:"resistanceModifier",attr:"resistance.value",type:"select",options:b.magicResistanceModifiers}],disease:[{label:"resistanceModifier",attr:"resistance.value",type:"select",options:b.magicResistanceModifiers}],consumable:[{label:"equipmentType",attr:"equipmentType.value",type:"select",options:b.equipmentTypes}],application:[{label:"TYPES.Item.skill",attr:"skill",type:"select",options:e}],trait:[{label:"traitType",attr:"traitType.value",type:"select",options:b.traitCategories}],career:[{label:"mageLevel",attr:"mageLevel.value",type:"select",options:b.mageLevels}],specialability:[{type:"prerendered",attr:"category.value",content:r},{label:"TYPES.Item.combatskill",attr:"list.value",type:"select",options:s,notStrict:!0},{label:"distribution",attr:"distribution",type:"text"}],liturgy:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"}],spell:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"},{label:"feature",attr:"feature",type:"text"}],ritual:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"},{label:"feature",attr:"feature",type:"text"}],ceremony:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"}],spellextension:[{label:"Category",attr:"category",type:"select",options:{spell:"spell",liturgy:"liturgy",ritual:"ritual",ceremony:"ceremony"}}],magictrick:[{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"feature",attr:"feature.value",type:"text"},{label:"distribution",attr:"distribution",type:"text"}],blessing:[{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"feature",attr:"feature.value",type:"text"}],npc:[{label:"TYPES.Item.species",attr:"details.species.value",type:"text"},{label:"TYPES.Item.career",attr:"details.career.value",type:"text"},{label:"TYPES.Item.culture",attr:"details.culture.value",type:"text"}],character:[{label:"TYPES.Item.species",attr:"details.species.value",type:"text"},{label:"TYPES.Item.career",attr:"details.career.value",type:"text"},{label:"TYPES.Item.culture",attr:"details.culture.value",type:"text"}],creature:[{label:"creatureClass",attr:"creatureClass.value",type:"text"},{label:"sizeCategory",attr:"status.size.value",type:"select",options:b.sizeCategories}],armor:[{label:"protection",attr:"protection.value",type:"select",options:{0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7"}},{label:"encumbrance",attr:"encumbrance.value",type:"select",options:{0:"0",1:"1",2:"2",3:"3",4:"4"}}],plant:[{label:"PLANT.landscape",attr:"location.landscape",type:"text"},{label:"PLANT.region",attr:"location.region",type:"text"},{label:"PLANT.healing",attr:"planttype.healing",type:"checkbox"},{label:"PLANT.poison",attr:"planttype.poison",type:"checkbox"},{label:"PLANT.physical",attr:"planttype.physical",type:"checkbox"},{label:"PLANT.psychic",attr:"planttype.psychic",type:"checkbox"},{label:"PLANT.crop",attr:"planttype.crop",type:"checkbox"},{label:"PLANT.defensive",attr:"planttype.defensive",type:"checkbox"},{label:"PLANT.supernatural",attr:"planttype.supernatural",type:"checkbox"},{label:"PLANT.highNorth",attr:"availability.highNorth",type:"range"},{label:"PLANT.grasLands",attr:"availability.grasLands",type:"range"},{label:"PLANT.swamps",attr:"availability.swamps",type:"range"},{label:"PLANT.woods",attr:"availability.woods",type:"range"},{label:"PLANT.jungle",attr:"availability.jungle",type:"range"},{label:"PLANT.mountains",attr:"availability.mountains",type:"range"},{label:"PLANT.desert",attr:"availability.desert",type:"range"},{label:"PLANT.maraskan",attr:"availability.maraskan",type:"range"}],magicalsign:[],patron:[],demonmark:[],essence:[],imprint:[{label:"Category",attr:"category",type:"text"}]})})});var Ys=Ri;var Lt=class{constructor(e,t={}){let a=e.documentName||e.type;switch(e.documentName){case"Actor":case"Item":a=e.type;break}let s="";if(game.settings.get("dsa5","indexDescription"))switch(a){case"creature":case"npc":case"character":s=getProperty(e,"system.description.value");break;case"JournalEntry":s=getProperty(e,"system.content");break;default:s=getProperty(e,"description.value")}this.document={name:e.name,filterType:a,data:$("
    ").html(s).text(),id:e.id||e._id,visible:e.visible?e.visible:!0,compendium:e.compendium?e.compendium.metadata.packageName:t.packageName||"",pack:e.pack||(t.packageName?t.id:void 0),img:e.img,price:e.system?.price?.value}}get uuid(){if(this.document.compendium)return`Compendium.${this.document.pack}.${this.document.id}`;switch(this.itemType){case"character":case"creature":case"npc":return`Actor.${this.id}`;case"JournalEntry":return`JournalEntry.${this.id}`;default:return`Item.${this.id}`}}get name(){return this.document.name}get data(){return this.document.data}get id(){return this.document.id}get itemType(){return this.document.filterType}get hasPrice(){return b.equipmentCategories.has(this.document.filterType)}async getItem(){return await fromUuid(this.uuid)}hasPermission(){return this.document.visible}async render(){(await this.getItem()).sheet.render(!0)}get compendium(){return this.document.compendium}get img(){return this.itemType=="JournalEntry"?"systems/dsa5/icons/categories/DSA-Auge.webp":this.document.img}};u(Lt,"SearchDocument");var Zt=class extends Lt{constructor(e,t){super(e);let a=Ys[t]||[];for(let s of a)this[s.attr]=s.attr.split(".").reduce((i,r)=>i[r]===void 0?{}:i[r],e.system)}};u(Zt,"AdvancedSearchDocument");var Rt=class extends Application{constructor(e){super(e),this.advancedFiltering=!1,this.journalBuild=!1,this.journalWorldBuild=!1,this.equipmentBuild=!1,this.equipmentWorldBuild,this.zooBuild=!1,this.zooWorldBuild=!1,this.currentDetailFilter={equipment:[],character:[],spell:[],journal:[],zoo:[]},this.journalIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data"]}}),this.equipmentIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data","itemType"],tag:["itemType"]}}),this.zooIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data","itemType"],tag:["itemType"]}}),this.detailFilter={},this.pages={equipment:{},character:{},spell:{},journal:{},zoo:{}},this.filters={equipment:{categories:{armor:!1,ammunition:!1,equipment:!1,meleeweapon:!1,rangeweapon:!1,poison:!1,disease:!1,consumable:!1,plant:!1},filterBy:{search:""}},character:{categories:{career:!1,advantage:!1,combatskill:!1,culture:!1,disadvantage:!1,trait:!1,skill:!1,specialability:!1,species:!1,application:!1,demonmark:!1,patron:!1,essence:!1,imprint:!1},filterBy:{search:""}},spell:{categories:{blessing:!1,ceremony:!1,liturgy:!1,magictrick:!1,ritual:!1,spell:!1,spellextension:!1,magicalsign:!1},filterBy:{search:""}},journal:{categories:{},filterBy:{search:""}},zoo:{categories:{npc:!1,character:!1,creature:!1},filterBy:{search:""}}}}async getData(e){let t=await super.getData(e);return t.categories=this.translateFilters(),t.isGM=game.user.isGM,t.items=this.items,t.advancedMode=this.advancedFiltering?"on":"",t.worldIndexed=game.settings.get("dsa5","indexWorldItems")?"on":"",t.fullTextEnabled=game.settings.get("dsa5","indexDescription")?"on":"",t.filterDuplicateItems=game.settings.get("dsa5","filterDuplicateItems")?"on":"",t.browseEnabled=this.browseEnabled?"on":"",this.advancedFiltering&&(t.advancedFilter=await this.buildDetailFilter("tbd",this.subcategory)),t}translateFilters(){return{equipment:this.buildFilter(this.filters.equipment),character:this.buildFilter(this.filters.character),spell:this.buildFilter(this.filters.spell),zoo:this.buildFilter(this.filters.zoo,"Actor"),journal:this.buildFilter(this.filters.journal)}}purgeAdvancedFilters(){for(let e in this.filters)for(let t in this.filters[e].categories)this.filters[e].categories[t]=!1;$(this._element).find('.filter[type="checkbox"]').prop("checked",!1),this.buildDetailFilter("none","none").then(e=>{$(this._element).find(".advancedSearch .groupbox").html(e)})}buildFilter(e,t="Item"){let a=[];return Object.keys(e.categories).forEach(function(s){a.push({label:game.i18n.localize(`TYPES.${t}.${s}`),selected:e.categories[s],key:s})}),a=a.sort(function(s,i){return s.label.localeCompare(i.label)}),a}static get defaultOptions(){let e=super.defaultOptions;return e.id="DSA5ItemLibrary",e.classes.push("dsa5","itemlibrary"),e.height=800,e.width=800,e.resizable=!0,e.title=game.i18n.localize("ItemLibrary"),e.template="systems/dsa5/templates/system/itemlibrary.html",e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"equipment"}],e}async getRandomItems(e,t){let a=[],s=this.equipmentIndex;return a.push(...await s.search(e,{field:["itemType"]})),(await Promise.all(this.shuffle(a.filter(i=>i.hasPermission)).slice(0,t+5).map(i=>i.getItem()))).filter(i=>{let r=i.getFlag("dsa5","enchantments");return!r||!r.find(n=>n.talisman)}).slice(0,t)}shuffle(e){let t=e.length,a,s;for(;t!==0;)s=Math.floor(Math.random()*t),t-=1,a=e[t],e[t]=e[s],e[s]=a;return e}async findCompendiumItem(e,t,a=!0){this.equipmentBuild||await this.buildEquipmentIndex();let s={field:["name"],where:{itemType:t}},i=await this.equipmentIndex.search(e,s);return a&&(i=i.filter(r=>r.compendium!="")),await Promise.all(i.map(r=>r.getItem()))}async getCategoryItems(e,t=!1,a=!1){await this.buildEquipmentIndex();let s=this.equipmentIndex.search(e,{field:["itemType"]});return t?(await Promise.all(s.map(i=>i.getItem()))).map(i=>i.toObject()):a?await Promise.all(s.map(i=>i.getItem())):s}async executeAdvancedFilter(e,t,a,s,i,r=[]){let n=u(g=>{for(let y of a)if(y[2]?g[y[0]]!=y[1]:g[y[0]].indexOf(y[1])==-1)return!1;return!0},"selFnct"),o=u(g=>{for(let y of s)if(g[y[0]].toLowerCase().indexOf(y[1])==-1)return!1;return!0},"txtFnct"),c=u(g=>{for(let y of i)if(g[y[0]]!=y[1])return!1;return!0},"cbFnct"),m=u(g=>{for(let y of r)if(g[y[0]]y[2])return!1;return!0},"rangeFct"),p=t.where(g=>(e==""||g.name.toLowerCase().indexOf(e)!=-1)&&n(g)&&o(g)&&c(g)&&m(g));return p=p.filter(g=>g.hasPermission).sort((g,y)=>g.name.toLowerCase()>y.name.toLowerCase()?1:-1),p}async advancedFilterStuff(e,t){let a=$(this._element).find(".detailFilters"),s=a.attr("data-subc"),i=this.filters[e].filterBy.search.toLowerCase(),r=this.detailFilter[s],n=[],o=[],c=[];for(let d of a.find("select")){let p=$(d).val();p!=""&&n.push([$(d).attr("name"),p,d.dataset.notstrict!="true"])}for(let d of a.find('input[type="text"]:not(.manualFilter)')){let p=$(d).val();p!=""&&o.push([$(d).attr("name"),p.toLowerCase()])}for(let d of a.find('input[type="checkbox"]:checked:not(.manualFilter)')){let p=$(d).val();p!=""&&c.push([$(d).attr("name"),p.toLowerCase()])}let m=await this.executeAdvancedFilter(i,r,n,o,c);return this.setBGImage(m,e),m=this.filterDuplications(m),m}filterDuplications(e){return game.settings.get("dsa5","filterDuplicateItems")&&(e=[...new Map(e.map(t=>[`${t.name}_${t.type}`,t])).values()]),e}async filterStuff(e,t,a){let s=this.filters[e].filterBy.search,i={field:["name","data"]},r=[],n=!1;for(let o in this.filters[e].categories){if(this.filters[e].categories[o]){let c,m=null;s==""?c=t.search(o,{field:["itemType"],sort:"name",where:{itemType:o}}):c=t.search(s,{...i,sort:"name",where:{itemType:o}});let d=Number(a)||0;c=c.slice(d,Math.min(d+60,c.length)),c.length==60&&(m=`${d+60}`),this.pages[e].next=m,r.push(...c)}n=this.filters[e].categories[o]||n}return n||(r=t.search(s,{...i,limit:60,page:a||!0,sort:"name"}),this.pages[e].next=r.next),r=r.result?r.result:r,r=r.filter(o=>o.hasPermission),this.setBGImage(r,e),r}setBGImage(e,t){$(this._element).find(`.${t} .libcontainer`)[`${e.length>0?"remove":"add"}Class`]("libraryImg")}async getItemTemplate(e,t){if(this.browseEnabled&&["Item","Actor"].includes(t))return e.map(a=>`
    `).join("");{let a="systems/dsa5/templates/system/libraryItem.html";return await renderTemplate(a,{items:e})}}async renderBrowseItem(e){let t=await fromUuid(e),a=`systems/dsa5/templates/items/browse/${t.type}.html`,s=await renderTemplate(a,{document:t,isGM:game.user.isGM,...await t.sheet.getData()});return`
    ${s}
    `}intersectionObserved(e,t){for(let a of e)if(a.isIntersecting){let s=a.target.dataset.uuid;this.renderBrowseItem(s).then(i=>{a.target.outerHTML=i}),t.unobserve(a.target)}}async renderResult(e,t,{index:a,itemType:s},i){let r=e.find(".searchResult .item-list"),n=await this.getItemTemplate(t,s);i||r.empty(),n=$(n);let o=u((m,d,p,g=!1)=>{m.stopPropagation();let y=d.find(m.currentTarget.dataset.itemId);m.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:p,uuid:y.uuid,pay:g}))},"itemDragStart");n.each(function(){let m=$(this);m.attr("draggable",!0).on("dragstart",d=>o(d,a,s)),m.find(".priceDrag").attr("draggable",!0).on("dragstart",d=>o(d,a,s,!0))}),r.append(n);let c=r.find(".loader");if(c.length>0){let m=new IntersectionObserver(this.intersectionObserved.bind(this),{root:e.find(".window-content")[0]});for(let d of c)m.observe(d)}}async filterItems(e,t,a){let s=this.selectIndex(t),i=this.advancedFiltering&&t!="journal"?await this.advancedFilterStuff(t,a):await this.filterStuff(t,s.index,a);return await this.renderResult(e,i,s,a),i}selectIndex(e){let t="Item",a=this.equipmentIndex;switch(e){case"zoo":t="Actor",a=this.zooIndex;break;case"journal":t="JournalEntry",a=this.journalIndex;break}return{index:a,itemType:t}}async _render(e=!1,t={}){await super._render(e,t),this.buildEquipmentIndex()}async buildEquipmentIndex(){await this._createIndex("equipment","Item",game.items)}async _createIndex(e,t,a){if(this[`${e}Build`])return;SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:""}),pct:0});let s=$(this._element).find(`*[data-tab="${e}"]`);this.showLoading(s,e);let i=game.packs.filter(p=>p.documentName==t&&(game.user.isGM||!p.private)&&!p.metadata.label.startsWith("WZ-")),r=100/(i.length+1),n=r,o=["name","system.type","system.description.value","img"],c;t=="Actor"?c=u(p=>p.getIndex({actorFields:o}),"func"):t=="JournalEntry"?c=u(p=>p.getDocuments(),"func"):c=u(p=>p.getDocuments({type__in:game.system.documentTypes.Item}),"func");let m=this.indexWorldItems(a,e);SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:"world items"}),pct:Math.round(r)});let d=i.map(async p=>{let g=await c(p);n+=r,SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:`${p.metadata.label} (${p.metadata.id})`}),pct:Math.round(n)}),m.push(...g.map(y=>new Lt(y,p.metadata)))});return Promise.all(d).then(p=>{this[`${e}Index`].add(m),this[`${e}Build`]=!0,SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:""}),pct:100}),this.hideLoading(s,e)})}subcategoryFields(e){let t=["name","itemType"],a=Ys[e]||[];for(let s of a)t.push(s.attr);return t}indexWorldItems(e,t){let a=[];return game.settings.get("dsa5","indexWorldItems")&&(a.push(...e.filter(s=>s.visible).map(s=>new Lt(s))),this[`${t}WorldBuild`]=!0),a}async createDetailIndex(e,t){if(!this.detailFilter[t]){let a=this.subcategoryFields(t),s=$(this._element).find(`*[data-tab="${e}"]`);s.find(".searchResult ul").html(""),this.showLoading(s,e),this.detailFilter[t]=new FlexSearch({encode:"simple",tokenize:"full",cache:!0,doc:{id:"id",field:a}});let{index:i,itemType:r}=this.selectIndex(e),o=(r=="Item"?game.items:game.actors).filter(g=>g.visible&&g.type==t).map(g=>new Zt(g,t)),c=i.search(t,{field:["itemType"]}),m={};for(let g of c)!g.document.pack||(m[g.document.pack]||(m[g.document.pack]=[]),m[g.document.pack].push(g.document.id));let d=[];for(let g of Object.entries(m))d.push(game.packs.get(g[0]).getDocuments({_id__in:g[1],type:t}));let p=await Promise.all(d);for(let g of p)o.push(...g.map(y=>new Zt(y,t)));this.detailFilter[t].add(o),this.hideLoading(s,e)}}async buildDetailFilter(e,t){let a=Ys[t]||[];if(a){let s=this.createDetailIndex(e,t),i=game.packs.filter(n=>n.metadata.type=="Item").reduce((n,o)=>{if(!n[o.metadata.packageName]){let c=game.i18n.has(`${o.metadata.packageName}.name`)?game.i18n.localize(`${o.metadata.packageName}.name`):game.modules.get(o.metadata.packageName)?.title.replace(/The Dark Eye 5th Ed. - /i,"")||"World";n[o.metadata.packageName]=c}return n},{}),r=await renderTemplate("systems/dsa5/templates/system/detailFilter.html",{fields:a,subcategory:t,moduleOptions:i});return await s,r}else return`

    ${game.i18n.localize("Library.selectAdvanced")}

    `}checkWorldStuffIndex(){game.settings.get("dsa5","indexWorldItems")&&(!this.journalWorldBuild&&this.journalBuild&&this.journalIndex.add(this.indexWorldItems(game.journal,"journal")),!this.equipmentWorldBuild&&this.equipmentBuild&&this.equipmentIndex.add(this.indexWorldItems(game.items,"equipment")),!this.zooWorldBuild&&this.zooBuild&&this.zooIndex.add(this.indexWorldItems(game.actors,"zoo")))}activateListeners(e){super.activateListeners(e),oe(e),e.on("click",".searchableAbility a",s=>yt(s)),e.on("click",".toggleAdvancedMode",()=>{this.advancedFiltering=!this.advancedFiltering,this.advancedFiltering?($(this._element).find(".toggleAdvancedMode").addClass("on"),$(this._element).find(".advancedSearch").fadeIn(),this.purgeAdvancedFilters()):($(this._element).find(".toggleAdvancedMode").removeClass("on"),$(this._element).find(".advancedSearch").fadeOut())}),e.on("change",".detailFilters input, .detailFilters select",()=>{let s=$(this._element).find(".tab.active"),i=s.attr("data-tab");this.filterItems(s,i)}),e.on("click",".filter",async s=>{let i=$(s.currentTarget).closest(".tab"),r=i.attr("data-tab"),n=s.currentTarget.dataset.category,o=$(s.currentTarget).is(":checked");this.advancedFiltering&&o&&(this.purgeAdvancedFilters(),this.subcategory=n,$(s.currentTarget).prop("checked",o),$(this._element).find(".advancedSearch .groupbox").html(await this.buildDetailFilter(r,n))),this.filters[r].categories[n]=o,this.filterItems(i,r)}),e.on("click",".item-name",s=>{this.getItemFromHTML(s).render()}),e.on("mousedown",".item-name",s=>{s.button==2&&f.showArtwork(this.getItemFromHTML(s))}),e.on("keyup",".filterBy-search",s=>{let i=$(s.currentTarget).closest(".tab"),r=i.attr("data-tab");this.filters[r].filterBy.search=$(s.currentTarget).val(),this.filterItems(i,r)});let t=u(s=>{s.stopPropagation();let i=s.currentTarget.dataset.type,r=s.currentTarget.dataset.uuid;!r||!i||s.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:i,uuid:r}))},"itemDragStart");e.on("click",".show-item",async s=>{let i=s.currentTarget.dataset.uuid;(await fromUuid(i)).sheet.render(!0)}),e.find(".show-item").attr("draggable",!0).on("dragstart",s=>t(s)),e.find('*[data-tab="journal"]').click(s=>{this._createIndex("journal","JournalEntry",game.journal)}),e.find('*[data-tab="zoo"]').click(s=>{this._createIndex("zoo","Actor",game.actors)}),e.find(".showDetails").click(s=>{let i=s.currentTarget.dataset.btn;$(s.currentTarget).find("i").toggleClass("fa-caret-left fa-caret-right"),e.find(`.${i} .detailBox`).toggleClass("dsahidden")}),e.find(".toggleWorldIndex").click(s=>{game.settings.set("dsa5","indexWorldItems",!game.settings.get("dsa5","indexWorldItems")),this.checkWorldStuffIndex(),$(s.currentTarget).toggleClass("on")}),e.find(".fulltextsearch").click(s=>{game.settings.set("dsa5","indexDescription",!game.settings.get("dsa5","indexDescription")),$(s.currentTarget).toggleClass("on")}),e.find(".browseEnabled").click(s=>{this.browseEnabled=!this.browseEnabled,$(s.currentTarget).toggleClass("on")}),e.find(".filterDuplicateItems").click(s=>{game.settings.set("dsa5","filterDuplicateItems",!game.settings.get("dsa5","filterDuplicateItems")),$(s.currentTarget).toggleClass("on")});let a=this;$(this._element).find(".window-content").on("scroll.infinit",debounce(function(s){if(a.advancedFiltering)return;let i=$(s.target),r=i.scrollTop()+i.innerHeight()>=i[0].scrollHeight-100,n=e.find(".tabs .item.active").attr("data-tab");if(r&&a.pages[n].next){let o=e.find(".tab.active");a.filterItems.call(a,o,n,a.pages[n].next)}},100))}getItemFromHTML(e){let t=$(e.currentTarget).parents(".browser-item").attr("data-item-id");switch($(e.currentTarget).closest(".tab").attr("data-tab")){case"zoo":return this.zooIndex.find(t);case"journal":return this.journalIndex.find(t);default:return this.equipmentIndex.find(t)}}showLoading(e,t){this.setBGImage([1],t),$(`
    ${game.i18n.localize("Library.buildingIndex")}
    `).appendTo(e.find(".searchResult"))}hideLoading(e,t){this.setBGImage([],t),e.find(".loader").remove()}};u(Rt,"DSA5ItemLibrary");var _t=class extends Dialog{constructor(e,t,a,s=""){let i={title:e,content:t,buttons:{initialize:{label:game.i18n.localize("initialize"),callback:async()=>{this.lock||await this.initialize()}},cancel:{label:game.i18n.localize("cancel"),callback:async()=>{this.lock||await this.dontInitialize()}}}};super(i),this.module=a,this.lang=s,this.folders={},this.journals={},this.scenes={},this.actors={},this.lock=!1}async initNotes(e,t,a){let s=await this.getFolderForType("JournalEntry");for(let i of e.notes)try{let r=t.find(n=>n.flags.dsa5.initId==i.entryId);if(!a.has(r._id)){let n=getProperty(r,"flags.dsa5.parent"),o=s;this.folders[n]?o=this.folders[n]:n&&(o=await this.getFolderForType("JournalEntry",s.id,n,0,getProperty(r,"flags.dsa5.foldercolor")||"")),r.folder=o.id;let c=game.journal.find(m=>m.name==r.name&&m.folder?.id==o.id&&m.flags.dsa5.initId==i.entryId);if(c)await c.update(r),a.set(r._id,c.id);else{let m=await JournalEntry.create(r);a.set(r._id,m.id)}}i.entryId=a.get(r._id)}catch(r){console.warn(`Could not initialize Scene Notes for scene :${e.name}`+r)}}async initScenes(e){let t=await this.getFolderForType("Scene"),s=(await game.packs.get(e.scenes).getDocuments()).map(p=>p.toObject()),r=(await game.packs.get(e.journal).getDocuments()).map(p=>p.toObject()),n=[],o=[],c=new Map,m=!1;for(let p of s){let g=m,y=game.scenes.find(h=>h.name==p.name&&h.folder?.id==t.id);if(!m&&y&&([g,m]=await new Promise((h,w)=>{new Dialog({title:game.i18n.localize("Book.sceneReset"),content:game.i18n.format("Book.sceneResetDescription",{name:p.name}),default:"Yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{h([!0,!1])}},all:{icon:'',label:game.i18n.localize("LocalizedIDs.all"),callback:()=>{h([!0,!0])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{h([!1,!1])}}},close:()=>{h([!1,!1])}}).render(!0)})),y&&!g){this.scenes[y.name]=y;continue}p.folder=t.id,await this.initNotes(p,r,c),y?(p._id=y.id,o.push(p)):n.push(p)}let d=await Scene.create(n,{dsaInit:!0});for(let p of d){this.scenes[p.name]=p;let g=await p.createThumbnail();await p.update({thumb:g.thumb},{diff:!1})}for(let p of o)await game.scenes.get(p._id).update(p),this.scenes[p.name]=game.scenes.get(p._id);if(e.initialScene){let p=this.scenes[e.initialScene];await game.settings.set("core",NotesLayer.TOGGLE_SETTING,!0),await p.activate(),await p.update({navigation:!0})}}async initialize(){this.lock=!0;let e=$(this._element).find(".initialize");e.prepend('');let t={};try{game.settings.settings.has(`${this.module}.initialized`)&&await game.settings.set(this.module,"initialized",!0)}catch{}try{await fetch(`modules/${this.module}/adventure${this.lang}.json`).then(async a=>a.json()).then(async a=>{t=a})}catch{try{await fetch(`modules/${this.module}/adventure.json`).then(async a=>a.json()).then(async a=>{t=a})}catch{console.warn(`Could not find book data for ${this.module} import.`)}}await fetch(`modules/${this.module}/initialization${this.lang}.json`).then(async a=>a.json()).then(async a=>{let s=a.folders;if(s){let i=await this.getFolderForType("JournalEntry"),r=a.folders[0].name;i&&(this.folders[i.data.name]=i,a.folders.shift());let n=await Folder.create(s);Array.isArray(n)||(n=[n]);for(let c of n)this.folders[c.data.name]=c;let o=[];for(let c in this.folders){let m=this.folders[c].getFlag("dsa5","parent"),d=m==r?game.i18n.localize(`${this.module}.name`):m;d&&o.push({_id:this.folders[c].id,parent:this.folders[d].id})}await Folder.updateDocuments(o)}if(a.items&&a.items.length>0){let i=await this.getFolderForType("Item"),r=[],n=[];for(let o of a.items){o.folder=i.id;let c=game.items.find(m=>m.name==o.name&&m.folder?.id==i.id);c?(o._id=c.id,n.push(o)):r.push(o)}await A.create(r),await A.updateDocuments(n)}if(a.playlists){let i=await this.getFolderForType("Playlist"),r=[],n=[],c=(await game.packs.get(a.playlists).getDocuments()).map(m=>m.toObject());for(let m of c){m.folder=i.id;let d=game.playlists.find(p=>p.name==m.name&&p.folder?.id==i.id);d?(m._id=d._id,n.push(m)):r.push(m)}await Playlist.create(r,{keepId:!0}),await Playlist.updateDocuments(n)}if(a.scenes&&await this.initScenes(a),a.actors){let i=await this.getFolderForType("Actor"),n=(await game.packs.get(a.actors).getDocuments()).map(g=>g.toObject()),o=[],c=[],m=new Map,d=0;if(getProperty(t,"chapters")){for(let g of t.chapters)for(let y of g.content)if(y.actors){let h=!1;for(let w of y.actors)m.has(w)||(m.set(w,y.name),h=!0);h&&(await this.getFolderForType("Actor",i.id,y.name,d),d+=1)}}for(let g of n){let y=m.has(g.name)?await this.getFolderForType("Actor",i.id,m.get(g.name)):i;g.folder=y.id,g._id&&delete g._id;let h=game.actors.find(w=>w.name==g.name&&[i.id,y.id].includes(w.folder?.id));h?(g._id=h.id,await h.deleteEmbeddedDocuments("Item",h.items.map(w=>w.id)),c.push(g)):o.push(g)}let p=await Actor.create(o);await Actor.updateDocuments(c);for(let g of p)this.actors[g.name]=g}}),this.lock=!1,e.find("i").remove(),ui.notifications.notify(game.i18n.localize("initComplete")),await this.close()}async dontInitialize(){game.settings.settings.has(`${this.module}.initialized`)&&await game.settings.set(this.module,"initialized",!0),ui.notifications.notify(game.i18n.localize("initSkipped")),await this.close()}submit(e){try{e.callback&&e.callback(this.options.jQuery?this.element:this.element[0])}catch(t){throw ui.notifications.error(t),new Error(t)}}async getFolderForType(e,t=null,a=null,s=0,i=""){return a||(a=game.i18n.localize(`${this.module}.name`)),f.getFolderForType(e,t,a,s,i)}};u(_t,"DSA5Initializer");var Ft=class extends ChatMessage{get isRoll(){return this.isDSARoll||super.isRoll}get roll(){return this.isDSARoll?new Js(""):super.roll}get isDSARoll(){return this.flags.data?this.flags.data.isDSARoll:!1}};u(Ft,"ChatMessageDSA5Roll");var Js=class extends Roll{render(){return""}};u(Js,"EmptyRoll");var Ht=class extends Hotbar{async _render(e=!1,t={}){await super._render(e,t),this.addContextColor()}async collapse(){return this._collapsed?!0:($(this.element).addClass("collapsedHotbar"),super.collapse())}async expand(){return this._collapsed?($(this.element).removeClass("collapsedHotbar"),super.expand()):!0}async updateDSA5Hotbar(){if(!game.settings.get("dsa5","hotbarv3"))return;let e=canvas.tokens.controlled;if(this.token=void 0,this.showEffects=!1,e.length===1){let t=e[0].actor;t&&t.isOwner&&(this.token=e[0])}e.length>=1&&(this.showEffects=!0),await this.render(!0,{focus:!1})}addContextColor(){let e=new RegExp(` ${game.i18n.localize("CHAR.PARRY")}$`),t=new RegExp(` ${game.i18n.localize("CHAR.ATTACK")}$`),a=$(this._element).find("#macro-list");for(let s of this.macros)!s.macro||(e.test(s.macro.name)?a.find(`[data-macro-id="${s.macro.id}"]`).addClass("parry"):t.test(s.macro.name)&&a.find(`[data-macro-id="${s.macro.id}"]`).addClass("attack"))}get template(){return game.settings.get("dsa5","hotbarv3")?"systems/dsa5/templates/system/hud/hotbar.html":super.template}activateListeners(e){if(super.activateListeners(e),game.settings.get("dsa5","hotbarv3")){e.find(".quantity-click").mousedown(s=>P.quantityClick(s)),e.on("mousedown","li.primary",async s=>(s.stopPropagation(),await this.tokenHotbar.executeQuickButton(s),!1)),e.find(".categoryFilter").click(s=>{this.filterCategory(s,e)});let t=this,a=u(function(s){return t.filterSections(s,e),!1},"fn");e.find(".sections").hover(function(){$(document).off("keydown.sectionFilter",a).on("keydown.sectionFilter",a)},function(){$(document).off("keydown.sectionFilter",a),t.searching="",e.find(".macro,.primary").removeClass("dsahidden"),e.find(".longLayout").removeClass("longLayout")}),e.find(".primary").hover(s=>this._betterTooltip(s)),e.find(".itdarkness input").change(s=>this.tokenHotbar.changeDarkness(s))}}async _betterTooltip(e){let t=e.currentTarget,a=t.dataset,s,i,r;switch(a.category){case"skillgm":s=game.i18n.format("TT.skillgm",{name:a.name});break;case"effect":let n=this.token.actor.effects.get(a.id);n&&(r=game.i18n.has(n.description)?game.i18n.localize(n.description):n.description);break;case"onUse":switch(i=this.token.actor?.items.get(a.id),i.type){case"specialability":r=i.system.rule?.value;break;case"advantage":case"disadvantage":break;default:r=i.system.description?.value}break;case"unequipped":case"consumable":case"weapon":case"spell":i=this.token.actor?.items.get(a.id),r=$(await renderTemplate(`systems/dsa5/templates/items/browse/${i.type}.html`,{isGM:game.user.isGM,...await i.sheet.getData(),document:i,skipHeader:!0,hint:!0})).find(".groupbox").html();break;default:s=game.i18n.localize(a.tooltip)}r&&(s=`

    ${a.name}

    ${r}
    `),s&&game.tooltip.activate(t,{text:s})}filterCategory(e,t){let a=e.currentTarget.dataset.filter;a?(t.find(".skillItems").addClass("collapsed"),t.find(`.skillItems[data-category="${a}"]`).removeClass("collapsed"),t.find(".categoryFilter").removeClass("active"),t.find(`.categoryFilter[data-filter="${a}"]`).addClass("active"),this.activeFilters=[a]):(t.find(".skillItems").removeClass("collapsed"),t.find(".categoryFilter").removeClass("active"),this.activeFilters=[])}filterSections(e,t){switch(this.searching=this.searching||"",e.which){case 91:case 18:case 17:return;case 8:this.searching=this.searching.slice(0,-1);break;default:this.searching+=e.key}e.preventDefault(),e.stopPropagation();let a=this.searching.toLowerCase();de(a),a?t.find(".sections").addClass("longLayout"):t.find(".sections").removeClass("longLayout");let s=t.find(".macro,.primary");return s.removeClass("dsahidden"),s.filter(function(){return this.dataset?.name?.toLowerCase().trim().indexOf(a)==-1}).addClass("dsahidden"),!1}async getData(e){let t=await super.getData(e);return game.settings.get("dsa5","hotbarv3")&&await this._h3Data(t),t}get tokenHotbar(){return game.dsa5.apps.tokenHotbar}async _h3Data(e){let t={skills:{},attacks:[]},a=[],s=[],i=!1,r=[];if(this.token){let d=this.token.actor;if(r=(this.activeFilters||[]).filter(p=>p!="gm"),d){let p=d.items.filter(h=>h.type=="combatskill").map(h=>T._calculateCombatSkillValues(h.toObject(),d.system));s=await this.tokenHotbar._effectEntries(d);let g=this.tokenHotbar._brawlEntry(p);if(H.isRiding(d)){let h=this._ridingEntry(d);h&&(t.skills.skill=[h])}g&&t.attacks.push(g),t.functions=this.tokenHotbar?._functionEntries()||[];for(let h of d.items)switch(h.type){case"skill":t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._skillEntry(h,"skill"));break;case"spell":case"liturgy":t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._skillEntry(h,"spell"));break;case"trait":Se.traitTypes.has(h.system.traitType.value)&&t.attacks.push(this.tokenHotbar._traitEntry(h));break;case"consumable":t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._actionEntry(h,"consumable",{abbrev:h.system.quantity.value}));break;case"meleeweapon":case"rangeweapon":let w=this.tokenHotbar._combatEntry(h,p,d);h.system.worn.value||(w.cssClass="unequipped"),t.attacks.push(w);break;default:h.getFlag("dsa5","onUseEffect")&&(t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._actionEntry(h,"onUse",{subfunction:"onUse"})));break}}}else if(game.user.isGM&&!game.settings.get("dsa5","disableTokenhotbarMaster")){t.skills.gm=this.tokenHotbar?._gmEntries()||[];let d=this.tokenHotbar?.skills||await this.tokenHotbar?.prepareSkills()||[];t.skills.skill=d,i=!0}let n=45,o=2,c={gm:"systems/dsa5/icons/categories/DSA-Auge.webp"},m={gm:"gmMenu"};for(let d of Object.keys(t.skills)){let p=`TYPES.Item.${d}`;a.push({key:d,tooltip:game.i18n.has(p)?game.i18n.localize(p):game.i18n.localize(m[d]),img:A.defaultImages[d]||c[d]})}if(t.attacks.length>0&&(t.attacks.sort((d,p)=>(p.cssClass||"").localeCompare(d.cssClass||"")||d.name.localeCompare(p.name)),a.unshift({key:"attacks",tooltip:game.i18n.localize("Combat"),img:"systems/dsa5/icons/categories/Meleeweapon.webp"})),this.showEffects){if(canvas.tokens.controlled.length>1){let g=await this.tokenHotbar._effectEntries(canvas.tokens.controlled[0].actor,{subfunction:"sharedEffect"});for(let y of canvas.tokens.controlled){let h=(await y.actor.actorEffects()).map(w=>w.name);g=g.filter(w=>h.includes(w.name))}s=g}let d=game.i18n.localize("CONDITION.add"),p={name:"CONDITION.add",id:"",icon:"icons/svg/aura.svg",cssClass:"effect",abbrev:d[0],subfunction:"addEffect",indicator:"+"};s.unshift(p)}r.length>0&&(r=Object.keys(t.skills).concat(["macro","attacks"]).filter(d=>!r.includes(d))),mergeObject(e,{token:{groups:t,effects:s},darkness:canvas?.scene?.darkness||0,hotBarcssClass:"hotbarV3",barWidth:`${522}px`,baseBarHeight:`${n}px`,barHeight:`${(n+7)*o+30}px`,filterCategories:a,selectedCategories:this.activeFilters||[],showEffects:this.showEffects,activeFilters:r,gmMode:i,macros:this._getAllMacros()})}_getAllMacros(){let e=Array.from({length:50},()=>"");for(let[t,a]of Object.entries(game.user.hotbar))e[parseInt(t)-1]=a;return e.map((t,a)=>{let s=t?game.macros.get(t):null;return{slot:a+1,key:a+1,icon:s?.img||null,cssClass:s?"active":"inactive",tooltip:s?s.name:null,macro:s}})}};u(Ht,"DSA5Hotbar");var je=class{constructor(){this.tokens={},this.actors={}}static get wantedKeys(){let e=["vision","targetMovement","shooterMovement","quickChange","mountOptions","narrowSpace","advantageousPosition","doubleAttack","reduceCostSpell","forceSpell","increaseCastingTime","decreaseCastingTime","removeGesture","removeFormula"];return J.isEnabled||e.push("distance"),e}getPath(e,t,a){let s=a||"",i=t._id||t.type;return e.token?`tokens.${e.token||e.actor}.${i}${s}`:`actors.${e.actor}.${i}${s}`}remember(e,t,a,s){let i=this.formDataSerialize(s);Object.entries(i).length>0&&setProperty(this,this.getPath(e,t,a),i)}recall(e,t,a){return getProperty(this,this.getPath(e,t,a))}formDataSerialize(e){let t=e.find("form"),a={};return t.find("select").each(function(){let s=$(this).attr("name");je.wantedKeys.includes(s)&&(a[s]=$(this).val())}),t.find('input[type="checkbox"]').each(function(){let s=$(this).attr("name");je.wantedKeys.includes(s)&&(a[s]=this.checked)}),t.find(".specAbs.active").each(function(){a.specAbs||(a.specAbs=[]),a.specAbs.push({id:$(this).attr("data-id"),step:$(this).attr("data-step")})}),e.find('[name="situationalModifiers"] option').each(function(){a.situationalModifiers||(a.situationalModifiers=[]),a.situationalModifiers.push({name:$(this).text().trim(),selected:this.selected})}),a}};u(je,"RollMemory");var Qs=class extends ActiveEffect{apply(e,t){if(Qs.itemChangeRegex.test(t.key)){let a=this._getModifiedItems(e,t);for(let s of a.items){let i=foundry.utils.flattenObject(s.overrides||{});i[a.key]=Number.isNumeric(s.value)?Number(a.value):a.value;let r={...t,key:a.key,value:a.value};super.apply(s,r),s.overrides=foundry.utils.expandObject(i)}}else return super.apply(e,t)}static async _onCreateDocuments(e,t){for(let a of e)a.parent.documentName=="Actor"&&await T.postUpdateConditions(a.parent);return super._onCreateDocuments(e,t)}static async _onUpdateDocuments(e,t){for(let a of e)a.parent.documentName=="Actor"&&await T.postUpdateConditions(a.parent);return super._onUpdateDocuments(e,t)}static async _onDeleteDocuments(e,t){for(let a of e)a.parent.documentName=="Actor"&&await T.postUpdateConditions(a.parent);return super._onDeleteDocuments(e,t)}isVisibleEffect(){return!this.disabled&&!this.notApplicable&&(game.user.isGM||!this.getFlag("dsa5","hidePlayers"))&&!this.getFlag("dsa5","hideOnToken")&&(this.origin==this.target?.uuid||!this.origin)}_displayScrollingStatus(e){let t=["dead"];!(game.user.isGM||this.target?.testUserPermission(game.user,"OBSERVER")||!game.settings.get("dsa5","hideEffects")?this.isVisibleEffect():t.some(i=>this.statuses.has(i)))||super._displayScrollingStatus(e)}_getModifiedItems(e,t){let a=t.key.split("."),s=a.shift();s=s.replace("@","").toLowerCase();let i=a.shift(),r=a.join("."),n=t.value;return{items:e?.items?.filter(c=>c.type==s&&(c.name==i||c.id==i))||[],key:r,value:n}}async _preUpdate(e,t,a){super._preUpdate(e,t,a),this._clearModifiedItems()}_clearModifiedItems(){if(this.parent instanceof CONFIG.Actor.documentClass){for(let e of this.changes)if(Qs.itemChangeRegex.test(e.key)){let t=this._getModifiedItems(this.parent,e);for(let a of t.items){let s=foundry.utils.flattenObject(a.overrides||{}),i=t.key;delete s[i];let r=getProperty(a._source,i);setProperty(a,i,r),a.overrides=foundry.utils.expandObject(s),a.sheet?.rendered&&a.sheet.render(!0)}}}}async _preDelete(e,t){super._preDelete(e,t),this._clearModifiedItems()}},gt=Qs;u(gt,"DSAActiveEffect"),L(gt,"itemChangeRegex",/^@/);var Sr=u((l,e)=>{let t=getProperty(l,e.key)||null;t==null&&/^system\.(vulnerabilities|resistances)/.test(e.key)&&(t=[],setProperty(l,e.key,t));let a=getType(t),s=null;switch(a){case"Array":let i=[],r=e.effect.name;for(let n of`${e.value}`.split(/[;,]+/)){let o=n.split(" "),c=o.pop(),m=o.join(" ");i.push({source:r,value:c,target:m})}s=t.concat(i)}return s!==null&&setProperty(l,e.key,s),s},"applyCustomEffect");Hooks.on("applyActiveEffect",(l,e)=>Sr(l,e));Hooks.once("init",()=>{console.log("Initializing DSA5 system"),CONFIG.statusEffects=b.statusEffects,game.dsa5={apps:{DSA5_Utility:f,DSA5Initializer:_t,DSA5ChatListeners:ae,DSA5Payment:B,SpecialabilityRulesDSA5:R,AdvantageRulesDSA5:O,Migrakel:Ie,DSA5Dialog:ee,DSA5StatusEffects:E,DPS:J,DSATables:U,DSA5SoundEffect:K,RequestRoll:q,DiceDSA5:_DiceDSA5,DSATour:Ne,OpposeDSA:j,EquipmentDamage:W,APTracker:_,DidYouKnow:Fe,MeasuredTemplateDSA:dt,Riding:H,RuleChaos:P,Trade:pe,DSAActiveEffectConfig:Q},entities:{Actordsa5:T,Itemdsa5:A},sheets:{ActorSheetdsa5:$e,ActorSheetdsa5Character:be,ActorSheetdsa5Creature:Oe,ActorSheetdsa5NPC:xe,MerchantSheetMixin:it,MerchantSheetDSA5:Ae,ItemSheetdsa5:Y},wizards:{CareerWizard:Xe,CultureWizard:Qe,SpeciesWizard:Ze},view:{tinyNotification:de,tabSlider:oe,clickableAbility:yt},dialogs:{DialogReactDSA5:ce,ReactToSkillDialog:ct,ActAttackDialog:Re,ReactToAttackDialog:Me},macro:Nt,config:b,memory:new je,itemLibrary:new Rt},CONFIG.Actor.documentClass=T,CONFIG.Item.documentClass=A,CONFIG.ChatMessage.template="systems/dsa5/templates/chat/chat-message.html",CONFIG.ChatMessage.documentClass=Ft,CONFIG.ui.combat=Ce,CONFIG.ui.hotbar=Ht,CONFIG.Combat.documentClass=He,CONFIG.Combatant.documentClass=Jt,CONFIG.ActiveEffect.documentClass=gt,CONFIG.ActiveEffect.legacyTransferral=!1});ki(); +
    `;mergeObject(Ri,{ammunition:[{label:"ammunitiongroup",attr:"ammunitiongroup.value",type:"select",options:b.ammunitiongroups}],equipment:[{label:"equipmentType",attr:"equipmentType.value",type:"select",options:b.equipmentTypes}],rangeweapon:[{label:"TYPES.Item.combatskill",attr:"combatskill.value",type:"select",options:t},{label:"ammunitiongroup",attr:"ammunitiongroup.value",type:"select",options:b.ammunitiongroups}],meleeweapon:[{label:"TYPES.Item.combatskill",attr:"combatskill.value",type:"select",options:a},{label:"guidevalue",attr:"guidevalue.value",type:"select",options:b.combatskillsGuidevalues},{label:"reach",attr:"reach.value",type:"select",options:b.meleeRanges}],poison:[{label:"resistanceModifier",attr:"resistance.value",type:"select",options:b.magicResistanceModifiers}],disease:[{label:"resistanceModifier",attr:"resistance.value",type:"select",options:b.magicResistanceModifiers}],consumable:[{label:"equipmentType",attr:"equipmentType.value",type:"select",options:b.equipmentTypes}],application:[{label:"TYPES.Item.skill",attr:"skill",type:"select",options:e}],trait:[{label:"traitType",attr:"traitType.value",type:"select",options:b.traitCategories}],career:[{label:"mageLevel",attr:"mageLevel.value",type:"select",options:b.mageLevels}],specialability:[{type:"prerendered",attr:"category.value",content:n},{label:"TYPES.Item.combatskill",attr:"list.value",type:"select",options:s,notStrict:!0},{label:"distribution",attr:"distribution",type:"text"}],liturgy:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"}],spell:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"},{label:"feature",attr:"feature",type:"text"}],ritual:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"},{label:"feature",attr:"feature",type:"text"}],ceremony:[{label:"resistanceModifier",attr:"resistanceModifier.value",type:"select",options:b.magicResistanceModifiers},{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"distribution",attr:"distribution.value",type:"text"}],spellextension:[{label:"Category",attr:"category",type:"select",options:{spell:"spell",liturgy:"liturgy",ritual:"ritual",ceremony:"ceremony"}}],magictrick:[{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"feature",attr:"feature.value",type:"text"},{label:"distribution",attr:"distribution",type:"text"}],blessing:[{label:"targetCategory",attr:"targetCategory.value",type:"text"},{label:"feature",attr:"feature.value",type:"text"}],npc:[{label:"TYPES.Item.species",attr:"details.species.value",type:"text"},{label:"TYPES.Item.career",attr:"details.career.value",type:"text"},{label:"TYPES.Item.culture",attr:"details.culture.value",type:"text"}],character:[{label:"TYPES.Item.species",attr:"details.species.value",type:"text"},{label:"TYPES.Item.career",attr:"details.career.value",type:"text"},{label:"TYPES.Item.culture",attr:"details.culture.value",type:"text"}],creature:[{label:"creatureClass",attr:"creatureClass.value",type:"text"},{label:"sizeCategory",attr:"status.size.value",type:"select",options:b.sizeCategories}],armor:[{label:"protection",attr:"protection.value",type:"select",options:{0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7"}},{label:"encumbrance",attr:"encumbrance.value",type:"select",options:{0:"0",1:"1",2:"2",3:"3",4:"4"}}],plant:[{label:"PLANT.landscape",attr:"location.landscape",type:"text"},{label:"PLANT.region",attr:"location.region",type:"text"},{label:"PLANT.healing",attr:"planttype.healing",type:"checkbox"},{label:"PLANT.poison",attr:"planttype.poison",type:"checkbox"},{label:"PLANT.physical",attr:"planttype.physical",type:"checkbox"},{label:"PLANT.psychic",attr:"planttype.psychic",type:"checkbox"},{label:"PLANT.crop",attr:"planttype.crop",type:"checkbox"},{label:"PLANT.defensive",attr:"planttype.defensive",type:"checkbox"},{label:"PLANT.supernatural",attr:"planttype.supernatural",type:"checkbox"},{label:"PLANT.highNorth",attr:"availability.highNorth",type:"range"},{label:"PLANT.grasLands",attr:"availability.grasLands",type:"range"},{label:"PLANT.swamps",attr:"availability.swamps",type:"range"},{label:"PLANT.woods",attr:"availability.woods",type:"range"},{label:"PLANT.jungle",attr:"availability.jungle",type:"range"},{label:"PLANT.mountains",attr:"availability.mountains",type:"range"},{label:"PLANT.desert",attr:"availability.desert",type:"range"},{label:"PLANT.maraskan",attr:"availability.maraskan",type:"range"}],magicalsign:[],patron:[],demonmark:[],essence:[],imprint:[{label:"Category",attr:"category",type:"text"}]})})});var Ys=Ri;var Lt=class{constructor(e,t={}){let a=e.documentName||e.type;switch(e.documentName){case"Actor":case"Item":a=e.type;break}let s="";if(game.settings.get("dsa5","indexDescription"))switch(a){case"creature":case"npc":case"character":s=getProperty(e,"system.description.value");break;case"JournalEntry":s=getProperty(e,"system.content");break;default:s=getProperty(e,"description.value")}this.document={name:e.name,filterType:a,data:$("
    ").html(s).text(),id:e.id||e._id,visible:e.visible?e.visible:!0,compendium:e.compendium?e.compendium.metadata.packageName:t.packageName||"",pack:e.pack||(t.packageName?t.id:void 0),img:e.img,price:e.system?.price?.value}}get uuid(){if(this.document.compendium)return`Compendium.${this.document.pack}.${this.document.id}`;switch(this.itemType){case"character":case"creature":case"npc":return`Actor.${this.id}`;case"JournalEntry":return`JournalEntry.${this.id}`;default:return`Item.${this.id}`}}get name(){return this.document.name}get data(){return this.document.data}get id(){return this.document.id}get itemType(){return this.document.filterType}get hasPrice(){return b.equipmentCategories.has(this.document.filterType)}async getItem(){return await fromUuid(this.uuid)}hasPermission(){return this.document.visible}async render(){(await this.getItem()).sheet.render(!0)}get compendium(){return this.document.compendium}get img(){return this.itemType=="JournalEntry"?"systems/dsa5/icons/categories/DSA-Auge.webp":this.document.img}};u(Lt,"SearchDocument");var Zt=class extends Lt{constructor(e,t){super(e);let a=Ys[t]||[];for(let s of a)this[s.attr]=s.attr.split(".").reduce((i,n)=>i[n]===void 0?{}:i[n],e.system)}};u(Zt,"AdvancedSearchDocument");var Rt=class extends Application{constructor(e){super(e),this.advancedFiltering=!1,this.journalBuild=!1,this.journalWorldBuild=!1,this.equipmentBuild=!1,this.equipmentWorldBuild,this.zooBuild=!1,this.zooWorldBuild=!1,this.currentDetailFilter={equipment:[],character:[],spell:[],journal:[],zoo:[]},this.journalIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data"]}}),this.equipmentIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data","itemType"],tag:["itemType"]}}),this.zooIndex=new FlexSearch({encode:"simple",tokenize:"reverse",cache:!0,doc:{id:"id",field:["name","data","itemType"],tag:["itemType"]}}),this.detailFilter={},this.pages={equipment:{},character:{},spell:{},journal:{},zoo:{}},this.filters={equipment:{categories:{armor:!1,ammunition:!1,equipment:!1,meleeweapon:!1,rangeweapon:!1,poison:!1,disease:!1,consumable:!1,plant:!1},filterBy:{search:""}},character:{categories:{career:!1,advantage:!1,combatskill:!1,culture:!1,disadvantage:!1,trait:!1,skill:!1,specialability:!1,species:!1,application:!1,demonmark:!1,patron:!1,essence:!1,imprint:!1},filterBy:{search:""}},spell:{categories:{blessing:!1,ceremony:!1,liturgy:!1,magictrick:!1,ritual:!1,spell:!1,spellextension:!1,magicalsign:!1},filterBy:{search:""}},journal:{categories:{},filterBy:{search:""}},zoo:{categories:{npc:!1,character:!1,creature:!1},filterBy:{search:""}}}}async getData(e){let t=await super.getData(e);return t.categories=this.translateFilters(),t.isGM=game.user.isGM,t.items=this.items,t.advancedMode=this.advancedFiltering?"on":"",t.worldIndexed=game.settings.get("dsa5","indexWorldItems")?"on":"",t.fullTextEnabled=game.settings.get("dsa5","indexDescription")?"on":"",t.filterDuplicateItems=game.settings.get("dsa5","filterDuplicateItems")?"on":"",t.browseEnabled=this.browseEnabled?"on":"",this.advancedFiltering&&(t.advancedFilter=await this.buildDetailFilter("tbd",this.subcategory)),t}translateFilters(){return{equipment:this.buildFilter(this.filters.equipment),character:this.buildFilter(this.filters.character),spell:this.buildFilter(this.filters.spell),zoo:this.buildFilter(this.filters.zoo,"Actor"),journal:this.buildFilter(this.filters.journal)}}purgeAdvancedFilters(){for(let e in this.filters)for(let t in this.filters[e].categories)this.filters[e].categories[t]=!1;$(this._element).find('.filter[type="checkbox"]').prop("checked",!1),this.buildDetailFilter("none","none").then(e=>{$(this._element).find(".advancedSearch .groupbox").html(e)})}buildFilter(e,t="Item"){let a=[];return Object.keys(e.categories).forEach(function(s){a.push({label:game.i18n.localize(`TYPES.${t}.${s}`),selected:e.categories[s],key:s})}),a=a.sort(function(s,i){return s.label.localeCompare(i.label)}),a}static get defaultOptions(){let e=super.defaultOptions;return e.id="DSA5ItemLibrary",e.classes.push("dsa5","itemlibrary"),e.height=800,e.width=800,e.resizable=!0,e.title=game.i18n.localize("ItemLibrary"),e.template="systems/dsa5/templates/system/itemlibrary.html",e.tabs=[{navSelector:".tabs",contentSelector:".content",initial:"equipment"}],e}async getRandomItems(e,t){let a=[],s=this.equipmentIndex;return a.push(...await s.search(e,{field:["itemType"]})),(await Promise.all(this.shuffle(a.filter(i=>i.hasPermission)).slice(0,t+5).map(i=>i.getItem()))).filter(i=>{let n=i.getFlag("dsa5","enchantments");return!n||!n.find(r=>r.talisman)}).slice(0,t)}shuffle(e){let t=e.length,a,s;for(;t!==0;)s=Math.floor(Math.random()*t),t-=1,a=e[t],e[t]=e[s],e[s]=a;return e}async findCompendiumItem(e,t,a=!0){this.equipmentBuild||await this.buildEquipmentIndex();let s={field:["name"],where:{itemType:t}},i=await this.equipmentIndex.search(e,s);return a&&(i=i.filter(n=>n.compendium!="")),await Promise.all(i.map(n=>n.getItem()))}async getCategoryItems(e,t=!1,a=!1){await this.buildEquipmentIndex();let s=this.equipmentIndex.search(e,{field:["itemType"]});return t?(await Promise.all(s.map(i=>i.getItem()))).map(i=>i.toObject()):a?await Promise.all(s.map(i=>i.getItem())):s}async executeAdvancedFilter(e,t,a,s,i,n=[]){let r=u(g=>{for(let y of a)if(y[2]?g[y[0]]!=y[1]:g[y[0]].indexOf(y[1])==-1)return!1;return!0},"selFnct"),o=u(g=>{for(let y of s)if(g[y[0]].toLowerCase().indexOf(y[1])==-1)return!1;return!0},"txtFnct"),c=u(g=>{for(let y of i)if(g[y[0]]!=y[1])return!1;return!0},"cbFnct"),m=u(g=>{for(let y of n)if(g[y[0]]y[2])return!1;return!0},"rangeFct"),p=t.where(g=>(e==""||g.name.toLowerCase().indexOf(e)!=-1)&&r(g)&&o(g)&&c(g)&&m(g));return p=p.filter(g=>g.hasPermission).sort((g,y)=>g.name.toLowerCase()>y.name.toLowerCase()?1:-1),p}async advancedFilterStuff(e,t){let a=$(this._element).find(".detailFilters"),s=a.attr("data-subc"),i=this.filters[e].filterBy.search.toLowerCase(),n=this.detailFilter[s],r=[],o=[],c=[];for(let d of a.find("select")){let p=$(d).val();p!=""&&r.push([$(d).attr("name"),p,d.dataset.notstrict!="true"])}for(let d of a.find('input[type="text"]:not(.manualFilter)')){let p=$(d).val();p!=""&&o.push([$(d).attr("name"),p.toLowerCase()])}for(let d of a.find('input[type="checkbox"]:checked:not(.manualFilter)')){let p=$(d).val();p!=""&&c.push([$(d).attr("name"),p.toLowerCase()])}let m=await this.executeAdvancedFilter(i,n,r,o,c);return this.setBGImage(m,e),m=this.filterDuplications(m),m}filterDuplications(e){return game.settings.get("dsa5","filterDuplicateItems")&&(e=[...new Map(e.map(t=>[`${t.name}_${t.type}`,t])).values()]),e}async filterStuff(e,t,a){let s=this.filters[e].filterBy.search,i={field:["name","data"]},n=[],r=!1;for(let o in this.filters[e].categories){if(this.filters[e].categories[o]){let c,m=null;s==""?c=t.search(o,{field:["itemType"],sort:"name",where:{itemType:o}}):c=t.search(s,{...i,sort:"name",where:{itemType:o}});let d=Number(a)||0;c=c.slice(d,Math.min(d+60,c.length)),c.length==60&&(m=`${d+60}`),this.pages[e].next=m,n.push(...c)}r=this.filters[e].categories[o]||r}return r||(n=t.search(s,{...i,limit:60,page:a||!0,sort:"name"}),this.pages[e].next=n.next),n=n.result?n.result:n,n=n.filter(o=>o.hasPermission),this.setBGImage(n,e),n}setBGImage(e,t){$(this._element).find(`.${t} .libcontainer`)[`${e.length>0?"remove":"add"}Class`]("libraryImg")}async getItemTemplate(e,t){if(this.browseEnabled&&["Item","Actor"].includes(t))return e.map(a=>`
    `).join("");{let a="systems/dsa5/templates/system/libraryItem.html";return await renderTemplate(a,{items:e})}}async renderBrowseItem(e){let t=await fromUuid(e),a=`systems/dsa5/templates/items/browse/${t.type}.html`,s=await renderTemplate(a,{document:t,isGM:game.user.isGM,...await t.sheet.getData()});return`
    ${s}
    `}intersectionObserved(e,t){for(let a of e)if(a.isIntersecting){let s=a.target.dataset.uuid;this.renderBrowseItem(s).then(i=>{a.target.outerHTML=i}),t.unobserve(a.target)}}async renderResult(e,t,{index:a,itemType:s},i){let n=e.find(".searchResult .item-list"),r=await this.getItemTemplate(t,s);i||n.empty(),r=$(r);let o=u((m,d,p,g=!1)=>{m.stopPropagation();let y=d.find(m.currentTarget.dataset.itemId);m.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:p,uuid:y.uuid,pay:g}))},"itemDragStart");r.each(function(){let m=$(this);m.attr("draggable",!0).on("dragstart",d=>o(d,a,s)),m.find(".priceDrag").attr("draggable",!0).on("dragstart",d=>o(d,a,s,!0))}),n.append(r);let c=n.find(".loader");if(c.length>0){let m=new IntersectionObserver(this.intersectionObserved.bind(this),{root:e.find(".window-content")[0]});for(let d of c)m.observe(d)}}async filterItems(e,t,a){let s=this.selectIndex(t),i=this.advancedFiltering&&t!="journal"?await this.advancedFilterStuff(t,a):await this.filterStuff(t,s.index,a);return await this.renderResult(e,i,s,a),i}selectIndex(e){let t="Item",a=this.equipmentIndex;switch(e){case"zoo":t="Actor",a=this.zooIndex;break;case"journal":t="JournalEntry",a=this.journalIndex;break}return{index:a,itemType:t}}async _render(e=!1,t={}){await super._render(e,t),this.buildEquipmentIndex()}async buildEquipmentIndex(){await this._createIndex("equipment","Item",game.items)}async _createIndex(e,t,a){if(this[`${e}Build`])return;SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:""}),pct:0});let s=$(this._element).find(`*[data-tab="${e}"]`);this.showLoading(s,e);let i=game.packs.filter(p=>p.documentName==t&&(game.user.isGM||!p.private)&&!p.metadata.label.startsWith("WZ-")),n=100/(i.length+1),r=n,o=["name","system.type","system.description.value","img"],c;t=="Actor"?c=u(p=>p.getIndex({actorFields:o}),"func"):t=="JournalEntry"?c=u(p=>p.getDocuments(),"func"):c=u(p=>p.getDocuments({type__in:game.system.documentTypes.Item}),"func");let m=this.indexWorldItems(a,e);SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:"world items"}),pct:Math.round(n)});let d=i.map(async p=>{let g=await c(p);r+=n,SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:`${p.metadata.label} (${p.metadata.id})`}),pct:Math.round(r)}),m.push(...g.map(y=>new Lt(y,p.metadata)))});return Promise.all(d).then(p=>{this[`${e}Index`].add(m),this[`${e}Build`]=!0,SceneNavigation.displayProgressBar({label:game.i18n.format("Library.loading",{item:""}),pct:100}),this.hideLoading(s,e)})}subcategoryFields(e){let t=["name","itemType"],a=Ys[e]||[];for(let s of a)t.push(s.attr);return t}indexWorldItems(e,t){let a=[];return game.settings.get("dsa5","indexWorldItems")&&(a.push(...e.filter(s=>s.visible).map(s=>new Lt(s))),this[`${t}WorldBuild`]=!0),a}async createDetailIndex(e,t){if(!this.detailFilter[t]){let a=this.subcategoryFields(t),s=$(this._element).find(`*[data-tab="${e}"]`);s.find(".searchResult ul").html(""),this.showLoading(s,e),this.detailFilter[t]=new FlexSearch({encode:"simple",tokenize:"full",cache:!0,doc:{id:"id",field:a}});let{index:i,itemType:n}=this.selectIndex(e),o=(n=="Item"?game.items:game.actors).filter(g=>g.visible&&g.type==t).map(g=>new Zt(g,t)),c=i.search(t,{field:["itemType"]}),m={};for(let g of c)!g.document.pack||(m[g.document.pack]||(m[g.document.pack]=[]),m[g.document.pack].push(g.document.id));let d=[];for(let g of Object.entries(m))d.push(game.packs.get(g[0]).getDocuments({_id__in:g[1],type:t}));let p=await Promise.all(d);for(let g of p)o.push(...g.map(y=>new Zt(y,t)));this.detailFilter[t].add(o),this.hideLoading(s,e)}}async buildDetailFilter(e,t){let a=Ys[t]||[];if(a){let s=this.createDetailIndex(e,t),i=game.packs.filter(r=>r.metadata.type=="Item").reduce((r,o)=>{if(!r[o.metadata.packageName]){let c=game.i18n.has(`${o.metadata.packageName}.name`)?game.i18n.localize(`${o.metadata.packageName}.name`):game.modules.get(o.metadata.packageName)?.title.replace(/The Dark Eye 5th Ed. - /i,"")||"World";r[o.metadata.packageName]=c}return r},{}),n=await renderTemplate("systems/dsa5/templates/system/detailFilter.html",{fields:a,subcategory:t,moduleOptions:i});return await s,n}else return`

    ${game.i18n.localize("Library.selectAdvanced")}

    `}checkWorldStuffIndex(){game.settings.get("dsa5","indexWorldItems")&&(!this.journalWorldBuild&&this.journalBuild&&this.journalIndex.add(this.indexWorldItems(game.journal,"journal")),!this.equipmentWorldBuild&&this.equipmentBuild&&this.equipmentIndex.add(this.indexWorldItems(game.items,"equipment")),!this.zooWorldBuild&&this.zooBuild&&this.zooIndex.add(this.indexWorldItems(game.actors,"zoo")))}activateListeners(e){super.activateListeners(e),oe(e),e.on("click",".searchableAbility a",s=>yt(s)),e.on("click",".toggleAdvancedMode",()=>{this.advancedFiltering=!this.advancedFiltering,this.advancedFiltering?($(this._element).find(".toggleAdvancedMode").addClass("on"),$(this._element).find(".advancedSearch").fadeIn(),this.purgeAdvancedFilters()):($(this._element).find(".toggleAdvancedMode").removeClass("on"),$(this._element).find(".advancedSearch").fadeOut())}),e.on("change",".detailFilters input, .detailFilters select",()=>{let s=$(this._element).find(".tab.active"),i=s.attr("data-tab");this.filterItems(s,i)}),e.on("click",".filter",async s=>{let i=$(s.currentTarget).closest(".tab"),n=i.attr("data-tab"),r=s.currentTarget.dataset.category,o=$(s.currentTarget).is(":checked");this.advancedFiltering&&o&&(this.purgeAdvancedFilters(),this.subcategory=r,$(s.currentTarget).prop("checked",o),$(this._element).find(".advancedSearch .groupbox").html(await this.buildDetailFilter(n,r))),this.filters[n].categories[r]=o,this.filterItems(i,n)}),e.on("click",".item-name",s=>{this.getItemFromHTML(s).render()}),e.on("mousedown",".item-name",s=>{s.button==2&&f.showArtwork(this.getItemFromHTML(s))}),e.on("keyup",".filterBy-search",s=>{let i=$(s.currentTarget).closest(".tab"),n=i.attr("data-tab");this.filters[n].filterBy.search=$(s.currentTarget).val(),this.filterItems(i,n)});let t=u(s=>{s.stopPropagation();let i=s.currentTarget.dataset.type,n=s.currentTarget.dataset.uuid;!n||!i||s.originalEvent.dataTransfer.setData("text/plain",JSON.stringify({type:i,uuid:n}))},"itemDragStart");e.on("click",".show-item",async s=>{let i=s.currentTarget.dataset.uuid;(await fromUuid(i)).sheet.render(!0)}),e.find(".show-item").attr("draggable",!0).on("dragstart",s=>t(s)),e.find('*[data-tab="journal"]').click(s=>{this._createIndex("journal","JournalEntry",game.journal)}),e.find('*[data-tab="zoo"]').click(s=>{this._createIndex("zoo","Actor",game.actors)}),e.find(".showDetails").click(s=>{let i=s.currentTarget.dataset.btn;$(s.currentTarget).find("i").toggleClass("fa-caret-left fa-caret-right"),e.find(`.${i} .detailBox`).toggleClass("dsahidden")}),e.find(".toggleWorldIndex").click(s=>{game.settings.set("dsa5","indexWorldItems",!game.settings.get("dsa5","indexWorldItems")),this.checkWorldStuffIndex(),$(s.currentTarget).toggleClass("on")}),e.find(".fulltextsearch").click(s=>{game.settings.set("dsa5","indexDescription",!game.settings.get("dsa5","indexDescription")),$(s.currentTarget).toggleClass("on")}),e.find(".browseEnabled").click(s=>{this.browseEnabled=!this.browseEnabled,$(s.currentTarget).toggleClass("on")}),e.find(".filterDuplicateItems").click(s=>{game.settings.set("dsa5","filterDuplicateItems",!game.settings.get("dsa5","filterDuplicateItems")),$(s.currentTarget).toggleClass("on")});let a=this;$(this._element).find(".window-content").on("scroll.infinit",debounce(function(s){if(a.advancedFiltering)return;let i=$(s.target),n=i.scrollTop()+i.innerHeight()>=i[0].scrollHeight-100,r=e.find(".tabs .item.active").attr("data-tab");if(n&&a.pages[r].next){let o=e.find(".tab.active");a.filterItems.call(a,o,r,a.pages[r].next)}},100))}getItemFromHTML(e){let t=$(e.currentTarget).parents(".browser-item").attr("data-item-id");switch($(e.currentTarget).closest(".tab").attr("data-tab")){case"zoo":return this.zooIndex.find(t);case"journal":return this.journalIndex.find(t);default:return this.equipmentIndex.find(t)}}showLoading(e,t){this.setBGImage([1],t),$(`
    ${game.i18n.localize("Library.buildingIndex")}
    `).appendTo(e.find(".searchResult"))}hideLoading(e,t){this.setBGImage([],t),e.find(".loader").remove()}};u(Rt,"DSA5ItemLibrary");var _t=class extends Dialog{constructor(e,t,a,s=""){let i={title:e,content:t,buttons:{initialize:{label:game.i18n.localize("initialize"),callback:async()=>{this.lock||await this.initialize()}},cancel:{label:game.i18n.localize("cancel"),callback:async()=>{this.lock||await this.dontInitialize()}}}};super(i),this.module=a,this.lang=s,this.folders={},this.journals={},this.scenes={},this.actors={},this.lock=!1}async initNotes(e,t,a){let s=await this.getFolderForType("JournalEntry");for(let i of e.notes)try{let n=t.find(r=>r.flags.dsa5.initId==i.entryId);if(!a.has(n._id)){let r=getProperty(n,"flags.dsa5.parent"),o=s;this.folders[r]?o=this.folders[r]:r&&(o=await this.getFolderForType("JournalEntry",s.id,r,0,getProperty(n,"flags.dsa5.foldercolor")||"")),n.folder=o.id;let c=game.journal.find(m=>m.name==n.name&&m.folder?.id==o.id&&m.flags.dsa5.initId==i.entryId);if(c)await c.update(n),a.set(n._id,c.id);else{let m=await JournalEntry.create(n);a.set(n._id,m.id)}}i.entryId=a.get(n._id)}catch(n){console.warn(`Could not initialize Scene Notes for scene :${e.name}`+n)}}async initScenes(e){let t=await this.getFolderForType("Scene"),s=(await game.packs.get(e.scenes).getDocuments()).map(p=>p.toObject()),n=(await game.packs.get(e.journal).getDocuments()).map(p=>p.toObject()),r=[],o=[],c=new Map,m=!1;for(let p of s){let g=m,y=game.scenes.find(h=>h.name==p.name&&h.folder?.id==t.id);if(!m&&y&&([g,m]=await new Promise((h,w)=>{new Dialog({title:game.i18n.localize("Book.sceneReset"),content:game.i18n.format("Book.sceneResetDescription",{name:p.name}),default:"Yes",buttons:{Yes:{icon:'',label:game.i18n.localize("yes"),callback:()=>{h([!0,!1])}},all:{icon:'',label:game.i18n.localize("LocalizedIDs.all"),callback:()=>{h([!0,!0])}},cancel:{icon:'',label:game.i18n.localize("cancel"),callback:()=>{h([!1,!1])}}},close:()=>{h([!1,!1])}}).render(!0)})),y&&!g){this.scenes[y.name]=y;continue}p.folder=t.id,await this.initNotes(p,n,c),y?(p._id=y.id,o.push(p)):r.push(p)}let d=await Scene.create(r,{dsaInit:!0});for(let p of d){this.scenes[p.name]=p;let g=await p.createThumbnail();await p.update({thumb:g.thumb},{diff:!1})}for(let p of o)await game.scenes.get(p._id).update(p),this.scenes[p.name]=game.scenes.get(p._id);if(e.initialScene){let p=this.scenes[e.initialScene];await game.settings.set("core",NotesLayer.TOGGLE_SETTING,!0),await p.activate(),await p.update({navigation:!0})}}async initialize(){this.lock=!0;let e=$(this._element).find(".initialize");e.prepend('');let t={};try{game.settings.settings.has(`${this.module}.initialized`)&&await game.settings.set(this.module,"initialized",!0)}catch{}try{await fetch(`modules/${this.module}/adventure${this.lang}.json`).then(async a=>a.json()).then(async a=>{t=a})}catch{try{await fetch(`modules/${this.module}/adventure.json`).then(async a=>a.json()).then(async a=>{t=a})}catch{console.warn(`Could not find book data for ${this.module} import.`)}}await fetch(`modules/${this.module}/initialization${this.lang}.json`).then(async a=>a.json()).then(async a=>{let s=a.folders;if(s){let i=await this.getFolderForType("JournalEntry"),n=a.folders[0].name;i&&(this.folders[i.data.name]=i,a.folders.shift());let r=await Folder.create(s);Array.isArray(r)||(r=[r]);for(let c of r)this.folders[c.data.name]=c;let o=[];for(let c in this.folders){let m=this.folders[c].getFlag("dsa5","parent"),d=m==n?game.i18n.localize(`${this.module}.name`):m;d&&o.push({_id:this.folders[c].id,parent:this.folders[d].id})}await Folder.updateDocuments(o)}if(a.items&&a.items.length>0){let i=await this.getFolderForType("Item"),n=[],r=[];for(let o of a.items){o.folder=i.id;let c=game.items.find(m=>m.name==o.name&&m.folder?.id==i.id);c?(o._id=c.id,r.push(o)):n.push(o)}await C.create(n),await C.updateDocuments(r)}if(a.playlists){let i=await this.getFolderForType("Playlist"),n=[],r=[],c=(await game.packs.get(a.playlists).getDocuments()).map(m=>m.toObject());for(let m of c){m.folder=i.id;let d=game.playlists.find(p=>p.name==m.name&&p.folder?.id==i.id);d?(m._id=d._id,r.push(m)):n.push(m)}await Playlist.create(n,{keepId:!0}),await Playlist.updateDocuments(r)}if(a.scenes&&await this.initScenes(a),a.actors){let i=await this.getFolderForType("Actor"),r=(await game.packs.get(a.actors).getDocuments()).map(g=>g.toObject()),o=[],c=[],m=new Map,d=0;if(getProperty(t,"chapters")){for(let g of t.chapters)for(let y of g.content)if(y.actors){let h=!1;for(let w of y.actors)m.has(w)||(m.set(w,y.name),h=!0);h&&(await this.getFolderForType("Actor",i.id,y.name,d),d+=1)}}for(let g of r){let y=m.has(g.name)?await this.getFolderForType("Actor",i.id,m.get(g.name)):i;g.folder=y.id,g._id&&delete g._id;let h=game.actors.find(w=>w.name==g.name&&[i.id,y.id].includes(w.folder?.id));h?(g._id=h.id,await h.deleteEmbeddedDocuments("Item",h.items.map(w=>w.id)),c.push(g)):o.push(g)}let p=await Actor.create(o);await Actor.updateDocuments(c);for(let g of p)this.actors[g.name]=g}}),this.lock=!1,e.find("i").remove(),ui.notifications.notify(game.i18n.localize("initComplete")),await this.close()}async dontInitialize(){game.settings.settings.has(`${this.module}.initialized`)&&await game.settings.set(this.module,"initialized",!0),ui.notifications.notify(game.i18n.localize("initSkipped")),await this.close()}submit(e){try{e.callback&&e.callback(this.options.jQuery?this.element:this.element[0])}catch(t){throw ui.notifications.error(t),new Error(t)}}async getFolderForType(e,t=null,a=null,s=0,i=""){return a||(a=game.i18n.localize(`${this.module}.name`)),f.getFolderForType(e,t,a,s,i)}};u(_t,"DSA5Initializer");var Ft=class extends ChatMessage{get isRoll(){return this.isDSARoll||super.isRoll}get roll(){return this.isDSARoll?new Js(""):super.roll}get isDSARoll(){return this.flags.data?this.flags.data.isDSARoll:!1}};u(Ft,"ChatMessageDSA5Roll");var Js=class extends Roll{render(){return""}};u(Js,"EmptyRoll");var Ht=class extends Hotbar{async _render(e=!1,t={}){await super._render(e,t),this.addContextColor()}async collapse(){return this._collapsed?!0:($(this.element).addClass("collapsedHotbar"),super.collapse())}async expand(){return this._collapsed?($(this.element).removeClass("collapsedHotbar"),super.expand()):!0}async updateDSA5Hotbar(){if(!game.settings.get("dsa5","hotbarv3"))return;let e=canvas.tokens.controlled;if(this.token=void 0,this.showEffects=!1,e.length===1){let t=e[0].actor;t&&t.isOwner&&(this.token=e[0])}e.length>=1&&(this.showEffects=!0),await this.render(!0,{focus:!1})}addContextColor(){let e=new RegExp(` ${game.i18n.localize("CHAR.PARRY")}$`),t=new RegExp(` ${game.i18n.localize("CHAR.ATTACK")}$`),a=$(this._element).find("#macro-list");for(let s of this.macros)!s.macro||(e.test(s.macro.name)?a.find(`[data-macro-id="${s.macro.id}"]`).addClass("parry"):t.test(s.macro.name)&&a.find(`[data-macro-id="${s.macro.id}"]`).addClass("attack"))}get template(){return game.settings.get("dsa5","hotbarv3")?"systems/dsa5/templates/system/hud/hotbar.html":super.template}activateListeners(e){if(super.activateListeners(e),game.settings.get("dsa5","hotbarv3")){e.find(".quantity-click").mousedown(s=>P.quantityClick(s)),e.on("mousedown","li.primary",async s=>(s.stopPropagation(),await this.tokenHotbar.executeQuickButton(s),!1)),e.find(".categoryFilter").click(s=>{this.filterCategory(s,e)});let t=this,a=u(function(s){return t.filterSections(s,e),!1},"fn");e.find(".sections").hover(function(){$(document).off("keydown.sectionFilter",a).on("keydown.sectionFilter",a)},function(){$(document).off("keydown.sectionFilter",a),t.searching="",e.find(".macro,.primary").removeClass("dsahidden"),e.find(".longLayout").removeClass("longLayout")}),e.find(".primary").hover(s=>this._betterTooltip(s)),e.find(".itdarkness input").change(s=>this.tokenHotbar.changeDarkness(s))}}async _betterTooltip(e){let t=e.currentTarget,a=t.dataset,s,i,n;switch(a.category){case"skillgm":s=game.i18n.format("TT.skillgm",{name:a.name});break;case"effect":let r=this.token.actor.effects.get(a.id);r&&(n=game.i18n.has(r.description)?game.i18n.localize(r.description):r.description);break;case"onUse":switch(i=this.token.actor?.items.get(a.id),i.type){case"specialability":n=i.system.rule?.value;break;case"advantage":case"disadvantage":break;default:n=i.system.description?.value}break;case"unequipped":case"consumable":case"weapon":case"spell":i=this.token.actor?.items.get(a.id),n=$(await renderTemplate(`systems/dsa5/templates/items/browse/${i.type}.html`,{isGM:game.user.isGM,...await i.sheet.getData(),document:i,skipHeader:!0,hint:!0})).find(".groupbox").html();break;default:s=game.i18n.localize(a.tooltip)}n&&(s=`

    ${a.name}

    ${n}
    `),s&&game.tooltip.activate(t,{text:s})}filterCategory(e,t){let a=e.currentTarget.dataset.filter;a?(t.find(".skillItems").addClass("collapsed"),t.find(`.skillItems[data-category="${a}"]`).removeClass("collapsed"),t.find(".categoryFilter").removeClass("active"),t.find(`.categoryFilter[data-filter="${a}"]`).addClass("active"),this.activeFilters=[a]):(t.find(".skillItems").removeClass("collapsed"),t.find(".categoryFilter").removeClass("active"),this.activeFilters=[])}filterSections(e,t){switch(this.searching=this.searching||"",e.which){case 8:this.searching=this.searching.slice(0,-1);break;default:if(!e.key.match(/[a-zA-Z0-9öäüÖÄÜ]/))return;this.searching+=e.key}e.preventDefault(),e.stopPropagation();let a=this.searching.toLowerCase();de(a),a?t.find(".sections").addClass("longLayout"):t.find(".sections").removeClass("longLayout");let s=t.find(".macro,.primary");return s.removeClass("dsahidden"),s.filter(function(){return this.dataset?.name?.toLowerCase().trim().indexOf(a)==-1}).addClass("dsahidden"),!1}async getData(e){let t=await super.getData(e);return game.settings.get("dsa5","hotbarv3")&&await this._h3Data(t),t}get tokenHotbar(){return game.dsa5.apps.tokenHotbar}async _h3Data(e){let t={skills:{},attacks:[]},a=[],s=[],i=!1,n=[];if(this.token){let d=this.token.actor;if(n=(this.activeFilters||[]).filter(p=>p!="gm"),d){let p=d.items.filter(h=>h.type=="combatskill").map(h=>T._calculateCombatSkillValues(h.toObject(),d.system));s=await this.tokenHotbar._effectEntries(d);let g=this.tokenHotbar._brawlEntry(p);if(H.isRiding(d)){let h=this._ridingEntry(d);h&&(t.skills.skill=[h])}g&&t.attacks.push(g),t.functions=this.tokenHotbar?._functionEntries()||[];for(let h of d.items)switch(h.type){case"skill":t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._skillEntry(h,"skill"));break;case"spell":case"liturgy":t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._skillEntry(h,"spell"));break;case"trait":Se.traitTypes.has(h.system.traitType.value)&&t.attacks.push(this.tokenHotbar._traitEntry(h));break;case"consumable":t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._actionEntry(h,"consumable",{abbrev:h.system.quantity.value}));break;case"meleeweapon":case"rangeweapon":let w=this.tokenHotbar._combatEntry(h,p,d);h.system.worn.value||(w.cssClass="unequipped"),t.attacks.push(w);break;default:h.getFlag("dsa5","onUseEffect")&&(t.skills[h.type]||(t.skills[h.type]=[]),t.skills[h.type].push(this.tokenHotbar._actionEntry(h,"onUse",{subfunction:"onUse"})));break}}}else if(game.user.isGM&&!game.settings.get("dsa5","disableTokenhotbarMaster")){t.skills.gm=this.tokenHotbar?._gmEntries()||[];let d=this.tokenHotbar?.skills||await this.tokenHotbar?.prepareSkills()||[];t.skills.skill=d,i=!0}let r=45,o=2,c={gm:"systems/dsa5/icons/categories/DSA-Auge.webp"},m={gm:"gmMenu"};for(let d of Object.keys(t.skills)){let p=`TYPES.Item.${d}`;a.push({key:d,tooltip:game.i18n.has(p)?game.i18n.localize(p):game.i18n.localize(m[d]),img:C.defaultImages[d]||c[d]})}if(t.attacks.length>0&&(t.attacks.sort((d,p)=>(p.cssClass||"").localeCompare(d.cssClass||"")||d.name.localeCompare(p.name)),a.unshift({key:"attacks",tooltip:game.i18n.localize("Combat"),img:"systems/dsa5/icons/categories/Meleeweapon.webp"})),this.showEffects){if(canvas.tokens.controlled.length>1){let g=await this.tokenHotbar._effectEntries(canvas.tokens.controlled[0].actor,{subfunction:"sharedEffect"});for(let y of canvas.tokens.controlled){let h=(await y.actor.actorEffects()).map(w=>w.name);g=g.filter(w=>h.includes(w.name))}s=g}let d=game.i18n.localize("CONDITION.add"),p={name:"CONDITION.add",id:"",icon:"icons/svg/aura.svg",cssClass:"effect",abbrev:d[0],subfunction:"addEffect",indicator:"+"};s.unshift(p)}n.length>0&&(n=Object.keys(t.skills).concat(["macro","attacks"]).filter(d=>!n.includes(d))),mergeObject(e,{token:{groups:t,effects:s},darkness:canvas?.scene?.darkness||0,hotBarcssClass:"hotbarV3",barWidth:`${522}px`,baseBarHeight:`${r}px`,barHeight:`${(r+7)*o+30}px`,filterCategories:a,selectedCategories:this.activeFilters||[],showEffects:this.showEffects,activeFilters:n,gmMode:i,macros:this._getAllMacros()})}_getAllMacros(){let e=Array.from({length:50},()=>"");for(let[t,a]of Object.entries(game.user.hotbar))e[parseInt(t)-1]=a;return e.map((t,a)=>{let s=t?game.macros.get(t):null;return{slot:a+1,key:a+1,icon:s?.img||null,cssClass:s?"active":"inactive",tooltip:s?s.name:null,macro:s}})}};u(Ht,"DSA5Hotbar");var je=class{constructor(){this.tokens={},this.actors={}}static get wantedKeys(){let e=["vision","targetMovement","shooterMovement","quickChange","mountOptions","narrowSpace","advantageousPosition","doubleAttack","reduceCostSpell","forceSpell","increaseCastingTime","decreaseCastingTime","removeGesture","removeFormula"];return J.isEnabled||e.push("distance"),e}getPath(e,t,a){let s=a||"",i=t._id||t.type;return e.token?`tokens.${e.token||e.actor}.${i}${s}`:`actors.${e.actor}.${i}${s}`}remember(e,t,a,s){let i=this.formDataSerialize(s);Object.entries(i).length>0&&setProperty(this,this.getPath(e,t,a),i)}recall(e,t,a){return getProperty(this,this.getPath(e,t,a))}formDataSerialize(e){let t=e.find("form"),a={};return t.find("select").each(function(){let s=$(this).attr("name");je.wantedKeys.includes(s)&&(a[s]=$(this).val())}),t.find('input[type="checkbox"]').each(function(){let s=$(this).attr("name");je.wantedKeys.includes(s)&&(a[s]=this.checked)}),t.find(".specAbs.active").each(function(){a.specAbs||(a.specAbs=[]),a.specAbs.push({id:$(this).attr("data-id"),step:$(this).attr("data-step")})}),e.find('[name="situationalModifiers"] option').each(function(){a.situationalModifiers||(a.situationalModifiers=[]),a.situationalModifiers.push({name:$(this).text().trim(),selected:this.selected})}),a}};u(je,"RollMemory");var Qs=class extends ActiveEffect{apply(e,t){if(Qs.itemChangeRegex.test(t.key)){let a=this._getModifiedItems(e,t);for(let s of a.items){let i=foundry.utils.flattenObject(s.overrides||{});i[a.key]=Number.isNumeric(s.value)?Number(a.value):a.value;let n={...t,key:a.key,value:a.value};super.apply(s,n),s.overrides=foundry.utils.expandObject(i)}}else return super.apply(e,t)}static async _onCreateDocuments(e,t){for(let a of e)a.parent.documentName=="Actor"&&await T.postUpdateConditions(a.parent);return super._onCreateDocuments(e,t)}static async _onUpdateDocuments(e,t){for(let a of e)a.parent.documentName=="Actor"&&await T.postUpdateConditions(a.parent);return super._onUpdateDocuments(e,t)}static async _onDeleteDocuments(e,t){for(let a of e)a.parent.documentName=="Actor"&&await T.postUpdateConditions(a.parent);return super._onDeleteDocuments(e,t)}isVisibleEffect(){return!this.disabled&&!this.notApplicable&&(game.user.isGM||!this.getFlag("dsa5","hidePlayers"))&&!this.getFlag("dsa5","hideOnToken")&&(this.origin==this.target?.uuid||!this.origin)}_displayScrollingStatus(e){let t=["dead"];!(game.user.isGM||this.target?.testUserPermission(game.user,"OBSERVER")||!game.settings.get("dsa5","hideEffects")?this.isVisibleEffect():t.some(i=>this.statuses.has(i)))||super._displayScrollingStatus(e)}_getModifiedItems(e,t){let a=t.key.split("."),s=a.shift();s=s.replace("@","").toLowerCase();let i=a.shift(),n=a.join("."),r=t.value;return{items:e?.items?.filter(c=>c.type==s&&(c.name==i||c.id==i))||[],key:n,value:r}}async _preUpdate(e,t,a){super._preUpdate(e,t,a),this._clearModifiedItems()}_clearModifiedItems(){if(this.parent instanceof CONFIG.Actor.documentClass){for(let e of this.changes)if(Qs.itemChangeRegex.test(e.key)){let t=this._getModifiedItems(this.parent,e);for(let a of t.items){let s=foundry.utils.flattenObject(a.overrides||{}),i=t.key;delete s[i];let n=getProperty(a._source,i);setProperty(a,i,n),a.overrides=foundry.utils.expandObject(s),a.sheet?.rendered&&a.sheet.render(!0)}}}}async _preDelete(e,t){super._preDelete(e,t),this._clearModifiedItems()}},gt=Qs;u(gt,"DSAActiveEffect"),L(gt,"itemChangeRegex",/^@/);var An=u((l,e)=>{let t=getProperty(l,e.key)||null;t==null&&/^system\.(vulnerabilities|resistances)/.test(e.key)&&(t=[],setProperty(l,e.key,t));let a=getType(t),s=null;switch(a){case"Array":let i=[],n=e.effect.name;for(let r of`${e.value}`.split(/[;,]+/)){let o=r.split(" "),c=o.pop(),m=o.join(" ");i.push({source:n,value:c,target:m})}s=t.concat(i)}return s!==null&&setProperty(l,e.key,s),s},"applyCustomEffect");Hooks.on("applyActiveEffect",(l,e)=>An(l,e));Hooks.once("init",()=>{console.log("Initializing DSA5 system"),CONFIG.statusEffects=b.statusEffects,game.dsa5={apps:{DSA5_Utility:f,DSA5Initializer:_t,DSA5ChatListeners:ae,DSA5Payment:B,SpecialabilityRulesDSA5:R,AdvantageRulesDSA5:O,Migrakel:Ie,DSA5Dialog:ee,DSA5StatusEffects:E,DPS:J,DSATables:U,DSA5SoundEffect:K,RequestRoll:q,DiceDSA5:_DiceDSA5,DSATour:Ne,OpposeDSA:j,EquipmentDamage:W,APTracker:_,DidYouKnow:Fe,MeasuredTemplateDSA:dt,Riding:H,RuleChaos:P,Trade:pe,DSAActiveEffectConfig:Q},entities:{Actordsa5:T,Itemdsa5:C},sheets:{ActorSheetdsa5:$e,ActorSheetdsa5Character:be,ActorSheetdsa5Creature:Oe,ActorSheetdsa5NPC:ze,MerchantSheetMixin:it,MerchantSheetDSA5:Ae,ItemSheetdsa5:Y},wizards:{CareerWizard:Xe,CultureWizard:Qe,SpeciesWizard:Ze},view:{tinyNotification:de,tabSlider:oe,clickableAbility:yt},dialogs:{DialogReactDSA5:ce,ReactToSkillDialog:ct,ActAttackDialog:Re,ReactToAttackDialog:Me},macro:Nt,config:b,memory:new je,itemLibrary:new Rt},CONFIG.Actor.documentClass=T,CONFIG.Item.documentClass=C,CONFIG.ChatMessage.template="systems/dsa5/templates/chat/chat-message.html",CONFIG.ChatMessage.documentClass=Ft,CONFIG.ui.combat=Ce,CONFIG.ui.hotbar=Ht,CONFIG.Combat.documentClass=He,CONFIG.Combatant.documentClass=Jt,CONFIG.ActiveEffect.documentClass=gt,CONFIG.ActiveEffect.legacyTransferral=!1});ki(); diff --git a/lang/en.json b/lang/en.json index 8f33418d..0156948b 100644 --- a/lang/en.json +++ b/lang/en.json @@ -7,6 +7,8 @@ "Attribute-hard": "Very Difficult (-4)", "Attribute-vhard": "Extremely Difficult (-6)", "char": "Attribute", + "leftClick": "Left-", + "rightClick": "Right-", "CHAR": { "MU": "Courage", "KL": "Sagacity", @@ -18,6 +20,7 @@ "KK": "Strength", "ATTACK": "Attack", "PARRY": "Parry", + "GE/KK": "Agility / Strength", "GEKK": "Agility / Strength", "DAMAGE": "Damage", "DODGE": "Dodge", @@ -191,6 +194,7 @@ "buy": "Buy", "sell": "Sell", "exchange": "Exchange", + "exchangeWithTarget": "Exchange with marked target", "splitItem": "Split {name}", "commerce": "Trade", "hidePlayer": "Hide for player", @@ -558,7 +562,7 @@ "Spent": "Spent", "skModifier": "Spirit (Target)", "step": "Step", - "stepValue": "Step", + "stepValue": "Level", "status": "State", "stone": "Stone", "selfDamage": "injured self, Damage: ", @@ -914,6 +918,7 @@ "SplitItem": "Split", "DuplicateItem": "Duplicate", "EquipItem": "Equip", + "UnEquipItem": "Unequip", "Dropdown": "Details", "increaseFontSize": "Increase/Decrease font size", "DeleteItem": "Delete", @@ -1066,7 +1071,8 @@ "tokenhotbarMod": "Modifier/Value", "tokenhotbarMoney": "Left-: pay
    Right-: get paid", "tokenhotbarSkill": "Left-: request roll
    Right-: request group check
    Ctrl + : 3d20 check", - "effectVariant": "Alternative effect like e.g. a second or third attack" + "effectVariant": "Alternative effect like e.g. a second or third attack", + "skillgm": "{name}
    Left-: Request roll
    Right-: Request group check
    CTRL + : 3W20 Probe" }, "HELP": { "showHelp": "Show help", @@ -1584,6 +1590,8 @@ "gear": "Update icons, effects and effectformula of all gear, weapons and armors. THIS WILL OVERRIDE MANUAL MODIFICATIONS!" }, "DSASETTINGS": { + "hotbarv3": "DSA Hotbar Conversion", + "hotbarv3Hint": "The hotbar is completely replaced by a TDE variant. Abilities and other elements are directly dependent on the selected token. (Recommendation: Deactivate the token hotbar additionally)", "enableMasterTokenFunctions": "Enable Master Token Functions", "enableMasterTokenFunctionsHint": "Chose the game muster functions you want to be shown in the token hotbar", "meleeBotchTableEnabled": "Close Combat-Botch Table", diff --git a/lazy/patchhtml/changelog_de_5.3.0.html b/lazy/patchhtml/changelog_de_5.3.0.html new file mode 100644 index 00000000..65604a50 --- /dev/null +++ b/lazy/patchhtml/changelog_de_5.3.0.html @@ -0,0 +1,46 @@ +

    Wichtige Änderungen (18.01.2024)

    +

    Das fließende Update

    +

    In dieser Runde haben wir erhebliche Zeit darauf verwendet, ältere Module (siehe unten) an die neuesten Entwicklungen anzupassen. Dies umfasst vor allem zahlreiche kleinere Fehlerkorrekturen sowie Designverbesserungen im Journalbrowser. Aufgrund der langen Wartezeit, die erforderlich wäre, um alle Module zu aktualisieren, haben wir uns entschieden, diesen Patch schrittweise einzuführen. Das bedeutet, dass die Module nach und nach auf Version 5.3.0 (bzw. 5.3.1 für englischen Inhalt) aktualisiert werden, um den Fortschritt nicht zu beeinträchtigen. Dabei können auch neue Funktionen eingeführt werden, die wir erst in einem späteren umfassenderen Patch ankündigen werden.

    +

    Journalbrowser Upgrades

    +

    Einige Kleinigkeiten sollten den Journalbrowser nun angenehmer in der Benutzung machen.

    +
      +
    • Die Suchfunktion hinterlegt gesuchte Begriffe nun zusätzlich mit einem gelben Hintergrund.
    • +
    • Die Suchfunktion zeigt über einen roten Streifen auf der Scrollbar zusätzlich die Position der gefundenen Texte auf der aktuellen Seite.
    • +
    • Das Journalbrowser Inhaltsverzeichnis sollte nun beim Wechsel der Seiten nicht mehr springen.
    • +
    • Der Journalbrowser zeigt im Inhaltsverzeichnis nun zusätzlich die Headings der aktuellen Seite, ähnlich wie normale Journals.
    • +
    +

    Divinarium Liturgiae

    +

    Alle Liturgien und Zeremonien wurden auf den neuesten Stand des Divinarium Liturgiae aktualisiert. Falls sich dabei die Steigerungskosten geändert haben, wurden alle Professionen neu kalkuliert und entsprechend angepasst. Kurz nach diesem Update werden alle Module auf den Stand 5.3.0 aktualisiert und die durchgeführten Änderungen integriert.

    +

    Zusätzlich wurden zahlreiche kleinere Bugfixes in den Daten der DSA-Items implementiert. Die Datenbank für die Zaubererweiterungen der Liturgien wurde ebenfalls aktualisiert und enthält nun alle neuen Erweiterungen.

    +

    Da es mehr als 5000 Erweiterungen für Zauber, Liturgien, Rituale und Zeremonien gibt, ist es uns nicht möglich, ihre Funktionalität aufgrund der schieren Menge selbst zu implementieren. Hier ist die Zusammenarbeit der TDE/DSA-Community entscheidend. Wenn du dich dazu berufen fühlst, uns dabei zu helfen, findest du weitere Informationen unter: https://github.com/Plushtoast/dsa5-extensiondb

    +

    AP Logging

    +

    Nun hast du die Möglichkeit, die Verwendung von Abenteuerpunkten zu protokollieren. Die genutzten Abenteuerpunkte werden außerhalb des Charakters in einem speziellen Journal gespeichert, um den benötigten Speicherplatz des Charakters nicht unnötig zu belasten – das kann sonst recht ausufern :) . Ein Journal im Ordner "Abenteuerpunkte Historie" wird angelegt und bei Verwendung von Abenteuerpunkten regelmäßig aktualisiert.

    +

    Standardmäßig ist diese Funktion deaktiviert und kann nur vom Spielleiter aktiviert oder deaktiviert werden. Der zugehörige Schalter befindet sich in den Einstellungen. Wenn Charaktere Spielern zugewiesen sind, wird automatisch ein entsprechendes Journal erstellt, sobald sich die Abenteuerpunkte ändern. Spieler haben standardmäßig Schreibrechte für dieses Journal und können so eigenständig ohne Spielleiter ihre Steigerungen vornehmen (obwohl Manipulation möglich ist). Wenn das Journal auf "Read only" gesetzt wird, wird die Protokollierung nur dann durchgeführt, wenn ein Spielleiter online ist (wodurch Manipulation schwieriger wird).

    +

    Tokenhotbar V3

    +

    Wir freuen uns besonders, die neue Tokenhotbar vorzustellen, die die Hotbar in DSA ersetzt. Die Tokenhotbar ermöglicht den Zugriff auf alle wichtigen Funktionen eines Charakters direkt über die Hotbar. Dabei stehen, ähnlich wie in der vorherigen Version der Tokenhotbar, alle möglichen Funktionen zur Verfügung. Dieses neue Verhalten lässt sich aber auch in den Einstellungen der Tokenhotbar deaktivieren.

    +

    Für diejenigen, die die bisherige Tokenhotbar benutzen, wird empfohlen, diese zu deaktivieren. Wir sind gespannt auf euer Feedback und freuen uns darauf.

    +

    Havena - Unendlichkeit und Tiefernrausch

    +

    Die Havena Erweiterung "Unendlichkeit und Tiefenrausch", die sich vornehmlich mit der Gottheit Numinoru und Kreaturen des Meeres beschäftigt, ist nun ebenfalls Teil des Havena RSH Moduls und sollte mit dessen Modulupdate auf 5.3.0 verfügbar sein.

    +

    Verbesserungen

    +
      +
    • Die Sichtschwellen im Meistermenü haben nun einen Reset Button
    • +
    • Der Zauber Ecliptifactus funktioniert jetzt ziemlich anständig :)
    • +
    • Ein beschworenes Flammenschwert kann nun zusätzlich vom Akteur gelöst werden und sich selbständig als Token fortbewegen.
    • +
    • Aller Zauber mit Zielkategorie Zone sollten nun ein Template für die Größe der Zone inbegriffen haben.
    • +
    • Heldenbögen ohne Ausrüstungsgegenstände enthalten nun einen Hinweis für Drag & Drop, der es Neulingen helfen sollte sich schneller zurecht zu finden.
    • +
    • Beim Start eines Prügelkampfs wird nun abgefragt, ob alle Waffen abgelegt werden sollen. Deren Reichweite hat anschließend keinen Einfluss auf die Berechnung der Wurfmodifikatoren. Tipp: Man kann den Schaden als SP anwenden um Rüstungen zu ignorieren. Möglicherweise möchte man den Kampf etwas schneller gestalten so (und nicht nur 1 Prügelpunkt pro Treffer kassieren).
    • +
    • Die Schriftart Andalus wird nun nicht mehr in der Sidebar in Überschriften verwendet. Dadurch sollte diese etwas leserlicher sein. Sie findet sich nur noch in Journals und ähnlichen Texten.
    • +
    • Alle Wesenszüge nach Herkunft wurden den Regionalspielhilfen und den Spielhilfen für Orks und Achaz hinzugefügt und auch automatisiert, sofern möglich.
    • +
    • Alle Prägungen wurden den Regelmodulen und Regionalspielhilfen hinzugefügt und automatisiert sofern möglich.
    • +
    • Alle Bestiarien und Regionalspielhilfen sollten nun Bestien und Akteure im Journalbrowser aufgeführt haben.
    • +
    • Alle (Tier)-ruf Liturgien beschwören nun im Kampf automatisch die entsprechende Anzahl an Kreaturen (benötigt das Modul Times-Up)
    • +
    • Die Bibliothek rendert im Browse Mode/Stöbermodus die Elemente nun nur noch wenn sie im Viewport sind. Das verbessert die Performance enorm.
    • +
    • Die Bibliothek kann nun Browse Mode/Stöbermodus auch für Akteure (zur Erinnerung, der Browse Mode kann in der Bibliothek aktiviert werden und zeigt Elemente detailliert an zum Stöbern)
    • +
    • Die Settings für automatische Tokengröße (abhängig von der Großenkategorie) und für die automatische Ressourcenleiste (KaP, AsP) sind in die Prototype Token Konfiguration gewandert (wo sie hingehören)
    • +
    • Besonderen Dank an Zoidable für die Implementierung von "Talentverbesserung", "Nervös machen" und "Gegenhalten"
    • +
    +

    Bugfixes

    +
      +
    • Das ein oder andere On-use Macro sollte wieder richtig funktionieren (z.B. Hexenkrallen).
    • +
    • Ein paar Zaubererweiterungen sollten den Schaden nun richtig modifizieren.
    • +
    diff --git a/lazy/patchhtml/changelog_en_5.3.0.html b/lazy/patchhtml/changelog_en_5.3.0.html new file mode 100644 index 00000000..6efce2e7 --- /dev/null +++ b/lazy/patchhtml/changelog_en_5.3.0.html @@ -0,0 +1,45 @@ +

    Important changes

    +

    The Seamless Update

    +

    In this round, we invested significant time in adapting older modules (see below) to the latest developments. This includes numerous minor bug fixes and design improvements in the Journal Browser. Due to the extended waiting time that would be required to update all modules at once, we have decided to introduce this patch gradually. This means that modules will be updated to version 5.3.0 (or 5.3.1 for English content) one by one to avoid hindering overall progress. Additionally, new features may be introduced, which will be announced in a later comprehensive patch.

    +

    Journal Browser Upgrades

    +

    Several enhancements have been implemented to make the Journal Browser more user-friendly.

    +
      +
    • The search function now highlights searched terms with a yellow background.
    • +
    • The search function indicates the position of found texts on the current page with a red stripe on the scrollbar.
    • +
    • The Journal Browser Table of Contents should no longer jump when switching pages.
    • +
    • The Journal Browser Table of Contents now additionally displays the headings of the current page, similar to regular journals.
    • +
    +

    Divinarium Liturgiae

    +

    All liturgies and ceremonies have been updated to the latest Divinarium Liturgiae standards. If there were changes in the advancement costs, all professions have been recalculated and adjusted accordingly. Shortly after this update, all modules will be updated to version 5.3.0, incorporating the implemented changes. Numerous minor bug fixes have also been applied to the data of DSA items. The database for spell extensions of liturgies has been updated and now includes all new extensions.

    +

    Given the sheer volume of over 5000 extensions for spells, liturgies, rituals, and ceremonies, implementing their functionality ourselves is not feasible. Collaboration with the TDE/DSA community is crucial. If you feel called to contribute, you can find more information at: https://github.com/Plushtoast/dsa5-extensiondb

    +

    AP Logging

    +

    You now have the option to log the use of Adventure Points. The utilized Adventure Points are stored outside the character in a special journal, preventing unnecessary strain on the character's storage space – it can get quite extensive :) . A journal is created in the "Adventure Points History" folder and is regularly updated when Adventure Points are used.

    +

    This feature is disabled by default and can only be activated or deactivated by a Game Master. The corresponding switch can be found in the settings. For characters assigned to players, a corresponding journal is automatically created when Adventure Points change. Players have write permissions on this journal by default, allowing them to independently make advancements without needing a Game Master (though manipulation is still possible). If the journal is set to "Read only," logging will only occur when a Game Master is online (making manipulation more difficult).

    +

    Tokenhotbar V3

    +

    We are particularly excited to introduce the new Tokenhotbar, replacing the hotbar in DSA. The Tokenhotbar allows access to all essential character functions directly through the hotbar. Similar to the previous version of the Tokenhotbar, all possible functions are available. However, this new behavior can also be deactivated in the Tokenhotbar settings.

    +

    For those using the previous Tokenhotbar, it is recommended to deactivate it. We look forward to your feedback.

    +

    Havena - Infinity and Abyssal Depths

    +

    The Havena expansion "Infinity and Abyssal Depths," primarily focusing on the deity Numinoru and creatures of the sea, is now part of the Havena RSH module and should be available with its module update to version 5.3.0.

    +

    Improvements

    +
      +
    • Sighting thresholds in the Game Master menu now have a reset button.
    • +
    • The spell Ecliptifactus now functions quite decently.
    • +
    • A summoned Flame Sword can now be detached by the actor and move independently as a token.
    • +
    • All spells with a Zone target category should now include a template for the size of the zone.
    • +
    • Character sheets without equipment now include a Drag & Drop hint to help newcomers navigate more quickly.
    • +
    • When initiating a brawl, there is now a prompt asking if all weapons should be dropped. Their range subsequently does not affect the calculation of throw modifiers. Tip: Applying damage as SP can be used to ignore armor. This may speed up the fight (not receiving only 1 brawl point per hit).
    • +
    • The font Andalus is no longer used in headings in the sidebar. This should make it more readable. It is now only used in journals and similar texts.
    • +
    • All origin traits have been added to regional supplements and supplements for orcs and Achaz and automated where possible.
    • +
    • All imprints have been added to rule modules and regional supplements and automated where possible.
    • +
    • All bestiaries and regional supplements should now list creatures and actors in the Journal Browser.
    • +
    • All (animal)-call liturgies now automatically summon the corresponding number of creatures in combat (requires the Times-Up module).
    • +
    • The library now renders elements in Browse Mode only when they are in the viewport, significantly improving performance.
    • +
    • The library can now use Browse Mode for actors as well (to remind, Browse Mode can be activated in the library, displaying elements in detail for browsing).
    • +
    • The settings for automatic token size (dependent on the size category) and for the automatic resource bar (KaP, AsP) have moved to the Prototype Token configuration (where they belong).
    • +
    • Special thanks to Zoidable for implementing "Talent Improvement," "Make Nervous," and "Counter."
    • +
    +

    Bugfixes

    +
      +
    • Some on-use macros should now work correctly again (e.g., Witch Claws).
    • +
    • Some spell extensions should now properly modify damage.
    • +
    diff --git a/lazy/patchhtml/news_de_5.3.0.html b/lazy/patchhtml/news_de_5.3.0.html new file mode 100644 index 00000000..3e04557c --- /dev/null +++ b/lazy/patchhtml/news_de_5.3.0.html @@ -0,0 +1,14 @@ +
    +

    Foundry DSA News (18.01.2024)

    +

    Das fließende Update

    +

    Dieses mal gibt es keine konkreten Angaben für Releases, den dies ist der fließende Patch. Was bedeuetet das? Auf Grund von Änderungen die wir an allen Modulen vornehmen müssen, wird sich dieser Patch eher über längere Zeit ziehen und immer mal wieder kleinere Änderungen mit sich ziehen um Foundry v11 abzuschließen und die Module für eine Weile zu festigen. Diese Änderungen werden erst in einem späteren Patch nochmals detailliert aufgeführt werden.

    +

    Das gleiche gilt für die folgenden Module die wir für Q1 planen. Wann genau sie kommen steht noch nicht fest, deswegen erfolgt eine Ankündigung auch erst in den Patchnotes eines folgenden Patches. Trotzdem können wir schonmal verraten was geplant ist:

    +
      +
    • Die Streitenden Königreiche (Englisch)
    • +
    • Rabenkrieg 4
    • +
    • RSH Das Dornenreich
    • +
    • Kaiser Retos Waffenkammer
    • +
    • RSH Winterwacht
    • +
    +

    Viel Spaß

    +
    \ No newline at end of file diff --git a/lazy/patchhtml/news_en_5.3.0.html b/lazy/patchhtml/news_en_5.3.0.html new file mode 100644 index 00000000..ab615175 --- /dev/null +++ b/lazy/patchhtml/news_en_5.3.0.html @@ -0,0 +1,16 @@ +
    +

    Foundry TDE News (01/18/2024)

    +

    The rolling update

    +

    This time there are no specific details for releases as this is the rolling patch. Was bedeuetet das? Auf Grund + von Änderungen die wir an allen Modulen vornehmen müssen, wird sich dieser Patch eher über längere Zeit ziehen + und immer mal wieder kleinere Änderungen mit sich ziehen um Foundry v11 abzuschließen und die Module für eine + Weile zu festigen. Diese Änderungen werden erst in einem späteren Patch nochmals detailliert aufgeführt werden. +

    +

    The same applies to the following modules we are planning for Q1. Wann genau sie kommen steht noch nicht fest, + deswegen erfolgt eine Ankündigung auch erst in den Patchnotes eines folgenden Patches. Nevertheless, we can + already reveal what is planned:

    +
      +
    • Regional supplement, The Warring Kingdom
    • +
    + +
    \ No newline at end of file diff --git a/lazy/updatenotes.json b/lazy/updatenotes.json index a7042854..2062a49b 100644 --- a/lazy/updatenotes.json +++ b/lazy/updatenotes.json @@ -76,6 +76,10 @@ { "version": "5.2.0", "text": "
    • Upcoming modules (german): Rahjas Diener, Die Siebenwindküste, Körperlose Schrecken, Banner der Treue
    • Bum fights
    • Player trade v1
    • New layouts
    • Don't forget to visit VTTom's Youtube channel for recent tutorial videos (german, some with subtitle)
    • Some english explanatory videos here: Let's VTT
    • And big thanks again to all our voluntary helpers! Especially Gunthgard, VTTom, Nellkir, Lambert, Adalariel, Mckee, Rapunzel, Zoidable and in memoriam Niemand.
    " + }, + { + "version": "5.3.0", + "text": "
    • Upcoming modules (german): Rabenkrieg IV, DSK - Fasar, Königreich der Dornen, Winterwacht, Kaiser Retos Waffenkammer, Warring Kingdoms
    • New Tokenbar
    • Data maintenance
    • Don't forget to visit VTTom's Youtube channel for recent tutorial videos (german, some with subtitle)
    • Some english explanatory videos here: Let's VTT
    • And big thanks again to all our voluntary helpers! Especially Gunthgard, VTTom, Nellkir, Lambert, Adalariel, Mckee, Rapunzel, Zoidable, Qowy and in memoriam Niemand.
    " } ] diff --git a/modules/actor/actor-dsa5.js b/modules/actor/actor-dsa5.js index ce3ed137..b1e97103 100644 --- a/modules/actor/actor-dsa5.js +++ b/modules/actor/actor-dsa5.js @@ -263,7 +263,7 @@ export default class Actordsa5 extends Actor { actor[attr] = isChange; if(isChange) - await actor.addCondition(effect, target, true).then(() => actor[attr] = undefined); + await actor.addCondition(effect, target, true, true).then(() => actor[attr] = undefined); } static async postUpdateConditions(actor) { @@ -2693,7 +2693,7 @@ export default class Actordsa5 extends Actor { return { result, cardOptions, options }; } - async addCondition(effect, value = 1, absolute = false, auto = true) { + async addCondition(effect, value = 1, absolute = false, auto = false) { if (effect == "bleeding" || effect.id == "bleeding") return await RuleChaos.bleedingMessage(this); //V11 actor delta fix for #displayScrollingStatus diff --git a/modules/dialog/dialog-combat-dsa5.js b/modules/dialog/dialog-combat-dsa5.js index 7a111984..3873b340 100644 --- a/modules/dialog/dialog-combat-dsa5.js +++ b/modules/dialog/dialog-combat-dsa5.js @@ -138,7 +138,7 @@ export default class DSA5CombatDialog extends DialogShared { if (modIndex >= 0) { attackStatEffect = situationalModifiers.splice(modIndex, 1).pop() } - let defenseModifiers = [] + const defenseModifiers = [] Itemdsa5.getSubClass(item.type).getSituationalModifiers(defenseModifiers, actor, { mode: "parry" }, item) modIndex = defenseModifiers.findIndex(x => x.name == game.i18n.localize("statuseffects")) let defenseStatEffect diff --git a/modules/hooks/configuration.js b/modules/hooks/configuration.js index 1f4f6043..8de2434c 100644 --- a/modules/hooks/configuration.js +++ b/modules/hooks/configuration.js @@ -94,7 +94,7 @@ export function setupConfiguration() { hint: "migrationVersion", scope: "world", config: false, - default: 25, + default: 26, type: Number }) diff --git a/modules/hooks/texteditor.js b/modules/hooks/texteditor.js index 39b98cb1..4be4931a 100644 --- a/modules/hooks/texteditor.js +++ b/modules/hooks/texteditor.js @@ -78,7 +78,7 @@ export function setEnrichers() { } }, { - pattern: /@EmbedItem\[[a-zA-ZöüäÖÜÄ&ë;'\(\)„“:, -\.0-9›‹âïß\/]+\]({[a-zA-Z=]+})?/g, + pattern: /@EmbedItem\[[a-zA-ZöüäÖÜÄ&ë;'\(\)„“:,’ -\.0-9›‹âïßôñé\/]+\]({[a-zA-Z=]+})?/g, enricher: async(match, options) => { let uuid = match[0].match(/(?:\[)(.*?)(?=\])/)[0].slice(1) let document = await fromUuid(uuid) diff --git a/modules/system/hotbar.js b/modules/system/hotbar.js index 33ea215d..7b7d261c 100644 --- a/modules/system/hotbar.js +++ b/modules/system/hotbar.js @@ -173,14 +173,12 @@ export default class DSA5Hotbar extends Hotbar { filterSections(ev, html) { this.searching = this.searching || "" switch(ev.which){ - case 91: - case 18: - case 17: - return case 8: this.searching = this.searching.slice(0, -1) break default: + if(!ev.key.match(/[a-zA-Z0-9öäüÖÄÜ]/)) return + this.searching += ev.key } ev.preventDefault() diff --git a/modules/system/migrator.js b/modules/system/migrator.js index 107550bf..224f624f 100644 --- a/modules/system/migrator.js +++ b/modules/system/migrator.js @@ -22,6 +22,9 @@ async function migrateDSA(currentVersion, migrationVersion) { if(currentVersion < 24){ await migratTo24() } + if(currentVersion < 27){ + await migrateTo26() + } await game.settings.set("dsa5", "migrationVersion", migrationVersion) } @@ -33,6 +36,10 @@ async function migratTo24() { } } +async function migrateTo26() { + game.settings.set("dsa5", "disableTokenhotbar", true) +} + export async function showPatchViewer() { const notes = await fetch("systems/dsa5/lazy/updatenotes.json") const json = await notes.json() @@ -51,7 +58,7 @@ export default function migrateWorld() { await setupDefaulTokenConfig() const currentVersion = await game.settings.get("dsa5", "migrationVersion") - const NEEDS_MIGRATION_VERSION = 26 + const NEEDS_MIGRATION_VERSION = 27 const needsMigration = currentVersion < NEEDS_MIGRATION_VERSION //betaWarning() diff --git a/modules/system/onUseEffects.js b/modules/system/onUseEffects.js index d692a6cf..4b9e86e1 100644 --- a/modules/system/onUseEffects.js +++ b/modules/system/onUseEffects.js @@ -21,19 +21,25 @@ export default class OnUseEffect { try { args.result = result; const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor - //TODO passing multiple scopes here kind of messes things up - const fn = new AsyncFunction("args", "actor", "item", - ` - const that = this; - ${documents[0].command.replace(/( |\(|{)this\./g, " that.")} - `) + const fn = new AsyncFunction("args", "actor", "item", documents[0].command) result.ret = await fn.call(this, args, this.item.actor, this.item) } catch (err) { - ui.notifications.error( - `There was an error in your macro syntax. See the console (F12) for details` - ); - console.error(err); - result.error = true; + //Todo passing multiple scopes kind of fails + try { + const fn2 = new AsyncFunction("args", "actor", "item", + ` + const that = this; + ${documents[0].command.replace(/( |\(|{)this\./g, " that.")} + `) + result.ret = await fn2.call(this, args, this.item.actor) + } + catch (err) { + ui.notifications.error( + `There was an error in your macro syntax. See the console (F12) for details` + ); + console.error(err); + result.error = true; + } } } else { ui.notifications.error(game.i18n.format("DSAError.macroNotFound", { name })); diff --git a/modules/system/tokenHotbar2.js b/modules/system/tokenHotbar2.js index 68c922f9..2fc35988 100644 --- a/modules/system/tokenHotbar2.js +++ b/modules/system/tokenHotbar2.js @@ -90,7 +90,6 @@ export default class TokenHotbar2 extends Application { }) Hooks.on("updateActiveEffect", (effect, options) => { - console.log(effect, effect.parent, effect.parent.id) parentUpdate(effect) }) @@ -667,14 +666,12 @@ export default class TokenHotbar2 extends Application { filterButtons(ev){ switch(ev.which){ - case 91: - case 18: - case 17: - return case 8: this.searching = this.searching.slice(0, -1) break default: + if(!ev.key.match(/[a-zA-Z0-9öäüÖÄÜ]/)) return + this.searching += ev.key } ev.preventDefault() diff --git a/styles/css/dsa5.css b/styles/css/dsa5.css index f839ffdc..16b91f16 100644 --- a/styles/css/dsa5.css +++ b/styles/css/dsa5.css @@ -1 +1 @@ -:root{--border-color:#736953a6;--bg-color:#e1d3c6;--button-color:#532902e7;--sheet-bg:#2e2c2a15;--sheet-border:#968678;--boldFont:"Signika";--normalFont:"Signika";--minColumnWidth: 330px;--minColumnWidth40: 264px;--minColumnWidth60: 396px}@font-face{font-family:"GentiumBasic";src:url("../../fonts/GenBasR.eot");src:url("../../fonts/GenBasR.eot?#iefix") format("embedded-opentype"),url("../../fonts/GenBasR.otf") format("opentype"),url("../../fonts/GenBasR.svg") format("svg"),url("../../fonts/GenBasR.ttf") format("truetype"),url("../../fonts/GenBasR.woff") format("woff"),url("../../fonts/GenBasR.woff2") format("woff2");font-weight:normal;font-style:normal}@font-face{font-family:"GentiumBasic-BoldItalic";src:url("../../fonts/GenBasBI.eot");src:url("../../fonts/GenBasBI.eot?#iefix") format("embedded-opentype"),url("../../fonts/GenBasBI.otf") format("opentype"),url("../../fonts/GenBasBI.svg") format("svg"),url("../../fonts/GenBasBI.ttf") format("truetype"),url("../../fonts/GenBasBI.woff") format("woff"),url("../../fonts/GenBasBI.woff2") format("woff2");font-weight:normal;font-style:normal}@font-face{font-family:"GentiumBasic-Bold";src:url("../../fonts/GenBasB.eot");src:url("../../fonts/GenBasB.eot?#iefix") format("embedded-opentype"),url("../../fonts/GenBasB.otf") format("opentype"),url("../../fonts/GenBasB.svg") format("svg"),url("../../fonts/GenBasB.ttf") format("truetype"),url("../../fonts/GenBasB.woff") format("woff"),url("../../fonts/GenBasB.woff2") format("woff2");font-weight:normal;font-style:normal}@font-face{font-family:"Andalus";src:url("../../fonts/andlso.eot");src:url("../../fonts/andlso.eot?#iefix") format("embedded-opentype"),url("../../fonts/andlso.otf") format("opentype"),url("../../fonts/andlso.svg") format("svg"),url("../../fonts/andlso.ttf") format("truetype"),url("../../fonts/andlso.woff") format("woff"),url("../../fonts/andlso.woff2") format("woff2");font-weight:normal;font-style:normal}#tinymce{overflow-y:hidden;overflow-x:hidden}.tox-tinymce{width:100%}.editor-content ul{margin:0px 0px}.overflowhidden{overflow:hidden}.scrollY{overflow-y:auto;overflow-x:hidden}body{padding:0px;overflow:hidden;font-size:14px;font-family:var(--normalFont)}textarea{font-family:var(--normalFont)}b{font-family:var(--boldFont);font-weight:bold}h1,h2,h3,h4,h5,h6,h7{overflow:hidden}h1 a.content-link,h1 a.entity-link,h2 a.content-link,h2 a.entity-link,h3 a.content-link,h3 a.entity-link,h4 a.content-link,h4 a.entity-link,h5 a.content-link,h5 a.entity-link,h6 a.content-link,h6 a.entity-link,h7 a.content-link,h7 a.entity-link{background:none;padding:0;border:none}.dsa5 h1,.dsa5 h2,.dsa5 h3,.dsa5 h4,.dsa5 h5,.dsa5 h6,.dsa5 h7{font-family:"Andalus"}.schwierig,.einfach{margin-left:40px;position:relative}.schwierig:before,.einfach:before{content:"";background:url("../../icons/einfach.webp");background-size:contain;background-repeat:no-repeat;position:absolute;left:-40px;top:0;height:30px;width:30px;margin-right:5px}.schwierig:before{background-image:url("../../icons/schwierig.webp")}.obfuscateSection.pale{opacity:.3}.dsa5 .tab.description.active{display:flex;flex-flow:column;height:calc(100% - 129px);overflow-y:hidden}.dsa5 .tab.description.active .editor{height:100%}.dsa5.item-sheet img{max-height:50px;max-width:50px;margin-top:5px;border-color:rgba(0,0,0,0)}.dsa5.item-sheet img.fullImg{width:100%;max-width:initial;max-height:initial}.dsa5.item textarea{padding:1px 3px}.dsa5 .editor{border:none;overflow:auto;flex-grow:1;display:flex;padding:3px;margin-top:0px;margin-bottom:7px;height:100%;width:100%}.hovermenu{display:inline-block;position:absolute;top:2px;right:3px;z-index:1;cursor:pointer}.hovermenu i{color:var(--border-color);padding:2px}.hovermenu i:hover{color:#3f3636}.notes-box{min-height:70px}.item-box{min-height:30px}.character-sheet nav.sheet-tabs,.creature-sheet nav.sheet-tabs,.npc-sheet nav.sheet-tabs{margin-bottom:20px}.character-sheet .general,.npc-sheet .general,.creature-sheet .general{display:flex;flex-direction:row;width:100%;margin:0}#field-distinguishingmark{width:calc(50% - 15px)}.sheet-header{margin-bottom:10px}.actor .sheet-header .entity-link{padding:0;border:none;background:none}table.infoTable{width:100%}table.infoTable tr td:first-child{width:15%}.creature-sheet .headerInput,.sheet-header .headerInput,.npc-sheet .general .headerInput,.sheet-header .headerInput,.character-sheet .general .headerInput,.character-sheet .sheet-header .headerInput{box-sizing:border-box;margin:5px}.npc-sheet .general .headerInput input,.sheet-header .headerInput input,.creature-sheet .headerInput input,.sheet-header .headerInput input,.character-sheet .general .headerInput input,.sheet-header .headerInput input{border:none;border-bottom:1px solid var(--border-color);box-shadow:none;background-color:rgba(0,0,0,0);border-radius:0px;height:auto}.creature-sheet .headerInput span,.sheet-header .headerInput span,.npc-sheet .general .headerInput span,.sheet-header .headerInput span,.character-sheet .general .headerInput span,.sheet-header .headerInput span{color:#333;margin-left:4px;margin-bottom:2px;font-size:12px}.item form .form-group input[type=checkbox]{flex:3}.form-group.full-height .editor,.form-group.full-height .tox{min-height:100px;flex-grow:3;border:1px solid var(--border-color);background-color:rgba(0,0,0,.05);margin:0}.dsa5.item form .form-group.autoHeight div{height:auto}.centerCell{display:flex;align-self:center}form .form-group.autoHeight label{align-self:stretch;vertical-align:middle}form .form-group.full-height label,form .form-group.full-height input{align-self:stretch;vertical-align:middle}form .form-group.full-height textarea{min-height:140px;font-size:14px}form .career .form-group.full-height textarea{min-height:80px}form .form-group.double span{flex:.9;display:inline;text-align:center}form .form-group.double .input-text{flex:1;display:inline;text-align:center}form .form-group.tripple .input-text{flex:2}form .form-group.doubleInput .input-text{flex:1.45}form .form-group div.input-text{padding:0 3px}form .form-group div.input-text ul{padding:0;margin:0}form .form-group.tripple select{flex:1;padding:0}.emphasize{color:#fff;background-color:darkred}.emphasize input::placeholder{color:#fff}input[type=text].emphasize{border-color:darkred}.emphasize2{color:#fff;background-color:#0a59c2}.maxMods{transition:background-color .3s linear}.charimg{width:115px;height:115px;object-fit:contain}.minimumColumnLayout .characteristics-table{min-width:unset}.characteristics-table{flex:6;display:block;min-width:var(--minColumnWidth60)}.characteristics-table.ctab2{flex:4;min-width:var(--minColumnWidth40)}.characteristics-table .table-data,.characteristics-table .table-header{flex:1}.characteristics-table .table-data:first-child,.characteristics-table .table-header:first-child{flex:2}.character-sheet .window-content{padding:0}.window-app .window-content select:not([multiple]) option{color:#fff;background:#1d1c1c}select[multiple] option{background-color:rgba(0,0,0,0)}select[multiple] option:checked{background-color:#12496c;color:#fff}.characteristics-table .table-row{text-align:center;width:100%;border-bottom:none;border-right:none;display:flex}.skills.body{background:#4f6d65;background:linear-gradient(90deg, rgb(79, 109, 101) 0%, rgba(255, 255, 255, 0) 100%)}.skills.social{background:#85302e;background:linear-gradient(90deg, rgb(133, 48, 46) 0%, rgba(255, 255, 255, 0) 100%)}.skills.knowledge{background:#4b6585;background:linear-gradient(90deg, rgb(75, 101, 133) 0%, rgba(255, 255, 255, 0) 100%)}.skills.trade{background:#cda25e;background:linear-gradient(90deg, rgb(205, 162, 94) 0%, rgba(255, 255, 255, 0) 100%)}.skills.nature{background:#535829;background:linear-gradient(90deg, rgb(83, 88, 41) 0%, rgba(255, 255, 255, 0) 100%)}.table-title,.label-text{font-weight:bold;font-family:var(--boldFont);background:#bc886f;background:linear-gradient(90deg, rgba(188, 136, 111, 0.8) 0%, rgba(255, 255, 255, 0) 100%)}.bookWizardsheet .window-content .table-title,.dsajournal .window-content .label-text,.bookWizardsheet .window-content table tr:first-child,.dsajournal .window-content table tr:first-child{font-weight:bold;font-family:var(--boldFont);border-bottom-style:double;text-align:center;background:rgba(188,136,111,.3)}.bookWizardsheet .window-content table,.dsajournal .window-content table,.bookWizardsheet .window-content table tr,.dsajournal .window-content table tr,.bookWizardsheet .window-content table td,.dsajournal .window-content table td{border-color:var(--border-color)}.table-title{background:#bc886f;background:linear-gradient(90deg, rgb(188, 136, 111) 0%, rgba(255, 255, 255, 0) 100%);box-shadow:none}.table-header{font-weight:bold;font-family:var(--boldFont)}.skill-section{display:flex}.skill-select{display:inline-block}.skill-section .flexcolumn{flex:50%}#combat #combat-round .encounters{color:#444}#combat #combat-round .encounters h4,#combat #combat-round .encounters a{color:#444}#combat-tracker .token-effect{box-shadow:0px 0px 10px #000 inset}.tour .step-title{overflow:initial}.directory .directory-list .directory-item.folder .context{color:#000}.chat-buttons{float:right}.die-attack,.die-mu,.diet-mu:after{background-image:url("../../icons/dice/d20mu.svg");color:#fff}.die-kl,.diet-kl:after{background-image:url("../../icons/dice/d20kl.svg");color:#fff}.die-dodge,.die-parry,.die-in,.die-poison,.die-disease,.diet-in:after{background-image:url("../../icons/dice/d20in.svg");color:#fff}.die-ch,.diet-ch:after{background-image:url("../../icons/dice/d20ch.svg");color:#fff}.die-ff,.diet-ff:after{background-image:url("../../icons/dice/d20ff.svg")}.die-ge,.diet-ge:after{background-image:url("../../icons/dice/d20ge.svg")}.die-ko,.diet-ko:after{background-image:url("../../icons/dice/d20ko.svg")}.die-kk,.diet-kk:after{background-image:url("../../icons/dice/d20kk.svg")}.d20height{line-height:35px}.skills .d20:after{content:"";position:absolute;top:0;left:0;right:0;bottom:0;opacity:.35;background-size:contain;background-position:center;background-repeat:no-repeat}.d6.die-AsP{background-position:center 2.5px;background-image:url("../../icons/dice/d6blue.svg")}.d6.die-LeP{color:#fff;background-position:center 2.5px;background-image:url("../../icons/dice/d6red.svg")}.d6.die-KaP{color:#fff;background-position:center 2.5px;background-image:url("../../icons/dice/d6green.svg")}.d6.die-effect,.d6.die-damage{background-image:url("../../icons/dice/d6white.svg");background-position:center 2.5px;color:#fff}.d2.die-damage,.d3.die-damage{background-image:url("../../icons/dice/d6white.svg");background-position:center 2.5px;color:#fff}.dice-tooltip .dice-rolls .roll.die{line-height:35px}.d20,.d6,.d2,.d3{font-family:"GentiumBasic-Bold";width:35px;height:35px;display:inline-block;background-size:contain;line-height:35px;text-align:center;background-position:calc(50% + 1px);background-repeat:no-repeat}.skills .d20{width:22px;height:22px;line-height:22px;font-size:10px;position:relative;display:inline-block}.rollButton .d20,.reactClick .d20{width:30px;height:30px;line-height:30px;font-size:12px;float:right}.rollButton .d20{float:left}.chatmoney{width:15px;height:15px;display:inline-block}input[type=text].col-Money-D{color:#927c01}input[type=text].col-Money-S{color:#474444}input[type=text].col-Money-K{color:#9c5e5e}input[type=text].col-Money-H{color:#944b32}.Money-D,.money-D{background:url("../../icons/money-D.webp");background-repeat:no-repeat;background-size:contain}.Money-K,.money-K{background:url("../../icons/money-K.webp");background-repeat:no-repeat;background-size:contain}.Money-S,.money-S{background:url("../../icons/money-S.webp");background-repeat:no-repeat;background-size:contain}.Money-H,.money-H{background:url("../../icons/money-H.webp");background-repeat:no-repeat;background-size:contain}.chatLineHeight{line-height:15px;display:inline-block}.cards{padding:3px}.cards>div{margin:1px;flex-grow:1;position:relative}.cards .item{box-shadow:0 0 12px rgba(110,59,1,.5607843137) inset}.cards a{padding:4px;border-radius:2px;width:100%;display:inline-block;text-align:center}.cards a.onUseItem,.cards a.traditionPayCost{width:28px;box-shadow:none}.cards a.onUseItem+a,.cards a.traditionPayCost+a{width:calc(100% - 28px)}.main-row{display:flex;width:100%;flex:1}.row-section{display:flex}.row-section.wrap{flex-wrap:wrap}.row-section .col{flex:100%}.row-section .col.libItem{margin-top:30px;padding:10px;border-radius:10px;background-color:rgba(0,0,0,.05);border:1px solid var(--border-color)}.row-section .col.morph{flex:50%;min-width:var(--minColumnWidth)}.row-section .col.morph40{flex:40%;min-width:var(--minColumnWidth40)}.row-section .col.morph60{flex:60%}.row-section.filterfull .col.morph{flex:100%}.row-section.skills{border:.5px solid var(--border-color);margin:0;padding:2px}.reverseFlex{flex-flow:row-reverse}.reverseColumnFlex{flex-flow:column-reverse}.thinscroll::-webkit-scrollbar{width:6px}.thinscroll{scrollbar-width:thin}.columnFlex{flex-flow:column;align-items:stretch}.skills span{margin:0}.lineheight{line-height:26px}.item .image{height:30px;background-size:contain;background-repeat:no-repeat;background-position:4px 0px}.inventory{line-height:30px}.row-section .col.three{flex:30%}.row-section .col.four{flex:25%}.row-section .col.thirtyfive{flex:35%}.row-section .col.fourtyfive{flex:45%}.row-section .col.five{flex:20%}.row-section .col.eight{flex:12.5%}.row-section .col.ten{flex:10%}.row-section .col.zerofive{flex:5%}.row-section .col.col95{flex:95%}.row-section .col.fourty{flex:40%}.row-section .col.third{flex:30%}.row-section .col.ninety{flex:90%}.row-section .col.eighty{flex:80%}.row-section .col.eighty.fixed{position:relative;max-width:80%;overflow:hidden}.row-section .col.eighty.fixed:hover{overflow:visible;z-index:50}.row-section .col.seventy{flex:70%}.row-section .col.fifteen{flex:15%}.row-section .col.sixty{flex:60%}.row-section .col.seventeen{flex:17.5%}.row-section .col.two{flex:50%;max-width:50%}.max20{max-width:20%}.groupbox{border:1px solid var(--border-color);border-radius:3px;margin:10px 2px;min-height:50px}.header-label{text-align:center;height:100%}.center{text-align:center}.right{text-align:right}.very-small{font-size:10px}.inventory .very-small{line-height:14px}.small{font-size:12px}.selectableRow{border:1px solid #000;cursor:pointer}.row-section.selectableRow.tableOdd:hover{background-color:#fff}.selectableRow:hover{background-color:#fff}.selectableRow.selected{box-shadow:inset 0px 0px 10px 5px rgba(188,136,111,.8)}a.img-entity-link{border:none;background:none;display:block}a.img-entity-link:hover{background:#fff}.row-section .twoColors:nth-child(4n-1),.row-section .twoColors:nth-child(4n){background-color:rgba(0,0,0,.1)}.row-section.rowColors:nth-child(odd),.row-section.tableOdd:nth-child(even){background-color:rgba(0,0,0,.1)}.col.morph .tableOdd:nth-child(even){background-color:rgba(0,0,0,.1)}.row-section.inverseRowtable>.col:nth-child(odd),.row-section.rowtable>.col:nth-child(even){background-color:rgba(0,0,0,.1)}.advance{color:rgba(51,48,41,.6509803922);margin-left:4px;font-size:8px;line-height:8px}.combat-actions{display:flex;gap:5px;flex-wrap:wrap}.combat-actions .combat-action{display:block;color:rgba(51,48,41,0.6509803922);padding:1px 5px;border:1px solid rgba(51,48,41,0.6509803922);border-radius:5px}.row-section .col.combat-item-name{flex-grow:0}.buttons a .fas,.buttons a .fa{border-radius:100%;border:1px solid var(--border-color);padding:2px;color:rgba(51,48,41,.6509803922)}.lighticon{color:rgba(68,68,68,.65)}.button.green{background:#006f3d;background:linear-gradient(90deg, rgb(0, 38, 13) 0%, rgb(0, 111, 61) 100%);position:relative;color:#fff}.condition-toggle,.condition-edit,.ench,.spells .very-small a .fas,.inventory .very-small a .fas{padding:1px;border:none;color:var(--border-color)}::-webkit-scrollbar{width:14px}::-webkit-scrollbar-track{background:#111}::-webkit-scrollbar-thumb{background:#782e22;border:1px solid #111}.sidebar-tab ::-webkit-scrollbar-thumb{background:#782e22;border:1px solid #111}.sidebar-tab ::-webkit-scrollbar{width:8px}.sheet.journal-entry:not(.dsajournal) .sidebar.directory{background:rgba(0,0,0,.6)}.window-app.dsajournal .editor-content p{margin-right:10px}form.dsa5.item-sheet{padding-left:10px;padding-right:10px}.qOverlay{position:relative}.qOverlay .img{position:absolute;left:0;right:0;top:0;bottom:0;background-repeat:no-repeat;background-position:center;background-size:contain}.qOverlay .overlay{height:100%;width:100%;min-height:200px;line-height:200px;font-size:200px;opacity:.2}.dsalist li{width:100%}.statusEffectMenu,.dsalist li,#chat-form,.browser-item,.effect-change .key,.inputTooltipAvailable,.journalHeader,.tokenQuickHot>ul>li,.bags,.hero,.window-app .window-content{position:relative}#dice-config .window-content{position:unset}#client-settings section.content .settings-list{overflow-y:hidden;max-height:max-content}.form-group.full-height .editor.prosemirror,.editor.prosemirror{min-height:300px}.dsa5.item .item-header{background-size:100% 50px;background-repeat:no-repeat;height:50px}.dsa5.item .item-header h1{margin:0 10%;cursor:pointer}.dsa5.item div.item-header,.dsa5.item .item-header input{text-align:center;padding:8px;background:none;border:none}.item-main .row-section{margin-left:10px;font-size:12px}.item-main .col label,.item-main .col input{border:1px solid var(--border-color)}.item-main label{padding:6px;display:inline-block;width:100%;text-align:center}.item-main.noequipment{margin-top:15px}.dsa5.item .item-main input{margin:0;border-radius:0%;height:29px;margin:0;width:100%;text-align:center}.label-text{border:1px solid var(--border-color);padding:0px 6px;text-align:center}.form-group .label-text i{font-size:10px}.dsa5.item .input-text,.creature-sheet .input-text{border:1px solid var(--border-color);border-radius:0px;height:28px;text-align:center}.dsa5.item select,.creature-sheet select{height:28px;font-family:var(--normalFont);border-radius:0;text-align:center}.dsa5.item section.content{height:calc(100% - 140px)}.dsa5.item section.content .tab.active{height:100%}.directory .directory-list .directory-item.active{border-color:#000}.popoutImage{cursor:pointer}#combat li.combatant .token-initiative .initiative,#combat li.combatant .token-name{text-shadow:none}#combat li.combatant .roll{background-image:url("../../icons/dice/d6white.svg");position:relative}#combat li.combatant .roll:before{position:absolute;content:"6";color:#fff;left:0;right:0;top:-2px;bottom:0}#combat li.combatant .roll:hover{background-image:url("../../icons/dice/d6green.svg")}.window-content>section,.window-content>form{padding:12px}.window-content .dialog-content,.window-content .dialog-buttons{padding:12px}.imagebox{position:relative;height:95px;background-size:cover;display:inline-block}.itemLibrary .detailBox span,.itemLibrary .detailBox input{margin:1px 2px;width:calc(100% - 4px)}.cards-notification .icon,.didYouKnow img,fieldset,.app.sidebar-popout,.dsa5.item h1,.dsajournal img,.itemLibrary img,.charimg,.dsa5.post-item img{border:none}.dsajournal .heading.h3 a:before{content:"";font-family:"Font Awesome 6 Pro";font-weight:900;color:darkred;position:relative;left:-5px}.defender video{margin:5px 25%;border:none}.attacker video,.attacker img{margin:5px 25%;border:none}.defender img{margin:5px 25%;border:none}.sender-image{max-width:30px;height:30px;border:none}.message-sender.with-image{line-height:30px}#scenes .scene h3{text-shadow:none}#scenes .scene h3 a{border:1px solid #403d3d;background-color:rgba(0,0,0,.6);color:#fff;border-radius:10px;padding:0px 10px}#combat li.combatant.active{background:rgba(0,0,0,.1)}li.folder{margin-left:8px}.chatModifiers .expand-mods{float:right;font-size:10px}.expandDetails.shown{display:block}.expandDetails.shown .filterHide{display:block}.expandDetails ul{margin:0 0 .5em 0;list-style-type:none}.expandDetails li{display:inline-block;font-size:12px;margin-right:5px}.mayorAttributeBox{margin-top:10px;max-width:150px}.mayorAttributeBox input,.mayorAttributeBox span{width:35px;display:inline-block}.showAll .notLearned{display:flex}.setCustomPrice.edit .priceTag,.setCustomPrice .customPriceTag{display:none}.minimumColumnLayout .notOnMinimum,.onlySingleColumn,.singleColumnLayout .onlyMultiColumn,.tokenQuickHot .subbuttons .secondary.shown.dsahidden,.domainToggle,.locktrue .advance,.privateMessageIndicator .fas,.chatIndicator .fas,.combatant:not(.active) .aggroButton,.tocCollapsing.expanded .col.three *,.tokenQuickHot .subbuttons .secondary:not(.shown),.hero .details{display:none}[data-hide-damage=true] .damageSecret,[data-hide-damage=true] .die-damage{display:none}.dsahidden,.roll-dialog-tag,.expandDetails{display:none}.chatModifiers ul,.chatModifiers div{display:none}.generationWizard [data-tab=description] h2,.notLearned,.showAll .filterHide,.statusEffectMenu .filterHide,.filterHide{display:none}.singleColumnLayout .onlySingleColumn,.setCustomPrice.edit .customPriceTag{display:block}.row-section.skills.searchbox{margin-bottom:10px;font-weight:normal;color:#0e0c0c}.row-section.skills.searchbox input{display:inline-block;width:calc(100% - 20px)}input[type=search]{width:calc(100% - 2px);min-width:20px;height:26px;background:rgba(0,0,0,.05);padding:1px 3px;margin:0;color:#191813;font-family:inherit;font-size:inherit;text-align:inherit;line-height:inherit;border:1px solid #7a7971;border-radius:3px;-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text}.healthbar{height:24px;border:1px solid #615757;box-sizing:border-box;overflow:hidden;box-shadow:inset 0 0 10px #fff;position:relative;background:rgba(78,70,70,.5411764706)}.barLeft{border-top-left-radius:10px;border-bottom-left-radius:10px;border-right-width:0px}.barRight{border-top-right-radius:10px;border-bottom-right-radius:10px}.barRight.middle{border-radius:0px;border-right:none}.barRight .bar{width:calc(100%*var(--a)/var(--b))}.barLeft .bar{left:calc(100%*(1 - var(--a)/var(--b)));width:calc(100%*var(--a)/var(--b))}.barLeft.soloBar .bar{left:0;width:calc(100%*var(--a)/var(--b))}.bar{height:24px;width:100%;box-shadow:inset 0 0 10px #fff;position:absolute;z-index:0;top:0px;left:0px;transition:width .1s ease-in-out}.soloBar{border-top-right-radius:10px;border-bottom-right-radius:10px;border-right-width:1px}.barLabel{height:22px;padding:1px;text-align:center;box-sizing:border-box;color:#fff;position:relative;z-index:1;text-shadow:0px 0px 3px #000}.barLabel input{height:22px;line-height:22px;width:30px;display:inline-block;border:none;padding:0;margin:0;color:#fff;box-shadow:none;background:none;text-shadow:0px 0px 3px #000}.barLabel input:focus{box-shadow:none}.barLabel input:hover{background-color:rgba(0,0,0,.3)}.barLabel span{width:30px;display:inline-block}.soloBar .LeP{background:linear-gradient(90deg, rgb(101, 7, 7) 0%, rgb(207, 14, 14) 100%)}.LeP{background:#cf0e0e;background:linear-gradient(90deg, rgb(207, 14, 14) 0%, rgb(101, 7, 7) 100%)}.tempLeP{background:#fc8f2a;background:linear-gradient(90deg, rgb(252, 143, 42) 0%, rgb(182, 97, 1) 100%)}.AsP{background:#0e90cf;background:linear-gradient(90deg, rgb(11, 11, 217) 0%, rgb(14, 144, 207) 100%)}.KaP{background:#93cf0e;background:linear-gradient(90deg, rgb(4, 162, 54) 0%, rgb(147, 207, 14) 100%)}.schip{width:25px;height:25px;background-size:contain;background-repeat:no-repeat;display:inline-block}.schip.tiny{width:15px;height:15px}.schip:active,.schip:focus{box-shadow:none;border:none}.emptySchip{background-image:url("../../icons/gray_schip.webp")}.fullSchip{background-image:url("../../icons/schip.webp")}.sheet nav.sheet-tabs .item.active,.tabs .item.active{text-shadow:0 0 10px #bc886f,0 0 10px #bc886f;border-bottom:3px solid var(--border-color)}.sheet nav.sheet-tabs .item{padding:8px 12px 5px 12px;border-bottom:3px solid rgba(0,0,0,0)}.dieButton span{border:1px solid rgba(0,0,0,0)}.dieButton.dieSelected span{border:1px solid #000}.dsa5.item-sheet .statusEffect img,.statusEffect img{border:none;background:rgba(0,0,0,.3);height:28px;width:28px;margin:0}.diseases .statusEffect img{height:20px;width:20px;border:1px solid rgba(0,0,0,0)}.diseases .statusEffect img:hover{border-color:#000}.statusEffect{height:34px;line-height:34px}.statusEffectMenu ul{display:none;position:absolute;right:-10px;top:-10px;width:164px;border:1px solid #000;background:rgba(0,0,0,.7);padding:8px;margin:0;min-height:90px}.statusEffectMenu li.search{display:block;width:100%;margin-bottom:10px}.statusEffectMenu li.search input{color:#fff;width:80%}.statusEffectMenu li.search a{color:#fff;border:1px solid #fff;padding:3px;border-radius:2px}.form-group input::placeholder{color:#adaaaa}.statusEffectMenu li.search input::placeholder{color:#adaaaa}.statusEffectMenu li.search:hover{border-color:rgba(0,0,0,0)}.opposed-message{text-align:center}.statusEffectMenu li{display:inline-block;width:30px;height:30px;border:1px solid rgba(0,0,0,0)}.statusEffectMenu li:hover{border:1px solid #000}.statusEffectMenu img{width:30px;height:30px;border:none}.itemLibrary{padding:10px}.itemLibrary nav{line-height:20px;margin-bottom:10px}.itemLibrary nav img{position:relative;top:3px;margin-right:3px;min-width:20px}.itemLibrary ul{display:flex;flex-wrap:wrap;width:100%}.itemLibrary ul li.browser-item{list-style-type:none;flex:24%;display:inline-block;display:flex;line-height:26px;min-width:120px}.itemLibrary ul li.browser-item .priceDrag{padding-top:2px;min-width:30px;line-height:10px;font-size:10px;cursor:grab;text-overflow:ellipsis;overflow:hidden}.itemLibrary .item-list li.browser-item{flex:49%;border:1px solid #ddd;min-width:240px}.itemLibrary .item-list li.browser-item a{display:inline-block;padding:2px;width:calc(100% - 44px);height:40px;line-height:36px}.itemLibrary .item-list li.browser-item .image{height:40px;width:40px;display:inline-block;background-size:contain}.itemLibrary .categories li label{text-overflow:ellipsis;overflow:hidden;min-width:80px}.lineheight2{line-height:26px}.lineheight2 span{display:inline-block;vertical-align:middle;line-height:12px}.itemLibrary .item-list li a span{display:inline-block;vertical-align:middle;line-height:12px}.dsalist{list-style-type:none}.sheet.journal-entry.dsajournal .pages-list .directory-item .page-heading .page-heading{margin-left:10px}.dsajournal .heading.h2 a:before,.dsalist li::before{content:"";display:inline-block;height:10px;width:20px;position:absolute;left:-20px;top:2px;background-image:url("../../icons/dsalist.webp");background-size:contain;background-repeat:no-repeat}.chatImgPreview .image{width:60px;height:60px;background-size:contain;background-repeat:no-repeat;background-position:center;margin:0 auto}.dsajournal .heading.h2 a:before{position:relative;width:15px;left:-5px}.item .image.extension{height:auto;background-position:center;margin:4px}.extension{background-image:url("../../icons/categories/Spellextension.webp")}.extensions p{line-height:15px}.card-content input{width:30px;display:inline-block}.window-app.largeDialog .window-content .dialog-buttons{flex-grow:0;display:flex}.largeDialog button.default{background:rgba(0,0,0,.05);border:2px groove #c9c7b8}.largeDialog .row-section label{flex:1}.largeDialog .garadanb h2{margin-top:0}.largeDialog h2{margin-top:20px}.largeDialog h3{margin-top:10px}.largeDialog .sheet-tabs{height:32px;flex:0 0 32px;margin:4px 0;border-top:1px solid #b5b3a4;border-bottom:1px solid #b5b3a4}.largeDialog .sheet-tabs .item{padding:8px 12px 5px 12px;border-bottom:2px solid rgba(0,0,0,0)}.largeDialog .show-item{display:inline-block;font-size:10px;border:1px solid #a09494;border-radius:100%;width:20px;height:20px;line-height:18px;color:#5a5a5a;text-align:center}.largeDialog img{border:none;margin-bottom:10px}.largeDialog .error{width:100%}.largeDialog .error p{background:#970808;color:#fff}.chatButton,.roll-button{border:1px solid var(--border-color);padding:2px;border-radius:3px;box-shadow:0 0 12px rgba(110,59,1,.5607843137) inset;display:inline-block}.chatButton img{display:inline-block;margin:0;margin-right:4px;width:15px;height:15px;background:#000;position:relative;top:2px}h2 .chatButton img{width:30px;height:30px;top:5px}h2 .chat-condition,h2 .chatButton{width:100%;border:none;box-shadow:none;background:none}.chatButton i,.roll-button i{margin-right:1px}.botch-roll{color:darkred}.detailbox{border:1px solid var(--border-color);padding:5px}.quickfind{position:absolute;background-image:url("../../icons/backgrounds/quickfind.webp");background-size:100%;background-repeat:no-repeat;background-position:top;padding:15px;padding-top:74px;bottom:100%;width:100%;color:#000;line-height:26px}.quickfind ul{list-style-type:none;margin:0}.quickfind li{padding:0px 4px;display:inline-block;border:2px solid rgba(0,0,0,0);width:100%}.quickfind li:hover{background-color:rgba(0,0,0,.2);text-shadow:none}.quickfind li:before{height:22px;background-position:center}.quickfind li.focus{border:2px solid #946603;border-radius:2px}.fokusregel{width:100px;float:right;background-image:url("../../icons/fokus.webp");background-size:100%;background-repeat:no-repeat;height:72px;text-align:center;line-height:72px;font-family:"Andalus";color:darkred;position:relative;margin-bottom:10px;font-weight:bold}.fokusregel:after{position:absolute;font-size:28px;bottom:0;left:0;right:0}.fokusregel.f1:after{content:"I"}.fokusregel.f2:after{content:"II"}.magazinContainer{display:inline-block;width:3px}.initTracker .item-structure{top:-102%;border-color:#0e0c0c}.item-structure{border:.5px solid var(--bg-color);height:100%;width:4px;position:relative}.item-structure .inner{position:absolute;left:0;right:0;bottom:0;height:calc(100%*var(--b)/var(--a));background-color:#20ca02}a.documentName-link,a.inline-roll{background:var(--bg-color)}.whisper .privateMessageIndicator .fas{display:inline-block;color:#730707}.blind .chatIndicator .fa-eye-slash{display:inline-block;color:#2248a2}#token-hud .attribute.bar1 input{border:1px solid #e60c0c}#token-hud .attribute.bar2 input{border:1px solid #659db5}#token-hud .attribute.bar3{position:absolute;top:-45px}#token-hud .attribute.bar3 input{border:1px solid #7cd000}.specAbsContainer{margin-left:20px;padding:10px}.specAbs{border:1px solid var(--border-color);box-shadow:0 0 12px rgba(110,59,1,.5607843137) inset;border-radius:2px;line-height:20px;color:#888;position:relative}.specAbs>div{padding:3px}.specAbs.active{color:inherit}.specAbs .variantChange{text-align:center;border:1px solid var(--border-color);border-radius:50%;background-color:#5b260c;position:absolute;left:-16px;top:calc(50% - 10px);width:20px;height:20px;line-height:20px;color:#fff;padding:0;transition:all ease-in-out .3s}.specAbs .variantChange:hover{background-color:#000}.noBorder,.bookWizardsheet .window-content .table-title.noBorder,.dialog-buttons img,.result-image{border:none}.bookWizardsheet .sheet.journal-entry .pages-list .heading-link{line-height:inherit}.bookWizardsheet .sheet.journal-entry .pages-list .headings{display:block;font-family:var(--normalFont);margin:6px 0 0 3px;--level-indent: 8px}.bookWizardsheet .sheet.journal-entry .pages-list .headings li{line-height:inherit;height:auto}.libraryImg,.extImg{background-image:url("../../icons/categories/ability_combat.webp");background-size:contain;background-repeat:no-repeat;background-position:center}.specImg{background-image:url("../../icons/categories/ability_combat.webp");background-size:contain;background-repeat:no-repeat;background-position:center}.specImg.ab_1{background-image:url("../../icons/categories/Combat_Skill.webp")}.specImg.ab_2{background-image:url("../../icons/categories/Skill.webp")}.specImg.ab_3{background-image:url("../../icons/categories/Armor.webp")}.specImg.ab_4{background-image:url("../../icons/categories/ability_general.webp")}.libraryImg{background-image:url("../../icons/backgrounds/library.webp");margin-top:50px;height:300px}.extImg{background-image:url("../../icons/categories/Spellextension.webp")}.embeddedItemDrag,.rollTarget{cursor:pointer}.specAbs:hover{cursor:pointer}.specAbs.active{border-color:#cf1e1e}#chat-controls .control-buttons{flex:0 0 72px}.centerMargin,.loader{margin:0 auto}.libItem .compendium{font-size:10px;color:#696767;line-height:10px;text-align:center;pointer-events:none}.browser-item:hover{box-shadow:inset 0px 0px 5px #000}.browser-item a:hover{text-shadow:none}.browser-item .compendium{position:absolute;bottom:2px;right:2px;font-size:10px;color:#696767;line-height:10px}.chat-condition,.item-sheet .chatButton,.dsajournal .chatButton{padding:0px 4px;border:1px solid #4b4a44;border-radius:2px;white-space:nowrap;word-break:break-all;box-shadow:none;background:var(--bg-color);display:inline}.chat-condition img,.item-sheet .chatButton img,.dsajournal .chatButton img{top:3px}.obfuscationBtn:nth-of-type(2){display:none}.chatpaperfield{border-image:url("../../icons/backgrounds/chatpaper_v45.webp");clear:both;border-image-width:24px;border-image-slice:70 70 70 fill;margin:25px 0px;padding:20px 20px 20px 30px}.maskfield{position:relative;clear:both;padding:70px 30px 30px 30px;margin:34px 0px;border-image:url("../../icons/backgrounds/maskfield_v45.webp");border-image-width:60px 20px 60px 20px;border-image-slice:90 30 90 30 fill}.citefield{position:relative;clear:both;padding:30px;margin:25px 0px;border-image:url("../../icons/backgrounds/cite_v45.webp");border-image-width:60px 20px 60px 20px;border-image-slice:90 30 90 30 fill}.dsajournal .window-content .maskfield tr:first-child{background:none}.nobr{white-space:nowrap}select.noAppearance{-webkit-appearance:none;appearance:none;height:auto;text-align:center;width:100%}.aggroButton{border-radius:100%;padding:3px;display:block;width:24px;position:absolute;left:-20px;height:24px;margin-top:12px;border:1px solid darkred;background-color:#fff;cursor:pointer;box-shadow:2px 2px 6px #000;z-index:1}.aggroButton:hover{background-color:#d1d1ca}#combat-popout.combat-sidebar li.combatant .token-initiative .initiative,#combat-popout.combat-sidebar li.combatant .token-name{text-shadow:none}#combat-popout .aggroButton{left:-1px}.adventurePoints .row-section:hover{background-color:rgba(0,0,0,.2)}.adventurePoints .fa-plus,.adventurePoints .fa-angles-up{color:green}.adventurePoints .fa-minus,.adventurePoints .fa-angles-down{color:darkred}.effect-change .key input{width:90%}.effect-change .selMenu+.select2{width:8%;background:#efe4e4;position:absolute}.effect-change .selMenu+.select2 .select2-selection__rendered{width:0px;padding:0}.effect-change .selMenu+.select2.select2-container--open{width:100%;left:0}.effect-change .selMenu+.select2.select2-container--open .select2-selection__rendered{width:100%;padding:0}.gearDamaged,.resistEffect,.applyEffect,.applyTableEffect,.placeTemplate,.smallChatButton{width:100%;padding:4px;height:100%;line-height:unset;font-size:11px}.adventureWizard .fa-toggle-on,.adventureWizard .fa-check{color:green}.adventureWizard .fa-toggle-off,.adventureWizard .fa-times{color:darkred}.adventureWizard .toc{list-style-type:none;padding-left:4px}.adventureWizard .toc ul{list-style-type:none;padding-left:0px}.tocCollapsing.expanded .col.three{flex:20px}.tocCollapsing.expanded .col.seventy{flex:calc(100% - 20px)}.tocCollapserBox{position:relative;height:0}.tocCollapser{position:absolute;top:30px;left:-5px;font-size:10px}.getChapter.selected,.subChapter.selected{font-weight:bold}.inputTooltipAvailable:after{content:"*";position:absolute;right:3px;top:3px;font-size:10px;color:#82817d}.subChapter{font-weight:normal;font-family:var(--normalFont)}.toc ul li{display:block;padding:4px}.toc ul li:before{color:darkred;margin-right:5px}.adventureWizard .cover{width:98%;position:relative}.scrollable{overflow-y:auto;max-height:100%}.adventureWizard{max-height:100%}.adventureWizard>div{max-height:100%}.adventureWizard .chapter{padding:8px}.adventureWizard .chapter *{user-select:text}.adventureWizard .toc{scrollbar-width:6px}.adventureWizard .toc::-webkit-scrollbar{width:6px}.adventureWizard .picto{height:40px;line-height:40px}.adventureWizard .breadcrumbs{display:flex;background-color:rgba(202,183,180,.3803921569);border-radius:5px;border-bottom:1px solid #b5b3a4;border-top:1px solid #b5b3a4}.adventureWizard .breadcrumbs>div{flex:1;max-width:150px;min-width:150px;border-radius:5px;padding:3px;margin:1px;box-shadow:inset 0px 0px 3px #000;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:all .3s ease-in-out;text-align:center}.adventureWizard .breadcrumbs>div:hover{cursor:pointer;background-color:rgba(14,12,12,.3);color:#fff}.picto.ten{max-width:10%}.picto.fourty{max-width:40%}.journalHeader .jrnIcons{color:#5c5c5c;float:right}.journalHeader .jrnIcons a{display:inline-block;margin-right:10px}.position-relative{position:relative}.combatant-advanced{flex:0 0 48px;position:relative;height:50px}.combatant-advanced i{position:absolute;bottom:0;right:0;color:#000;width:14px}.combatant-advanced .actions,.combatant-advanced .ongoing{font-size:10px;background:#6f3900;width:14px;height:15px;padding:0;margin:0;line-height:15px;text-align:center;color:#fff;border-radius:50px;position:absolute;right:0;top:0}.combatant-advanced .actions{left:0;right:auto;background:#6d0400}.initTracker .combatant-advanced .actions{right:0;left:unset}.initTracker .combatant-advanced .ongoing{bottom:4px;top:unset}.combatant-advanced i.reversed{transform:scaleX(-1)}.combatant-advanced i.def:after{content:attr(data-defenseCount);position:absolute;left:0;right:0;text-align:center;z-index:1;color:#fff;font-size:10px;line-height:12px}.initTracker .combatant-advanced{height:var(--iniTrackerSize)}.initTracker .combatant-advanced i{left:4px;bottom:4px;right:unset}.tinyEntityLink a{width:22px;overflow:hidden;font-size:12px;float:right;overflow:hidden;border:1px solid #000}.tokenQuickHot{position:absolute;top:0;height:var(--tokenQuickhotsize);left:5px;right:7px;z-index:-2;transition:transform .3s ease-in-out}.tokenQuickHot ul{font-size:0;display:inline-block}.tokenQuickHot.expanded{transform:translateY(-45px)}.tokenQuickHot .subbuttons{position:absolute;z-index:2}#controls ol li.control-tool[data-tool=targetUser]{color:#609ec6}.tokenQuickHot .direction0 .subbuttons{bottom:var(--tokenQuickhotdistance)}.tokenQuickHot .direction1 .subbuttons{right:var(--tokenQuickhotdistance)}.tokenQuickHot .direction2 .subbuttons{top:var(--tokenQuickhotdistance)}.tokenQuickHot .direction3 .subbuttons{left:var(--tokenQuickhotdistance)}.tokenQuickHot .direction1 .dragHandler,.tokenQuickHot .direction3 .dragHandler{height:14px;width:var(--tokenQuickhotsize);line-height:14px}.initTracker .dragHandler,.tokenQuickHot .dragHandler{width:14px;height:var(--tokenQuickhotsize);background:rgba(0,0,0,.2);text-align:center;line-height:var(--tokenQuickhotsize);float:right}.initTracker .dragHandler:hover{color:#fff}.tokenQuickHot .dragHandler:hover{color:#fff}.tokenQuickHot a{box-shadow:inset 0px 0px 10px #403014;color:#fff;padding:2px;margin-bottom:2px}.tokenQuickHot .effect>div{background-color:rgba(0,0,0,.3)}.initTracker li,.tokenQuickHot li{background-color:rgba(0,0,0,.5);display:inline-block;font-size:14px;width:var(--tokenQuickhotsize);height:var(--tokenQuickhotsize);border:1px solid #000;border-radius:3px;pointer-events:all;background-size:cover;box-shadow:inset 0px 0px 5px #636363;background-repeat:no-repeat;position:relative;box-sizing:border-box}.tokenQuickHot li input{color:#fff}.tokenQuickHot li .subbuttons li{width:200px;height:28px;line-height:28px}.initTracker .waitingTackerList li{width:calc(var(--iniTrackerSize)*.5);height:calc(var(--iniTrackerSize)*.5)}.waitingTackerList{position:absolute;top:calc(var(--iniTrackerSize)*-0.5);left:30px;z-index:-1}.initTracker .newRound{border-color:#496fd7;background-color:rgba(73,111,215,.1764705882);box-shadow:inset 0px 0px 10px #496fd7;border-top-left-radius:0px;border-bottom-left-radius:0px}.initTracker .turnRound{padding:2px;border-radius:100%;width:21px;display:inline-block}.initTracker .newRound .turnRound{background-color:#496fd7}.initTracker .waitTitle{background-image:none}.initTracker .waitTitle i{float:left;width:100%;line-height:calc(var(--iniTrackerSize)*.5);text-align:center;color:#fff}.initTracker li{box-shadow:none;border:1px solid rgba(0,0,0,0);background-color:rgba(0,0,0,0);cursor:pointer;background-color:rgba(0,0,0,.5);border-radius:10px}.initTracker li .roll:before{position:absolute;content:"6";color:#fff;left:0;right:0;top:5px;bottom:0;text-align:center}.initTracker .token-initiative{position:absolute;bottom:-20px;left:0;right:0}.initTracker .aggroButton{left:0;right:0;margin:0 auto 0;bottom:0}.initTracker li .roll{position:relative;display:block;width:30px;height:30px;background:url("../../icons/dice/d6white.svg") no-repeat 50% 50%;background-size:auto;background-size:35px;margin:0 auto}.initTracker li.active{border-color:#fff;box-shadow:inset 0px 0px 10px #fff}.initTracker li.defeated,.initTracker li.hidden{opacity:.5}.initTracker li.defeated{background-size:75% 75%;background-position:center}.iniTrackerList{margin:0;padding:0;display:inline-block}.initTracker .dragHandler{width:15px;background:none;border:none;line-height:var(--iniTrackerSize)}.initTracker li{width:var(--iniTrackerSize);height:var(--iniTrackerSize)}#hotbar .skillItems li:hover,.tokenQuickHot li:hover{border:1px solid red;cursor:pointer}.tokenStatusEffects .dialog-content{height:100%;min-height:calc(100% - 24px)}.tokenQuickHot .tokenHotbarInner{opacity:var(--tokenHotbarOpacity);transition:opacity .3s ease-in-out}.tokenQuickHot .tokenHotbarInner:hover{opacity:1}.tokenQuickHot .tokenHotbarInner .skillgm.body,.tokenQuickHot .tokenHotbarInner .skill.body{background:#4f6d65;box-shadow:none;background:linear-gradient(90deg, rgb(79, 109, 101) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.social,.tokenQuickHot .tokenHotbarInner .skill.social{background:#85302e;box-shadow:none;background:linear-gradient(90deg, rgb(133, 48, 46) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.knowledge,.tokenQuickHot .tokenHotbarInner .skill.knowledge{background:#4b6585;box-shadow:none;background:linear-gradient(90deg, rgb(75, 101, 133) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.trade,.tokenQuickHot .tokenHotbarInner .skill.trade{background:#cda25e;box-shadow:none;background:linear-gradient(90deg, rgb(205, 162, 94) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.nature,.tokenQuickHot .tokenHotbarInner .skill.nature{background:#535829;box-shadow:none;background:linear-gradient(90deg, rgb(83, 88, 41) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner div{background-size:cover;height:100%;width:100%;position:absolute;color:#fff;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000}.tokenQuickHot .tokenHotbarInner input{height:var(--tokenQuickhotsize);display:block;width:100%;margin:0;float:left;text-align:center;font-size:20px;border:none}.tokenQuickHot .tokenHotbarInner .itdarkness{width:calc(var(--tokenQuickhotsize)*2);position:relative}.tokenQuickHot .tokenHotbarInner .itdarkness input{height:auto;position:absolute;bottom:0}.tokenQuickHot .tokenHotbarInner .itdarkness i{position:absolute;top:4px;left:6px;color:#8a6100}.tokenQuickHot .tokenHotbarInner .itdarkness i.fa-moon{color:#05235b;right:6px;left:unset}.tokenQuickHot .tokenHotbarInner .subbuttons .combatTooltip{height:35px;line-height:35px;text-align:center;width:100px}.tokenQuickHot .tokenHotbarInner .subbuttons div{background-size:contain;background-repeat:no-repeat;background-position:center;width:30px;position:inherit;float:left}.tokenQuickHot .tokenHotbarInner .subbuttons label{display:inline-block;cursor:pointer;overflow:hidden;max-width:155px;text-overflow:ellipsis;white-space:nowrap}.tokenQuickHot li span{position:absolute;top:-25px;left:-73px;background:#1d1c1c;width:180px;display:inline-block;color:#fff;padding:5px;text-align:center;border-radius:4px}.tokenQuickHot li .fa{font-size:calc(var(--tokenQuickhotsize) - 15px);line-height:var(--tokenQuickhotsize);text-align:center}.tokenQuickHot li.spell{box-shadow:inset 0px 0px 10px #121092}.tokenQuickHot li.skill{box-shadow:inset 0px 0px 10px #0d813e}.window-app.initTracker .window-header,.window-app.tokenQuickHot .window-header{display:none}.window-app.initTracker,.window-app.tokenQuickHot{padding:0}.initTracker .controls{display:inline-block;width:29px}.initTracker:hover .iniDetailsList{display:block}.iniDetailsList{margin:30px 29px 0 29px;padding:0;display:none}.iniDetailsList li{height:20px;text-align:center;background:rgba(0,0,0,.5);color:#fff}.initTracker .hoverbuttons{color:#fff;position:absolute;right:0;top:25%;opacity:0;transform:opacity .3s}.initTracker .combat-control{min-width:20px;display:inline-block}.initTracker li:hover .hoverbuttons{opacity:1}.initTracker .controls i{color:#fff;background:rgba(0,0,0,.7);border-radius:5px}.initTracker .controls.right{text-align:right}.initTracker button{line-height:21px}.tokenHotbarInner>ul>li.effect>div:before{font-family:"Font Awesome 5 Free";font-weight:900;content:""}.window-app.initTracker::after,.window-app.initTracker .window-content{background:none;margin:0;padding:0;overflow:visible}.window-app.tokenQuickHot::after,.window-app.tokenQuickHot .window-content{background:none;margin:0;padding:0;overflow:visible}.window-app.initTracker::after,.window-app.tokenQuickHot::after{content:none}.ench-fw{position:relative;top:-3px}.bags .slot{width:50px;height:50px;background-size:contain;border:1px solid var(--border-color);background-color:#faebd7;background-repeat:no-repeat;background-position:center;border-radius:5px;cursor:pointer}.bags .slot.deactivated{opacity:.5}.bags .slot:hover{border-color:#0a59c2}.itemInfo{position:absolute;display:none;width:200px;border:1px solid var(--border-color);padding:5px;background-color:rgba(0,0,0,.8);color:#fff;border-radius:5px}.bagUsage{position:relative;border:1px solid var(--border-color);margin:5px;background-color:rgba(14,12,12,.1)}.bagUsage .fillage{position:absolute;top:0;left:0;bottom:0;background-color:#40a9dd}.bagUsage .fillage.exceeded{background-color:#d42d2d}.bagUsage .fillText{position:relative;z-index:1}.fa-dsa5-player,.fa-dsa5{position:relative;width:25px;height:25px}.fa-dsa5-player:before,.fa-dsa5:before{content:"";background-image:url("../../icons/categories/DSA-Auge.webp");background-size:contain;background-repeat:no-repeat;background-position:center;position:absolute;left:0;right:0;top:0;bottom:0}.fa-dsa5-player:before{background-image:url("../../icons/categories/DSA-Auge-Spieler.webp")}.columnFlex{display:flex;flex-direction:column}.verticalFlex{display:flex;flex-direction:row;position:relative}.verticalFlex .bar{flex:1;height:30%}.verticalFlex .bar.AsP{top:30%}.verticalFlex .bar.KaP{top:60%}.bar-wounds.swarmcount:after{content:"";position:absolute;top:0;left:0;right:0;bottom:0;background-image:linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 98%, rgba(0, 0, 0, 0.3) 100%);background-size:calc(100%/var(--swarm) + .1%) 100%;background-repeat:repeat-x}.hero.victim{box-shadow:inset 0px 0px 10px #8a0202}.smallBoxItem,.hero .actorItem{display:inline-block;padding:2px;border:1px solid var(--border-color);line-height:12px;border-radius:2px}.domainsPretty li{display:inline-block;border:ridge 2px #daa520;line-height:18px;border-radius:2px;margin:3px;padding:0px 8px;box-shadow:1px 1px 3px #000;background-color:#f4da99}.domainsPretty li.magical{border-color:#0a59c2;background-color:#c0dbff}.domainsPretty li.blessed{border-color:#006f3d;background-color:#bae1b1}#combat li.combatant .token-resource{color:#777171}.progress{width:27px;height:27px;line-height:27px;background:none;margin:0 auto;box-shadow:none;position:relative;float:right}.progress>span{width:50%;height:100%;overflow:hidden;position:absolute;top:0;z-index:1}.progress .progress-left{left:0}.progress .progress-bar{width:100%;height:100%;background:none;border-width:2px;border-style:solid;position:absolute;top:0}.progress .progress-left .progress-bar{left:100%;border-top-right-radius:13.5px;border-bottom-right-radius:13.5px;border-left:0;-webkit-transform-origin:center left;transform-origin:center left;transform:rotate(var(--transformLeft))}.progress .progress-right{right:0}.progress .progress-right .progress-bar{left:-100%;border-top-left-radius:13.5px;border-bottom-left-radius:13.5px;border-right:0;-webkit-transform-origin:center right;transform-origin:center right;transform:rotate(var(--transformRight))}.progress .progress-value{width:90%;height:90%;border-radius:50%;color:#44484b;font-size:8px;line-height:27px;text-align:center;position:absolute;top:5%;left:5%}.progress.blue .progress-bar{border-color:#0e4f79}.patchviewer h1{margin:0}.patchviewer h1 a{display:block;float:left;color:#000}.patchviewer h1 img{width:50px;margin:0;margin-right:15px;float:left}.patchviewer .table-title{border:1px solid var(--border-color);border-radius:10px}.noscrollWizard .content{overflow-y:hidden}.skill-test .targets{align-items:center;justify-content:center;margin-bottom:20px}.skill-test .targets .image{width:40px;height:40px;position:relative}.multipleTarget{margin-left:25px}.missingTarget{margin-left:25px}.missingTarget div i{color:darkred}.skill-test .targets div i{color:darkred}.targets .addTarget{margin-left:20px}.targetChoser .combatant{border:1px solid rgba(0,0,0,0)}.targetChoser .combatant.hidden{opacity:.5}.targetChoser .combatant:hover{background:rgba(0,0,0,.1)}.targetChoser .combatant.selectedTarget{border-color:#000}.multipleTarget i{color:#e68044}.skill-test .targets .image i{position:absolute;z-index:1;bottom:0;left:0;top:0;right:0}.libButton .label-text i{font-size:12px}.libButton .fa-toggle-off{color:darkred;margin-right:6px}.libButton .on .fa-toggle-off{color:green}.libButton .on .fa-toggle-off:before{content:""}.searchMatch{background-color:#ff0}.searchLines{position:absolute;top:0px;right:0;width:16px;bottom:0;pointer-events:none}.searchLines .marker{position:absolute;width:100%;height:2px;background-color:#fff;pointer-events:none}.tinyHudIcons{border:1px solid #000;margin-left:1px;width:40px;border-radius:5px;height:40px;background-image:url("../../icons/backgrounds/macrobg.webp");background-repeat:no-repeat}.advancedSearch .groupbox{margin:0;margin-right:10px;padding:3px}.advancedSearch .groupbox select{width:100%}.advancedSearch .groupbox .form-group{margin-top:4px}.advancedSearch .cbParent{line-height:24px}.advancedSearch .cbParent label{text-overflow:ellipsis}.advancedSearch input[type=checkbox]{float:right}input[type=checkbox].autoCheckbox{width:auto;height:auto}.slot,.gearD{z-index:0;position:relative}.item .image.rar,.item .image.common{z-index:0;position:relative}.gearD:before{content:"";background-size:contain;background-repeat:no-repeat;position:absolute;width:12px;height:12px;left:25px;bottom:0;z-index:1}.damaged1:before{background-image:url("../../icons/damaged1.webp")}.damaged2:before{background-image:url("../../icons/damaged2.webp")}.damaged3:before,.damaged4:before{background-image:url("../../icons/damaged3.webp")}.slot div{height:100%;background-size:contain}.damaged1 .slot.rar:after,.slot.common:after{content:"";background-image:url("../../icons/backgrounds/common.webp");background-size:contain;background-repeat:no-repeat;position:absolute;left:0;right:0;bottom:0;top:0;z-index:-1;opacity:.4}.image.rar:after,.image.common:after{content:"";background-image:url("../../icons/backgrounds/common.webp");background-size:contain;background-repeat:no-repeat;position:absolute;left:0;right:0;bottom:0;top:0;z-index:-1;opacity:.4}.image.rar:after,.image.common:after{background-position:4px 0px}.image.rar:after{background-image:url("../../icons/backgrounds/rar.webp");opacity:.7}.defenseToggle .off{color:#d3d3d3}.garadanborder{max-width:80%;border-image-source:url("../../icons/backgrounds/garadanborder.webp");clear:both;border-image-width:16px;border-image-slice:16 5 33 5 fill;margin:0 auto}.garadanborder .innersection{padding-bottom:20px}.garadanb.garadanborder,.garadanb{max-width:100%;border-image-width:16px;border-image-slice:30 5 50 5 fill;text-align:center;font-weight:bold;letter-spacing:1px}.garadanb.garadanborder *,.garadanb *{border:none}.garadanb.garadanborder small,.garadanb small{font-size:smaller;line-height:auto;font-weight:normal;letter-spacing:0px;margin:0;padding:0}.garadanb{padding-bottom:30px;border-image-source:url("../../icons/backgrounds/garadanb.webp")}.garadanb.garadanborder{position:initial;border-image-slice:16 5 33 5 fill;padding-bottom:0px;border-image-source:url("../../icons/backgrounds/garadanborder.webp")}.garadanicon{background-repeat:no-repeat;background-size:contain;height:55px;margin-left:55%;margin-top:12px;background-position:center;width:55px}.garjourn{display:inline-block;width:15px;height:15px;background-size:contain;background-repeat:no-repeat;margin-left:3px;margin-right:3px}.garjourn.boronsrad{background-image:url("../../icons/Garadan6.webp")}.garjourn.koenig{background-image:url("../../icons/KoenigIcon.webp")}.garjourn.springer{background-image:url("../../icons/SpringerIcon.webp")}.garjourn.turm{background-image:url("../../icons/TurmIcon.webp")}.garjourn.bauer{background-image:url("../../icons/BauerIcon.webp")}.journal-picto{display:inline-block;position:relative;min-width:20px;margin-left:5px}.journal-picto:before{content:"";position:absolute;bottom:0;top:0;left:0;right:0;background-repeat:no-repeat;background-position:center;background-size:contain}.garadanborder h2{text-decoration:none;border:none;margin:0;margin-top:0px;margin-top:20px;font-size:24px;line-height:24px}.garadanborder h3{margin:0;border:none;font-size:14px}.reactClick{margin:2px}.reactClick img{width:26px;float:left;border:none}.didYouKnow,.tinyNotifications li{background-color:rgba(0,0,0,.548);color:#fff;border-radius:10px;padding:10px}.bumFight,.didYouKnow{position:fixed;top:40%;left:calc(50% - 200px);z-index:1002;width:400px;display:none}.bumFight .col.five,.didYouKnow .col.five{display:flex;justify-content:center;align-items:center}.bumFight{display:block;transition:all 2s ease;width:500px;left:calc(50% - 250px);top:20%}.bumFight .intererior{position:absolute;top:calc(50% - 175px);left:0;bottom:0;right:0}.bumFight .fist{border:none;width:250px;height:250px;margin-left:110px;margin-top:80px;position:relative;z-index:-1;animation:bumAnimation .5s cubic-bezier(0.64, 0, 0.78, 0) 0s 1 normal forwards,bumAnimation2 .7s cubic-bezier(0.64, 0, 0.78, 0) .5s 1 normal forwards}.bumFight .title{border-bottom:none;text-align:center;font-size:40px;position:relative;z-index:1;background:url("../../../../ui/pausebg.png") no-repeat 50% 50%;color:#fff;border-radius:10px;padding:10px;text-shadow:#000;animation:bumAnimation .5s cubic-bezier(0.64, 0, 0.78, 0) 0s 1 normal forwards,bumAnimation2 .7s cubic-bezier(0.64, 0, 0.78, 0) .5s 1 normal forwards}.bumFight .glass{border:none;width:500px;height:500px;opacity:0;animation:windowAnim .5s cubic-bezier(0.64, 0, 0.78, 0) 0s 1 normal forwards}@keyframes bumAnimation{0%{transform:scale(0);opacity:0}50%{opacity:1}100%{transform:scale(1)}}@keyframes windowAnim{0%{opacity:0}99%{opacity:0}100%{opacity:1}}@keyframes bumAnimation2{0%{animation-timing-function:ease-out;transform:scale(1);transform-origin:center center}10%{animation-timing-function:ease-in;transform:scale(0.91)}17%{animation-timing-function:ease-out;transform:scale(0.98)}33%{animation-timing-function:ease-in;transform:scale(0.87)}45%{animation-timing-function:ease-out;transform:scale(1)}}.flexAlignCenter{justify-content:center;align-items:center}.settings-sidebar button{margin:3px 0}#sidebar{overflow:visible}.plantContainer{display:inline-block;position:relative;cursor:pointer;height:45px;width:45px}.plantContainer input{position:absolute;opacity:0;height:45px;width:45px}.plantContainer span{position:absolute;top:0;left:0;height:45px;width:45px;background:url("../../icons/categories/planthealing.webp");background-position:center;background-size:contain;background-repeat:no-repeat;opacity:.45;transition:all .3s ease-in-out}.plantContainer.defensive span{background-image:url("../../icons/categories/plantdefensive.webp")}.plantContainer.psychic span{background-image:url("../../icons/categories/plantpsychic.webp")}.plantContainer.physical span{background-image:url("../../icons/categories/plantphysical.webp")}.plantContainer.crop span{background-image:url("../../icons/categories/plantcrop.webp")}.plantContainer.poison span{background-image:url("../../icons/categories/plantpoison.webp")}.plantContainer.supernatural span{background-image:url("../../icons/categories/plantsupernatural.webp")}.plantContainer:hover input~span,.plantContainer input:checked~span{opacity:1}.tinyNotifications{position:fixed;top:calc(100% - 250px);left:50px;list-style:none;margin:0;padding:0;z-index:160}.fxmaster .window-content .directory-item .config input[type=text]{color:#000}.ammo-selector{width:calc(100% - 31px);padding:0px;margin:0px 1px}.window-app .condition-show{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.panToToken{cursor:pointer}.panToToken:hover{box-shadow:inset 0px 0px 5px #000}.rowHover:hover{box-shadow:inset 0px 0px 5px #000}#sidebar,#players,#hotbar{position:relative}.effect-change input::placeholder{color:#a9a7a0}.select2-results__option[role=group]:hover{background-color:rgba(0,0,0,0)}.postChatSection.maskfield:after{background-image:url("../../icons/backgrounds/blackbook.webp");background-size:250px 30px;background-position:center calc(100% - 8px)}.postChatSection .postContentChat{cursor:pointer}.postChatSection .postContentChat em{padding:5px;border-radius:50%;transition:.3s ease-in-out all}.postChatSection .postContentChat:hover em{background-color:#fff;color:#000}.navWrapper{position:relative}.navWrapper .sheet-tabs{white-space:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar;scrollbar-width:none;user-select:none;scroll-behavior:smooth}.navWrapper .sheet-tabs::-webkit-scrollbar{display:none}.navWrapper .sheet-tabs.dragging{scroll-behavior:unset;cursor:grab}.navWrapper .sheet-tabs.dragging.left-btn,.navWrapper .sheet-tabs.dragging.right-btn{pointer-events:none}.navWrapper .tabs{justify-content:initial}.navWrapper .tabs .item{flex:1}.navWrapper .right-btn,.navWrapper .left-btn{position:absolute;font-size:1.4em;cursor:pointer;padding:8px;color:#756c6c;display:none;backdrop-filter:blur(10px)}.navWrapper .right-btn{right:0}.navWrapper .left-btn{left:0}.itemTooltip h1{border:none;font-size:22px;line-height:26px}.itemTooltip .col{flex:50%}.itemTooltip .show-item{display:none}#hotbar.hotbarV3{margin-bottom:0}#hotbar.hotbarV3 .sections{max-height:90px;height:90px;background-color:rgba(0,0,0,.5)}#hotbar.hotbarV3 .categoryFilters{height:30px}#hotbar.hotbarV3 .actorEffects{align-items:flex-end}#hotbar.hotbarV3 .function{color:#fff;right:0}#hotbar.hotbarV3 li,#hotbar.hotbarV3 ul{margin:0;padding:0;list-style:none}#hotbar.hotbarV3 li .fa{font-size:30px;line-height:45px;text-align:center}#hotbar.hotbarV3 .actorEffect:first-child{margin-left:auto}#hotbar.hotbarV3 .actorEffect div{width:28px;height:28px;background-size:contain}#hotbar.hotbarV3 .categoryFilter{overflow:hidden}#hotbar.hotbarV3 .categoryFilter:first-child{border-top-left-radius:10px}#hotbar.hotbarV3 .categoryFilter:last-child{border-top-right-radius:10px}#hotbar.hotbarV3 .actorEffect,#hotbar.hotbarV3 .categoryFilter{flex:0 0 30px;border:1px solid #000;box-shadow:inset 0px 0px 5px #636363;height:30px;width:30px;cursor:pointer;background-size:cover;line-height:30px;text-align:center;background-color:rgba(0,0,0,.5);color:var(--color-text-light-heading)}#hotbar.hotbarV3 .actorEffect.active,#hotbar.hotbarV3 .categoryFilter.active{border-color:#006400}#hotbar.hotbarV3 .actorEffect:hover,#hotbar.hotbarV3 .categoryFilter:hover{border-color:#ff4500}#hotbar.hotbarV3 .actorEffect div,#hotbar.hotbarV3 .categoryFilter div{background-size:cover;height:100%;width:100%}#hotbar.hotbarV3 .actorEffect{align-self:flex-end}#hotbar.hotbarV3 #hotbar-directory-controls{margin-top:30px;height:90px}#hotbar.hotbarV3 .quickFunctions{display:flex;flex-wrap:wrap;justify-content:center;flex-direction:column}#hotbar.hotbarV3 .quickFunctions li{flex:0 0 20px;margin-left:5px;height:20px;width:20px;cursor:pointer;pointer-events:all;background-size:cover;background-repeat:no-repeat;position:relative;box-sizing:border-box}#hotbar.hotbarV3 .quickFunctions li.itdarkness{height:90px}#hotbar.hotbarV3 .quickFunctions li div{height:100%;width:100%;position:absolute}#hotbar.hotbarV3 .effect div{color:#000;font-size:24px;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff}#hotbar.hotbarV3 .itdarkness{line-height:0}#hotbar.hotbarV3 .itdarkness .rangeContainer{height:55px}#hotbar.hotbarV3 .updateDarkness{writing-mode:bt-lr;-webkit-appearance:slider-vertical;appearance:slider-vertical;width:50px;height:100%;transform:rotate(-90deg);margin-top:15px;margin-left:-15px}#hotbar.hotbarV3 .longLayout .skillItems li{flex:0 0 90px;text-align:center;max-width:90px}#hotbar.hotbarV3 .longLayout .skillItems li div{display:none}#hotbar.hotbarV3 .longLayout .skillItems li .nameContent{line-height:45px;display:block;overflow:hidden;text-overflow:ellipsis}#hotbar.hotbarV3 #macro-list,#hotbar.hotbarV3 .skillItems{margin:0;padding:0;white-space:nowrap;overflow-y:scroll;display:flex;flex-wrap:wrap;height:100%;transition:all .15s ease-in-out;scroll-snap-type:y mandatory}#hotbar.hotbarV3 #macro-list input,#hotbar.hotbarV3 .skillItems input{height:100%;display:block;width:100%;margin:0;float:left;text-align:center;font-size:20px;color:#fff}#hotbar.hotbarV3 #macro-list.collapsedKeydown,#hotbar.hotbarV3 #macro-list.collapsed,#hotbar.hotbarV3 .skillItems.collapsedKeydown,#hotbar.hotbarV3 .skillItems.collapsed{width:0px;flex:0}#hotbar.hotbarV3 #macro-list .nameContent,#hotbar.hotbarV3 .skillItems .nameContent{display:none;color:#fff}#hotbar.hotbarV3 #macro-list .skillgm .nameContent,#hotbar.hotbarV3 #macro-list .skill .nameContent,#hotbar.hotbarV3 .skillItems .skillgm .nameContent,#hotbar.hotbarV3 .skillItems .skill .nameContent{color:#000}#hotbar.hotbarV3 #macro-list .skillgm.body,#hotbar.hotbarV3 #macro-list .skill.body,#hotbar.hotbarV3 .skillItems .skillgm.body,#hotbar.hotbarV3 .skillItems .skill.body{background:#4f6d65;box-shadow:none;background:linear-gradient(90deg, rgb(79, 109, 101) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.social,#hotbar.hotbarV3 #macro-list .skill.social,#hotbar.hotbarV3 .skillItems .skillgm.social,#hotbar.hotbarV3 .skillItems .skill.social{background:#85302e;box-shadow:none;background:linear-gradient(90deg, rgb(133, 48, 46) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.knowledge,#hotbar.hotbarV3 #macro-list .skill.knowledge,#hotbar.hotbarV3 .skillItems .skillgm.knowledge,#hotbar.hotbarV3 .skillItems .skill.knowledge{background:#4b6585;box-shadow:none;background:linear-gradient(90deg, rgb(75, 101, 133) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.trade,#hotbar.hotbarV3 #macro-list .skill.trade,#hotbar.hotbarV3 .skillItems .skillgm.trade,#hotbar.hotbarV3 .skillItems .skill.trade{background:#cda25e;box-shadow:none;background:linear-gradient(90deg, rgb(205, 162, 94) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.nature,#hotbar.hotbarV3 #macro-list .skill.nature,#hotbar.hotbarV3 .skillItems .skillgm.nature,#hotbar.hotbarV3 .skillItems .skill.nature{background:#535829;box-shadow:none;background:linear-gradient(90deg, rgb(83, 88, 41) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list li,#hotbar.hotbarV3 .skillItems li{flex:0 0 var(--base-bar-height);height:var(--base-bar-height);border:1px solid #000;background-color:rgba(0,0,0,.5);pointer-events:all;background-size:cover;box-shadow:inset 0px 0px 5px #636363;background-repeat:no-repeat;position:relative;box-sizing:border-box;scroll-snap-align:start}#hotbar.hotbarV3 #macro-list li.unequipped,#hotbar.hotbarV3 .skillItems li.unequipped{background:#006400;box-shadow:inset 0px 0px 25px #000;filter:grayscale(100%)}#hotbar.hotbarV3 #macro-list li:hover,#hotbar.hotbarV3 .skillItems li:hover{border-color:#ff4500}#hotbar.hotbarV3 #macro-list li div,#hotbar.hotbarV3 .skillItems li div{background-size:cover;height:100%;width:100%;position:absolute;color:#fff;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;transition:all .15s ease-in-out}#hotbar.hotbarV3 #macro-list li div:hover,#hotbar.hotbarV3 .skillItems li div:hover{transform:scale(1.1)}#hotbar.hotbarV3 #macro-list{border:none}@media(max-width: 1120px){#hotbar.hotbarV3{height:var(--hotbar-height)}}.dsa5-immersive .tokenQuickHot li{box-shadow:inset 0px 0px 5px #403014;background-image:url("../../icons/backgrounds/macrobg.webp")}.dsa5-immersive .tokenQuickHot li input{color:#000}.dsa5-immersive .sidebar-tab .directory-list .directory-item.collapsed{color:#fff}.dsa5-immersive .sidebar-tab .directory-list .directory-item.collapsed h3{color:#fff}.dsa5-immersive .sidebar-tab .directory-list .directory-item h3{color:#000}.dsa5-immersive #sidebar-tabs{border-bottom:1px solid #000;box-shadow:0 0 10px #000;background-color:rgba(16,13,8,.4784313725)}.dsa5-immersive .chat-message{background:none}.dsa5-immersive .chat-message .message-header{padding:10px 5px;background-image:url("../../icons/backgrounds/kapitelstart.webp");background-size:112% 110%;background-repeat:no-repeat;background-position:67% -5px;color:#191815}.dsa5-immersive .sidebar-popout .chat-message,.dsa5-immersive #sidebar .chat-message{padding:8px 15px 15px 15px;padding-left:18px;margin-bottom:8px;border-image:url("../../icons/backgrounds/chatpaper.webp");border-image-width:30px;border-image-slice:50 50 fill;border-image-repeat:round}.dsa5-immersive .app.sidebar-popout .window-content{color:#333}.dsa5-immersive .sidebar-popout .dice-tray input[type=text],.dsa5-immersive #sidebar .dice-tray input[type=text]{color:#000}.dsa5-immersive .compendium-footer .source{color:#fff}.dsa5-immersive .window-app{background:none;box-shadow:none}.dsa5-immersive .window-app.actor .window-content{box-shadow:0 0 20px #000}.dsa5-immersive .window-app.image-popout .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-immersive .window-app .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-immersive .window-app.dsajournal .window-content,.dsa5-immersive .window-app.bookWizardsheet .window-content{background-image:url("../../icons/backgrounds/journalentry_v45.webp");background-size:97% 1000px;background-position:center;background-repeat:repeat-y}.dsa5-immersive .window-app.dsajournal .window-content a.content-link,.dsa5-immersive .window-app.dsajournal .window-content a.inline-roll,.dsa5-immersive .window-app.bookWizardsheet .window-content a.content-link,.dsa5-immersive .window-app.bookWizardsheet .window-content a.inline-roll{border:none;color:#b93d00;font-weight:bold;background:none}.dsa5-immersive .window-app.dsajournal .window-content a.content-link i,.dsa5-immersive .window-app.dsajournal .window-content a.inline-roll i,.dsa5-immersive .window-app.bookWizardsheet .window-content a.content-link i,.dsa5-immersive .window-app.bookWizardsheet .window-content a.inline-roll i{color:#b93d00}.dsa5-immersive .window-app.dsajournal .window-content{padding:0 40px}.dsa5-immersive .window-app.bookWizardsheet .video-container,.dsa5-immersive .window-app.dsajournal .window-content .video-container{position:relative;width:100%;padding-bottom:56.25%}.dsa5-immersive .window-app.bookWizardsheet .video-container iframe,.dsa5-immersive .window-app.dsajournal .window-content .video-container iframe{position:absolute;top:0;left:0;width:100%;height:100%;border:0}.dsa5-immersive .window-app.dialog .window-content{padding-top:14px;padding-bottom:14px}.dsa5-immersive .window-app.npc-sheet .window-header,.dsa5-immersive .window-app.character-sheet .window-header,.dsa5-immersive .window-app.item .window-header{background-image:url("../../icons/backgrounds/sidebar-top.webp");border:none;top:2px}.dsa5-immersive .window-app.npc-sheet:not(.monarch):after,.dsa5-immersive .window-app.character-sheet:not(.monarch):after,.dsa5-immersive .window-app.item:not(.monarch):after{background-image:url("../../icons/backgrounds/sidebar-bot.webp");bottom:2px;content:""}.dsa5-immersive .window-app:not(.monarch) .window-header,.dsa5-immersive .window-app:after{background-repeat:no-repeat;position:relative;min-height:40px;z-index:1;height:40px;width:100%;background-size:100% 40px}.dsa5-immersive .window-app.creature-sheet .window-content{box-shadow:none}.dsa5-immersive .window-app.monarch .window-header,.dsa5-immersive .window-app.monarch:after{background-image:none}.dsa5-immersive .window-app .window-header{background-image:url("../../icons/backgrounds/blackhat.webp");top:7px;border:none}.dsa5-immersive .window-app:not(.monarch):after{background-image:url("../../icons/backgrounds/blackbook.webp");bottom:12px;content:""}.dsa5-immersive .window-app.creature-sheet:after{background-image:url("../../icons/backgrounds/blackcreaturebot.webp")}.dsa5-immersive .window-app.masterMenu:after{background-image:url("../../icons/backgrounds/masterborder.webp")}.dsa5-immersive .window-app.creature-sheet .window-resizable-handle{bottom:18px}.dsa5-immersive .window-app .window-header .aa-item-settings,.dsa5-immersive .window-app .window-header [id^=popout_]{width:15px;height:15px;margin-top:10px}.dsa5-immersive .window-app:not(.monarch) .window-header>a{width:15px;height:15px;margin-top:10px}.dsa5-immersive .window-app:not(.monarch) .window-header>a i{width:22px;border:1px solid #111;padding:3px;background-color:#444;text-align:center;border-radius:100%;color:#fff}.dsa5-immersive .window-app .aa-item-settings i,.dsa5-immersive .window-app .window-header [id^=popout_] i{width:22px;border:1px solid #111;padding:3px;background-color:#444;text-align:center;border-radius:100%;color:#fff}.dsa5-immersive .window-app .window-resizable-handle{z-index:2;bottom:11px;right:25px}.dsa5-immersive .window-app .window-header .window-title{text-align:center;margin-left:15%;margin-top:5px;color:#fff;font-family:var(--boldFont);font-weight:bold;font-family:"GentiumBasic-Bold";text-shadow:0px 0px 2px rgba(0,0,0,.75)}.dsa5-immersive .window-app.npc-sheet .window-header .window-title,.dsa5-immersive .window-app.character-sheet .window-header .window-title{margin-top:10px;color:#000;text-shadow:1px 1px #fff}.dsa5-immersive .window-app .header-button.close{margin-right:25px}.dsa5-immersive .window-app.actor .window-content,.dsa5-immersive .window-app.item .window-content{margin-left:15px;margin-right:15px}.dsa5-immersive .window-app.dsa5Decent:after{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .window-app.initTracker::after,.dsa5-immersive .window-app.initTracker .window-content{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .window-app.tokenQuickHot::after,.dsa5-immersive .window-app.tokenQuickHot .window-content{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .window-app.initTracker::after,.dsa5-immersive .window-app.tokenQuickHot::after{content:none}.dsa5-immersive .window-app.dsa5Decent .window-content,.dsa5-immersive .window-app.dsa5Decent .window-header{background:rgba(0,0,0,.5);padding:0;position:unset;color:#fff}.dsa5-immersive .window-app.dsa5Decent .window-content li{background:rgba(255,255,255,.2)}.dsa5-immersive .window-app.dsa5Decent .window-content li:hover{background:rgba(255,255,255,.5)}.dsa5-immersive .window-app.dsa5Decent:after{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .app.sidebar-popout .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-immersive .character-sheet form{border-color:#000;border-style:double;border-width:10px;border-image:url("../../icons/backgrounds/actor.webp") 27 28 28 28;padding:4px;margin:0px}.dsa5-immersive #settings .fshopButton div{display:inline-block;background-image:url("../../lazy/patchimages/UlissesDigital.png");background-size:contain;width:20px;height:19px;margin:0;background-repeat:no-repeat;background-position:center;position:relative;top:5px}.dsa5-immersive #sidebar{border:none;margin:0px;height:100vh}.dsa5-immersive #sidebar .sidebar-tab .folder.collapsed .folder-header a i{color:#d8d4d4}.dsa5-immersive #sidebar .playlists-sidebar .sound-control{color:#3b3b3b}.dsa5-immersive #sidebar .playlists-sidebar .sound-control.inactive i{color:#797373}.dsa5-immersive #sidebar .sidebar-tab.playlists-sidebar a.sound-control[data-action=sound-stop],.dsa5-immersive #sidebar .sidebar-tab.playlists-sidebar .folder a.sound-control[data-action=playlist-stop] i,.dsa5-immersive #sidebar .sidebar-tab.playlists-sidebar .folder .folder-header a.sound-control[data-action=playlist-stop] i{color:var(--color-text-hyperlink)}.dsa5-immersive #sidebar button.fshopButton{background:#006f3d;background:linear-gradient(90deg, rgb(0, 38, 13) 0%, rgb(0, 111, 61) 100%);position:relative}.dsa5-immersive #sidebar.collapsed:before{content:none}.dsa5-immersive #sidebar .directory-list .documentName,.dsa5-immersive #sidebar .playlist.now-playing,.dsa5-immersive #sidebar .directory-list .directory-item.compendium,.dsa5-immersive #sidebar .directory-list .directory-item.document{background-color:var(--sheet-bg);margin:3px;border:1px solid var(--sheet-border);border-radius:5px;color:#000;margin-left:10px}.dsa5-immersive #sidebar .sidebar-tab{color:#555}.dsa5-immersive #sidebar .sidebar-tab a.inactive i{color:#acacac}.dsa5-immersive #sidebar .sidebar-tab .jump-to-bottom{color:#fff}.dsa5-immersive #sidebar .sidebar-tab .jump-to-bottom i{color:#fff}.dsa5-immersive #sidebar .global-control{margin-left:10px}.dsa5-immersive #sidebar .global-control .playlist-header{color:#fff}.dsa5-immersive #sidebar:before{position:absolute;top:0;bottom:0;left:-13px;right:0;content:"";background-image:url("../../icons/backgrounds/menu.webp");background-repeat:repeat-y;background-size:100%;z-index:-1}.dsa5-immersive .dsa5.item .item-header{background-image:url("../../icons/backgrounds/kapitelstart.webp")}.dsa5-immersive .dsa5.item.minimized .window-header .window-title{color:#000}.dsa5-immersive .dsa5.item .window-header .window-title{color:rgba(0,0,0,0);text-shadow:none}.dsa5-immersive .sidebar-popout{color:#555}.dsa5-immersive .sidebar-popout a i{color:#555}.dsa5-immersive .sidebar-popout a.inactive i{color:#acacac}.dsa5-immersive .sidebar-popout .jump-to-bottom{color:#fff}.dsa5-immersive .sidebar-popout .jump-to-bottom i{color:#fff}.dsa5-immersive .itemTooltip{background-image:url("../../icons/backgrounds/macrobg.webp");background-size:cover;color:#000;padding:1px;border:2px solid #000;border-radius:5px}.dsa5-immersive #hotbar:before{background-image:url("../../icons/backgrounds/hotbarpart.webp"),url("../../icons/backgrounds/hotbarpart.webp"),url("../../icons/backgrounds/hotbar4.webp");background-size:30px 48px,66px 48px,100% 100%;background-repeat:no-repeat;content:"";position:absolute;left:0px;right:-32px;bottom:-10px;top:-10px;z-index:-1;background-position:8px 11px,calc(100% - 8px) 11px,center}.dsa5-immersive #hotbar.hotbarV3{margin-bottom:10px}.dsa5-immersive #hotbar.hotbarV3:before{background-size:30px 91px,34px 91px,calc(100% - 26px) calc(100% - 20px);background-position:8px 39px,calc(100% - 33px) 39px,0px 18px}.dsa5-immersive #hotbar.hotbarV3 .function{color:#000}.dsa5-immersive #hotbar.hotbarV3 .sections{background:none}.dsa5-immersive #hotbar.hotbarV3 .nameContent{color:#000}.dsa5-immersive #hotbar.hotbarV3 .actorEffect,.dsa5-immersive #hotbar.hotbarV3 .categoryFilter{background-image:url("../../icons/backgrounds/macrobg.webp");background-size:cover;color:#000}.dsa5-immersive #hotbar.hotbarV3 .actorEffect{box-shadow:inset 0px 0px 25px #403014}.dsa5-immersive #hotbar.hotbarV3 #macro-list li,.dsa5-immersive #hotbar.hotbarV3 .skillItems li{box-shadow:inset 0px 0px 25px #403014;background-image:url("../../icons/backgrounds/macrobg.webp")}.dsa5-immersive #hotbar.hotbarV3 #macro-list li.unequipped,.dsa5-immersive #hotbar.hotbarV3 .skillItems li.unequipped{box-shadow:inset 0px 0px 25px #000}.dsa5-immersive #hotbar.hotbarV3 #macro-list input,.dsa5-immersive #hotbar.hotbarV3 .skillItems input{color:#000}.dsa5-immersive #hotbar.collapsedHotbar:before{background-image:url("../../icons/backgrounds/hotbarpart.webp")}.dsa5-immersive #hotbar .macro{background:none;border:1px solid rgba(0,0,0,.5)}.dsa5-immersive #hotbar .macro.active{box-shadow:inset 0px 0px 25px #403014;background:url("../../icons/backgrounds/macrobg.webp")}.dsa5-immersive #hotbar .macro.active.parry{box-shadow:inset 0px 0px 15px #016e0a}.dsa5-immersive #hotbar .macro.active.attack{box-shadow:inset 0px 0px 15px #7e0202}.dsa5-immersive #hotbar #macro-list{border:none;margin:0}.dsa5-immersive #hotbar .bar-controls{margin:0;background:none;color:#000;border:none;box-shadow:none}.dsa5-immersive #hotbar .bar-controls:first-child{margin-left:5px}@media(max-width: 1120px){.dsa5-immersive #hotbar:before{background-size:36px 88px,66px 88px,190% 100%;background-position:-3px 18px,calc(100% + 3px) 18px,center;right:-58px;left:6px}.dsa5-immersive #hotbar.hotbarV3:before{background-size:36px 105px,66px 105px,190% 100%;background-position:-1px 24px,calc(100% + 30px) 24px,center;left:0px;right:0px}.dsa5-immersive #hotbar #hotbar-page-controls a,.dsa5-immersive #hotbar #hotbar-directory-controls a{margin:6px 0}}.dsa5-immersive .window-app.npc-sheet.app .window-content{box-shadow:none}.dsa5-immersive #players{background:none;border:none;box-shadow:none}.dsa5-immersive #players:before{background-image:url("../../icons/backgrounds/dsabot.webp");background-size:100% 15px;background-repeat:no-repeat;content:"";position:absolute;left:-2px;right:-2px;bottom:-5px;top:-20px;z-index:-1;background-position:center 100%}.dsa5-immersive #players h3{border:none;position:relative;overflow:visible}.dsa5-immersive #players h3:before{background-image:url("../../icons/backgrounds/dsahead.webp"),url("../../icons/backgrounds/dsamid.webp");background-size:100% 30px,100% calc(100% - 30px);background-repeat:no-repeat;content:"";position:absolute;left:-5px;right:-5px;bottom:0px;top:-20px;z-index:-1;background-position:center 0px,center 30px}.dsa5-immersive #players #player-list{border:none;position:relative;overflow:visible}.dsa5-immersive #players #player-list:before{background-image:url("../../icons/backgrounds/dsamid.webp");background-size:100% 50px;background-repeat:repeat-y;content:"";position:absolute;left:-2px;right:-2px;bottom:5px;top:-3px;z-index:-1;background-position:center 0px}.dsa5-immersive #sidebar button,.dsa5-immersive .initTracker button,.dsa5-immersive .masterMenu button,.dsa5-immersive .sheetButton,.dsa5-immersive .sidebar-popout button,.dsa5-immersive .sidebar-popout .dice-tray button{background-image:linear-gradient(to right top, #be2020, #af1622, #9f0d22, #8f0522, #7f0021);color:#fff;border:1px solid #000}.dsa5-immersive #sidebar button:active,.dsa5-immersive .initTracker button:active,.dsa5-immersive .masterMenu button:active,.dsa5-immersive .sheetButton:active,.dsa5-immersive .sidebar-popout button:active,.dsa5-immersive .sidebar-popout .dice-tray button:active{box-shadow:inset 0 0 5px #000}.dsa5-immersive #sidebar button:hover,.dsa5-immersive .initTracker button:hover,.dsa5-immersive .masterMenu button:hover,.dsa5-immersive .sheetButton:hover,.dsa5-immersive .sidebar-popout button:hover,.dsa5-immersive .sidebar-popout .dice-tray button:hover{box-shadow:inset 0 0 3px #fff}.dsa5-immersive #sidebar button.lastRound,.dsa5-immersive .initTracker button.lastRound,.dsa5-immersive .masterMenu button.lastRound,.dsa5-immersive .sheetButton.lastRound,.dsa5-immersive .sidebar-popout button.lastRound,.dsa5-immersive .sidebar-popout .dice-tray button.lastRound{background-color:#02234d;background-image:none}.dsa5-immersive .dsajournal.sheet.journal-entry .journal-entry-content{background:none;border:none}.dsa5-immersive .dsajournal .header-search,.dsa5-immersive .dsajournal.sheet.journal-entry .pages-list .directory-item .page-number,.dsa5-immersive .dsajournal .directory-item{color:#000}.dsa5-immersive #compendium li.compendium-pack{background-color:var(--sheet-bg);margin:3px;border:1px solid var(--sheet-border);border-radius:5px;color:#000;margin-left:10px;padding:5px}.dsa5-immersive #compendium.sidebar-tab .entry-name i{color:#fff}.dsa5-immersive #compendium .compendium h3{color:#fff;margin-left:3px}.dsa5-immersive .compendium.directory .directory-header .compendium-name{color:#fff}.dsa5-immersive #compendium li.compendium-pack .compendium-footer,.dsa5-immersive #playlists li.sound .sound-playback .sound-timer{color:#0e0c0c}.dsa5-immersive #playlists.sidebar-tab .directory-list .directory-item.playlist.collapsed{color:#555}.dsa5-immersive .sound-name{color:#5c5c5c}.dsa5-immersive .app.sidebar-popout{backdrop-filter:none}.dsa5-legacy .window-app.dsajournal .window-content{background-image:url("../../icons/backgrounds/journalentry.webp");background-size:97% 1000px;padding:0 50px}.dsa5-legacy .chatpaperfield{border-image:url("../../icons/backgrounds/chatpaper.webp");border-image-width:30px;border-image-slice:80 50 40 fill;border-image-repeat:round;padding:10px 20px 10px 30px}.dsa5-legacy .maskfield{position:relative;padding:10px 20px 30px 20px;color:#fff;border-image:url("../../icons/backgrounds/maskfield.webp");border-image-width:15px;border-image-slice:20 20 fill;border-image-repeat:round}.dsa5-legacy .maskfield:after{content:"";pointer-events:none;position:absolute;bottom:-23px;left:0;right:0;height:50px;z-index:1;background:url("../../icons/backgrounds/mask.webp");background-repeat:no-repeat;background-size:150px 50px;background-position:bottom center}.dsa5-legacy .maskfield .editor .mce-content-body{color:#fff}.dsa5-legacy .maskfield .editor.prosemirror .editor-menu{background-color:#fff}.dsa5-legacy .maskfield .editor.prosemirror.editing-source textarea{color:#fff}.dsa5-legacy .maskfield .documentName-link,.dsa5-legacy .maskfield .entity-link a.content-link{color:#000}.dsa5-legacy .bookWizardsheet .window-content .table-title,.dsa5-legacy .dsajournal .window-content .label-text,.dsa5-legacy .bookWizardsheet .window-content table tr:first-child,.dsa5-legacy .dsajournal .window-content table tr:first-child{background:#bc886f;background:linear-gradient(90deg, rgba(188, 136, 111, 0.8) 0%, rgba(255, 255, 255, 0) 100%);border-bottom-style:solid;text-align:left}.dsa5-legacy .window-app.bookWizardsheet .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.content-link,.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.inline-roll,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.content-link,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.inline-roll{border:none;color:#ee770e;font-weight:bold;background:none}.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.content-link i,.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.inline-roll i,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.content-link i,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.inline-roll i{color:#ee770e}:root{--app-height: 100vh}body{height:var(--app-height)}/*# sourceMappingURL=dsa5.css.map */ +:root{--border-color:#736953a6;--bg-color:#e1d3c6;--button-color:#532902e7;--sheet-bg:#2e2c2a15;--sheet-border:#968678;--boldFont:"Signika";--normalFont:"Signika";--minColumnWidth: 330px;--minColumnWidth40: 264px;--minColumnWidth60: 396px}@font-face{font-family:"GentiumBasic";src:url("../../fonts/GenBasR.eot");src:url("../../fonts/GenBasR.eot?#iefix") format("embedded-opentype"),url("../../fonts/GenBasR.otf") format("opentype"),url("../../fonts/GenBasR.svg") format("svg"),url("../../fonts/GenBasR.ttf") format("truetype"),url("../../fonts/GenBasR.woff") format("woff"),url("../../fonts/GenBasR.woff2") format("woff2");font-weight:normal;font-style:normal}@font-face{font-family:"GentiumBasic-BoldItalic";src:url("../../fonts/GenBasBI.eot");src:url("../../fonts/GenBasBI.eot?#iefix") format("embedded-opentype"),url("../../fonts/GenBasBI.otf") format("opentype"),url("../../fonts/GenBasBI.svg") format("svg"),url("../../fonts/GenBasBI.ttf") format("truetype"),url("../../fonts/GenBasBI.woff") format("woff"),url("../../fonts/GenBasBI.woff2") format("woff2");font-weight:normal;font-style:normal}@font-face{font-family:"GentiumBasic-Bold";src:url("../../fonts/GenBasB.eot");src:url("../../fonts/GenBasB.eot?#iefix") format("embedded-opentype"),url("../../fonts/GenBasB.otf") format("opentype"),url("../../fonts/GenBasB.svg") format("svg"),url("../../fonts/GenBasB.ttf") format("truetype"),url("../../fonts/GenBasB.woff") format("woff"),url("../../fonts/GenBasB.woff2") format("woff2");font-weight:normal;font-style:normal}@font-face{font-family:"Andalus";src:url("../../fonts/andlso.eot");src:url("../../fonts/andlso.eot?#iefix") format("embedded-opentype"),url("../../fonts/andlso.otf") format("opentype"),url("../../fonts/andlso.svg") format("svg"),url("../../fonts/andlso.ttf") format("truetype"),url("../../fonts/andlso.woff") format("woff"),url("../../fonts/andlso.woff2") format("woff2");font-weight:normal;font-style:normal}#tinymce{overflow-y:hidden;overflow-x:hidden}.tox-tinymce{width:100%}.editor-content ul{margin:0px 0px}.overflowhidden{overflow:hidden}.scrollY{overflow-y:auto;overflow-x:hidden}body{padding:0px;overflow:hidden;font-size:14px;font-family:var(--normalFont)}textarea{font-family:var(--normalFont)}b{font-family:var(--boldFont);font-weight:bold}h1,h2,h3,h4,h5,h6,h7{overflow:hidden}h1 a.content-link,h1 a.entity-link,h2 a.content-link,h2 a.entity-link,h3 a.content-link,h3 a.entity-link,h4 a.content-link,h4 a.entity-link,h5 a.content-link,h5 a.entity-link,h6 a.content-link,h6 a.entity-link,h7 a.content-link,h7 a.entity-link{background:none;padding:0;border:none}.dsa5 h1,.dsa5 h2,.dsa5 h3,.dsa5 h4,.dsa5 h5,.dsa5 h6,.dsa5 h7{font-family:"Andalus"}.schwierig,.einfach{margin-left:40px;position:relative}.schwierig:before,.einfach:before{content:"";background:url("../../icons/einfach.webp");background-size:contain;background-repeat:no-repeat;position:absolute;left:-40px;top:0;height:30px;width:30px;margin-right:5px}.schwierig:before{background-image:url("../../icons/schwierig.webp")}.obfuscateSection.pale{opacity:.3}.dsa5 .tab.description.active{display:flex;flex-flow:column;height:calc(100% - 129px);overflow-y:hidden}.dsa5 .tab.description.active .editor{height:100%}.dsa5.item-sheet img{max-height:50px;max-width:50px;margin-top:5px;border-color:rgba(0,0,0,0)}.dsa5.item-sheet img.fullImg{width:100%;max-width:initial;max-height:initial}.dsa5.item textarea{padding:1px 3px}.dsa5 .editor{border:none;overflow:auto;flex-grow:1;display:flex;padding:3px;margin-top:0px;margin-bottom:7px;height:100%;width:100%}.hovermenu{display:inline-block;position:absolute;top:2px;right:3px;z-index:1;cursor:pointer}.hovermenu i{color:var(--border-color);padding:2px}.hovermenu i:hover{color:#3f3636}.notes-box{min-height:70px}.item-box{min-height:30px}.character-sheet nav.sheet-tabs,.creature-sheet nav.sheet-tabs,.npc-sheet nav.sheet-tabs{margin-bottom:20px}.character-sheet .general,.npc-sheet .general,.creature-sheet .general{display:flex;flex-direction:row;width:100%;margin:0}#field-distinguishingmark{width:calc(50% - 15px)}.sheet-header{margin-bottom:10px}.actor .sheet-header .entity-link{padding:0;border:none;background:none}table.infoTable{width:100%}table.infoTable tr td:first-child{width:15%}.creature-sheet .headerInput,.sheet-header .headerInput,.npc-sheet .general .headerInput,.sheet-header .headerInput,.character-sheet .general .headerInput,.character-sheet .sheet-header .headerInput{box-sizing:border-box;margin:5px}.npc-sheet .general .headerInput input,.sheet-header .headerInput input,.creature-sheet .headerInput input,.sheet-header .headerInput input,.character-sheet .general .headerInput input,.sheet-header .headerInput input{border:none;border-bottom:1px solid var(--border-color);box-shadow:none;background-color:rgba(0,0,0,0);border-radius:0px;height:auto}.creature-sheet .headerInput span,.sheet-header .headerInput span,.npc-sheet .general .headerInput span,.sheet-header .headerInput span,.character-sheet .general .headerInput span,.sheet-header .headerInput span{color:#333;margin-left:4px;margin-bottom:2px;font-size:12px}.item form .form-group input[type=checkbox]{flex:3}.form-group.full-height .editor,.form-group.full-height .tox{min-height:100px;flex-grow:3;border:1px solid var(--border-color);background-color:rgba(0,0,0,.05);margin:0}.dsa5.item form .form-group.autoHeight div{height:auto}.centerCell{display:flex;align-self:center}form .form-group.autoHeight label{align-self:stretch;vertical-align:middle}form .form-group.full-height label,form .form-group.full-height input{align-self:stretch;vertical-align:middle}form .form-group.full-height textarea{min-height:140px;font-size:14px}form .career .form-group.full-height textarea{min-height:80px}form .form-group.double span{flex:.9;display:inline;text-align:center}form .form-group.double .input-text{flex:1;display:inline;text-align:center}form .form-group.tripple .input-text{flex:2}form .form-group.doubleInput .input-text{flex:1.45}form .form-group div.input-text{padding:0 3px}form .form-group div.input-text ul{padding:0;margin:0}form .form-group.tripple select{flex:1;padding:0}.emphasize{color:#fff;background-color:darkred}.emphasize input::placeholder{color:#fff}input[type=text].emphasize{border-color:darkred}.emphasize2{color:#fff;background-color:#0a59c2}.maxMods{transition:background-color .3s linear}.charimg{width:115px;height:115px;object-fit:contain}.minimumColumnLayout .characteristics-table{min-width:unset}.characteristics-table{flex:6;display:block;min-width:var(--minColumnWidth60)}.characteristics-table.ctab2{flex:4;min-width:var(--minColumnWidth40)}.characteristics-table .table-data,.characteristics-table .table-header{flex:1}.characteristics-table .table-data:first-child,.characteristics-table .table-header:first-child{flex:2}.character-sheet .window-content{padding:0}.window-app .window-content select:not([multiple]) option{color:#fff;background:#1d1c1c}select[multiple] option{background-color:rgba(0,0,0,0)}select[multiple] option:checked{background-color:#12496c;color:#fff}.characteristics-table .table-row{text-align:center;width:100%;border-bottom:none;border-right:none;display:flex}.skills.body{background:#4f6d65;background:linear-gradient(90deg, rgb(79, 109, 101) 0%, rgba(255, 255, 255, 0) 100%)}.skills.social{background:#85302e;background:linear-gradient(90deg, rgb(133, 48, 46) 0%, rgba(255, 255, 255, 0) 100%)}.skills.knowledge{background:#4b6585;background:linear-gradient(90deg, rgb(75, 101, 133) 0%, rgba(255, 255, 255, 0) 100%)}.skills.trade{background:#cda25e;background:linear-gradient(90deg, rgb(205, 162, 94) 0%, rgba(255, 255, 255, 0) 100%)}.skills.nature{background:#535829;background:linear-gradient(90deg, rgb(83, 88, 41) 0%, rgba(255, 255, 255, 0) 100%)}.table-title,.label-text{font-weight:bold;font-family:var(--boldFont);background:#bc886f;background:linear-gradient(90deg, rgba(188, 136, 111, 0.8) 0%, rgba(255, 255, 255, 0) 100%)}.bookWizardsheet .window-content .table-title,.dsajournal .window-content .label-text,.bookWizardsheet .window-content table tr:first-child,.dsajournal .window-content table tr:first-child{font-weight:bold;font-family:var(--boldFont);border-bottom-style:double;text-align:center;background:rgba(188,136,111,.3)}.bookWizardsheet .window-content table,.dsajournal .window-content table,.bookWizardsheet .window-content table tr,.dsajournal .window-content table tr,.bookWizardsheet .window-content table td,.dsajournal .window-content table td{border-color:var(--border-color)}.table-title{background:#bc886f;background:linear-gradient(90deg, rgb(188, 136, 111) 0%, rgba(255, 255, 255, 0) 100%);box-shadow:none}.table-header{font-weight:bold;font-family:var(--boldFont)}.skill-section{display:flex}.skill-select{display:inline-block}.skill-section .flexcolumn{flex:50%}#combat #combat-round .encounters{color:#444}#combat #combat-round .encounters h4,#combat #combat-round .encounters a{color:#444}#combat-tracker .token-effect{box-shadow:0px 0px 10px #000 inset}.tour .step-title{overflow:initial}.directory .directory-list .directory-item.folder .context{color:#000}.chat-buttons{float:right}.die-attack,.die-mu,.diet-mu:after{background-image:url("../../icons/dice/d20mu.svg");color:#fff}.die-kl,.diet-kl:after{background-image:url("../../icons/dice/d20kl.svg");color:#fff}.die-dodge,.die-parry,.die-in,.die-poison,.die-disease,.diet-in:after{background-image:url("../../icons/dice/d20in.svg");color:#fff}.die-ch,.diet-ch:after{background-image:url("../../icons/dice/d20ch.svg");color:#fff}.die-ff,.diet-ff:after{background-image:url("../../icons/dice/d20ff.svg")}.die-ge,.diet-ge:after{background-image:url("../../icons/dice/d20ge.svg")}.die-ko,.diet-ko:after{background-image:url("../../icons/dice/d20ko.svg")}.die-kk,.diet-kk:after{background-image:url("../../icons/dice/d20kk.svg")}.d20height{line-height:35px}.skills .d20:after{content:"";position:absolute;top:0;left:0;right:0;bottom:0;opacity:.35;background-size:contain;background-position:center;background-repeat:no-repeat}.d6.die-AsP{background-position:center 2.5px;background-image:url("../../icons/dice/d6blue.svg")}.d6.die-LeP{color:#fff;background-position:center 2.5px;background-image:url("../../icons/dice/d6red.svg")}.d6.die-KaP{color:#fff;background-position:center 2.5px;background-image:url("../../icons/dice/d6green.svg")}.d6.die-effect,.d6.die-damage{background-image:url("../../icons/dice/d6white.svg");background-position:center 2.5px;color:#fff}.d2.die-damage,.d3.die-damage{background-image:url("../../icons/dice/d6white.svg");background-position:center 2.5px;color:#fff}.dice-tooltip .dice-rolls .roll.die{line-height:35px}.d20,.d6,.d2,.d3{font-family:"GentiumBasic-Bold";width:35px;height:35px;display:inline-block;background-size:contain;line-height:35px;text-align:center;background-position:calc(50% + 1px);background-repeat:no-repeat}.skills .d20{width:22px;height:22px;line-height:22px;font-size:10px;position:relative;display:inline-block}.rollButton .d20,.reactClick .d20{width:30px;height:30px;line-height:30px;font-size:12px;float:right}.rollButton .d20{float:left}.chatmoney{width:15px;height:15px;display:inline-block}input[type=text].col-Money-D{color:#927c01}input[type=text].col-Money-S{color:#474444}input[type=text].col-Money-K{color:#9c5e5e}input[type=text].col-Money-H{color:#944b32}.Money-D,.money-D{background:url("../../icons/money-D.webp");background-repeat:no-repeat;background-size:contain}.Money-K,.money-K{background:url("../../icons/money-K.webp");background-repeat:no-repeat;background-size:contain}.Money-S,.money-S{background:url("../../icons/money-S.webp");background-repeat:no-repeat;background-size:contain}.Money-H,.money-H{background:url("../../icons/money-H.webp");background-repeat:no-repeat;background-size:contain}.chatLineHeight{line-height:15px;display:inline-block}.cards{padding:3px}.cards>div{margin:1px;flex-grow:1;position:relative}.cards .item{box-shadow:0 0 12px rgba(110,59,1,.5607843137) inset}.cards a{padding:4px;border-radius:2px;width:100%;display:inline-block;text-align:center}.cards a.onUseItem,.cards a.traditionPayCost{width:28px;box-shadow:none}.cards a.onUseItem+a,.cards a.traditionPayCost+a{width:calc(100% - 28px)}.main-row{display:flex;width:100%;flex:1}.row-section{display:flex}.row-section.wrap{flex-wrap:wrap}.row-section .col{flex:100%}.row-section .col.libItem{margin-top:30px;padding:10px;border-radius:10px;background-color:rgba(0,0,0,.05);border:1px solid var(--border-color)}.row-section .col.morph{flex:50%;min-width:var(--minColumnWidth)}.row-section .col.morph40{flex:40%;min-width:var(--minColumnWidth40)}.row-section .col.morph60{flex:60%}.row-section.filterfull .col.morph{flex:100%}.row-section.skills{border:.5px solid var(--border-color);margin:0;padding:2px}.reverseFlex{flex-flow:row-reverse}.reverseColumnFlex{flex-flow:column-reverse}.thinscroll::-webkit-scrollbar{width:6px}.thinscroll{scrollbar-width:thin}.columnFlex{flex-flow:column;align-items:stretch}.skills span{margin:0}.lineheight{line-height:26px}.item .image{height:30px;background-size:contain;background-repeat:no-repeat;background-position:4px 0px}.inventory{line-height:30px}.row-section .col.three{flex:30%}.row-section .col.four{flex:25%}.row-section .col.thirtyfive{flex:35%}.row-section .col.fourtyfive{flex:45%}.row-section .col.five{flex:20%}.row-section .col.eight{flex:12.5%}.row-section .col.ten{flex:10%}.row-section .col.zerofive{flex:5%}.row-section .col.col95{flex:95%}.row-section .col.fourty{flex:40%}.row-section .col.third{flex:30%}.row-section .col.ninety{flex:90%}.row-section .col.eighty{flex:80%}.row-section .col.eighty.fixed{position:relative;max-width:80%;overflow:hidden}.row-section .col.eighty.fixed:hover{overflow:visible;z-index:50}.row-section .col.seventy{flex:70%}.row-section .col.fifteen{flex:15%}.row-section .col.sixty{flex:60%}.row-section .col.seventeen{flex:17.5%}.row-section .col.two{flex:50%;max-width:50%}.max20{max-width:20%}.groupbox{border:1px solid var(--border-color);border-radius:3px;margin:10px 2px;min-height:50px}.header-label{text-align:center;height:100%}.center{text-align:center}.right{text-align:right}.very-small{font-size:10px}.inventory .very-small{line-height:14px}.small{font-size:12px}.selectableRow{border:1px solid #000;cursor:pointer}.row-section.selectableRow.tableOdd:hover{background-color:#fff}.selectableRow:hover{background-color:#fff}.selectableRow.selected{box-shadow:inset 0px 0px 10px 5px rgba(188,136,111,.8)}a.img-entity-link{border:none;background:none;display:block}a.img-entity-link:hover{background:#fff}.row-section .twoColors:nth-child(4n-1),.row-section .twoColors:nth-child(4n){background-color:rgba(0,0,0,.1)}.row-section.rowColors:nth-child(odd),.row-section.tableOdd:nth-child(even){background-color:rgba(0,0,0,.1)}.col.morph .tableOdd:nth-child(even){background-color:rgba(0,0,0,.1)}.row-section.inverseRowtable>.col:nth-child(odd),.row-section.rowtable>.col:nth-child(even){background-color:rgba(0,0,0,.1)}.advance{color:rgba(51,48,41,.6509803922);margin-left:4px;font-size:8px;line-height:8px}.combat-actions{display:flex;gap:5px;flex-wrap:wrap}.combat-actions .combat-action{display:block;color:rgba(51,48,41,0.6509803922);padding:1px 5px;border:1px solid rgba(51,48,41,0.6509803922);border-radius:5px}.row-section .col.combat-item-name{flex-grow:0}.buttons a .fas,.buttons a .fa{border-radius:100%;border:1px solid var(--border-color);padding:2px;color:rgba(51,48,41,.6509803922)}.lighticon{color:rgba(68,68,68,.65)}.button.green{background:#006f3d;background:linear-gradient(90deg, rgb(0, 38, 13) 0%, rgb(0, 111, 61) 100%);position:relative;color:#fff}.condition-toggle,.condition-edit,.ench,.spells .very-small a .fas,.inventory .very-small a .fas{padding:1px;border:none;color:var(--border-color)}::-webkit-scrollbar{width:14px}::-webkit-scrollbar-track{background:#111}::-webkit-scrollbar-thumb{background:#782e22;border:1px solid #111}.sidebar-tab ::-webkit-scrollbar-thumb{background:#782e22;border:1px solid #111}.sidebar-tab ::-webkit-scrollbar{width:8px}.sheet.journal-entry:not(.dsajournal) .sidebar.directory{background:rgba(0,0,0,.6)}.window-app.dsajournal .editor-content p{margin-right:10px}form.dsa5.item-sheet{padding-left:10px;padding-right:10px}.qOverlay{position:relative}.qOverlay .img{position:absolute;left:0;right:0;top:0;bottom:0;background-repeat:no-repeat;background-position:center;background-size:contain}.qOverlay .overlay{height:100%;width:100%;min-height:200px;line-height:200px;font-size:200px;opacity:.2}.dsalist li{width:100%}.statusEffectMenu,.dsalist li,#chat-form,.browser-item,.effect-change .key,.inputTooltipAvailable,.journalHeader,.tokenQuickHot>ul>li,.bags,.hero,.window-app .window-content{position:relative}#dice-config .window-content{position:unset}#client-settings section.content .settings-list{overflow-y:hidden;max-height:max-content}.form-group.full-height .editor.prosemirror,.editor.prosemirror{min-height:300px}.dsa5.item .item-header{background-size:100% 50px;background-repeat:no-repeat;height:50px}.dsa5.item .item-header h1{margin:0 10%;cursor:pointer}.dsa5.item div.item-header,.dsa5.item .item-header input{text-align:center;padding:8px;background:none;border:none}.item-main .row-section{margin-left:10px;font-size:12px}.item-main .col label,.item-main .col input{border:1px solid var(--border-color)}.item-main label{padding:6px;display:inline-block;width:100%;text-align:center}.item-main.noequipment{margin-top:15px}.dsa5.item .item-main input{margin:0;border-radius:0%;height:29px;margin:0;width:100%;text-align:center}.label-text{border:1px solid var(--border-color);padding:0px 6px;text-align:center}.form-group .label-text i{font-size:10px}.dsa5.item .input-text,.creature-sheet .input-text{border:1px solid var(--border-color);border-radius:0px;height:28px;text-align:center}.dsa5.item select,.creature-sheet select{height:28px;font-family:var(--normalFont);border-radius:0;text-align:center}.dsa5.item section.content{height:calc(100% - 140px)}.dsa5.item section.content .tab.active{height:100%}.directory .directory-list .directory-item.active{border-color:#000}.popoutImage{cursor:pointer}#combat li.combatant .token-initiative .initiative,#combat li.combatant .token-name{text-shadow:none}#combat li.combatant .roll{background-image:url("../../icons/dice/d6white.svg");position:relative}#combat li.combatant .roll:before{position:absolute;content:"6";color:#fff;left:0;right:0;top:-2px;bottom:0}#combat li.combatant .roll:hover{background-image:url("../../icons/dice/d6green.svg")}.window-content>section,.window-content>form{padding:12px}.window-content .dialog-content,.window-content .dialog-buttons{padding:12px}.imagebox{position:relative;height:95px;background-size:cover;display:inline-block}.itemLibrary .detailBox span,.itemLibrary .detailBox input{margin:1px 2px;width:calc(100% - 4px)}.cards-notification .icon,.didYouKnow img,fieldset,.app.sidebar-popout,.dsa5.item h1,.dsajournal img,.itemLibrary img,.charimg,.dsa5.post-item img{border:none}.dsajournal .heading.h3 a:before{content:"";font-family:"Font Awesome 6 Pro";font-weight:900;color:darkred;position:relative;left:-5px}.defender video{margin:5px 25%;border:none}.attacker video,.attacker img{margin:5px 25%;border:none}.defender img{margin:5px 25%;border:none}.sender-image{max-width:30px;height:30px;border:none}.message-sender.with-image{line-height:30px}#scenes .scene h3{text-shadow:none}#scenes .scene h3 a{border:1px solid #403d3d;background-color:rgba(0,0,0,.6);color:#fff;border-radius:10px;padding:0px 10px}#combat li.combatant.active{background:rgba(0,0,0,.1)}li.folder{margin-left:8px}.chatModifiers .expand-mods{float:right;font-size:10px}.expandDetails.shown{display:block}.expandDetails.shown .filterHide{display:block}.expandDetails ul{margin:0 0 .5em 0;list-style-type:none}.expandDetails li{display:inline-block;font-size:12px;margin-right:5px}.mayorAttributeBox{margin-top:10px;max-width:150px}.mayorAttributeBox input,.mayorAttributeBox span{width:35px;display:inline-block}.showAll .notLearned{display:flex}.setCustomPrice.edit .priceTag,.setCustomPrice .customPriceTag{display:none}.minimumColumnLayout .notOnMinimum,.onlySingleColumn,.singleColumnLayout .onlyMultiColumn,.tokenQuickHot .subbuttons .secondary.shown.dsahidden,.domainToggle,.locktrue .advance,.privateMessageIndicator .fas,.chatIndicator .fas,.combatant:not(.active) .aggroButton,.tocCollapsing.expanded .col.three *,.tokenQuickHot .subbuttons .secondary:not(.shown),.hero .details{display:none}[data-hide-damage=true] .damageSecret,[data-hide-damage=true] .die-damage{display:none}.dsahidden,.roll-dialog-tag,.expandDetails{display:none}.chatModifiers ul,.chatModifiers div{display:none}.generationWizard [data-tab=description] h2,.notLearned,.showAll .filterHide,.statusEffectMenu .filterHide,.filterHide{display:none}.singleColumnLayout .onlySingleColumn,.setCustomPrice.edit .customPriceTag{display:block}.row-section.skills.searchbox{margin-bottom:10px;font-weight:normal;color:#0e0c0c}.row-section.skills.searchbox input{display:inline-block;width:calc(100% - 20px)}input[type=search]{width:calc(100% - 2px);min-width:20px;height:26px;background:rgba(0,0,0,.05);padding:1px 3px;margin:0;color:#191813;font-family:inherit;font-size:inherit;text-align:inherit;line-height:inherit;border:1px solid #7a7971;border-radius:3px;-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text}.healthbar{height:24px;border:1px solid #615757;box-sizing:border-box;overflow:hidden;box-shadow:inset 0 0 10px #fff;position:relative;background:rgba(78,70,70,.5411764706)}.barLeft{border-top-left-radius:10px;border-bottom-left-radius:10px;border-right-width:0px}.barRight{border-top-right-radius:10px;border-bottom-right-radius:10px}.barRight.middle{border-radius:0px;border-right:none}.barRight .bar{width:calc(100%*var(--a)/var(--b))}.barLeft .bar{left:calc(100%*(1 - var(--a)/var(--b)));width:calc(100%*var(--a)/var(--b))}.barLeft.soloBar .bar{left:0;width:calc(100%*var(--a)/var(--b))}.bar{height:24px;width:100%;box-shadow:inset 0 0 10px #fff;position:absolute;z-index:0;top:0px;left:0px;transition:width .1s ease-in-out}.soloBar{border-top-right-radius:10px;border-bottom-right-radius:10px;border-right-width:1px}.barLabel{height:22px;padding:1px;text-align:center;box-sizing:border-box;color:#fff;position:relative;z-index:1;text-shadow:0px 0px 3px #000}.barLabel input{height:22px;line-height:22px;width:30px;display:inline-block;border:none;padding:0;margin:0;color:#fff;box-shadow:none;background:none;text-shadow:0px 0px 3px #000}.barLabel input:focus{box-shadow:none}.barLabel input:hover{background-color:rgba(0,0,0,.3)}.barLabel span{width:30px;display:inline-block}.soloBar .LeP{background:linear-gradient(90deg, rgb(101, 7, 7) 0%, rgb(207, 14, 14) 100%)}.LeP{background:#cf0e0e;background:linear-gradient(90deg, rgb(207, 14, 14) 0%, rgb(101, 7, 7) 100%)}.tempLeP{background:#fc8f2a;background:linear-gradient(90deg, rgb(252, 143, 42) 0%, rgb(182, 97, 1) 100%)}.AsP{background:#0e90cf;background:linear-gradient(90deg, rgb(11, 11, 217) 0%, rgb(14, 144, 207) 100%)}.KaP{background:#93cf0e;background:linear-gradient(90deg, rgb(4, 162, 54) 0%, rgb(147, 207, 14) 100%)}.schip{width:25px;height:25px;background-size:contain;background-repeat:no-repeat;display:inline-block}.schip.tiny{width:15px;height:15px}.schip:active,.schip:focus{box-shadow:none;border:none}.emptySchip{background-image:url("../../icons/gray_schip.webp")}.fullSchip{background-image:url("../../icons/schip.webp")}.sheet nav.sheet-tabs .item.active,.tabs .item.active{text-shadow:0 0 10px #bc886f,0 0 10px #bc886f;border-bottom:3px solid var(--border-color)}.sheet nav.sheet-tabs .item{padding:8px 12px 5px 12px;border-bottom:3px solid rgba(0,0,0,0)}.dieButton span{border:1px solid rgba(0,0,0,0)}.dieButton.dieSelected span{border:1px solid #000}.dsa5.item-sheet .statusEffect img,.statusEffect img{border:none;background:rgba(0,0,0,.3);height:28px;width:28px;margin:0}.diseases .statusEffect img{height:20px;width:20px;border:1px solid rgba(0,0,0,0)}.diseases .statusEffect img:hover{border-color:#000}.statusEffect{height:34px;line-height:34px}.statusEffectMenu ul{display:none;position:absolute;right:-10px;top:-10px;width:164px;border:1px solid #000;background:rgba(0,0,0,.7);padding:8px;margin:0;min-height:90px}.statusEffectMenu li.search{display:block;width:100%;margin-bottom:10px}.statusEffectMenu li.search input{color:#fff;width:80%}.statusEffectMenu li.search a{color:#fff;border:1px solid #fff;padding:3px;border-radius:2px}.form-group input::placeholder{color:#adaaaa}.statusEffectMenu li.search input::placeholder{color:#adaaaa}.statusEffectMenu li.search:hover{border-color:rgba(0,0,0,0)}.opposed-message{text-align:center}.statusEffectMenu li{display:inline-block;width:30px;height:30px;border:1px solid rgba(0,0,0,0)}.statusEffectMenu li:hover{border:1px solid #000}.statusEffectMenu img{width:30px;height:30px;border:none}.itemLibrary{padding:10px}.itemLibrary nav{line-height:20px;margin-bottom:10px}.itemLibrary nav img{position:relative;top:3px;margin-right:3px;min-width:20px}.itemLibrary ul{display:flex;flex-wrap:wrap;width:100%}.itemLibrary ul li.browser-item{list-style-type:none;flex:24%;display:inline-block;display:flex;line-height:26px;min-width:120px}.itemLibrary ul li.browser-item .priceDrag{padding-top:2px;min-width:30px;line-height:10px;font-size:10px;cursor:grab;text-overflow:ellipsis;overflow:hidden}.itemLibrary .item-list li.browser-item{flex:49%;border:1px solid #ddd;min-width:240px}.itemLibrary .item-list li.browser-item a{display:inline-block;padding:2px;width:calc(100% - 44px);height:40px;line-height:36px}.itemLibrary .item-list li.browser-item .image{height:40px;width:40px;display:inline-block;background-size:contain}.itemLibrary .categories li label{text-overflow:ellipsis;overflow:hidden;min-width:80px}.lineheight2{line-height:26px}.lineheight2 span{display:inline-block;vertical-align:middle;line-height:12px}.itemLibrary .item-list li a span{display:inline-block;vertical-align:middle;line-height:12px}.dsalist{list-style-type:none}.sheet.journal-entry.dsajournal .pages-list .directory-item .page-heading .page-heading{margin-left:10px}.dsajournal .heading.h2 a:before,.dsalist li::before{content:"";display:inline-block;height:10px;width:20px;position:absolute;left:-20px;top:2px;background-image:url("../../icons/dsalist.webp");background-size:contain;background-repeat:no-repeat}.chatImgPreview .image{width:60px;height:60px;background-size:contain;background-repeat:no-repeat;background-position:center;margin:0 auto}.dsajournal .heading.h2 a:before{position:relative;width:15px;left:-5px}.item .image.extension{height:auto;background-position:center;margin:4px}.extension{background-image:url("../../icons/categories/Spellextension.webp")}.extensions p{line-height:15px}.card-content input{width:30px;display:inline-block}.window-app.largeDialog .window-content .dialog-buttons{flex-grow:0;display:flex}.largeDialog button.default{background:rgba(0,0,0,.05);border:2px groove #c9c7b8}.largeDialog .row-section label{flex:1}.largeDialog .garadanb h2{margin-top:0}.largeDialog h2{margin-top:20px}.largeDialog h3{margin-top:10px}.largeDialog .sheet-tabs{height:32px;flex:0 0 32px;margin:4px 0;border-top:1px solid #b5b3a4;border-bottom:1px solid #b5b3a4}.largeDialog .sheet-tabs .item{padding:8px 12px 5px 12px;border-bottom:2px solid rgba(0,0,0,0)}.largeDialog .show-item{display:inline-block;font-size:10px;border:1px solid #a09494;border-radius:100%;width:20px;height:20px;line-height:18px;color:#5a5a5a;text-align:center}.largeDialog img{border:none;margin-bottom:10px}.largeDialog .error{width:100%}.largeDialog .error p{background:#970808;color:#fff}.chatButton,.roll-button{border:1px solid var(--border-color);padding:2px;border-radius:3px;box-shadow:0 0 12px rgba(110,59,1,.5607843137) inset;display:inline-block}.chatButton img{display:inline-block;margin:0;margin-right:4px;width:15px;height:15px;background:#000;position:relative;top:2px}h2 .chatButton img{width:30px;height:30px;top:5px}h2 .chat-condition,h2 .chatButton{width:100%;border:none;box-shadow:none;background:none}.chatButton i,.roll-button i{margin-right:1px}.botch-roll{color:darkred}.detailbox{border:1px solid var(--border-color);padding:5px}.quickfind{position:absolute;background-image:url("../../icons/backgrounds/quickfind.webp");background-size:100%;background-repeat:no-repeat;background-position:top;padding:15px;padding-top:74px;bottom:100%;width:100%;color:#000;line-height:26px}.quickfind ul{list-style-type:none;margin:0}.quickfind li{padding:0px 4px;display:inline-block;border:2px solid rgba(0,0,0,0);width:100%}.quickfind li:hover{background-color:rgba(0,0,0,.2);text-shadow:none}.quickfind li:before{height:22px;background-position:center}.quickfind li.focus{border:2px solid #946603;border-radius:2px}.fokusregel{width:100px;float:right;background-image:url("../../icons/fokus.webp");background-size:100%;background-repeat:no-repeat;height:72px;text-align:center;line-height:72px;font-family:"Andalus";color:darkred;position:relative;margin-bottom:10px;font-weight:bold}.fokusregel:after{position:absolute;font-size:28px;bottom:0;left:0;right:0}.fokusregel.f1:after{content:"I"}.fokusregel.f2:after{content:"II"}.magazinContainer{display:inline-block;width:3px}.initTracker .item-structure{top:-102%;border-color:#0e0c0c}.item-structure{border:.5px solid var(--bg-color);height:100%;width:4px;position:relative}.item-structure .inner{position:absolute;left:0;right:0;bottom:0;height:calc(100%*var(--b)/var(--a));background-color:#20ca02}a.documentName-link,a.inline-roll{background:var(--bg-color)}.whisper .privateMessageIndicator .fas{display:inline-block;color:#730707}.blind .chatIndicator .fa-eye-slash{display:inline-block;color:#2248a2}#token-hud .attribute.bar1 input{border:1px solid #e60c0c}#token-hud .attribute.bar2 input{border:1px solid #659db5}#token-hud .attribute.bar3{position:absolute;top:-45px}#token-hud .attribute.bar3 input{border:1px solid #7cd000}.specAbsContainer{margin-left:20px;padding:10px}.specAbs{border:1px solid var(--border-color);box-shadow:0 0 12px rgba(110,59,1,.5607843137) inset;border-radius:2px;line-height:20px;color:#888;position:relative}.specAbs>div{padding:3px}.specAbs.active{color:inherit}.specAbs .variantChange{text-align:center;border:1px solid var(--border-color);border-radius:50%;background-color:#5b260c;position:absolute;left:-16px;top:calc(50% - 10px);width:20px;height:20px;line-height:20px;color:#fff;padding:0;transition:all ease-in-out .3s}.specAbs .variantChange:hover{background-color:#000}.noBorder,.bookWizardsheet .window-content .table-title.noBorder,.dialog-buttons img,.result-image{border:none}.bookWizardsheet .sheet.journal-entry .pages-list .heading-link{line-height:inherit}.bookWizardsheet .sheet.journal-entry .pages-list .headings{display:block;font-family:var(--normalFont);margin:6px 0 0 3px;--level-indent: 8px}.bookWizardsheet .sheet.journal-entry .pages-list .headings li{line-height:inherit;height:auto}.libraryImg,.extImg{background-image:url("../../icons/categories/ability_combat.webp");background-size:contain;background-repeat:no-repeat;background-position:center}.specImg{background-image:url("../../icons/categories/ability_combat.webp");background-size:contain;background-repeat:no-repeat;background-position:center}.specImg.ab_1{background-image:url("../../icons/categories/Combat_Skill.webp")}.specImg.ab_2{background-image:url("../../icons/categories/Skill.webp")}.specImg.ab_3{background-image:url("../../icons/categories/Armor.webp")}.specImg.ab_4{background-image:url("../../icons/categories/ability_general.webp")}.libraryImg{background-image:url("../../icons/backgrounds/library.webp");margin-top:50px;height:300px}.extImg{background-image:url("../../icons/categories/Spellextension.webp")}.embeddedItemDrag,.rollTarget{cursor:pointer}.specAbs:hover{cursor:pointer}.specAbs.active{border-color:#cf1e1e}#chat-controls .control-buttons{flex:0 0 72px}.centerMargin,.loader{margin:0 auto}.libItem .compendium{font-size:10px;color:#696767;line-height:10px;text-align:center;pointer-events:none}.browser-item:hover{box-shadow:inset 0px 0px 5px #000}.browser-item a:hover{text-shadow:none}.browser-item .compendium{position:absolute;bottom:2px;right:2px;font-size:10px;color:#696767;line-height:10px}.chat-condition,.item-sheet .chatButton,.dsajournal .chatButton{padding:0px 4px;border:1px solid #4b4a44;border-radius:2px;white-space:nowrap;word-break:break-all;box-shadow:none;background:var(--bg-color);display:inline}.chat-condition img,.item-sheet .chatButton img,.dsajournal .chatButton img{top:3px}.obfuscationBtn:nth-of-type(2){display:none}.chatpaperfield{border-image:url("../../icons/backgrounds/chatpaper_v45.webp");clear:both;border-image-width:24px;border-image-slice:70 70 70 fill;margin:25px 0px;padding:20px 20px 20px 30px}.maskfield{position:relative;clear:both;padding:70px 30px 30px 30px;margin:34px 0px;border-image:url("../../icons/backgrounds/maskfield_v45.webp");border-image-width:60px 20px 60px 20px;border-image-slice:90 30 90 30 fill}.citefield{position:relative;clear:both;padding:30px;margin:25px 0px;border-image:url("../../icons/backgrounds/cite_v45.webp");border-image-width:60px 20px 60px 20px;border-image-slice:90 30 90 30 fill}.dsajournal .window-content .maskfield tr:first-child{background:none}.nobr{white-space:nowrap}select.noAppearance{-webkit-appearance:none;appearance:none;height:auto;text-align:center;width:100%}.aggroButton{border-radius:100%;padding:3px;display:block;width:24px;position:absolute;left:-20px;height:24px;margin-top:12px;border:1px solid darkred;background-color:#fff;cursor:pointer;box-shadow:2px 2px 6px #000;z-index:1}.aggroButton:hover{background-color:#d1d1ca}#combat-popout.combat-sidebar li.combatant .token-initiative .initiative,#combat-popout.combat-sidebar li.combatant .token-name{text-shadow:none}#combat-popout .aggroButton{left:-1px}.adventurePoints .row-section:hover{background-color:rgba(0,0,0,.2)}.adventurePoints .fa-plus,.adventurePoints .fa-angles-up{color:green}.adventurePoints .fa-minus,.adventurePoints .fa-angles-down{color:darkred}.effect-change .key input{width:90%}.effect-change .selMenu+.select2{width:8%;background:#efe4e4;position:absolute}.effect-change .selMenu+.select2 .select2-selection__rendered{width:0px;padding:0}.effect-change .selMenu+.select2.select2-container--open{width:100%;left:0}.effect-change .selMenu+.select2.select2-container--open .select2-selection__rendered{width:100%;padding:0}.gearDamaged,.resistEffect,.applyEffect,.applyTableEffect,.placeTemplate,.smallChatButton{width:100%;padding:4px;height:100%;line-height:unset;font-size:11px}.adventureWizard .fa-toggle-on,.adventureWizard .fa-check{color:green}.adventureWizard .fa-toggle-off,.adventureWizard .fa-times{color:darkred}.adventureWizard .toc{list-style-type:none;padding-left:4px}.adventureWizard .toc ul{list-style-type:none;padding-left:0px}.tocCollapsing.expanded .col.three{flex:20px}.tocCollapsing.expanded .col.seventy{flex:calc(100% - 20px)}.tocCollapserBox{position:relative;height:0}.tocCollapser{position:absolute;top:30px;left:-5px;font-size:10px}.getChapter.selected,.subChapter.selected{font-weight:bold}.inputTooltipAvailable:after{content:"*";position:absolute;right:3px;top:3px;font-size:10px;color:#82817d}.subChapter{font-weight:normal;font-family:var(--normalFont)}.toc ul li{display:block;padding:4px}.toc ul li:before{color:darkred;margin-right:5px}.adventureWizard .cover{width:98%;position:relative}.scrollable{overflow-y:auto;max-height:100%}.adventureWizard{max-height:100%}.adventureWizard>div{max-height:100%}.adventureWizard .chapter{padding:8px}.adventureWizard .chapter *{user-select:text}.adventureWizard .toc{scrollbar-width:6px}.adventureWizard .toc::-webkit-scrollbar{width:6px}.adventureWizard .picto{height:40px;line-height:40px}.adventureWizard .breadcrumbs{display:flex;background-color:rgba(202,183,180,.3803921569);border-radius:5px;border-bottom:1px solid #b5b3a4;border-top:1px solid #b5b3a4}.adventureWizard .breadcrumbs>div{flex:1;max-width:150px;min-width:150px;border-radius:5px;padding:3px;margin:1px;box-shadow:inset 0px 0px 3px #000;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:all .3s ease-in-out;text-align:center}.adventureWizard .breadcrumbs>div:hover{cursor:pointer;background-color:rgba(14,12,12,.3);color:#fff}.picto.ten{max-width:10%}.picto.fourty{max-width:40%}.journalHeader .jrnIcons{color:#5c5c5c;float:right}.journalHeader .jrnIcons a{display:inline-block;margin-right:10px}.position-relative{position:relative}.combatant-advanced{flex:0 0 48px;position:relative;height:50px}.combatant-advanced i{position:absolute;bottom:0;right:0;color:#000;width:14px}.combatant-advanced .actions,.combatant-advanced .ongoing{font-size:10px;background:#6f3900;width:14px;height:15px;padding:0;margin:0;line-height:15px;text-align:center;color:#fff;border-radius:50px;position:absolute;right:0;top:0}.combatant-advanced .actions{left:0;right:auto;background:#6d0400}.initTracker .combatant-advanced .actions{right:0;left:unset}.initTracker .combatant-advanced .ongoing{bottom:4px;top:unset}.combatant-advanced i.reversed{transform:scaleX(-1)}.combatant-advanced i.def:after{content:attr(data-defenseCount);position:absolute;left:0;right:0;text-align:center;z-index:1;color:#fff;font-size:10px;line-height:12px}.initTracker .combatant-advanced{height:var(--iniTrackerSize)}.initTracker .combatant-advanced i{left:4px;bottom:4px;right:unset}.tinyEntityLink a{width:22px;overflow:hidden;font-size:12px;float:right;overflow:hidden;border:1px solid #000}.tokenQuickHot{position:absolute;top:0;height:var(--tokenQuickhotsize);left:5px;right:7px;z-index:-2;transition:transform .3s ease-in-out}.tokenQuickHot ul{font-size:0;display:inline-block}.tokenQuickHot.expanded{transform:translateY(-45px)}.tokenQuickHot .subbuttons{position:absolute;z-index:2}#controls ol li.control-tool[data-tool=targetUser]{color:#609ec6}.tokenQuickHot .direction0 .subbuttons{bottom:var(--tokenQuickhotdistance)}.tokenQuickHot .direction1 .subbuttons{right:var(--tokenQuickhotdistance)}.tokenQuickHot .direction2 .subbuttons{top:var(--tokenQuickhotdistance)}.tokenQuickHot .direction3 .subbuttons{left:var(--tokenQuickhotdistance)}.tokenQuickHot .direction1 .dragHandler,.tokenQuickHot .direction3 .dragHandler{height:14px;width:var(--tokenQuickhotsize);line-height:14px}.initTracker .dragHandler,.tokenQuickHot .dragHandler{width:14px;height:var(--tokenQuickhotsize);background:rgba(0,0,0,.2);text-align:center;line-height:var(--tokenQuickhotsize);float:right}.initTracker .dragHandler:hover{color:#fff}.tokenQuickHot .dragHandler:hover{color:#fff}.tokenQuickHot a{box-shadow:inset 0px 0px 10px #403014;color:#fff;padding:2px;margin-bottom:2px}.tokenQuickHot .effect>div{background-color:rgba(0,0,0,.3)}.initTracker li,.tokenQuickHot li{background-color:rgba(0,0,0,.5);display:inline-block;font-size:14px;width:var(--tokenQuickhotsize);height:var(--tokenQuickhotsize);border:1px solid #000;border-radius:3px;pointer-events:all;background-size:cover;box-shadow:inset 0px 0px 5px #636363;background-repeat:no-repeat;position:relative;box-sizing:border-box}.tokenQuickHot li input{color:#fff}.tokenQuickHot li .subbuttons li{width:200px;height:28px;line-height:28px}.initTracker .waitingTackerList li{width:calc(var(--iniTrackerSize)*.5);height:calc(var(--iniTrackerSize)*.5)}.waitingTackerList{position:absolute;top:calc(var(--iniTrackerSize)*-0.5);left:30px;z-index:-1}.initTracker .newRound{border-color:#496fd7;background-color:rgba(73,111,215,.1764705882);box-shadow:inset 0px 0px 10px #496fd7;border-top-left-radius:0px;border-bottom-left-radius:0px}.initTracker .turnRound{padding:2px;border-radius:100%;width:21px;display:inline-block}.initTracker .newRound .turnRound{background-color:#496fd7}.initTracker .waitTitle{background-image:none}.initTracker .waitTitle i{float:left;width:100%;line-height:calc(var(--iniTrackerSize)*.5);text-align:center;color:#fff}.initTracker li{box-shadow:none;border:1px solid rgba(0,0,0,0);background-color:rgba(0,0,0,0);cursor:pointer;background-color:rgba(0,0,0,.5);border-radius:10px}.initTracker li .roll:before{position:absolute;content:"6";color:#fff;left:0;right:0;top:5px;bottom:0;text-align:center}.initTracker .token-initiative{position:absolute;bottom:-20px;left:0;right:0}.initTracker .aggroButton{left:0;right:0;margin:0 auto 0;bottom:0}.initTracker li .roll{position:relative;display:block;width:30px;height:30px;background:url("../../icons/dice/d6white.svg") no-repeat 50% 50%;background-size:auto;background-size:35px;margin:0 auto}.initTracker li.active{border-color:#fff;box-shadow:inset 0px 0px 10px #fff}.initTracker li.defeated,.initTracker li.hidden{opacity:.5}.initTracker li.defeated{background-size:75% 75%;background-position:center}.iniTrackerList{margin:0;padding:0;display:inline-block}.initTracker .dragHandler{width:15px;background:none;border:none;line-height:var(--iniTrackerSize)}.initTracker li{width:var(--iniTrackerSize);height:var(--iniTrackerSize)}#hotbar .skillItems li:hover,.tokenQuickHot li:hover{border:1px solid red;cursor:pointer}.tokenStatusEffects .dialog-content{height:100%;min-height:calc(100% - 24px)}.tokenQuickHot .tokenHotbarInner{opacity:var(--tokenHotbarOpacity);transition:opacity .3s ease-in-out}.tokenQuickHot .tokenHotbarInner:hover{opacity:1}.tokenQuickHot .tokenHotbarInner .skillgm.body,.tokenQuickHot .tokenHotbarInner .skill.body{background:#4f6d65;box-shadow:none;background:linear-gradient(90deg, rgb(79, 109, 101) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.social,.tokenQuickHot .tokenHotbarInner .skill.social{background:#85302e;box-shadow:none;background:linear-gradient(90deg, rgb(133, 48, 46) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.knowledge,.tokenQuickHot .tokenHotbarInner .skill.knowledge{background:#4b6585;box-shadow:none;background:linear-gradient(90deg, rgb(75, 101, 133) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.trade,.tokenQuickHot .tokenHotbarInner .skill.trade{background:#cda25e;box-shadow:none;background:linear-gradient(90deg, rgb(205, 162, 94) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner .skillgm.nature,.tokenQuickHot .tokenHotbarInner .skill.nature{background:#535829;box-shadow:none;background:linear-gradient(90deg, rgb(83, 88, 41) 0%, rgb(255, 255, 255) 100%)}.tokenQuickHot .tokenHotbarInner div{background-size:cover;height:100%;width:100%;position:absolute;color:#fff;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000}.tokenQuickHot .tokenHotbarInner input{height:var(--tokenQuickhotsize);display:block;width:100%;margin:0;float:left;text-align:center;font-size:20px;border:none}.tokenQuickHot .tokenHotbarInner .itdarkness{width:calc(var(--tokenQuickhotsize)*2);position:relative}.tokenQuickHot .tokenHotbarInner .itdarkness input{height:auto;position:absolute;bottom:0}.tokenQuickHot .tokenHotbarInner .itdarkness i{position:absolute;top:4px;left:6px;color:#8a6100}.tokenQuickHot .tokenHotbarInner .itdarkness i.fa-moon{color:#05235b;right:6px;left:unset}.tokenQuickHot .tokenHotbarInner .subbuttons .combatTooltip{height:35px;line-height:35px;text-align:center;width:100px}.tokenQuickHot .tokenHotbarInner .subbuttons div{background-size:contain;background-repeat:no-repeat;background-position:center;width:30px;position:inherit;float:left}.tokenQuickHot .tokenHotbarInner .subbuttons label{display:inline-block;cursor:pointer;overflow:hidden;max-width:155px;text-overflow:ellipsis;white-space:nowrap}.tokenQuickHot li span{position:absolute;top:-25px;left:-73px;background:#1d1c1c;width:180px;display:inline-block;color:#fff;padding:5px;text-align:center;border-radius:4px}.tokenQuickHot li .fa{font-size:calc(var(--tokenQuickhotsize) - 15px);line-height:var(--tokenQuickhotsize);text-align:center}.tokenQuickHot li.spell{box-shadow:inset 0px 0px 10px #121092}.tokenQuickHot li.skill{box-shadow:inset 0px 0px 10px #0d813e}.window-app.initTracker .window-header,.window-app.tokenQuickHot .window-header{display:none}.window-app.initTracker,.window-app.tokenQuickHot{padding:0}.initTracker .controls{display:inline-block;width:29px}.initTracker:hover .iniDetailsList{display:block}.iniDetailsList{margin:30px 29px 0 29px;padding:0;display:none}.iniDetailsList li{height:20px;text-align:center;background:rgba(0,0,0,.5);color:#fff}.initTracker .hoverbuttons{color:#fff;position:absolute;right:0;top:25%;opacity:0;transform:opacity .3s}.initTracker .combat-control{min-width:20px;display:inline-block}.initTracker li:hover .hoverbuttons{opacity:1}.initTracker .controls i{color:#fff;background:rgba(0,0,0,.7);border-radius:5px}.initTracker .controls.right{text-align:right}.initTracker button{line-height:21px}.tokenHotbarInner>ul>li.effect>div:before{font-family:"Font Awesome 5 Free";font-weight:900;content:""}.window-app.initTracker::after,.window-app.initTracker .window-content{background:none;margin:0;padding:0;overflow:visible}.window-app.tokenQuickHot::after,.window-app.tokenQuickHot .window-content{background:none;margin:0;padding:0;overflow:visible}.window-app.initTracker::after,.window-app.tokenQuickHot::after{content:none}.ench-fw{position:relative;top:-3px}.bags .slot{width:50px;height:50px;background-size:contain;border:1px solid var(--border-color);background-color:#faebd7;background-repeat:no-repeat;background-position:center;border-radius:5px;cursor:pointer}.bags .slot.deactivated{opacity:.5}.bags .slot:hover{border-color:#0a59c2}.itemInfo{position:absolute;display:none;width:200px;border:1px solid var(--border-color);padding:5px;background-color:rgba(0,0,0,.8);color:#fff;border-radius:5px}.bagUsage{position:relative;border:1px solid var(--border-color);margin:5px;background-color:rgba(14,12,12,.1)}.bagUsage .fillage{position:absolute;top:0;left:0;bottom:0;background-color:#40a9dd}.bagUsage .fillage.exceeded{background-color:#d42d2d}.bagUsage .fillText{position:relative;z-index:1}.fa-dsa5-player,.fa-dsa5{position:relative;width:25px;height:25px}.fa-dsa5-player:before,.fa-dsa5:before{content:"";background-image:url("../../icons/categories/DSA-Auge.webp");background-size:contain;background-repeat:no-repeat;background-position:center;position:absolute;left:0;right:0;top:0;bottom:0}.fa-dsa5-player:before{background-image:url("../../icons/categories/DSA-Auge-Spieler.webp")}.columnFlex{display:flex;flex-direction:column}.verticalFlex{display:flex;flex-direction:row;position:relative}.verticalFlex .bar{flex:1;height:30%}.verticalFlex .bar.AsP{top:30%}.verticalFlex .bar.KaP{top:60%}.bar-wounds.swarmcount:after{content:"";position:absolute;top:0;left:0;right:0;bottom:0;background-image:linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 98%, rgba(0, 0, 0, 0.3) 100%);background-size:calc(100%/var(--swarm) + .1%) 100%;background-repeat:repeat-x}.hero.victim{box-shadow:inset 0px 0px 10px #8a0202}.smallBoxItem,.hero .actorItem{display:inline-block;padding:2px;border:1px solid var(--border-color);line-height:12px;border-radius:2px}.domainsPretty li{display:inline-block;border:ridge 2px #daa520;line-height:18px;border-radius:2px;margin:3px;padding:0px 8px;box-shadow:1px 1px 3px #000;background-color:#f4da99}.domainsPretty li.magical{border-color:#0a59c2;background-color:#c0dbff}.domainsPretty li.blessed{border-color:#006f3d;background-color:#bae1b1}#combat li.combatant .token-resource{color:#777171}.progress{width:27px;height:27px;line-height:27px;background:none;margin:0 auto;box-shadow:none;position:relative;float:right}.progress>span{width:50%;height:100%;overflow:hidden;position:absolute;top:0;z-index:1}.progress .progress-left{left:0}.progress .progress-bar{width:100%;height:100%;background:none;border-width:2px;border-style:solid;position:absolute;top:0}.progress .progress-left .progress-bar{left:100%;border-top-right-radius:13.5px;border-bottom-right-radius:13.5px;border-left:0;-webkit-transform-origin:center left;transform-origin:center left;transform:rotate(var(--transformLeft))}.progress .progress-right{right:0}.progress .progress-right .progress-bar{left:-100%;border-top-left-radius:13.5px;border-bottom-left-radius:13.5px;border-right:0;-webkit-transform-origin:center right;transform-origin:center right;transform:rotate(var(--transformRight))}.progress .progress-value{width:90%;height:90%;border-radius:50%;color:#44484b;font-size:8px;line-height:27px;text-align:center;position:absolute;top:5%;left:5%}.progress.blue .progress-bar{border-color:#0e4f79}.patchviewer h1{margin:0}.patchviewer h1 a{display:block;float:left;color:#000}.patchviewer h1 img{width:50px;margin:0;margin-right:15px;float:left}.patchviewer .table-title{border:1px solid var(--border-color);border-radius:10px}.noscrollWizard .content{overflow-y:hidden}.skill-test .targets{align-items:center;justify-content:center;margin-bottom:20px}.skill-test .targets .image{width:40px;height:40px;position:relative}.multipleTarget{margin-left:25px}.missingTarget{margin-left:25px}.missingTarget div i{color:darkred}.skill-test .targets div i{color:darkred}.targets .addTarget{margin-left:20px}.targetChoser .combatant{border:1px solid rgba(0,0,0,0)}.targetChoser .combatant.hidden{opacity:.5}.targetChoser .combatant:hover{background:rgba(0,0,0,.1)}.targetChoser .combatant.selectedTarget{border-color:#000}.multipleTarget i{color:#e68044}.skill-test .targets .image i{position:absolute;z-index:1;bottom:0;left:0;top:0;right:0}.libButton .label-text i{font-size:12px}.libButton .fa-toggle-off{color:darkred;margin-right:6px}.libButton .on .fa-toggle-off{color:green}.libButton .on .fa-toggle-off:before{content:""}.searchMatch{background-color:#ff0}.searchLines{position:absolute;top:0px;right:0;width:16px;bottom:0;pointer-events:none}.searchLines .marker{position:absolute;width:100%;height:2px;background-color:#fff;pointer-events:none}.tinyHudIcons{border:1px solid #000;margin-left:1px;width:40px;border-radius:5px;height:40px;background-image:url("../../icons/backgrounds/macrobg.webp");background-repeat:no-repeat}.advancedSearch .groupbox{margin:0;margin-right:10px;padding:3px}.advancedSearch .groupbox select{width:100%}.advancedSearch .groupbox .form-group{margin-top:4px}.advancedSearch .cbParent{line-height:24px}.advancedSearch .cbParent label{text-overflow:ellipsis}.advancedSearch input[type=checkbox]{float:right}input[type=checkbox].autoCheckbox{width:auto;height:auto}.slot,.gearD{z-index:0;position:relative}.item .image.rar,.item .image.common{z-index:0;position:relative}.gearD:before{content:"";background-size:contain;background-repeat:no-repeat;position:absolute;width:12px;height:12px;left:25px;bottom:0;z-index:1}.damaged1:before{background-image:url("../../icons/damaged1.webp")}.damaged2:before{background-image:url("../../icons/damaged2.webp")}.damaged3:before,.damaged4:before{background-image:url("../../icons/damaged3.webp")}.slot div{height:100%;background-size:contain}.damaged1 .slot.rar:after,.slot.common:after{content:"";background-image:url("../../icons/backgrounds/common.webp");background-size:contain;background-repeat:no-repeat;position:absolute;left:0;right:0;bottom:0;top:0;z-index:-1;opacity:.4}.image.rar:after,.image.common:after{content:"";background-image:url("../../icons/backgrounds/common.webp");background-size:contain;background-repeat:no-repeat;position:absolute;left:0;right:0;bottom:0;top:0;z-index:-1;opacity:.4}.image.rar:after,.image.common:after{background-position:4px 0px}.image.rar:after{background-image:url("../../icons/backgrounds/rar.webp");opacity:.7}.defenseToggle .off{color:#d3d3d3}.garadanborder{max-width:80%;border-image-source:url("../../icons/backgrounds/garadanborder.webp");clear:both;border-image-width:16px;border-image-slice:16 5 33 5 fill;margin:0 auto}.garadanborder .innersection{padding-bottom:20px}.garadanb.garadanborder,.garadanb{max-width:100%;border-image-width:16px;border-image-slice:30 5 50 5 fill;text-align:center;font-weight:bold;letter-spacing:1px}.garadanb.garadanborder *,.garadanb *{border:none}.garadanb.garadanborder small,.garadanb small{font-size:smaller;line-height:auto;font-weight:normal;letter-spacing:0px;margin:0;padding:0}.garadanb{padding-bottom:30px;border-image-source:url("../../icons/backgrounds/garadanb.webp")}.garadanb.garadanborder{position:initial;border-image-slice:16 5 33 5 fill;padding-bottom:0px;border-image-source:url("../../icons/backgrounds/garadanborder.webp")}.garadanicon{background-repeat:no-repeat;background-size:contain;height:55px;margin-left:55%;margin-top:12px;background-position:center;width:55px}.garjourn{display:inline-block;width:15px;height:15px;background-size:contain;background-repeat:no-repeat;margin-left:3px;margin-right:3px}.garjourn.boronsrad{background-image:url("../../icons/Garadan6.webp")}.garjourn.koenig{background-image:url("../../icons/KoenigIcon.webp")}.garjourn.springer{background-image:url("../../icons/SpringerIcon.webp")}.garjourn.turm{background-image:url("../../icons/TurmIcon.webp")}.garjourn.bauer{background-image:url("../../icons/BauerIcon.webp")}.journal-picto{display:inline-block;position:relative;min-width:20px;margin-left:5px}.journal-picto:before{content:"";position:absolute;bottom:0;top:0;left:0;right:0;background-repeat:no-repeat;background-position:center;background-size:contain}.garadanborder h2{text-decoration:none;border:none;margin:0;margin-top:0px;margin-top:20px;font-size:24px;line-height:24px}.garadanborder h3{margin:0;border:none;font-size:14px}.reactClick{margin:2px}.reactClick img{width:26px;float:left;border:none}.didYouKnow,.tinyNotifications li{background-color:rgba(0,0,0,.548);color:#fff;border-radius:10px;padding:10px}.bumFight,.didYouKnow{position:fixed;top:40%;left:calc(50% - 200px);z-index:1002;width:400px;display:none}.bumFight .col.five,.didYouKnow .col.five{display:flex;justify-content:center;align-items:center}.bumFight{display:block;transition:all 2s ease;width:500px;left:calc(50% - 250px);top:20%}.bumFight .intererior{position:absolute;top:calc(50% - 175px);left:0;bottom:0;right:0}.bumFight .fist{border:none;width:250px;height:250px;margin-left:110px;margin-top:80px;position:relative;z-index:-1;animation:bumAnimation .5s cubic-bezier(0.64, 0, 0.78, 0) 0s 1 normal forwards,bumAnimation2 .7s cubic-bezier(0.64, 0, 0.78, 0) .5s 1 normal forwards}.bumFight .title{border-bottom:none;text-align:center;font-size:40px;position:relative;z-index:1;background:url("../../../../ui/pausebg.png") no-repeat 50% 50%;color:#fff;border-radius:10px;padding:10px;text-shadow:#000;animation:bumAnimation .5s cubic-bezier(0.64, 0, 0.78, 0) 0s 1 normal forwards,bumAnimation2 .7s cubic-bezier(0.64, 0, 0.78, 0) .5s 1 normal forwards}.bumFight .glass{border:none;width:500px;height:500px;opacity:0;animation:windowAnim .5s cubic-bezier(0.64, 0, 0.78, 0) 0s 1 normal forwards}@keyframes bumAnimation{0%{transform:scale(0);opacity:0}50%{opacity:1}100%{transform:scale(1)}}@keyframes windowAnim{0%{opacity:0}99%{opacity:0}100%{opacity:1}}@keyframes bumAnimation2{0%{animation-timing-function:ease-out;transform:scale(1);transform-origin:center center}10%{animation-timing-function:ease-in;transform:scale(0.91)}17%{animation-timing-function:ease-out;transform:scale(0.98)}33%{animation-timing-function:ease-in;transform:scale(0.87)}45%{animation-timing-function:ease-out;transform:scale(1)}}.flexAlignCenter{justify-content:center;align-items:center}.settings-sidebar button{margin:3px 0}#sidebar{overflow:visible}.plantContainer{display:inline-block;position:relative;cursor:pointer;height:45px;width:45px}.plantContainer input{position:absolute;opacity:0;height:45px;width:45px}.plantContainer span{position:absolute;top:0;left:0;height:45px;width:45px;background:url("../../icons/categories/planthealing.webp");background-position:center;background-size:contain;background-repeat:no-repeat;opacity:.45;transition:all .3s ease-in-out}.plantContainer.defensive span{background-image:url("../../icons/categories/plantdefensive.webp")}.plantContainer.psychic span{background-image:url("../../icons/categories/plantpsychic.webp")}.plantContainer.physical span{background-image:url("../../icons/categories/plantphysical.webp")}.plantContainer.crop span{background-image:url("../../icons/categories/plantcrop.webp")}.plantContainer.poison span{background-image:url("../../icons/categories/plantpoison.webp")}.plantContainer.supernatural span{background-image:url("../../icons/categories/plantsupernatural.webp")}.plantContainer:hover input~span,.plantContainer input:checked~span{opacity:1}.tinyNotifications{position:fixed;top:calc(100% - 250px);left:50px;list-style:none;margin:0;padding:0;z-index:160}.fxmaster .window-content .directory-item .config input[type=text]{color:#000}.ammo-selector{width:calc(100% - 31px);padding:0px;margin:0px 1px}.window-app .condition-show{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.panToToken{cursor:pointer}.panToToken:hover{box-shadow:inset 0px 0px 5px #000}.rowHover:hover{box-shadow:inset 0px 0px 5px #000}#sidebar,#players,#hotbar{position:relative}.effect-change input::placeholder{color:#a9a7a0}.select2-results__option[role=group]:hover{background-color:rgba(0,0,0,0)}.postChatSection.maskfield:after{background-image:url("../../icons/backgrounds/blackbook.webp");background-size:250px 30px;background-position:center calc(100% - 8px)}.postChatSection .postContentChat{cursor:pointer}.postChatSection .postContentChat em{padding:5px;border-radius:50%;transition:.3s ease-in-out all}.postChatSection .postContentChat:hover em{background-color:#fff;color:#000}.navWrapper{position:relative}.navWrapper .sheet-tabs{white-space:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar;scrollbar-width:none;user-select:none;scroll-behavior:smooth}.navWrapper .sheet-tabs::-webkit-scrollbar{display:none}.navWrapper .sheet-tabs.dragging{scroll-behavior:unset;cursor:grab}.navWrapper .sheet-tabs.dragging.left-btn,.navWrapper .sheet-tabs.dragging.right-btn{pointer-events:none}.navWrapper .tabs{justify-content:initial}.navWrapper .tabs .item{flex:1}.navWrapper .right-btn,.navWrapper .left-btn{position:absolute;font-size:1.4em;cursor:pointer;padding:8px;color:#756c6c;display:none;backdrop-filter:blur(10px)}.navWrapper .right-btn{right:0}.navWrapper .left-btn{left:0}.itemTooltip{max-height:500px;text-overflow:ellipsis;overflow:hidden}.itemTooltip p{text-overflow:ellipsis;overflow:hidden}.itemTooltip h1{border:none;font-size:22px;line-height:26px}.itemTooltip .col{flex:50%}.itemTooltip .show-item{display:none}#hotbar.hotbarV3{margin-bottom:0}#hotbar.hotbarV3 .sections{max-height:90px;height:90px;background-color:rgba(0,0,0,.5)}#hotbar.hotbarV3 .categoryFilters{height:30px}#hotbar.hotbarV3 .actorEffects{align-items:flex-end}#hotbar.hotbarV3 .function{color:#fff;right:0}#hotbar.hotbarV3 li,#hotbar.hotbarV3 ul{margin:0;padding:0;list-style:none}#hotbar.hotbarV3 li .fa{font-size:30px;line-height:45px;text-align:center}#hotbar.hotbarV3 .actorEffect:first-child{margin-left:auto}#hotbar.hotbarV3 .actorEffect div{width:28px;height:28px;background-size:contain}#hotbar.hotbarV3 .categoryFilter{overflow:hidden}#hotbar.hotbarV3 .categoryFilter:first-child{border-top-left-radius:10px}#hotbar.hotbarV3 .categoryFilter:last-child{border-top-right-radius:10px}#hotbar.hotbarV3 .actorEffect,#hotbar.hotbarV3 .categoryFilter{flex:0 0 30px;border:1px solid #000;box-shadow:inset 0px 0px 5px #636363;height:30px;width:30px;cursor:pointer;background-size:cover;line-height:30px;text-align:center;background-color:rgba(0,0,0,.5);color:var(--color-text-light-heading)}#hotbar.hotbarV3 .actorEffect.active,#hotbar.hotbarV3 .categoryFilter.active{border-color:#006400}#hotbar.hotbarV3 .actorEffect:hover,#hotbar.hotbarV3 .categoryFilter:hover{border-color:#ff4500}#hotbar.hotbarV3 .actorEffect div,#hotbar.hotbarV3 .categoryFilter div{background-size:cover;height:100%;width:100%}#hotbar.hotbarV3 .actorEffect{align-self:flex-end}#hotbar.hotbarV3 #hotbar-directory-controls{margin-top:30px;height:90px}#hotbar.hotbarV3 .quickFunctions{display:flex;flex-wrap:wrap;justify-content:center;flex-direction:column}#hotbar.hotbarV3 .quickFunctions li{flex:0 0 20px;margin-left:5px;height:20px;width:20px;cursor:pointer;pointer-events:all;background-size:cover;background-repeat:no-repeat;position:relative;box-sizing:border-box}#hotbar.hotbarV3 .quickFunctions li.itdarkness{height:90px}#hotbar.hotbarV3 .quickFunctions li div{height:100%;width:100%;position:absolute}#hotbar.hotbarV3 .effect div{color:#000;font-size:24px;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff}#hotbar.hotbarV3 .itdarkness{line-height:0}#hotbar.hotbarV3 .itdarkness .rangeContainer{height:55px}#hotbar.hotbarV3 .updateDarkness{writing-mode:bt-lr;-webkit-appearance:slider-vertical;appearance:slider-vertical;width:50px;height:100%;transform:rotate(-90deg);margin-top:15px;margin-left:-15px}#hotbar.hotbarV3 .longLayout .skillItems li{flex:0 0 90px;text-align:center;max-width:90px}#hotbar.hotbarV3 .longLayout .skillItems li div{display:none}#hotbar.hotbarV3 .longLayout .skillItems li .nameContent{line-height:45px;display:block;overflow:hidden;text-overflow:ellipsis}#hotbar.hotbarV3 #macro-list,#hotbar.hotbarV3 .skillItems{margin:0;padding:0;white-space:nowrap;overflow-y:scroll;display:flex;flex-wrap:wrap;height:100%;transition:all .15s ease-in-out;scroll-snap-type:y mandatory}#hotbar.hotbarV3 #macro-list input,#hotbar.hotbarV3 .skillItems input{height:100%;display:block;width:100%;margin:0;float:left;text-align:center;font-size:20px;color:#fff}#hotbar.hotbarV3 #macro-list.collapsedKeydown,#hotbar.hotbarV3 #macro-list.collapsed,#hotbar.hotbarV3 .skillItems.collapsedKeydown,#hotbar.hotbarV3 .skillItems.collapsed{width:0px;flex:0}#hotbar.hotbarV3 #macro-list .nameContent,#hotbar.hotbarV3 .skillItems .nameContent{display:none;color:#fff}#hotbar.hotbarV3 #macro-list .skillgm .nameContent,#hotbar.hotbarV3 #macro-list .skill .nameContent,#hotbar.hotbarV3 .skillItems .skillgm .nameContent,#hotbar.hotbarV3 .skillItems .skill .nameContent{color:#000}#hotbar.hotbarV3 #macro-list .skillgm.body,#hotbar.hotbarV3 #macro-list .skill.body,#hotbar.hotbarV3 .skillItems .skillgm.body,#hotbar.hotbarV3 .skillItems .skill.body{background:#4f6d65;box-shadow:none;background:linear-gradient(90deg, rgb(79, 109, 101) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.social,#hotbar.hotbarV3 #macro-list .skill.social,#hotbar.hotbarV3 .skillItems .skillgm.social,#hotbar.hotbarV3 .skillItems .skill.social{background:#85302e;box-shadow:none;background:linear-gradient(90deg, rgb(133, 48, 46) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.knowledge,#hotbar.hotbarV3 #macro-list .skill.knowledge,#hotbar.hotbarV3 .skillItems .skillgm.knowledge,#hotbar.hotbarV3 .skillItems .skill.knowledge{background:#4b6585;box-shadow:none;background:linear-gradient(90deg, rgb(75, 101, 133) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.trade,#hotbar.hotbarV3 #macro-list .skill.trade,#hotbar.hotbarV3 .skillItems .skillgm.trade,#hotbar.hotbarV3 .skillItems .skill.trade{background:#cda25e;box-shadow:none;background:linear-gradient(90deg, rgb(205, 162, 94) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list .skillgm.nature,#hotbar.hotbarV3 #macro-list .skill.nature,#hotbar.hotbarV3 .skillItems .skillgm.nature,#hotbar.hotbarV3 .skillItems .skill.nature{background:#535829;box-shadow:none;background:linear-gradient(90deg, rgb(83, 88, 41) 0%, rgb(255, 255, 255) 100%)}#hotbar.hotbarV3 #macro-list>li,#hotbar.hotbarV3 .skillItems>li{flex:0 0 var(--base-bar-height);height:var(--base-bar-height);border:1px solid #000;background-color:rgba(0,0,0,.5);pointer-events:all;background-size:cover;box-shadow:inset 0px 0px 5px #636363;background-repeat:no-repeat;position:relative;box-sizing:border-box;scroll-snap-align:start}#hotbar.hotbarV3 #macro-list>li.unequipped,#hotbar.hotbarV3 .skillItems>li.unequipped{background:#006400;box-shadow:inset 0px 0px 25px #000;filter:grayscale(100%)}#hotbar.hotbarV3 #macro-list>li:hover,#hotbar.hotbarV3 .skillItems>li:hover{border-color:#ff4500}#hotbar.hotbarV3 #macro-list>li div,#hotbar.hotbarV3 .skillItems>li div{background-size:cover;height:100%;width:100%;position:absolute;color:#fff;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;transition:all .15s ease-in-out}#hotbar.hotbarV3 #macro-list>li div:hover,#hotbar.hotbarV3 .skillItems>li div:hover{transform:scale(1.1)}#hotbar.hotbarV3 #macro-list{border:none}@media(max-width: 1120px){#hotbar.hotbarV3{height:var(--hotbar-height)}}.dsa5-immersive .tokenQuickHot li{box-shadow:inset 0px 0px 5px #403014;background-image:url("../../icons/backgrounds/macrobg.webp")}.dsa5-immersive .tokenQuickHot li input{color:#000}.dsa5-immersive .sidebar-tab .directory-list .directory-item.collapsed{color:#fff}.dsa5-immersive .sidebar-tab .directory-list .directory-item.collapsed h3{color:#fff}.dsa5-immersive .sidebar-tab .directory-list .directory-item h3{color:#000}.dsa5-immersive #sidebar-tabs{border-bottom:1px solid #000;box-shadow:0 0 10px #000;background-color:rgba(16,13,8,.4784313725)}.dsa5-immersive .chat-message{background:none}.dsa5-immersive .chat-message .message-header{padding:10px 5px;background-image:url("../../icons/backgrounds/kapitelstart.webp");background-size:112% 110%;background-repeat:no-repeat;background-position:67% -5px;color:#191815}.dsa5-immersive .sidebar-popout .chat-message,.dsa5-immersive #sidebar .chat-message{padding:8px 15px 15px 15px;padding-left:18px;margin-bottom:8px;border-image:url("../../icons/backgrounds/chatpaper.webp");border-image-width:30px;border-image-slice:50 50 fill;border-image-repeat:round}.dsa5-immersive .app.sidebar-popout .window-content{color:#333}.dsa5-immersive .sidebar-popout .dice-tray input[type=text],.dsa5-immersive #sidebar .dice-tray input[type=text]{color:#000}.dsa5-immersive .compendium-footer .source{color:#fff}.dsa5-immersive .window-app{background:none;box-shadow:none}.dsa5-immersive .window-app.actor .window-content{box-shadow:0 0 20px #000}.dsa5-immersive .window-app.image-popout .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-immersive .window-app .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-immersive .window-app.dsajournal .window-content,.dsa5-immersive .window-app.bookWizardsheet .window-content{background-image:url("../../icons/backgrounds/journalentry_v45.webp");background-size:97% 1000px;background-position:center;background-repeat:repeat-y}.dsa5-immersive .window-app.dsajournal .window-content a.content-link,.dsa5-immersive .window-app.dsajournal .window-content a.inline-roll,.dsa5-immersive .window-app.bookWizardsheet .window-content a.content-link,.dsa5-immersive .window-app.bookWizardsheet .window-content a.inline-roll{border:none;color:#b93d00;font-weight:bold;background:none}.dsa5-immersive .window-app.dsajournal .window-content a.content-link i,.dsa5-immersive .window-app.dsajournal .window-content a.inline-roll i,.dsa5-immersive .window-app.bookWizardsheet .window-content a.content-link i,.dsa5-immersive .window-app.bookWizardsheet .window-content a.inline-roll i{color:#b93d00}.dsa5-immersive .window-app.dsajournal .window-content{padding:0 40px}.dsa5-immersive .window-app.bookWizardsheet .video-container,.dsa5-immersive .window-app.dsajournal .window-content .video-container{position:relative;width:100%;padding-bottom:56.25%}.dsa5-immersive .window-app.bookWizardsheet .video-container iframe,.dsa5-immersive .window-app.dsajournal .window-content .video-container iframe{position:absolute;top:0;left:0;width:100%;height:100%;border:0}.dsa5-immersive .window-app.dialog .window-content{padding-top:14px;padding-bottom:14px}.dsa5-immersive .window-app.npc-sheet .window-header,.dsa5-immersive .window-app.character-sheet .window-header,.dsa5-immersive .window-app.item .window-header{background-image:url("../../icons/backgrounds/sidebar-top.webp");border:none;top:2px}.dsa5-immersive .window-app.npc-sheet:not(.monarch):after,.dsa5-immersive .window-app.character-sheet:not(.monarch):after,.dsa5-immersive .window-app.item:not(.monarch):after{background-image:url("../../icons/backgrounds/sidebar-bot.webp");bottom:2px;content:""}.dsa5-immersive .window-app:not(.monarch) .window-header,.dsa5-immersive .window-app:after{background-repeat:no-repeat;position:relative;min-height:40px;z-index:1;height:40px;width:100%;background-size:100% 40px}.dsa5-immersive .window-app.creature-sheet .window-content{box-shadow:none}.dsa5-immersive .window-app.monarch .window-header,.dsa5-immersive .window-app.monarch:after{background-image:none}.dsa5-immersive .window-app .window-header{background-image:url("../../icons/backgrounds/blackhat.webp");top:7px;border:none}.dsa5-immersive .window-app:not(.monarch):after{background-image:url("../../icons/backgrounds/blackbook.webp");bottom:12px;content:""}.dsa5-immersive .window-app.creature-sheet:after{background-image:url("../../icons/backgrounds/blackcreaturebot.webp")}.dsa5-immersive .window-app.masterMenu:after{background-image:url("../../icons/backgrounds/masterborder.webp")}.dsa5-immersive .window-app.creature-sheet .window-resizable-handle{bottom:18px}.dsa5-immersive .window-app .window-header .aa-item-settings,.dsa5-immersive .window-app .window-header [id^=popout_]{width:15px;height:15px;margin-top:10px}.dsa5-immersive .window-app:not(.monarch) .window-header>a{width:15px;height:15px;margin-top:10px}.dsa5-immersive .window-app:not(.monarch) .window-header>a i{width:22px;border:1px solid #111;padding:3px;background-color:#444;text-align:center;border-radius:100%;color:#fff}.dsa5-immersive .window-app .aa-item-settings i,.dsa5-immersive .window-app .window-header [id^=popout_] i{width:22px;border:1px solid #111;padding:3px;background-color:#444;text-align:center;border-radius:100%;color:#fff}.dsa5-immersive .window-app .window-resizable-handle{z-index:2;bottom:11px;right:25px}.dsa5-immersive .window-app .window-header .window-title{text-align:center;margin-left:15%;margin-top:5px;color:#fff;font-family:var(--boldFont);font-weight:bold;font-family:"GentiumBasic-Bold";text-shadow:0px 0px 2px rgba(0,0,0,.75)}.dsa5-immersive .window-app.npc-sheet .window-header .window-title,.dsa5-immersive .window-app.character-sheet .window-header .window-title{margin-top:10px;color:#000;text-shadow:1px 1px #fff}.dsa5-immersive .window-app .header-button.close{margin-right:25px}.dsa5-immersive .window-app.actor .window-content,.dsa5-immersive .window-app.item .window-content{margin-left:15px;margin-right:15px}.dsa5-immersive .window-app.dsa5Decent:after{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .window-app.initTracker::after,.dsa5-immersive .window-app.initTracker .window-content{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .window-app.tokenQuickHot::after,.dsa5-immersive .window-app.tokenQuickHot .window-content{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .window-app.initTracker::after,.dsa5-immersive .window-app.tokenQuickHot::after{content:none}.dsa5-immersive .window-app.dsa5Decent .window-content,.dsa5-immersive .window-app.dsa5Decent .window-header{background:rgba(0,0,0,.5);padding:0;position:unset;color:#fff}.dsa5-immersive .window-app.dsa5Decent .window-content li{background:rgba(255,255,255,.2)}.dsa5-immersive .window-app.dsa5Decent .window-content li:hover{background:rgba(255,255,255,.5)}.dsa5-immersive .window-app.dsa5Decent:after{background:none;margin:0;padding:0;overflow:visible}.dsa5-immersive .app.sidebar-popout .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-immersive .character-sheet form{border-color:#000;border-style:double;border-width:10px;border-image:url("../../icons/backgrounds/actor.webp") 27 28 28 28;padding:4px;margin:0px}.dsa5-immersive #settings .fshopButton div{display:inline-block;background-image:url("../../lazy/patchimages/UlissesDigital.png");background-size:contain;width:20px;height:19px;margin:0;background-repeat:no-repeat;background-position:center;position:relative;top:5px}.dsa5-immersive #sidebar{border:none;margin:0px;height:100vh}.dsa5-immersive #sidebar .sidebar-tab .folder.collapsed .folder-header a i{color:#d8d4d4}.dsa5-immersive #sidebar .playlists-sidebar .sound-control{color:#3b3b3b}.dsa5-immersive #sidebar .playlists-sidebar .sound-control.inactive i{color:#797373}.dsa5-immersive #sidebar .sidebar-tab.playlists-sidebar a.sound-control[data-action=sound-stop],.dsa5-immersive #sidebar .sidebar-tab.playlists-sidebar .folder a.sound-control[data-action=playlist-stop] i,.dsa5-immersive #sidebar .sidebar-tab.playlists-sidebar .folder .folder-header a.sound-control[data-action=playlist-stop] i{color:var(--color-text-hyperlink)}.dsa5-immersive #sidebar button.fshopButton{background:#006f3d;background:linear-gradient(90deg, rgb(0, 38, 13) 0%, rgb(0, 111, 61) 100%);position:relative}.dsa5-immersive #sidebar.collapsed:before{content:none}.dsa5-immersive #sidebar .directory-list .documentName,.dsa5-immersive #sidebar .playlist.now-playing,.dsa5-immersive #sidebar .directory-list .directory-item.compendium,.dsa5-immersive #sidebar .directory-list .directory-item.document{background-color:var(--sheet-bg);margin:3px;border:1px solid var(--sheet-border);border-radius:5px;color:#000;margin-left:10px}.dsa5-immersive #sidebar .sidebar-tab{color:#555}.dsa5-immersive #sidebar .sidebar-tab a.inactive i{color:#acacac}.dsa5-immersive #sidebar .sidebar-tab .jump-to-bottom{color:#fff}.dsa5-immersive #sidebar .sidebar-tab .jump-to-bottom i{color:#fff}.dsa5-immersive #sidebar .global-control{margin-left:10px}.dsa5-immersive #sidebar .global-control .playlist-header{color:#fff}.dsa5-immersive #sidebar:before{position:absolute;top:0;bottom:0;left:-13px;right:0;content:"";background-image:url("../../icons/backgrounds/menu.webp");background-repeat:repeat-y;background-size:100%;z-index:-1}.dsa5-immersive .dsa5.item .item-header{background-image:url("../../icons/backgrounds/kapitelstart.webp")}.dsa5-immersive .dsa5.item.minimized .window-header .window-title{color:#000}.dsa5-immersive .dsa5.item .window-header .window-title{color:rgba(0,0,0,0);text-shadow:none}.dsa5-immersive .sidebar-popout{color:#555}.dsa5-immersive .sidebar-popout a i{color:#555}.dsa5-immersive .sidebar-popout a.inactive i{color:#acacac}.dsa5-immersive .sidebar-popout .jump-to-bottom{color:#fff}.dsa5-immersive .sidebar-popout .jump-to-bottom i{color:#fff}.dsa5-immersive .itemTooltip{background-image:url("../../icons/backgrounds/macrobg.webp");background-size:cover;color:#000;padding:1px;border:2px solid #000;border-radius:5px}.dsa5-immersive #hotbar:before{background-image:url("../../icons/backgrounds/hotbarpart.webp"),url("../../icons/backgrounds/hotbarpart.webp"),url("../../icons/backgrounds/hotbar4.webp");background-size:30px 48px,66px 48px,100% 100%;background-repeat:no-repeat;content:"";position:absolute;left:0px;right:-32px;bottom:-10px;top:-10px;z-index:-1;background-position:8px 11px,calc(100% - 8px) 11px,center}.dsa5-immersive #hotbar.hotbarV3{margin-bottom:10px}.dsa5-immersive #hotbar.hotbarV3:before{background-size:30px 91px,34px 91px,calc(100% - 26px) calc(100% - 20px);background-position:8px 39px,calc(100% - 33px) 39px,0px 18px}.dsa5-immersive #hotbar.hotbarV3 .function{color:#000}.dsa5-immersive #hotbar.hotbarV3 .sections{background:none}.dsa5-immersive #hotbar.hotbarV3 .nameContent{color:#000}.dsa5-immersive #hotbar.hotbarV3 .actorEffect,.dsa5-immersive #hotbar.hotbarV3 .categoryFilter{background-image:url("../../icons/backgrounds/macrobg.webp");background-size:cover;color:#000}.dsa5-immersive #hotbar.hotbarV3 .actorEffect{box-shadow:inset 0px 0px 25px #403014}.dsa5-immersive #hotbar.hotbarV3 #macro-list>li,.dsa5-immersive #hotbar.hotbarV3 .skillItems>li{box-shadow:inset 0px 0px 25px #403014;background-image:url("../../icons/backgrounds/macrobg.webp")}.dsa5-immersive #hotbar.hotbarV3 #macro-list>li.unequipped,.dsa5-immersive #hotbar.hotbarV3 .skillItems>li.unequipped{box-shadow:inset 0px 0px 25px #000}.dsa5-immersive #hotbar.hotbarV3 #macro-list input,.dsa5-immersive #hotbar.hotbarV3 .skillItems input{color:#000}.dsa5-immersive #hotbar.collapsedHotbar:before{background-image:url("../../icons/backgrounds/hotbarpart.webp")}.dsa5-immersive #hotbar .macro{background:none;border:1px solid rgba(0,0,0,.5)}.dsa5-immersive #hotbar .macro.active{box-shadow:inset 0px 0px 25px #403014;background:url("../../icons/backgrounds/macrobg.webp")}.dsa5-immersive #hotbar .macro.active.parry{box-shadow:inset 0px 0px 15px #016e0a}.dsa5-immersive #hotbar .macro.active.attack{box-shadow:inset 0px 0px 15px #7e0202}.dsa5-immersive #hotbar #macro-list{border:none;margin:0}.dsa5-immersive #hotbar .bar-controls{margin:0;background:none;color:#000;border:none;box-shadow:none}.dsa5-immersive #hotbar .bar-controls:first-child{margin-left:5px}@media(max-width: 1120px){.dsa5-immersive #hotbar:before{background-size:36px 88px,66px 88px,190% 100%;background-position:-3px 18px,calc(100% + 3px) 18px,center;right:-58px;left:6px}.dsa5-immersive #hotbar.hotbarV3:before{background-size:36px 105px,66px 105px,190% 100%;background-position:-1px 24px,calc(100% + 30px) 24px,center;left:0px;right:0px}.dsa5-immersive #hotbar #hotbar-page-controls a,.dsa5-immersive #hotbar #hotbar-directory-controls a{margin:6px 0}}.dsa5-immersive .window-app.npc-sheet.app .window-content{box-shadow:none}.dsa5-immersive #players{background:none;border:none;box-shadow:none}.dsa5-immersive #players:before{background-image:url("../../icons/backgrounds/dsabot.webp");background-size:100% 15px;background-repeat:no-repeat;content:"";position:absolute;left:-2px;right:-2px;bottom:-5px;top:-20px;z-index:-1;background-position:center 100%}.dsa5-immersive #players h3{border:none;position:relative;overflow:visible}.dsa5-immersive #players h3:before{background-image:url("../../icons/backgrounds/dsahead.webp"),url("../../icons/backgrounds/dsamid.webp");background-size:100% 30px,100% calc(100% - 30px);background-repeat:no-repeat;content:"";position:absolute;left:-5px;right:-5px;bottom:0px;top:-20px;z-index:-1;background-position:center 0px,center 30px}.dsa5-immersive #players #player-list{border:none;position:relative;overflow:visible}.dsa5-immersive #players #player-list:before{background-image:url("../../icons/backgrounds/dsamid.webp");background-size:100% 50px;background-repeat:repeat-y;content:"";position:absolute;left:-2px;right:-2px;bottom:5px;top:-3px;z-index:-1;background-position:center 0px}.dsa5-immersive #sidebar button,.dsa5-immersive .initTracker button,.dsa5-immersive .masterMenu button,.dsa5-immersive .sheetButton,.dsa5-immersive .sidebar-popout button,.dsa5-immersive .sidebar-popout .dice-tray button{background-image:linear-gradient(to right top, #be2020, #af1622, #9f0d22, #8f0522, #7f0021);color:#fff;border:1px solid #000}.dsa5-immersive #sidebar button:active,.dsa5-immersive .initTracker button:active,.dsa5-immersive .masterMenu button:active,.dsa5-immersive .sheetButton:active,.dsa5-immersive .sidebar-popout button:active,.dsa5-immersive .sidebar-popout .dice-tray button:active{box-shadow:inset 0 0 5px #000}.dsa5-immersive #sidebar button:hover,.dsa5-immersive .initTracker button:hover,.dsa5-immersive .masterMenu button:hover,.dsa5-immersive .sheetButton:hover,.dsa5-immersive .sidebar-popout button:hover,.dsa5-immersive .sidebar-popout .dice-tray button:hover{box-shadow:inset 0 0 3px #fff}.dsa5-immersive #sidebar button.lastRound,.dsa5-immersive .initTracker button.lastRound,.dsa5-immersive .masterMenu button.lastRound,.dsa5-immersive .sheetButton.lastRound,.dsa5-immersive .sidebar-popout button.lastRound,.dsa5-immersive .sidebar-popout .dice-tray button.lastRound{background-color:#02234d;background-image:none}.dsa5-immersive .dsajournal.sheet.journal-entry .journal-entry-content{background:none;border:none}.dsa5-immersive .dsajournal .header-search,.dsa5-immersive .dsajournal.sheet.journal-entry .pages-list .directory-item .page-number,.dsa5-immersive .dsajournal .directory-item{color:#000}.dsa5-immersive #compendium li.compendium-pack{background-color:var(--sheet-bg);margin:3px;border:1px solid var(--sheet-border);border-radius:5px;color:#000;margin-left:10px;padding:5px}.dsa5-immersive #compendium.sidebar-tab .entry-name i{color:#fff}.dsa5-immersive #compendium .compendium h3{color:#fff;margin-left:3px}.dsa5-immersive .compendium.directory .directory-header .compendium-name{color:#fff}.dsa5-immersive #compendium li.compendium-pack .compendium-footer,.dsa5-immersive #playlists li.sound .sound-playback .sound-timer{color:#0e0c0c}.dsa5-immersive #playlists.sidebar-tab .directory-list .directory-item.playlist.collapsed{color:#555}.dsa5-immersive .sound-name{color:#5c5c5c}.dsa5-immersive .app.sidebar-popout{backdrop-filter:none}.dsa5-legacy .window-app.dsajournal .window-content{background-image:url("../../icons/backgrounds/journalentry.webp");background-size:97% 1000px;padding:0 50px}.dsa5-legacy .chatpaperfield{border-image:url("../../icons/backgrounds/chatpaper.webp");border-image-width:30px;border-image-slice:80 50 40 fill;border-image-repeat:round;padding:10px 20px 10px 30px}.dsa5-legacy .maskfield{position:relative;padding:10px 20px 30px 20px;color:#fff;border-image:url("../../icons/backgrounds/maskfield.webp");border-image-width:15px;border-image-slice:20 20 fill;border-image-repeat:round}.dsa5-legacy .maskfield:after{content:"";pointer-events:none;position:absolute;bottom:-23px;left:0;right:0;height:50px;z-index:1;background:url("../../icons/backgrounds/mask.webp");background-repeat:no-repeat;background-size:150px 50px;background-position:bottom center}.dsa5-legacy .maskfield .editor .mce-content-body{color:#fff}.dsa5-legacy .maskfield .editor.prosemirror .editor-menu{background-color:#fff}.dsa5-legacy .maskfield .editor.prosemirror.editing-source textarea{color:#fff}.dsa5-legacy .maskfield .documentName-link,.dsa5-legacy .maskfield .entity-link a.content-link{color:#000}.dsa5-legacy .bookWizardsheet .window-content .table-title,.dsa5-legacy .dsajournal .window-content .label-text,.dsa5-legacy .bookWizardsheet .window-content table tr:first-child,.dsa5-legacy .dsajournal .window-content table tr:first-child{background:#bc886f;background:linear-gradient(90deg, rgba(188, 136, 111, 0.8) 0%, rgba(255, 255, 255, 0) 100%);border-bottom-style:solid;text-align:left}.dsa5-legacy .window-app.bookWizardsheet .window-content{background:url("../../icons/backgrounds/sheet2.webp") no-repeat;background-position:center;background-repeat:repeat-y;background-size:101% 1400px}.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.content-link,.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.inline-roll,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.content-link,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.inline-roll{border:none;color:#ee770e;font-weight:bold;background:none}.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.content-link i,.dsa5-legacy .window-app.dsajournal .window-content .maskfield a.inline-roll i,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.content-link i,.dsa5-legacy .window-app.bookWizardsheet .window-content .maskfield a.inline-roll i{color:#ee770e}:root{--app-height: 100vh}body{height:var(--app-height)}/*# sourceMappingURL=dsa5.css.map */ diff --git a/styles/css/dsa5.css.map b/styles/css/dsa5.css.map index f95174bb..5216fe47 100644 --- a/styles/css/dsa5.css.map +++ b/styles/css/dsa5.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["../scss/dsa5.scss","../scss/immersive.scss","../scss/legacy.scss","../scss/applefix.scss"],"names":[],"mappings":"CACA,MACI,yBACA,mBACA,yBACA,qBACA,uBACA,qBACA,uBACA,wBACA,0BACA,0BAGF,WACE,2BACA,mCAGA,uTAGA,mBACA,kBAGF,WACE,sCACA,oCAGA,6TAGA,mBACA,kBAGF,WACE,gCACA,mCAGA,uTAGA,mBACA,kBAGF,WACE,sBACA,kCAGA,iTAGA,mBACA,kBAGF,SACE,kBACA,kBAGF,aACE,WAGF,mBACE,eAGF,gBACE,gBAGF,SACE,gBACA,kBAGF,KAEE,YACA,gBAGA,eACA,8BAGF,SACE,8BAGF,EACE,4BACA,iBAGF,qBACE,gBAEA,qPAEE,gBACA,UACA,YAKF,+DACE,sBAIJ,oBAEE,iBACA,kBACA,kCACE,WACA,2CACA,wBACA,4BACA,kBACA,WACA,MACA,YACA,WACA,iBAIJ,kBACE,mDAGF,uBACE,WAIA,8BACE,aACA,iBACA,0BACA,kBAEA,sCACE,YAIJ,qBACE,gBACA,eACA,eACA,2BAEA,6BACE,WACA,kBACA,mBAIJ,oBACE,gBAGF,cACE,YACA,cACA,YACA,aACA,YACA,eACA,kBACA,YACA,WAIJ,WACE,qBACA,kBACA,QACA,UACA,UACA,eAEA,aACE,0BACA,YAEA,mBACE,cAKN,WACE,gBAGF,UACE,gBAGF,yFACE,mBAGF,uEACE,aACA,mBACA,WACA,SAGF,0BACE,uBAGF,cACE,mBAGF,kCACE,UACA,YACA,gBAGF,gBACE,WACA,kCACE,UAIJ,uMAIE,sBACA,WAGF,0NAGI,YACA,4CACA,gBACA,+BACA,kBACA,YAGJ,oNAGI,WACA,gBACA,kBACA,eAIJ,4CACE,OAIA,6DACE,iBACA,YACA,qCACA,iCACA,SAIJ,2CACE,YAGF,YACE,aACA,kBAKE,kCACE,mBACA,sBAIA,sEACE,mBACA,sBAGF,sCACE,iBACA,eAKN,8CACE,gBAKE,6BACE,QACA,eACA,kBAGF,oCACE,OACA,eACA,kBAIJ,qCACE,OAGF,yCACE,UAGF,gCACE,cAEA,mCACE,UACA,SAIJ,gCACE,OACA,UAKN,WACE,WACA,yBACA,8BACE,WAIJ,2BACE,qBAGF,YACE,WACA,yBAGF,SACE,uCAGF,SACE,YACA,aACA,mBAGF,4CACE,gBAGF,uBACE,OACA,cACA,kCAEA,6BACE,OACA,kCAGF,wEACE,OAGF,gGACE,OAIJ,iCACE,UAGF,0DACE,WACA,mBAGF,wBACE,+BAEA,gCACE,yBACA,WAIJ,kCACE,kBACA,WACA,mBACA,kBACA,aAIA,aACE,mBACA,qFAGF,eACE,mBACA,oFAGF,kBACE,mBACA,qFAGF,cACE,mBACA,qFAGF,eACE,mBACA,mFAIJ,yBACE,iBACA,4BAGA,mBACA,4FAGF,6LAEI,iBACA,4BACA,2BACA,kBACA,gCAGJ,uOAGE,iCAGF,aACE,mBACA,sFACA,gBAGF,cACE,iBACA,4BAGF,eACE,aAGF,cACE,qBAGF,2BACE,SAGF,kCAKE,WAJA,yEACE,WAMJ,8BACE,mCAGJ,kBACE,iBAGA,2DACE,WAGF,cACE,YAGF,mCACE,mDACA,WAGF,uBACE,mDACA,WAGF,sEACE,mDACA,WAGF,uBACE,mDACA,WAGF,uBACE,mDAGF,uBACE,mDAGF,uBACE,mDAGF,uBACE,mDAGF,WACE,iBAGF,mBACE,WACA,kBACA,MACA,OACA,QACA,SACA,YACA,wBACA,2BACA,4BAIA,YACE,iCACA,oDAGF,YACE,WACA,iCACA,mDAGF,YACE,WACA,iCACA,qDAGF,8BAEE,qDACA,iCACA,WAIJ,8BAEE,qDACA,iCACA,WAGF,oCACE,iBAGF,iBACE,gCACA,WACA,YACA,qBACA,wBACA,iBACA,kBACA,oCACA,4BAGF,aACE,WACA,YACA,iBACA,eACA,kBACA,qBAGF,kCACE,WACA,YACA,iBACA,eACA,YAGF,iBACE,WAGF,WACE,WACA,YACA,qBAIA,6BACE,cAGF,6BACE,cAGF,6BACE,cAGF,6BACE,cAIJ,kBACE,2CACA,4BACA,wBAGF,kBACE,2CACA,4BACA,wBAGF,kBACE,2CACA,4BACA,wBAGF,kBACE,2CACA,4BACA,wBAGF,gBACE,iBACA,qBAGF,OACE,YAEA,WACE,WACA,YACA,kBAGF,aACE,qDAGF,SACE,YACA,kBACA,WACA,qBACA,kBAEA,6CACE,WACA,gBAEA,iDACE,wBAMR,UACE,aACA,WACA,OAGF,aACE,aAEA,kBACE,eAGF,kBACE,UAEA,0BACE,gBACA,aACA,mBACA,iCACA,qCAGF,wBACE,SACA,gCAGF,0BACE,SACA,kCAGF,0BACE,SAIJ,mCACE,UAGF,oBACE,sCACA,SACA,YAIJ,aACE,sBAGF,mBACE,yBAEF,+BACE,UAEF,YACE,qBAGF,YACE,iBACA,oBAGF,aACE,SAGF,YACE,iBAGF,aACE,YACA,wBACA,4BACA,4BAGF,WACE,iBAMA,wBACE,SAGF,uBACE,SAGF,6BACE,SAGF,6BACE,SAGF,uBACE,SAGF,wBACE,WAGF,sBACE,SAGF,2BACE,QAGF,wBACE,SAGF,yBACE,SAGF,wBACE,SAGF,yBACE,SAGF,yBACE,SACA,+BACE,kBACA,cACA,gBACA,qCACE,iBACA,WAMN,0BACE,SAGF,0BACE,SAGF,wBACE,SAGF,4BACE,WAGF,sBACE,SACA,cAIJ,OACE,cAGF,UACE,qCACA,kBACA,gBACA,gBAGF,cACE,kBACA,YAGF,QACE,kBAGF,OACE,iBAGF,YACE,eAGF,uBACE,iBAGF,OACE,eAGF,eACE,sBACA,eAGF,0CACE,sBAIA,qBACE,sBAGF,wBACE,uDAIJ,kBACE,YACA,gBACA,cAEA,wBACE,gBAMA,8EACE,gCAIJ,4EACE,gCAIJ,qCACE,gCAIA,4FACE,gCAIJ,SACE,iCACA,gBACA,cACA,gBAGF,gBAEE,aACA,QACA,eAEA,+BACE,cACA,kCACA,gBACA,6CACA,kBAKF,mCACE,YAKF,+BACE,mBACA,qCACA,YACA,iCAIJ,WACE,yBAGF,cACE,mBACA,2EACA,kBACA,WAGF,iGACE,YACA,YACA,0BAGF,oBACE,WAGF,0BACE,gBAGF,0BACE,mBACA,sBAIA,uCACE,mBACA,sBAGF,iCACE,UAIJ,yDACE,0BAIA,yCACE,kBAIJ,qBACE,kBACA,mBAGF,UACE,kBACA,eACE,kBACA,OACA,QACA,MACA,SAEA,4BACA,2BACA,wBAEF,mBACE,YACA,WACA,iBACA,kBACA,gBACA,WAIJ,YACE,WAGF,8KACE,kBAGF,6BACE,eAGF,gDACE,kBACA,uBAGF,gEAEE,iBAIA,wBACE,0BACA,4BACA,YAEA,2BACE,aACA,eAIJ,yDACE,kBACA,YACA,gBACA,YAKF,wBACE,iBACA,eAIA,4CACE,qCAIJ,iBACE,YACA,qBACA,WACA,kBAGF,uBACE,gBAIJ,4BACE,SACA,iBACA,YACA,SACA,WACA,kBAGF,YACE,qCACA,gBAGA,kBAGF,0BACE,eAGF,mDACE,qCACA,kBACA,YAGA,kBAGF,yCAEE,YACA,8BACA,gBACA,kBAGF,2BACE,0BAEA,uCACE,YAIJ,kDACE,kBAGF,aACE,eAIA,oFACE,iBAKJ,2BACE,qDACA,kBAEA,kCACE,kBACA,YACA,WACA,OACA,QACA,SACA,SAGF,iCACE,qDAMA,6CACE,aAIJ,gEACE,aAIJ,UACE,kBACA,YACA,sBACA,qBAIA,2DACE,eACA,uBAIJ,mJACE,YAGF,iCACE,YACA,iCACA,gBACA,cACA,kBACA,UAGF,gBACE,eACA,YAIA,8BACE,eACA,YAIJ,cACE,eACA,YAGF,cACE,eACA,YACA,YAGF,2BACE,iBAGF,kBACE,iBACA,oBACE,yBACA,gCACA,WACA,mBACA,iBAIJ,4BACE,0BAGF,UACE,gBAGF,4BACE,YACA,eAIA,qBAKE,cAJA,iCACE,cAMJ,kBACE,kBACA,qBAGF,kBACE,qBACA,eACA,iBAIJ,mBACE,gBACA,gBAEA,iDACE,WACA,qBAIJ,qBACE,aAIA,+DACE,aAIJ,8WAKE,aAIA,0EACE,aAIJ,2CACE,aAIA,qCACE,aAIJ,uHAEE,aAGF,2EAEE,cAGF,8BAME,mBACA,mBACA,cAPA,oCACE,qBACA,wBAQJ,mBACE,uBACA,eACA,YACA,2BACA,gBACA,SACA,cACA,oBACA,kBACA,mBACA,oBACA,yBACA,kBACA,yBACA,sBACA,qBACA,iBAGF,WACE,YACA,yBACA,sBACA,gBACA,+BACA,kBACA,sCAGF,SACE,4BACA,+BACA,uBAGF,UACE,6BACA,gCAEA,iBACE,kBACA,kBAGF,eACE,mCAKF,cACE,wCACA,mCAGF,sBACE,OACA,mCAIJ,KACE,YACA,WACA,+BACA,kBACA,UACA,QACA,SACA,iCAGF,SACE,6BACA,gCACA,uBAGF,UACE,YACA,YACA,kBACA,sBACA,WACA,kBACA,UACA,6BAEA,gBACE,YACA,iBACA,WACA,qBACA,YACA,UACA,SACA,WACA,gBACA,gBACA,6BAEA,sBACE,gBAEF,sBACE,gCAIJ,eACE,WACA,qBAIJ,cACE,4EAGF,KACE,mBACA,4EAGF,SACE,mBACA,8EAGF,KACE,mBACA,+EAGF,KACE,mBACA,8EAGF,OACE,WACA,YACA,wBACA,4BACA,qBAEA,YACE,WACA,YAGF,2BACE,gBACA,YAIJ,YACE,oDAGF,WACE,+CAGF,sDAEE,8CACA,4CAGF,4BACE,0BACA,sCAIA,gBACE,+BAGF,4BACE,sBAIJ,qDACE,YACA,0BACA,YACA,WACA,SAGF,4BACE,YACA,WACA,+BAEA,kCACE,kBAIJ,cACE,YACA,iBAIA,qBACE,aACA,kBACA,YACA,UACA,YACA,sBACA,0BACA,YACA,SACA,gBAGF,4BACE,cACA,WACA,mBAEA,kCACE,WACA,UAGF,8BACE,WACA,sBACA,YACA,kBAKN,+BACE,cAIA,+CACE,cAGF,kCACE,2BAIJ,iBACE,kBAIA,qBACE,qBACA,WACA,YACA,+BAEA,2BACE,sBAIJ,sBACE,WACA,YACA,YAIJ,aACE,aAEA,iBACE,iBACA,mBAEA,qBACE,kBACA,QACA,iBACA,eAIJ,gBACE,aACA,eACA,WAEA,gCACE,qBACA,SACA,qBACA,aACA,iBACA,gBAEA,2CACE,gBACA,eACA,iBACA,eACA,YACA,uBACA,gBAKN,wCACE,SACA,sBACA,gBAEA,0CACE,qBACA,YACA,wBACA,YACA,iBAGF,+CACE,YACA,WACA,qBACA,wBAIJ,kCACE,uBACA,gBACA,eAIJ,aACE,iBAEA,kBACE,qBACA,sBACA,iBAIJ,kCACE,qBACA,sBACA,iBAGF,SACE,qBAGF,wFACE,iBAGF,qDACE,WACA,qBACA,YACA,WACA,kBACA,WACA,QACA,iDACA,wBACA,4BAGF,uBACE,WACA,YACA,wBACA,4BACA,2BACA,cAGF,iCACE,kBACA,WACA,UAGF,uBACE,YACA,2BACA,WAGF,WACE,mEAGF,cACE,iBAIF,oBACE,WACA,qBAGF,wDACE,YACA,aAIA,4BACE,2BACA,0BAGF,gCACE,OAGF,0BACE,aAGF,gBACE,gBAGF,gBACE,gBAGF,yBACE,YACA,cACA,aACA,6BACA,gCAEA,+BACE,0BACA,sCAIJ,wBACE,qBACA,eACA,yBACA,mBACA,WACA,YACA,iBACA,cACA,kBAGF,iBACE,YACA,mBAGF,oBACE,WAEA,sBACE,mBACA,WAKN,yBACE,qCACA,YACA,kBACA,qDACA,qBAGF,gBACE,qBACA,SACA,iBACA,WACA,YACA,gBACA,kBACA,QAIA,mBACE,WACA,YACA,QAGF,kCACE,WACA,YACA,gBACA,gBAIJ,6BACE,iBAGF,YACE,cAGF,WACE,qCACA,YAGF,WACE,kBACA,+DACA,qBACA,4BACA,wBACA,aACA,iBACA,YACA,WACA,WACA,iBAEA,cACE,qBACA,SAGF,cAME,gBACA,qBACA,+BACA,WARA,oBACE,gCACA,iBAQF,qBACE,YACA,2BAGF,oBACE,yBACA,kBAKN,YACE,YACA,YACA,+CACA,qBACA,4BACA,YACA,kBACA,iBACA,sBACA,cACA,kBACA,mBACA,iBAEA,kBACE,kBACA,eACA,SACA,OACA,QAGF,qBACE,YAGF,qBACE,aAIJ,kBACE,qBACA,UAGF,6BACE,UACA,qBAGF,gBACE,kCACA,YACA,UACA,kBAEA,uBACE,kBACA,OACA,QACA,SACA,oCACA,yBAKF,kCACE,2BAIJ,uCACE,qBACA,cAGF,oCACE,qBACA,cAIA,iCACE,yBAGF,iCACE,yBAGF,2BAKE,kBACA,UALA,iCACE,yBAQN,kBACE,iBACA,aAGF,SACE,qCACA,qDACA,kBACA,iBAEA,WACA,kBACA,aACE,YAEF,gBACE,cAGF,wBACE,kBACA,qCACA,kBACA,yBACA,kBACA,WACA,qBACA,WACA,YACA,iBACA,WACA,UACA,+BAEA,8BACE,sBAKN,mGAGE,YAKE,gEACE,oBAEF,4DACE,cACA,8BACA,mBACA,oBAEA,+DACE,oBACA,YAMR,oBACE,mEACA,wBACA,4BACA,2BAGF,SACE,mEACA,wBACA,4BACA,2BAEA,cACE,iEAGF,cACE,0DAGF,cACE,0DAGF,cACE,oEAIJ,YACE,6DACA,gBACA,aAGF,QACE,mEAGF,8BAEE,eAIA,eACE,eAGF,gBACE,qBAIJ,gCACE,cAGF,sBAEE,cAGF,qBACE,eACA,cACA,iBACA,kBACA,oBAIA,oBACE,kCAGF,sBACE,iBAGF,0BACE,kBACA,WACA,UACA,eACA,cACA,iBAIJ,gEACE,gBACA,yBACA,kBACA,mBACA,qBACA,gBACA,2BACA,eAGF,4EACE,QAIF,+BACE,aAGF,gBACE,+DACA,WACA,wBACA,iCAEA,gBACA,4BAGF,WACE,kBACA,WACA,4BACA,gBACA,+DACA,uCACA,oCAIF,WACE,kBACA,WACA,aACA,gBACA,0DACA,uCACA,oCAIF,sDACE,gBAGF,MACE,mBAGF,oBACE,wBACA,gBACA,YACA,kBACA,WAGF,aACE,mBACA,YACA,cACA,WACA,kBACA,WACA,YACA,gBACA,yBACA,sBACA,eACA,4BACA,UAEA,mBACE,yBAMA,gIACE,iBAIJ,4BACE,UAKF,oCACE,gCAGF,yDAEE,YAGF,4DAEE,cAKF,0BACE,UAQA,iCACE,SACA,mBACA,kBACA,8DACE,UACA,UAEF,yDACE,WACA,OACA,sFACE,WACA,UAWV,0FACE,WACA,YACA,YACA,kBACA,eAIA,0DACE,YAGF,2DACE,cAGF,sBAME,qBACA,iBANA,yBACE,qBACA,iBASJ,mCACE,UAGF,qCACE,uBAIJ,iBACE,kBACA,SAGF,cACE,kBACA,SACA,UACA,eAGF,0CACE,iBAGF,6BACE,YACA,kBACA,UACA,QACA,eACA,cAGF,YACE,mBACA,8BAGF,WACE,cACA,YAEA,kBACE,cACA,iBAIJ,wBACE,UACA,kBAGF,YACE,gBACA,gBAGF,iBACE,gBAEA,qBACE,gBAGF,0BACE,YACA,4BACG,iBAIL,sBAKE,oBAJA,yCACE,UAMJ,wBACE,YACA,iBAGF,8BACE,aACA,+CACA,kBACA,gCACA,6BAEA,kCACE,OACA,gBACA,gBACA,kBACA,YACA,WACA,kCACA,mBACA,gBACA,uBACA,+BACA,kBAEA,wCACE,eACA,mCACA,WAON,WACE,cAGF,cACE,cAIJ,yBACE,cACA,YAEA,2BACE,qBACA,kBAIJ,mBACE,kBAGF,oBACE,cACA,kBACA,YAEA,sBACE,kBACA,SACA,QACA,WACA,WAGF,0DAEE,eACA,mBACA,WACA,YACA,UACA,SACA,iBACA,kBACA,WACA,mBACA,kBACA,QACA,MAGF,6BACE,OACA,WACA,mBAKF,0CACE,QACA,WAEF,0CACE,WACA,UAKF,+BACE,qBAGF,gCACE,gCACA,kBACA,OACA,QACA,kBACA,UACA,WACA,eACA,iBAIJ,iCAOE,6BANA,mCACE,SACA,WACA,YAMJ,kBACE,WACA,gBACA,eACA,YACA,gBACA,sBAGF,eACE,kBACA,MACA,gCACA,SACA,UACA,WACA,qCAEA,kBACE,YACA,qBAGF,wBACE,4BAGF,2BACE,kBACA,UAIJ,mDACE,cAIA,uCACE,oCAGF,uCACE,mCAGF,uCACE,iCAGF,uCACE,kCAGF,gFACE,YACA,+BACA,iBAIJ,sDACE,WACA,gCACA,0BACA,kBACA,qCACA,YAGF,gCACE,WAIA,kCACE,WAGF,iBACE,sCACA,WACA,YACA,kBAGF,2BACE,gCAIJ,kCACE,gCACA,qBACA,eACA,+BACA,gCACA,sBACA,kBACA,mBACA,sBACA,qCACA,4BACA,kBACA,sBAGF,wBACE,WAGF,iCACE,YACA,YACA,iBAGF,mCACE,qCACA,sCAGF,mBACE,kBACA,qCACA,UACA,WAIA,uBACE,qBACA,8CACA,sCACA,2BACA,8BAGF,wBACE,YACA,mBACA,WACA,qBAGF,kCACE,yBAGF,wBACE,sBAEA,0BACE,WACA,WACA,2CACA,kBACA,WAIJ,gBACE,gBACA,+BACA,+BACA,eACA,gCACA,mBAEA,6BACE,kBACA,YACA,WACA,OACA,QACA,QACA,SACA,kBAIJ,+BACE,kBACA,aACA,OACA,QAGF,0BACE,OACA,QACA,gBACA,SAIA,sBACE,kBACA,cACA,WACA,YACA,iEACA,qBACA,qBACA,cAGF,uBACE,kBACA,mCAGF,gDACE,WAGF,yBACE,wBACA,2BAKN,gBACE,SACA,UACA,qBAIA,0BACE,WACA,gBACA,YACA,kCAGF,gBACE,4BACA,6BAIJ,qDAEE,qBACA,eAGF,oCACE,YACA,6BAIA,iCACE,kCACA,mCACA,uCACE,UAIA,4FACE,mBACA,gBACA,iFAGF,gGACE,mBACA,gBACA,gFAGF,sGACE,mBACA,gBACA,iFAGF,8FACE,mBACA,gBACA,iFAGF,gGACE,mBACA,gBACA,+EAGJ,qCACE,sBACA,YACA,WACA,kBACA,WACA,4EAEF,uCACE,gCACA,cACA,WACA,SACA,WACA,kBACA,eACA,YAEF,6CACE,uCACA,kBACA,mDACE,YACA,kBACA,SAEF,+CACE,kBACA,QACA,SACA,cACA,uDACE,cACA,UACA,WAKJ,4DACE,YACA,iBACA,kBACA,YAEF,iDACE,wBACA,4BACA,2BACA,WACA,iBACA,WAEF,mDACE,qBACA,eACA,gBACA,gBACA,uBACA,mBAMJ,uBACE,kBACA,UACA,WACA,mBACA,YACA,qBACA,WACA,YACA,kBACA,kBAGF,sBACE,gDACA,qCACA,kBAGF,wBACE,sCAGF,wBACE,sCAMJ,gFACE,aAGF,kDACE,UAKF,uBACE,qBACA,WAGF,mCACE,cAIJ,gBACE,wBACA,UACA,aAEA,mBACE,YACA,kBACA,0BACA,WAKF,2BACE,WACA,kBACA,QACA,QACA,UACA,sBAGF,6BACE,eACA,qBAGF,oCACE,UAIA,yBACE,WACA,0BACA,kBAGF,6BACE,iBAIJ,oBACE,iBAIJ,0CACE,kCACA,gBACA,YAKE,uEACE,gBACA,SACA,UACA,iBAKF,2EACE,gBACA,SACA,UACA,iBAIJ,gEACE,aAIJ,SACE,kBACA,SAGF,YACE,WACA,YACA,wBACA,qCACA,yBACA,4BACA,2BACA,kBACA,eACA,wBACE,WAEF,kBACE,qBAIJ,UACE,kBACA,aACA,YACA,qCACA,YACA,gCACA,WACA,kBAGF,UACE,kBACA,qCACA,WACA,mCAEA,mBACE,kBACA,MACA,OACA,SACA,yBAEA,4BACE,yBAIJ,oBACE,kBACA,UAIJ,yBACE,kBACA,WACA,YAGF,uCACE,WACA,6DACA,wBACA,4BACA,2BACA,kBACA,OACA,QACA,MACA,SAGF,uBACE,qEAGF,YACE,aACA,sBAGF,cACE,aACA,mBACA,kBAEA,mBACE,OACA,WAEA,uBACE,QAGF,uBACE,QAKN,6BACE,WACA,kBACA,MACA,OACA,QACA,SACA,4GACA,mDACA,2BAIA,aACE,sCAGJ,+BAEI,qBACA,YACA,qCACA,iBACA,kBAGJ,kBACE,qBACA,yBACA,iBACA,kBACA,WACA,gBACA,4BACA,yBAEA,0BACE,qBACA,yBAGF,0BACE,qBACA,yBAIJ,qCACE,cAGF,UACE,WACA,YACA,iBACA,gBACA,cACA,gBACA,kBACA,YAEA,eACE,UACA,YACA,gBACA,kBACA,MACA,UAGF,yBACE,OAGF,wBACE,WACA,YACA,gBACA,iBACA,mBACA,kBACA,MAGF,uCACE,UACA,+BACA,kCACA,cACA,qCACA,6BACA,uCAGF,0BACE,QAEA,wCACE,WACA,8BACA,iCACA,eACA,sCACA,8BACA,wCAIJ,0BACE,UACA,WACA,kBACA,cACA,cACA,iBACA,kBACA,kBACA,OACA,QAGF,6BACE,qBAKF,gBAcE,SAbA,kBACE,cACA,WACA,WAGF,oBACE,WACA,SACA,kBACA,WAMJ,0BACE,qCACA,mBAIJ,yBACE,kBAGF,qBACE,mBACA,uBACA,mBAEA,4BACE,WACA,YACA,kBAIJ,gBACE,iBAGF,eACE,iBAEA,qBACE,cAIJ,2BACE,cAGF,oBACE,iBAGF,yBACE,+BAEA,gCACE,WAGF,+BACE,0BAGF,wCACE,kBAIJ,kBACE,cAGF,8BACE,kBACA,UACA,SACA,OACA,MACA,QAIA,yBACE,eAEF,0BACE,cACA,iBAEF,8BACE,YAEA,qCACE,YAKN,aACE,sBAGF,aACE,kBACA,QACA,QACA,WACA,SACA,oBAEA,qBACE,kBACA,WACA,WACA,sBACA,oBAIJ,cACE,sBACA,gBACA,WACA,kBACA,YACA,6DACA,4BAIA,0BACE,SACA,kBACA,YAEA,iCACE,WAGF,sCACE,eAIJ,0BACE,iBAEA,gCACE,uBAIJ,qCACE,YAIJ,kCACE,WACA,YAGF,aACE,UACA,kBAIA,qCACE,UACA,kBAIJ,cACE,WACA,wBACA,4BACA,kBACA,WACA,YACA,UACA,SACA,UAGF,iBACE,kDAGF,iBACE,kDAGF,kCACE,kDAGF,UACE,YACA,wBAGF,6CACE,WACA,4DACA,wBACA,4BACA,kBACA,OACA,QACA,SACA,MACA,WACA,WAIA,qCACE,WACA,4DACA,wBACA,4BACA,kBACA,OACA,QACA,SACA,MACA,WACA,WAGF,qCACE,4BAGF,iBACE,yDACA,WAIJ,oBACE,cAGF,eACE,cACA,sEACA,WACA,wBACA,kCACA,cACA,6BACE,oBAIJ,kCAEE,eACA,wBACA,kCACA,kBACA,iBACA,mBACA,sCACE,YAEF,8CACE,kBACA,iBACA,mBACA,mBACA,SACA,UAIJ,UACE,oBACA,iEAGF,wBACE,iBACA,kCACA,mBACA,sEAGF,aACE,4BACA,wBACA,YACA,gBACA,gBACA,2BACA,WAGF,UACE,qBACA,WACA,YACA,wBACA,4BACA,gBACA,iBAEA,oBACE,kDAGF,iBACE,oDAGF,mBACE,sDAGF,eACE,kDAGF,gBACE,mDAIJ,eACE,qBACA,kBACA,eACA,gBAGF,sBACI,WACA,kBACA,SACA,MACA,OACA,QACA,4BACA,2BACA,wBAKF,kBACE,qBACA,YACA,SACA,eACA,gBACA,eACA,iBAGF,kBACE,SACA,YACA,eAIJ,YACE,WAEA,gBACE,WACA,WACA,YAIJ,kCACE,kCACA,WACA,mBACA,aAGF,sBAEE,eACA,QACA,uBACA,aACA,YACA,aAEA,0CACE,aACA,uBACA,mBAIJ,UACE,cACA,uBACA,YACA,uBACA,QAEA,sBACG,kBACA,sBACA,OACA,SACA,QAEH,gBACE,YACA,YACA,aACA,kBACA,gBACA,kBACA,WACA,sJAGF,iBACE,mBACA,kBACA,eACA,kBACA,UACA,+DACA,WACA,mBACA,aACA,iBACA,sJAGF,iBACE,YACA,YACA,aACA,UACA,6EAIJ,wBACE,GACE,mBACA,UAGF,IACE,UAGF,KACE,oBAIJ,sBACE,GACE,UAGF,IACE,UAGF,KACE,WAIJ,yBACE,GACE,mCACA,mBACA,+BAGF,IACE,kCACA,sBAGF,IACE,mCACA,sBAGF,IACE,kCACA,sBAGF,IACE,mCACA,oBAIJ,iBACE,uBACA,mBAGF,yBACE,aAGF,SACE,iBAGF,gBACE,qBACA,kBACA,eACA,YACA,WAEA,sBACE,kBACA,UACA,YACA,WAGF,qBACE,kBACA,MACA,OACA,YACA,WACA,2DACA,2BACA,wBACA,4BACA,YACA,+BAGF,+BACE,mEAGF,6BACE,iEAGF,8BACE,kEAGF,0BACE,8DAGF,4BACE,gEAGF,kCACE,sEAGF,oEACE,UAIJ,mBACE,eACA,uBACA,UACA,gBACA,SACA,UACA,YAGF,mEACE,WAGF,eACE,wBACA,YACA,eAGF,4BACE,uBACA,gBACA,mBAGF,YACE,eAEA,kBACE,kCAIJ,gBACE,kCAKF,0BACE,kBAGF,kCACE,cAKF,2CACE,+BAIA,iCACE,+DACA,2BACA,4CAGF,kCACE,eACA,qCACE,YACA,kBACA,+BAEF,2CACE,sBACA,WAKN,YACE,kBAEA,wBACE,mBACA,gBACA,iCACA,4CACA,qBACA,iBACA,uBACA,2CACE,aAGF,iCACE,sBACA,YAEA,qFACE,oBAKN,kBACE,wBACA,wBACE,OAIJ,6CACE,kBACA,gBACA,eACA,YACA,cACA,aACA,2BAGF,uBACE,QAGF,sBACE,OAMF,gBACE,YACA,eACA,iBAEF,kBACE,SAEF,wBACE,aAIJ,iBACE,gBACA,2BACE,gBACA,YACA,gCAEF,kCACE,YAEF,+BACE,qBAEF,2BACE,WACA,QAEF,wCACE,SACA,UACA,gBAGA,wBACE,eACA,iBACA,kBAKF,0CACE,iBAEF,kCACE,WACA,YACA,wBAGJ,iCACE,gBACA,6CACE,4BAEF,4CACE,6BAGJ,+DAEE,cACA,sBACA,qCACA,YACA,WACA,eACA,sBACA,iBACA,kBACA,gCACA,sCAEA,6EACE,qBAEF,2EACE,qBAEF,uEACE,sBACE,YACA,WAGN,8BACE,oBAGF,4CACE,gBACA,YAIF,iCACE,aACA,eACA,uBACA,sBACA,oCACE,cACA,gBACA,YACA,WACA,eACA,mBACA,sBACA,4BACA,kBACA,sBAIA,+CACE,YAGF,wCACE,YACA,WACA,kBAKN,6BACE,WACA,eACA,4EAEF,6BACE,cAEA,6CACE,YAGJ,iCACE,mBACA,mCACA,2BACA,WACA,YACA,yBACA,gBACA,kBAIE,4CACE,cACA,kBAEA,eACA,gDACE,aAEF,yDACE,iBACA,cACA,gBACA,uBAMR,0DAEE,SACA,UACA,mBACA,kBACA,aACA,eACA,YACA,gCACA,6BAIA,sEACE,YACA,cACA,WACA,SACA,WACA,kBACA,eACA,WAGF,0KAEE,UACA,OAEF,oFACE,aACA,WAKA,wMACE,WAEF,wKACE,mBACA,gBACA,iFAGF,gLACE,mBACA,gBACA,gFAGF,4LACE,mBACA,gBACA,iFAGF,4KACE,mBACA,gBACA,iFAGF,gLACE,mBACA,gBACA,+EAIJ,gEACE,gCACA,8BAEA,sBACA,gCACA,mBACA,sBACA,qCACA,4BACA,kBACA,sBACA,wBAEA,sFACE,mBACA,mCACA,uBAGF,4EACE,qBAGF,wEACE,sBACA,YACA,WACA,kBACA,WACA,4EACA,gCACA,oFACE,qBAMR,6BACE,YAGJ,0BACE,iBACI,6BC3xIJ,kCACI,qCACA,6DAEA,wCACI,WAIJ,uEACE,WACA,0EACE,WAIJ,gEACE,WAIN,8BACI,6BACA,yBACA,2CAGJ,8BACI,gBAGJ,8CACI,iBACA,kEACA,0BACA,4BAGA,6BACA,cAGJ,qFAEI,2BACA,kBACA,kBAEA,2DACA,wBACA,8BACA,0BAGJ,oDACI,WAGJ,iHAEI,WAGJ,2CACI,WAGJ,4BAkFI,gBACA,gBAlFA,kDACI,yBAGJ,yDACI,gEACA,2BACA,2BACA,4BAGJ,4CACI,gEACA,2BACA,2BACA,4BAGJ,mHAEI,sEACA,2BACA,2BACA,2BAEA,gSAEI,YACA,cACA,iBACA,gBAEA,wSACI,cAKZ,uDACI,eAKA,qIACI,kBACA,WACA,sBAEA,mJACI,kBACA,MACA,OACA,WACA,YACA,SAKZ,mDACI,iBACA,oBAGJ,gKAGI,iEACA,YACA,QAGJ,+KAGI,iEACA,WACA,WAMJ,2FAEI,4BACA,kBACA,gBACA,UACA,YACA,WACA,0BAGJ,2DACI,gBAKA,6FAEI,sBAIR,2CACI,8DACA,QACA,YAGJ,gDACI,+DACA,YACA,WAGJ,iDACI,sEAGJ,6CACI,kEAGJ,oEACI,YAKA,sHAEI,WACA,YACA,gBAIR,2DACI,WACA,YACA,gBAEA,6DACI,WACA,sBACA,YACA,sBACA,kBACA,mBACA,WAIR,2GAEI,WACA,sBACA,YACA,sBACA,kBACA,mBACA,WAGJ,qDACI,UACA,YACA,WAGJ,yDACI,kBACA,gBACA,eACA,WACA,4BACA,iBACA,gCACA,wCAGJ,4IAEI,gBACA,WACA,yBAGJ,iDACI,kBAGJ,mGAEI,iBACA,kBAGJ,6CACI,gBACA,SACA,UACA,iBAKA,uGAEI,gBACA,SACA,UACA,iBAMJ,2GAEI,gBACA,SACA,UACA,iBAIR,gGAEI,aAIA,6GACE,0BACA,UACA,eACA,WAGF,0DACE,gCAEA,gEACE,gCAGJ,6CACI,gBACA,SACA,UACA,iBAKZ,oDACI,gEACA,2BACA,2BACA,4BAGJ,sCACI,kBACA,oBACA,kBACA,mEACA,YACA,WAGJ,2CACI,qBACA,kEACA,wBACA,WACA,YACA,SACA,4BACA,2BACA,kBACA,QAGJ,yBACI,YACA,WACA,aAEA,2EACI,cAGJ,2DACI,cAEJ,sEACI,cAGJ,yUAGI,kCAGJ,4CACI,mBACA,2EACA,kBAGJ,0CACI,aAGJ,4OAII,iCACA,WACA,qCACA,kBACA,WACA,iBAGJ,sCACI,WAII,mDACI,cAIR,sDACI,WACA,mEAIR,yCACI,iBACA,0DACI,WAIR,gCACI,kBACA,MACA,SACA,WACA,QACA,WACA,0DACA,2BACA,qBACA,WAKJ,wCACI,kEAGJ,kEACI,WAGJ,wDACI,oBACA,iBAIR,gCACI,WAGI,oCACI,WAGJ,6CACI,cAIR,gDACI,WACA,6DAIR,6BACI,6DACA,sBACA,WACA,YACA,sBACA,kBAIA,+BACI,2JACA,8CACA,4BACA,WACA,kBACA,SACA,YACA,aACA,UACA,WACA,0DAGJ,iCACI,mBACA,wCACI,wEACA,6DAEJ,2CACI,WAEJ,2CACI,gBAEJ,8CACI,WAEJ,+FAEI,6DACA,sBACA,WAEJ,8CACI,sCAIA,gGACI,sCACA,6DAEA,sHACI,mCAGR,sGACI,WAKZ,+CACI,gEAGJ,+BACI,gBACA,gCAEA,sCACI,sCACA,uDAEA,4CACI,sCAGJ,6CACI,sCAKZ,oCACI,YACA,SAGJ,sCACI,SACA,gBAGA,WACA,YAGA,gBAEA,kDACI,gBAKZ,0BAEQ,+BACI,8CACA,2DACA,YACA,SAEJ,wCACI,gDACA,4DACA,SACA,UAGA,qGACI,cAMhB,0DACI,gBAGJ,yBACI,gBACA,YACA,gBAEA,gCACI,4DACA,0BACA,4BACA,WACA,kBACA,UACA,WACA,YACA,UACA,WACA,gCAGJ,4BAeI,YACA,kBACA,iBAhBA,mCACI,wGACA,iDACA,4BACA,WACA,kBACA,UACA,WACA,WACA,UACA,WACA,2CAQR,sCACI,YACA,kBACA,iBAEA,6CACI,4DACA,0BACA,2BACA,WACA,kBACA,UACA,WACA,WACA,SACA,WACA,+BAKZ,6NAMI,4FACA,WACA,sBAEA,uQACI,8BAGJ,iQACI,8BAGJ,yRACI,yBACA,sBAKJ,uEACE,gBACA,YAGF,gLACE,WAKF,+CACE,iCACA,WACA,qCACA,kBACA,WACA,iBACA,YAGF,sDACI,WAEJ,2CACE,WACA,gBAIJ,yEACE,WAGF,mIACE,cAGF,0FACE,WAGF,4BACE,cAGF,oCACE,qBCjuBA,oDACI,kEACA,2BACA,eAIR,6BACI,2DACA,wBACA,iCACA,0BACA,4BAGJ,wBACI,kBAeA,4BACA,WACA,2DACA,wBACA,8BACA,0BAnBA,8BACE,WACA,oBACA,kBACA,aACA,OACA,QACA,YACA,UACA,oDACA,4BACA,2BACA,kCASF,kDACE,WAIA,yDACE,sBAEF,oEACE,WAIJ,+FAGE,WAIN,iPAGI,mBACA,4FACA,0BACA,gBAIA,yDACI,gEACA,2BACA,2BACA,4BAOI,gUAEI,YACA,cACA,iBACA,gBAEA,wUACI,cCzFxB,MACI,oBAGJ,KACI","file":"dsa5.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["../scss/dsa5.scss","../scss/immersive.scss","../scss/legacy.scss","../scss/applefix.scss"],"names":[],"mappings":"CACA,MACI,yBACA,mBACA,yBACA,qBACA,uBACA,qBACA,uBACA,wBACA,0BACA,0BAGF,WACE,2BACA,mCAGA,uTAGA,mBACA,kBAGF,WACE,sCACA,oCAGA,6TAGA,mBACA,kBAGF,WACE,gCACA,mCAGA,uTAGA,mBACA,kBAGF,WACE,sBACA,kCAGA,iTAGA,mBACA,kBAGF,SACE,kBACA,kBAGF,aACE,WAGF,mBACE,eAGF,gBACE,gBAGF,SACE,gBACA,kBAGF,KAEE,YACA,gBAGA,eACA,8BAGF,SACE,8BAGF,EACE,4BACA,iBAGF,qBACE,gBAEA,qPAEE,gBACA,UACA,YAKF,+DACE,sBAIJ,oBAEE,iBACA,kBACA,kCACE,WACA,2CACA,wBACA,4BACA,kBACA,WACA,MACA,YACA,WACA,iBAIJ,kBACE,mDAGF,uBACE,WAIA,8BACE,aACA,iBACA,0BACA,kBAEA,sCACE,YAIJ,qBACE,gBACA,eACA,eACA,2BAEA,6BACE,WACA,kBACA,mBAIJ,oBACE,gBAGF,cACE,YACA,cACA,YACA,aACA,YACA,eACA,kBACA,YACA,WAIJ,WACE,qBACA,kBACA,QACA,UACA,UACA,eAEA,aACE,0BACA,YAEA,mBACE,cAKN,WACE,gBAGF,UACE,gBAGF,yFACE,mBAGF,uEACE,aACA,mBACA,WACA,SAGF,0BACE,uBAGF,cACE,mBAGF,kCACE,UACA,YACA,gBAGF,gBACE,WACA,kCACE,UAIJ,uMAIE,sBACA,WAGF,0NAGI,YACA,4CACA,gBACA,+BACA,kBACA,YAGJ,oNAGI,WACA,gBACA,kBACA,eAIJ,4CACE,OAIA,6DACE,iBACA,YACA,qCACA,iCACA,SAIJ,2CACE,YAGF,YACE,aACA,kBAKE,kCACE,mBACA,sBAIA,sEACE,mBACA,sBAGF,sCACE,iBACA,eAKN,8CACE,gBAKE,6BACE,QACA,eACA,kBAGF,oCACE,OACA,eACA,kBAIJ,qCACE,OAGF,yCACE,UAGF,gCACE,cAEA,mCACE,UACA,SAIJ,gCACE,OACA,UAKN,WACE,WACA,yBACA,8BACE,WAIJ,2BACE,qBAGF,YACE,WACA,yBAGF,SACE,uCAGF,SACE,YACA,aACA,mBAGF,4CACE,gBAGF,uBACE,OACA,cACA,kCAEA,6BACE,OACA,kCAGF,wEACE,OAGF,gGACE,OAIJ,iCACE,UAGF,0DACE,WACA,mBAGF,wBACE,+BAEA,gCACE,yBACA,WAIJ,kCACE,kBACA,WACA,mBACA,kBACA,aAIA,aACE,mBACA,qFAGF,eACE,mBACA,oFAGF,kBACE,mBACA,qFAGF,cACE,mBACA,qFAGF,eACE,mBACA,mFAIJ,yBACE,iBACA,4BAGA,mBACA,4FAGF,6LAEI,iBACA,4BACA,2BACA,kBACA,gCAGJ,uOAGE,iCAGF,aACE,mBACA,sFACA,gBAGF,cACE,iBACA,4BAGF,eACE,aAGF,cACE,qBAGF,2BACE,SAGF,kCAKE,WAJA,yEACE,WAMJ,8BACE,mCAGJ,kBACE,iBAGA,2DACE,WAGF,cACE,YAGF,mCACE,mDACA,WAGF,uBACE,mDACA,WAGF,sEACE,mDACA,WAGF,uBACE,mDACA,WAGF,uBACE,mDAGF,uBACE,mDAGF,uBACE,mDAGF,uBACE,mDAGF,WACE,iBAGF,mBACE,WACA,kBACA,MACA,OACA,QACA,SACA,YACA,wBACA,2BACA,4BAIA,YACE,iCACA,oDAGF,YACE,WACA,iCACA,mDAGF,YACE,WACA,iCACA,qDAGF,8BAEE,qDACA,iCACA,WAIJ,8BAEE,qDACA,iCACA,WAGF,oCACE,iBAGF,iBACE,gCACA,WACA,YACA,qBACA,wBACA,iBACA,kBACA,oCACA,4BAGF,aACE,WACA,YACA,iBACA,eACA,kBACA,qBAGF,kCACE,WACA,YACA,iBACA,eACA,YAGF,iBACE,WAGF,WACE,WACA,YACA,qBAIA,6BACE,cAGF,6BACE,cAGF,6BACE,cAGF,6BACE,cAIJ,kBACE,2CACA,4BACA,wBAGF,kBACE,2CACA,4BACA,wBAGF,kBACE,2CACA,4BACA,wBAGF,kBACE,2CACA,4BACA,wBAGF,gBACE,iBACA,qBAGF,OACE,YAEA,WACE,WACA,YACA,kBAGF,aACE,qDAGF,SACE,YACA,kBACA,WACA,qBACA,kBAEA,6CACE,WACA,gBAEA,iDACE,wBAMR,UACE,aACA,WACA,OAGF,aACE,aAEA,kBACE,eAGF,kBACE,UAEA,0BACE,gBACA,aACA,mBACA,iCACA,qCAGF,wBACE,SACA,gCAGF,0BACE,SACA,kCAGF,0BACE,SAIJ,mCACE,UAGF,oBACE,sCACA,SACA,YAIJ,aACE,sBAGF,mBACE,yBAEF,+BACE,UAEF,YACE,qBAGF,YACE,iBACA,oBAGF,aACE,SAGF,YACE,iBAGF,aACE,YACA,wBACA,4BACA,4BAGF,WACE,iBAMA,wBACE,SAGF,uBACE,SAGF,6BACE,SAGF,6BACE,SAGF,uBACE,SAGF,wBACE,WAGF,sBACE,SAGF,2BACE,QAGF,wBACE,SAGF,yBACE,SAGF,wBACE,SAGF,yBACE,SAGF,yBACE,SACA,+BACE,kBACA,cACA,gBACA,qCACE,iBACA,WAMN,0BACE,SAGF,0BACE,SAGF,wBACE,SAGF,4BACE,WAGF,sBACE,SACA,cAIJ,OACE,cAGF,UACE,qCACA,kBACA,gBACA,gBAGF,cACE,kBACA,YAGF,QACE,kBAGF,OACE,iBAGF,YACE,eAGF,uBACE,iBAGF,OACE,eAGF,eACE,sBACA,eAGF,0CACE,sBAIA,qBACE,sBAGF,wBACE,uDAIJ,kBACE,YACA,gBACA,cAEA,wBACE,gBAMA,8EACE,gCAIJ,4EACE,gCAIJ,qCACE,gCAIA,4FACE,gCAIJ,SACE,iCACA,gBACA,cACA,gBAGF,gBAEE,aACA,QACA,eAEA,+BACE,cACA,kCACA,gBACA,6CACA,kBAKF,mCACE,YAKF,+BACE,mBACA,qCACA,YACA,iCAIJ,WACE,yBAGF,cACE,mBACA,2EACA,kBACA,WAGF,iGACE,YACA,YACA,0BAGF,oBACE,WAGF,0BACE,gBAGF,0BACE,mBACA,sBAIA,uCACE,mBACA,sBAGF,iCACE,UAIJ,yDACE,0BAIA,yCACE,kBAIJ,qBACE,kBACA,mBAGF,UACE,kBACA,eACE,kBACA,OACA,QACA,MACA,SAEA,4BACA,2BACA,wBAEF,mBACE,YACA,WACA,iBACA,kBACA,gBACA,WAIJ,YACE,WAGF,8KACE,kBAGF,6BACE,eAGF,gDACE,kBACA,uBAGF,gEAEE,iBAIA,wBACE,0BACA,4BACA,YAEA,2BACE,aACA,eAIJ,yDACE,kBACA,YACA,gBACA,YAKF,wBACE,iBACA,eAIA,4CACE,qCAIJ,iBACE,YACA,qBACA,WACA,kBAGF,uBACE,gBAIJ,4BACE,SACA,iBACA,YACA,SACA,WACA,kBAGF,YACE,qCACA,gBAGA,kBAGF,0BACE,eAGF,mDACE,qCACA,kBACA,YAGA,kBAGF,yCAEE,YACA,8BACA,gBACA,kBAGF,2BACE,0BAEA,uCACE,YAIJ,kDACE,kBAGF,aACE,eAIA,oFACE,iBAKJ,2BACE,qDACA,kBAEA,kCACE,kBACA,YACA,WACA,OACA,QACA,SACA,SAGF,iCACE,qDAMA,6CACE,aAIJ,gEACE,aAIJ,UACE,kBACA,YACA,sBACA,qBAIA,2DACE,eACA,uBAIJ,mJACE,YAGF,iCACE,YACA,iCACA,gBACA,cACA,kBACA,UAGF,gBACE,eACA,YAIA,8BACE,eACA,YAIJ,cACE,eACA,YAGF,cACE,eACA,YACA,YAGF,2BACE,iBAGF,kBACE,iBACA,oBACE,yBACA,gCACA,WACA,mBACA,iBAIJ,4BACE,0BAGF,UACE,gBAGF,4BACE,YACA,eAIA,qBAKE,cAJA,iCACE,cAMJ,kBACE,kBACA,qBAGF,kBACE,qBACA,eACA,iBAIJ,mBACE,gBACA,gBAEA,iDACE,WACA,qBAIJ,qBACE,aAIA,+DACE,aAIJ,8WAKE,aAIA,0EACE,aAIJ,2CACE,aAIA,qCACE,aAIJ,uHAEE,aAGF,2EAEE,cAGF,8BAME,mBACA,mBACA,cAPA,oCACE,qBACA,wBAQJ,mBACE,uBACA,eACA,YACA,2BACA,gBACA,SACA,cACA,oBACA,kBACA,mBACA,oBACA,yBACA,kBACA,yBACA,sBACA,qBACA,iBAGF,WACE,YACA,yBACA,sBACA,gBACA,+BACA,kBACA,sCAGF,SACE,4BACA,+BACA,uBAGF,UACE,6BACA,gCAEA,iBACE,kBACA,kBAGF,eACE,mCAKF,cACE,wCACA,mCAGF,sBACE,OACA,mCAIJ,KACE,YACA,WACA,+BACA,kBACA,UACA,QACA,SACA,iCAGF,SACE,6BACA,gCACA,uBAGF,UACE,YACA,YACA,kBACA,sBACA,WACA,kBACA,UACA,6BAEA,gBACE,YACA,iBACA,WACA,qBACA,YACA,UACA,SACA,WACA,gBACA,gBACA,6BAEA,sBACE,gBAEF,sBACE,gCAIJ,eACE,WACA,qBAIJ,cACE,4EAGF,KACE,mBACA,4EAGF,SACE,mBACA,8EAGF,KACE,mBACA,+EAGF,KACE,mBACA,8EAGF,OACE,WACA,YACA,wBACA,4BACA,qBAEA,YACE,WACA,YAGF,2BACE,gBACA,YAIJ,YACE,oDAGF,WACE,+CAGF,sDAEE,8CACA,4CAGF,4BACE,0BACA,sCAIA,gBACE,+BAGF,4BACE,sBAIJ,qDACE,YACA,0BACA,YACA,WACA,SAGF,4BACE,YACA,WACA,+BAEA,kCACE,kBAIJ,cACE,YACA,iBAIA,qBACE,aACA,kBACA,YACA,UACA,YACA,sBACA,0BACA,YACA,SACA,gBAGF,4BACE,cACA,WACA,mBAEA,kCACE,WACA,UAGF,8BACE,WACA,sBACA,YACA,kBAKN,+BACE,cAIA,+CACE,cAGF,kCACE,2BAIJ,iBACE,kBAIA,qBACE,qBACA,WACA,YACA,+BAEA,2BACE,sBAIJ,sBACE,WACA,YACA,YAIJ,aACE,aAEA,iBACE,iBACA,mBAEA,qBACE,kBACA,QACA,iBACA,eAIJ,gBACE,aACA,eACA,WAEA,gCACE,qBACA,SACA,qBACA,aACA,iBACA,gBAEA,2CACE,gBACA,eACA,iBACA,eACA,YACA,uBACA,gBAKN,wCACE,SACA,sBACA,gBAEA,0CACE,qBACA,YACA,wBACA,YACA,iBAGF,+CACE,YACA,WACA,qBACA,wBAIJ,kCACE,uBACA,gBACA,eAIJ,aACE,iBAEA,kBACE,qBACA,sBACA,iBAIJ,kCACE,qBACA,sBACA,iBAGF,SACE,qBAGF,wFACE,iBAGF,qDACE,WACA,qBACA,YACA,WACA,kBACA,WACA,QACA,iDACA,wBACA,4BAGF,uBACE,WACA,YACA,wBACA,4BACA,2BACA,cAGF,iCACE,kBACA,WACA,UAGF,uBACE,YACA,2BACA,WAGF,WACE,mEAGF,cACE,iBAIF,oBACE,WACA,qBAGF,wDACE,YACA,aAIA,4BACE,2BACA,0BAGF,gCACE,OAGF,0BACE,aAGF,gBACE,gBAGF,gBACE,gBAGF,yBACE,YACA,cACA,aACA,6BACA,gCAEA,+BACE,0BACA,sCAIJ,wBACE,qBACA,eACA,yBACA,mBACA,WACA,YACA,iBACA,cACA,kBAGF,iBACE,YACA,mBAGF,oBACE,WAEA,sBACE,mBACA,WAKN,yBACE,qCACA,YACA,kBACA,qDACA,qBAGF,gBACE,qBACA,SACA,iBACA,WACA,YACA,gBACA,kBACA,QAIA,mBACE,WACA,YACA,QAGF,kCACE,WACA,YACA,gBACA,gBAIJ,6BACE,iBAGF,YACE,cAGF,WACE,qCACA,YAGF,WACE,kBACA,+DACA,qBACA,4BACA,wBACA,aACA,iBACA,YACA,WACA,WACA,iBAEA,cACE,qBACA,SAGF,cAME,gBACA,qBACA,+BACA,WARA,oBACE,gCACA,iBAQF,qBACE,YACA,2BAGF,oBACE,yBACA,kBAKN,YACE,YACA,YACA,+CACA,qBACA,4BACA,YACA,kBACA,iBACA,sBACA,cACA,kBACA,mBACA,iBAEA,kBACE,kBACA,eACA,SACA,OACA,QAGF,qBACE,YAGF,qBACE,aAIJ,kBACE,qBACA,UAGF,6BACE,UACA,qBAGF,gBACE,kCACA,YACA,UACA,kBAEA,uBACE,kBACA,OACA,QACA,SACA,oCACA,yBAKF,kCACE,2BAIJ,uCACE,qBACA,cAGF,oCACE,qBACA,cAIA,iCACE,yBAGF,iCACE,yBAGF,2BAKE,kBACA,UALA,iCACE,yBAQN,kBACE,iBACA,aAGF,SACE,qCACA,qDACA,kBACA,iBAEA,WACA,kBACA,aACE,YAEF,gBACE,cAGF,wBACE,kBACA,qCACA,kBACA,yBACA,kBACA,WACA,qBACA,WACA,YACA,iBACA,WACA,UACA,+BAEA,8BACE,sBAKN,mGAGE,YAKE,gEACE,oBAEF,4DACE,cACA,8BACA,mBACA,oBAEA,+DACE,oBACA,YAMR,oBACE,mEACA,wBACA,4BACA,2BAGF,SACE,mEACA,wBACA,4BACA,2BAEA,cACE,iEAGF,cACE,0DAGF,cACE,0DAGF,cACE,oEAIJ,YACE,6DACA,gBACA,aAGF,QACE,mEAGF,8BAEE,eAIA,eACE,eAGF,gBACE,qBAIJ,gCACE,cAGF,sBAEE,cAGF,qBACE,eACA,cACA,iBACA,kBACA,oBAIA,oBACE,kCAGF,sBACE,iBAGF,0BACE,kBACA,WACA,UACA,eACA,cACA,iBAIJ,gEACE,gBACA,yBACA,kBACA,mBACA,qBACA,gBACA,2BACA,eAGF,4EACE,QAIF,+BACE,aAGF,gBACE,+DACA,WACA,wBACA,iCAEA,gBACA,4BAGF,WACE,kBACA,WACA,4BACA,gBACA,+DACA,uCACA,oCAIF,WACE,kBACA,WACA,aACA,gBACA,0DACA,uCACA,oCAIF,sDACE,gBAGF,MACE,mBAGF,oBACE,wBACA,gBACA,YACA,kBACA,WAGF,aACE,mBACA,YACA,cACA,WACA,kBACA,WACA,YACA,gBACA,yBACA,sBACA,eACA,4BACA,UAEA,mBACE,yBAMA,gIACE,iBAIJ,4BACE,UAKF,oCACE,gCAGF,yDAEE,YAGF,4DAEE,cAKF,0BACE,UAQA,iCACE,SACA,mBACA,kBACA,8DACE,UACA,UAEF,yDACE,WACA,OACA,sFACE,WACA,UAWV,0FACE,WACA,YACA,YACA,kBACA,eAIA,0DACE,YAGF,2DACE,cAGF,sBAME,qBACA,iBANA,yBACE,qBACA,iBASJ,mCACE,UAGF,qCACE,uBAIJ,iBACE,kBACA,SAGF,cACE,kBACA,SACA,UACA,eAGF,0CACE,iBAGF,6BACE,YACA,kBACA,UACA,QACA,eACA,cAGF,YACE,mBACA,8BAGF,WACE,cACA,YAEA,kBACE,cACA,iBAIJ,wBACE,UACA,kBAGF,YACE,gBACA,gBAGF,iBACE,gBAEA,qBACE,gBAGF,0BACE,YACA,4BACG,iBAIL,sBAKE,oBAJA,yCACE,UAMJ,wBACE,YACA,iBAGF,8BACE,aACA,+CACA,kBACA,gCACA,6BAEA,kCACE,OACA,gBACA,gBACA,kBACA,YACA,WACA,kCACA,mBACA,gBACA,uBACA,+BACA,kBAEA,wCACE,eACA,mCACA,WAON,WACE,cAGF,cACE,cAIJ,yBACE,cACA,YAEA,2BACE,qBACA,kBAIJ,mBACE,kBAGF,oBACE,cACA,kBACA,YAEA,sBACE,kBACA,SACA,QACA,WACA,WAGF,0DAEE,eACA,mBACA,WACA,YACA,UACA,SACA,iBACA,kBACA,WACA,mBACA,kBACA,QACA,MAGF,6BACE,OACA,WACA,mBAKF,0CACE,QACA,WAEF,0CACE,WACA,UAKF,+BACE,qBAGF,gCACE,gCACA,kBACA,OACA,QACA,kBACA,UACA,WACA,eACA,iBAIJ,iCAOE,6BANA,mCACE,SACA,WACA,YAMJ,kBACE,WACA,gBACA,eACA,YACA,gBACA,sBAGF,eACE,kBACA,MACA,gCACA,SACA,UACA,WACA,qCAEA,kBACE,YACA,qBAGF,wBACE,4BAGF,2BACE,kBACA,UAIJ,mDACE,cAIA,uCACE,oCAGF,uCACE,mCAGF,uCACE,iCAGF,uCACE,kCAGF,gFACE,YACA,+BACA,iBAIJ,sDACE,WACA,gCACA,0BACA,kBACA,qCACA,YAGF,gCACE,WAIA,kCACE,WAGF,iBACE,sCACA,WACA,YACA,kBAGF,2BACE,gCAIJ,kCACE,gCACA,qBACA,eACA,+BACA,gCACA,sBACA,kBACA,mBACA,sBACA,qCACA,4BACA,kBACA,sBAGF,wBACE,WAGF,iCACE,YACA,YACA,iBAGF,mCACE,qCACA,sCAGF,mBACE,kBACA,qCACA,UACA,WAIA,uBACE,qBACA,8CACA,sCACA,2BACA,8BAGF,wBACE,YACA,mBACA,WACA,qBAGF,kCACE,yBAGF,wBACE,sBAEA,0BACE,WACA,WACA,2CACA,kBACA,WAIJ,gBACE,gBACA,+BACA,+BACA,eACA,gCACA,mBAEA,6BACE,kBACA,YACA,WACA,OACA,QACA,QACA,SACA,kBAIJ,+BACE,kBACA,aACA,OACA,QAGF,0BACE,OACA,QACA,gBACA,SAIA,sBACE,kBACA,cACA,WACA,YACA,iEACA,qBACA,qBACA,cAGF,uBACE,kBACA,mCAGF,gDACE,WAGF,yBACE,wBACA,2BAKN,gBACE,SACA,UACA,qBAIA,0BACE,WACA,gBACA,YACA,kCAGF,gBACE,4BACA,6BAIJ,qDAEE,qBACA,eAGF,oCACE,YACA,6BAIA,iCACE,kCACA,mCACA,uCACE,UAIA,4FACE,mBACA,gBACA,iFAGF,gGACE,mBACA,gBACA,gFAGF,sGACE,mBACA,gBACA,iFAGF,8FACE,mBACA,gBACA,iFAGF,gGACE,mBACA,gBACA,+EAGJ,qCACE,sBACA,YACA,WACA,kBACA,WACA,4EAEF,uCACE,gCACA,cACA,WACA,SACA,WACA,kBACA,eACA,YAEF,6CACE,uCACA,kBACA,mDACE,YACA,kBACA,SAEF,+CACE,kBACA,QACA,SACA,cACA,uDACE,cACA,UACA,WAKJ,4DACE,YACA,iBACA,kBACA,YAEF,iDACE,wBACA,4BACA,2BACA,WACA,iBACA,WAEF,mDACE,qBACA,eACA,gBACA,gBACA,uBACA,mBAMJ,uBACE,kBACA,UACA,WACA,mBACA,YACA,qBACA,WACA,YACA,kBACA,kBAGF,sBACE,gDACA,qCACA,kBAGF,wBACE,sCAGF,wBACE,sCAMJ,gFACE,aAGF,kDACE,UAKF,uBACE,qBACA,WAGF,mCACE,cAIJ,gBACE,wBACA,UACA,aAEA,mBACE,YACA,kBACA,0BACA,WAKF,2BACE,WACA,kBACA,QACA,QACA,UACA,sBAGF,6BACE,eACA,qBAGF,oCACE,UAIA,yBACE,WACA,0BACA,kBAGF,6BACE,iBAIJ,oBACE,iBAIJ,0CACE,kCACA,gBACA,YAKE,uEACE,gBACA,SACA,UACA,iBAKF,2EACE,gBACA,SACA,UACA,iBAIJ,gEACE,aAIJ,SACE,kBACA,SAGF,YACE,WACA,YACA,wBACA,qCACA,yBACA,4BACA,2BACA,kBACA,eACA,wBACE,WAEF,kBACE,qBAIJ,UACE,kBACA,aACA,YACA,qCACA,YACA,gCACA,WACA,kBAGF,UACE,kBACA,qCACA,WACA,mCAEA,mBACE,kBACA,MACA,OACA,SACA,yBAEA,4BACE,yBAIJ,oBACE,kBACA,UAIJ,yBACE,kBACA,WACA,YAGF,uCACE,WACA,6DACA,wBACA,4BACA,2BACA,kBACA,OACA,QACA,MACA,SAGF,uBACE,qEAGF,YACE,aACA,sBAGF,cACE,aACA,mBACA,kBAEA,mBACE,OACA,WAEA,uBACE,QAGF,uBACE,QAKN,6BACE,WACA,kBACA,MACA,OACA,QACA,SACA,4GACA,mDACA,2BAIA,aACE,sCAGJ,+BAEI,qBACA,YACA,qCACA,iBACA,kBAGJ,kBACE,qBACA,yBACA,iBACA,kBACA,WACA,gBACA,4BACA,yBAEA,0BACE,qBACA,yBAGF,0BACE,qBACA,yBAIJ,qCACE,cAGF,UACE,WACA,YACA,iBACA,gBACA,cACA,gBACA,kBACA,YAEA,eACE,UACA,YACA,gBACA,kBACA,MACA,UAGF,yBACE,OAGF,wBACE,WACA,YACA,gBACA,iBACA,mBACA,kBACA,MAGF,uCACE,UACA,+BACA,kCACA,cACA,qCACA,6BACA,uCAGF,0BACE,QAEA,wCACE,WACA,8BACA,iCACA,eACA,sCACA,8BACA,wCAIJ,0BACE,UACA,WACA,kBACA,cACA,cACA,iBACA,kBACA,kBACA,OACA,QAGF,6BACE,qBAKF,gBAcE,SAbA,kBACE,cACA,WACA,WAGF,oBACE,WACA,SACA,kBACA,WAMJ,0BACE,qCACA,mBAIJ,yBACE,kBAGF,qBACE,mBACA,uBACA,mBAEA,4BACE,WACA,YACA,kBAIJ,gBACE,iBAGF,eACE,iBAEA,qBACE,cAIJ,2BACE,cAGF,oBACE,iBAGF,yBACE,+BAEA,gCACE,WAGF,+BACE,0BAGF,wCACE,kBAIJ,kBACE,cAGF,8BACE,kBACA,UACA,SACA,OACA,MACA,QAIA,yBACE,eAEF,0BACE,cACA,iBAEF,8BACE,YAEA,qCACE,YAKN,aACE,sBAGF,aACE,kBACA,QACA,QACA,WACA,SACA,oBAEA,qBACE,kBACA,WACA,WACA,sBACA,oBAIJ,cACE,sBACA,gBACA,WACA,kBACA,YACA,6DACA,4BAIA,0BACE,SACA,kBACA,YAEA,iCACE,WAGF,sCACE,eAIJ,0BACE,iBAEA,gCACE,uBAIJ,qCACE,YAIJ,kCACE,WACA,YAGF,aACE,UACA,kBAIA,qCACE,UACA,kBAIJ,cACE,WACA,wBACA,4BACA,kBACA,WACA,YACA,UACA,SACA,UAGF,iBACE,kDAGF,iBACE,kDAGF,kCACE,kDAGF,UACE,YACA,wBAGF,6CACE,WACA,4DACA,wBACA,4BACA,kBACA,OACA,QACA,SACA,MACA,WACA,WAIA,qCACE,WACA,4DACA,wBACA,4BACA,kBACA,OACA,QACA,SACA,MACA,WACA,WAGF,qCACE,4BAGF,iBACE,yDACA,WAIJ,oBACE,cAGF,eACE,cACA,sEACA,WACA,wBACA,kCACA,cACA,6BACE,oBAIJ,kCAEE,eACA,wBACA,kCACA,kBACA,iBACA,mBACA,sCACE,YAEF,8CACE,kBACA,iBACA,mBACA,mBACA,SACA,UAIJ,UACE,oBACA,iEAGF,wBACE,iBACA,kCACA,mBACA,sEAGF,aACE,4BACA,wBACA,YACA,gBACA,gBACA,2BACA,WAGF,UACE,qBACA,WACA,YACA,wBACA,4BACA,gBACA,iBAEA,oBACE,kDAGF,iBACE,oDAGF,mBACE,sDAGF,eACE,kDAGF,gBACE,mDAIJ,eACE,qBACA,kBACA,eACA,gBAGF,sBACI,WACA,kBACA,SACA,MACA,OACA,QACA,4BACA,2BACA,wBAKF,kBACE,qBACA,YACA,SACA,eACA,gBACA,eACA,iBAGF,kBACE,SACA,YACA,eAIJ,YACE,WAEA,gBACE,WACA,WACA,YAIJ,kCACE,kCACA,WACA,mBACA,aAGF,sBAEE,eACA,QACA,uBACA,aACA,YACA,aAEA,0CACE,aACA,uBACA,mBAIJ,UACE,cACA,uBACA,YACA,uBACA,QAEA,sBACG,kBACA,sBACA,OACA,SACA,QAEH,gBACE,YACA,YACA,aACA,kBACA,gBACA,kBACA,WACA,sJAGF,iBACE,mBACA,kBACA,eACA,kBACA,UACA,+DACA,WACA,mBACA,aACA,iBACA,sJAGF,iBACE,YACA,YACA,aACA,UACA,6EAIJ,wBACE,GACE,mBACA,UAGF,IACE,UAGF,KACE,oBAIJ,sBACE,GACE,UAGF,IACE,UAGF,KACE,WAIJ,yBACE,GACE,mCACA,mBACA,+BAGF,IACE,kCACA,sBAGF,IACE,mCACA,sBAGF,IACE,kCACA,sBAGF,IACE,mCACA,oBAIJ,iBACE,uBACA,mBAGF,yBACE,aAGF,SACE,iBAGF,gBACE,qBACA,kBACA,eACA,YACA,WAEA,sBACE,kBACA,UACA,YACA,WAGF,qBACE,kBACA,MACA,OACA,YACA,WACA,2DACA,2BACA,wBACA,4BACA,YACA,+BAGF,+BACE,mEAGF,6BACE,iEAGF,8BACE,kEAGF,0BACE,8DAGF,4BACE,gEAGF,kCACE,sEAGF,oEACE,UAIJ,mBACE,eACA,uBACA,UACA,gBACA,SACA,UACA,YAGF,mEACE,WAGF,eACE,wBACA,YACA,eAGF,4BACE,uBACA,gBACA,mBAGF,YACE,eAEA,kBACE,kCAIJ,gBACE,kCAKF,0BACE,kBAGF,kCACE,cAKF,2CACE,+BAIA,iCACE,+DACA,2BACA,4CAGF,kCACE,eACA,qCACE,YACA,kBACA,+BAEF,2CACE,sBACA,WAKN,YACE,kBAEA,wBACE,mBACA,gBACA,iCACA,4CACA,qBACA,iBACA,uBACA,2CACE,aAGF,iCACE,sBACA,YAEA,qFACE,oBAKN,kBACE,wBACA,wBACE,OAIJ,6CACE,kBACA,gBACA,eACA,YACA,cACA,aACA,2BAGF,uBACE,QAGF,sBACE,OAKJ,aACE,iBAKA,uBACA,gBALA,eACE,uBACA,gBAIF,gBACE,YACA,eACA,iBAEF,kBACE,SAEF,wBACE,aAIJ,iBACE,gBACA,2BACE,gBACA,YACA,gCAEF,kCACE,YAEF,+BACE,qBAEF,2BACE,WACA,QAEF,wCACE,SACA,UACA,gBAGA,wBACE,eACA,iBACA,kBAKF,0CACE,iBAEF,kCACE,WACA,YACA,wBAGJ,iCACE,gBACA,6CACE,4BAEF,4CACE,6BAGJ,+DAEE,cACA,sBACA,qCACA,YACA,WACA,eACA,sBACA,iBACA,kBACA,gCACA,sCAEA,6EACE,qBAEF,2EACE,qBAEF,uEACE,sBACE,YACA,WAGN,8BACE,oBAGF,4CACE,gBACA,YAIF,iCACE,aACA,eACA,uBACA,sBACA,oCACE,cACA,gBACA,YACA,WACA,eACA,mBACA,sBACA,4BACA,kBACA,sBAIA,+CACE,YAGF,wCACE,YACA,WACA,kBAKN,6BACE,WACA,eACA,4EAEF,6BACE,cAEA,6CACE,YAGJ,iCACE,mBACA,mCACA,2BACA,WACA,YACA,yBACA,gBACA,kBAIE,4CACE,cACA,kBAEA,eACA,gDACE,aAEF,yDACE,iBACA,cACA,gBACA,uBAMR,0DAEE,SACA,UACA,mBACA,kBACA,aACA,eACA,YACA,gCACA,6BAEA,sEACE,YACA,cACA,WACA,SACA,WACA,kBACA,eACA,WAGF,0KAEE,UACA,OAEF,oFACE,aACA,WAKA,wMACE,WAEF,wKACE,mBACA,gBACA,iFAGF,gLACE,mBACA,gBACA,gFAGF,4LACE,mBACA,gBACA,iFAGF,4KACE,mBACA,gBACA,iFAGF,gLACE,mBACA,gBACA,+EAIJ,gEACE,gCACA,8BAEA,sBACA,gCACA,mBACA,sBACA,qCACA,4BACA,kBACA,sBACA,wBAEA,sFACE,mBACA,mCACA,uBAGF,4EACE,qBAGF,wEACE,sBACA,YACA,WACA,kBACA,WACA,4EACA,gCACA,oFACE,qBAMR,6BACE,YAGJ,0BACE,iBACI,6BChyIJ,kCACI,qCACA,6DAEA,wCACI,WAIJ,uEACE,WACA,0EACE,WAIJ,gEACE,WAIN,8BACI,6BACA,yBACA,2CAGJ,8BACI,gBAGJ,8CACI,iBACA,kEACA,0BACA,4BAGA,6BACA,cAGJ,qFAEI,2BACA,kBACA,kBAEA,2DACA,wBACA,8BACA,0BAGJ,oDACI,WAGJ,iHAEI,WAGJ,2CACI,WAGJ,4BAkFI,gBACA,gBAlFA,kDACI,yBAGJ,yDACI,gEACA,2BACA,2BACA,4BAGJ,4CACI,gEACA,2BACA,2BACA,4BAGJ,mHAEI,sEACA,2BACA,2BACA,2BAEA,gSAEI,YACA,cACA,iBACA,gBAEA,wSACI,cAKZ,uDACI,eAKA,qIACI,kBACA,WACA,sBAEA,mJACI,kBACA,MACA,OACA,WACA,YACA,SAKZ,mDACI,iBACA,oBAGJ,gKAGI,iEACA,YACA,QAGJ,+KAGI,iEACA,WACA,WAMJ,2FAEI,4BACA,kBACA,gBACA,UACA,YACA,WACA,0BAGJ,2DACI,gBAKA,6FAEI,sBAIR,2CACI,8DACA,QACA,YAGJ,gDACI,+DACA,YACA,WAGJ,iDACI,sEAGJ,6CACI,kEAGJ,oEACI,YAKA,sHAEI,WACA,YACA,gBAIR,2DACI,WACA,YACA,gBAEA,6DACI,WACA,sBACA,YACA,sBACA,kBACA,mBACA,WAIR,2GAEI,WACA,sBACA,YACA,sBACA,kBACA,mBACA,WAGJ,qDACI,UACA,YACA,WAGJ,yDACI,kBACA,gBACA,eACA,WACA,4BACA,iBACA,gCACA,wCAGJ,4IAEI,gBACA,WACA,yBAGJ,iDACI,kBAGJ,mGAEI,iBACA,kBAGJ,6CACI,gBACA,SACA,UACA,iBAKA,uGAEI,gBACA,SACA,UACA,iBAMJ,2GAEI,gBACA,SACA,UACA,iBAIR,gGAEI,aAIA,6GACE,0BACA,UACA,eACA,WAGF,0DACE,gCAEA,gEACE,gCAGJ,6CACI,gBACA,SACA,UACA,iBAKZ,oDACI,gEACA,2BACA,2BACA,4BAGJ,sCACI,kBACA,oBACA,kBACA,mEACA,YACA,WAGJ,2CACI,qBACA,kEACA,wBACA,WACA,YACA,SACA,4BACA,2BACA,kBACA,QAGJ,yBACI,YACA,WACA,aAEA,2EACI,cAGJ,2DACI,cAEJ,sEACI,cAGJ,yUAGI,kCAGJ,4CACI,mBACA,2EACA,kBAGJ,0CACI,aAGJ,4OAII,iCACA,WACA,qCACA,kBACA,WACA,iBAGJ,sCACI,WAII,mDACI,cAIR,sDACI,WACA,mEAIR,yCACI,iBACA,0DACI,WAIR,gCACI,kBACA,MACA,SACA,WACA,QACA,WACA,0DACA,2BACA,qBACA,WAKJ,wCACI,kEAGJ,kEACI,WAGJ,wDACI,oBACA,iBAIR,gCACI,WAGI,oCACI,WAGJ,6CACI,cAIR,gDACI,WACA,6DAIR,6BACI,6DACA,sBACA,WACA,YACA,sBACA,kBAIA,+BACI,2JACA,8CACA,4BACA,WACA,kBACA,SACA,YACA,aACA,UACA,WACA,0DAGJ,iCACI,mBACA,wCACI,wEACA,6DAEJ,2CACI,WAEJ,2CACI,gBAEJ,8CACI,WAEJ,+FAEI,6DACA,sBACA,WAEJ,8CACI,sCAIA,gGACI,sCACA,6DAEA,sHACI,mCAGR,sGACI,WAKZ,+CACI,gEAGJ,+BACI,gBACA,gCAEA,sCACI,sCACA,uDAEA,4CACI,sCAGJ,6CACI,sCAKZ,oCACI,YACA,SAGJ,sCACI,SACA,gBAGA,WACA,YAGA,gBAEA,kDACI,gBAKZ,0BAEQ,+BACI,8CACA,2DACA,YACA,SAEJ,wCACI,gDACA,4DACA,SACA,UAGA,qGACI,cAMhB,0DACI,gBAGJ,yBACI,gBACA,YACA,gBAEA,gCACI,4DACA,0BACA,4BACA,WACA,kBACA,UACA,WACA,YACA,UACA,WACA,gCAGJ,4BAeI,YACA,kBACA,iBAhBA,mCACI,wGACA,iDACA,4BACA,WACA,kBACA,UACA,WACA,WACA,UACA,WACA,2CAQR,sCACI,YACA,kBACA,iBAEA,6CACI,4DACA,0BACA,2BACA,WACA,kBACA,UACA,WACA,WACA,SACA,WACA,+BAKZ,6NAMI,4FACA,WACA,sBAEA,uQACI,8BAGJ,iQACI,8BAGJ,yRACI,yBACA,sBAKJ,uEACE,gBACA,YAGF,gLACE,WAKF,+CACE,iCACA,WACA,qCACA,kBACA,WACA,iBACA,YAGF,sDACI,WAEJ,2CACE,WACA,gBAIJ,yEACE,WAGF,mIACE,cAGF,0FACE,WAGF,4BACE,cAGF,oCACE,qBCjuBA,oDACI,kEACA,2BACA,eAIR,6BACI,2DACA,wBACA,iCACA,0BACA,4BAGJ,wBACI,kBAeA,4BACA,WACA,2DACA,wBACA,8BACA,0BAnBA,8BACE,WACA,oBACA,kBACA,aACA,OACA,QACA,YACA,UACA,oDACA,4BACA,2BACA,kCASF,kDACE,WAIA,yDACE,sBAEF,oEACE,WAIJ,+FAGE,WAIN,iPAGI,mBACA,4FACA,0BACA,gBAIA,yDACI,gEACA,2BACA,2BACA,4BAOI,gUAEI,YACA,cACA,iBACA,gBAEA,wUACI,cCzFxB,MACI,oBAGJ,KACI","file":"dsa5.css"} \ No newline at end of file diff --git a/styles/scss/dsa5.scss b/styles/scss/dsa5.scss index 8bdd7a19..96273751 100644 --- a/styles/scss/dsa5.scss +++ b/styles/scss/dsa5.scss @@ -4091,6 +4091,13 @@ } .itemTooltip { + max-height:500px; + p { + text-overflow: ellipsis; + overflow:hidden; + } + text-overflow: ellipsis; + overflow: hidden; h1 { border: none; font-size: 22px; @@ -4274,8 +4281,6 @@ transition: all 0.15s ease-in-out; scroll-snap-type: y mandatory; - - input{ height: 100%; display: block; @@ -4333,7 +4338,7 @@ } } - li { + & > li { flex: 0 0 var(--base-bar-height); height: var(--base-bar-height); diff --git a/styles/scss/immersive.scss b/styles/scss/immersive.scss index eff56285..5b082bd9 100644 --- a/styles/scss/immersive.scss +++ b/styles/scss/immersive.scss @@ -521,7 +521,7 @@ } #macro-list, .skillItems { - li { + & > li { box-shadow: inset 0px 0px 25px #403014; background-image: url("../../icons/backgrounds/macrobg.webp"); diff --git a/system.json b/system.json index e8b3ac17..7e19d1a0 100644 --- a/system.json +++ b/system.json @@ -2,7 +2,7 @@ "id": "dsa5", "title": "Das Schwarze Auge/The Dark Eye (5th Edition)", "description": "The \"Das Schwarze Auge\" system for Foundry VTT. Includes all relevant mechanisms to play in the wonderous world of Aventuria and Das Schwarze Auge/The Dark Eye.", - "version": "5.2.20", + "version": "5.3.0", "authors": [ { "name": "Plushtoast" @@ -104,7 +104,7 @@ }, "url": "https://github.com/Plushtoast/dsa5-foundryVTT", "manifest": "https://raw.githubusercontent.com/Plushtoast/dsa5-foundryVTT/foundry11/system.json", - "download": "https://github.com/Plushtoast/dsa5-foundryVTT/releases/download/5.2.8/dsa5-foundryVTT-5.2.8.zip", + "download": "https://github.com/Plushtoast/dsa5-foundryVTT/releases/download/5.3.0/dsa5-foundryVTT-5.3.0.zip", "name": "dsa5", "minimumCoreVersion": "11.306", "packFolders": [ diff --git a/templates/items/browse/plant.html b/templates/items/browse/plant.html index e40af6c9..a9d6eca2 100644 --- a/templates/items/browse/plant.html +++ b/templates/items/browse/plant.html @@ -44,19 +44,22 @@

    {{document.name}}

    {{/each}}
    - + {{#if document.system.location.landscape}}
    {{localize "PLANT.landscape"}}
    {{document.system.location.landscape}}
    + {{/if}} + {{#if document.system.location.region}}
    {{localize "PLANT.region"}}
    {{document.system.location.region}}
    + {{/if}}
    {{localize "PLANT.search"}}
    @@ -81,12 +84,14 @@

    {{document.name}}

    {{{enrichedEffect}}}
    + {{if enrichedRecipes}}
    {{localize "PLANT.recipes"}}
    {{{enrichedRecipes}}}
    + {{/if}}
    diff --git a/templates/system/hud/hotbar.html b/templates/system/hud/hotbar.html index 7c9bd3d9..2c3c6f48 100644 --- a/templates/system/hud/hotbar.html +++ b/templates/system/hud/hotbar.html @@ -1,110 +1,110 @@ -
    - -
    - - -
    -
    +
    + +
    + + +
    +
    diff --git a/templates/wizard/adventure/adventure_toc.html b/templates/wizard/adventure/adventure_toc.html index 51172a9f..70e2595d 100644 --- a/templates/wizard/adventure/adventure_toc.html +++ b/templates/wizard/adventure/adventure_toc.html @@ -17,7 +17,6 @@

    {{/if}}
    - {{log pageTocs}}