mirador_rails 0.3.2 → 0.3.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -76,14 +76,14 @@ return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1
76
76
  blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxdl:"┐",boxdL:"╕",boxDl:"╖",boxDL:"╗",boxdr:"┌",boxdR:"╒",boxDr:"╓",boxDR:"╔",boxh:"─",boxH:"═",boxhd:"┬",boxHd:"╤",boxhD:"╥",boxHD:"╦",boxhu:"┴",boxHu:"╧",boxhU:"╨",boxHU:"╩",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxul:"┘",boxuL:"╛",boxUl:"╜",boxUL:"╝",boxur:"└",boxuR:"╘",boxUr:"╙",boxUR:"╚",boxv:"│",boxV:"║",boxvh:"┼",boxvH:"╪",boxVh:"╫",boxVH:"╬",boxvl:"┤",boxvL:"╡",boxVl:"╢",boxVL:"╣",boxvr:"├",boxvR:"╞",boxVr:"╟",boxVR:"╠",bprime:"‵",breve:"˘",Breve:"˘",brvbar:"¦",bscr:"𝒷",Bscr:"ℬ",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsolb:"⧅",bsol:"\\",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",capand:"⩄",capbrcup:"⩉",capcap:"⩋",cap:"∩",Cap:"⋒",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",centerdot:"·",CenterDot:"·",cfr:"𝔠",Cfr:"ℭ",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cir:"○",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",colon:":",Colon:"∷",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",conint:"∮",Conint:"∯",ContourIntegral:"∮",copf:"𝕔",Copf:"ℂ",coprod:"∐",Coproduct:"∐",copy:"©",COPY:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",cross:"✗",Cross:"⨯",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",cupbrcap:"⩈",cupcap:"⩆",CupCap:"≍",cup:"∪",Cup:"⋓",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",dagger:"†",Dagger:"‡",daleth:"ℸ",darr:"↓",Darr:"↡",dArr:"⇓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",ddagger:"‡",ddarr:"⇊",DD:"ⅅ",dd:"ⅆ",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",diamond:"⋄",Diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrowBar:"⤓",downarrow:"↓",DownArrow:"↓",Downarrow:"⇓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVectorBar:"⥖",DownLeftVector:"↽",DownRightTeeVector:"⥟",DownRightVectorBar:"⥗",DownRightVector:"⇁",DownTeeArrow:"↧",DownTee:"⊤",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",Ecirc:"Ê",ecirc:"ê",ecir:"≖",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",edot:"ė",eDot:"≑",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp13:" ",emsp14:" ",emsp:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",escr:"ℯ",Escr:"ℰ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",exponentiale:"ⅇ",ExponentialE:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",forall:"∀",ForAll:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",fscr:"𝒻",Fscr:"ℱ",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",ge:"≥",gE:"≧",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",gescc:"⪩",ges:"⩾",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",gg:"≫",Gg:"⋙",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gla:"⪥",gl:"≷",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gne:"⪈",gnE:"≩",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",gtcc:"⪧",gtcir:"⩺",gt:">",GT:">",Gt:"≫",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",harrcir:"⥈",harr:"↔",hArr:"⇔",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"𝔥",Hfr:"ℌ",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"𝕙",Hopf:"ℍ",horbar:"―",HorizontalLine:"─",hscr:"𝒽",Hscr:"ℋ",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",ifr:"𝔦",Ifr:"ℑ",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",Im:"ℑ",imof:"⊷",imped:"Ƶ",Implies:"⇒",incare:"℅",in:"∈",infin:"∞",infintie:"⧝",inodot:"ı",intcal:"⊺",int:"∫",Int:"∬",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",iscr:"𝒾",Iscr:"ℐ",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",lang:"⟨",Lang:"⟪",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",larrb:"⇤",larrbfs:"⤟",larr:"←",Larr:"↞",lArr:"⇐",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",latail:"⤙",lAtail:"⤛",lat:"⪫",late:"⪭",lates:"⪭︀",lbarr:"⤌",lBarr:"⤎",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",lE:"≦",LeftAngleBracket:"⟨",LeftArrowBar:"⇤",leftarrow:"←",LeftArrow:"←",Leftarrow:"⇐",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVectorBar:"⥙",LeftDownVector:"⇃",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTeeArrow:"↤",LeftTee:"⊣",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangleBar:"⧏",LeftTriangle:"⊲",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVectorBar:"⥘",LeftUpVector:"↿",LeftVectorBar:"⥒",LeftVector:"↼",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",lescc:"⪨",les:"⩽",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",llarr:"⇇",ll:"≪",Ll:"⋘",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoustache:"⎰",lmoust:"⎰",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lnE:"≨",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftrightarrow:"⟷",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longmapsto:"⟼",longrightarrow:"⟶",LongRightArrow:"⟶",Longrightarrow:"⟹",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",lscr:"𝓁",Lscr:"ℒ",lsh:"↰",Lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",ltcc:"⪦",ltcir:"⩹",lt:"<",LT:"<",Lt:"≪",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",midast:"*",midcir:"⫰",mid:"∣",middot:"·",minusb:"⊟",minus:"−",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",mscr:"𝓂",Mscr:"ℳ",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natural:"♮",naturals:"ℕ",natur:"♮",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",nearhk:"⤤",nearr:"↗",neArr:"⇗",nearrow:"↗",ne:"≠",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nharr:"↮",nhArr:"⇎",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlarr:"↚",nlArr:"⇍",nldr:"‥",nlE:"≦̸",nle:"≰",nleftarrow:"↚",nLeftarrow:"⇍",nleftrightarrow:"↮",nLeftrightarrow:"⇎",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",nopf:"𝕟",Nopf:"ℕ",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangleBar:"⧏̸",NotLeftTriangle:"⋪",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangleBar:"⧐̸",NotRightTriangle:"⋫",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",nparallel:"∦",npar:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",nprec:"⊀",npreceq:"⪯̸",npre:"⪯̸",nrarrc:"⤳̸",nrarr:"↛",nrArr:"⇏",nrarrw:"↝̸",nrightarrow:"↛",nRightarrow:"⇏",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nvdash:"⊬",nvDash:"⊭",nVdash:"⊮",nVDash:"⊯",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwarr:"↖",nwArr:"⇖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",Ocirc:"Ô",ocirc:"ô",ocir:"⊚",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",orarr:"↻",Or:"⩔",or:"∨",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",otimesas:"⨶",Otimes:"⨷",otimes:"⊗",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",para:"¶",parallel:"∥",par:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plus:"+",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",popf:"𝕡",Popf:"ℙ",pound:"£",prap:"⪷",Pr:"⪻",pr:"≺",prcue:"≼",precapprox:"⪷",prec:"≺",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",pre:"⪯",prE:"⪳",precsim:"≾",prime:"′",Prime:"″",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportional:"∝",Proportion:"∷",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",qopf:"𝕢",Qopf:"ℚ",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quot:'"',QUOT:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",Rang:"⟫",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarr:"→",Rarr:"↠",rArr:"⇒",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",ratail:"⤚",rAtail:"⤜",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rBarr:"⤏",RBarr:"⤐",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",Re:"ℜ",rect:"▭",reg:"®",REG:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",rfr:"𝔯",Rfr:"ℜ",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrowBar:"⇥",rightarrow:"→",RightArrow:"→",Rightarrow:"⇒",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVectorBar:"⥕",RightDownVector:"⇂",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTeeArrow:"↦",RightTee:"⊢",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangleBar:"⧐",RightTriangle:"⊳",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVectorBar:"⥔",RightUpVector:"↾",RightVectorBar:"⥓",RightVector:"⇀",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoustache:"⎱",rmoust:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"𝕣",Ropf:"ℝ",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",rscr:"𝓇",Rscr:"ℛ",rsh:"↱",Rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",scap:"⪸",Scaron:"Š",scaron:"š",Sc:"⪼",sc:"≻",sccue:"≽",sce:"⪰",scE:"⪴",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdotb:"⊡",sdot:"⋅",sdote:"⩦",searhk:"⤥",searr:"↘",seArr:"⇘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",solbar:"⌿",solb:"⧄",sol:"/",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",square:"□",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squ:"□",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",Sub:"⋐",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",Subset:"⋐",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succapprox:"⪸",succ:"≻",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",sum:"∑",Sum:"∑",sung:"♪",sup1:"¹",sup2:"²",sup3:"³",sup:"⊃",Sup:"⋑",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",Supset:"⋑",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swarr:"↙",swArr:"⇙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",therefore:"∴",Therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",ThinSpace:" ",thinsp:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",tilde:"˜",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",timesbar:"⨱",timesb:"⊠",times:"×",timesd:"⨰",tint:"∭",toea:"⤨",topbot:"⌶",topcir:"⫱",top:"⊤",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",TRADE:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",uarr:"↑",Uarr:"↟",uArr:"⇑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrowBar:"⤒",uparrow:"↑",UpArrow:"↑",Uparrow:"⇑",UpArrowDownArrow:"⇅",updownarrow:"↕",UpDownArrow:"↕",Updownarrow:"⇕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",upsi:"υ",Upsi:"ϒ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTeeArrow:"↥",UpTee:"⊥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",vArr:"⇕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vBar:"⫨",Vbar:"⫫",vBarv:"⫩",Vcy:"В",vcy:"в",vdash:"⊢",vDash:"⊨",Vdash:"⊩",VDash:"⊫",Vdashl:"⫦",veebar:"⊻",vee:"∨",Vee:"⋁",veeeq:"≚",vellip:"⋮",verbar:"|",Verbar:"‖",vert:"|",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",Wedge:"⋀",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xharr:"⟷",xhArr:"⟺",Xi:"Ξ",xi:"ξ",xlarr:"⟵",xlArr:"⟸",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrarr:"⟶",xrArr:"⟹",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",yuml:"ÿ",Yuml:"Ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",zfr:"𝔷",Zfr:"ℨ",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",zopf:"𝕫",Zopf:"ℤ",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}},{}],26:[function(require,module,exports){module.exports={Aacute:"Á",aacute:"á",Acirc:"Â",acirc:"â",acute:"´",AElig:"Æ",aelig:"æ",Agrave:"À",agrave:"à",amp:"&",AMP:"&",Aring:"Å",aring:"å",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",brvbar:"¦",Ccedil:"Ç",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",COPY:"©",curren:"¤",deg:"°",divide:"÷",Eacute:"É",eacute:"é",Ecirc:"Ê",ecirc:"ê",Egrave:"È",egrave:"è",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",GT:">",Iacute:"Í",iacute:"í",Icirc:"Î",icirc:"î",iexcl:"¡",Igrave:"Ì",igrave:"ì",iquest:"¿",Iuml:"Ï",iuml:"ï",laquo:"«",lt:"<",LT:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",Ntilde:"Ñ",ntilde:"ñ",Oacute:"Ó",oacute:"ó",Ocirc:"Ô",ocirc:"ô",Ograve:"Ò",ograve:"ò",ordf:"ª",ordm:"º",Oslash:"Ø",oslash:"ø",Otilde:"Õ",otilde:"õ",Ouml:"Ö",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',QUOT:'"',raquo:"»",reg:"®",REG:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",THORN:"Þ",thorn:"þ",times:"×",Uacute:"Ú",uacute:"ú",Ucirc:"Û",ucirc:"û",Ugrave:"Ù",ugrave:"ù",uml:"¨",Uuml:"Ü",uuml:"ü",Yacute:"Ý",yacute:"ý",yen:"¥",yuml:"ÿ"}},{}],27:[function(require,module,exports){module.exports={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}},{}],28:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i<len;i++)listeners[i].apply(this,args);return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned&&(m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(position<0)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],29:[function(require,module,exports){function CollectingHandler(cbs){this._cbs=cbs||{},this.events=[]}module.exports=CollectingHandler;var EVENTS=require("./").EVENTS;Object.keys(EVENTS).forEach(function(name){if(0===EVENTS[name])name="on"+name,CollectingHandler.prototype[name]=function(){this.events.push([name]),this._cbs[name]&&this._cbs[name]()};else if(1===EVENTS[name])name="on"+name,CollectingHandler.prototype[name]=function(a){this.events.push([name,a]),this._cbs[name]&&this._cbs[name](a)};else{if(2!==EVENTS[name])throw Error("wrong number of arguments");name="on"+name,CollectingHandler.prototype[name]=function(a,b){this.events.push([name,a,b]),this._cbs[name]&&this._cbs[name](a,b)}}}),CollectingHandler.prototype.onreset=function(){this.events=[],this._cbs.onreset&&this._cbs.onreset()},CollectingHandler.prototype.restart=function(){this._cbs.onreset&&this._cbs.onreset();for(var i=0,len=this.events.length;i<len;i++)if(this._cbs[this.events[i][0]]){var num=this.events[i].length;1===num?this._cbs[this.events[i][0]]():2===num?this._cbs[this.events[i][0]](this.events[i][1]):this._cbs[this.events[i][0]](this.events[i][1],this.events[i][2])}}},{"./":36}],30:[function(require,module,exports){function FeedHandler(callback,options){this.init(callback,options)}function getElements(what,where){return DomUtils.getElementsByTagName(what,where,!0)}function getOneElement(what,where){return DomUtils.getElementsByTagName(what,where,!0,1)[0]}function fetch(what,where,recurse){return DomUtils.getText(DomUtils.getElementsByTagName(what,where,recurse,1)).trim()}function addConditionally(obj,prop,what,where,recurse){var tmp=fetch(what,where,recurse);tmp&&(obj[prop]=tmp)}var index=require("./index.js"),DomHandler=index.DomHandler,DomUtils=index.DomUtils;require("inherits")(FeedHandler,DomHandler),FeedHandler.prototype.init=DomHandler;var isValidFeed=function(value){return"rss"===value||"feed"===value||"rdf:RDF"===value};FeedHandler.prototype.onend=function(){var tmp,childs,feed={},feedRoot=getOneElement(isValidFeed,this.dom);feedRoot&&("feed"===feedRoot.name?(childs=feedRoot.children,feed.type="atom",addConditionally(feed,"id","id",childs),addConditionally(feed,"title","title",childs),(tmp=getOneElement("link",childs))&&(tmp=tmp.attribs)&&(tmp=tmp.href)&&(feed.link=tmp),addConditionally(feed,"description","subtitle",childs),(tmp=fetch("updated",childs))&&(feed.updated=new Date(tmp)),addConditionally(feed,"author","email",childs,!0),feed.items=getElements("entry",childs).map(function(item){var tmp,entry={};return item=item.children,addConditionally(entry,"id","id",item),addConditionally(entry,"title","title",item),(tmp=getOneElement("link",item))&&(tmp=tmp.attribs)&&(tmp=tmp.href)&&(entry.link=tmp),(tmp=fetch("summary",item)||fetch("content",item))&&(entry.description=tmp),
77
77
  (tmp=fetch("updated",item))&&(entry.pubDate=new Date(tmp)),entry})):(childs=getOneElement("channel",feedRoot.children).children,feed.type=feedRoot.name.substr(0,3),feed.id="",addConditionally(feed,"title","title",childs),addConditionally(feed,"link","link",childs),addConditionally(feed,"description","description",childs),(tmp=fetch("lastBuildDate",childs))&&(feed.updated=new Date(tmp)),addConditionally(feed,"author","managingEditor",childs,!0),feed.items=getElements("item",feedRoot.children).map(function(item){var tmp,entry={};return item=item.children,addConditionally(entry,"id","guid",item),addConditionally(entry,"title","title",item),addConditionally(entry,"link","link",item),addConditionally(entry,"description","description",item),(tmp=fetch("pubDate",item))&&(entry.pubDate=new Date(tmp)),entry}))),this.dom=feed,DomHandler.prototype._handleCallback.call(this,feedRoot?null:Error("couldn't find root of feed"))},module.exports=FeedHandler},{"./index.js":36,inherits:38}],31:[function(require,module,exports){function Parser(cbs,options){this._options=options||{},this._cbs=cbs||{},this._tagname="",this._attribname="",this._attribvalue="",this._attribs=null,this._stack=[],this.startIndex=0,this.endIndex=null,this._lowerCaseTagNames="lowerCaseTags"in this._options?!!this._options.lowerCaseTags:!this._options.xmlMode,this._lowerCaseAttributeNames="lowerCaseAttributeNames"in this._options?!!this._options.lowerCaseAttributeNames:!this._options.xmlMode,this._options.Tokenizer&&(Tokenizer=this._options.Tokenizer),this._tokenizer=new Tokenizer(this._options,this),this._cbs.onparserinit&&this._cbs.onparserinit(this)}var Tokenizer=require("./Tokenizer.js"),formTags={input:!0,option:!0,optgroup:!0,select:!0,button:!0,datalist:!0,textarea:!0},openImpliesClose={tr:{tr:!0,th:!0,td:!0},th:{th:!0},td:{thead:!0,th:!0,td:!0},body:{head:!0,link:!0,script:!0},li:{li:!0},p:{p:!0},h1:{p:!0},h2:{p:!0},h3:{p:!0},h4:{p:!0},h5:{p:!0},h6:{p:!0},select:formTags,input:formTags,output:formTags,button:formTags,datalist:formTags,textarea:formTags,option:{option:!0},optgroup:{optgroup:!0}},voidElements={__proto__:null,area:!0,base:!0,basefont:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,isindex:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,path:!0,circle:!0,ellipse:!0,line:!0,rect:!0,use:!0,stop:!0,polyline:!0,polygon:!0},re_nameEnd=/\s|\//;require("inherits")(Parser,require("events").EventEmitter),Parser.prototype._updatePosition=function(initialOffset){null===this.endIndex?this._tokenizer._sectionStart<=initialOffset?this.startIndex=0:this.startIndex=this._tokenizer._sectionStart-initialOffset:this.startIndex=this.endIndex+1,this.endIndex=this._tokenizer.getAbsoluteIndex()},Parser.prototype.ontext=function(data){this._updatePosition(1),this.endIndex--,this._cbs.ontext&&this._cbs.ontext(data)},Parser.prototype.onopentagname=function(name){if(this._lowerCaseTagNames&&(name=name.toLowerCase()),this._tagname=name,!this._options.xmlMode&&name in openImpliesClose)for(var el;(el=this._stack[this._stack.length-1])in openImpliesClose[name];this.onclosetag(el));!this._options.xmlMode&&name in voidElements||this._stack.push(name),this._cbs.onopentagname&&this._cbs.onopentagname(name),this._cbs.onopentag&&(this._attribs={})},Parser.prototype.onopentagend=function(){this._updatePosition(1),this._attribs&&(this._cbs.onopentag&&this._cbs.onopentag(this._tagname,this._attribs),this._attribs=null),!this._options.xmlMode&&this._cbs.onclosetag&&this._tagname in voidElements&&this._cbs.onclosetag(this._tagname),this._tagname=""},Parser.prototype.onclosetag=function(name){if(this._updatePosition(1),this._lowerCaseTagNames&&(name=name.toLowerCase()),!this._stack.length||name in voidElements&&!this._options.xmlMode)this._options.xmlMode||"br"!==name&&"p"!==name||(this.onopentagname(name),this._closeCurrentTag());else{var pos=this._stack.lastIndexOf(name);if(pos!==-1)if(this._cbs.onclosetag)for(pos=this._stack.length-pos;pos--;)this._cbs.onclosetag(this._stack.pop());else this._stack.length=pos;else"p"!==name||this._options.xmlMode||(this.onopentagname(name),this._closeCurrentTag())}},Parser.prototype.onselfclosingtag=function(){this._options.xmlMode||this._options.recognizeSelfClosing?this._closeCurrentTag():this.onopentagend()},Parser.prototype._closeCurrentTag=function(){var name=this._tagname;this.onopentagend(),this._stack[this._stack.length-1]===name&&(this._cbs.onclosetag&&this._cbs.onclosetag(name),this._stack.pop())},Parser.prototype.onattribname=function(name){this._lowerCaseAttributeNames&&(name=name.toLowerCase()),this._attribname=name},Parser.prototype.onattribdata=function(value){this._attribvalue+=value},Parser.prototype.onattribend=function(){this._cbs.onattribute&&this._cbs.onattribute(this._attribname,this._attribvalue),this._attribs&&!Object.prototype.hasOwnProperty.call(this._attribs,this._attribname)&&(this._attribs[this._attribname]=this._attribvalue),this._attribname="",this._attribvalue=""},Parser.prototype._getInstructionName=function(value){var idx=value.search(re_nameEnd),name=idx<0?value:value.substr(0,idx);return this._lowerCaseTagNames&&(name=name.toLowerCase()),name},Parser.prototype.ondeclaration=function(value){if(this._cbs.onprocessinginstruction){var name=this._getInstructionName(value);this._cbs.onprocessinginstruction("!"+name,"!"+value)}},Parser.prototype.onprocessinginstruction=function(value){if(this._cbs.onprocessinginstruction){var name=this._getInstructionName(value);this._cbs.onprocessinginstruction("?"+name,"?"+value)}},Parser.prototype.oncomment=function(value){this._updatePosition(4),this._cbs.oncomment&&this._cbs.oncomment(value),this._cbs.oncommentend&&this._cbs.oncommentend()},Parser.prototype.oncdata=function(value){this._updatePosition(1),this._options.xmlMode||this._options.recognizeCDATA?(this._cbs.oncdatastart&&this._cbs.oncdatastart(),this._cbs.ontext&&this._cbs.ontext(value),this._cbs.oncdataend&&this._cbs.oncdataend()):this.oncomment("[CDATA["+value+"]]")},Parser.prototype.onerror=function(err){this._cbs.onerror&&this._cbs.onerror(err)},Parser.prototype.onend=function(){if(this._cbs.onclosetag)for(var i=this._stack.length;i>0;this._cbs.onclosetag(this._stack[--i]));this._cbs.onend&&this._cbs.onend()},Parser.prototype.reset=function(){this._cbs.onreset&&this._cbs.onreset(),this._tokenizer.reset(),this._tagname="",this._attribname="",this._attribs=null,this._stack=[],this._cbs.onparserinit&&this._cbs.onparserinit(this)},Parser.prototype.parseComplete=function(data){this.reset(),this.end(data)},Parser.prototype.write=function(chunk){this._tokenizer.write(chunk)},Parser.prototype.end=function(chunk){this._tokenizer.end(chunk)},Parser.prototype.pause=function(){this._tokenizer.pause()},Parser.prototype.resume=function(){this._tokenizer.resume()},Parser.prototype.parseChunk=Parser.prototype.write,Parser.prototype.done=Parser.prototype.end,module.exports=Parser},{"./Tokenizer.js":34,events:28,inherits:38}],32:[function(require,module,exports){function ProxyHandler(cbs){this._cbs=cbs||{}}module.exports=ProxyHandler;var EVENTS=require("./").EVENTS;Object.keys(EVENTS).forEach(function(name){if(0===EVENTS[name])name="on"+name,ProxyHandler.prototype[name]=function(){this._cbs[name]&&this._cbs[name]()};else if(1===EVENTS[name])name="on"+name,ProxyHandler.prototype[name]=function(a){this._cbs[name]&&this._cbs[name](a)};else{if(2!==EVENTS[name])throw Error("wrong number of arguments");name="on"+name,ProxyHandler.prototype[name]=function(a,b){this._cbs[name]&&this._cbs[name](a,b)}}})},{"./":36}],33:[function(require,module,exports){function Stream(options){Parser.call(this,new Cbs(this),options)}function Cbs(scope){this.scope=scope}module.exports=Stream;var Parser=require("./WritableStream.js");require("inherits")(Stream,Parser),Stream.prototype.readable=!0;var EVENTS=require("../").EVENTS;Object.keys(EVENTS).forEach(function(name){if(0===EVENTS[name])Cbs.prototype["on"+name]=function(){this.scope.emit(name)};else if(1===EVENTS[name])Cbs.prototype["on"+name]=function(a){this.scope.emit(name,a)};else{if(2!==EVENTS[name])throw Error("wrong number of arguments!");Cbs.prototype["on"+name]=function(a,b){this.scope.emit(name,a,b)}}})},{"../":36,"./WritableStream.js":35,inherits:38}],34:[function(require,module,exports){function whitespace(c){return" "===c||"\n"===c||"\t"===c||"\f"===c||"\r"===c}function characterState(char,SUCCESS){return function(c){c===char&&(this._state=SUCCESS)}}function ifElseState(upper,SUCCESS,FAILURE){var lower=upper.toLowerCase();return upper===lower?function(c){c===lower?this._state=SUCCESS:(this._state=FAILURE,this._index--)}:function(c){c===lower||c===upper?this._state=SUCCESS:(this._state=FAILURE,this._index--)}}function consumeSpecialNameChar(upper,NEXT_STATE){var lower=upper.toLowerCase();return function(c){c===lower||c===upper?this._state=NEXT_STATE:(this._state=IN_TAG_NAME,this._index--)}}function Tokenizer(options,cbs){this._state=TEXT,this._buffer="",this._sectionStart=0,this._index=0,this._bufferOffset=0,this._baseState=TEXT,this._special=SPECIAL_NONE,this._cbs=cbs,this._running=!0,this._ended=!1,this._xmlMode=!(!options||!options.xmlMode),this._decodeEntities=!(!options||!options.decodeEntities)}module.exports=Tokenizer;var decodeCodePoint=require("entities/lib/decode_codepoint.js"),entityMap=require("entities/maps/entities.json"),legacyMap=require("entities/maps/legacy.json"),xmlMap=require("entities/maps/xml.json"),i=0,TEXT=i++,BEFORE_TAG_NAME=i++,IN_TAG_NAME=i++,IN_SELF_CLOSING_TAG=i++,BEFORE_CLOSING_TAG_NAME=i++,IN_CLOSING_TAG_NAME=i++,AFTER_CLOSING_TAG_NAME=i++,BEFORE_ATTRIBUTE_NAME=i++,IN_ATTRIBUTE_NAME=i++,AFTER_ATTRIBUTE_NAME=i++,BEFORE_ATTRIBUTE_VALUE=i++,IN_ATTRIBUTE_VALUE_DQ=i++,IN_ATTRIBUTE_VALUE_SQ=i++,IN_ATTRIBUTE_VALUE_NQ=i++,BEFORE_DECLARATION=i++,IN_DECLARATION=i++,IN_PROCESSING_INSTRUCTION=i++,BEFORE_COMMENT=i++,IN_COMMENT=i++,AFTER_COMMENT_1=i++,AFTER_COMMENT_2=i++,BEFORE_CDATA_1=i++,BEFORE_CDATA_2=i++,BEFORE_CDATA_3=i++,BEFORE_CDATA_4=i++,BEFORE_CDATA_5=i++,BEFORE_CDATA_6=i++,IN_CDATA=i++,AFTER_CDATA_1=i++,AFTER_CDATA_2=i++,BEFORE_SPECIAL=i++,BEFORE_SPECIAL_END=i++,BEFORE_SCRIPT_1=i++,BEFORE_SCRIPT_2=i++,BEFORE_SCRIPT_3=i++,BEFORE_SCRIPT_4=i++,BEFORE_SCRIPT_5=i++,AFTER_SCRIPT_1=i++,AFTER_SCRIPT_2=i++,AFTER_SCRIPT_3=i++,AFTER_SCRIPT_4=i++,AFTER_SCRIPT_5=i++,BEFORE_STYLE_1=i++,BEFORE_STYLE_2=i++,BEFORE_STYLE_3=i++,BEFORE_STYLE_4=i++,AFTER_STYLE_1=i++,AFTER_STYLE_2=i++,AFTER_STYLE_3=i++,AFTER_STYLE_4=i++,BEFORE_ENTITY=i++,BEFORE_NUMERIC_ENTITY=i++,IN_NAMED_ENTITY=i++,IN_NUMERIC_ENTITY=i++,IN_HEX_ENTITY=i++,j=0,SPECIAL_NONE=j++,SPECIAL_SCRIPT=j++,SPECIAL_STYLE=j++;Tokenizer.prototype._stateText=function(c){"<"===c?(this._index>this._sectionStart&&this._cbs.ontext(this._getSection()),this._state=BEFORE_TAG_NAME,this._sectionStart=this._index):this._decodeEntities&&this._special===SPECIAL_NONE&&"&"===c&&(this._index>this._sectionStart&&this._cbs.ontext(this._getSection()),this._baseState=TEXT,this._state=BEFORE_ENTITY,this._sectionStart=this._index)},Tokenizer.prototype._stateBeforeTagName=function(c){"/"===c?this._state=BEFORE_CLOSING_TAG_NAME:"<"===c?(this._cbs.ontext(this._getSection()),this._sectionStart=this._index):">"===c||this._special!==SPECIAL_NONE||whitespace(c)?this._state=TEXT:"!"===c?(this._state=BEFORE_DECLARATION,this._sectionStart=this._index+1):"?"===c?(this._state=IN_PROCESSING_INSTRUCTION,this._sectionStart=this._index+1):(this._state=this._xmlMode||"s"!==c&&"S"!==c?IN_TAG_NAME:BEFORE_SPECIAL,this._sectionStart=this._index)},Tokenizer.prototype._stateInTagName=function(c){("/"===c||">"===c||whitespace(c))&&(this._emitToken("onopentagname"),this._state=BEFORE_ATTRIBUTE_NAME,this._index--)},Tokenizer.prototype._stateBeforeCloseingTagName=function(c){whitespace(c)||(">"===c?this._state=TEXT:this._special!==SPECIAL_NONE?"s"===c||"S"===c?this._state=BEFORE_SPECIAL_END:(this._state=TEXT,this._index--):(this._state=IN_CLOSING_TAG_NAME,this._sectionStart=this._index))},Tokenizer.prototype._stateInCloseingTagName=function(c){(">"===c||whitespace(c))&&(this._emitToken("onclosetag"),this._state=AFTER_CLOSING_TAG_NAME,this._index--)},Tokenizer.prototype._stateAfterCloseingTagName=function(c){">"===c&&(this._state=TEXT,this._sectionStart=this._index+1)},Tokenizer.prototype._stateBeforeAttributeName=function(c){">"===c?(this._cbs.onopentagend(),this._state=TEXT,this._sectionStart=this._index+1):"/"===c?this._state=IN_SELF_CLOSING_TAG:whitespace(c)||(this._state=IN_ATTRIBUTE_NAME,this._sectionStart=this._index)},Tokenizer.prototype._stateInSelfClosingTag=function(c){">"===c?(this._cbs.onselfclosingtag(),this._state=TEXT,this._sectionStart=this._index+1):whitespace(c)||(this._state=BEFORE_ATTRIBUTE_NAME,this._index--)},Tokenizer.prototype._stateInAttributeName=function(c){("="===c||"/"===c||">"===c||whitespace(c))&&(this._cbs.onattribname(this._getSection()),this._sectionStart=-1,this._state=AFTER_ATTRIBUTE_NAME,this._index--)},Tokenizer.prototype._stateAfterAttributeName=function(c){"="===c?this._state=BEFORE_ATTRIBUTE_VALUE:"/"===c||">"===c?(this._cbs.onattribend(),this._state=BEFORE_ATTRIBUTE_NAME,this._index--):whitespace(c)||(this._cbs.onattribend(),this._state=IN_ATTRIBUTE_NAME,this._sectionStart=this._index)},Tokenizer.prototype._stateBeforeAttributeValue=function(c){'"'===c?(this._state=IN_ATTRIBUTE_VALUE_DQ,this._sectionStart=this._index+1):"'"===c?(this._state=IN_ATTRIBUTE_VALUE_SQ,this._sectionStart=this._index+1):whitespace(c)||(this._state=IN_ATTRIBUTE_VALUE_NQ,this._sectionStart=this._index,this._index--)},Tokenizer.prototype._stateInAttributeValueDoubleQuotes=function(c){'"'===c?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=BEFORE_ATTRIBUTE_NAME):this._decodeEntities&&"&"===c&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=BEFORE_ENTITY,this._sectionStart=this._index)},Tokenizer.prototype._stateInAttributeValueSingleQuotes=function(c){"'"===c?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=BEFORE_ATTRIBUTE_NAME):this._decodeEntities&&"&"===c&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=BEFORE_ENTITY,this._sectionStart=this._index)},Tokenizer.prototype._stateInAttributeValueNoQuotes=function(c){whitespace(c)||">"===c?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=BEFORE_ATTRIBUTE_NAME,this._index--):this._decodeEntities&&"&"===c&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=BEFORE_ENTITY,this._sectionStart=this._index)},Tokenizer.prototype._stateBeforeDeclaration=function(c){this._state="["===c?BEFORE_CDATA_1:"-"===c?BEFORE_COMMENT:IN_DECLARATION},Tokenizer.prototype._stateInDeclaration=function(c){">"===c&&(this._cbs.ondeclaration(this._getSection()),this._state=TEXT,this._sectionStart=this._index+1)},Tokenizer.prototype._stateInProcessingInstruction=function(c){">"===c&&(this._cbs.onprocessinginstruction(this._getSection()),this._state=TEXT,this._sectionStart=this._index+1)},Tokenizer.prototype._stateBeforeComment=function(c){"-"===c?(this._state=IN_COMMENT,this._sectionStart=this._index+1):this._state=IN_DECLARATION},Tokenizer.prototype._stateInComment=function(c){"-"===c&&(this._state=AFTER_COMMENT_1)},Tokenizer.prototype._stateAfterComment1=function(c){"-"===c?this._state=AFTER_COMMENT_2:this._state=IN_COMMENT},Tokenizer.prototype._stateAfterComment2=function(c){">"===c?(this._cbs.oncomment(this._buffer.substring(this._sectionStart,this._index-2)),this._state=TEXT,this._sectionStart=this._index+1):"-"!==c&&(this._state=IN_COMMENT)},Tokenizer.prototype._stateBeforeCdata1=ifElseState("C",BEFORE_CDATA_2,IN_DECLARATION),Tokenizer.prototype._stateBeforeCdata2=ifElseState("D",BEFORE_CDATA_3,IN_DECLARATION),Tokenizer.prototype._stateBeforeCdata3=ifElseState("A",BEFORE_CDATA_4,IN_DECLARATION),Tokenizer.prototype._stateBeforeCdata4=ifElseState("T",BEFORE_CDATA_5,IN_DECLARATION),Tokenizer.prototype._stateBeforeCdata5=ifElseState("A",BEFORE_CDATA_6,IN_DECLARATION),Tokenizer.prototype._stateBeforeCdata6=function(c){"["===c?(this._state=IN_CDATA,this._sectionStart=this._index+1):(this._state=IN_DECLARATION,this._index--)},Tokenizer.prototype._stateInCdata=function(c){"]"===c&&(this._state=AFTER_CDATA_1)},Tokenizer.prototype._stateAfterCdata1=characterState("]",AFTER_CDATA_2),Tokenizer.prototype._stateAfterCdata2=function(c){">"===c?(this._cbs.oncdata(this._buffer.substring(this._sectionStart,this._index-2)),this._state=TEXT,this._sectionStart=this._index+1):"]"!==c&&(this._state=IN_CDATA)},Tokenizer.prototype._stateBeforeSpecial=function(c){"c"===c||"C"===c?this._state=BEFORE_SCRIPT_1:"t"===c||"T"===c?this._state=BEFORE_STYLE_1:(this._state=IN_TAG_NAME,this._index--)},Tokenizer.prototype._stateBeforeSpecialEnd=function(c){this._special!==SPECIAL_SCRIPT||"c"!==c&&"C"!==c?this._special!==SPECIAL_STYLE||"t"!==c&&"T"!==c?this._state=TEXT:this._state=AFTER_STYLE_1:this._state=AFTER_SCRIPT_1},Tokenizer.prototype._stateBeforeScript1=consumeSpecialNameChar("R",BEFORE_SCRIPT_2),Tokenizer.prototype._stateBeforeScript2=consumeSpecialNameChar("I",BEFORE_SCRIPT_3),Tokenizer.prototype._stateBeforeScript3=consumeSpecialNameChar("P",BEFORE_SCRIPT_4),Tokenizer.prototype._stateBeforeScript4=consumeSpecialNameChar("T",BEFORE_SCRIPT_5),Tokenizer.prototype._stateBeforeScript5=function(c){("/"===c||">"===c||whitespace(c))&&(this._special=SPECIAL_SCRIPT),this._state=IN_TAG_NAME,this._index--},Tokenizer.prototype._stateAfterScript1=ifElseState("R",AFTER_SCRIPT_2,TEXT),Tokenizer.prototype._stateAfterScript2=ifElseState("I",AFTER_SCRIPT_3,TEXT),Tokenizer.prototype._stateAfterScript3=ifElseState("P",AFTER_SCRIPT_4,TEXT),Tokenizer.prototype._stateAfterScript4=ifElseState("T",AFTER_SCRIPT_5,TEXT),Tokenizer.prototype._stateAfterScript5=function(c){">"===c||whitespace(c)?(this._special=SPECIAL_NONE,this._state=IN_CLOSING_TAG_NAME,this._sectionStart=this._index-6,this._index--):this._state=TEXT},Tokenizer.prototype._stateBeforeStyle1=consumeSpecialNameChar("Y",BEFORE_STYLE_2),Tokenizer.prototype._stateBeforeStyle2=consumeSpecialNameChar("L",BEFORE_STYLE_3),Tokenizer.prototype._stateBeforeStyle3=consumeSpecialNameChar("E",BEFORE_STYLE_4),Tokenizer.prototype._stateBeforeStyle4=function(c){("/"===c||">"===c||whitespace(c))&&(this._special=SPECIAL_STYLE),this._state=IN_TAG_NAME,this._index--},Tokenizer.prototype._stateAfterStyle1=ifElseState("Y",AFTER_STYLE_2,TEXT),Tokenizer.prototype._stateAfterStyle2=ifElseState("L",AFTER_STYLE_3,TEXT),Tokenizer.prototype._stateAfterStyle3=ifElseState("E",AFTER_STYLE_4,TEXT),Tokenizer.prototype._stateAfterStyle4=function(c){">"===c||whitespace(c)?(this._special=SPECIAL_NONE,this._state=IN_CLOSING_TAG_NAME,this._sectionStart=this._index-5,this._index--):this._state=TEXT},Tokenizer.prototype._stateBeforeEntity=ifElseState("#",BEFORE_NUMERIC_ENTITY,IN_NAMED_ENTITY),Tokenizer.prototype._stateBeforeNumericEntity=ifElseState("X",IN_HEX_ENTITY,IN_NUMERIC_ENTITY),Tokenizer.prototype._parseNamedEntityStrict=function(){if(this._sectionStart+1<this._index){var entity=this._buffer.substring(this._sectionStart+1,this._index),map=this._xmlMode?xmlMap:entityMap;map.hasOwnProperty(entity)&&(this._emitPartial(map[entity]),this._sectionStart=this._index+1)}},Tokenizer.prototype._parseLegacyEntity=function(){var start=this._sectionStart+1,limit=this._index-start;for(limit>6&&(limit=6);limit>=2;){var entity=this._buffer.substr(start,limit);if(legacyMap.hasOwnProperty(entity))return this._emitPartial(legacyMap[entity]),void(this._sectionStart+=limit+1);limit--}},Tokenizer.prototype._stateInNamedEntity=function(c){";"===c?(this._parseNamedEntityStrict(),this._sectionStart+1<this._index&&!this._xmlMode&&this._parseLegacyEntity(),this._state=this._baseState):(c<"a"||c>"z")&&(c<"A"||c>"Z")&&(c<"0"||c>"9")&&(this._xmlMode||this._sectionStart+1===this._index||(this._baseState!==TEXT?"="!==c&&this._parseNamedEntityStrict():this._parseLegacyEntity()),this._state=this._baseState,this._index--)},Tokenizer.prototype._decodeNumericEntity=function(offset,base){var sectionStart=this._sectionStart+offset;if(sectionStart!==this._index){var entity=this._buffer.substring(sectionStart,this._index),parsed=parseInt(entity,base);this._emitPartial(decodeCodePoint(parsed)),this._sectionStart=this._index}else this._sectionStart--;this._state=this._baseState},Tokenizer.prototype._stateInNumericEntity=function(c){";"===c?(this._decodeNumericEntity(2,10),this._sectionStart++):(c<"0"||c>"9")&&(this._xmlMode?this._state=this._baseState:this._decodeNumericEntity(2,10),this._index--)},Tokenizer.prototype._stateInHexEntity=function(c){";"===c?(this._decodeNumericEntity(3,16),this._sectionStart++):(c<"a"||c>"f")&&(c<"A"||c>"F")&&(c<"0"||c>"9")&&(this._xmlMode?this._state=this._baseState:this._decodeNumericEntity(3,16),this._index--)},Tokenizer.prototype._cleanup=function(){this._sectionStart<0?(this._buffer="",this._bufferOffset+=this._index,this._index=0):this._running&&(this._state===TEXT?(this._sectionStart!==this._index&&this._cbs.ontext(this._buffer.substr(this._sectionStart)),this._buffer="",this._bufferOffset+=this._index,this._index=0):this._sectionStart===this._index?(this._buffer="",this._bufferOffset+=this._index,this._index=0):(this._buffer=this._buffer.substr(this._sectionStart),this._index-=this._sectionStart,this._bufferOffset+=this._sectionStart),this._sectionStart=0)},Tokenizer.prototype.write=function(chunk){this._ended&&this._cbs.onerror(Error(".write() after done!")),this._buffer+=chunk,this._parse()},Tokenizer.prototype._parse=function(){for(;this._index<this._buffer.length&&this._running;){var c=this._buffer.charAt(this._index);this._state===TEXT?this._stateText(c):this._state===BEFORE_TAG_NAME?this._stateBeforeTagName(c):this._state===IN_TAG_NAME?this._stateInTagName(c):this._state===BEFORE_CLOSING_TAG_NAME?this._stateBeforeCloseingTagName(c):this._state===IN_CLOSING_TAG_NAME?this._stateInCloseingTagName(c):this._state===AFTER_CLOSING_TAG_NAME?this._stateAfterCloseingTagName(c):this._state===IN_SELF_CLOSING_TAG?this._stateInSelfClosingTag(c):this._state===BEFORE_ATTRIBUTE_NAME?this._stateBeforeAttributeName(c):this._state===IN_ATTRIBUTE_NAME?this._stateInAttributeName(c):this._state===AFTER_ATTRIBUTE_NAME?this._stateAfterAttributeName(c):this._state===BEFORE_ATTRIBUTE_VALUE?this._stateBeforeAttributeValue(c):this._state===IN_ATTRIBUTE_VALUE_DQ?this._stateInAttributeValueDoubleQuotes(c):this._state===IN_ATTRIBUTE_VALUE_SQ?this._stateInAttributeValueSingleQuotes(c):this._state===IN_ATTRIBUTE_VALUE_NQ?this._stateInAttributeValueNoQuotes(c):this._state===BEFORE_DECLARATION?this._stateBeforeDeclaration(c):this._state===IN_DECLARATION?this._stateInDeclaration(c):this._state===IN_PROCESSING_INSTRUCTION?this._stateInProcessingInstruction(c):this._state===BEFORE_COMMENT?this._stateBeforeComment(c):this._state===IN_COMMENT?this._stateInComment(c):this._state===AFTER_COMMENT_1?this._stateAfterComment1(c):this._state===AFTER_COMMENT_2?this._stateAfterComment2(c):this._state===BEFORE_CDATA_1?this._stateBeforeCdata1(c):this._state===BEFORE_CDATA_2?this._stateBeforeCdata2(c):this._state===BEFORE_CDATA_3?this._stateBeforeCdata3(c):this._state===BEFORE_CDATA_4?this._stateBeforeCdata4(c):this._state===BEFORE_CDATA_5?this._stateBeforeCdata5(c):this._state===BEFORE_CDATA_6?this._stateBeforeCdata6(c):this._state===IN_CDATA?this._stateInCdata(c):this._state===AFTER_CDATA_1?this._stateAfterCdata1(c):this._state===AFTER_CDATA_2?this._stateAfterCdata2(c):this._state===BEFORE_SPECIAL?this._stateBeforeSpecial(c):this._state===BEFORE_SPECIAL_END?this._stateBeforeSpecialEnd(c):this._state===BEFORE_SCRIPT_1?this._stateBeforeScript1(c):this._state===BEFORE_SCRIPT_2?this._stateBeforeScript2(c):this._state===BEFORE_SCRIPT_3?this._stateBeforeScript3(c):this._state===BEFORE_SCRIPT_4?this._stateBeforeScript4(c):this._state===BEFORE_SCRIPT_5?this._stateBeforeScript5(c):this._state===AFTER_SCRIPT_1?this._stateAfterScript1(c):this._state===AFTER_SCRIPT_2?this._stateAfterScript2(c):this._state===AFTER_SCRIPT_3?this._stateAfterScript3(c):this._state===AFTER_SCRIPT_4?this._stateAfterScript4(c):this._state===AFTER_SCRIPT_5?this._stateAfterScript5(c):this._state===BEFORE_STYLE_1?this._stateBeforeStyle1(c):this._state===BEFORE_STYLE_2?this._stateBeforeStyle2(c):this._state===BEFORE_STYLE_3?this._stateBeforeStyle3(c):this._state===BEFORE_STYLE_4?this._stateBeforeStyle4(c):this._state===AFTER_STYLE_1?this._stateAfterStyle1(c):this._state===AFTER_STYLE_2?this._stateAfterStyle2(c):this._state===AFTER_STYLE_3?this._stateAfterStyle3(c):this._state===AFTER_STYLE_4?this._stateAfterStyle4(c):this._state===BEFORE_ENTITY?this._stateBeforeEntity(c):this._state===BEFORE_NUMERIC_ENTITY?this._stateBeforeNumericEntity(c):this._state===IN_NAMED_ENTITY?this._stateInNamedEntity(c):this._state===IN_NUMERIC_ENTITY?this._stateInNumericEntity(c):this._state===IN_HEX_ENTITY?this._stateInHexEntity(c):this._cbs.onerror(Error("unknown _state"),this._state),this._index++}this._cleanup()},Tokenizer.prototype.pause=function(){this._running=!1},Tokenizer.prototype.resume=function(){this._running=!0,this._index<this._buffer.length&&this._parse(),this._ended&&this._finish()},Tokenizer.prototype.end=function(chunk){this._ended&&this._cbs.onerror(Error(".end() after done!")),chunk&&this.write(chunk),this._ended=!0,this._running&&this._finish()},Tokenizer.prototype._finish=function(){this._sectionStart<this._index&&this._handleTrailingData(),this._cbs.onend()},Tokenizer.prototype._handleTrailingData=function(){var data=this._buffer.substr(this._sectionStart);this._state===IN_CDATA||this._state===AFTER_CDATA_1||this._state===AFTER_CDATA_2?this._cbs.oncdata(data):this._state===IN_COMMENT||this._state===AFTER_COMMENT_1||this._state===AFTER_COMMENT_2?this._cbs.oncomment(data):this._state!==IN_NAMED_ENTITY||this._xmlMode?this._state!==IN_NUMERIC_ENTITY||this._xmlMode?this._state!==IN_HEX_ENTITY||this._xmlMode?this._state!==IN_TAG_NAME&&this._state!==BEFORE_ATTRIBUTE_NAME&&this._state!==BEFORE_ATTRIBUTE_VALUE&&this._state!==AFTER_ATTRIBUTE_NAME&&this._state!==IN_ATTRIBUTE_NAME&&this._state!==IN_ATTRIBUTE_VALUE_SQ&&this._state!==IN_ATTRIBUTE_VALUE_DQ&&this._state!==IN_ATTRIBUTE_VALUE_NQ&&this._state!==IN_CLOSING_TAG_NAME&&this._cbs.ontext(data):(this._decodeNumericEntity(3,16),this._sectionStart<this._index&&(this._state=this._baseState,this._handleTrailingData())):(this._decodeNumericEntity(2,10),this._sectionStart<this._index&&(this._state=this._baseState,this._handleTrailingData())):(this._parseLegacyEntity(),this._sectionStart<this._index&&(this._state=this._baseState,this._handleTrailingData()))},Tokenizer.prototype.reset=function(){Tokenizer.call(this,{xmlMode:this._xmlMode,decodeEntities:this._decodeEntities},this._cbs)},Tokenizer.prototype.getAbsoluteIndex=function(){return this._bufferOffset+this._index},Tokenizer.prototype._getSection=function(){return this._buffer.substring(this._sectionStart,this._index)},Tokenizer.prototype._emitToken=function(name){this._cbs[name](this._getSection()),this._sectionStart=-1},Tokenizer.prototype._emitPartial=function(value){this._baseState!==TEXT?this._cbs.onattribdata(value):this._cbs.ontext(value)}},{"entities/lib/decode_codepoint.js":22,"entities/maps/entities.json":25,"entities/maps/legacy.json":26,"entities/maps/xml.json":27}],35:[function(require,module,exports){function Stream(cbs,options){var parser=this._parser=new Parser(cbs,options),decoder=this._decoder=new StringDecoder;WritableStream.call(this,{decodeStrings:!1}),this.once("finish",function(){parser.end(decoder.end())})}module.exports=Stream;var Parser=require("./Parser.js"),WritableStream=require("stream").Writable||require("readable-stream").Writable,StringDecoder=require("string_decoder").StringDecoder,Buffer=require("buffer").Buffer;require("inherits")(Stream,WritableStream),WritableStream.prototype._write=function(chunk,encoding,cb){chunk instanceof Buffer&&(chunk=this._decoder.write(chunk)),this._parser.write(chunk),cb()}},{"./Parser.js":31,buffer:5,inherits:38,"readable-stream":3,stream:55,string_decoder:56}],36:[function(require,module,exports){function defineProp(name,value){return delete module.exports[name],module.exports[name]=value,value}var Parser=require("./Parser.js"),DomHandler=require("domhandler");module.exports={Parser:Parser,Tokenizer:require("./Tokenizer.js"),ElementType:require("domelementtype"),DomHandler:DomHandler,get FeedHandler(){return defineProp("FeedHandler",require("./FeedHandler.js"))},get Stream(){return defineProp("Stream",require("./Stream.js"))},get WritableStream(){return defineProp("WritableStream",require("./WritableStream.js"))},get ProxyHandler(){return defineProp("ProxyHandler",require("./ProxyHandler.js"))},get DomUtils(){return defineProp("DomUtils",require("domutils"))},get CollectingHandler(){return defineProp("CollectingHandler",require("./CollectingHandler.js"))},DefaultHandler:DomHandler,get RssHandler(){return defineProp("RssHandler",this.FeedHandler)},parseDOM:function(data,options){var handler=new DomHandler(options);return new Parser(handler,options).end(data),handler.dom},parseFeed:function(feed,options){var handler=new module.exports.FeedHandler(options);return new Parser(handler,options).end(feed),handler.dom},createDomStream:function(cb,options,elementCb){var handler=new DomHandler(cb,options,elementCb);return new Parser(handler,options)},EVENTS:{attribute:2,cdatastart:0,cdataend:0,text:1,processinginstruction:2,comment:1,commentend:0,closetag:1,opentag:2,opentagname:1,error:1,end:0}}},{"./CollectingHandler.js":29,"./FeedHandler.js":30,"./Parser.js":31,"./ProxyHandler.js":32,"./Stream.js":33,"./Tokenizer.js":34,"./WritableStream.js":35,domelementtype:9,domhandler:10,domutils:13}],37:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<<mLen|m,eLen+=mLen;eLen>0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],38:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],39:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],40:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr);
78
78
  }},{}],41:[function(require,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i<args.length;)args[i++]=arguments[i];return process.nextTick(function(){fn.apply(null,args)})}}!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports=nextTick:module.exports=process.nextTick}).call(this,require("_process"))},{_process:42}],42:[function(require,module,exports){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}var cachedSetTimeout,cachedClearTimeout,process=module.exports={};!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],43:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":44}],44:[function(require,module,exports){"use strict";function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args"),util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v<keys.length;v++){var method=keys[v];Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method])}},{"./_stream_readable":46,"./_stream_writable":48,"core-util-is":6,inherits:38,"process-nextick-args":41}],45:[function(require,module,exports){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform"),util=require("core-util-is");util.inherits=require("inherits"),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":47,"core-util-is":6,inherits:38}],46:[function(require,module,exports){(function(process){"use strict";function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream){Duplex=Duplex||require("./_stream_duplex"),options=options||{},this.objectMode=!!options.objectMode,stream instanceof Duplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode);var hwm=options.highWaterMark,defaultHwm=this.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:defaultHwm,this.highWaterMark=~~this.highWaterMark,this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){return Duplex=Duplex||require("./_stream_duplex"),this instanceof Readable?(this._readableState=new ReadableState(options,this),this.readable=!0,options&&"function"==typeof options.read&&(this._read=options.read),void Stream.call(this)):new Readable(options)}function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er)stream.emit("error",er);else if(null===chunk)state.reading=!1,onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||0===state.length)}function computeNewHighWaterMark(n){return n>=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark&&(debug("maybeReadMore read 0"),stream.read(0),len!==state.length);)len=state.length;state.readingMore=!1}function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,processNextTick(resume_,stream,state))}function resume_(stream,state){state.reading||(debug("resume read 0"),stream.read(0)),state.resumeScheduled=!1,state.awaitDrain=0,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){if(0===state.length)return null;var ret;return state.objectMode?ret=state.buffer.shift():!n||n>=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return n<list.head.data.length?(ret=list.head.data.slice(0,n),list.head.data=list.head.data.slice(n)):ret=n===list.head.data.length?list.shift():hasStrings?copyFromBufferString(n,list):copyFromBuffer(n,list),ret}function copyFromBufferString(n,list){var p=list.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++)f(xs[i],i)}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex,processNextTick=require("process-nextick-args"),isArray=require("isarray");Readable.ReadableState=ReadableState;var Stream,EElistenerCount=(require("events").EventEmitter,function(emitter,type){return emitter.listeners(type).length});!function(){try{Stream=require("stream")}catch(_){}finally{Stream||(Stream=require("events").EventEmitter)}}();var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims"),util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util"),debug=void 0;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function(){};var StringDecoder,BufferList=require("./internal/streams/BufferList");util.inherits(Readable,Stream),Readable.prototype.push=function(chunk,encoding){var state=this._readableState;return state.objectMode||"string"!=typeof chunk||(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=bufferShim.from(chunk,encoding),encoding="")),readableAddChunk(this,state,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",!0)},Readable.prototype.isPaused=function(){return this._readableState.flowing===!1},Readable.prototype.setEncoding=function(enc){return StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this._readableState.decoder=new StringDecoder(enc),this._readableState.encoding=enc,this};var MAX_HWM=8388608;Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n<state.highWaterMark)&&(doRead=!0,debug("length less than watermark",doRead)),state.ended||state.reading?(doRead=!1,debug("reading or ended",doRead)):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,state.reading||(n=howMuchToRead(nOrig,state)));var ret;return ret=n>0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var index=indexOf(state.pipes,dest);return index===-1?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if("data"===ev)this._readableState.flowing!==!1&&this.resume();else if("readable"===ev){var state=this._readableState;state.endEmitted||state.readableListening||(state.readableListening=state.needReadable=!0,state.emittedReadable=!1,state.reading?state.length&&emitReadable(this,state):processNextTick(nReadingNextTick,this))}return res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!0,resume(this,state)),this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Readable.prototype.wrap=function(stream){var state=this._readableState,paused=!1,self=this;stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&self.push(chunk)}self.push(null)}),stream.on("data",function(chunk){if(debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),(!state.objectMode||null!==chunk&&void 0!==chunk)&&(state.objectMode||chunk&&chunk.length)){var ret=self.push(chunk);ret||(paused=!0,stream.pause())}});for(var i in stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));var events=["error","close","destroy","pause","resume"];return forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))}),self._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},self},Readable._fromList=fromList}).call(this,require("_process"))},{"./_stream_duplex":44,"./internal/streams/BufferList":49,_process:42,buffer:5,"buffer-shims":4,"core-util-is":6,events:28,inherits:38,isarray:40,"process-nextick-args":41,"string_decoder/":56,util:3}],47:[function(require,module,exports){"use strict";function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=!1;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null,ts.writecb=null,null!==data&&void 0!==data&&stream.push(data),cb(er);var rs=stream._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&stream._read(rs.highWaterMark)}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options),this._transformState=new TransformState(this);var stream=this;this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(er,data){done(stream,er,data)}):done(stream)})}function done(stream,er,data){if(er)return stream.emit("error",er);null!==data&&void 0!==data&&stream.push(data);var ws=stream._writableState,ts=stream._transformState;if(ws.length)throw new Error("Calling transform done when ws.length != 0");if(ts.transforming)throw new Error("Calling transform done when still transforming");return stream.push(null)}module.exports=Transform;var Duplex=require("./_stream_duplex"),util=require("core-util-is");util.inherits=require("inherits"),util.inherits(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("_transform() is not implemented")},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null!==ts.writechunk&&ts.writecb&&!ts.transforming?(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)):ts.needTransform=!0}},{"./_stream_duplex":44,"core-util-is":6,inherits:38}],48:[function(require,module,exports){(function(process){"use strict";function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk,this.encoding=encoding,this.callback=cb,this.next=null}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex"),options=options||{},this.objectMode=!!options.objectMode,stream instanceof Duplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode);var hwm=options.highWaterMark,defaultHwm=this.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:defaultHwm,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var noDecode=options.decodeStrings===!1;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){return Duplex=Duplex||require("./_stream_duplex"),realHasInstance.call(Writable,this)||this instanceof Duplex?(this._writableState=new WritableState(options,this),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev)),void Stream.call(this)):new Writable(options)}function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er),processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=!0,er=!1;return null===chunk?er=new TypeError("May not write null values to stream"):Buffer.isBuffer(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er&&(stream.emit("error",er),processNextTick(cb,er),valid=!1),valid}function decodeChunk(state,chunk,encoding){return state.objectMode||state.decodeStrings===!1||"string"!=typeof chunk||(chunk=bufferShim.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding),Buffer.isBuffer(chunk)&&(encoding="buffer");var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest=new WriteReq(chunk,encoding,cb),last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?processNextTick(cb,er):cb(er),stream._writableState.errorEmitted=!0,stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state);finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?asyncWrite(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=new Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0;entry;)buffer[count]=entry,entry=entry.next,count+=1;doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state)}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequestCount=0,state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function prefinish(stream,state){state.prefinished||(state.prefinished=!0,stream.emit("prefinish"))}function finishMaybe(stream,state){var need=needFinish(state);return need&&(0===state.pendingcb?(prefinish(stream,state),state.finished=!0,stream.emit("finish")):prefinish(stream,state)),need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?processNextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(err){var entry=_this.entry;for(_this.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree?state.corkedRequestsFree.next=_this:state.corkedRequestsFree=_this}}module.exports=Writable;var Duplex,processNextTick=require("process-nextick-args"),asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream,internalUtil={deprecate:require("util-deprecate")};!function(){try{Stream=require("stream")}catch(_){}finally{Stream||(Stream=require("events").EventEmitter)}}();var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(this,require("_process"))},{"./_stream_duplex":44,_process:42,buffer:5,"buffer-shims":4,"core-util-is":6,events:28,inherits:38,"process-nextick-args":41,"util-deprecate":57}],49:[function(require,module,exports){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var bufferShim=(require("buffer").Buffer,require("buffer-shims"));module.exports=BufferList,BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},{buffer:5,"buffer-shims":4}],50:[function(require,module,exports){
79
- module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":45}],51:[function(require,module,exports){(function(process){var Stream=function(){try{return require("stream")}catch(_){}}();exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=Stream||exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),!process.browser&&"disable"===process.env.READABLE_STREAM&&Stream&&(module.exports=Stream)}).call(this,require("_process"))},{"./lib/_stream_duplex.js":44,"./lib/_stream_passthrough.js":45,"./lib/_stream_readable.js":46,"./lib/_stream_transform.js":47,"./lib/_stream_writable.js":48,_process:42}],52:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":47}],53:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":48}],54:[function(require,module,exports){module.exports=function(string){return string.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")}},{}],55:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter,inherits=require("inherits");inherits(Stream,EE),Stream.Readable=require("readable-stream/readable.js"),Stream.Writable=require("readable-stream/writable.js"),Stream.Duplex=require("readable-stream/duplex.js"),Stream.Transform=require("readable-stream/transform.js"),Stream.PassThrough=require("readable-stream/passthrough.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&options.end===!1||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:28,inherits:38,"readable-stream/duplex.js":43,"readable-stream/passthrough.js":50,"readable-stream/readable.js":51,"readable-stream/transform.js":52,"readable-stream/writable.js":53}],56:[function(require,module,exports){function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding))throw new Error("Unknown encoding: "+encoding)}function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2,this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3,this.charLength=this.charReceived?3:0}var Buffer=require("buffer").Buffer,isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},StringDecoder=exports.StringDecoder=function(encoding){switch(this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,""),assertEncoding(encoding),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=base64DetectIncompleteChar;break;default:return void(this.write=passThroughWrite)}this.charBuffer=new Buffer(6),this.charReceived=0,this.charLength=0};StringDecoder.prototype.write=function(buffer){for(var charStr="";this.charLength;){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived<this.charLength)return"";buffer=buffer.slice(available,buffer.length),charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(!(charCode>=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:5}],57:[function(require,module,exports){(function(global){function deprecate(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],58:[function(require,module,exports){function extend(){for(var target={},i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source)hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty},{}]},{},[1])(1)}),function(global){function Mirador(config){return this instanceof Mirador?(this.eventEmitter=new Mirador.EventEmitter,this.saveController=new Mirador.SaveController(jQuery.extend(!0,{},config,{eventEmitter:this.eventEmitter})),this.viewer=new Mirador.Viewer({state:this.saveController,eventEmitter:this.eventEmitter}),this):new Mirador(config)}global.Mirador=global.Mirador||Mirador}(window),function($){$.DEFAULT_SETTINGS={workspaceType:"singleObject",saveSession:!1,workspaces:{singleObject:{label:"Single Object",addNew:!1,move:!1,iconClass:"image"},compare:{label:"Compare",iconClass:"columns"},bookReading:{defaultWindowOptions:{},label:"Book Reading",addNew:!0,move:!1,iconClass:"book"}},manifests:[],data:[],layout:"1x1",openManifestsPage:!1,preserveManifestOrder:!1,windowSettings:{availableViews:["ThumbnailsView","ImageView","ScrollView","BookView"],viewType:"ImageView",bottomPanel:!0,bottomPanelVisible:!0,sidePanel:!0,sidePanelOptions:{toc:!0,annotations:!1},sidePanelVisible:!0,overlay:!0,canvasControls:{annotations:{annotationLayer:!0,annotationCreation:!0,annotationState:"off",annotationRefresh:!1},imageManipulation:{manipulationLayer:!0,controls:{rotate:!0,brightness:!0,contrast:!0,saturate:!0,grayscale:!0,invert:!0}}},fullScreen:!0,displayLayout:!0,layoutOptions:{newObject:!0,close:!0,slotRight:!0,slotLeft:!0,slotAbove:!0,slotBelow:!0}},windowObjects:[],autoHideControls:!0,fadeDuration:400,timeoutDuration:3e3,availableAnnotationModes:[],availableAnnotationDrawingTools:["Rectangle","Ellipse","Freehand","Polygon","Pin"],availableAnnotationStylePickers:["StrokeColor","FillColor","StrokeType"],drawingToolsSettings:{doubleClickReactionTime:300,strokeColor:"deepSkyBlue",fillColor:"deepSkyBlue",fillColorAlpha:0,shapeHandleSize:10,fixedShapeSize:10,newlyCreatedShapeStrokeWidthFactor:5,hoverColor:"yellow"},availableExternalCommentsPanel:!1,shapeHandleSize:10,availableCanvasTools:[],mainMenuSettings:{show:!0,buttons:{bookmark:!1,layout:!0,options:!1,fullScreenViewer:!0}},workspacePanelSettings:{maxRows:5,maxColumns:5,preserveWindows:!0},showAddFromURLBox:!0,buildPath:"build/mirador/",i18nPath:"locales/",imagesPath:"images/",annotationEndpoint:{},annotationBodyEditor:{module:"TinyMCEAnnotationBodyEditor",options:{config:{plugins:"image link media directionality",toolbar:"bold italic | bullist numlist | link image media | removeformat | ltr rtl"}}},jsonStorageEndpoint:{name:"JSONBlob API Endpoint",module:"JSONBlobAPI",options:{ssl:!0,port:"443",host:"jsonblob.com"}},sharingEndpoint:{url:"",storeId:123,APIKey:"23983hf98j3f9283jf2983fj"},lockController:{lockProfile:"lazyZoom",notifyMaxMin:!0}}}(Mirador),function($){$.Viewer=function(options){jQuery.extend(!0,this,{id:null,data:null,element:null,canvas:null,workspaceType:null,layout:null,workspace:null,mainMenu:null,workspaceAutoSave:null,windowSize:{},resizeRatio:{},currentWorkspaceVisible:!0,state:null,eventEmitter:null,overlayStates:{workspacePanelVisible:!1,manifestsPanelVisible:!1,optionsPanelVisible:!1,bookmarkPanelVisible:!1},manifests:[]},options),this.id=this.state.getStateProperty("id"),this.data=this.state.getStateProperty("data"),this.element=this.element||jQuery("#"+this.id),options.availableAnnotationDrawingTools&&options.availableAnnotationDrawingTools.length>0&&(this.availableAnnotationDrawingTools=options.availableAnnotationDrawingTools),this.data&&this.init()},$.Viewer.prototype={init:function(){var _this=this;i18next.use(i18nextXHRBackend).use(i18nextBrowserLanguageDetector).init({fallbackLng:"en",load:"unspecific",debug:!1,backend:{loadPath:_this.state.getStateProperty("buildPath")+_this.state.getStateProperty("i18nPath")+"{{lng}}/{{ns}}.json"}},_this.setupViewer.bind(_this))},setupViewer:function(){var _this=this,backgroundImage=_this.state.getStateProperty("buildPath")+_this.state.getStateProperty("imagesPath")+"debut_dark.png";this.element.css("background-color","#333").css("background-image","url("+backgroundImage+")").css("background-position","left top").css("background-repeat","repeat"),Handlebars.registerHelper("t",function(i18n_key){var result=i18next.t(i18n_key);return new Handlebars.SafeString(result)});var showMainMenu=!1;jQuery.each(this.state.getStateProperty("mainMenuSettings").buttons,function(key,value){value&&(showMainMenu=!0)}),this.state.getStateProperty("mainMenuSettings").userButtons&&this.state.getStateProperty("mainMenuSettings").userButtons.length>0&&(showMainMenu=!0),this.state.getStateProperty("mainMenuSettings").userLogo&&!jQuery.isEmptyObject(this.state.getStateProperty("mainMenuSettings").userLogo)&&(showMainMenu=!0),this.state.getStateProperty("mainMenuSettings").show===!1&&(showMainMenu=!1),showMainMenu&&(this.mainMenu=new $.MainMenu({appendTo:this.element,state:this.state,eventEmitter:this.eventEmitter})),this.canvas=jQuery("<div/>").addClass("mirador-viewer").appendTo(this.element),showMainMenu||this.canvas.css("top","0px"),this.layout="string"!=typeof this.state.getStateProperty("layout")?JSON.stringify(this.state.getStateProperty("layout")):this.state.getStateProperty("layout"),this.workspace=new $.Workspace({layoutDescription:"{"===this.layout.charAt(0)?JSON.parse(this.layout):$.layoutDescriptionFromGridString(this.layout),appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter}),this.workspacePanel=new $.WorkspacePanel({appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter}),this.manifestsPanel=new $.ManifestsPanel({appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter}),showMainMenu&&this.state.getStateProperty("mainMenuSettings").buttons.bookmark&&(this.bookmarkPanel=new $.BookmarkPanel({appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter})),this.set("currentWorkspaceVisible",!0),this.bindEvents(),this.listenForActions(),this.getManifestsData(),0===this.state.getStateProperty("windowObjects").length&&this.state.getStateProperty("openManifestsPage")&&this.workspace.slots[0].addItem()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("manifestReceived",function(event,newManifest){if(_this.state.getStateProperty("windowObjects")){var check=jQuery.grep(_this.state.getStateProperty("windowObjects"),function(object,index){return object.loadedManifest===newManifest.uri});jQuery.each(check,function(index,config){_this.loadManifestFromConfig(config)})}}),_this.eventEmitter.subscribe("TOGGLE_WORKSPACE_PANEL",function(event){_this.toggleWorkspacePanel()}),_this.eventEmitter.subscribe("TOGGLE_BOOKMARK_PANEL",function(event){_this.toggleBookmarkPanel()}),_this.eventEmitter.subscribe("TOGGLE_FULLSCREEN",function(event){$.fullscreenElement()?($.exitFullscreen(),_this.eventEmitter.publish("ENABLE_WINDOW_FULLSCREEN")):($.enterFullscreen(_this.element[0]),_this.eventEmitter.publish("DISABLE_WINDOW_FULLSCREEN"))}),jQuery(document).on("webkitfullscreenchange mozfullscreenchange fullscreenchange",function(){_this.eventEmitter.publish("MAINMENU_FULLSCREEN_BUTTON"),$.fullscreenElement()||_this.eventEmitter.publish("ENABLE_WINDOW_FULLSCREEN")}),_this.eventEmitter.subscribe("TOGGLE_LOAD_WINDOW",function(event){_this.toggleLoadWindow()}),_this.eventEmitter.subscribe("ADD_MANIFEST_FROM_URL",function(event,url,location){_this.addManifestFromUrl(url,location)}),_this.eventEmitter.subscribe("TOGGLE_OVERLAYS_FALSE",function(event){jQuery.each(_this.overlayStates,function(oState,value){_this.set(oState,!1,{parent:"overlayStates"})})})},bindEvents:function(){},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){var _this=this;options?this[options.parent][prop]=value:this[prop]=value,_this.eventEmitter.publish(prop+".set",value)},toggleOverlay:function(state){var _this=this;jQuery.each(this.overlayStates,function(oState,value){state!==oState&&_this.set(oState,!1,{parent:"overlayStates"})});var currentState=this.get(state,"overlayStates");this.set(state,!currentState,{parent:"overlayStates"})},toggleLoadWindow:function(){this.toggleOverlay("manifestsPanelVisible")},toggleWorkspacePanel:function(){this.toggleOverlay("workspacePanelVisible")},toggleBookmarkPanel:function(){this.toggleOverlay("bookmarkPanelVisible")},getManifestsData:function(){var _this=this;_this.data.forEach(function(manifest){if(manifest.hasOwnProperty("manifestContent")){var content=manifest.manifestContent;_this.addManifestFromUrl(content["@id"],manifest.location?manifest.location:"",content)}else if(manifest.hasOwnProperty("manifestUri")){var url=manifest.manifestUri;_this.addManifestFromUrl(url,manifest.location?manifest.location:"",null)}else manifest.hasOwnProperty("collectionUri")&&jQuery.getJSON(manifest.collectionUri).done(function(data,status,jqXHR){data.hasOwnProperty("manifests")?jQuery.each(data.manifests,function(ci,mfst){_this.addManifestFromUrl(mfst["@id"],"",null)}):data.hasOwnProperty("members")&&jQuery.each(data.members,function(ci,mfst){_this.addManifestFromUrl(mfst["@id"],"",null)})}).fail(function(jqXHR,status,error){console.log(jqXHR,status,error)})})},hasWidgets:function(collection){return"undefined"!=typeof collection.widgets&&collection.widgets&&!jQuery.isEmptyObject(collection.widgets)&&collection.widgets.length>0},addManifestFromUrl:function(url,location,content){var manifest,_this=this;_this.state.getStateProperty("manifests")[url]||(manifest=new $.Manifest(url,location,content),_this.eventEmitter.publish("manifestQueued",manifest,location),manifest.request.done(function(){_this.eventEmitter.publish("manifestReceived",manifest)}))},loadManifestFromConfig:function(options){var _this=this,windowConfig=jQuery.extend(!0,{},options);_this.eventEmitter.publish("DELETE_FROM_CONFIG",options),_this.eventEmitter.publish("ADD_WINDOW",windowConfig)}}}(Mirador),function($){$.Workspace=function(options){jQuery.extend(!0,this,{workspaceSlotCls:"slot",focusedSlot:null,slots:[],windows:[],appendTo:null,layoutDescription:null,state:null,eventEmitter:null},options);var uid=$.genUUID();this.element=this.element||jQuery('<div class="workspace-container" id="workspace-'+uid+'">'),this.init()},$.Workspace.prototype={init:function(){this.element.appendTo(this.appendTo),this.calculateLayout(),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("resizeMirador",function(event){_this.calculateLayout()}),_this.eventEmitter.subscribe("manifestQueued",function(event,manifestPromise){var targetSlot;if(_this.state.getStateProperty("windowObjects")){_this.state.getStateProperty("windowObjects").forEach(function(windowConfig,index){targetSlot=windowConfig.slotAddress?_this.getSlotFromAddress(windowConfig.slotAddress):_this.focusedSlot||_this.slots.filter(function(slot){return!!slot.hasOwnProperty("window")})[0]})}}),_this.eventEmitter.subscribe("REMOVE_WINDOW",function(event,windowId){_this.removeWindow(windowId)}),_this.eventEmitter.subscribe("REMOVE_NODE",function(event,node){_this.removeNode(node)}),_this.eventEmitter.subscribe("ADD_SLOT_ITEM",function(event,slot){_this.addItem(slot)}),_this.eventEmitter.subscribe("ADD_WINDOW",function(event,windowConfig){_this.addWindow(windowConfig)}),_this.eventEmitter.subscribe("SPLIT_RIGHT",function(event,slot){_this.splitRight(slot)}),_this.eventEmitter.subscribe("SPLIT_LEFT",function(event,slot){_this.splitLeft(slot)}),_this.eventEmitter.subscribe("SPLIT_DOWN",function(event,slot){_this.splitDown(slot)}),_this.eventEmitter.subscribe("SPLIT_UP",function(event,slot){_this.splitUp(slot)}),_this.eventEmitter.subscribe("RESET_WORKSPACE_LAYOUT",function(event,options){_this.resetLayout(options.layoutDescription)})},bindEvents:function(){var _this=this;d3.select(window).on("resize",function(event){_this.calculateLayout()})},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){var _this=this;options?this[options.parent][prop]=value:this[prop]=value,_this.eventEmitter.publish(prop+".set",value)},calculateLayout:function(resetting){function cell(){this.style("left",function(d){return d.x+"px"}).style("top",function(d){return d.y+"px"}).style("width",function(d){return Math.max(0,d.dx)+"px"}).style("height",function(d){return Math.max(0,d.dy)+"px"})}var layout,_this=this;_this.layout=layout=new Isfahan({containerId:_this.element.attr("id"),layoutDescription:_this.layoutDescription,configuration:null,padding:3});var data=layout.filter(function(d){return!d.children}),divs=d3.select("#"+_this.element.attr("id")).selectAll(".layout-slot").data(data,function(d){return d.id});divs.call(cell).each(function(d){_this.slots.forEach(function(slot){slot.slotID===d.id&&(slot.layoutAddress=d.address)})}),divs.enter().append("div").attr("class","layout-slot").attr("data-layout-slot-id",function(d){return d.id}).call(cell).each(function(d){var appendTo=_this.element.children("div").filter('[data-layout-slot-id="'+d.id+'"]')[0];_this.slots.push(new $.Slot({slotID:d.id,layoutAddress:d.address,focused:!0,appendTo:appendTo,state:_this.state,eventEmitter:_this.eventEmitter}))}),divs.exit().remove("div").each(function(d){var slotMap=_this.slots.reduce(function(map,temp_slot){return d.id===temp_slot.slotID&&(map[d.id]=temp_slot),map},{}),slot=slotMap[d.id];slot&&slot.window&&!resetting&&_this.eventEmitter.publish("REMOVE_WINDOW",slot.window.id),slot.window=null,_this.slots.splice(_this.slots.indexOf(slot),1)});var root=jQuery.grep(_this.layout,function(node){return!node.parent})[0];_this.eventEmitter.publish("layoutChanged",root),_this.eventEmitter.publish("slotsUpdated",{slots:_this.slots}),_this.slots.length<=1?_this.eventEmitter.publish("HIDE_REMOVE_SLOT"):_this.eventEmitter.publish("SHOW_REMOVE_SLOT")},split:function(targetSlot,direction){function addSibling(node,indexDifference){if(nodeIsNotRoot){var siblingIndex=nodeIndex+indexDifference,newSibling=_this.newNode(node.type,node);return node.parent.children.splice(siblingIndex,0,newSibling),_this.layout.push(newSibling),newSibling}node.type="row"===node.type?"column":"row",mutateAndAdd(node,indexDifference)}function mutateAndAdd(node,indexDifference){var newParent=_this.newNode(node.type,node.parent);node.type="row"===node.type?"column":"row",newSibling=_this.newNode(node.type,newParent),newParent.children=[],newParent.children.push(node),newParent.children.splice(indexDifference,0,newSibling),nodeIsNotRoot&&(newParent.parent=node.parent,newParent.parent.children[nodeIndex]=newParent),node.parent=newParent,_this.layout.push(newParent,newSibling)}var _this=this,node=jQuery.grep(_this.layout,function(node){return node.id===targetSlot.slotID})[0];nodeIndex=node.parent?node.parent.children.indexOf(node):0,nodeIsNotRoot=node.parent,"column"===node.type?"r"===direction||"l"===direction?(indexDifference="r"===direction?1:0,addSibling(node,indexDifference)):(indexDifference="d"===direction?1:0,mutateAndAdd(node,indexDifference)):"r"===direction||"l"===direction?(indexDifference="r"===direction?1:0,mutateAndAdd(node,indexDifference)):(indexDifference="d"===direction?1:0,addSibling(node,indexDifference));var root=jQuery.grep(_this.layout,function(node){return!node.parent})[0];_this.layoutDescription=root,_this.calculateLayout()},splitRight:function(targetSlot){var _this=this;_this.split(targetSlot,"r")},splitLeft:function(targetSlot){var _this=this;_this.split(targetSlot,"l")},splitUp:function(targetSlot){var _this=this;_this.split(targetSlot,"u")},splitDown:function(targetSlot){var _this=this;_this.split(targetSlot,"d")},removeNode:function(targetSlot){var remainingNode,_this=this,node=jQuery.grep(_this.layout,function(node){return node.id===targetSlot.slotID})[0],nodeIndex=node.parent.children.indexOf(node),root=jQuery.grep(_this.layout,function(node){return!node.parent})[0];2===node.parent.children.length?(node.parent.children.splice(nodeIndex,1),remainingNode=node.parent.children[0],remainingNode.parent.id=remainingNode.id,delete node.parent):1===node.parent.children.length||node.parent.children.splice(nodeIndex,1),_this.layoutDescription=root,_this.calculateLayout(),_this.eventEmitter.publish("slotRemoved",targetSlot)},newNode:function(type,parent){return"undefined"==typeof parent?{type:type,id:$.genUUID()}:{type:type,id:$.genUUID(),parent:parent}},getSlotFromAddress:function(address){var _this=this;return _this.slots.filter(function(slot){return slot.layoutAddress===address})[0]},resetLayout:function(layoutDescription){this.layoutDescription=layoutDescription,this.calculateLayout(!0),this.placeWindows()},placeWindows:function(){var _this=this;_this.windows.length>_this.slots.length&&_this.windows.slice(0,_this.windows.length-_this.slots.length).forEach(function(removedWindow){_this.eventEmitter.publish("REMOVE_WINDOW",removedWindow.id)}),_this.windows.forEach(function(window){var slot=_this.getAvailableSlot();slot.window=window,window.update({id:window.id,slotAddress:slot.layoutAddress,state:_this.state,appendTo:slot.element,canvasID:window.canvasID,viewType:window.viewType})})},getAvailableSlot:function(){return this.slots.filter(function(slot){return!slot.window})[0]},clearSlot:function(slotId){this.slots[slotId].windowElement&&this.slots[slotId].windowElement.remove(),this.slots[slotId].window=null},addItem:function(slot){var _this=this;this.focusedSlot=slot,_this.eventEmitter.publish("TOGGLE_LOAD_WINDOW")},addWindow:function(windowConfig){var newWindow,targetSlot,_this=this;_this.eventEmitter.publish("TOGGLE_OVERLAYS_FALSE"),targetSlot=windowConfig.slotAddress?_this.getSlotFromAddress(windowConfig.slotAddress):_this.focusedSlot||_this.getAvailableSlot(),windowConfig.appendTo=targetSlot.element,windowConfig.state=_this.state,windowConfig.eventEmitter=_this.eventEmitter,targetSlot.window&&_this.eventEmitter.publish("REMOVE_WINDOW",targetSlot.window.id),windowConfig.slotAddress=targetSlot.layoutAddress,windowConfig.id=windowConfig.id||$.genUUID(),_this.eventEmitter.publish("windowSlotAdded",{id:windowConfig.id,slotAddress:windowConfig.slotAddress});var mergedConfig=jQuery.extend(!0,{},_this.state.getStateProperty("windowSettings"),windowConfig);mergedConfig.hasOwnProperty("loadedManifest")&&(mergedConfig.manifest=_this.state.getStateProperty("manifests")[mergedConfig.loadedManifest],delete mergedConfig.loadedManifest),mergedConfig.hasOwnProperty("bottomPanel")&&(mergedConfig.bottomPanelAvailable=mergedConfig.bottomPanel,delete mergedConfig.bottomPanel),mergedConfig.hasOwnProperty("sidePanel")&&(mergedConfig.sidePanelAvailable=mergedConfig.sidePanel,delete mergedConfig.sidePanel),mergedConfig.hasOwnProperty("overlay")&&(mergedConfig.overlayAvailable=mergedConfig.overlay,delete mergedConfig.overlay),newWindow=new $.Window(mergedConfig),_this.windows.push(newWindow),targetSlot.window=newWindow,_this.eventEmitter.publish("windowAdded",{id:windowConfig.id,slotAddress:windowConfig.slotAddress})},removeWindow:function(windowId){var _this=this;_this.windows=_this.windows.filter(function(window){return window.id!==windowId}),_this.eventEmitter.publish("windowRemoved",windowId)}}}(Mirador),function($){$.BookmarkPanel=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,state:null,eventEmitter:null},options),this.init()},$.BookmarkPanel.prototype={init:function(){this.element=jQuery(this.template()).appendTo(this.appendTo);var jsonStorageEndpoint=this.state.getStateProperty("jsonStorageEndpoint"),saveModule=jsonStorageEndpoint.module,saveOptions=jsonStorageEndpoint.options;this.storageModule=new $[saveModule](saveOptions),this.bindEvents(),this.listenForActions()},bindEvents:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("bookmarkPanelVisible.set",function(_,stateValue){_this.onPanelVisible(_,stateValue)}),_this.eventEmitter.subscribe("saveControllerConfigUpdated",function(){_this.onConfigUpdated()})},onPanelVisible:function(_,stateValue){var _this=this;return stateValue?void _this.show():void _this.hide()},onConfigUpdated:function(){var _this=this;_this.storageModule.save(_this.state.currentConfig).then(function(blobId){var bookmarkURL=window.location.href.replace(window.location.hash,"")+"?json="+blobId;_this.element.find("#share-url").val(bookmarkURL).focus().select()})},hide:function(){jQuery(this.element).hide({effect:"slide",direction:"up",duration:300,easing:"swing"})},show:function(){jQuery(this.element).show({effect:"slide",direction:"up",duration:300,easing:"swing"})},template:Handlebars.compile(['<div id="bookmark-panel">','<h3>{{t "bookmarkTitle"}}</h3>',"<span>",'{{t "url"}}: <input id="share-url" type="text"></input>','<a href="javascript:;" class="mirador-btn mirador-icon-copy" data-clipboard-target="share-url"><i class="fa fa-files-o fa-lg"></i></a>',"</span>","</div>"].join(""))}}(Mirador),function($){$.MainMenu=function(options){jQuery.extend(!0,this,{element:null,mainMenuHeight:null,mainMenuWidth:null,windowOptionsMenu:null,loadWindow:null,clearLocalStorage:"",viewerCls:"mirador-viewer",mainMenuBarCls:"mirador-main-menu-bar",mainMenuCls:"mirador-main-menu",windowOptionsMenuCls:"mirador-window-options-menu",clearLocalStorageCls:"clear-local-storage",clearLocalStorageDialogCls:"mirador-main-menu-clear-local-storage",collectionsListingCls:"mirador-listing-collections",state:null,eventEmitter:null},options),this.element=this.element||jQuery("<div/>"),this.init()},$.MainMenu.prototype={init:function(){this.element.addClass(this.mainMenuBarCls).appendTo(this.appendTo),this.element.append(this.template({mainMenuCls:this.mainMenuCls,showBookmark:this.state.getStateProperty("mainMenuSettings").buttons.bookmark,showLayout:this.state.getStateProperty("mainMenuSettings").buttons.layout,showOptions:this.state.getStateProperty("mainMenuSettings").buttons.options,showFullScreenViewer:this.state.getStateProperty("mainMenuSettings").buttons.fullScreenViewer,userButtons:this.state.getStateProperty("mainMenuSettings").userButtons,userLogo:this.state.getStateProperty("mainMenuSettings").userLogo})),this.element.find(".mainmenu-button").each(function(){jQuery(this).qtip({content:{text:jQuery(this).attr("title")},position:{my:"top center",at:"bottom center"},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}})}),this.listenForActions(),this.bindEvents()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("MAINMENU_FULLSCREEN_BUTTON",function(event){var fullScreenButton=_this.element.find(".fullscreen-viewer span");fullScreenButton.hasClass("fa-expand")?fullScreenButton.removeClass("fa-expand").addClass("fa-compress"):fullScreenButton.removeClass("fa-compress").addClass("fa-expand")})},bindEvents:function(){var _this=this;this.element.find(".change-layout").on("click",function(){_this.eventEmitter.publish("TOGGLE_WORKSPACE_PANEL"),_this.element.find(".bookmark-workspace").removeClass("active"),jQuery(this).hasClass("active")?jQuery(this).removeClass("active"):jQuery(this).addClass("active")}),this.element.find(".bookmark-workspace").on("click",function(){_this.eventEmitter.publish("TOGGLE_BOOKMARK_PANEL"),_this.element.find(".change-layout").removeClass("active"),jQuery(this).hasClass("active")?jQuery(this).removeClass("active"):jQuery(this).addClass("active")}),this.element.find(".window-options").on("click",function(){}),this.element.find(".fullscreen-viewer").on("click",function(){_this.eventEmitter.publish("TOGGLE_FULLSCREEN")})},template:Handlebars.compile(["{{#if userLogo}}",'<ul class="user-logo {{mainMenuCls}}">',"{{userlogo userLogo}}","</ul>","{{/if}}",'<ul class="{{mainMenuCls}}">',"{{#if showBookmark}}","<li>",'<a href="javascript:;" class="bookmark-workspace mainmenu-button" title="{{t "bookmarkTooltip"}}" aria-label="{{t "bookmarkTooltip"}}">','<span class="fa fa-bookmark fa-lg fa-fw"></span> {{t "bookmark"}}',"</a>","</li>","{{/if}}","{{#if showLayout}}","<li>",'<a href="javascript:;" class="change-layout mainmenu-button" title="{{t "changeLayoutTooltip"}}" aria-label="{{t "changeLayoutTooltip"}}">','<span class="fa fa-th-large fa-lg fa-fw"></span> {{t "changeLayout"}}',"</a>","</li>","{{/if}}","{{#if showFullScreenViewer}}","<li>",'<a href="javascript:;" class="fullscreen-viewer mainmenu-button" title="{{t "fullScreenTooltip"}}" aria-label="{{t "fullScreenTooltip"}}">','<span class="fa fa-expand fa-lg fa-fw"></span> {{t "fullScreen"}}',"</a>","</li>","{{/if}}","</ul>","{{#if userButtons}}","{{userbtns userButtons}}","{{/if}}"].join(""))};var processUserButtons=function(btns){for(var output=[],btns_len=btns.length,i=0;i<btns_len;i++)output.push(processUserBtn(btns[i]));return output},processUserBtn=function(btn){var $sub_ul,$li=jQuery("<li>"),$a=jQuery("<a>");try{if(btn.li_attributes&&$li.attr(btn.li_attributes),!btn.label)throw"userButtons must have labels";return $a.text(btn.label),btn.iconClass&&$a.prepend('<span class="'+btn.iconClass+'"></span> '),btn.attributes&&$a.attr(btn.attributes),$li.append($a),btn.sublist&&($sub_ul=jQuery("<ul>"),btn.ul_attributes&&$sub_ul.attr(btn.ul_attributes),$sub_ul.append(processUserButtons(btn.sublist)),
80
- $li.append($sub_ul)),$li}catch(err){return console&&console.log&&console.log(err),jQuery()}};Handlebars.registerHelper("userbtns",function(userButtons){return new Handlebars.SafeString(jQuery('<ul class="user-buttons '+this.mainMenuCls+'"></ul>').append(processUserButtons(userButtons)).get(0).outerHTML)}),Handlebars.registerHelper("userlogo",function(userLogo){return new Handlebars.SafeString(processUserBtn(userLogo).get(0).outerHTML)})}(Mirador),function($){$.ManifestListItem=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,loadStatus:null,thumbHeight:80,urlHeight:150,resultsWidth:0,maxPreviewImagesWidth:0,repoWidth:80,metadataWidth:450,margin:15,remainingWidth:20,imagesTotalWidth:0,tplData:null,allImages:[],remaining:0,state:null,eventEmitter:null},options),this.init()},$.ManifestListItem.prototype={init:function(){var _this=this;if(this.maxPreviewImagesWidth=this.resultsWidth-(this.repoWidth+this.margin+this.metadataWidth+this.margin+this.remainingWidth),this.maxPreviewImagesWidth=.95*this.maxPreviewImagesWidth,Handlebars.registerHelper("pluralize",function(count,singular,plural){return 1===count?singular:plural}),this.fetchTplData(this.manifestId),_this.state.getStateProperty("preserveManifestOrder"))if(0===this.appendTo.children().length)this.element=jQuery(this.template(this.tplData)).prependTo(this.appendTo).hide().fadeIn("slow");else{var liList=_this.appendTo.find("li");jQuery.each(liList,function(index,item){var prev=parseFloat(jQuery(item).attr("data-index-number")),next=parseFloat(jQuery(liList[index+1]).attr("data-index-number")),current=_this.tplData.index;return current<=prev&&(next>current||isNaN(next))?(_this.element=jQuery(_this.template(_this.tplData)).insertBefore(jQuery(item)).hide().fadeIn("slow"),!1):current>prev&&(current<next||isNaN(next))?(_this.element=jQuery(_this.template(_this.tplData)).insertAfter(jQuery(item)).hide().fadeIn("slow"),!1):void 0})}else this.element=jQuery(this.template(this.tplData)).prependTo(this.appendTo).hide().fadeIn("slow");this.bindEvents(),this.listenForActions()},fetchTplData:function(){var _this=this,location=_this.manifest.location,manifest=_this.manifest.jsonLd;this.tplData={label:$.JsonLd.getTextValue(manifest.label),repository:location,canvasCount:manifest.sequences[0].canvases.length,images:[],index:_this.state.getManifestIndex(manifest["@id"])},this.tplData.repoImage=function(){_this.tplData.repository;if(manifest.logo){if("string"==typeof manifest.logo)return manifest.logo;if("undefined"!=typeof manifest.logo["@id"])return manifest.logo["@id"]}return""}();for(var i=0;i<manifest.sequences[0].canvases.length;i++){var canvas=manifest.sequences[0].canvases[i];if(0!==canvas.width){var aspectRatio=canvas.height/canvas.width,width=_this.thumbHeight/aspectRatio;url=_this.manifest.getThumbnailForCanvas(canvas,width),_this.allImages.push({url:url,width:width,height:_this.thumbHeight,id:canvas["@id"],index:i})}}jQuery.each(_this.allImages,function(index,value){var width=value.width;return _this.imagesTotalWidth+=width+_this.margin,_this.imagesTotalWidth>=_this.maxPreviewImagesWidth?(value.width>_this.maxPreviewImagesWidth&&_this.tplData.images.push(value),_this.imagesTotalWidth-=width+_this.margin,!1):void _this.tplData.images.push(value)}),_this.remaining=this.tplData.remaining=function(){var remaining=_this.allImages.length-_this.tplData.images.length;if(remaining>0)return remaining}()},render:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("manifestPanelWidthChanged",function(event,newWidth){_this.updateDisplay(newWidth)})},bindEvents:function(){var _this=this;this.element.find("img").on("load",function(){jQuery(this).hide().fadeIn(600)}),this.element.on("click",function(){var windowConfig={manifest:_this.manifest,canvasID:null,viewType:"ThumbnailsView"};_this.eventEmitter.publish("ADD_WINDOW",windowConfig)}),this.element.find(".preview-image").on("click",function(e){e.stopPropagation();var windowConfig={manifest:_this.manifest,canvasID:jQuery(this).attr("data-image-id"),viewType:_this.state.getStateProperty("windowSettings").viewType};_this.eventEmitter.publish("ADD_WINDOW",windowConfig)})},updateDisplay:function(newWidth){var _this=this,newMaxPreviewWidth=newWidth-(_this.repoWidth+_this.margin+_this.metadataWidth+_this.margin+_this.remainingWidth);newMaxPreviewWidth*=.95;var image=null;if(newMaxPreviewWidth<_this.maxPreviewImagesWidth){for(;_this.imagesTotalWidth>=newMaxPreviewWidth&&(image=_this.tplData.images.pop());)_this.imagesTotalWidth-=image.width+_this.margin,_this.element.find('img[data-image-id="'+image.id+'"]').remove();0===_this.remaining&&_this.allImages.length-_this.tplData.images.length>0&&_this.element.find(".preview-images").after('<i class="fa fa fa-ellipsis-h remaining"></i>'),_this.remaining=_this.allImages.length-_this.tplData.images.length}else if(newMaxPreviewWidth>_this.maxPreviewImagesWidth){var currentLastImage=_this.tplData.images[_this.tplData.images.length-1],index=currentLastImage?currentLastImage.index+1:0;if(image=_this.allImages[index]){for(;_this.imagesTotalWidth+image.width+_this.margin<newMaxPreviewWidth&&(_this.tplData.images.push(image),_this.imagesTotalWidth+=image.width+_this.margin,_this.element.find(".preview-images").append('<img src="'+image.url+'" width="'+image.width+'" height="'+image.height+'" class="preview-image flash" data-image-id="'+image.id+'">'),index++,image=_this.allImages[index]););_this.remaining>0&&_this.allImages.length-_this.tplData.images.length===0&&_this.element.find(".remaining").remove(),_this.remaining=_this.allImages.length-_this.tplData.images.length}}_this.maxPreviewImagesWidth=newMaxPreviewWidth,_this.eventEmitter.publish("manifestListItemRendered")},hide:function(){},show:function(){},template:Handlebars.compile(["<li data-index-number={{index}}>",'<div class="repo-image">',"{{#if repoImage}}",'<img src="{{repoImage}}" alt="repoImg">',"{{else}}",'<span class="default-logo"></span>',"{{/if}}","</div>",'<div class="select-metadata">','<div class="manifest-title">','<h3 title="{{{label}}}">{{{label}}}</h3>',"</div>",'<div class="item-info">','<div class="item-info-row">',"{{#if repository}}",'<div class="repo-label">{{repository}}</div>',"{{/if}}",'<div class="canvas-count">{{canvasCount}} {{pluralize canvasCount (t "item") (t "items")}}</div>',"</div>","</div>","</div>",'<div class="preview-thumb">','<div class="preview-images">',"{{#each images}}",'<img src="{{url}}" width="{{width}}" height="{{height}}" class="preview-image flash" data-image-id="{{id}}">',"{{/each}}","</div>","{{#if remaining}}",'<i class="fa fa fa-ellipsis-h remaining"></i>',"{{/if}}","</div>","</li>"].join(""))}}(Mirador),function($){$.ManifestsPanel=function(options){jQuery.extend(!0,this,{element:null,listItems:null,appendTo:null,manifestListItems:[],manifestListElement:null,manifestLoadStatusIndicator:null,resultsWidth:0,state:null,eventEmitter:null},options);var _this=this;_this.init()},$.ManifestsPanel.prototype={init:function(){this.element=jQuery(this.template({showURLBox:this.state.getStateProperty("showAddFromURLBox")})).appendTo(this.appendTo),this.manifestListElement=this.element.find("ul");var clone=this.element.clone().css("visibility","hidden").css("display","block").appendTo(this.appendTo);this.resultsWidth=clone.find(".select-results").outerWidth(),this.controlsHeight=clone.find(".manifest-panel-controls").outerHeight(),this.paddingListElement=this.controlsHeight,this.manifestListElement.css("padding-bottom",this.paddingListElement),clone.remove(),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("manifestsPanelVisible.set",function(_,stateValue){_this.onPanelVisible(_,stateValue)}),_this.eventEmitter.subscribe("manifestReceived",function(event,newManifest){_this.onManifestReceived(event,newManifest)})},bindEvents:function(){var _this=this;this.element.find("form#url-load-form").on("submit",function(event){event.preventDefault(),_this.addManifestUrl(jQuery(this).find("input").val())}),this.element.find(".remove-object-option").on("click",function(event){_this.togglePanel(event)}),this.element.find("#manifest-search").on("keyup input",function(event){_this.filterManifests(this.value)}),this.element.find("#manifest-search-form").on("submit",function(event){event.preventDefault()}),jQuery(window).resize($.throttle(function(){_this.resizePanel()},50,!0))},hide:function(){jQuery(this.element).hide({effect:"fade",duration:160,easing:"easeOutCubic"})},show:function(){jQuery(this.element).show({effect:"fade",duration:160,easing:"easeInCubic"})},addManifestUrl:function(url){var _this=this;_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[url,"(Added from URL)"])},togglePanel:function(event){var _this=this;_this.eventEmitter.publish("TOGGLE_LOAD_WINDOW")},filterManifests:function(value){var _this=this;value.length>0?_this.element.find(".items-listing li").show().filter(function(){return jQuery(this).text().toLowerCase().indexOf(value.toLowerCase())===-1}).hide():_this.element.find(".items-listing li").show()},resizePanel:function(){var _this=this,clone=_this.element.clone().css("visibility","hidden").css("display","block").appendTo(_this.appendTo);_this.resultsWidth=clone.find(".select-results").outerWidth(),clone.remove(),_this.eventEmitter.publish("manifestPanelWidthChanged",_this.resultsWidth)},onPanelVisible:function(_,stateValue){var _this=this;return stateValue?void _this.show():void _this.hide()},onManifestReceived:function(event,newManifest){var _this=this;_this.manifestListItems.push(new $.ManifestListItem({manifest:newManifest,resultsWidth:_this.resultsWidth,state:_this.state,eventEmitter:_this.eventEmitter,appendTo:_this.manifestListElement})),_this.element.find("#manifest-search").keyup()},template:Handlebars.compile(['<div id="manifest-select-menu">','<div class="container">','<div class="manifest-panel-controls">','<a class="remove-object-option"><i class="fa fa-times fa-lg fa-fw"></i>{{t "close"}}</a>','<div id="load-controls">',"{{#if showURLBox}}",'<form action="" id="url-load-form">','<label for="url-loader">{{t "addNewObject"}}:</label>','<input type="text" id="url-loader" name="url-load" placeholder="http://...">','<input type="submit" value="{{t "load"}}">',"</form>","{{/if}}",'<form action="" id="manifest-search-form">','<label for="manifest-search">{{t "filterObjects"}}:</label>','<input id="manifest-search" type="text" name="manifest-filter">',"</form>","</div>","</div>",'<div class="select-results">','<ul class="items-listing">',"</ul>","</div>","</div>","</div>"].join(""))}}(Mirador),function($){$.WorkspacePanel=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,workspace:null,state:null,eventEmitter:null},options),this.init()},$.WorkspacePanel.prototype={init:function(){var _this=this,templateData={rows:$.layoutDescriptionFromGridString(_this.state.getStateProperty("workspacePanelSettings").maxColumns+"x"+_this.state.getStateProperty("workspacePanelSettings").maxRows).children.map(function(column,rowIndex){return column.columns=column.children.map(function(row,columnIndex){return row.gridString=rowIndex+1+"x"+(columnIndex+1),row}),column})};this.element=jQuery(this.template(templateData)).appendTo(this.appendTo);var backgroundImage=_this.state.getStateProperty("buildPath")+_this.state.getStateProperty("imagesPath")+"debut_dark.png";this.element.css("background-image","url("+backgroundImage+")").css("background-repeat","repeat"),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("workspacePanelVisible.set",function(_,stateValue){_this.onPanelVisible(_,stateValue)})},bindEvents:function(){var _this=this;_this.element.find(".grid-item").on("click",function(){var gridString=jQuery(this).data("gridstring");_this.select(gridString)}),_this.element.find(".grid-item").on("mouseover",function(){var gridString=jQuery(this).data("gridstring");_this.hover(gridString)}),_this.element.find(".select-grid").on("mouseout",function(){_this.reset()})},select:function(gridString){var _this=this,layoutDescription=$.layoutDescriptionFromGridString(gridString);_this.eventEmitter.publish("RESET_WORKSPACE_LAYOUT",{layoutDescription:layoutDescription}),_this.eventEmitter.publish("TOGGLE_WORKSPACE_PANEL")},hover:function(gridString){var _this=this,highestRow=gridString.charAt(0),highestColumn=gridString.charAt(2),gridItems=_this.element.find(".grid-item");gridItems.removeClass("hovered"),gridItems.filter(function(index){var gridString=jQuery(this).data("gridstring"),change=gridString.charAt(0)<=highestRow&&gridString.charAt(2)<=highestColumn;return change}).addClass("hovered"),_this.element.find(".grid-instructions").hide(),_this.element.find(".grid-text").text(gridString).show()},reset:function(){var _this=this;_this.element.find(".grid-item").removeClass("hovered"),_this.element.find(".grid-instructions").show(),_this.element.find(".grid-text").hide()},hide:function(){jQuery(this.element).hide({effect:"fade",duration:160,easing:"easeOutCubic"})},show:function(){var onComplete=function(){jQuery(this).css("display","block")};jQuery(this.element).show({effect:"fade",duration:160,easing:"easeInCubic",complete:onComplete})},onPanelVisible:function(_,stateValue){var _this=this;return stateValue?void _this.show():void _this.hide()},template:Handlebars.compile(['<div id="workspace-select-menu">','<h1>{{t "changeLayout"}}</h1>','<h3 class="grid-text"></h3>','<h3 class="grid-instructions">{{t "selectGrid"}}</h3>','<div class="select-grid">',"{{#each rows}}",'<div class="grid-row">',"{{#each columns}}",'<a class="grid-item" data-gridString="{{gridString}}">','<div class="grid-icon"></div>',"</a>","{{/each}}","</div>","{{/each}}","</div>","</div>"].join(""))}}(Mirador),function($){$.Manifest=function(manifestUri,location,manifestContent){manifestContent?(jQuery.extend(!0,this,{jsonLd:null,location:location,uri:manifestUri,request:null}),this.initFromManifestContent(manifestContent)):manifestUri.indexOf("info.json")!==-1?(jQuery.extend(!0,this,{jsonLd:null,location:location,uri:manifestUri,request:null}),this.initFromInfoJson(manifestUri)):(jQuery.extend(!0,this,{jsonLd:null,location:location,uri:manifestUri,request:null}),this.init(manifestUri))},$.Manifest.prototype={init:function(manifestUri){var _this=this;this.request=jQuery.ajax({url:manifestUri,dataType:"json",async:!0}),this.request.done(function(jsonLd){_this.jsonLd=jsonLd})},initFromInfoJson:function(infoJsonUrl){var _this=this;this.request=jQuery.ajax({url:infoJsonUrl,dataType:"json",async:!0}),this.request.done(function(jsonLd){_this.jsonLd=_this.generateInfoWrapper(jsonLd)})},initFromManifestContent:function(manifestContent){var _this=this;this.request=jQuery.Deferred(),this.request.done(function(jsonLd){_this.jsonLd=jsonLd}),_this.request.resolve(manifestContent)},getThumbnailForCanvas:function(canvas,width){var service,thumbnailUrl,version="1.1",compliance=-1;if(width=parseInt(width,10),canvas.hasOwnProperty("thumbnail"))"string"==typeof canvas.thumbnail?thumbnailUrl=canvas.thumbnail:canvas.thumbnail.hasOwnProperty("service")?(service=canvas.thumbnail.service,service.hasOwnProperty("profile")&&(compliance=$.Iiif.getComplianceLevelFromProfile(service.profile)),0===compliance?thumbnailUrl=canvas.thumbnail["@id"]:(service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version))):thumbnailUrl=canvas.thumbnail["@id"];else{var resource=canvas.images[0].resource;service=resource.default?resource.default.service:resource.service,service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version)}return thumbnailUrl},getVersion:function(){var versionMap={"http://www.shared-canvas.org/ns/context.json":"1","http://iiif.io/api/presentation/1/context.json":"1","http://iiif.io/api/presentation/2/context.json":"2","http://iiif.io/api/presentation/2.1/context.json":"2.1"};return versionMap[this.jsonLd["@context"]]},getCanvases:function(){var _this=this;return _this.jsonLd.sequences[0].canvases},getAnnotationsListUrls:function(canvasId){var _this=this,canvas=jQuery.grep(_this.getCanvases(),function(canvas,index){return canvas["@id"]===canvasId})[0],annotationsListUrls=[];if(canvas&&canvas.otherContent)for(var i=0;i<canvas.otherContent.length;i++)annotationsListUrls.push(canvas.otherContent[i]["@id"]);return annotationsListUrls},getStructures:function(){var _this=this;return _this.jsonLd.structures},generateInfoWrapper:function(infoJson){var dummyManifest={"@context":"http://www.shared-canvas.org/ns/context.json","@id":infoJson["@id"],"@type":"sc:Manifest",label:infoJson["@id"].split("/")[infoJson["@id"].split("/").length-1],sequences:[{"@id":infoJson["@id"]+"/sequence/1","@type":"sc:Sequence",canvases:[{"@id":infoJson["@id"]+"/sequence/1/canvas/1","@type":"sc:Canvas",width:infoJson.width,height:infoJson.height,images:[{"@id":infoJson["@id"]+"/sequence/1/canvas/1/image/1","@type":"sc:image",motivation:"sc:painting",resource:{"@id":infoJson,"@type":"dctypes:Image",format:"image/jpeg",height:infoJson.height,width:infoJson.width,service:{"@id":infoJson["@id"],"@context":infoJson["@context"],profile:infoJson.profile}}}]}]}]};return dummyManifest}}}(Mirador),function($){function PaperItem(item){this.item=item}function Group(paperScope,opts){var item=new paperScope.Group(opts);PaperItem.call(this,item)}function PointText(paperScope,opts){var text=new paperScope.PointText(opts);PaperItem.call(this,text)}function PointTextIcon(paperScope,opts){this.paperScope=paperScope,opts.justification="center",opts.font="FontAwesome",this.content=opts.content,PointText.call(this,paperScope,opts),this.rasterMask.addData("self",this)}function DeleteActionIcon(paperScope,opts){this.paperScope=paperScope,opts.fillColor=opts.fillColor||"black",opts.fontSize=opts.size||24/paperScope.view.zoom,opts.content="",this.rasterMask=new Icon(paperScope,{name:opts.name.replace("delete","Delete_mask"),size:new paperScope.Size(opts.fontSize,opts.fontSize)}),PointTextIcon.call(this,paperScope,opts)}function RotationIcon(paperScope,opts){this.paperScope=paperScope,opts.justification="center",opts.fillColor=opts.fillColor||"black",opts.fontSize=opts.size||16/paperScope.view.zoom,opts.content="",this.rasterMask=new Icon(paperScope,{name:opts.name.replace("rotation","Rotation_mask"),size:new paperScope.Size(opts.fontSize,opts.fontSize)}),PointTextIcon.call(this,paperScope,opts)}$.AnnotationUtils=function(){},PaperItem.prototype={getItem:function(){return this.item},translateByXY:function(x,y){this.item.position.x+=x,this.item.position.y+=y},translateByPoint:function(point){this.item.position=this.item.position.add(point)},setOnMouseDownListener:function(callback){this.mouseDown=callback},onMouseDown:function(){this.mouseDown.call(this,this.item)},remove:function(){this.item.remove()},rotate:function(angle,pivot){pivot?this.item.rotate(angle,pivot):this.item.rotate(angle)},setPosition:function(point){this.item.position=point},getWidth:function(){return this.item.width},getHeight:function(){return this.item.height},addData:function(key,data){this.item.data[key]=data},getData:function(key){return this.item.data[key]},resize:function(size){this.item.size=size}},Group.prototype=Object.create(PaperItem.prototype,{}),Group.constructor=Group;var Icon=function(paperScope,opts){this.paperScope=paperScope;var item=new paperScope.Raster(opts);PaperItem.call(this,item),opts&&opts.onLoad&&(this.item.onLoad=opts.onLoad)};Icon.prototype=Object.create(PaperItem.prototype,{}),Icon.constructor=Icon,PointText.prototype=Object.create(PaperItem.prototype),PointText.prototype.resize=function(newSize){this.item.fontSize=newSize},PointText.constructor=PointText,PointTextIcon.prototype=Object.create(PointText.prototype,{}),PointTextIcon.prototype.setPosition=function(point){this.rasterMask.setPosition(point),PointText.prototype.setPosition.call(this,point)},PointTextIcon.prototype.rotate=function(angle,pivot){this.rasterMask.rotate(angle,pivot),PointText.prototype.rotate.call(this,angle,pivot)},PointTextIcon.prototype.translateByPoint=function(point){this.rasterMask.translateByPoint(point),PointText.prototype.translateByPoint.call(this,point)},PointTextIcon.prototype.translateByXY=function(x,y){this.rasterMask.translateByXY(x,y),PointText.prototype.translateByXY.call(this,x,y)},PointTextIcon.prototype.remove=function(){this.rasterMask.remove(),PointText.prototype.remove.call(this)},PointTextIcon.prototype.resize=function(size){this.rasterMask.resize(new this.paperScope.Size(size,size)),PointText.prototype.resize.call(this,size)},PointTextIcon.prototype.getMask=function(){return this.rasterMask},PointTextIcon.prototype.constructor=PointTextIcon,DeleteActionIcon.prototype=Object.create(PointTextIcon.prototype,{}),DeleteActionIcon.prototype.setOnMouseDownListener=function(overlay){this.mouseDown=function(){overlay.eventEmitter.publish("deleteShape."+overlay.windowId,[this.getData("parent")]),overlay.mode="delete"}},RotationIcon.prototype=Object.create(PointTextIcon.prototype,{}),RotationIcon.prototype.setOnMouseDownListener=function(overlay){this.mouseDown=function(){overlay.mode="rotate"}},$.AnnotationUtils.prototype={Icon:Icon,PointText:PointText,DeleteActionIcon:DeleteActionIcon,RotationIcon:RotationIcon,Group:Group}}(Mirador),function($){$.AnnotationTooltip=function(options){jQuery.extend(this,{targetElement:null,annotations:[],windowId:"",eventEmitter:null},options),this.init()},$.AnnotationTooltip.prototype={init:function(){this.editor=$[this.state.currentConfig.annotationBodyEditor.module],this.editorOptions=this.state.currentConfig.annotationBodyEditor.options,this.activeEditor=null,this.activeEditorTip=null,this.inEditOrCreateMode=!1},showEditor:function(params){var _this=this;if(!_this.activeEditor){var editorContainer=_this.editorTemplate({id:jQuery.isEmptyObject(params.annotation)?"":params.annotation["@id"],windowId:_this.windowId}),selector="#annotation-editor-"+_this.windowId;_this.activeEditor=new _this.editor(jQuery.extend({},_this.editorOptions,{annotation:params.annotation,windowId:_this.windowId})),_this.activeEditorTip=_this.targetElement.qtip({content:{text:editorContainer},position:{my:"center",at:"center",container:_this.targetElement,viewport:_this.targetElement},style:{classes:"qtip-bootstrap qtip"+_this.windowId},show:{event:!1},hide:{fixed:!0,delay:300,event:!1},events:{render:function(event,api){_this.eventEmitter.publish("disableTooltips."+_this.windowId),api.elements.tooltip.draggable(),jQuery(selector).on("submit",function(event){event.preventDefault(),jQuery(selector+" a.save").click()}),jQuery(selector+" a.cancel").on("click",function(event){event.preventDefault();var cancelCallback=function(){api.destroy()};_this.eventEmitter.publish("onAnnotationCreatedCanceled."+_this.windowId,[cancelCallback,!_this.activeEditor.isDirty()])}),jQuery(selector+" a.save").on("click",function(event){if(event.preventDefault(),params.onSaveClickCheck()){var annotation=_this.activeEditor.createAnnotation();params.onAnnotationCreated&&params.onAnnotationCreated(annotation),api.destroy(),_this.activeEditor=null,_this.activeEditorTip=null}}),_this.activeEditor.show(selector),_this.eventEmitter.publish("annotationEditorAvailable."+_this.windowId)}}}),_this.activeEditorTip.qtip("show")}},initializeViewerUpgradableToEditor:function(params){var _this=this;_this.activeEditorTip=jQuery(_this.targetElement).qtip({overwrite:!1,content:{text:""},position:{target:"mouse",my:"bottom left",at:"top right",adjust:{mouse:!1,method:"shift"},container:params.container,viewport:params.viewport},style:{classes:"qtip-bootstrap qtip-viewer",tip:!1},hide:{fixed:!0,delay:300,event:!1},events:{shown:function(event,api){params.onTooltipShown&&params.onTooltipShown(event,api)},hidden:function(event,api){params.onTooltipHidden&&params.onTooltipHidden(event,api),_this.removeAllEvents(api,params)},visible:function(event,api){_this.removeAllEvents(api,params),_this.addViewerEvents(api,params)},move:function(event,api){api.cache.contentUpdated&&(_this.removeAllEvents(api,params),_this.addViewerEvents(api,params)),api.cache.contentUpdated=!1}}});var api=jQuery(_this.targetElement).qtip("api");api.cache.annotations=[],api.cache.hidden=!0},removeAllEvents:function(api,viewerParams){var _this=this,editorSelector="#annotation-editor-"+_this.windowId,viewerSelector="#annotation-viewer-"+_this.windowId;jQuery(viewerSelector+" a.delete").off("click"),jQuery(viewerSelector+" a.edit").off("click"),jQuery(editorSelector+" a.save").off("click"),jQuery(editorSelector+" a.cancel").off("click")},addViewerEvents:function(api,viewerParams){var _this=this,selector="#annotation-viewer-"+_this.windowId;jQuery(selector+" a.delete").on("click",function(event){event.preventDefault();var elem=this;new $.DialogBuilder(viewerParams.container).dialog({message:i18next.t("deleteAnnotation"),closeButton:!1,buttons:{no:{label:i18next.t("no"),className:"btn-default",callback:function(){}},yes:{label:i18next.t("yes"),className:"btn-primary",callback:function(){var display=jQuery(elem).parents(".annotation-display"),id=display.attr("data-anno-id"),callback=function(){api.hide(),display.remove()};_this.eventEmitter.publish("onAnnotationDeleted."+_this.windowId,[id,callback])}}}})}),jQuery(selector+" a.edit").on("click",function(event){event.preventDefault();var display=jQuery(this).parents(".annotation-display"),id=display.attr("data-anno-id"),oaAnno=viewerParams.getAnnoFromRegion(id)[0];_this.state.getStateProperty("availableExternalCommentsPanel")?(_this.eventEmitter.publish("annotationInEditMode."+_this.windowId,[oaAnno]),api.destroy(),jQuery(api.tooltip).remove()):(_this.freezeQtip(api,oaAnno,viewerParams),_this.removeAllEvents(api,viewerParams),_this.addEditorEvents(api,viewerParams)),_this.eventEmitter.publish("SET_ANNOTATION_EDITING."+_this.windowId,{annotationId:id,isEditable:!0,tooltip:_this}),_this.eventEmitter.publish("modeChange."+_this.windowId,"editingAnnotation")})},addEditorEvents:function(api,viewerParams){var _this=this,selector="#annotation-editor-"+_this.windowId;jQuery(selector).on("submit",function(event){event.preventDefault(),jQuery(selector+" a.save").click()}),jQuery(selector+" a.save").on("click",function(event){event.preventDefault();var display=jQuery(this).parents(".annotation-editor"),id=display.attr("data-anno-id"),oaAnno=viewerParams.getAnnoFromRegion(id)[0];_this.activeEditor.updateAnnotation(oaAnno),_this.eventEmitter.publish("annotationEditSave."+_this.windowId,[oaAnno])}),jQuery(selector+" a.cancel").on("click",function(event){event.preventDefault();var display=jQuery(this).parents(".annotation-editor"),id=display.attr("data-anno-id"),oaAnno=viewerParams.getAnnoFromRegion(id)[0];_this.unFreezeQtip(api,oaAnno,viewerParams),_this.eventEmitter.publish("annotationEditCancel."+_this.windowId,[id])})},showViewer:function(params){var _this=this,api=jQuery(_this.targetElement).qtip("api");if(api&&(!params.shouldDisplayTooltip||params.shouldDisplayTooltip(api)))if(0===params.annotations.length)api.cache.hidden||(api.disable(!1),api.hide(params.triggerEvent),api.cache.annotations=[],api.cache.hidden=!0,api.disable(!0));else{var oldAnnotations=api.cache.annotations,isTheSame=oldAnnotations.length==params.annotations.length;if(isTheSame)for(var i=0;i<params.annotations.length;i++)if(oldAnnotations[i]!=params.annotations[i]){isTheSame=!1;break}!api.cache.hidden&&isTheSame||(api.disable(!1),api.cache.contentUpdated=!1,_this.setTooltipContent(params.annotations),api.cache.origin=params.triggerEvent,api.reposition(params.triggerEvent,!0),api.show(params.triggerEvent),api.cache.annotations=params.annotations,api.cache.hidden=!1,api.disable(!0))}},setTooltipContent:function(annotations){var _this=this,api=jQuery(this.targetElement).qtip("api");api&&(api.cache.contentUpdated=!0,api.set({"content.text":this.getViewerContent(annotations)}),_this.eventEmitter.publish("tooltipViewerSet."+this.windowId))},getViewerContent:function(annotations){var annoText,tags=[],htmlAnnotations=[];jQuery.each(annotations,function(index,annotation){tags=[],jQuery.isArray(annotation.resource)?jQuery.each(annotation.resource,function(index,value){"oa:Tag"===value["@type"]?tags.push(value.chars):annoText=value.chars}):annoText=annotation.resource.chars;var username="";annotation.annotatedBy&&annotation.annotatedBy.name&&(username=annotation.annotatedBy.name);var showUpdate=!1;"manifest"!==annotation.endpoint&&(showUpdate=annotation.endpoint.userAuthorize("update",annotation));var showDelete=!1;"manifest"!==annotation.endpoint&&(showDelete=annotation.endpoint.userAuthorize("delete",annotation)),htmlAnnotations.push({annoText:$.sanitizeHtml(annoText),tags:tags,id:annotation["@id"],username:username,showUpdate:showUpdate,showDelete:showDelete})});var template=this.viewerTemplate({annotations:htmlAnnotations,windowId:this.windowId});return template},freezeQtip:function(api,oaAnno,viewerParams){var _this=this;if(this.inEditOrCreateMode)throw"AnnotationTooltip already in edit mode";this.inEditOrCreateMode=!0,_this.eventEmitter.publish("disableRectTool."+this.windowId);var editorContainer=this.editorTemplate({id:jQuery.isEmptyObject(oaAnno)?"":oaAnno["@id"],windowId:this.windowId});api.set({"content.text":editorContainer,"hide.event":!1}),this.activeEditor=new this.editor(jQuery.extend({},this.editorOptions,{annotation:oaAnno,windowId:this.windowId})),this.activeEditor.show("form#annotation-editor-"+this.windowId),_this.eventEmitter.publish("annotationEditorAvailable."+this.windowId),jQuery(api.elements.tooltip).removeClass("qtip-viewer"),api.elements.tooltip.draggable(),viewerParams.onEnterEditMode&&viewerParams.onEnterEditMode(api,oaAnno)},unFreezeQtip:function(api,oaAnno,viewerParams){var _this=this;if(!this.inEditOrCreateMode)throw"AnnotationTooltip not in edit mode";this.inEditOrCreateMode=!1,_this.eventEmitter.publish("enableRectTool."+this.windowId),api.set({"content.text":this.getViewerContent([oaAnno]),"hide.event":"mouseleave"}).hide(),jQuery(api.elements.tooltip).addClass("qtip-viewer"),viewerParams.onExitEditMode&&viewerParams.onExitEditMode(api,oaAnno)},editorTemplate:Handlebars.compile(['<form id="annotation-editor-{{windowId}}" class="annotation-editor annotation-tooltip" {{#if id}}data-anno-id="{{id}}"{{/if}}>',"<div>",'<div class="button-container">','<a href="#cancel" class="cancel"><i class="fa fa-times-circle-o fa-fw"></i>{{t "cancel"}}</a>','<a href="#save" class="save"><i class="fa fa-database fa-fw"></i>{{t "save"}}</a>',"</div>","</div>","</form>"].join("")),viewerTemplate:Handlebars.compile(['<div class="all-annotations" id="annotation-viewer-{{windowId}}">',"{{#each annotations}}",'<div class="annotation-display annotation-tooltip" data-anno-id="{{id}}">','<div class="button-container">','{{#if showUpdate}}<a href="#edit" class="edit"><i class="fa fa-pencil-square-o fa-fw"></i>{{t "edit"}}</a>{{/if}}','{{#if showDelete}}<a href="#delete" class="delete"><i class="fa fa-trash-o fa-fw"></i>{{t "delete"}}</a>{{/if}}',"</div>",'<div class="text-viewer">','{{#if username}}<p class="user">{{username}}:</p>{{/if}}',"<p>{{{annoText}}}</p>","</div>",'<div id="tags-viewer-{{windowId}}" class="tags-viewer">',"{{#each tags}}",'<span class="tag">{{this}}</span>',"{{/each}}","</div>","</div>","{{/each}}","</div>"].join(""))}}(Mirador),function($){$.CatchEndpoint=function(options){jQuery.extend(this,{token:null,prefix:null,params:"",dfd:null,context_id:"None",collection_id:"None",userid:"test@mirador.org",username:"mirador-test",annotationsList:[],annotationsListCatch:null,windowID:null,eventEmitter:null},options),this.init()},$.CatchEndpoint.prototype={init:function(){this.catchOptions={user:{id:this.userid,name:this.username},permissions:{read:[],update:[this.userid],
81
- delete:[this.userid],admin:[this.userid]}}},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},search:function(options,successCallback,errorCallback){var _this=this;this.annotationsList=[],jQuery.ajax({url:this.prefix+"/search"+this.params,type:"GET",dataType:"json",headers:{"x-annotator-auth-token":this.token},data:{uri:options.uri,userid:options.userid?options.userid:void 0,username:options.username?options.username:void 0,text:options.text?options.text:void 0,tag:options.tag?options.tag:void 0,parentid:options.parentid?options.parentid:void 0,contextId:_this.context_id,collectionId:_this.collection_id,media:options.media?options.media:"image",limit:options.limit?options.limit:-1},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback?successCallback(data):(_this.annotationsListCatch=data.rows,jQuery.each(_this.annotationsListCatch,function(index,value){_this.annotationsList.push(_this.getAnnotationInOA(value))}),_this.dfd.resolve(!0),_this.eventEmitter.publish("catchAnnotationsLoaded."+_this.windowID,_this.annotationsListCatch))},error:function(){"function"==typeof errorCallback?errorCallback():console.log("There was an error searching this endpoint")}})},deleteAnnotation:function(annotationID,successCallback,errorCallback){var _this=this;jQuery.ajax({url:this.prefix+"/destroy/"+annotationID+this.params,type:"DELETE",dataType:"json",headers:{"x-annotator-auth-token":this.token},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(),_this.eventEmitter.publish("catchAnnotationDeleted."+_this.windowID,annotationID)},error:function(){"function"==typeof errorCallback&&errorCallback()}})},update:function(oaAnnotation,successCallback,errorCallback){var annotations=this.getAnnotationInEndpoint(oaAnnotation),_this=this;annotations.forEach(function(annotation){var annotationID=annotation.id;jQuery.ajax({url:_this.prefix+"/update/"+annotationID+_this.params,type:"POST",dataType:"json",headers:{"x-annotator-auth-token":_this.token},data:JSON.stringify(annotation),contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(_this.getAnnotationInOA(data)),_this.eventEmitter.publish("catchAnnotationUpdated."+_this.windowID,annotation)},error:function(){"function"==typeof errorCallback&&errorCallback()}})})},create:function(oaAnnotation,successCallback,errorCallback){var _this=this,annotations=this.getAnnotationInEndpoint(oaAnnotation);annotations.forEach(function(annotation){_this.createCatchAnnotation(annotation,successCallback,errorCallback)})},createCatchAnnotation:function(catchAnnotation,successCallback,errorCallback){var _this=this;jQuery.ajax({url:this.prefix+"/create"+this.params,type:"POST",dataType:"json",headers:{"x-annotator-auth-token":this.token},data:JSON.stringify(catchAnnotation),contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(_this.getAnnotationInOA(data)),_this.eventEmitter.publish("catchAnnotationCreated."+_this.windowID,data)},error:function(){"function"==typeof errorCallback&&errorCallback()}})},userAuthorize:function(action,annotation){if(this.roles&&(this.roles.indexOf("Instructor")!==-1||this.roles.indexOf("Administrator")!==-1))return!0;if(annotation.permissions){var permissionUserIds=annotation.permissions[action]||[];return 0===permissionUserIds.length||permissionUserIds.indexOf(this.userid)!==-1}return!annotation.user||this.userid===annotation.user.userid},getAnnotationInOA:function(annotation){var id,on,annotatedBy,motivation=[],resource=[];if(id=annotation.id,annotation.tags.length>0&&(motivation.push("oa:tagging"),jQuery.each(annotation.tags,function(index,value){resource.push({"@type":"oa:Tag",chars:value})})),annotation.parent&&"0"!==annotation.parent)motivation.push("oa:replying"),on=annotation.parent;else{var value;motivation.push("oa:commenting"),jQuery.isArray(annotation.rangePosition)?on=annotation.rangePosition:"object"==typeof annotation.rangePosition?(value="xywh="+annotation.rangePosition.x+","+annotation.rangePosition.y+","+annotation.rangePosition.width+","+annotation.rangePosition.height,on={"@type":"oa:SpecificResource",full:annotation.uri,selector:{"@type":"oa:FragmentSelector",value:value}}):(value=annotation.rangePosition,on={"@type":"oa:SpecificResource",full:annotation.uri,selector:{"@type":"oa:SvgSelector",value:value}})}resource.push({"@type":"dctypes:Text",format:"text/html",chars:annotation.text}),annotatedBy={"@id":annotation.user.id,name:annotation.user.name};var oaAnnotation={"@context":"http://iiif.io/api/presentation/2/context.json","@id":String(id),"@type":"oa:Annotation",motivation:motivation,resource:resource,on:on,annotatedBy:annotatedBy,annotatedAt:annotation.created,serializedAt:annotation.updated,permissions:annotation.permissions,endpoint:this};return oaAnnotation},getAnnotationInEndpoint:function(oaAnnotation){var _this=this,uris=[];oaAnnotation.on.forEach(function(value){jQuery.inArray(value.full,uris)===-1&&uris.push(value.full)});var annotations=[];return uris.forEach(function(uri){var text,annotation={},tags=[];oaAnnotation["@id"]&&(annotation.id=oaAnnotation["@id"]),annotation.media="image",jQuery.each(oaAnnotation.resource,function(index,value){"oa:Tag"===value["@type"]?tags.push(value.chars):"dctypes:Text"===value["@type"]&&(text=value.chars)}),annotation.tags=tags,annotation.text=text,annotation.uri=uri,annotation.contextId=_this.context_id,annotation.collectionId=_this.collection_id,annotation.rangePosition=oaAnnotation.on;var coordsArray=[];oaAnnotation.on.forEach(function(value){var xywh=value.selector.default.value.split("=")[1].split(",");coordsArray.push(xywh.map(function(i){return parseInt(i)}))});var left=coordsArray.map(function(i){return i[0]}),top=coordsArray.map(function(i){return i[1]}),right=coordsArray.map(function(i){return i[0]+i[2]}),bottom=coordsArray.map(function(i){return i[1]+i[3]}),newRect={x:Math.min.apply(null,left),y:Math.min.apply(null,top),width:Math.max.apply(null,right)-Math.min.apply(null,left),height:Math.max.apply(null,bottom)-Math.min.apply(null,top)},canvas=_this.imagesList[$.getImageIndexById(_this.imagesList,uri)],imageUrl=$.getThumbnailForCanvas(canvas,300);imageUrl=imageUrl.replace("full",newRect.x+","+newRect.y+","+newRect.width+","+newRect.height),annotation.thumb=imageUrl,annotation.bounds={x:newRect.x,y:newRect.y,width:newRect.width,height:newRect.height},annotation.updated=(new Date).toISOString(),oaAnnotation.annotatedAt?annotation.created=oaAnnotation.annotatedAt:annotation.created=annotation.updated,annotation.user={},oaAnnotation.annotatedBy?(annotation.user.name=oaAnnotation.annotatedBy.name,annotation.user.id=oaAnnotation.annotatedBy["@id"]):annotation.user=_this.catchOptions.user,annotation.permissions=_this.catchOptions.permissions,annotation.archived=!1,annotation.ranges=[],annotation.parent="0",annotations.push(annotation)}),annotations}}}(Mirador),function($){$.Endpoint=function(options){jQuery.extend(this,{dfd:null,annotationsList:[],windowID:null,eventEmitter:null},options),this.init()},$.Endpoint.prototype={init:function(){},search:function(options,successCallback,errorCallback){var _this=this;jQuery.ajax({url:"",type:"GET",dataType:"json",headers:{},data:{},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback?successCallback(data):(jQuery.each(data,function(index,value){_this.annotationsList.push(_this.getAnnotationInOA(value))}),_this.dfd.resolve(!0))},error:function(){"function"==typeof errorCallback&&errorCallback()}})},deleteAnnotation:function(annotationID,successCallback,errorCallback){jQuery.ajax({url:"",type:"DELETE",dataType:"json",headers:{},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback()},error:function(){"function"==typeof errorCallback&&errorCallback()}})},update:function(oaAnnotation,successCallback,errorCallback){this.getAnnotationInEndpoint(oaAnnotation);jQuery.ajax({url:"",type:"POST",dataType:"json",headers:{},data:"",contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback()},error:function(){"function"==typeof errorCallback&&errorCallback()}})},create:function(oaAnnotation,successCallback,errorCallback){var _this=this;jQuery.ajax({url:"",type:"POST",dataType:"json",headers:{},data:"",contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(_this.getAnnotationInOA(data))},error:function(){"function"==typeof errorCallback&&errorCallback()}})},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},getAnnotationInOA:function(annotation){},getAnnotationInEndpoint:function(oaAnnotation){}}}(Mirador),function($){$.LegacyOpenAnnotationStrategy=function(options){jQuery.extend(this,{},options),this.init()},$.LegacyOpenAnnotationStrategy.prototype={init:function(){},isThisType:function(annotation){return!(!annotation.on||"string"!=typeof annotation.on)&&annotation.on.indexOf("xywh=")!==-1},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay,bounds=overlay.draftPaths[0].bounds;return oaAnno.on=win.canvasID+"#xywh="+Math.round(bounds.x)+","+Math.round(bounds.y)+","+Math.round(bounds.width)+","+Math.round(bounds.height),oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation))return osdRegionDrawTool.parseRectangle(annotation.on,annotation)}}}(Mirador),function($){$.LocalStorageEndpoint=function(options){jQuery.extend(this,{token:null,prefix:null,dfd:null,annotationsList:[],windowID:null,eventEmitter:null},options),this.init()},$.LocalStorageEndpoint.prototype={init:function(){},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},search:function(options,successCallback,errorCallback){var _this=this;this.annotationsList=[];try{_this.annotationsList=_this.getAnnotationList(options.uri),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback?successCallback(_this.annotationsList):_this.dfd.resolve(!0)}catch(e){"function"==typeof errorCallback?errorCallback():console.log("There was an error searching this endpoint")}},deleteAnnotation:function(annotationID,successCallback,errorCallback){var _this=this,keys=[];jQuery.each(_this.annotationsList[0].on,function(index,value){jQuery.inArray(value.full,keys)===-1&&keys.push(value.full)}),0===keys.length&&"function"==typeof errorCallback&&errorCallback(),jQuery.each(keys,function(index,key){try{_this.annotationsList=jQuery.grep(_this.annotationsList,function(value,index){return value["@id"]!==annotationID}),jQuery.each(_this.annotationsList,function(index,value){delete value.endpoint}),localStorage.setItem(key,JSON.stringify(_this.annotationsList)),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback&&successCallback()}catch(e){"function"==typeof errorCallback&&errorCallback()}})},update:function(oaAnnotation,successCallback,errorCallback){var _this=this,annotationID=oaAnnotation["@id"],keys=[];jQuery.each(oaAnnotation.on,function(index,value){jQuery.inArray(value.full,keys)===-1&&keys.push(value.full)}),0===keys.length&&"function"==typeof errorCallback&&errorCallback(),jQuery.each(keys,function(index,key){try{0===_this.annotationsList.length&&(_this.annotationsList=_this.getAnnotationList(key)),jQuery.each(_this.annotationsList,function(index,value){if(value["@id"]===annotationID)return _this.annotationsList[index]=oaAnnotation,!1}),jQuery.each(_this.annotationsList,function(index,value){delete value.endpoint}),localStorage.setItem(key,JSON.stringify(_this.annotationsList)),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback&&successCallback(oaAnnotation)}catch(e){"function"==typeof errorCallback&&errorCallback()}})},create:function(oaAnnotation,successCallback,errorCallback){var _this=this,keys=[];jQuery.each(oaAnnotation.on,function(index,value){jQuery.inArray(value.full,keys)===-1&&keys.push(value.full)}),0===keys.length&&"function"==typeof errorCallback&&errorCallback(),jQuery.each(keys,function(index,key){try{0===_this.annotationsList.length&&(_this.annotationsList=_this.getAnnotationList(key)),oaAnnotation["@id"]=$.genUUID(),_this.annotationsList.push(oaAnnotation),jQuery.each(_this.annotationsList,function(index,value){delete value.endpoint}),localStorage.setItem(key,JSON.stringify(_this.annotationsList)),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback&&successCallback(oaAnnotation)}catch(e){"function"==typeof errorCallback&&errorCallback()}})},getAnnotationList:function(key){var data=localStorage.getItem(key);return data?JSON.parse(data):[]},userAuthorize:function(action,annotation){return!0}}}(Mirador),function($){$.Mirador21Strategy=function(options){jQuery.extend(this,{},options),this.init()},$.Mirador21Strategy.prototype={init:function(){},isThisType:function(annotation){return!!(annotation.on&&"object"==typeof annotation.on&&annotation.on.selector&&"object"==typeof annotation.on.selector&&annotation.on.selector.value&&"string"==typeof annotation.on.selector.value&&"oa:SvgSelector"===annotation.on.selector["@type"])},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay,svg=overlay.getSVGString(overlay.draftPaths);return oaAnno.on={"@type":"oa:SpecificResource",full:win.canvasID,selector:{"@type":"oa:SvgSelector",value:svg},within:{"@id":win.loadedManifest,"@type":"sc:Manifest"}},oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation))return osdRegionDrawTool.svgOverlay.parseSVG(annotation.on.selector.value,annotation)}}}(Mirador),function($){$.MiradorDualStrategy=function(options){jQuery.extend(this,{},options),this.init()},$.MiradorDualStrategy.prototype={init:function(){},isThisType:function(annotation){return!!(annotation.on&&jQuery.isArray(annotation.on)&&annotation.on.length>0&&"object"==typeof annotation.on[0]&&annotation.on[0].selector&&"object"==typeof annotation.on[0].selector&&"oa:Choice"===annotation.on[0].selector["@type"]&&annotation.on[0].selector.default&&"object"==typeof annotation.on[0].selector.default&&annotation.on[0].selector.default.value&&"string"==typeof annotation.on[0].selector.default.value&&annotation.on[0].selector.item&&"object"==typeof annotation.on[0].selector.item&&annotation.on[0].selector.item.value&&"string"==typeof annotation.on[0].selector.item.value)&&(0===annotation.on[0].selector.default.value.indexOf("xywh=")&&0===annotation.on[0].selector.item.value.indexOf("<svg"))},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay;return oaAnno.on=[],jQuery.each(overlay.draftPaths,function(index,path){var svg=overlay.getSVGString([path]),bounds=path.bounds;oaAnno.on.push({"@type":"oa:SpecificResource",full:win.canvasID,selector:{"@type":"oa:Choice",default:{"@type":"oa:FragmentSelector",value:"xywh="+Math.round(bounds.x)+","+Math.round(bounds.y)+","+Math.round(bounds.width)+","+Math.round(bounds.height)},item:{"@type":"oa:SvgSelector",value:svg}},within:{"@id":win.loadedManifest,"@type":"sc:Manifest"}})}),oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation)){var regionArray=[];return jQuery.each(annotation.on,function(index,target){regionArray=regionArray.concat(osdRegionDrawTool.svgOverlay.parseSVG(target.selector.item.value,annotation))}),regionArray}}}}(Mirador),function($){$.MiradorLegacyStrategy=function(options){jQuery.extend(this,{},options),this.init()},$.MiradorLegacyStrategy.prototype={init:function(){},isThisType:function(annotation){return!!(annotation.on&&"object"==typeof annotation.on&&annotation.on.selector&&"object"==typeof annotation.on.selector&&annotation.on.selector.value&&"string"==typeof annotation.on.selector.value&&"oa:FragmentSelector"===annotation.on.selector["@type"])&&0===annotation.on.selector.value.indexOf("xywh=")},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay,bounds=overlay.draftPaths[0].bounds;return oaAnno.on={"@type":"oa:SpecificResource",full:win.canvasID,selector:{"@type":"oa:FragmentSelector",value:"xywh="+Math.round(bounds.x)+","+Math.round(bounds.y)+","+Math.round(bounds.width)+","+Math.round(bounds.height)}},oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation))return osdRegionDrawTool.parseRectangle(annotation.on.full+"#"+annotation.on.selector.value,annotation)}}}(Mirador),function($){$.OsdRegionDrawTool=function(options){jQuery.extend(this,{osdViewer:null,parent:null,osd:null,list:null,annotationsToShapesMap:{},eventEmitter:null},options),this.eventsSubscriptions=[],this.init()},$.OsdRegionDrawTool.prototype={init:function(){this.svgOverlay=this.osdViewer.svgOverlay(this.osdViewer.id,this.windowId,this.state,this.eventEmitter),this.svgOverlay.show(),this.svgOverlay.disable(),this.listenForActions()},enterDisplayAnnotations:function(){this.svgOverlay.setMouseTool(),this.svgOverlay.inEditOrCreateMode?this.svgOverlay.checkToRemoveFocus():(this.exitEditMode(!0),this.render())},enterCreateAnnotation:function(){this.svgOverlay.inEditOrCreateMode?this.svgOverlay.checkToRemoveFocus():(this.osdViewer.setMouseNavEnabled(!1),this.svgOverlay.show(),this.svgOverlay.enable(),this.render())},enterCreateShape:function(){this.svgOverlay.inEditOrCreateMode?this.svgOverlay.checkToRemoveFocus():(this.osdViewer.setMouseNavEnabled(!1),this.svgOverlay.show(),this.svgOverlay.enable())},enterEditAnnotation:function(){this.osdViewer.setMouseNavEnabled(!1),this.svgOverlay.show(),this.svgOverlay.enableEdit()},enterDefault:function(){this.svgOverlay.removeMouseTool(),this.exitEditMode(!1)},exitEditMode:function(showAnnotations){this.osdViewer.setMouseNavEnabled(!0),this.svgOverlay.disable(),showAnnotations?this.svgOverlay.show():this.svgOverlay.hide()},render:function(){if(this.parent.mode===$.AnnotationsLayer.DISPLAY_ANNOTATIONS){this.svgOverlay.restoreEditedShapes(),this.svgOverlay.paperScope.activate(),this.svgOverlay.paperScope.project.clear();var _this=this;_this.annotationsToShapesMap={};for(var strategies=[new $.Mirador21Strategy,new $.LegacyOpenAnnotationStrategy,new $.MiradorLegacyStrategy,new $.MiradorDualStrategy],i=0;i<this.list.length;i++){var shapeArray,annotation=this.list[i];if("object"==typeof annotation&&annotation.on){var j;for(j=0;j<strategies.length;j++)if(strategies[j].isThisType(annotation)){shapeArray=strategies[j].parseRegion(annotation,_this);break}if(j===strategies.length)continue}_this.svgOverlay.restoreLastView(shapeArray),_this.annotationsToShapesMap[annotation["@id"]]=shapeArray}var windowElement=_this.state.getWindowElement(_this.windowId);this.annoTooltip=new $.AnnotationTooltip({targetElement:jQuery(this.osdViewer.element),state:_this.state,eventEmitter:_this.eventEmitter,windowId:_this.windowId}),this.annoTooltip.initializeViewerUpgradableToEditor({container:windowElement,viewport:windowElement,getAnnoFromRegion:_this.getAnnoFromRegion.bind(this)}),this.svgOverlay.paperScope.view.draw(),_this.eventEmitter.publish("annotationsRendered."+_this.windowId)}},parseRectangle:function(rectString,annotation){var shapeArray=rectString.split("=")[1].split(","),shape={x:parseInt(shapeArray[0]),y:parseInt(shapeArray[1]),width:parseInt(shapeArray[2]),height:parseInt(shapeArray[3])};return this.svgOverlay.createRectangle(shape,annotation)},showTooltipsFromMousePosition:function(event,location,absoluteLocation){var _this=this,hitOptions={fill:!0,stroke:!0,segments:!0},hoverColor=this.state.getStateProperty("drawingToolsSettings").hoverColor,annotations=[];for(var key in _this.annotationsToShapesMap)if(_this.annotationsToShapesMap.hasOwnProperty(key))for(var shapeArray=_this.annotationsToShapesMap[key],idx=0;idx<shapeArray.length;idx++){var shapeTool=this.svgOverlay.getTool(shapeArray[idx]);if(shapeArray[idx].hitTest(location,hitOptions)){if(annotations.push(shapeArray[idx].data.annotation),shapeTool.onHover)for(var k=0;k<shapeArray.length;k++)shapeTool.onHover(!0,shapeArray[k],hoverColor);break}shapeTool.onHover&&shapeTool.onHover(!1,shapeArray[idx])}this.svgOverlay.paperScope.view.draw(),_this.annoTooltip.showViewer({annotations:annotations,triggerEvent:event,shouldDisplayTooltip:function(api){if(api.elements.tooltip){var cursorWithinTooltip=!0,leftSide=api.elements.tooltip.offset().left-_this.svgOverlay.hitOptions.tolerance,rightSide=api.elements.tooltip.offset().left+api.elements.tooltip.width()+_this.svgOverlay.hitOptions.tolerance;(absoluteLocation.x<leftSide||rightSide<absoluteLocation.x)&&(cursorWithinTooltip=!1);var topSide=api.elements.tooltip.offset().top-_this.svgOverlay.hitOptions.tolerance,bottomSide=api.elements.tooltip.offset().top+api.elements.tooltip.height()+_this.svgOverlay.hitOptions.tolerance;return(absoluteLocation.y<topSide||bottomSide<absoluteLocation.y)&&(cursorWithinTooltip=!1),!cursorWithinTooltip}return!0}})},listenForActions:function(){var _this=this;this._thisDestroy=function(){_this.destroy()},_this.osdViewer.addHandler("close",this._thisDestroy),this.eventsSubscriptions.push(this.eventEmitter.subscribe("DESTROY_EVENTS."+this.windowId,function(event){_this.destroy()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("updateTooltips."+_this.windowId,function(event,location,absoluteLocation){_this.annoTooltip&&!_this.annoTooltip.inEditOrCreateMode&&_this.showTooltipsFromMousePosition(event,location,absoluteLocation)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("removeTooltips."+_this.windowId,function(){jQuery(_this.osdViewer.element).qtip("destroy",!0)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("disableTooltips."+_this.windowId,function(){_this.annoTooltip&&(_this.annoTooltip.inEditOrCreateMode=!0)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("enableTooltips."+_this.windowId,function(){_this.annoTooltip&&(_this.annoTooltip.inEditOrCreateMode=!1),_this.svgOverlay.restoreDraftShapes()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("SET_ANNOTATION_EDITING."+_this.windowId,function(event,options){jQuery.each(_this.annotationsToShapesMap,function(key,paths){key===options.annotationId?(options.isEditable?_this.eventEmitter.publish("SET_OVERLAY_TOOLTIP."+_this.windowId,{tooltip:options.tooltip,visible:!0,paths:paths}):_this.eventEmitter.publish("SET_OVERLAY_TOOLTIP."+_this.windowId,{tooltip:null,visible:!1,paths:[]}),jQuery.each(paths,function(index,path){var tool=_this.svgOverlay.getTool(path);tool.onHover(!1,path),path.data.editable=options.isEditable,options.isEditable?(path.data.currentStrokeValue=path.data.editStrokeValue,path.strokeWidth=path.data.currentStrokeValue/_this.svgOverlay.paperScope.view.zoom):(path.data.currentStrokeValue=path.data.defaultStrokeValue,path.strokeWidth=path.data.currentStrokeValue/_this.svgOverlay.paperScope.view.zoom)})):jQuery.each(paths,function(index,path){path.data.editable=!1})}),_this.svgOverlay.paperScope.view.draw()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("refreshOverlay."+_this.windowId,function(event){_this.render()}))},getAnnoFromRegion:function(regionId){return this.list.filter(function(annotation){return annotation["@id"]===regionId})},destroy:function(){var _this=this;this.eventsSubscriptions.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)}),this.osdViewer.removeHandler("close",this._thisDestroy)}}}(Mirador),function($){$.Ellipse=function(options){jQuery.extend(this,{name:"Ellipse",logoClass:"radio_button_unchecked",idPrefix:"ellipse_",tooltip:"ellipseTooltip"},options),this.init()},$.Ellipse.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var segments=[],pixel=1/overlay.paperScope.view.zoom;segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-(Math.sqrt(2)+1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-(Math.sqrt(2)+1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-(Math.sqrt(2)+1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x+(Math.sqrt(2)-1)*pixel,initialPoint.y-1*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y+(Math.sqrt(2)-1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-(Math.sqrt(2)+1)*pixel,initialPoint.y-1*pixel));var _this=this,shape=new overlay.paperScope.Path({segments:segments,name:overlay.getName(_this)});return shape.dashArray=overlay.dashArray,shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape.strokeColor=overlay.strokeColor,shape.fillColor=overlay.fillColor,shape.fillColor.alpha=overlay.fillColorAlpha,shape.closed=!0,shape.data.rotation=0,overlay.segment=shape.segments[6],this.updateSelection(!0,shape,overlay),shape},updateSelection:function(selected,item,overlay){if(item._name.toString().indexOf(this.idPrefix)!=-1){item.segments.length>10&&item.removeSegment(10),item.smooth({from:-7,to:1}),item.selected=selected,item.segments[2].selected=selected;var inHandle=item.segments[7].handleIn.clone();inHandle=inHandle.multiply(-1);var outHandle=item.segments[7].handleOut.clone();if(outHandle=outHandle.multiply(-1),item.segments[1].handleIn=inHandle,item.segments[1].handleOut=new overlay.paperScope.Point(0,0),item.segments[2].handleIn=new overlay.paperScope.Point(0,0),item.segments[2].handleOut=new overlay.paperScope.Point(0,0),item.segments[3].handleIn=new overlay.paperScope.Point(0,0),item.segments[3].handleOut=outHandle,selected){var point=item.segments[2].point.clone();point=point.add(item.segments[2].handleOut),item.contains(point)&&(item.segments[2].handleOut=item.segments[2].handleOut.rotate(180,item.segments[2])),item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.addData("pivot",item.segments[7].point),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.setOnMouseDownListener(overlay)),item.data.rotationIcon||(item.data.rotationIcon=new overlay.annotationUtils.RotationIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"rotation",fillColor:item.selectedColor}),item.data.rotationIcon.addData("pivot",item.segments[3].point),item.data.rotationIcon.addData("type","rotationIcon"),item.data.rotationIcon.addData("self",item.data.rotationIcon),item.data.rotationIcon.addData("parent",item),item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.setOnMouseDownListener(overlay)),item.data.group||(item.data.group=new overlay.annotationUtils.Group(overlay.paperScope,[item,item.data.deleteIcon.getItem(),item.data.deleteIcon.getMask().getItem(),item.data.rotationIcon.getItem(),item.data.rotationIcon.getMask().getItem()])),item.contains(item.data.deleteIcon.getItem().position)&&(item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.rotate(180,item.data.deleteIcon.getData("pivot")),item.data.deleteIcon.rotate(180)),item.contains(item.data.rotationIcon.getItem().position)&&(item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.rotate(180,item.data.rotationIcon.getData("pivot")),item.data.rotationIcon.rotate(180))}else item.data.group&&(item.data.group.remove(),item.data.group=null,overlay.paperScope.project.activeLayer.addChild(item)),item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null),item.data.rotationIcon&&(item.data.rotationIcon.remove(),item.data.rotationIcon=null),item.segments[2].handleOut=new overlay.paperScope.Point(0,0)}},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&(item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(24/overlay.paperScope.view.zoom)),item._name.toString().indexOf("rotation")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(16/overlay.paperScope.view.zoom)))},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){"create"==overlay.mode&&overlay.path?overlay.onDrawFinish():("translate"===overlay.mode||"deform"===overlay.mode&&overlay.path)&&overlay.onEditFinish()},translate:function(event,overlay){for(var i=0;i<overlay.path.segments.length;i++)overlay.path.segments[i].point.x+=event.delta.x,overlay.path.segments[i].point.y+=event.delta.y;overlay.path.data.rotationIcon.translateByXY(event.delta.x,event.delta.y),overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y)},rotate:function(event,overlay){var center=overlay.path.position,rotation=Math.atan2(event.point.y-center.y+event.delta.y,event.point.x-center.x+event.delta.x)-Math.atan2(event.point.y-center.y,event.point.x-center.x);rotation*=180/Math.PI,overlay.path.data.group.rotate(rotation,overlay.path.position),overlay.path.data.deleteIcon.rotate(-rotation),overlay.path.data.rotationIcon.rotate(-rotation),overlay.path.data.rotation+=rotation},onMouseDrag:function(event,overlay){if("translate"==overlay.mode)return void this.translate(event,overlay);if("rotate"===overlay.mode)return void this.rotate(event,overlay);if("create"==overlay.mode||"deform"==overlay.mode){for(var idx=-1,l=0;l<overlay.path.segments.length;l++)if(overlay.path.segments[l]==overlay.segment){idx=l;break}var translation=new overlay.paperScope.Point(event.delta.x,event.delta.y),rot=overlay.path.data.rotation;translation=translation.rotate(-rot);var translationX=new overlay.paperScope.Point(translation.x,0);translationX=translationX.rotate(rot);var translationY=new overlay.paperScope.Point(0,translation.y);
82
- translationY=translationY.rotate(rot),0!==idx&&4!==idx&&6!==idx&&8!==idx||(translationX=translationX.multiply(2/(1+Math.sqrt(.5))),translationY=translationY.multiply(2/(1+Math.sqrt(.5))));var moveTopSize=0===idx||1===idx||2===idx||3===idx||4===idx,moveBottomSize=6===idx||7===idx||8===idx,moveRightSize=4===idx||5===idx||6===idx,moveLeftSize=0===idx||8===idx||9===idx;if(moveTopSize){overlay.path.data.rotationIcon.translateByPoint(translationY),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationY),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationY),overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationY);var trTop=translationY.clone();trTop=trTop.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trTop),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trTop),trTop=trTop.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trTop),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trTop)}if(moveBottomSize){overlay.path.data.deleteIcon.translateByPoint(translationY),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationY);var trBottom=translationY.clone();trBottom=trBottom.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trBottom),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trBottom),trBottom=trBottom.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trBottom),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trBottom)}if((moveTopSize||moveBottomSize)&&(translationY=translationY.multiply(.5),overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationY),overlay.path.segments[9].point=overlay.path.segments[9].point.add(translationY)),moveRightSize){overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationX);var trRight=translationX.clone();trRight=trRight.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trRight),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trRight),trRight=trRight.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trRight),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trRight)}if(moveLeftSize){overlay.path.segments[9].point=overlay.path.segments[9].point.add(translationX);var trLeft=translationX.clone();trLeft=trLeft.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trLeft),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trLeft),trLeft=trLeft.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trLeft),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trLeft)}(moveRightSize||moveLeftSize)&&(translationX=translationX.multiply(.5),overlay.path.data.rotationIcon.translateByPoint(translationX),overlay.path.data.deleteIcon.translateByPoint(translationX),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationX),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationX),overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationX),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationX));var point=overlay.path.segments[2].point.clone();point=point.add(overlay.path.segments[2].handleOut),overlay.path.contains(point)&&(overlay.path.segments[2].handleOut=overlay.path.segments[2].handleOut.rotate(180,overlay.path.segments[2])),overlay.path.contains(overlay.path.data.deleteIcon.getItem().position)&&(overlay.path.data.deleteIcon.rotate(180,overlay.path.data.deleteIcon.getData("pivot")),overlay.path.data.deleteIcon.rotate(180)),overlay.path.contains(overlay.path.data.rotationIcon.getItem().position)&&(overlay.path.data.rotationIcon.rotate(180,overlay.path.data.rotationIcon.getData("pivot")),overlay.path.data.rotationIcon.rotate(180)),overlay.path.segments.length>10&&overlay.path.removeSegment(10),overlay.path.smooth({from:-7,to:1})}},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type||"handle-in"===hitResult.type||"handle-out"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1&&"deform"!=overlay.mode&&"translate"!=overlay.mode&&"create"!=overlay.mode){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return hitResult.item.data.self.onMouseDown(),void("rotate"===overlay.mode&&(overlay.path=hitResult.item.data.self.getItem().data.parent));"segment"===hitResult.type&&(overlay.mode="deform",overlay.segment=null,overlay.path=null,this.setCursor(hitResult,overlay)),"stroke"!==hitResult.type&&"handle-in"!==hitResult.type&&"handle-out"!==hitResult.type||(overlay.mode="translate",overlay.segment=null,overlay.path=null)}return"translate"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):overlay.path=hitResult.item):"deform"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):(overlay.path=hitResult.item,overlay.segment=hitResult.segment)):void(overlay.path=this.createShape(event.point,overlay))},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.Freehand=function(options){jQuery.extend(this,{name:"Freehand",logoClass:"gesture",idPrefix:"smooth_path_",tooltip:"freehandTooltip"},options),this.init()},$.Freehand.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var _this=this,shape=new overlay.paperScope.Path({segments:[initialPoint],dashArray:overlay.dashArray,strokeColor:overlay.strokeColor,name:overlay.getName(_this)});return shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape},updateSelection:function(selected,item,overlay){item._name.toString().indexOf(this.idPrefix)!==-1&&(item.selected=selected,selected?item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(item))),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.deleteIcon.setOnMouseDownListener(overlay)):item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null))},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.self.resize(24/overlay.paperScope.view.zoom))},getPivotPointForDeleteIcon:function(item){for(var points=[],i=0;i<item.segments.length;i++)points.push(item.segments[i].point);return{x:this.getGeometricCenterOfPoints(points).x,y:this.getLowestPoint(points).y}},getLowestPoint:function(points){for(var lx=0,ly=0,i=0;i<points.length;i++)lx=Math.max(lx,points[i].x),ly=Math.max(ly,points[i].y);return{x:lx,y:ly}},getGeometricCenterOfPoints:function(points){for(var cx=0,cy=0,i=0;i<points.length;i++)cx+=points[i].x,cy+=points[i].y;return{x:cx/points.length,y:cy/points.length}},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){"create"===overlay.mode&&overlay.path&&(overlay.path.simplify(),overlay.onDrawFinish())},onMouseDrag:function(event,overlay){if("deform"!==overlay.mode)return"translate"===overlay.mode?void(overlay.path&&(overlay.path.position.x+=event.delta.x,overlay.path.position.y+=event.delta.y,overlay.path.data.deleteIcon&&overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y))):void("create"===overlay.mode&&(overlay.path.add(event.point),overlay.path.data.deleteIcon&&(overlay.path.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(overlay.path))),overlay.path.data.deleteIcon.setPosition(overlay.path.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))))));if(overlay.segment){overlay.segment.point.x+=event.delta.x,overlay.segment.point.y+=event.delta.y,overlay.path.smooth();var path=overlay.segment.path;path.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(path))),path.data.deleteIcon.setPosition(path.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom)))}},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"handle-in"===hitResult.type||"handle-out"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return void hitResult.item.data.self.onMouseDown();if("create"!==overlay.mode){if("stroke"===hitResult.type)return overlay.mode="translate",void(overlay.path=hitResult.item);if("segment"===hitResult.type||"handle-out"===hitResult.type||"handle-in"===hitResult.type)return event.modifiers.shift&&hitResult.item.segments.length>2?void hitResult.segment.remove():(overlay.mode="deform",overlay.segment=hitResult.segment,void(overlay.path=hitResult.item))}}else"create"!==overlay.mode&&(overlay.mode="");if(""===overlay.mode)return void(overlay.path=this.createShape(event.point,overlay))},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.getTools=function(options){return this.svgOverlayTools?this.svgOverlayTools:(options.partOfPrefix="_partOf",this.svgOverlayTools=[new $.Rectangle(options),new $.Freehand(options),new $.Polygon(options),new $.Ellipse(options),new $.Pin(options)],this.svgOverlayTools)},OpenSeadragon.Viewer.prototype.svgOverlay=function(osdViewerId,windowId,state,eventEmitter){return new $.Overlay(this,osdViewerId,windowId,state,eventEmitter)};var FILL_COLOR_ALPHA_WORKAROUND=1e-5;$.Overlay=function(viewer,osdViewerId,windowId,state,eventEmitter){var drawingToolsSettings=state.getStateProperty("drawingToolsSettings");this.drawingToolsSettings=drawingToolsSettings;var availableAnnotationDrawingTools=state.getStateProperty("availableAnnotationDrawingTools"),availableExternalCommentsPanel=state.getStateProperty("availableExternalCommentsPanel");jQuery.extend(this,{disabled:!0,inEditOrCreateMode:!1,osdViewerId:osdViewerId,windowId:windowId,commentPanel:null,mode:"",draftPaths:[],editedPaths:[],hoveredPath:null,path:null,segment:null,latestMouseDownTime:-1,doubleClickReactionTime:drawingToolsSettings.doubleClickReactionTime,availableAnnotationDrawingTools:availableAnnotationDrawingTools,availableExternalCommentsPanel:availableExternalCommentsPanel,dashArray:[],fixedShapeSize:drawingToolsSettings.fixedShapeSize,selectedColor:drawingToolsSettings.selectedColor||"#004c66",shapeHandleSize:drawingToolsSettings.shapeHandleSize,partOfPrefix:"_partOf",hitOptions:{handles:!0,stroke:!0,segments:!0,tolerance:5}}),this.tools=$.getTools(drawingToolsSettings),this.currentTool=null,this.dashArray=[],this.strokeColor=drawingToolsSettings.strokeColor,this.fillColor=drawingToolsSettings.fillColor,this.fillColorAlpha=drawingToolsSettings.fillColorAlpha,this.viewer=viewer,this.canvas=document.createElement("canvas"),jQuery(this.canvas).attr("tabindex","0").mousedown(function(){jQuery(this).focus()}),this.canvas.id="draw_canvas_"+this.windowId,this.viewer.canvas.appendChild(this.canvas);this.slotWindowElement=state.getWindowElement(this.windowId),this.state=state,this.eventEmitter=eventEmitter,this.eventsSubscriptions=[],this.resize(),this.show(),this.init()},$.Overlay.prototype={init:function(){var _this=this;this.lastAngle=0,this.paperScope=new paper.PaperScope,this.paperScope.setup("draw_canvas_"+_this.windowId),this.paperScope.activate(),this.paperScope.project.options.handleSize=_this.state.getStateProperty("shapeHandleSize"),jQuery(_this.canvas).attr("keepalive","true"),this.annotationUtils=new $.AnnotationUtils,this.paperScope.view.onFrame=function(event){if(_this.paperScope.snapPoint&&(_this.paperScope.snapPoint.remove(),_this.paperScope.snapPoint=null),_this.path&&!_this.path.closed&&_this.cursorLocation&&_this.currentTool&&_this.currentTool.idPrefix.indexOf("rough_path_")!=-1){var distanceToFirst=_this.path.segments[0].point.getDistance(_this.cursorLocation);_this.path.segments.length>1&&distanceToFirst<_this.hitOptions.tolerance&&(_this.paperScope.snapPoint=new _this.paperScope.Path.Circle({name:"snapPoint",center:_this.path.segments[0].point,radius:_this.hitOptions.tolerance/_this.paperScope.view.zoom,fillColor:_this.path.strokeColor,strokeColor:_this.path.strokeColor}))}},this.mouseToolKey="draw_canvas_"+_this.windowId,this.setMouseTool(),this.listenForActions()},setMouseTool:function(){this.removeMouseTool();var mouseTool=new this.paperScope.Tool;mouseTool.overlay=this,mouseTool.onMouseUp=this.onMouseUp,mouseTool.onMouseDrag=this.onMouseDrag,mouseTool.onMouseMove=this.onMouseMove,mouseTool.onMouseDown=this.onMouseDown,mouseTool.onDoubleClick=this.onDoubleClick,mouseTool.onKeyDown=function(event){},jQuery.data(document.body,this.mouseToolKey,mouseTool)},removeMouseTool:function(){var mouseTool=jQuery.data(document.body,this.mouseToolKey);mouseTool&&(mouseTool.remove(),jQuery.removeData(document.body,this.mouseToolKey))},handleDeleteShapeEvent:function(event,shape){var _this=this;new $.DialogBuilder(this.slotWindowElement).dialog({message:i18next.t("deleteShape"),closeButton:!1,className:"mirador-dialog",buttons:{no:{label:i18next.t("no"),className:"btn-default",callback:function(){}},yes:{label:i18next.t("yes"),className:"btn-primary",callback:function(){_this.deleteShape(shape)}}}})},listenForActions:function(){var _this=this;this._thisResize=function(){_this.resize()},this._thisRotate=function(event){_this.rotate(event),_this.resize()},this.viewer.addHandler("animation",this._thisResize),this.viewer.addHandler("open",this._thisResize),this.viewer.addHandler("animation-finish",this._thisResize),this.viewer.addHandler("update-viewport",this._thisResize),this.viewer.addHandler("resize",this._thisResize),this.viewer.addHandler("rotate",this._thisRotate),this.viewer.addHandler("constrain",this._thisResize),this._thisDestroy=function(){_this.destroy()},this.viewer.addHandler("close",this._thisDestroy),this.eventsSubscriptions.push(this.eventEmitter.subscribe("DESTROY_EVENTS."+this.windowId,function(event){_this.destroy()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("toggleDrawingTool."+_this.windowId,function(event,tool){if(!_this.disabled){_this.currentTool=null,_this.mode="";for(var i=0;i<_this.tools.length;i++)_this.tools[i].logoClass===tool&&(_this.currentTool=_this.tools[i])}}));var _thisHandleDeleteShapeEvent=function(event,shape){_this.handleDeleteShapeEvent(event,shape)};this.eventsSubscriptions.push(_this.eventEmitter.subscribe("deleteShape."+_this.windowId,_thisHandleDeleteShapeEvent)),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("changeBorderColor."+_this.windowId,function(event,color){_this.strokeColor=color,_this.hoveredPath&&(_this.hoveredPath.strokeColor=color,_this.paperScope.view.draw())})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("changeFillColor."+_this.windowId,function(event,color,alpha){_this.fillColor=color,0===alpha&&(alpha=FILL_COLOR_ALPHA_WORKAROUND),_this.fillColorAlpha=alpha,_this.hoveredPath&&_this.hoveredPath.closed&&(_this.hoveredPath.fillColor=color,_this.hoveredPath.fillColor.alpha=alpha,_this.paperScope.view.draw())})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("toggleBorderType."+_this.windowId,function(event,type){"solid"==type?_this.dashArray=[]:"dashed"==type?_this.dashArray=[5,5]:"dotdashed"==type&&(_this.dashArray=[2,5,7,5]),_this.hoveredPath&&(_this.hoveredPath.dashArray=_this.dashArray,_this.paperScope.view.draw())})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("annotationEditSave."+_this.windowId,function(event,oaAnno){var onAnnotationSaved=jQuery.Deferred();if(_this.draftPaths.length){var writeStrategy=new $.MiradorDualStrategy;writeStrategy.buildAnnotation({annotation:oaAnno,window:_this.state.getWindowObjectById(_this.windowId),overlay:_this}),_this.eventEmitter.publish("annotationUpdated."+_this.windowId,[oaAnno]),onAnnotationSaved.resolve()}else new $.DialogBuilder(_this.slotWindowElement).dialog({message:i18next.t("editModalSaveAnnotationWithNoShapesMsg"),closeButton:!1,className:"mirador-dialog",buttons:{success:{label:i18next.t("editModalBtnSaveWithoutShapes"),className:"btn-success",callback:function(){oaAnno.on={"@type":"oa:SpecificResource",full:_this.state.getWindowObjectById(_this.windowId).canvasID},_this.eventEmitter.publish("annotationUpdated."+_this.windowId,[oaAnno]),onAnnotationSaved.resolve()}},danger:{label:i18next.t("editModalBtnDeleteAnnotation"),className:"btn-danger",callback:function(){_this.eventEmitter.publish("annotationDeleted."+_this.windowId,[oaAnno["@id"]]),onAnnotationSaved.resolve()}},main:{label:i18next.t("cancel"),className:"btn-default",callback:function(){onAnnotationSaved.reject()}}}});jQuery.when(onAnnotationSaved.promise()).then(function(){_this.eventEmitter.publish("annotationEditSaveSuccessful."+_this.windowId),_this.eventEmitter.publish("SET_ANNOTATION_EDITING."+_this.windowId,{annotationId:oaAnno["@id"],isEditable:!1,tooltip:_this}),_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId)},function(){})})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("annotationEditCancel."+_this.windowId,function(event,id){_this.eventEmitter.publish("SET_ANNOTATION_EDITING."+_this.windowId,{annotationId:id,isEditable:!1,tooltip:_this.annoTooltip}),_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("clearDraftPaths."+_this.windowId,function(){_this.clearDraftData()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("onAnnotationCreated."+_this.windowId,function(event,oaAnno){for(var i=0;i<_this.draftPaths.length;i++)_this.draftPaths[i].data&&_this.draftPaths[i].data.newlyCreated&&(_this.draftPaths[i].strokeWidth/=_this.draftPaths[i].data.newlyCreatedStrokeFactor,_this.draftPaths[i].data.currentStrokeValue/=_this.draftPaths[i].data.newlyCreatedStrokeFactor,delete _this.draftPaths[i].data.newlyCreated,delete _this.draftPaths[i].data.newlyCreatedStrokeFactor);var writeStrategy=new $.MiradorDualStrategy;writeStrategy.buildAnnotation({annotation:oaAnno,window:_this.state.getWindowObjectById(_this.windowId),overlay:_this}),_this.eventEmitter.publish("annotationCreated."+_this.windowId,[oaAnno,function(){_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId),_this.eventEmitter.publish("enableTooltips."+_this.windowId),_this.clearDraftData(),_this.annoTooltip=null,_this.annoEditorVisible=!1}])})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("onAnnotationCreatedCanceled."+_this.windowId,function(event,cancelCallback,immediate){var cancel=function(){_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId),_this.clearDraftData(),_this.annoTooltip=null,_this.annoEditorVisible=!1};immediate?cancel():new $.DialogBuilder(_this.slotWindowElement).dialog({message:i18next.t("cancelAnnotation"),closeButton:!1,className:"mirador-dialog",buttons:{no:{label:i18next.t("no"),className:"btn-default",callback:function(){}},yes:{label:i18next.t("yes"),className:"btn-primary",callback:function(){cancel(),cancelCallback&&cancelCallback()}}}})})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("onAnnotationDeleted."+_this.windowId,function(event,id,callback){_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("annotationDeleted."+_this.windowId,[id]),_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId),callback&&callback()})),this.eventsSubscriptions.push(this.eventEmitter.subscribe("SET_OVERLAY_TOOLTIP."+this.windowId,function(event,options){_this.annoTooltip=options.tooltip,_this.annoEditorVisible=options.visible,_this.draftPaths=options.paths})),this.eventsSubscriptions.push(this.eventEmitter.subscribe("CANCEL_ACTIVE_ANNOTATIONS."+this.windowId,function(event){_this.clearDraftData(),_this.annoTooltip=null,_this.annoEditorVisible=!1})),this.eventsSubscriptions.push(this.eventEmitter.subscribe("ANNOTATIONS_LIST_UPDATED",function(event,options){options.windowId&&_this.eventEmitter.publish("refreshOverlay."+_this.windowId)}))},deleteShape:function(shape){for(var i=0;i<this.draftPaths.length;i++)if(this.draftPaths[i]._name.toString()===shape._name.toString()){this.draftPaths.splice(i,1);break}this.removeFocus(),shape.remove()},getMousePositionInImage:function(mousePosition){return mousePosition.x<0&&(mousePosition.x=0),mousePosition.x>this.viewer.tileSources.width&&(mousePosition.x=this.viewer.tileSources.width),mousePosition.y<0&&(mousePosition.y=0),mousePosition.y>this.viewer.tileSources.height&&(mousePosition.y=this.viewer.tileSources.height),mousePosition},adjustDeltaForShape:function(lastPoint,currentPoint,delta,bounds){return lastPoint.x<currentPoint.x?bounds.x+bounds.width>this.viewer.tileSources.width&&(delta.x=this.viewer.tileSources.width-(bounds.x+bounds.width)):bounds.x<0&&(delta.x=Math.abs(bounds.x)),lastPoint.y<currentPoint.y?bounds.y+bounds.height>this.viewer.tileSources.height&&(delta.y=this.viewer.tileSources.height-(bounds.y+bounds.height)):bounds.y<0&&(delta.y=Math.abs(bounds.y)),delta},onMouseUp:function(event){this.overlay.disabled||(event.stopPropagation(),this.overlay.currentTool&&this.overlay.currentTool.onMouseUp(event,this.overlay))},onMouseDrag:function(event){if(this.overlay.disabled){var absolutePoint={x:event.event.clientX,y:event.event.clientY};this.overlay.eventEmitter.publish("updateTooltips."+this.overlay.windowId,[event.point,absolutePoint])}else if(event.stopPropagation(),this.overlay.currentTool){if("Freehand"===this.overlay.currentTool.name&&"create"===this.overlay.mode)event.point=this.overlay.getMousePositionInImage(event.point),event.delta=event.point-event.lastPoint;else if(this.overlay.path){var bounds=this.overlay.path.bounds;event.delta=this.overlay.adjustDeltaForShape(event.lastPoint,event.point,event.delta,bounds)}this.overlay.currentTool.onMouseDrag(event,this.overlay)}this.overlay.paperScope.view.draw()},onMouseMove:function(event){if(this.overlay.disabled){var absolutePoint={x:event.event.clientX,y:event.event.clientY};this.overlay.eventEmitter.publish("updateTooltips."+this.overlay.windowId,[event.point,absolutePoint])}else this.overlay.paperScope.project.hitTest(event.point,this.overlay.hitOptions)?this.overlay.eventEmitter.publish("POINTER_CURSOR."+this.overlay.windowId):this.overlay.currentTool&&!this.overlay.path?this.overlay.eventEmitter.publish("CROSSHAIR_CURSOR."+this.overlay.windowId):this.overlay.eventEmitter.publish("DEFAULT_CURSOR."+this.overlay.windowId),event.stopPropagation(),this.overlay.currentTool&&this.overlay.currentTool.onMouseMove(event,this.overlay);this.overlay.paperScope.view.draw()},onMouseDown:function(event){if(!this.overlay.disabled){event.stopPropagation();var date=new Date,time=date.getTime();if(time-this.overlay.latestMouseDownTime<this.overlay.doubleClickReactionTime)this.overlay.latestMouseDownTime=time,this.onDoubleClick(event);else{this.overlay.latestMouseDownTime=time;var hitResult=this.overlay.paperScope.project.hitTest(event.point,this.overlay.hitOptions);if("create"!==this.overlay.mode&&""!==this.overlay.mode&&(this.overlay.mode="",this.overlay.currentTool=null),hitResult&&"create"!==this.overlay.mode){var overlayEditable=!1;if("undefined"!=typeof hitResult.item.data.editable&&(overlayEditable=hitResult.item.data.editable),hitResult.item._name.toString().indexOf(this.overlay.partOfPrefix)!==-1&&(overlayEditable=!0),!overlayEditable)return}if(hitResult&&(!this.overlay.currentTool||hitResult.item._name.toString().indexOf(this.overlay.currentTool.idPrefix)===-1&&""===this.overlay.mode)){var prefix=hitResult.item._name.toString();prefix=prefix.substring(0,prefix.indexOf("_")+1);var longPrefix=hitResult.item._name.toString().split("_");longPrefix=longPrefix[0]+"_"+longPrefix[1]+"_";for(var j=0;j<this.overlay.tools.length;j++)if(this.overlay.tools[j].idPrefix===prefix||this.overlay.tools[j].idPrefix===longPrefix){this.overlay.eventEmitter.publish("toggleDrawingTool."+this.overlay.windowId,this.overlay.tools[j].logoClass);break}}this.overlay.currentTool&&(this.overlay.eventEmitter.publish("HUD_REMOVE_CLASS."+this.overlay.windowId,[".hud-dropdown","hud-disabled"]),event.point=this.overlay.getMousePositionInImage(event.point),this.overlay.currentTool.onMouseDown(event,this.overlay))}this.overlay.hover(),this.overlay.paperScope.view.draw()}},onDoubleClick:function(event){event.stopPropagation(),this.overlay.currentTool&&this.overlay.currentTool.onDoubleClick(event,this.overlay)},fitFixedSizeShapes:function(shape){if(shape.data.fixedSize=!0,shape.name.toString().indexOf("pin_")!=-1){var scale=1/shape.bounds.width;scale*=this.fixedShapeSize/this.paperScope.view.zoom,shape.scale(scale,shape.segments[0].point)}},updateSelection:function(selected,item){if(item&&item._name){var shapeTool=this.getTool(item);shapeTool&&(item.selectedColor=this.selectedColor,shapeTool.updateSelection(selected,item,this))}},rotate:function(event){this.paperScope&&this.paperScope.view&&(this.paperScope.view._matrix.rotate(event.degrees-this.lastAngle,this.paperScope.view.center),this.lastAngle=event.degrees)},resize:function(){var viewportBounds=this.viewer.viewport.getBounds(!0);this.canvas.width=this.viewer.viewport.containerSize.x,this.canvas.height=this.viewer.viewport.containerSize.y;var transform="translate(0px,0px)";if(this.canvas.style.WebkitTransform=transform,this.canvas.style.msTransform=transform,this.canvas.style.transform=transform,this.canvas.style.marginLeft="0px",this.canvas.style.marginTop="0px",this.paperScope&&this.paperScope.view){this.paperScope.view.viewSize=new this.paperScope.Size(this.canvas.width,this.canvas.height),this.paperScope.view.zoom=this.viewer.viewport.viewportToImageZoom(this.viewer.viewport.getZoom(!0)),this.paperScope.view.center=new this.paperScope.Size(this.viewer.world.getItemAt(0).source.dimensions.x*viewportBounds.x+this.paperScope.view.bounds.width/2,this.viewer.world.getItemAt(0).source.dimensions.x*viewportBounds.y+this.paperScope.view.bounds.height/2),this.paperScope.view.update(!0);for(var allItems=this.paperScope.project.getItems({name:/_/}),j=0;j<allItems.length;j++)allItems[j].data.fixedSize&&this.fitFixedSizeShapes(allItems[j]),this.getTool(allItems[j]).onResize&&this.getTool(allItems[j]).onResize(allItems[j],this),allItems[j].strokeWidth=allItems[j].data.currentStrokeValue/this.paperScope.view.zoom,allItems[j].style&&(allItems[j].style.strokeWidth=allItems[j].data.currentStrokeValue/this.paperScope.view.zoom)}},hover:function(){if(this.currentTool)if(!this.currentTool&&this.hoveredPath&&(this.updateSelection(!1,this.hoveredPath),this.hoveredPath=null),this.hoveredPath){if(this.hoveredPath._name.toString().indexOf(this.currentTool.idPrefix)===-1&&(this.updateSelection(!1,this.hoveredPath),this.hoveredPath=null),this.path&&this.path._name.toString().indexOf(this.currentTool.idPrefix)!==-1){if(this.currentTool.partOfPrefix&&this.path._name.toString().indexOf(this.currentTool.partOfPrefix)!==-1)return;if(this.hoveredPath){if(this.hoveredPath._name.toString()===this.path._name.toString())return;this.updateSelection(!1,this.hoveredPath)}this.hoveredPath=this.path,this.updateSelection(!0,this.hoveredPath)}}else this.path&&this.path._name.toString().indexOf(this.currentTool.idPrefix)!=-1&&(this.hoveredPath=this.path,this.updateSelection(!0,this.hoveredPath))},removeFocus:function(){this.hoveredPath&&(this.updateSelection(!1,this.hoveredPath),this.hoveredPath=null),this.path&&(this.updateSelection(!1,this.path),this.path=null)},restoreEditedShapes:function(){this.editedPaths=[],this.removeFocus()},restoreDraftShapes:function(){this.clearDraftData(),this.removeFocus()},getTool:function(shape){for(var i=0;i<this.tools.length;i++)if(shape.name.toString().indexOf(this.tools[i].idPrefix)!==-1)return this.tools[i]},replaceShape:function(shape,annotation){var shapeTool=this.getTool(shape);shapeTool&&shapeTool.SEGMENT_POINTS_COUNT&&shapeTool.SEGMENT_POINTS_COUNT!==shape.segments.length&&shapeTool.adaptSegments(shape,this);var cloned=new this.paperScope.Path({segments:shape.segments,name:shape.name});return cloned.data.defaultStrokeValue=1,cloned.data.editStrokeValue=5,cloned.data.currentStrokeValue=cloned.data.defaultStrokeValue,cloned.strokeWidth=cloned.data.currentStrokeValue/this.paperScope.view.zoom,cloned.strokeColor=shape.strokeColor,cloned.dashArray=shape.dashArray,shape.fillColor&&(cloned.fillColor=shape.fillColor,0===shape.fillColor.alpha&&(shape.fillColor.alpha=FILL_COLOR_ALPHA_WORKAROUND),shape.fillColor.alpha&&(cloned.fillColor.alpha=shape.fillColor.alpha)),cloned.closed=shape.closed,cloned.data.rotation=shape.data.rotation,cloned.data.fixedSize=shape.data.fixedSize,cloned.data.annotation=annotation,cloned.data.fixedSize&&this.fitFixedSizeShapes(cloned),shape.remove(),cloned},createRectangle:function(shape,annotation){var paperItems=[],rect=new $.Rectangle,initialPoint={x:shape.x,y:shape.y},currentMode=this.mode,currentPath=this.path,strokeColor=this.strokeColor,fillColor=this.fillColor,fillColorAlpha=this.fillColorAlpha||FILL_COLOR_ALPHA_WORKAROUND;this.strokeColor=this.state.getStateProperty("drawingToolsSettings").strokeColor,this.fillColor=this.state.getStateProperty("drawingToolsSettings").fillColor,this.fillColorAlpha=this.state.getStateProperty("drawingToolsSettings").fillColorAlpha||FILL_COLOR_ALPHA_WORKAROUND,
83
- this.mode="create",this.path=rect.createShape(initialPoint,this);var eventData={delta:{x:shape.width,y:shape.height}};return rect.onMouseDrag(eventData,this),paperItems.push(this.path),paperItems[0].data.annotation=annotation,this.updateSelection(!1,paperItems[0]),this.strokeColor=strokeColor,this.fillColor=fillColor,this.fillColorAlpha=fillColorAlpha,this.path=currentPath,this.mode=currentMode,paperItems},parseSVG:function(svg,annotation){var paperItems=[],svgParser=new DOMParser,svgDOM=svgParser.parseFromString(svg,"text/xml");if("parsererror"!=svgDOM.documentElement.nodeName){var svgTag=this.paperScope.project.importSVG(svg),body=svgTag.removeChildren()[0];if(svgTag.remove(),"Group"==body.className){for(var items=body.removeChildren(),itemIdx=0;itemIdx<items.length;itemIdx++)paperItems.push(this.replaceShape(items[itemIdx],annotation));body.remove()}else paperItems.push(this.replaceShape(body,annotation));return this.paperScope.view.update(!0),paperItems}},restoreLastView:function(shapeArray){for(var i=0;i<this.editedPaths.length;i++)for(var idx=0;idx<shapeArray.length;idx++)shapeArray[idx].name==this.editedPaths[i].name&&(shapeArray[idx].segments=this.editedPaths[i].segments,shapeArray[idx].name=this.editedPaths[i].name,shapeArray[idx].strokeWidth=shapeArray[idx].data.currentStrokeValue/this.paperScope.view.zoom,shapeArray[idx].strokeColor=this.editedPaths[i].strokeColor,shapeArray[idx].dashArray=this.editedPaths[i].dashArray,this.editedPaths[i].fillColor&&(shapeArray[idx].fillColor=this.editedPaths[i].fillColor,this.editedPaths[i].fillColor.alpha&&(shapeArray[idx].fillColor.alpha=this.editedPaths[i].fillColor.alpha)),this.editedPaths[i].style&&(shapeArray[idx].style=this.editedPaths[i].style,shapeArray[idx].style.strokeWidth=shapeArray[idx].data.currentStrokeValue/this.paperScope.view.zoom),shapeArray[idx].closed=this.editedPaths[i].closed,shapeArray[idx].data.rotation=this.editedPaths[i].data.rotation,shapeArray[idx].data.fixedSize=this.editedPaths[i].data.fixedSize,shapeArray[idx].data.annotation=this.editedPaths[i].data.annotation,shapeArray[idx].data.fixedSize&&this.fitFixedSizeShapes(shapeArray[idx]))},deselectAll:function(){this.paperScope&&this.paperScope.view&&this.paperScope.project&&(this.paperScope.project.deselectAll(),this.paperScope.view.update(!0),this.destroyCommentPanel())},hide:function(){this.canvas.style.display="none",this.deselectAll()},show:function(){this.canvas.style.display="block"},checkToRemoveFocus:function(){this.currentTool="",this.inEditOrCreateMode&&this.path&&this.removeFocus()},disable:function(){this.disabled=!0,this.inEditOrCreateMode=!1,this.eventEmitter.publish("enableTooltips."+this.windowId),this.deselectAll()},enableEdit:function(){this.disabled=!1,this.inEditOrCreateMode=!0,this.eventEmitter.publish("disableTooltips."+this.windowId)},enable:function(){this.disabled=!1,this.eventEmitter.publish("disableTooltips."+this.windowId)},refresh:function(){this.paperScope.view.update(!0)},destroyCommentPanel:function(){this.eventEmitter.publish("removeTooltips."+this.windowId),jQuery(this.canvas).parents(".mirador-osd").qtip("destroy",!0),this.commentPanel=null},getName:function(tool){return tool.idPrefix+$.genUUID()},getSVGString:function(shapes){var svg="<svg xmlns='http://www.w3.org/2000/svg'>";if(shapes.length>1){svg+="<g>";for(var i=0;i<shapes.length;i++){this.updateSelection(!1,shapes[i]),shapes[i].data.fixedSize&&this.fitFixedSizeShapes(shapes[i]);var anno=shapes[i].data.annotation;shapes[i].data.annotation=null,svg+=shapes[i].exportSVG({asString:!0}),shapes[i].data.annotation=anno}svg+="</g>"}else{this.updateSelection(!1,shapes[0]),shapes[0].data.fixedSize&&this.fitFixedSizeShapes(shapes[0]);var annoSingle=shapes[0].data.annotation;shapes[0].data.annotation=null,svg+=shapes[0].exportSVG({asString:!0}),shapes[0].data.annotation=annoSingle}return svg+="</svg>"},onDrawFinish:function(){var shape=this.path;if(shape){this.inEditOrCreateMode=!0,this.hoveredPath&&this.updateSelection(!1,this.hoveredPath);var newlyCreatedStrokeFactor=this.drawingToolsSettings.newlyCreatedShapeStrokeWidthFactor||5;if(shape.data.newlyCreatedStrokeFactor=newlyCreatedStrokeFactor,shape.data.newlyCreated=!0,shape.data.currentStrokeValue*=newlyCreatedStrokeFactor,shape.strokeWidth*=newlyCreatedStrokeFactor,this.hoveredPath=shape,this.segment=null,this.path=null,this.mode="",this.draftPaths.push(shape),shape.data.editable=!0,this.updateSelection(!0,this.hoveredPath),"undefined"!=typeof this.annoTooltip&&this.annoTooltip||(this.annoTooltip=new $.AnnotationTooltip({targetElement:jQuery(this.canvas).parents(".mirador-osd"),state:this.state,eventEmitter:this.eventEmitter,windowId:this.windowId})),this.availableExternalCommentsPanel)return void this.eventEmitter.publish("annotationShapeCreated."+this.windowId,[this,shape]);var _this=this;"undefined"!=typeof this.annoEditorVisible&&this.annoEditorVisible||(this.annoTooltip.showEditor({annotation:{},onSaveClickCheck:function(){return _this.draftPaths.length},onAnnotationCreated:function(oaAnno){_this.eventEmitter.publish("onAnnotationCreated."+_this.windowId,[oaAnno])}}),_this.annoEditorVisible=!0)}},onEditFinish:function(){var _this=this;jQuery.each(this.draftPaths,function(index,value){_this.path.name===value.name&&(_this.draftPaths[index]=_this.path)})},clearDraftData:function(){for(var _this=this,idx=0;idx<_this.draftPaths.length;idx++)_this.updateSelection(!1,this.draftPaths[idx]),_this.draftPaths[idx].remove();_this.draftPaths=[],_this.path&&_this.path.remove(),_this.paperScope.view.update(!0),_this.hoveredPath=null,_this.segment=null,_this.path=null,_this.mode=""},destroy:function(){var _this=this;this.eventsSubscriptions.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)}),this.viewer.removeHandler("animation",this._thisResize),this.viewer.removeHandler("open",this._thisResize),this.viewer.removeHandler("animation-finish",this._thisResize),this.viewer.removeHandler("update-viewport",this._thisResize),this.viewer.removeHandler("resize",this._thisResize),this.viewer.removeHandler("rotate",this._thisResize),this.viewer.removeHandler("constrain",this._thisResize),this.viewer.removeHandler("close",this._thisDestroy)}}}(Mirador),function($){$.Pin=function(options){jQuery.extend(this,{name:"Pin",logoClass:"room",idPrefix:"pin_",tooltip:"pinTooltip"},options),this.init()},$.Pin.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var _this=this,size=overlay.fixedShapeSize,pathData="";pathData+="M"+initialPoint.x+","+initialPoint.y,pathData+=" Q"+initialPoint.x+","+(initialPoint.y-size),pathData+=" "+(initialPoint.x+size)+","+(initialPoint.y-2*size),pathData+=" A"+size+","+size+" 0 1 0",pathData+=" "+(initialPoint.x-size)+","+(initialPoint.y-2*size),pathData+=" Q"+initialPoint.x+","+(initialPoint.y-size),pathData+=" "+initialPoint.x+","+initialPoint.y;var shape=new overlay.paperScope.Path(pathData);return shape.name=overlay.getName(_this),shape.dashArray=overlay.dashArray,shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape.strokeColor=overlay.strokeColor,shape.fillColor=overlay.fillColor,shape.fillColor.alpha=overlay.fillColorAlpha,shape.closed=!0,overlay.fitFixedSizeShapes(shape),shape},updateSelection:function(selected,item,overlay){item._name.toString().indexOf(this.idPrefix)!==-1&&(selected?(item.strokeColor=overlay.selectedColor,item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",item.segments[0].point),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.deleteIcon.setOnMouseDownListener(overlay))):(item.strokeColor=overlay.strokeColor,item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null)))},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&item._name.toString().indexOf("delete")&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.self.resize(24/overlay.paperScope.view.zoom))},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){},onMouseDrag:function(event,overlay){"translate"===overlay.mode&&overlay.path&&(overlay.path.position.x+=event.delta.x,overlay.path.position.y+=event.delta.y,overlay.path.data.deleteIcon&&overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y))},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type||"handle-in"===hitResult.type||"handle-out"===hitResult.type||"segment"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void 0},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return void hitResult.item.data.self.onMouseDown();"translate"!==overlay.mode&&(overlay.mode="translate",overlay.segment=null,overlay.path=null)}return"translate"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):overlay.path=hitResult.item):(overlay.path=this.createShape(event.point,overlay),void overlay.onDrawFinish())},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.Polygon=function(options){jQuery.extend(this,{name:"Polygon",logoClass:"timeline",idPrefix:"rough_path_",tooltip:"polygonTooltip"},options),this.init()},$.Polygon.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var _this=this,shape=new overlay.paperScope.Path({segments:[initialPoint],dashArray:overlay.dashArray,strokeColor:overlay.strokeColor,name:overlay.getName(_this)});return shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape},updateSelection:function(selected,item,overlay){item._name.toString().indexOf(this.idPrefix)!=-1&&(item.selected=selected,selected?item.data.deleteIcon||"create"===overlay.mode||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(item))),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.deleteIcon.setOnMouseDownListener(overlay)):item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null))},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.self.resize(24/overlay.paperScope.view.zoom))},getPivotPointForDeleteIcon:function(item){for(var points=[],i=0;i<item.segments.length;i++)points.push(item.segments[i].point);return{x:this.getGeometricCenterOfPoints(points).x,y:this.getLowestPoint(points).y}},getLowestPoint:function(points){for(var lx=0,ly=0,i=0;i<points.length;i++)lx=Math.max(lx,points[i].x),ly=Math.max(ly,points[i].y);return{x:lx,y:ly}},getGeometricCenterOfPoints:function(points){for(var cx=0,cy=0,i=0;i<points.length;i++)cx+=points[i].x,cy+=points[i].y;return{x:cx/points.length,y:cy/points.length}},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){},onMouseDrag:function(event,overlay){if("deform"===overlay.mode&&overlay.segment){overlay.segment.point.x+=event.delta.x,overlay.segment.point.y+=event.delta.y;var path=overlay.segment.path;return void(path.data.deleteIcon&&(path.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(path))),path.data.deleteIcon.setPosition(path.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom)))))}"translate"===overlay.mode&&overlay.path&&(overlay.path.position.x+=event.delta.x,overlay.path.position.y+=event.delta.y,overlay.path.data.deleteIcon&&overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y))},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"handle-in"===hitResult.type||"handle-out"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return void hitResult.item.data.self.onMouseDown();if("create"!==overlay.mode){if(overlay.path?document.body.style.cursor="default":(overlay.mode="edit",overlay.segment=null,overlay.path=null,document.body.style.cursor="move"),"stroke"===hitResult.type)return overlay.mode="translate",void(overlay.path=hitResult.item);if("segment"===hitResult.type)return event.modifiers.shift&&hitResult.item.segments.length>2?void hitResult.segment.remove():(overlay.mode="deform",overlay.segment=hitResult.segment,void(overlay.path=hitResult.item))}}else"create"!==overlay.mode&&(overlay.mode="");return""===overlay.mode?void(overlay.path=this.createShape(event.point,overlay)):"create"===overlay.mode?void overlay.path.add(event.point):void 0},onDoubleClick:function(event,overlay){"create"===overlay.mode&&overlay.path&&overlay.path.segments.length>1&&(overlay.path.segments[0].point.getDistance(overlay.path.segments[overlay.path.segments.length-1].point)*overlay.paperScope.view.zoom<overlay.hitOptions.tolerance&&(overlay.path.closed=!0,overlay.path.fillColor=overlay.fillColor,overlay.path.fillColor.alpha=overlay.fillColorAlpha,overlay.path.segments[overlay.path.segments.length-1].remove()),overlay.onDrawFinish())}}}(Mirador),function($){$.Rectangle=function(options){jQuery.extend(this,{name:"Rectangle",logoClass:"check_box_outline_blank",idPrefix:"rectangle_",tooltip:"rectangleTooltip"},options),this.init()},$.Rectangle.prototype={init:function(){this.SEGMENT_POINTS_COUNT=9},createShape:function(initialPoint,overlay){overlay.mode="create";var pixel=1/overlay.paperScope.view.zoom,segments=this._createSegments(initialPoint,pixel,overlay),shape=new overlay.paperScope.Path({segments:segments,fullySelected:!0,name:overlay.getName(this)});return shape.dashArray=overlay.dashArray,shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape.strokeColor=overlay.strokeColor,shape.fillColor=overlay.fillColor,shape.fillColor.alpha=overlay.fillColorAlpha,shape.closed=!0,shape.data.rotation=0,overlay.segment=shape.segments[5],this.updateSelection(!0,shape,overlay),shape},_createSegments:function(initialPoint,pixel,overlay){var segments=[];return segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y-1*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y-1*pixel)),segments},updateSelection:function(selected,item,overlay){if(item._name.toString().indexOf(this.idPrefix)!=-1){if(item._name.toString().indexOf(this.partOfPrefix)!=-1)return;if(item.selected=selected,selected){item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",item.segments[6].point),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.setOnMouseDownListener(overlay)),item.data.rotationIcon||(item.data.rotationIcon=new overlay.annotationUtils.RotationIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"rotation",fillColor:item.selectedColor}),item.data.rotationIcon.addData("pivot",item.segments[1].point),item.data.rotationIcon.addData("type","rotationIcon"),item.data.rotationIcon.addData("self",item.data.rotationIcon),item.data.rotationIcon.addData("parent",item),item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.setOnMouseDownListener(overlay)),item.data.group||(item.data.group=new overlay.annotationUtils.Group(overlay.paperScope,[item,item.data.deleteIcon.getItem(),item.data.deleteIcon.getMask().getItem(),item.data.rotationIcon.getItem(),item.data.rotationIcon.getMask().getItem()]));var point=item.segments[1].point.clone();point=point.add(item.segments[1].handleOut),item.contains(point)&&(item.segments[1].handleOut=item.segments[1].handleOut.rotate(180,item.segments[1])),item.contains(item.data.deleteIcon.getItem().position)&&(item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.rotate(180,item.data.deleteIcon.getData("pivot")),item.data.deleteIcon.rotate(180)),item.contains(item.data.rotationIcon.getItem().position)&&(item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.rotate(180,item.data.rotationIcon.getData("pivot")),item.data.rotationIcon.rotate(180)),item.segments[1].handleOut.selected=!1}else item.data.group&&(item.data.group.remove(),item.data.group=null,overlay.paperScope.project.activeLayer.addChild(item)),item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null),item.data.rotationIcon&&(item.data.rotationIcon.remove(),item.data.rotationIcon=null),item.segments[1].handleOut=new overlay.paperScope.Point(0,0)}},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},adaptSegments:function(shape,overlay){var handleSegment=shape.segments[1].clone();shape.segments.splice(1,0,handleSegment)},onMouseUp:function(event,overlay){"create"===overlay.mode&&overlay.path?overlay.onDrawFinish():("translate"===overlay.mode||"deform"===overlay.mode&&overlay.path)&&overlay.onEditFinish()},translate:function(event,overlay){for(var i=0;i<overlay.path.segments.length;i++)overlay.path.segments[i].point.x+=event.delta.x,overlay.path.segments[i].point.y+=event.delta.y;overlay.path.data.rotationIcon.translateByXY(event.delta.x,event.delta.y),overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y)},rotate:function(event,overlay){var center=overlay.path.position,rotation=Math.atan2(event.point.y-center.y+event.delta.y,event.point.x-center.x+event.delta.x)-Math.atan2(event.point.y-center.y,event.point.x-center.x);rotation*=180/Math.PI,overlay.path.data.group.rotate(rotation,overlay.path.position),overlay.path.data.deleteIcon.rotate(-rotation),overlay.path.data.rotationIcon.rotate(-rotation),overlay.path.data.rotation+=rotation},onMouseDrag:function(event,overlay){if("translate"==overlay.mode)return void this.translate(event,overlay);if("rotate"===overlay.mode)return void this.rotate(event,overlay);if("create"==overlay.mode||"deform"==overlay.mode){for(var idx=-1,l=0;l<overlay.path.segments.length;l++)if(overlay.path.segments[l]==overlay.segment){idx=l;break}var translation=new overlay.paperScope.Point(event.delta.x,event.delta.y),rot=overlay.path.data.rotation;translation=translation.rotate(-rot);var translationX=new overlay.paperScope.Point(translation.x,0);translationX=translationX.rotate(rot);var translationY=new overlay.paperScope.Point(0,translation.y);translationY=translationY.rotate(rot);var moveTopSize=0===idx||1===idx||2===idx||3===idx,moveBottomSize=5===idx||6===idx||7===idx,moveRightSize=3===idx||4===idx||5===idx,moveLeftSize=0===idx||7===idx||8===idx;moveTopSize&&(overlay.path.data.rotationIcon.translateByPoint(translationY),overlay.path.segments[0].point=overlay.path.segments[0].point.add(translationY),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationY),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationY),overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationY)),moveBottomSize&&(overlay.path.data.deleteIcon.translateByPoint(translationY),overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationY),overlay.path.segments[6].point=overlay.path.segments[6].point.add(translationY),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationY)),(moveTopSize||moveBottomSize)&&(translationY=translationY.multiply(.5),overlay.path.segments[4].point=overlay.path.segments[4].point.add(translationY),overlay.path.segments[8].point=overlay.path.segments[8].point.add(translationY)),moveRightSize&&(overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationX),overlay.path.segments[4].point=overlay.path.segments[4].point.add(translationX),overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationX)),moveLeftSize&&(overlay.path.segments[0].point=overlay.path.segments[0].point.add(translationX),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationX),overlay.path.segments[8].point=overlay.path.segments[8].point.add(translationX)),(moveRightSize||moveLeftSize)&&(translationX=translationX.multiply(.5),overlay.path.data.rotationIcon.translateByPoint(translationX),overlay.path.data.deleteIcon.translateByPoint(translationX),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationX),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationX),overlay.path.segments[6].point=overlay.path.segments[6].point.add(translationX));var point=overlay.path.segments[1].point.clone();point=point.add(overlay.path.segments[1].handleOut),overlay.path.contains(point)&&(overlay.path.segments[1].handleOut=overlay.path.segments[1].handleOut.rotate(180,overlay.path.segments[1])),overlay.path.contains(overlay.path.data.deleteIcon.getItem().position)&&(overlay.path.data.deleteIcon.rotate(180,overlay.path.data.deleteIcon.getData("pivot")),overlay.path.data.deleteIcon.rotate(180)),overlay.path.contains(overlay.path.data.rotationIcon.getItem().position)&&(overlay.path.data.rotationIcon.rotate(180,overlay.path.data.rotationIcon.getData("pivot")),overlay.path.data.rotationIcon.rotate(180))}},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&(item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(24/overlay.paperScope.view.zoom)),item._name.toString().indexOf("rotation")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(16/overlay.paperScope.view.zoom)))},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1&&"deform"!==overlay.mode&&"translate"!==overlay.mode&&"create"!==overlay.mode){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return hitResult.item.data.self.onMouseDown(),void("rotate"===overlay.mode&&(overlay.path=hitResult.item.data.self.getItem().data.parent));"segment"===hitResult.type&&(overlay.mode="deform",overlay.segment=null,overlay.path=null,this.setCursor(hitResult,overlay)),"stroke"===hitResult.type&&(overlay.mode="translate",overlay.segment=null,overlay.path=null)}return"translate"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):overlay.path=hitResult.item):"deform"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):(overlay.path=hitResult.item,overlay.segment=hitResult.segment)):void(overlay.path=this.createShape(event.point,overlay))},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.SimpleASEndpoint=function(options){jQuery.extend(this,{token:null,uri:null,url:options.url,dfd:null,annotationsList:[],idMapper:{}},options),this.init()},$.SimpleASEndpoint.prototype={init:function(){this.catchOptions={user:{id:this.userid,name:this.username},permissions:{read:[],update:[this.userid],delete:[this.userid],admin:[this.userid]}}},search:function(options,successCallback,errorCallback){var _this=this;this.annotationsList=[],jQuery.ajax({url:_this.url+"/search",cache:!1,type:"GET",dataType:"json",headers:{},data:{uri:options.uri,APIKey:_this.APIKey,media:"image",limit:1e4},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback?successCallback(data):(_this.annotationsList=data,jQuery.each(_this.annotationsList,function(index,value){value.fullId=value["@id"],value["@id"]=$.genUUID(),_this.idMapper[value["@id"]]=value.fullId,value.endpoint=_this}),_this.dfd.resolve(!1))},error:function(){"function"==typeof errorCallback?errorCallback():console.log("The request for annotations has caused an error for endpoint: "+options.uri)}})},deleteAnnotation:function(annotationID,returnSuccess,returnError){var _this=this;jQuery.ajax({url:_this.url+"/destroy?uri="+encodeURIComponent(_this.idMapper[annotationID])+"&APIKey="+_this.APIKey,type:"DELETE",dataType:"json",headers:{},data:{uri:annotationID},contentType:"application/json; charset=utf-8",success:function(data){returnSuccess()},error:function(){returnError()}})},update:function(oaAnnotation,returnSuccess,returnError){var annotation=oaAnnotation,_this=this;shortId=annotation["@id"],annotation["@id"]=annotation.fullId,annotationID=annotation.fullId,delete annotation.fullId,delete annotation.endpoint,jQuery.ajax({url:_this.url+"/update/"+encodeURIComponent(annotationID)+"?APIKey="+_this.APIKey,type:"POST",dataType:"json",headers:{},data:JSON.stringify(annotation),contentType:"application/json; charset=utf-8",success:function(data){returnSuccess()},error:function(){returnError()}}),annotation.endpoint=_this,annotation.fullId=annotation["@id"],annotation["@id"]=shortId},create:function(oaAnnotation,returnSuccess,returnError){var annotation=oaAnnotation,_this=this;jQuery.ajax({url:_this.url+"/create?APIKey="+_this.APIKey,type:"POST",dataType:"json",headers:{},data:JSON.stringify(annotation),contentType:"application/json; charset=utf-8",success:function(data){data.fullId=data["@id"],data["@id"]=$.genUUID(),data.endpoint=_this,_this.idMapper[data["@id"]]=data.fullId,returnSuccess(data)},error:function(){returnError()}})},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},userAuthorize:function(action,annotation){return!0}}}(Mirador),function($){$.TinyMCEAnnotationBodyEditor=function(options){jQuery.extend(this,{annotation:null,windowId:null,config:{plugins:"",toolbar:""}},options),this.init()},$.TinyMCEAnnotationBodyEditor.prototype={init:function(){var _this=this,annoText="",tags=[];jQuery.isEmptyObject(_this.annotation)||(jQuery.isArray(_this.annotation.resource)?jQuery.each(_this.annotation.resource,function(index,value){"oa:Tag"===value["@type"]?tags.push(value.chars):annoText=value.chars}):annoText=_this.annotation.resource.chars),this.editorMarkup=this.editorTemplate({content:annoText,tags:tags.join(" "),windowId:_this.windowId})},show:function(selector){this.editorContainer=jQuery(selector).prepend(this.editorMarkup),tinymce.init({selector:selector+" textarea",plugins:this.config.plugins,menubar:!1,statusbar:!1,toolbar_items_size:"small",toolbar:this.config.toolbar,
84
- default_link_target:"_blank",setup:function(editor){editor.on("init",function(args){tinymce.execCommand("mceFocus",!1,args.target.id)})}})},isDirty:function(){return tinymce.activeEditor.isDirty()},createAnnotation:function(){var tagText=this.editorContainer.find(".tags-editor").val(),resourceText=tinymce.activeEditor.getContent(),tags=[];tagText=$.trimString(tagText),tagText&&(tags=tagText.split(/\s+/));var motivation=[],resource=[];return tags&&tags.length>0&&(motivation.push("oa:tagging"),jQuery.each(tags,function(index,value){resource.push({"@type":"oa:Tag",chars:value})})),motivation.push("oa:commenting"),resource.push({"@type":"dctypes:Text",format:"text/html",chars:resourceText}),{"@context":"http://iiif.io/api/presentation/2/context.json","@type":"oa:Annotation",motivation:motivation,resource:resource}},updateAnnotation:function(oaAnno){var tagText=this.editorContainer.find(".tags-editor").val(),resourceText=tinymce.activeEditor.getContent(),tags=[];tagText=$.trimString(tagText),tagText&&(tags=tagText.split(/\s+/));oaAnno.motivation=jQuery.grep(oaAnno.motivation,function(value){return"oa:tagging"!==value}),oaAnno.resource=jQuery.grep(oaAnno.resource,function(value){return"oa:Tag"!==value["@type"]}),tags.length>0&&(oaAnno.motivation.push("oa:tagging"),jQuery.each(tags,function(index,value){oaAnno.resource.push({"@type":"oa:Tag",chars:value})})),jQuery.each(oaAnno.resource,function(index,value){"dctypes:Text"===value["@type"]&&(value.chars=resourceText)})},editorTemplate:Handlebars.compile(['<textarea class="text-editor" placeholder="{{t "comments"}}…">{{#if content}}{{content}}{{/if}}</textarea>','<input id="tags-editor-{{windowId}}" class="tags-editor" placeholder="{{t "addTagsHere"}}…" {{#if tags}}value="{{tags}}"{{/if}}>'].join(""))}}(Mirador),function($){$.Slot=function(options){jQuery.extend(!0,this,{workspaceSlotCls:"slot",slotID:null,layoutAddress:null,focused:null,appendTo:null,window:null,windowElement:null,state:null,eventEmitter:null},options),this.init()},$.Slot.prototype={init:function(){this.events=[],this.element=jQuery(this.template({workspaceSlotCls:this.workspaceSlotCls,slotID:this.slotId})),this.element.appendTo(this.appendTo),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;this.events=[_this.eventEmitter.subscribe("slotRemoved",function(event,slot){_this.slotID===slot.slotID&&_this.clearSlot()}),_this.eventEmitter.subscribe("layoutChanged",function(event,layoutRoot){_this.window&&(_this.window.slotAddress=_this.layoutAddress,_this.eventEmitter.publish("windowSlotAddressUpdated",{id:_this.window.id,slotAddress:_this.window.slotAddress}))}),_this.eventEmitter.subscribe("HIDE_REMOVE_SLOT",function(event){_this.element.find(".remove-slot-option").hide(),_this.window&&_this.eventEmitter.publish("HIDE_REMOVE_OBJECT."+_this.window.id)}),_this.eventEmitter.subscribe("SHOW_REMOVE_SLOT",function(event){_this.element.find(".remove-slot-option").show(),_this.window&&_this.eventEmitter.publish("SHOW_REMOVE_OBJECT."+_this.window.id)}),_this.eventEmitter.subscribe("ADD_ITEM_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.addItem()}),_this.eventEmitter.subscribe("REMOVE_SLOT_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("REMOVE_NODE",_this)}),_this.eventEmitter.subscribe("SPLIT_RIGHT_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_RIGHT",_this)}),_this.eventEmitter.subscribe("SPLIT_LEFT_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_LEFT",_this)}),_this.eventEmitter.subscribe("SPLIT_DOWN_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_DOWN",_this)}),_this.eventEmitter.subscribe("SPLIT_UP_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_UP",_this)})]},bindEvents:function(){var _this=this,dropTarget=this.element.find(".dropMask");this.element.find(".addItemLink").on("click",function(){_this.addItem()}),this.element.find(".remove-slot-option").on("click",function(){_this.eventEmitter.publish("REMOVE_NODE",_this)}),this.element.on("dragover",function(e){e.preventDefault(),dropTarget.show()}),dropTarget.on("dragenter",function(e){e.preventDefault(),_this.element.addClass("draggedOver")}),dropTarget.on("dragleave",function(e){e.preventDefault(),_this.element.removeClass("draggedOver"),dropTarget.hide()}),this.element.on("drop",function(e){_this.dropItem(e)})},dropItem:function(e){var _this=this;e.preventDefault();var text_url=e.originalEvent.dataTransfer.getData("text/plain");text_url?_this.handleDrop(text_url):e.originalEvent.dataTransfer.items[0].getAsString(function(url){_this.handleDrop(url)})},handleDrop:function(url){var _this=this;url=url||text_url;var windowConfig,manifestUrl=$.getQueryParams(url).manifest||url,collectionUrl=$.getQueryParams(url).collection,canvasId=$.getQueryParams(url).canvas,imageInfoUrl=$.getQueryParams(url).image;"undefined"!=typeof _this.state.getStateProperty("manifests")[manifestUrl]?(windowConfig={manifest:_this.state.getStateProperty("manifests")[manifestUrl],slotAddress:_this.getAddress()},canvasId&&(windowConfig.canvasID=canvasId,windowConfig.viewType="ImageView"),_this.eventEmitter.publish("ADD_WINDOW",windowConfig)):"undefined"!=typeof imageInfoUrl?_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[imageInfoUrl,"(Added from URL)"]):"undefined"!=typeof collectionUrl?(jQuery.getJSON(collectionUrl).done(function(data,status,jqXHR){data.hasOwnProperty("manifests")?jQuery.each(data.manifests,function(ci,mfst){_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[mfst["@id"],"(Added from URL)"])}):data.hasOwnProperty("members")&&jQuery.each(data.members,function(ci,mfst){_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[mfst["@id"],"(Added from URL)"])})}),_this.addItem()):_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[manifestUrl,"(Added from URL)"]),_this.eventEmitter.subscribe("manifestReceived",function(event,manifest){var windowConfig;manifest.jsonLd["@id"]!==manifestUrl&&manifest.jsonLd["@id"]+"/info.json"!==imageInfoUrl||(windowConfig={manifest:manifest,slotAddress:_this.getAddress()},manifest.jsonLd["@id"]+"/info.json"===imageInfoUrl&&(canvasId=manifest.jsonLd.sequences[0].canvases[0]["@id"]),canvasId&&(windowConfig.canvasID=canvasId,windowConfig.viewType="ImageView"),_this.eventEmitter.publish("ADD_WINDOW",windowConfig))})},destroyEvents:function(){var _this=this;this.events.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)})},clearSlot:function(){this.destroyEvents(),this.window&&delete this.window},getAddress:function(){return this.layoutAddress},addItem:function(){var _this=this;_this.focused=!0,_this.eventEmitter.publish("ADD_SLOT_ITEM",_this)},template:Handlebars.compile(['<div id="{{slotID}}" class="{{workspaceSlotCls}}">','<div class="slotIconContainer">','<h1 class="plus" role="presentation" aria-label="Add item using Link">',"<span>+</span>",'<div class="dropIcon">','<i class="fa fa-level-down"></i>',"</div>","</h1>",'<h1 class="addItemText">{{t "addItem"}}</h1>','<h1 class="dropMeMessage">{{t "dropToLoad"}}</h1>',"</div>",'<a class="addItemLink" role="button" aria-label="Add item"></a>','<a class="remove-slot-option"><i class="fa fa-times fa-lg fa-fw"></i> {{t "close"}}</a>','<a class="dropMask"></a>',"</div>"].join(""))}}(Mirador),function($){$.Window=function(options){jQuery.extend(this,{state:null,eventEmitter:null,element:null,scrollImageRatio:.9,canvasID:null,focusImages:[],imagesList:null,annotationsList:[],endpoint:null,currentImageMode:"ImageView",imageModes:["ImageView","BookView"],originalImageModes:["ImageView","BookView"],focuses:["ThumbnailsView","ImageView","ScrollView","BookView"],focusModules:{ThumbnailsView:null,ImageView:null,ScrollView:null,BookView:null},focusOverlaysAvailable:{ThumbnailsView:{overlay:{MetadataView:!1},bottomPanel:{"":!1}},ImageView:{overlay:{MetadataView:!1},bottomPanel:{ThumbnailsView:!0}},ScrollView:{overlay:{MetadataView:!1},bottomPanel:{"":!1}},BookView:{overlay:{MetadataView:!1},bottomPanel:{ThumbnailsView:!0}}},windowOptions:null,sidePanel:null,annotationsAvailable:{ThumbnailsView:!1,ImageView:!0,ScrollView:!1,BookView:!1},bottomPanel:null,overlay:null,annoEndpointAvailable:!1,iconClasses:{ImageView:"fa fa-photo fa-lg fa-fw",BookView:"fa fa-columns fa-lg fa-fw",ScrollView:"fa fa-ellipsis-h fa-lg fa-fw",ThumbnailsView:"fa fa-th fa-lg fa-rotate-90 fa-fw"}},options),this.init(),this.bindAnnotationEvents()},$.Window.prototype={init:function(){var _this=this,manifest=_this.manifest.jsonLd,focusState=_this.viewType,templateData={};for(this.events=[];_this.annotationsList.length>0;)_this.annotationsList.pop();switch(_this.eventEmitter.unsubscribe("currentCanvasIDUpdated."+_this.id),_this.eventEmitter.publish("DESTROY_EVENTS."+_this.id),_this.removeBookView(),this.imageModes=this.originalImageModes,this.imageModes=jQuery.map(this.imageModes,function(value,index){return jQuery.inArray(value,_this.focuses)===-1?null:value}),_this.imagesList=_this.manifest.getCanvases(),_this.canvasID||(_this.canvasID=_this.imagesList[0]["@id"]),this.annoEndpointAvailable=!jQuery.isEmptyObject(_this.state.getStateProperty("annotationEndpoint")),this.canvasControls.annotations.annotationLayer||(this.canvasControls.annotations.annotationCreation=!1,this.annoEndpointAvailable=!1,this.canvasControls.annotations.annotationState="off"),_this.getAnnotations(),this.canvasControls.imageManipulation.manipulationLayer&&(this.canvasControls.imageManipulation.manipulationLayer=!Object.keys(this.canvasControls.imageManipulation.controls).every(function(element,index,array){return _this.canvasControls.imageManipulation.controls[element]===!1})),_this.eventEmitter.publish("windowUpdated",{id:_this.id,annotationsAvailable:this.annotationsAvailable}),"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable||jQuery.each(this.focusOverlaysAvailable,function(key,value){_this.focusOverlaysAvailable[key].bottomPanel={"":!1}}),templateData.sidePanel=this.sidePanelAvailable,this.sidePanelAvailable&&(templateData.sidePanel=!Object.keys(this.sidePanelOptions).every(function(element,index,array){return _this.sidePanelOptions[element]===!1})),"undefined"==typeof this.overlayAvailable||this.overlayAvailable?templateData.MetadataView=!0:jQuery.each(this.focusOverlaysAvailable,function(key,value){_this.focusOverlaysAvailable[key].overlay={"":!1}}),templateData.iconClasses={},jQuery.each(this.focuses,function(index,value){templateData[value]=!0,templateData.iconClasses[value]=_this.iconClasses[value]}),templateData.title=$.JsonLd.getTextValue(manifest.label),templateData.displayLayout=this.displayLayout,templateData.layoutOptions=this.layoutOptions,this.displayLayout&&(templateData.displayLayout=!Object.keys(this.layoutOptions).every(function(element,index,array){return _this.layoutOptions[element]===!1})),templateData.currentFocusClass=_this.iconClasses[_this.viewType],templateData.showFullScreen=_this.fullScreen,_this.element=jQuery(this.template(templateData)).appendTo(_this.appendTo),this.element.find(".manifest-info .mirador-tooltip").each(function(){jQuery(this).qtip({content:{text:jQuery(this).attr("title")},position:{my:"top center",at:"bottom center",adjust:{method:"shift",y:-11},container:_this.element,viewport:!0},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}})}),this.element.find(".manifest-info .window-manifest-title").qtip({content:{text:jQuery(this).attr("title")},position:{my:"top center",at:"bottom left",adjust:{method:"shift",x:20,y:1},container:_this.element,viewport:!0},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}}),_this.eventEmitter.publish("WINDOW_ELEMENT_UPDATED",{windowId:_this.id,element:_this.element}),_this.clearViews(),_this.clearPanelsAndOverlay(),this.listenForActions(),_this.bindNavigation(),focusState){case"ThumbnailsView":_this.toggleThumbnails(_this.canvasID);break;case"ImageView":_this.toggleImageView(_this.canvasID);break;case"BookView":_this.toggleBookView(_this.canvasID);break;case"ScrollView":_this.toggleScrollView(_this.canvasID)}_this.state.getSlots().length<=1&&_this.element.find(".remove-object-option").hide(),this.bindEvents(),1===this.imagesList.length?this.bottomPanelVisibility(!1):this.bottomPanelVisibility(this.bottomPanelVisible),this.sidePanelVisibility(this.sidePanelVisible,"0s"),this.events.push(this.eventEmitter.subscribe("windowRemoved",function(event,id){_this.id===id&&_this.destroy()}))},destroy:function(){var _this=this;this.events.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)}),this.element.remove()},update:function(options){jQuery.extend(this,options),this.windowOptions&&(this.windowOptions.osdBounds=null,this.windowOptions.zoomLevel=null),this.init()},removeBookView:function(){this.focuses=this.availableViews;var manifest=this.manifest.jsonLd;manifest.sequences[0].viewingHint&&"paged"!==manifest.sequences[0].viewingHint.toLowerCase()&&(this.focuses=jQuery.grep(this.focuses,function(value){return"BookView"!==value}))},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("bottomPanelSet."+_this.id,function(event,visible){var panel=_this.element.find(".bottomPanel");visible===!0?panel.css({transform:"translateY(0)"}):panel.css({transform:"translateY(100%)"})}),_this.events.push(_this.eventEmitter.subscribe("HIDE_REMOVE_OBJECT."+_this.id,function(event){_this.element.find(".remove-object-option").hide()})),_this.events.push(this.eventEmitter.subscribe("SHOW_REMOVE_OBJECT."+_this.id,function(event){_this.element.find(".remove-object-option").show()})),_this.events.push(_this.eventEmitter.subscribe("sidePanelStateUpdated."+this.id,function(event,state){state.open?(_this.element.find(".mirador-icon-toc").addClass("selected"),_this.element.find(".view-container").removeClass("maximised")):(_this.element.find(".mirador-icon-toc").removeClass("selected"),_this.element.find(".view-container").addClass("maximised"))})),_this.events.push(_this.eventEmitter.subscribe("sidePanelVisibilityByTab."+this.id,function(event,visible){_this.sidePanelVisibility(visible,"0s")})),_this.events.push(_this.eventEmitter.subscribe("SET_CURRENT_CANVAS_ID."+this.id,function(event,canvasID){_this.setCurrentCanvasID(canvasID)})),_this.events.push(_this.eventEmitter.subscribe("REMOVE_CLASS."+this.id,function(event,className){_this.element.find(".view-container").removeClass(className)})),_this.events.push(_this.eventEmitter.subscribe("ADD_CLASS."+this.id,function(event,className){_this.element.find(".view-container").addClass(className)})),_this.events.push(_this.eventEmitter.subscribe("UPDATE_FOCUS_IMAGES."+this.id,function(event,images){_this.updateFocusImages(images.array)})),_this.events.push(_this.eventEmitter.subscribe("HIDE_ICON_TOC."+this.id,function(event){_this.element.find(".mirador-icon-toc").hide()})),_this.events.push(_this.eventEmitter.subscribe("SHOW_ICON_TOC."+this.id,function(event){_this.element.find(".mirador-icon-toc").show()})),_this.events.push(_this.eventEmitter.subscribe("SET_BOTTOM_PANEL_VISIBILITY."+this.id,function(event,visibility){"undefined"!=typeof visibility&&null!==visibility?_this.bottomPanelVisibility(visibility):_this.bottomPanelVisibility(_this.bottomPanelVisible)})),_this.events.push(_this.eventEmitter.subscribe("TOGGLE_BOTTOM_PANEL_VISIBILITY."+this.id,function(event){var visible=!_this.bottomPanelVisible;_this.bottomPanelVisibility(visible)})),_this.events.push(_this.eventEmitter.subscribe("DISABLE_WINDOW_FULLSCREEN",function(event){_this.element.find(".mirador-osd-fullscreen").hide()})),_this.events.push(_this.eventEmitter.subscribe("ENABLE_WINDOW_FULLSCREEN",function(event){_this.element.find(".mirador-osd-fullscreen").show()}))},bindEvents:function(){var _this=this;jQuery(window).resize($.debounce(function(){if(_this.focusModules.ScrollView){var containerHeight=_this.element.find(".view-container").height(),triggerShow=!1;"ScrollView"===_this.viewType&&(triggerShow=!0),_this.focusModules.ScrollView.reloadImages(Math.floor(containerHeight*_this.scrollImageRatio),triggerShow)}},300)),this.element.find(".mirador-osd-fullscreen").on("click",function(){$.fullscreenElement()?$.exitFullscreen():$.enterFullscreen(_this.element[0])}),jQuery(document).on("webkitfullscreenchange mozfullscreenchange fullscreenchange",function(){_this.toggleFullScreen()})},bindAnnotationEvents:function(){var _this=this;_this.eventEmitter.subscribe("annotationCreated."+_this.id,function(event,oaAnno,eventCallback){var annoID;_this.endpoint.create(oaAnno,function(data){annoID=String(data["@id"]),_this.annotationsList.push(data),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList}),eventCallback()},function(){console.log("There was an error saving this new annotation")})}),_this.eventEmitter.subscribe("annotationUpdated."+_this.id,function(event,oaAnno){_this.endpoint.update(oaAnno,function(data){jQuery.each(_this.annotationsList,function(index,value){if(value["@id"]===data["@id"])return _this.annotationsList[index]=data,!1}),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})},function(){console.log("There was an error updating this annotation")})}),_this.eventEmitter.subscribe("annotationDeleted."+_this.id,function(event,annoId){_this.endpoint.deleteAnnotation(annoId,function(){_this.annotationsList=jQuery.grep(_this.annotationsList,function(e){return e["@id"]!==annoId}),_this.eventEmitter.publish("removeOverlay."+_this.id,annoId),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})},function(){})}),_this.eventEmitter.subscribe("updateAnnotationList."+_this.id,function(event){for(;_this.annotationsList.length>0;)_this.annotationsList.pop();_this.getAnnotations()})},clearViews:function(){var _this=this;jQuery.each(_this.focusModules,function(key,value){_this.focusModules[key]=null})},clearPanelsAndOverlay:function(){this.sidePanel=null,this.bottomPanel=null,this.overlay=null},updatePanelsAndOverlay:function(state){var _this=this;jQuery.each(this.focusOverlaysAvailable[state],function(panelType,viewOptions){jQuery.each(viewOptions,function(view,displayed){""!==view&&null===_this[panelType]&&(_this[panelType]=new $[view]({manifest:_this.manifest,appendTo:_this.element.find("."+panelType),state:_this.state,eventEmitter:_this.eventEmitter,windowId:_this.id,panel:!0,canvasID:_this.canvasID,imagesList:_this.imagesList,thumbInfo:{thumbsHeight:80,listingCssCls:"panel-listing-thumbs",thumbnailCls:"panel-thumbnail-view"}})),displayed=_this.focusOverlaysAvailable[state][panelType][view],""!==view&&displayed&&_this.togglePanels(panelType,displayed,view,state),""===view&&_this[panelType]&&_this.togglePanels(panelType,displayed,view,state),""===view&&_this.adjustFocusSize(panelType,displayed)})})},updateSidePanel:function(){if(this.sidePanelAvailable){var _this=this,tocAvailable=_this.sidePanelOptions.toc,annotationsTabAvailable=_this.sidePanelOptions.annotations,layersTabAvailable=_this.sidePanelOptions.layers,hasStructures=!0,structures=_this.manifest.getStructures();structures&&0!==structures.length||(hasStructures=!1),null===this.sidePanel?this.sidePanel=new $.SidePanel({windowId:_this.id,state:_this.state,eventEmitter:_this.eventEmitter,appendTo:_this.element.find(".sidePanel"),manifest:_this.manifest,canvasID:_this.canvasID,layersTabAvailable:layersTabAvailable,tocTabAvailable:tocAvailable,annotationsTabAvailable:annotationsTabAvailable,hasStructures:hasStructures}):this.sidePanel.update("annotations",annotationsTabAvailable)}},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},togglePanels:function(panelType,panelState,viewType,focusState){this.focusOverlaysAvailable[focusState][panelType][viewType]=panelState,this[panelType].toggle(panelState),this.adjustFocusSize(panelType,panelState)},sidePanelVisibility:function(visible,transitionDuration){var _this=this;_this.sidePanelVisible=visible,tocIconElement=this.element.find(".mirador-icon-toc"),sidePanelElement=this.element.find(".sidePanel"),viewContainerElement=this.element.find(".view-container"),sidePanelElement.css("transition-duration",transitionDuration),viewContainerElement.css("transition",transitionDuration),visible&&sidePanelElement.hasClass("minimized")?(tocIconElement.addClass("selected"),sidePanelElement.removeClass("minimized").width(280).css("border-right","1px solid lightgray"),viewContainerElement.css("margin-left",280)):visible||sidePanelElement.hasClass("minimized")||(tocIconElement.removeClass("selected"),viewContainerElement.css("margin-left",0),sidePanelElement.addClass("minimized").css("border","none").width(0)),_this.eventEmitter.publish("windowUpdated",{id:_this.id,sidePanelVisible:visible})},bottomPanelVisibility:function(visible){var _this=this;_this.bottomPanelVisible=visible,_this.eventEmitter.publish("bottomPanelSet."+_this.id,visible),_this.eventEmitter.publish("windowUpdated",{id:_this.id,bottomPanelVisible:visible})},adjustFocusSize:function(panelType,panelState){"bottomPanel"===panelType?this.focusModules[this.viewType].adjustHeight("focus-max-height",panelState):"sidePanel"===panelType&&this.focusModules[this.viewType].adjustWidth("focus-max-width",panelState)},toggleMetadataOverlay:function(focusState){var currentState=this.focusOverlaysAvailable[focusState].overlay.MetadataView;currentState?this.element.find(".mirador-icon-metadata-view").removeClass("selected"):this.element.find(".mirador-icon-metadata-view").addClass("selected"),jQuery.each(this.focusOverlaysAvailable,function(focusType,options){focusState!==focusType&&(this.overlay.MetadataView=!currentState)}),this.togglePanels("overlay",!currentState,"MetadataView",focusState)},toggleFocus:function(focusState,imageMode){var _this=this;this.viewType=focusState,imageMode&&jQuery.inArray(imageMode,this.imageModes)>-1&&(this.currentImageMode=imageMode),jQuery.each(this.focusModules,function(focusKey,module){module&&focusState!==focusKey&&module.toggle(!1)}),this.focusModules[focusState].toggle(!0),this.updateManifestInfo(),this.updatePanelsAndOverlay(focusState),this.updateSidePanel(),_this.eventEmitter.publish("focusUpdated"),_this.eventEmitter.publish("windowUpdated",{id:_this.id,viewType:_this.viewType,canvasID:_this.canvasID,imageMode:_this.currentImageMode,loadedManifest:_this.manifest.jsonLd["@id"],slotAddress:_this.slotAddress})},toggleThumbnails:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.ThumbnailsView)this.focusModules.ThumbnailsView=new $.ThumbnailsView({manifest:this.manifest,appendTo:this.element.find(".view-container"),state:this.state,eventEmitter:this.eventEmitter,windowId:this.id,canvasID:this.canvasID,imagesList:this.imagesList});else{var view=this.focusModules.ThumbnailsView;view.updateImage(canvasID)}this.toggleFocus("ThumbnailsView","")},toggleImageView:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.ImageView)this.focusModules.ImageView=new $.ImageView({manifest:this.manifest,appendTo:this.element.find(".view-container"),qtipElement:this.element,windowId:this.id,state:this.state,eventEmitter:this.eventEmitter,canvasID:canvasID,imagesList:this.imagesList,osdOptions:this.windowOptions,bottomPanelAvailable:this.bottomPanelAvailable,annoEndpointAvailable:this.annoEndpointAvailable,canvasControls:this.canvasControls,annotationState:this.canvasControls.annotations.annotationState});else{var view=this.focusModules.ImageView;view.updateImage(canvasID)}this.toggleFocus("ImageView","ImageView")},toggleBookView:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.BookView)this.focusModules.BookView=new $.BookView({manifest:this.manifest,appendTo:this.element.find(".view-container"),windowId:this.id,state:this.state,eventEmitter:this.eventEmitter,canvasID:canvasID,imagesList:this.imagesList,osdOptions:this.windowOptions,bottomPanelAvailable:this.bottomPanelAvailable});else{var view=this.focusModules.BookView;view.updateImage(canvasID)}this.toggleFocus("BookView","BookView")},toggleScrollView:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.ScrollView){var containerHeight=this.element.find(".view-container").height();this.focusModules.ScrollView=new $.ScrollView({manifest:this.manifest,appendTo:this.element.find(".view-container"),state:this.state,eventEmitter:this.eventEmitter,windowId:this.id,canvasID:this.canvasID,imagesList:this.imagesList,thumbInfo:{thumbsHeight:Math.floor(containerHeight*this.scrollImageRatio),listingCssCls:"scroll-listing-thumbs",thumbnailCls:"scroll-view"}})}else{var view=this.focusModules.ScrollView;view.updateImage(canvasID)}this.toggleFocus("ScrollView","")},updateFocusImages:function(imageList){this.focusImages=imageList,this.bottomPanel&&this.bottomPanel.updateFocusImages(this.focusImages)},setCurrentCanvasID:function(canvasID){var _this=this;for(this.canvasID=canvasID,_this.eventEmitter.publish("removeTooltips."+_this.id),_this.eventEmitter.unsubscribe("annotationListLoaded."+_this.id);_this.annotationsList.length>0;)_this.annotationsList.pop();switch(this.getAnnotations(),this.currentImageMode){case"ImageView":this.toggleImageView(this.canvasID);break;case"BookView":this.toggleBookView(this.canvasID)}_this.eventEmitter.publish("currentCanvasIDUpdated."+_this.id,canvasID)},replaceWindow:function(newSlotAddress,newElement){this.slotAddress=newSlotAddress,this.appendTo=newElement,this.update()},setCursorFrameStart:function(canvasID){},updateManifestInfo:function(){var _this=this;_this.element.find(".mirador-icon-view-type > i:first").removeClass().addClass(_this.iconClasses[_this.viewType]),this.focusOverlaysAvailable[this.viewType].overlay.MetadataView&&this.element.find(".mirador-icon-metadata-view").addClass("selected")},getAnnotations:function(){var _this=this,urls=_this.manifest.getAnnotationsListUrls(_this.canvasID);if(0!==urls.length&&jQuery.each(urls,function(index,url){jQuery.get(url,function(list){var annotations=list.resources;jQuery.each(annotations,function(index,value){"undefined"==typeof value["@id"]&&(value["@id"]=$.genUUID()),value.endpoint="manifest"}),_this.annotationsList=_this.annotationsList.concat(annotations),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})})}),this.annoEndpointAvailable){var dfd=jQuery.Deferred(),module=_this.state.getStateProperty("annotationEndpoint").module,options=_this.state.getStateProperty("annotationEndpoint").options||{};options.name=_this.state.getStateProperty("annotationEndpoint").name,_this.endpoint&&null!==_this.endpoint?_this.endpoint.set("dfd",dfd):(options.dfd=dfd,options.windowID=_this.id,options.imagesList=_this.imagesList,options.eventEmitter=_this.eventEmitter,_this.endpoint=new $[module](options)),_this.endpoint.search({uri:_this.canvasID}),dfd.done(function(loaded){_this.annotationsList=_this.annotationsList.concat(_this.endpoint.annotationsList),_this.annotationsList=jQuery.grep(_this.annotationsList,function(value,index){return"undefined"!=typeof value.on}),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})})}},toggleFullScreen:function(){var _this=this;OpenSeadragon.isFullScreen()?(this.element.find(".mirador-osd-fullscreen i").removeClass("fa-expand").addClass("fa-compress"),this.element.find(".mirador-osd-toggle-bottom-panel").hide(),_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.id,!1)):(this.element.find(".mirador-osd-fullscreen i").removeClass("fa-compress").addClass("fa-expand"),this.element.find(".mirador-osd-toggle-bottom-panel").show(),_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.id,!0))},bindNavigation:function(){var _this=this;this.element.find(".mirador-icon-view-type").on("mouseenter",function(){_this.element.find(".image-list").stop().slideFadeToggle(300)}).on("mouseleave",function(){_this.element.find(".image-list").stop().slideFadeToggle(300)}),this.element.find(".mirador-icon-window-menu").on("mouseenter",function(){_this.element.find(".slot-controls").stop().slideFadeToggle(300)}).on("mouseleave",function(){_this.element.find(".slot-controls").stop().slideFadeToggle(300)}),this.element.find(".single-image-option").on("click",function(){_this.toggleImageView(_this.canvasID)}),this.element.find(".book-option").on("click",function(){_this.toggleBookView(_this.canvasID)}),this.element.find(".scroll-option").on("click",function(){_this.toggleScrollView(_this.canvasID)}),this.element.find(".thumbnails-option").on("click",function(){_this.toggleThumbnails(_this.canvasID)}),this.element.find(".mirador-icon-metadata-view").on("click",function(){_this.toggleMetadataOverlay(_this.viewType)}),this.element.find(".mirador-icon-toc").on("click",function(){_this.sidePanelVisibility(!_this.sidePanelVisible,"0.3s")}),this.element.find(".new-object-option").on("click",function(){_this.eventEmitter.publish("ADD_ITEM_FROM_WINDOW",_this.id)}),this.element.find(".remove-object-option").on("click",function(){_this.eventEmitter.publish("REMOVE_SLOT_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-right").on("click",function(){_this.eventEmitter.publish("SPLIT_RIGHT_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-left").on("click",function(){_this.eventEmitter.publish("SPLIT_LEFT_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-below").on("click",function(){_this.eventEmitter.publish("SPLIT_DOWN_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-above").on("click",function(){_this.eventEmitter.publish("SPLIT_UP_FROM_WINDOW",_this.id)})},template:Handlebars.compile(['<div class="window">','<div class="manifest-info">','<div class="window-manifest-navigation">','<a href="javascript:;" class="mirador-btn mirador-icon-view-type" role="button" title="{{t "viewTypeTooltip"}}" aria-label="{{t "viewTypeTooltip"}}">','<i class="{{currentFocusClass}}"></i>','<i class="fa fa-caret-down"></i>','<ul class="dropdown image-list">',"{{#if ImageView}}",'<li class="single-image-option"><i class="{{iconClasses.ImageView}}"></i> {{t "imageView"}}</li>',"{{/if}}","{{#if BookView}}",'<li class="book-option"><i class="{{iconClasses.BookView}}"></i> {{t "bookView"}}</li>',"{{/if}}","{{#if ScrollView}}",'<li class="scroll-option"><i class="{{iconClasses.ScrollView}}"></i> {{t "scrollView"}}</li>',"{{/if}}","{{#if ThumbnailsView}}",'<li class="thumbnails-option"><i class="{{iconClasses.ThumbnailsView}}"></i> {{t "thumbnailsView"}}</li>',"{{/if}}","</ul>","</a>","{{#if MetadataView}}",'<a href="javascript:;" class="mirador-btn mirador-icon-metadata-view mirador-tooltip" role="button" title="{{t "metadataTooltip"}}" aria-label="{{t "metadataTooltip"}}">','<i class="fa fa-info-circle fa-lg fa-fw"></i>',"</a>","{{/if}}","{{#if showFullScreen}}",'<a class="mirador-btn mirador-osd-fullscreen mirador-tooltip" role="button" title="{{t "fullScreenWindowTooltip"}}" aria-label="{{t "fullScreenWindowTooltip"}}">','<i class="fa fa-lg fa-fw fa-expand"></i>',"</a>","{{/if}}","</div>","{{#if layoutOptions.close}}",'<a href="javascript:;" class="mirador-btn mirador-close-window remove-object-option mirador-tooltip" title="{{t "closeTooltip"}}" aria-label="{{t "closeTooltip"}}"><i class="fa fa-times fa-lg fa-fw"></i></a>',"{{/if}}","{{#if displayLayout}}",'<a href="javascript:;" class="mirador-btn mirador-icon-window-menu" title="{{t "changeLayoutTooltip"}}" aria-label="{{t "changeLayoutTooltip"}}"><i class="fa fa-th-large fa-lg fa-fw"></i><i class="fa fa-caret-down"></i>','<ul class="dropdown slot-controls">',"{{#if layoutOptions.newObject}}",'<li class="new-object-option"><i class="fa fa-refresh fa-lg fa-fw"></i> {{t "newObject"}}</li>','<hr class="menu-divider"/>',"{{/if}}","{{#if layoutOptions.slotRight}}",'<li class="add-slot-right"><i class="fa fa-arrow-circle-right fa-lg fa-fw"></i> {{t "addSlotRight"}}</li>',"{{/if}}","{{#if layoutOptions.slotLeft}}",'<li class="add-slot-left"><i class="fa fa-arrow-circle-left fa-lg fa-fw"></i> {{t "addSlotLeft"}}</li>',"{{/if}}","{{#if layoutOptions.slotAbove}}",'<li class="add-slot-above"><i class="fa fa-arrow-circle-up fa-lg fa-fw"></i> {{t "addSlotAbove"}}</li>',"{{/if}}","{{#if layoutOptions.slotBelow}}",'<li class="add-slot-below"><i class="fa fa-arrow-circle-down fa-lg fa-fw"></i> {{t "addSlotBelow"}}</li>',"{{/if}}","</ul>","</a>","{{/if}}","{{#if sidePanel}}",'<a href="javascript:;" class="mirador-btn mirador-icon-toc selected mirador-tooltip" title="{{t "sidePanelTooltip"}}" aria-label="{{t "sidePanelTooltip"}}"><i class="fa fa-bars fa-lg fa-fw"></i></a>',"{{/if}}",'<h3 class="window-manifest-title" title="{{{title}}}" aria-label="{{{title}}}">{{{title}}}</h3>',"</div>",'<div class="content-container">',"{{#if sidePanel}}",'<div class="sidePanel">',"</div>","{{/if}}",'<div class="overlay"></div>','<div class="view-container {{#unless sidePanel}}focus-max-width{{/unless}}">','<div class="bottomPanel">',"</div>","</div>","</div>","</div>"].join(""))
85
- }}(Mirador),function($){$.AnnotationsLayer=function(options){jQuery.extend(!0,this,{annotationsList:null,viewer:null,drawTool:null,selected:null,hovered:null,windowId:null,mode:"default",element:null,eventEmitter:null},options),this.init()},$.AnnotationsLayer.DISPLAY_ANNOTATIONS="displayAnnotations",$.AnnotationsLayer.prototype={init:function(){var _this=this;_this.eventEmitter.unsubscribe("modeChange."+_this.windowId),this.createStateMachine(),this.createRenderer(),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("modeChange."+_this.windowId,function(event,modeName){_this.mode=modeName,_this.modeSwitch()}),_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(event){_this.annotationsList=_this.state.getWindowAnnotationsList(_this.windowId),_this.updateRenderer()})},bindEvents:function(){},createStateMachine:function(){var _this=this;this.layerState=StateMachine.create({events:[{name:"startup",from:"none",to:"default"},{name:"defaultState",from:["default","display","create","edit"],to:"default"},{name:"displayAnnotations",from:["default","display","create","edit","newShape"],to:"display"},{name:"createAnnotation",from:["default","display"],to:"create"},{name:"createShape",from:"edit",to:"newShape"},{name:"editAnnotation",from:["default","display","newShape"],to:"edit"}],callbacks:{onstartup:function(event){_this.drawTool.enterDefault()},ondefaultState:function(event){_this.drawTool.enterDefault()},ondisplayAnnotations:function(event){_this.drawTool.enterDisplayAnnotations()},oncreateAnnotation:function(event){_this.drawTool.enterCreateAnnotation()},oncreateShape:function(event){_this.drawTool.enterCreateShape()},oneditAnnotation:function(event){_this.drawTool.enterEditAnnotation()}}})},createRenderer:function(){var _this=this;this.drawTool=new $.OsdRegionDrawTool({osdViewer:_this.viewer,parent:_this,list:_this.annotationsList,visible:!1,windowId:_this.windowId,state:_this.state,eventEmitter:_this.eventEmitter}),this.layerState.startup()},updateRenderer:function(){this.drawTool.list=this.annotationsList},modeSwitch:function(){"displayAnnotations"===this.mode?this.layerState.displayAnnotations():"editingAnnotation"===this.mode?this.layerState.editAnnotation():"creatingAnnotation"===this.mode?"edit"!==this.layerState.current?this.layerState.createAnnotation():this.layerState.createShape():"default"===this.mode&&this.layerState.defaultState()}}}(Mirador),function($){$.AnnotationsTab=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,visible:null,state:null,eventEmitter:null},options),this.init()},$.AnnotationsTab.prototype={init:function(){this.windowId=this.windowId,this.localState({id:"annotationsTab",visible:this.visible,annotationLists:[],selectedList:null,empty:!0,focusedList:null},!0),this.listenForActions(),this.render(this.localState()),this.loadTabComponents(),this.bindEvents()},localState:function(state,initial){var _this=this;return arguments.length?(this.annoTabState=state,initial||_this.eventEmitter.publish("annotationsTabStateUpdated."+this.windowId,this.annoTabState),this.annoTabState):this.annoTabState},loadTabComponents:function(){},tabStateUpdated:function(visible){var localState=this.localState();localState.visible=!localState.visible,this.localState(localState)},annotationListLoaded:function(){var _this=this,annotationSources=[],localState=this.localState();jQuery.each(_this.state.getWindowAnnotationsList(_this.windowId),function(index,value){"string"==typeof value.endpoint?annotationSources.push("manifest"):annotationSources.push(value.endpoint.name)}),annotationSources=annotationSources.filter(function(itm,i,annotationSources){return i==annotationSources.indexOf(itm)}),localState.annotationLists=annotationSources.map(function(annotationSource){return{annotationSource:annotationSource,layer:null,selected:annotationSource===localState.selectedList,focused:!1}}),localState.annotationLists.length&&(localState.empty=!1),this.localState(localState)},deselectList:function(listId){var localState=this.localState();localState.selectedList=null,localState.annotationLists.forEach(function(list){list.selected=!1}),this.localState(localState)},selectList:function(listId){var localState=this.localState();localState.selectedList=listId,localState.annotationLists.forEach(function(list){list.selected=list.annotationSource===listId}),this.localState(localState)},focusList:function(listId){var localState=this.localState();localState.focusedList=listId,localState.annotationLists.forEach(function(list){list.focused=list.annotationSource===listId}),this.localState(localState)},toggle:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("annotationsTabStateUpdated."+_this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("tabStateUpdated."+_this.windowId,function(_,data){_this.tabStateUpdated(data.annotationsTab)}),_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(_,data){_this.annotationListLoaded()}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event){_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(event){_this.annotationListLoaded()}),_this.selectList(_this.localState().selectedList)}),_this.eventEmitter.subscribe("listSelected."+_this.windowId,function(event,listId){_this.selectList(listId)}),_this.eventEmitter.subscribe("listDeselected."+_this.windowId,function(event,listId){_this.deselectList(listId)})},bindEvents:function(){var _this=this,listItems=this.element.find(".annotationListItem");listItems.on("click",function(event){var listClicked=jQuery(this).data("id");_this.localState().selectedList===listClicked?_this.eventEmitter.publish("listDeselected."+_this.windowId,listClicked):_this.eventEmitter.publish("listSelected."+_this.windowId,listClicked)})},render:function(state){var _this=this,templateData={annotationSources:state.annotationLists};this.element?(_this.appendTo.find(".annotationsPanel").remove(),this.element=jQuery(_this.template(templateData)).appendTo(_this.appendTo)):this.element=jQuery(_this.template(templateData)).appendTo(_this.appendTo),_this.bindEvents(),state.visible?this.element.show():this.element.hide()},template:Handlebars.compile(['<div class="annotationsPanel">','<ul class="annotationSources">',"{{#each annotationSources}}",'<li class="annotationListItem {{#if this.selected}}selected{{/if}} {{#if this.focused }}focused{{/if}}" data-id="{{this.annotationSource}}">',"<span>{{this.annotationSource}}</span>","</li>","{{/each}}","</ul>","</div>"].join(""))}}(Mirador),function($){$.BookView=function(options){jQuery.extend(this,{currentImg:null,windowId:null,currentImgIndex:0,stitchList:[],canvasID:null,imagesList:[],element:null,focusImages:[],manifest:null,viewingDirection:"left-to-right",viewingHint:"paged",osd:null,osdCls:"mirador-osd",osdOptions:{osdBounds:null,zoomLevel:null},stitchTileMargin:10,eventEmitter:null},options),this.init()},$.BookView.prototype={init:function(){var _this=this;null!==this.canvasID&&(this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID)),this.osdOptions||(this.osdOptions={osdBounds:null,zoomLevel:null}),this.currentImg=this.imagesList[this.currentImgIndex],this.element=jQuery(this.template()).appendTo(this.appendTo),this.hud=new $.Hud({appendTo:this.element,bottomPanelAvailable:this.bottomPanelAvailable,windowId:this.windowId,annotationLayerAvailable:!1,showNextPrev:1!==this.imagesList.length,eventEmitter:this.eventEmitter,showAnno:!1,showImageControls:!1}),this.manifest.jsonLd.sequences[0].viewingDirection&&(this.viewingDirection=this.manifest.jsonLd.sequences[0].viewingDirection.toLowerCase()),this.manifest.jsonLd.sequences[0].viewingHint&&(this.viewingHint=this.manifest.jsonLd.sequences[0].viewingHint.toLowerCase()),this.stitchList=this.getStitchList(),this.createOpenSeadragonInstance(),this.bindEvents(),this.listenForActions(),"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable?_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,null):_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,!1)},template:Handlebars.compile(['<div class="book-view">',"</div>"].join("")),listenForActions:function(){var _this=this,firstCanvasId=_this.imagesList[0]["@id"],lastCanvasId=_this.imagesList[_this.imagesList.length-1]["@id"];_this.eventEmitter.subscribe("bottomPanelSet."+_this.windowId,function(event,visible){var dodgers=_this.element.find(".mirador-osd-toggle-bottom-panel, .mirador-pan-zoom-controls"),arrows=_this.element.find(".mirador-osd-next, .mirador-osd-previous");visible===!0?(dodgers.addClass("bottom-panel-open"),arrows.addClass("bottom-panel-open")):(dodgers.removeClass("bottom-panel-open"),arrows.removeClass("bottom-panel-open"))}),_this.eventEmitter.subscribe("fitBounds."+_this.windowId,function(event,bounds){var rect=_this.osd.viewport.imageToViewportRectangle(Number(bounds.x),Number(bounds.y),Number(bounds.width),Number(bounds.height));_this.osd.viewport.fitBoundsWithConstraints(rect,!1)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasId){canvasId===firstCanvasId?(_this.element.find(".mirador-osd-previous").hide(),_this.element.find(".mirador-osd-next").show()):canvasId===lastCanvasId?(_this.element.find(".mirador-osd-next").hide(),_this.element.find(".mirador-osd-previous").show()):(_this.element.find(".mirador-osd-next").show(),_this.element.find(".mirador-osd-previous").show())})},bindEvents:function(){var _this=this;this.element.find(".mirador-osd-next").on("click",function(){_this.next()}),this.element.find(".mirador-osd-previous").on("click",function(){_this.previous()}),this.element.find(".mirador-osd-go-home").on("click",function(){_this.osd.viewport.goHome()}),this.element.find(".mirador-osd-up").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,-panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-right").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-down").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-left").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(-panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-zoom-in").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(osd.zoomPerClick/1),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-zoom-out").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(1/osd.zoomPerClick),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-toggle-bottom-panel").on("click",function(){_this.eventEmitter.publish("TOGGLE_BOTTOM_PANEL_VISIBILITY."+_this.windowId)})},getPanByValue:function(){var bounds=this.osd.viewport.getBounds(!0),panBy={x:.5*bounds.width,y:.5*bounds.height};return panBy},setBounds:function(){var _this=this;this.osdOptions.osdBounds=this.osd.viewport.getBounds(!0),_this.eventEmitter.publish("imageBoundsUpdated",{id:_this.windowId,osdBounds:{x:_this.osdOptions.osdBounds.x,y:_this.osdOptions.osdBounds.y,width:_this.osdOptions.osdBounds.width,height:_this.osdOptions.osdBounds.height}})},toggle:function(stateValue){stateValue?this.show():this.hide()},hide:function(){jQuery(this.element).hide({effect:"fade",duration:300,easing:"easeOutCubic"})},show:function(){jQuery(this.element).show({effect:"fade",duration:300,easing:"easeInCubic",complete:function(){jQuery(this).css("display","block")}})},adjustWidth:function(className,hasClass){var _this=this;hasClass?_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,className):_this.eventEmitter.publish("ADD_CLASS."+this.windowId,className)},adjustHeight:function(className,hasClass){hasClass?this.element.removeClass(className):this.element.addClass(className)},updateImage:function(canvasID){this.canvasID=canvasID,this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID),this.currentImg=this.imagesList[this.currentImgIndex];var newList=this.getStitchList(),is_same=this.stitchList.length==newList.length&&this.stitchList.every(function(element,index){return element===newList[index]});is_same||(this.stitchList=newList,this.osdOptions={osdBounds:null,zoomLevel:null},this.osd.close(),this.createOpenSeadragonInstance())},createOpenSeadragonInstance:function(){var elemOsd,uniqueID=$.genUUID(),osdId="mirador-osd-"+uniqueID,tileSources=[],_this=this,toolbarID="osd-toolbar-"+uniqueID,dfd=jQuery.Deferred();this.element.find("."+this.osdCls).remove(),jQuery.each(this.stitchList,function(index,image){var imageUrl=$.Iiif.getImageUrl(image),infoJsonUrl=imageUrl+"/info.json";jQuery.getJSON(infoJsonUrl).done(function(data,status,jqXHR){tileSources.splice(index,0,data),tileSources.length===_this.stitchList.length&&dfd.resolve()})}),dfd.done(function(){var aspectRatio=tileSources[0].height/tileSources[0].width;elemOsd=jQuery("<div/>").addClass(_this.osdCls).attr("id",osdId).appendTo(_this.element),_this.osd=$.OpenSeadragon({id:elemOsd.attr("id"),toolbarID:toolbarID}),_this.osd.addHandler("open",function(){_this.addLayer(tileSources.slice(1),aspectRatio);var addItemHandler=function(event){if(_this.osd.world.removeHandler("add-item",addItemHandler),_this.osdOptions.osdBounds){var rect=new OpenSeadragon.Rect(_this.osdOptions.osdBounds.x,_this.osdOptions.osdBounds.y,_this.osdOptions.osdBounds.width,_this.osdOptions.osdBounds.height);_this.osd.viewport.fitBounds(rect,!0)}else _this.osd.viewport.goHome(!0)};_this.osd.world.addHandler("add-item",addItemHandler),_this.osd.addHandler("zoom",$.debounce(function(){_this.setBounds()},300)),_this.osd.addHandler("pan",$.debounce(function(){_this.setBounds()},300))}),_this.osd.open(tileSources[0],{opacity:1,x:0,y:0,width:1})})},addLayer:function(tileSources,aspectRatio){var _this=this;jQuery.each(tileSources,function(index,value){var newAR=value.height/value.width,options={tileSource:value,opacity:1,x:1.01,y:0,width:aspectRatio/newAR};_this.osd.addTiledImage(options)})},next:function(){var next,_this=this;next=this.currentImgIndex%2===0?this.currentImgIndex+1:this.currentImgIndex+2,next<this.imagesList.length&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[next]["@id"])},previous:function(){var prev,_this=this;prev=this.currentImgIndex%2===0?this.currentImgIndex-2:this.currentImgIndex-1,prev>=0&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[prev]["@id"])},getStitchList:function(){var stitchList=[],leftIndex=[],rightIndex=[],topIndex=[],bottomIndex=[],_this=this;if(this.focusImages=[],"individuals"===this.viewingHint)stitchList=[this.currentImg];else if("paged"===this.viewingHint)if(0===this.currentImgIndex||this.currentImgIndex===this.imagesList.length-1)stitchList=[this.currentImg];else if(this.currentImgIndex%2===0)switch(this.viewingDirection){case"left-to-right":leftIndex[0]=this.currentImgIndex-1,stitchList=[this.imagesList[this.currentImgIndex-1],this.currentImg];break;case"right-to-left":rightIndex[0]=this.currentImgIndex-1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex-1]];break;case"top-to-bottom":topIndex[0]=this.currentImgIndex-1,stitchList=[this.imagesList[this.currentImgIndex-1],this.currentImg];break;case"bottom-to-top":bottomIndex[0]=this.currentImgIndex-1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex-1]]}else switch(this.viewingDirection){case"left-to-right":rightIndex[0]=this.currentImgIndex+1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex+1]];break;case"right-to-left":leftIndex[0]=this.currentImgIndex+1,stitchList=[this.imagesList[this.currentImgIndex+1],this.currentImg];break;case"top-to-bottom":bottomIndex[0]=this.currentImgIndex+1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex+1]];break;case"bottom-to-top":topIndex[0]=this.currentImgIndex+1,stitchList=[this.imagesList[this.currentImgIndex+1],this.currentImg]}else"continuous"===this.viewingHint;return jQuery.each(stitchList,function(index,image){_this.focusImages.push(image["@id"])}),_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:this.focusImages}),stitchList}}}(Mirador),function($){$.ContextControls=function(options){jQuery.extend(this,{element:null,container:null,mode:null,windowId:null,annoEndpointAvailable:!1,eventEmitter:null},options),this.init()},$.ContextControls.prototype={init:function(){var _this=this,showStrokeStyle=!1,showStrokeColor=!1,showFillColor=!1;this.availableAnnotationStylePickers.forEach(function(picker){"StrokeType"===picker&&(showStrokeStyle=!0),"FillColor"===picker&&(showFillColor=!0),"StrokeColor"===picker&&(showStrokeColor=!0)}),this.setBackground={solid:function(el){_this.setBackgroundImage(el,"border_type_1.png")},dashed:function(el){_this.setBackgroundImage(el,"border_type_2.png")},dotdashed:function(el){_this.setBackgroundImage(el,"border_type_3.png")}};var annotationProperties=this.canvasControls.annotations;annotationProperties.annotationLayer&&this.annoEndpointAvailable&&(this.annotationElement=jQuery(this.annotationTemplate({tools:_this.availableAnnotationTools,showEdit:annotationProperties.annotationCreation,showStrokeStyle:showStrokeStyle,showStrokeColor:showStrokeColor,showFillColor:showFillColor,showRefresh:annotationProperties.annotationRefresh})).appendTo(this.container.find(".mirador-osd-annotation-controls")),this.annotationElement.hide(),this.setQtips(this.container.find(".mirador-osd-annotation-controls")),this.setBorderFillColorPickers()),showStrokeStyle&&this.addStrokeStylePicker(),this.canvasControls.imageManipulation.manipulationLayer&&(this.manipulationElement=jQuery(this.manipulationTemplate({filtersSupported:Modernizr.cssfilters,showRotate:this.canvasControls.imageManipulation.controls.rotate,showBrightness:this.canvasControls.imageManipulation.controls.brightness,showContrast:this.canvasControls.imageManipulation.controls.contrast,showSaturate:this.canvasControls.imageManipulation.controls.saturate,showGrayscale:this.canvasControls.imageManipulation.controls.grayscale,showInvert:this.canvasControls.imageManipulation.controls.invert})).appendTo(this.container.find(".mirador-manipulation-controls")),this.setQtips(this.container.find(".mirador-manipulation-controls")),this.manipulationElement.hide()),this.bindEvents()},setQtips:function(element){var _this=this;element.find("a").each(function(){jQuery(this).qtip({content:{text:jQuery(this).attr("title")},position:{my:"bottom center",at:"top center",viewport:!0,container:_this.qtipElement},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}})})},addColorPicker:function(selector,options){this.container.find(selector).spectrum(options)},getImagePath:function(imageName){return this.state.getStateProperty("buildPath")+this.state.getStateProperty("imagesPath")+imageName},setBackgroundImage:function(el,imageName){el.css("background-image","url("+this.getImagePath(imageName)+")")},removeBackgroundImage:function(el){el.css("background-image","")},addStrokeStylePicker:function(){this.setBackground.solid(this.container.find(".mirador-line-type .solid")),this.setBackground.dashed(this.container.find(".mirador-line-type .dashed")),this.setBackground.dotdashed(this.container.find(".mirador-line-type .dotdashed"))},setBorderFillColorPickers:function(){var _this=this,defaultBorderColor=_this.state.getStateProperty("drawingToolsSettings").strokeColor,defaultFillColor=_this.state.getStateProperty("drawingToolsSettings").fillColor,defaultAlpha=_this.state.getStateProperty("drawingToolsSettings").fillColorAlpha,colorObj=tinycolor(defaultFillColor);colorObj.setAlpha(defaultAlpha),this.addColorPicker(".borderColorPicker",{showInput:!0,showInitial:!1,showPalette:!0,showButtons:!1,showSelectionPalette:!0,hideAfterPaletteSelect:!0,appendTo:"parent",containerClassName:"borderColorPickerPop"+_this.windowId,preferredFormat:"rgb",hide:function(color){_this.eventEmitter.publish("changeBorderColor."+_this.windowId,color.toHexString()),jQuery(this).spectrum("set",color.toHexString())},move:function(color){_this.eventEmitter.publish("changeBorderColor."+_this.windowId,color.toHexString())},show:function(color){_this.setColorPickerInCanvas(".borderColorPicker")},maxSelectionSize:4,color:defaultBorderColor,palette:[[defaultBorderColor,"black","red","green"],["white","blue","magenta","yellow"]]}),_this.container.find(".borderColorPicker").next(".sp-replacer").prepend("<i class='material-icons'>border_color</i>"),_this.addColorPicker(".fillColorPicker",{showInput:!0,showInitial:!1,showAlpha:!0,showPalette:!0,showButtons:!1,showSelectionPalette:!0,appendTo:"parent",clickoutFiresChange:!0,containerClassName:"fillColorPickerPop"+_this.windowId,preferredFormat:"rgb",hide:function(color){_this.eventEmitter.publish("changeFillColor."+_this.windowId,[color.toHexString(),color.getAlpha()]),jQuery(this).spectrum("set",color)},move:function(color){_this.eventEmitter.publish("changeFillColor."+_this.windowId,[color.toHexString(),color.getAlpha()])},show:function(color){_this.setColorPickerInCanvas(".fillColorPicker")},maxSelectionSize:4,color:colorObj,palette:[[colorObj,"black","red","green"],["white","blue","magenta","yellow"]]}),_this.container.find(".fillColorPicker").next(".sp-replacer").prepend("<i class='material-icons'>format_color_fill</i>")},setColorPickerInCanvas:function(selector){var pickerContainer=this.container.find(selector).siblings(".sp-container").first(),pickerOffset=pickerContainer.offset(),windowWidth=this.state.windowsElements[this.windowId].width();pickerContainer.width()+pickerOffset.left>windowWidth&&pickerContainer.offset({top:pickerOffset.top,left:windowWidth-pickerContainer.width()})},annotationShow:function(){this.annotationElement.fadeIn("150")},annotationHide:function(){this.annotationElement.fadeOut("150")},manipulationShow:function(){this.manipulationElement.fadeIn("150")},manipulationHide:function(){this.manipulationElement.fadeOut("150")},bindEvents:function(){var _this=this;this.container.find(".mirador-line-type").on("mouseenter",function(){return!jQuery(this).hasClass("hud-disabled")&&void _this.container.find(".type-list").stop().slideFadeToggle(300)}),this.container.find(".mirador-line-type").on("mouseleave",function(){return!jQuery(this).hasClass("hud-disabled")&&void _this.container.find(".type-list").stop().slideFadeToggle(300)}),this.container.find(".mirador-line-type").find("ul li").on("click",function(){if(jQuery(this).hasClass("hud-disabled"))return!1;var className=jQuery(this).find("i").attr("class").replace(/fa/,"").replace(/ /,"");_this.removeBackgroundImage(_this.container.find(".mirador-line-type .border-type-image")),_this.setBackground[className](_this.container.find(".mirador-line-type .border-type-image")),_this.eventEmitter.publish("toggleBorderType."+_this.windowId,className)})},annotationTemplate:Handlebars.compile(["{{#if showEdit}}",'<a class="mirador-osd-pointer-mode hud-control selected" title="{{t "pointerTooltip"}}">','<i class="fa fa-mouse-pointer"></i>',"</a>","{{#each tools}}",'<a class="mirador-osd-{{this.logoClass}}-mode hud-control mirador-osd-edit-mode" title="{{t this.tooltip}}">','<i class="material-icons">{{this.logoClass}}</i>',"</a>","{{/each}}","{{#if showStrokeStyle}}",'<a class="hud-control hud-dropdown hud-disabled mirador-line-type" aria-label="{{t "borderTypeTooltip"}}" title="{{t "borderTypeTooltip"}}">','<i class="material-icons mirador-border-icon">create</i>','<i class="border-type-image solid"></i>','<i class="fa fa-caret-down dropdown-icon"></i>','<ul class="dropdown type-list">','<li><i class="fa solid"></i> {{t "solid"}}</li>','<li><i class="fa dashed"></i> {{t "dashed"}}</li>','<li><i class="fa dotdashed"></i> {{t "dotDashed"}}</li>',"</ul>","</a>","{{/if}}","{{#if showStrokeColor}}",'<a class="hud-control hud-dropdown hud-disabled mirador-osd-color-picker" title="{{t "borderColorTooltip"}}">','<input type="text" class="borderColorPicker"/>',"</a>","{{/if}}","{{#if showFillColor}}",'<a class="hud-control hud-dropdown hud-disabled mirador-osd-color-picker" title="{{t "fillColorTooltip"}}">','<input type="text" class="fillColorPicker"/>',"</a>","{{/if}}","{{#if showRefresh}}",'<a class="hud-control mirador-osd-refresh-mode">','<i class="fa fa-lg fa-refresh"></i>',"</a>","{{/if}}","{{/if}}"].join("")),manipulationTemplate:Handlebars.compile(["{{#if showRotate}}",'<a class="hud-control mirador-osd-rotate-right" title="{{t "rotateRightTooltip"}}">','<i class="fa fa-lg fa-rotate-right"></i>',"</a>",'<a class="hud-control mirador-osd-rotate-left" title="{{t "rotateLeftTooltip"}}">','<i class="fa fa-lg fa-rotate-left"></i>',"</a>","{{/if}}","{{#if filtersSupported}}","{{#if showBrightness}}",'<a class="hud-control mirador-osd-brightness" title="{{t "brightnessTooltip"}}">','<i class="material-icons">wb_sunny</i>','<i class="fa fa-caret-down"></i>','<div class="mirador-osd-brightness-slider mirador-slider"/>',"</a>","{{/if}}","{{#if showContrast}}",'<a class="hud-control mirador-osd-contrast" title="{{t "contrastTooltip"}}">','<i class="material-icons">brightness_6</i>','<i class="fa fa-caret-down"></i>','<div class="mirador-osd-contrast-slider mirador-slider"/>',"</a>","{{/if}}","{{#if showSaturate}}",'<a class="hud-control mirador-osd-saturation" title="{{t "saturationTooltip"}}">','<i class="material-icons">gradient</i>','<i class="fa fa-caret-down"></i>','<div class="mirador-osd-saturation-slider mirador-slider"/>',"</a>","{{/if}}","{{#if showGrayscale}}",'<a class="hud-control mirador-osd-grayscale" title="{{t "grayscaleTooltip"}}">','<i class="material-icons">filter_b_and_w</i>',"</a>","{{/if}}","{{#if showInvert}}",'<a class="hud-control mirador-osd-invert" title="{{t "invertTooltip"}}">','<i class="material-icons">invert_colors</i>',"</a>","{{/if}}",'<a class="hud-control mirador-osd-reset" title="{{t "resetTooltip"}}">','<i class="fa fa-lg fa-refresh"></i>',"</a>","{{/if}}"].join("")),editorTemplate:Handlebars.compile(['<div class="mirador-osd-context-controls hud-container">','<a class="mirador-osd-back hud-control" role="button">','<i class="fa fa-lg fa-arrow-left"></i>',"</a>",'<a class="mirador-osd-rect-tool hud-control" role ="buton">','<i class="fa fa-lg fa-pencil-square"></i>',"</a>",'<a class="mirador-osd-rect-tool hud-control" role="button">','<i class="fa fa-lg fa-ellipsis-h"></i>',"</a>",'<a class="mirador-osd-rect-tool hud-control" role="button">','<i class="fa fa-lg fa-gear"></i>',"</a>","</div>"].join(""))}}(Mirador),function($){$.Hud=function(options){jQuery.extend(this,{element:null,windowId:null,annoState:null,annoEndpointAvailable:!1,eventEmitter:null},options),this.init()},$.Hud.prototype={init:function(){this.createStateMachines();var showAnno="undefined"!=typeof this.showAnno?this.showAnno:this.canvasControls.annotations.annotationLayer,showImageControls="undefined"!=typeof this.showImageControls?this.showImageControls:this.canvasControls.imageManipulation.manipulationLayer;this.element=jQuery(this.template({showNextPrev:this.showNextPrev,showBottomPanel:"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable,showAnno:showAnno,showImageControls:showImageControls})).appendTo(this.appendTo),(showAnno||showImageControls)&&(this.contextControls=new $.ContextControls({element:null,container:this.element.find(".mirador-osd-context-controls"),qtipElement:this.qtipElement,mode:"displayAnnotations",windowId:this.windowId,canvasControls:this.canvasControls,annoEndpointAvailable:this.annoEndpointAvailable,availableAnnotationTools:this.availableAnnotationTools,availableAnnotationStylePickers:this.availableAnnotationStylePickers,state:this.state,eventEmitter:this.eventEmitter})),this.listenForActions(),this.bindEvents()},listenForActions:function(){var _this=this;this.eventEmitter.subscribe("DISABLE_TOOLTIPS_BY_CLASS."+this.windowId,function(event,className){_this.element.find(className).qtip("disable")}),this.eventEmitter.subscribe("ENABLE_TOOLTIPS_BY_CLASS."+this.windowId,function(event,className){_this.element.find(className).qtip("enable")}),this.eventEmitter.subscribe("SET_STATE_MACHINE_POINTER."+this.windowId,function(event){"none"===_this.annoState.current?_this.annoState.startup():"off"===_this.annoState.current?_this.annoState.displayOn():_this.annoState.choosePointer()})},bindEvents:function(){},createStateMachines:function(){var _this=this;this.annoState=StateMachine.create({events:[{name:"startup",from:"none",to:"off"},{name:"displayOn",from:"off",to:"pointer"},{name:"displayOff",from:["pointer","shape"],to:"off"},{name:"choosePointer",from:["pointer","shape"],to:"pointer"},{name:"chooseShape",from:"pointer",to:"shape"},{name:"changeShape",from:"shape",to:"shape"},{name:"refresh",from:"pointer",to:"pointer"},{name:"refresh",from:"shape",to:"shape"}],callbacks:{onstartup:function(event,from,to){_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},ondisplayOn:function(event,from,to){_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-annotations-layer","selected"]),_this.annoEndpointAvailable&&_this.contextControls.annotationShow(),_this.eventEmitter.publish("modeChange."+_this.windowId,"displayAnnotations"),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("DISABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("DEFAULT_CURSOR."+_this.windowId),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},ondisplayOff:function(event,from,to){_this.annoEndpointAvailable&&(_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("CANCEL_ACTIVE_ANNOTATIONS."+_this.windowId),_this.contextControls.annotationHide()),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-annotations-layer","selected"]),_this.eventEmitter.publish("modeChange."+_this.windowId,"default"),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onchoosePointer:function(event,from,to){_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("DISABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("modeChange."+_this.windowId,"displayAnnotations"),_this.eventEmitter.publish("DEFAULT_CURSOR."+_this.windowId),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onchooseShape:function(event,from,to,shape){_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("ENABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-"+shape+"-mode","selected"]),_this.eventEmitter.publish("modeChange."+_this.windowId,"creatingAnnotation"),_this.eventEmitter.publish("CROSSHAIR_CURSOR."+_this.windowId),
86
- _this.eventEmitter.publish("toggleDrawingTool."+_this.windowId,shape),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onchangeShape:function(event,from,to,shape){_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("ENABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-"+shape+"-mode","selected"]),_this.eventEmitter.publish("CROSSHAIR_CURSOR."+_this.windowId),_this.eventEmitter.publish("toggleDrawingTool."+_this.windowId,shape),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onrefresh:function(event,from,to){}}}),this.manipulationState=StateMachine.create({events:[{name:"startup",from:"none",to:"manipulationOff"},{name:"displayOn",from:"manipulationOff",to:"manipulationOn"},{name:"displayOff",from:"manipulationOn",to:"manipulationOff"}],callbacks:{onstartup:function(event,from,to){_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,manipulationState:to})},ondisplayOn:function(event,from,to){_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-manipulation-toggle","selected"]),_this.contextControls.manipulationShow(),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,manipulationState:to})},ondisplayOff:function(event,from,to){_this.contextControls.manipulationHide(),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-manipulation-toggle","selected"]),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,manipulationState:to})}}})},template:Handlebars.compile(['<div class="mirador-hud">',"{{#if showNextPrev}}",'<a class="mirador-osd-previous hud-control ">','<i class="fa fa-3x fa-chevron-left "></i>',"</a>","{{/if}}",'<div class="mirador-osd-context-controls hud-container">',"{{#if showAnno}}",'<div class="mirador-osd-annotation-controls">','<a class="mirador-osd-annotations-layer hud-control" role="button" title="{{t "annotationTooltip"}}" aria-label="{{t "annotationTooltip"}}">','<i class="fa fa-lg fa-comments"></i>',"</a>","</div>","{{/if}}","{{#if showImageControls}}",'<div class="mirador-manipulation-controls">','<a class="mirador-manipulation-toggle hud-control" role="button" title="{{t "imageManipulationTooltip"}}" aria-label="{{t "imageManipulationTooltip"}}">','<i class="material-icons">tune</i>',"</a>","</div>","{{/if}}","</div>","{{#if showNextPrev}}",'<a class="mirador-osd-next hud-control ">','<i class="fa fa-3x fa-chevron-right"></i>',"</a>","{{/if}}","{{#if showBottomPanel}}",'<a class="mirador-osd-toggle-bottom-panel hud-control" role="button" aria-label="Toggle Bottom Panel">','<i class="fa fa-2x fa-ellipsis-h"></i>',"</a>","{{/if}}",'<div class="mirador-pan-zoom-controls hud-control">','<a class="mirador-osd-up hud-control" role="button" aria-label="Move image up">','<i class="fa fa-chevron-circle-up"></i>',"</a>",'<a class="mirador-osd-right hud-control" role="button" aria-label="Move image right">','<i class="fa fa-chevron-circle-right"></i>',"</a>",'<a class="mirador-osd-down hud-control" role="button" aria-label="Move image down">','<i class="fa fa-chevron-circle-down"></i>',"</a>",'<a class="mirador-osd-left hud-control" role="button" aria-label="Move image left">','<i class="fa fa-chevron-circle-left"></i>',"</a>",'<a class="mirador-osd-zoom-in hud-control" role="button" aria-label="Zoom in">','<i class="fa fa-plus-circle"></i>',"</a>",'<a class="mirador-osd-zoom-out hud-control" role="button" aria-label="Zoom out">','<i class="fa fa-minus-circle"></i>',"</a>",'<a class="mirador-osd-go-home hud-control" role="button" aria-label="Reset image bounds">','<i class="fa fa-home"></i>',"</a>","</div>","</div>"].join(""))}}(Mirador),function($){$.ImageView=function(options){jQuery.extend(this,{currentImg:null,windowId:null,currentImgIndex:0,canvasID:null,imagesList:[],element:null,elemOsd:null,manifest:null,osd:null,osdOptions:{osdBounds:null,zoomLevel:null},osdCls:"mirador-osd",elemAnno:null,annoCls:"annotation-canvas",annotationsLayer:null,forceShowControls:!1,eventEmitter:null},options),this.init()},$.ImageView.prototype={init:function(){var _this=this;null!==this.canvasID&&(this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID)),this.osdOptions||(this.osdOptions={osdBounds:null,zoomLevel:null}),this.currentImg=this.imagesList[this.currentImgIndex],this.element=jQuery(this.template()).appendTo(this.appendTo),this.elemAnno=jQuery("<div/>").addClass(this.annoCls).appendTo(this.element),this.createOpenSeadragonInstance($.Iiif.getImageUrl(this.currentImg)),_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:[this.canvasID]});var allTools=$.getTools(this.state.getStateProperty("drawingToolsSettings"));this.availableAnnotationTools=[];for(var i=0;i<this.state.getStateProperty("availableAnnotationDrawingTools").length;i++)for(var j=0;j<allTools.length;j++)if(this.state.getStateProperty("availableAnnotationDrawingTools")[i]==allTools[j].name){var values={};values.logoClass=allTools[j].logoClass,values.tooltip=allTools[j].tooltip,this.availableAnnotationTools.push(values)}this.hud=new $.Hud({appendTo:this.element,qtipElement:this.qtipElement,bottomPanelAvailable:this.bottomPanelAvailable,windowId:this.windowId,canvasControls:this.canvasControls,annoEndpointAvailable:this.annoEndpointAvailable,showNextPrev:1!==this.imagesList.length,availableAnnotationStylePickers:this.state.getStateProperty("availableAnnotationStylePickers"),availableAnnotationTools:this.availableAnnotationTools,state:this.state,eventEmitter:this.eventEmitter}),this.bindEvents(),this.listenForActions(),"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable?_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,null):_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,!1)},template:Handlebars.compile(['<div class="image-view">',"</div>"].join("")),listenForActions:function(){var _this=this,firstCanvasId=_this.imagesList[0]["@id"],lastCanvasId=_this.imagesList[_this.imagesList.length-1]["@id"];_this.eventEmitter.subscribe("bottomPanelSet."+_this.windowId,function(event,visible){var dodgers=_this.element.find(".mirador-osd-toggle-bottom-panel, .mirador-pan-zoom-controls"),arrows=_this.element.find(".mirador-osd-next, .mirador-osd-previous");visible===!0?(dodgers.addClass("bottom-panel-open"),arrows.addClass("bottom-panel-open")):(dodgers.removeClass("bottom-panel-open"),arrows.removeClass("bottom-panel-open"))}),_this.eventEmitter.subscribe("fitBounds."+_this.windowId,function(event,bounds){var rect=_this.osd.viewport.imageToViewportRectangle(Number(bounds.x),Number(bounds.y),Number(bounds.width),Number(bounds.height));_this.osd.viewport.fitBoundsWithConstraints(rect,!1)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasId){canvasId===firstCanvasId?(_this.element.find(".mirador-osd-previous").hide(),_this.element.find(".mirador-osd-next").show()):canvasId===lastCanvasId?(_this.element.find(".mirador-osd-next").hide(),_this.element.find(".mirador-osd-previous").show()):(_this.element.find(".mirador-osd-next").show(),_this.element.find(".mirador-osd-previous").show())}),_this.eventEmitter.subscribe("HUD_REMOVE_CLASS."+_this.windowId,function(event,elementSelector,className){_this.element.find(elementSelector).removeClass(className)}),_this.eventEmitter.subscribe("HUD_ADD_CLASS."+_this.windowId,function(event,elementSelector,className){_this.element.find(elementSelector).addClass(className)}),_this.eventEmitter.subscribe("HUD_FADE_IN."+_this.windowId,function(event,elementSelector,duration){_this.element.find(elementSelector).fadeIn(duration)}),_this.eventEmitter.subscribe("HUD_FADE_OUT."+_this.windowId,function(event,elementSelector,duration,complete){_this.element.find(elementSelector).fadeOut(duration,complete)}),_this.eventEmitter.subscribe("DEFAULT_CURSOR."+_this.windowId,function(event){jQuery(_this.osd.canvas).css("cursor","default")}),_this.eventEmitter.subscribe("CROSSHAIR_CURSOR."+_this.windowId,function(event){jQuery(_this.osd.canvas).css("cursor","crosshair")}),_this.eventEmitter.subscribe("POINTER_CURSOR."+_this.windowId,function(event){jQuery(_this.osd.canvas).css("cursor","pointer")})},bindEvents:function(){function setFilterCSS(){var filterCSS=jQuery.map(filterValues,function(value,key){return value}).join(" "),osdCanvas=jQuery(_this.osd.drawer.canvas);osdCanvas.css({filter:filterCSS,"-webkit-filter":filterCSS,"-moz-filter":filterCSS,"-o-filter":filterCSS,"-ms-filter":filterCSS})}function resetImageManipulationControls(){_this.osd&&_this.osd.viewport.setRotation(0),filterValues.brightness="brightness(100%)",_this.element.find(".mirador-osd-brightness-slider").slider("option","value",100),_this.element.find(".mirador-osd-brightness-slider").find(".percent").text("100%"),filterValues.contrast="contrast(100%)",_this.element.find(".mirador-osd-contrast-slider").slider("option","value",100),_this.element.find(".mirador-osd-contrast-slider").find(".percent").text("100%"),filterValues.saturate="saturate(100%)",_this.element.find(".mirador-osd-saturation-slider").slider("option","value",100),_this.element.find(".mirador-osd-saturation-slider").find(".percent").text("100%"),filterValues.grayscale="grayscale(0%)",_this.element.find(".mirador-osd-grayscale").removeClass("selected"),filterValues.invert="invert(0%)",_this.element.find(".mirador-osd-invert").removeClass("selected"),setFilterCSS()}var _this=this;this.element.find(".mirador-osd-next").on("click",function(){_this.next()}),this.element.find(".mirador-osd-previous").on("click",function(){_this.previous()}),this.element.find(".mirador-osd-annotations-layer").on("click",function(){"none"===_this.hud.annoState.current&&_this.hud.annoState.startup(this),"off"===_this.hud.annoState.current?(_this.hud.annoState.displayOn(this),_this.annotationState="on"):(_this.forceShowControls=!1,_this.hud.annoState.displayOff(this),_this.annotationState="off")}),this.element.find(".mirador-manipulation-toggle").on("click",function(){"none"===_this.hud.manipulationState.current&&_this.hud.manipulationState.startup(this),"manipulationOff"===_this.hud.manipulationState.current?_this.hud.manipulationState.displayOn(this):_this.hud.manipulationState.displayOff(this)}),this.element.find(".mirador-osd-go-home").on("click",function(){_this.osd.viewport.goHome()}),this.element.find(".mirador-osd-up").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,-panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-right").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-down").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-left").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(-panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-zoom-in").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(osd.zoomPerClick/1),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-zoom-out").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(1/osd.zoomPerClick),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-toggle-bottom-panel").on("click",function(){_this.eventEmitter.publish("TOGGLE_BOTTOM_PANEL_VISIBILITY."+_this.windowId)}),this.element.find(".mirador-osd-edit-mode").on("click",function(){var shape=jQuery(this).find(".material-icons").html();"pointer"===_this.hud.annoState.current?_this.hud.annoState.chooseShape(shape):_this.hud.annoState.changeShape(shape),_this.forceShowControls=!0,_this.element.find(".hud-control").stop(!0,!0).removeClass("hidden",_this.state.getStateProperty("fadeDuration"))}),this.element.find(".mirador-osd-pointer-mode").on("click",function(){"shape"===_this.hud.annoState.current&&(_this.hud.annoState.choosePointer(),_this.forceShowControls=!1)}),this.element.find(".mirador-osd-refresh-mode").on("click",function(){_this.eventEmitter.publish("updateAnnotationList."+_this.windowId)});var filterValues={brightness:"brightness(100%)",contrast:"contrast(100%)",saturate:"saturate(100%)",grayscale:"grayscale(0%)",invert:"invert(0%)"};this.element.find(".mirador-osd-rotate-right").on("click",function(){if(_this.osd){var currentRotation=_this.osd.viewport.getRotation();_this.osd.viewport.setRotation(currentRotation+90)}}),this.element.find(".mirador-osd-rotate-left").on("click",function(){if(_this.osd){var currentRotation=_this.osd.viewport.getRotation();_this.osd.viewport.setRotation(currentRotation-90)}}),this.element.find(".mirador-osd-brightness-slider").slider({orientation:"vertical",range:"min",min:0,max:200,value:100,create:function(event,ui){var v=jQuery(this).slider("value"),span=jQuery('<span class="percent">').text(v+"%");jQuery(this).find(".ui-slider-handle").append(span)},slide:function(event,ui){filterValues.brightness="brightness("+ui.value+"%)",setFilterCSS(),jQuery(this).find(".percent").text(ui.value+"%")}}).hide(),this.element.find(".mirador-osd-brightness").on("mouseenter",function(){_this.element.find(".mirador-osd-brightness-slider").stop(!0,!0).show()}).on("mouseleave",function(){_this.element.find(".mirador-osd-brightness-slider").stop(!0,!0).hide()}),this.element.find(".mirador-osd-contrast-slider").slider({orientation:"vertical",range:"min",min:0,max:200,value:100,create:function(event,ui){var v=jQuery(this).slider("value"),span=jQuery('<span class="percent">').text(v+"%");jQuery(this).find(".ui-slider-handle").append(span)},slide:function(event,ui){filterValues.contrast="contrast("+ui.value+"%)",setFilterCSS(),jQuery(this).find(".percent").text(ui.value+"%")}}).hide(),this.element.find(".mirador-osd-contrast").on("mouseenter",function(){_this.element.find(".mirador-osd-contrast-slider").stop(!0,!0).show()}).on("mouseleave",function(){_this.element.find(".mirador-osd-contrast-slider").stop(!0,!0).hide()}),this.element.find(".mirador-osd-saturation-slider").slider({orientation:"vertical",range:"min",min:0,max:200,value:100,create:function(event,ui){var v=jQuery(this).slider("value"),span=jQuery('<span class="percent">').text(v+"%");jQuery(this).find(".ui-slider-handle").append(span)},slide:function(event,ui){filterValues.saturate="saturate("+ui.value+"%)",setFilterCSS(),jQuery(this).find(".percent").text(ui.value+"%")}}).hide(),this.element.find(".mirador-osd-saturation").on("mouseenter",function(){_this.element.find(".mirador-osd-saturation-slider").stop(!0,!0).show()}).on("mouseleave",function(){_this.element.find(".mirador-osd-saturation-slider").stop(!0,!0).hide()}),this.element.find(".mirador-osd-grayscale").on("click",function(){jQuery(this).hasClass("selected")?(filterValues.grayscale="grayscale(0%)",jQuery(this).removeClass("selected")):(filterValues.grayscale="grayscale(100%)",jQuery(this).addClass("selected")),setFilterCSS()}),this.element.find(".mirador-osd-invert").on("click",function(){jQuery(this).hasClass("selected")?(filterValues.invert="invert(0%)",jQuery(this).removeClass("selected")):(filterValues.invert="invert(100%)",jQuery(this).addClass("selected")),setFilterCSS()}),this.element.find(".mirador-osd-reset").on("click",function(){resetImageManipulationControls()}),this.eventEmitter.subscribe("resetImageManipulationControls."+this.windowId,function(){resetImageManipulationControls()})},getPanByValue:function(){var bounds=this.osd.viewport.getBounds(!0),panBy={x:.5*bounds.width,y:.5*bounds.height};return panBy},setBounds:function(){var _this=this;this.osdOptions.osdBounds=this.osd.viewport.getBounds(!0),_this.eventEmitter.publish("imageBoundsUpdated",{id:_this.windowId,osdBounds:{x:_this.osdOptions.osdBounds.x,y:_this.osdOptions.osdBounds.y,width:_this.osdOptions.osdBounds.width,height:_this.osdOptions.osdBounds.height}});var rectangle=this.osd.viewport.viewportToImageRectangle(this.osdOptions.osdBounds);_this.eventEmitter.publish("imageRectangleUpdated",{id:_this.windowId,osdBounds:{x:Math.round(rectangle.x),y:Math.round(rectangle.y),width:Math.round(rectangle.width),height:Math.round(rectangle.height)}})},toggle:function(stateValue){stateValue?this.show():this.hide()},hide:function(){jQuery(this.element).hide({effect:"fade",duration:300,easing:"easeOutCubic"})},show:function(){jQuery(this.element).show({effect:"fade",duration:300,easing:"easeInCubic",complete:function(){jQuery(this).css("display","block")}})},adjustWidth:function(className,hasClass){var _this=this;hasClass?_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,className):_this.eventEmitter.publish("ADD_CLASS."+this.windowId,className)},adjustHeight:function(className,hasClass){hasClass?this.element.removeClass(className):this.element.addClass(className)},createOpenSeadragonInstance:function(imageUrl){var infoJsonUrl=imageUrl+"/info.json",uniqueID=$.genUUID(),osdID="mirador-osd-"+uniqueID,_this=this;this.element.find("."+this.osdCls).remove(),jQuery.getJSON(infoJsonUrl).done(function(infoJson,status,jqXHR){_this.elemOsd=jQuery("<div/>").addClass(_this.osdCls).attr("id",osdID).appendTo(_this.element),_this.osd=$.OpenSeadragon({id:osdID,tileSources:infoJson,uniqueID:uniqueID}),_this.osd.addHandler("zoom",$.debounce(function(){var point={x:-1e7,y:-1e7};_this.eventEmitter.publish("updateTooltips."+_this.windowId,[point,point])},30)),_this.osd.addHandler("pan",$.debounce(function(){var point={x:-1e7,y:-1e7};_this.eventEmitter.publish("updateTooltips."+_this.windowId,[point,point])},30)),_this.osd.addHandler("open",function(){if(_this.eventEmitter.publish("osdOpen."+_this.windowId),_this.osdOptions.osdBounds){var rect=new OpenSeadragon.Rect(_this.osdOptions.osdBounds.x,_this.osdOptions.osdBounds.y,_this.osdOptions.osdBounds.width,_this.osdOptions.osdBounds.height);_this.osd.viewport.fitBounds(rect,!0)}else _this.setBounds();_this.addAnnotationsLayer(_this.elemAnno);var originalState=_this.hud.annoState.current,selected=_this.element.find(".mirador-osd-edit-mode.selected"),shape=null;selected&&(shape=selected.find(".material-icons").html()),"none"===originalState?_this.hud.annoState.startup():"off"===originalState||"off"===_this.annotationState||_this.hud.annoState.displayOff(),"pointer"===originalState||"on"===_this.annotationState?_this.hud.annoState.displayOn():"shape"===originalState&&(_this.hud.annoState.displayOn(),_this.hud.annoState.chooseShape(shape)),_this.osd.addHandler("zoom",$.debounce(function(){_this.setBounds()},500)),_this.osd.addHandler("pan",$.debounce(function(){_this.setBounds()},500))})})},addAnnotationsLayer:function(element){var _this=this;_this.annotationsLayer=new $.AnnotationsLayer({state:_this.state,annotationsList:_this.state.getWindowAnnotationsList(_this.windowId)||[],viewer:_this.osd,windowId:_this.windowId,element:element,eventEmitter:_this.eventEmitter})},updateImage:function(canvasID){var _this=this;this.canvasID!==canvasID?(this.canvasID=canvasID,this.currentImgIndex=$.getImageIndexById(this.imagesList,canvasID),this.currentImg=this.imagesList[this.currentImgIndex],this.osdOptions={osdBounds:null,zoomLevel:null},this.eventEmitter.publish("resetImageManipulationControls."+this.windowId),this.osd.close(),this.createOpenSeadragonInstance($.Iiif.getImageUrl(this.currentImg)),_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:[canvasID]})):_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:[canvasID]})},next:function(){var _this=this,next=this.currentImgIndex+1;next<this.imagesList.length&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[next]["@id"])},previous:function(){var _this=this,prev=this.currentImgIndex-1;prev>=0&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[prev]["@id"])}}}(Mirador),function($){$.LayersTab=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,visible:null,state:null,eventEmitter:null},options),this.init()},$.LayersTab.prototype={init:function(){this.windowId=this.windowId,this.localState({id:"layersTab",visible:this.visible,selectedList:null,empty:!0},!0),this.listenForActions(),this.render(this.localState()),this.loadTabComponents(),this.bindEvents()},localState:function(state,initial){var _this=this;return arguments.length?(this.layerTabState=state,initial||_this.eventEmitter.publish("layersTabStateUpdated."+this.windowId,this.layerTabState),this.layerTabState):this.layerTabState},loadTabComponents:function(){},tabStateUpdated:function(visible){var localState=this.localState();localState.visible=!localState.visible,this.localState(localState)},toggle:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("layersTabStateUpdated."+_this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("tabStateUpdated."+_this.windowId,function(_,data){_this.tabStateUpdated(data.layersTab)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasID){})},bindEvents:function(){},render:function(state){var _this=this,templateData={};this.element&&_this.appendTo.find(".layersPanel").remove(),this.element=jQuery(_this.template(templateData)).appendTo(_this.appendTo),_this.bindEvents(),state.visible?this.element.show():this.element.hide()},template:Handlebars.compile(['<div class="layersPanel">',"</div>"].join(""))}}(Mirador),function($){$.MetadataView=function(options){jQuery.extend(this,{manifest:null,element:null,metadataTypes:null,metadataListingCls:"metadata-listing"},options),this.init()},$.MetadataView.prototype={init:function(){var _this=this,tplData={metadataListingCls:this.metadataListingCls};if(_this.manifest=_this.manifest.jsonLd,this.metadataTypes={},this.metadataTypes.details=_this.getMetadataDetails(_this.manifest),this.metadataTypes.rights=_this.getMetadataRights(_this.manifest),this.metadataTypes.links=_this.getMetadataLinks(_this.manifest),jQuery.each(this.metadataTypes,function(metadataKey,metadataValues){tplData[metadataKey]=[],jQuery.each(metadataValues,function(idx,itm){"object"==typeof itm.value&&(itm.value=_this.stringifyObject(itm.value)),"string"==typeof itm.value&&""!==itm.value&&tplData[metadataKey].push({label:_this.extractLabelFromAttribute(itm.label),value:"links"===metadataKey?itm.value:_this.addLinksToUris(itm.value)})})}),_this.manifest.logo){var logo="";"string"==typeof _this.manifest.logo?logo=_this.manifest.logo:"undefined"!=typeof _this.manifest.logo["@id"]&&(logo=_this.manifest.logo["@id"]),tplData.logo=logo}this.element=jQuery(this.template(tplData)).appendTo(this.appendTo),this.bindEvents()},stringifyObject:function(obj,nestingMargin){var str,_this=this,first=!0,increment=15,delimiter="<br/>";if(obj instanceof RegExp)return"/"+obj.source+"/";if("undefined"==typeof nestingMargin&&(nestingMargin=0),obj instanceof Array)return str="[ ",jQuery.each(obj,function(i,item){str+=(0===i?"":", ")+_this.stringifyObject(item,nestingMargin+increment)}),str+" ]";if("object"==typeof obj&&"sc:Collection"===obj["@type"]){var collectionUrl=obj["@id"],collectionLabel=obj.label||collectionUrl;return'<a href="'+collectionUrl+'" target="_blank">'+collectionLabel+"</a>"}if("object"==typeof obj){str='<div style="margin-left:'+nestingMargin+'px">';for(var i in obj)obj.hasOwnProperty(i)&&(str+=(first?"":delimiter)+i+": "+_this.stringifyObject(obj[i],nestingMargin+increment),first=!1);return str+"</div>"}return obj.toString()},stringifyRelated:function(obj){var str,next,label,format,_this=this;return obj instanceof Array?(str="",jQuery.each(obj,function(i,item){next=_this.stringifyRelated(item),""!==next&&(str+=(0===i?"":"<br/>")+next)}),str):"object"==typeof obj&&"@id"in obj?(label="label"in obj?obj.label:obj["@id"],format="format"in obj&&"text/html"!==obj.format?"("+obj.format+")":"",'<a href="'+obj["@id"]+'" target="_blank">'+label+"</a> "+format):_this.addLinksToUris(obj.toString())},getMetadataDetails:function(jsonLd){var mdList=[{label:"label",value:"<b>"+($.JsonLd.getTextValue(jsonLd.label)||"")+"</b>"},{label:"description",value:$.JsonLd.getTextValue(jsonLd.description)||""}];return jsonLd.metadata&&(value="",label="",jQuery.each(jsonLd.metadata,function(index,item){label=$.JsonLd.getTextValue(item.label),value=$.JsonLd.getTextValue(item.value),mdList.push({label:label,value:value})})),mdList},getMetadataRights:function(jsonLd){return[{label:i18next.t("license"),value:jsonLd.license||""},{label:i18next.t("attribution"),value:$.JsonLd.getTextValue(jsonLd.attribution)||""}]},getMetadataLinks:function(jsonLd){return[{label:i18next.t("related"),value:this.stringifyRelated(jsonLd.related||"")},{label:i18next.t("seeAlso"),value:this.stringifyRelated(jsonLd.seeAlso||"")},{label:i18next.t("within"),value:this.getWithin(jsonLd.within||"")}]},getWithin:function(within){if("object"==typeof within&&"sc:Collection"===within["@type"]){var collectionUrl=within["@id"],collectionLabel=within.label||collectionUrl;return'<a href="'+collectionUrl+'" target="_blank">'+collectionLabel+"</a>"}return within instanceof Array?within.map(this.getWithin).join("<br/>"):this.stringifyObject(within)},extractLabelFromAttribute:function(attr){var label=attr;return label=label.replace(/^@/,""),label=label.replace(/\s{2,}/g," ")},bindEvents:function(){},toggle:function(stateValue){stateValue?this.show():this.hide()},show:function(){var element=jQuery(this.element);this.panel&&(element=element.parent()),element.show({effect:"slide",direction:"right",duration:300,easing:"swing"})},hide:function(){var element=jQuery(this.element);this.panel&&(element=element.parent()),element.hide({effect:"slide",direction:"right",duration:300,easing:"swing"})},addLinksToUris:function(text){var matches,parsedTextWithLinks,regexUrl=/(http|ftp|https):\/\/[\w\-]+(\.[\w\-]+)+([\w.,@?\^=%&amp;:\/~+#\-]*[\w@?\^=%&amp;\/~+#\-])?/gi,textWithLinks=text;return"string"==typeof text&&(textWithLinks.indexOf("<a ")===-1?(matches=text.match(regexUrl),matches&&jQuery.each(matches,function(index,match){textWithLinks=textWithLinks.replace(match,'<a href="'+match+'" target="_blank">'+match+"</a>")})):(parsedTextWithLinks=jQuery("<div />").append(textWithLinks),jQuery(parsedTextWithLinks[0]).find("a").attr("target","_blank"),textWithLinks=parsedTextWithLinks[0].innerHTML)),textWithLinks},template:Handlebars.compile(['<div class="sub-title">{{t "details"}}:</div>','<div class="{{metadataListingCls}}">',"{{#each details}}",'<div class="metadata-item"><div class="metadata-label">{{label}}:</div><div class="metadata-value">{{{value}}}</div></div>',"{{/each}}","</div>",'<div class="sub-title">{{t "rights"}}:</div>',"{{#if rights}}",'<div class="{{metadataListingCls}}">',"{{#each rights}}",'<div class="metadata-item"><div class="metadata-label">{{label}}:</div><div class="metadata-value">{{{value}}}</div></div>',"{{/each}}","{{#if logo}}",'<div class="metadata-item"><div class="metadata-label">{{t "logo"}}:</div><img class="metadata-logo" src="{{logo}}"/></div>',"{{/if}}","</div>","{{else}}",'<div class="{{metadataListingCls}}">','<div class="metadata-item"><div class="metadata-label">{{t "rightsStatus"}}:</div><div class="metadata-value">{{t "unspecified"}}</div></div>',"</div>","{{/if}}","{{#if links}}",'<div class="sub-title">{{t "links"}}:</div>','<div class="{{metadataListingCls}}">',"{{#each links}}",'<div class="metadata-item"><div class="metadata-label">{{label}}:</div><div class="metadata-value">{{{value}}}</div></div>',"{{/each}}","</dl>","{{/if}}"].join(""),{noEscape:!0})}}(Mirador),function($){$.ScrollView=function(options){jQuery.extend(this,{currentImgIndex:0,canvasID:null,focusImages:[],manifest:null,element:null,imagesList:[],appendTo:null,thumbInfo:{thumbsHeight:150,listingCssCls:"listing-thumbs",thumbnailCls:"thumbnail-view"},windowId:null,panel:!1,lazyLoadingFactor:1.5},options),jQuery.extend($.ScrollView.prototype,$.ThumbnailsView.prototype),this.init()}}(Mirador),function($){$.SidePanel=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,panelState:{},tocTabAvailable:!1,annotationsTabAvailable:!1,layersTabAvailable:!1,toolsTabAvailable:!1,hasStructures:!1,state:null,eventEmitter:null},options),this.init()},$.SidePanel.prototype={init:function(){var _this=this;this.updateState({tabs:[{name:"toc",options:{available:_this.tocTabAvailable,id:"tocTab",label:"Index"}},{name:"layers",options:{available:_this.layersTabAvailable,id:"layersTab",label:"Layers"}}],width:280,open:!0},!0),this.listenForActions(),this.render(this.updateState()),this.loadSidePanelComponents()},loadSidePanelComponents:function(){var _this=this;new $.Tabs({windowId:this.windowId,appendTo:this.appendTo,tabs:this.panelState.tabs,hasStructures:this.hasStructures,eventEmitter:this.eventEmitter}),this.tocTabAvailable&&new $.TableOfContents({structures:this.manifest.getStructures(),appendTo:this.element.find(".tabContentArea"),windowId:this.windowId,canvasID:this.canvasID,manifestVersion:this.manifest.getVersion(),eventEmitter:this.eventEmitter}),_this.annotationsTabAvailable&&new $.AnnotationsTab({manifest:_this.manifest,windowId:this.windowId,appendTo:_this.element.find(".tabContentArea"),state:_this.state,eventEmitter:_this.eventEmitter}),_this.layersTabAvailable&&new $.LayersTab({manifest:_this.manifest,windowId:this.windowId,appendTo:_this.element.find(".tabContentArea"),canvasID:this.canvasID,state:_this.state,eventEmitter:_this.eventEmitter})},update:function(name,availability){var updatedState=this.panelState;jQuery.each(updatedState.tabs,function(index,value){value.name===name&&(value.options.available=availability)}),this.updateState(updatedState)},updateState:function(newState,initial){var _this=this;return arguments.length?(jQuery.extend(!0,this.panelState,newState),initial||_this.eventEmitter.publish("sidePanelStateUpdated."+this.windowId,this.panelState),this.panelState):this.panelState},panelToggled:function(){var currentState=this.updateState(),open=!currentState.open;currentState.open=open,this.updateState(currentState)},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("sidePanelStateUpdated."+this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("sidePanelResized",function(){}),_this.eventEmitter.subscribe("sidePanelToggled."+this.windowId,function(){_this.panelToggled()}),_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(event){var windowObject=_this.state.getWindowObjectById(_this.windowId);windowObject.annotationsAvailable[windowObject.viewType]&&_this.state.getWindowAnnotationsList(_this.windowId).length>0&&_this.update("annotations",!0)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,newCanvasId){_this.canvasID=newCanvasId})},render:function(renderingData){var _this=this;if(!this.element)return this.element=this.appendTo,void jQuery(_this.template(renderingData)).appendTo(_this.appendTo)},template:Handlebars.compile(['<div class="tabContentArea">','<ul class="tabGroup">',"</ul>","</div>"].join("")),toggle:function(enableSidePanel){var _this=this;enableSidePanel?(jQuery(this.appendTo).show({effect:"fade",duration:300,easing:"easeInCubic"}),_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,"focus-max-width"),_this.eventEmitter.publish("SHOW_ICON_TOC."+this.windowId)):(jQuery(this.appendTo).hide(),_this.eventEmitter.publish("ADD_CLASS."+this.windowId,"focus-max-width"),_this.eventEmitter.publish("HIDE_ICON_TOC."+this.windowId));
87
- }}}(Mirador),function($){$.WidgetStatusBar=function(options){jQuery.extend(!0,this,{},$.DEFAULT_SETTINGS,options)},$.WidgetStatusBar.prototype={}}(Mirador),function($){$.Tabs=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,windowId:null,tabState:{},tabs:[],eventEmitter:null},options),this.init()},$.Tabs.prototype={init:function(){this.state({tabs:this.tabs,selectedTabIndex:0},!0),this.listenForActions(),this.render(this.state()),this.bindEvents()},state:function(state,initial){var _this=this;return arguments.length?(jQuery.extend(!0,this.tabState,state),initial||_this.eventEmitter.publish("tabStateUpdated."+this.windowId,this.tabState),this.tabState):this.tabState},tabSelected:function(index){var state=this.state();state.selectedTabIndex=index,this.state(state)},getTemplateData:function(){return{annotationsTab:this.state().annotationsTab,tocTab:this.state().tocTab}},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("tabStateUpdated."+this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("tabSelected."+this.windowId,function(_,data){_this.tabSelected(data)}),_this.eventEmitter.subscribe("tabFocused.",function(){})},bindEvents:function(){var _this=this;this.element.find(".tab").on("click",function(event){_this.eventEmitter.publish("tabSelected."+_this.windowId,jQuery(this).index())})},render:function(renderingData){var _this=this;if(!this.element){var tabs=jQuery.grep(renderingData.tabs,function(value,index){return value.options.available});return renderingData.tabs=tabs,1===renderingData.tabs.length&&("toc"!==renderingData.tabs[0].name||_this.hasStructures||_this.eventEmitter.publish("sidePanelVisibilityByTab."+_this.windowId,!1),renderingData.tabs=[]),void(this.element=jQuery(_this.template(renderingData)).prependTo(_this.appendTo))}this.element.find(".tab").removeClass("selected");var tabClass="."+renderingData.tabs[renderingData.selectedTabIndex].options.id;this.element.find(tabClass).addClass("selected")},template:Handlebars.compile(['<ul class="tabGroup">',"{{#each tabs}}",'<li class="tab {{this.options.id}} {{#unless @index}}selected{{/unless}}" data-tabId="{{this.options.id}}">',"{{this.options.label}}","</li>","{{/each}}","</ul>"].join("")),toggle:function(){}}}(Mirador),function($){$.ThumbnailsView=function(options){jQuery.extend(this,{currentImgIndex:0,canvasID:null,focusImages:[],manifest:null,element:null,imagesList:[],appendTo:null,thumbInfo:{thumbsHeight:150,listingCssCls:"listing-thumbs",thumbnailCls:"thumbnail-view"},defaultThumbHeight:150,windowId:null,panel:!1,lazyLoadingFactor:1.5,eventEmitter:null},options),this.init()},$.ThumbnailsView.prototype={init:function(){null!==this.canvasID&&(this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID)),this.loadContent(),this.bindEvents(),this.listenForActions()},loadContent:function(){var _this=this,tplData={defaultHeight:this.thumbInfo.thumbsHeight,listingCssCls:this.thumbInfo.listingCssCls,thumbnailCls:this.thumbInfo.thumbnailCls};tplData.thumbs=jQuery.map(this.imagesList,function(canvas,index){if(0===canvas.width)return{};var aspectRatio=canvas.height/canvas.width,width=_this.thumbInfo.thumbsHeight/aspectRatio,thumbnailUrl=$.getThumbnailForCanvas(canvas,width);return{thumbUrl:thumbnailUrl,title:$.JsonLd.getTextValue(canvas.label),id:canvas["@id"],width:width,highlight:_this.currentImgIndex===index?"highlight":""}}),this.element=jQuery(_this.template(tplData)).appendTo(this.appendTo)},updateImage:function(canvasId){this.currentImgIndex=$.getImageIndexById(this.imagesList,canvasId),this.element.find(".highlight").removeClass("highlight"),this.element.find("img[data-image-id='"+canvasId+"']").addClass("highlight"),this.element.find("img[data-image-id='"+canvasId+"']").parent().addClass("highlight")},updateFocusImages:function(focusList){var _this=this;this.element.find(".highlight").removeClass("highlight"),jQuery.each(focusList,function(index,canvasId){_this.element.find("img[data-image-id='"+canvasId+"']").addClass("highlight"),_this.element.find("img[data-image-id='"+canvasId+"']").parent().addClass("highlight")})},currentImageChanged:function(){var scrollPosition,_this=this,target=_this.element.find(".highlight"),windowObject=this.state.getWindowObjectById(this.windowId);scrollPosition=windowObject&&"BookView"===windowObject.viewType?_this.element.scrollLeft()+(target.position().left+(target.next().width()+target.outerWidth())/2)-_this.element.width()/2:_this.element.scrollLeft()+(target.position().left+target.width()/2)-_this.element.width()/2,_this.element.scrollTo(scrollPosition,900)},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event){_this.currentImageChanged()}),_this.eventEmitter.subscribe("windowResize",$.debounce(function(){_this.loadImages()},100))},bindEvents:function(){var _this=this;_this.element.find("img").on("load",function(){jQuery(this).hide().fadeIn(750,function(){jQuery(this).css("display","block")})}),jQuery(_this.element).scroll(function(){_this.loadImages()}),_this.element.find(".thumbnail-image").on("click",function(){var canvasID=jQuery(this).attr("data-image-id");_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+_this.windowId,canvasID)})},toggle:function(stateValue){stateValue?this.show():this.hide()},loadImages:function(){var _this=this;jQuery.each(_this.element.find("img"),function(key,value){if($.isOnScreen(value,_this.lazyLoadingFactor)&&!jQuery(value).attr("src")){var url=jQuery(value).attr("data");_this.loadImage(value,url)}})},loadImage:function(imageElement,url){var imagePromise=$.createImagePromise(url);imagePromise.done(function(image){jQuery(imageElement).attr("src",image)})},reloadImages:function(newThumbHeight,triggerShow){var _this=this;this.thumbInfo.thumbsHeight=newThumbHeight,jQuery.each(this.imagesList,function(index,image){var aspectRatio=image.height/image.width,width=_this.thumbInfo.thumbsHeight/aspectRatio,newThumbURL=$.getThumbnailForCanvas(image,width),id=image["@id"],imageElement=_this.element.find('img[data-image-id="'+id+'"]');imageElement.attr("data",newThumbURL).attr("height",_this.thumbInfo.thumbsHeight).attr("width",width).attr("src","")}),triggerShow&&this.show()},template:Handlebars.compile(['<div class="{{thumbnailCls}}">','<ul class="{{listingCssCls}}" role="list" aria-label="Thumbnails">',"{{#thumbs}}",'<li class="{{highlight}}" role="listitem" aria-label="Thumbnail">','<img class="thumbnail-image {{highlight}}" title="{{title}}" data-image-id="{{id}}" src="" data="{{thumbUrl}}" height="{{../defaultHeight}}" width="{{width}}">','<div class="thumb-label">{{title}}</div>',"</li>","{{/thumbs}}","</ul>","</div>"].join("")),hide:function(){var element=jQuery(this.element);this.panel&&(element=element.parent()),element.hide({effect:"fade",duration:300,easing:"easeOutCubic"})},show:function(){var element=jQuery(this.element);this.panel&&(element=element.parent());var _this=this;element.show({effect:"fade",duration:300,easing:"easeInCubic",complete:function(){jQuery(this).css("display","block"),_this.loadImages()}})},adjustWidth:function(className,hasClass){var _this=this;hasClass?_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,className):_this.eventEmitter.publish("ADD_CLASS."+this.windowId,className)},adjustHeight:function(className,hasClass){hasClass?this.element.removeClass(className):this.element.addClass(className)}}}(Mirador),function($){$.TableOfContents=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,windowId:null,structures:[],manifestVersion:null,previousSelectedElements:[],selectedElements:[],previousOpenElements:[],openElements:[],hoveredElement:[],selectContext:null,tocData:{},active:null,eventEmitter:null},options),this.init();var self=this;window.render=function(){self.render()}},$.TableOfContents.prototype={init:function(){var _this=this;_this.structures&&0!==_this.structures.length?(this.element=jQuery(this.template({ranges:this.getTplData()})).appendTo(this.appendTo),this.tocData=_this.initTocData(),this.setSelectedElements($.getRangeIDByCanvasID(_this.structures,_this.canvasID)),this.element.find(".has-child ul").hide(),this.render()):this.element=jQuery(this.emptyTemplate()).appendTo(this.appendTo),this.bindEvents()},tabStateUpdated:function(data){"tocTab"===data.tabs[data.selectedTabIndex].options.id?this.element.show():this.element.hide()},getTplData:function(){var ranges,_this=this;_this.structures.map(function(structure){return structure.id=structure["@id"],structure});switch(_this.manifestVersion){case"1":ranges=_this.extractV1RangeTrees(_this.structures);break;case"2":ranges=_this.extractV2RangeTrees(_this.structures)}return ranges.length<2&&ranges[0].children&&(ranges=ranges[0].children),ranges},initTocData:function(){var _this=this,tocData={};return _this.structures.forEach(function(structure){var rangeID=structure["@id"],attrString='[data-rangeid="'+rangeID+'"]';tocData[structure["@id"]]={element:_this.element.find(attrString).closest("li")}}),tocData},extractV1RangeTrees:function(rangeList){function unflatten(flatRanges,parent,tree){tree="undefined"!=typeof tree?tree:[],parent="undefined"!=typeof parent?parent:{"@id":"root",label:"Table of Contents"};var children=jQuery.grep(flatRanges,function(child){return child.within||(child.within="root"),child.within==parent["@id"]});return children.length&&("root"===parent["@id"]?(children.forEach(function(child){child.level=0}),tree=children):(children.forEach(function(child){child.level=parent.level+1}),parent.children=children),jQuery.each(children,function(index,child){unflatten(flatRanges,child)})),tree}return unflatten(rangeList)},extractV2RangeTrees:function(rangeList){function unflatten(flatRanges,parent,tree){tree="undefined"!=typeof tree?tree:[],parent="undefined"!=typeof parent?parent:{"@id":"root",label:"Table of Contents"};var children=[];if(parent.ranges)jQuery.each(parent.ranges,function(index,id){id="object"==typeof id?id["@id"]:id;var child=jQuery.grep(flatRanges,function(range,index){if(range["@id"]===id)return range})[0];child&&children.push(child)});else if("root"===parent["@id"]){var top=jQuery.grep(flatRanges,function(range,index){if(range.hasOwnProperty("viewingHint")&&"top"===range.viewingHint)return range})[0];top&&children.push(top),0===children.length&&(jQuery.each(flatRanges,function(index,range){if(range.ranges)return children.push(range),!1}),0===children.length&&children.push({ranges:flatRanges}))}return children.length&&("root"===parent["@id"]?(children.forEach(function(child){child.level=0}),tree=children):(children.forEach(function(child){child.level=parent.level+1}),parent.children=children),jQuery.each(children,function(index,child){unflatten(flatRanges,child)})),tree}return unflatten(rangeList)},render:function(){var _this=this,toDeselect=_this.previousSelectedElements.map(function(rangeID){return _this.tocData[rangeID].element}),toSelect=_this.selectedElements.map(function(rangeID){return _this.tocData[rangeID].element}),toOpen=_this.openElements.filter(function(rangeID){return jQuery.inArray(rangeID,_this.previousOpenElements)===-1}).map(function(rangeID){return _this.tocData[rangeID].element}),toClose=_this.previousOpenElements.filter(function(rangeID){return jQuery.inArray(rangeID,_this.openElements)===-1}).map(function(rangeID){return _this.tocData[rangeID].element});_this.previousSelectedElements!==_this.selectedElements?(toDeselect.forEach(function(element){element.removeClass("selected")}),toSelect.forEach(function(element){element.addClass("selected")}),toClose.forEach(function(element){element.removeClass("open"),element.find("ul:first").slideFadeToggle()}),toOpen.forEach(function(element){element.addClass("open").find("ul:first").slideFadeToggle()})):(toOpen.forEach(function(element){element.addClass("open").find("ul:first").slideFadeToggle()}),toClose.forEach(function(element){element.removeClass("open").find("ul:first").slideFadeToggle()}))},bindEvents:function(){var _this=this;_this.eventEmitter.subscribe("tabStateUpdated."+_this.windowId,function(_,data){_this.tabStateUpdated(data)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasID){_this.structures&&(_this.setSelectedElements($.getRangeIDByCanvasID(_this.structures,canvasID)),_this.render())}),_this.element.find(".toc-link").on("click",function(event){event.stopPropagation();var rangeID=jQuery(this).data().rangeid,canvasID=jQuery.grep(_this.structures,function(item){return item["@id"]==rangeID})[0].canvases[0];_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+_this.windowId,canvasID)}),_this.element.find(".toc-caret").on("click",function(event){event.stopPropagation();var rangeID=jQuery(this).parent().data().rangeid;_this.setOpenItem(rangeID),_this.render()})},setActive:function(active){var _this=this;_this.active=active},setOpenItem:function(rangeID){var _this=this,alreadyOpen=jQuery.inArray(rangeID,_this.openElements)!==-1;_this.previousOpenElements=_this.openElements,_this.openElements=function(){return alreadyOpen?_this.openElements.filter(function(elementID){return elementID!==rangeID}):_this.openElements.map(function(elementID){return elementID}).concat([rangeID])}()},setSelectedElements:function(rangeIDs){var _this=this;_this.previousSelectedElements=_this.selectedElements,_this.selectedElements=rangeIDs,_this.previousOpenElements=_this.openElements,_this.openElements=_this.openElements.filter(function(openElementID){return jQuery.inArray(openElementID,_this.previousSelectedElements)===-1}).concat(rangeIDs).filter(function(openElementID,index,openElements){return index===openElements.indexOf(openElementID)})},emptyTemplate:Handlebars.compile(['<ul class="toc">','<li class="leaf-item open">','<h2><span>{{t "noIndex"}}</span></h2>',"</ul>"].join("")),template:function(tplData){var previousTemplate,template=Handlebars.compile(['<ul class="toc">',"{{#nestedRangeLevel ranges}}",'<li class="{{#if children}}has-child{{else}}leaf-item{{/if}}">',"{{{tocLevel id label level children}}}","{{#if children}}","<ul>","{{{nestedRangeLevel children}}}","</ul>","{{/if}}","<li>","{{/nestedRangeLevel}}","</ul>"].join(""));return Handlebars.registerHelper("nestedRangeLevel",function(children,options){var out="";return void 0!==options.fn&&(previousTemplate=options.fn),children.forEach(function(child){child.label=$.JsonLd.getTextValue(child.label),out+=previousTemplate(child)}),out}),Handlebars.registerHelper("tocLevel",function(id,label,level,children){var caret='<i class="fa fa-caret-right toc-caret"></i>',cert='<i class="fa fa-certificate star"></i>';return"<h"+(level+1)+'><a class="toc-link" data-rangeID="'+id+'">'+caret+cert+"<span>"+label+"</span></a></h"+(level+1)+">"}),template(tplData)},hide:function(){var _this=this;jQuery(this.appendTo).hide(),_this.eventEmitter.publish("ADD_CLASS."+this.windowId,"focus-max-width")},show:function(){var _this=this;jQuery(this.appendTo).show({effect:"fade",duration:300,easing:"easeInCubic"}),_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,"focus-max-width")}}}(Mirador),function($){$.DialogBuilder=function(container){this.container=container||jQuery(".window"),bootbox.setDefaults({container:this.container})},$.DialogBuilder.prototype={confirm:function(message,callback){return this._attachEvents(bootbox.confirm(message,callback))},dialog:function(opts){this._attachEvents(bootbox.dialog(opts))},_attachEvents:function(el){var _this=this;jQuery(el).on("shown.bs.modal",function(){var zIndex=2e4;jQuery(el).css("z-index",zIndex),jQuery(".modal-backdrop").prependTo(_this.container).css("z-index",zIndex)}),jQuery(el).on("hidden.bs.modal",function(){jQuery(".modal-backdrop").remove()})}}}(Mirador),function($){$.EventEmitter=function(config){jQuery.extend(!0,this,{debug:$.EventEmitter.debug,trace:$.EventEmitter.trace,debugExclude:$.EventEmitter.excludePatterns},config),this.emitterId=$.EventEmitter.nextId(),this.debug&&(this.logger=new $.EventEmitter.Logger({trace:this.trace,debugExclude:this.debugExclude}))},$.EventEmitter.id=0,$.EventEmitter.nextId=function(){return $.EventEmitter.id++,$.EventEmitter.id},$.EventEmitter.debug=!1,$.EventEmitter.trace=!1,$.EventEmitter.excludePatterns=[],$.EventEmitter.Logger=function(options){this.trace=options.trace,this.debugExclude=options.debugExclude,this.scaffoldMap={}},$.EventEmitter.Logger.prototype={log:function(){this.trace?console.trace.apply(console,arguments):console.log.apply(console,arguments)},exclude:function(str){for(var patterns=this.debugExclude,i=0;i<patterns.length;++i)if(str.match(patterns[i]))return!0;return!1},scaffoldHandler:function(eventId,handler){var _this=this,scaffold=function(){_this.log("EventEmitter:handler:",eventId,handler,Array.prototype.slice.call(arguments)),handler.apply(null,arguments)};return this.scaffoldMap[handler]=scaffold,scaffold},unscaffold:function(handler){var scaffold=this.scaffoldMap[handler];return delete this.scaffoldMap[handler],scaffold}},["subscribe","unsubscribe","publish"].forEach(function(action){$.EventEmitter.prototype[action]=function(){var event,args=Array.prototype.slice.call(arguments),eventId=args[0],globalEventId=this.emitterId.toString()+"::"+eventId,logging=this.logger&&!this.logger.exclude(globalEventId);if("subscribe"===action&&(event={name:eventId,handler:args[1]},logging&&(args[1]=this.logger.scaffoldHandler(globalEventId,args[1]))),"unsubscribe"===action&&logging&&(args[1]=this.logger.unscaffold(args[1])),args[0]=globalEventId,logging&&this.logger.log("EventEmitter:"+action+":",args),jQuery[action].apply(jQuery,args),event)return event}})}(Mirador),function($){$.Iiif={getImageUrl:function(image){if(!image.images[0].resource.service)return id=image.images[0].resource.default.service["@id"],id=id.replace(/\/$/,"");var id=image.images[0].resource.service["@id"];return id=id.replace(/\/$/,"")},getVersionFromContext:function(context){return"http://iiif.io/api/image/2/context.json"==context?"2.0":"1.1"},getComplianceLevelFromProfile:function(profile){var compliance=-1,complianceString=null;if(profile)switch("string"==typeof profile?complianceString=profile:"object"==typeof profile&&(complianceString=profile[0]),complianceString){case"http://iiif.io/api/image/2/level0.json":compliance=0;break;case"http://iiif.io/api/image/2/level1.json":compliance=1;break;case"http://iiif.io/api/image/2/level2.json":compliance=2}return compliance},makeUriWithWidth:function(uri,width,version){return uri=uri.replace(/\/$/,""),"1"==version[0]?uri+"/full/"+width+",/0/native.jpg":uri+"/full/"+width+",/0/default.jpg"},getImageHostUrl:function(json){var regex,matches=[];return json.hasOwnProperty("image_host")||(json.image_host=json.tilesUrl||json["@id"]||"",json.hasOwnProperty("identifier")?(regex=new RegExp("/?"+json.identifier+"/?$","i"),json.image_host=json.image_host.replace(regex,"")):(regex=new RegExp("(.*)/(.*)$"),matches=regex.exec(json.image_host),matches.length>1&&(json.image_host=matches[1],json.identifier=matches[2]))),json.image_host}}}(Mirador),function($){function getAPIUri(host,port,ssl,body){var proto="http";port=port?port:"80",ssl&&(proto="https",port=port?port:"443"),host=host?host:"jsonblob.com";var path=JSONBLOB_API_ENDPOINT;return("string"==typeof body||body instanceof String)&&(path+="/"+body),proto+"://"+host+":"+port+path}function initSettings(method,host,port,ssl,requestBody){var ajaxSettings={type:method,url:getAPIUri(host,port,ssl,requestBody),contentType:"application/json; charset=UTF-8",accept:"application/json",dataType:"json",processData:!1};return"string"==typeof requestBody||requestBody instanceof String||(ajaxSettings.data=JSON.stringify(requestBody)),ajaxSettings}function syncRequest(method,host,port,ssl,requestBody){var result,settings=initSettings(method,host,port,ssl,requestBody);return settings.async=!1,settings.success=function(data,textStatus,request){result=data},jQuery.ajax(settings),result}function asyncRequest(method,host,port,ssl,requestBody,cb){var settings=initSettings(method,host,port,ssl,requestBody);settings.success=cb,jQuery.ajax(settings)}var JSONBLOB_API_ENDPOINT="/api/jsonBlob";$.JSONBlobAPI=function(options){this.options=options},$.JSONBlobAPI.prototype={readSync:function(blobId){return syncRequest("GET",this.options.host,this.options.port,this.options.ssl,blobId)},save:function(blob){var deferred=jQuery.Deferred();return asyncRequest("POST",this.options.host,this.options.port,this.options.ssl,blob,function(data,textStatus,request){var blobid=request.getResponseHeader("X-Jsonblob");deferred.resolve(blobid)}),deferred.promise()}}}(Mirador),function($){function getDisplayLanguage(languages,items){var itemLanguages=items.map(function(itm){return"string"==typeof itm?null:itm["@language"]}),bestLanguageMatch=null;return jQuery.each(languages,function(idx,lang){return null===bestLanguageMatch&&void(itemLanguages.indexOf(lang)!==-1&&(bestLanguageMatch=lang))}),null===bestLanguageMatch&&itemLanguages.indexOf(null)===-1&&(bestLanguageMatch=itemLanguages[0]),bestLanguageMatch}$.JsonLd={getTextValue:function(propertyValue,language){var languages=window.navigator.languages||["en"];if("string"==typeof language?languages=[language].concat(languages):Array.isArray(language)&&(languages=language.concat(languages)),"undefined"==typeof propertyValue||null===propertyValue)return"";if("string"==typeof propertyValue)return $.sanitizeHtml(propertyValue);if(Array.isArray(propertyValue)){var displayLanguage=getDisplayLanguage(languages,propertyValue),text="";return jQuery.each(propertyValue,function(idx,item){var textToAdd="";"string"==typeof item&&null===displayLanguage?textToAdd=item:item["@language"]===displayLanguage&&(textToAdd=item["@value"]),""!==textToAdd&&""!==text&&(text+="<br/>"),text+=textToAdd}),$.sanitizeHtml(text)}return $.sanitizeHtml(propertyValue["@value"])}}}(Mirador),function($){function generateUUID(){var d=(new Date).getTime(),uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"===c?r:3&r|8).toString(16)});return uuid}$.LocalJSONBlobAPI=function(opts){this.options={storage:window.localStorage},jQuery.extend(this.options,opts)},$.LocalJSONBlobAPI.prototype={readSync:function(blobId){return JSON.parse(this.options.storage.getItem(blobId))},save:function(blob){var deferred=jQuery.Deferred(),uuid=generateUUID();return this.options.storage.setItem("BM-"+uuid,JSON.stringify(blob)),deferred.resolve("BM-"+uuid),deferred.promise()}}}(Mirador),function($){$.OpenSeadragon=function(options){var osd=OpenSeadragon(jQuery.extend({preserveViewport:!0,visibilityRatio:1,minZoomLevel:0,defaultZoomLevel:0,blendTime:.1,alwaysBlend:!1,prefixUrl:"images/openseadragon/",showNavigationControl:!1},options));return osd}}(Mirador),function($){$.SaveController=function(config){function index(previousValue,currentValue,currentIndex){var newObj={};return newObj[currentValue]=previousValue,newObj}function iterateStringify(object){for(var property in object)object.hasOwnProperty(property)&&(object[property]instanceof Array?object[property]=JSON.stringify(object[property]):"object"==typeof object[property]&&iterateStringify(object[property]))}function iterateParse(object){for(var property in object)object.hasOwnProperty(property)&&("string"==typeof object[property]&&"["===object[property][0]?object[property]=JSON.parse(object[property]):"object"==typeof object[property]&&iterateParse(object[property]))}jQuery.extend(!0,this,{currentConfig:null,originalConfig:null,shareEndpoint:null,historySize:null,sessionID:null,slots:[],eventEmitter:null}),config.availableAnnotationDrawingTools&&(config.availableAnnotationDrawingTools=jQuery.grep(config.availableAnnotationDrawingTools,function(element,index){return jQuery.inArray(element,$.DEFAULT_SETTINGS.availableAnnotationDrawingTools)>=0})),config.mainMenuSettings&&!config.mainMenuSettings.buttons&&(config.mainMenuSettings.buttons={}),jQuery.each(config,function(key,value){if("string"==typeof key&&key.indexOf(".")!==-1){var array=key.split(".").reverse(),object=array.reduce(index,value);delete config[key],jQuery.extend(!0,config,object)}}),iterateStringify(config);var newConfig=jQuery.extend(!0,{},$.DEFAULT_SETTINGS,config);iterateParse(newConfig),this.init(newConfig)},$.SaveController.prototype={init:function(config){var _this=this;if(this.eventEmitter=config.eventEmitter,config.saveSession===!1)return this.currentConfig=config,this.bindEvents(),!1;saveModule=config.jsonStorageEndpoint.module,saveOptions=config.jsonStorageEndpoint.options,_this.storageModule=new $[saveModule](saveOptions);var sessionID=window.location.hash.substring(1);if(sessionID?this.sessionID=sessionID:this.sessionID=$.genUUID(),localStorage.getItem(this.sessionID))this.currentConfig=JSON.parse(localStorage.getItem(sessionID));else{var paramURL=window.location.search.substring(1);if(paramURL){var params=paramURL.split("="),jsonblob=params[1];this.currentConfig=this.storageModule.readSync(jsonblob)||config}else this.currentConfig=config}this.currentConfig.windowObjects=jQuery.map(this.currentConfig.windowObjects,function(value,index){return 0===Object.keys(value).length?null:value}),this.currentConfig.windowObjects&&jQuery.each(this.currentConfig.windowObjects,function(index,window){window.id||(window.id=$.genUUID())});var cleanURL=window.location.href.replace(window.location.search,"");window.location.hash?history.replaceState(this.currentConfig,"Mirador Session",cleanURL):history.replaceState(this.currentConfig,"Mirador Session",cleanURL+"#"+this.sessionID),this.bindEvents()},getWindowObjectById:function(windowId){var returnObject=null;return jQuery.each(this.currentConfig.windowObjects,function(index,window){if(window.id===windowId)return returnObject=window,!1}),returnObject},getWindowAnnotationsList:function(windowId){return this.windowsAnnotationsLists?this.windowsAnnotationsLists[windowId]:null},getSlots:function(){return this.slots},getWindowElement:function(windowId){return this.windowsElements?this.windowsElements[windowId]:null},getStateProperty:function(prop){return this.get(prop,"currentConfig")},getManifestIndex:function(manifestUri){var manifestIndex=-1;return jQuery.each(this.currentConfig.data,function(index,dataObj){if(dataObj.manifestUri===manifestUri)return manifestIndex=index,!1}),manifestIndex},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){var _this=this;options?this[options.parent][prop]=value:this[prop]=value,this.currentConfig.saveSession&&this.save(),_this.eventEmitter.publish("saveControllerConfigUpdated")},bindEvents:function(){var _this=this;_this.eventEmitter.subscribe("manifestsPanelVisible.set",function(event,manifestPanelVisible){_this.set("manifestPanelVisible",manifestPanelVisible,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("windowUpdated",function(event,options){var windowObjects=_this.currentConfig.windowObjects;windowObjects&&windowObjects.length>0?jQuery.each(windowObjects,function(index,window){window.id===options.id&&jQuery.extend(windowObjects[index],options)}):windowObjects=[options],_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("imageBoundsUpdated",function(event,options){var windowObjects=_this.currentConfig.windowObjects;windowObjects&&windowObjects.length>0&&jQuery.each(windowObjects,function(index,window){window.id===options.id&&(windowObjects[index].windowOptions||(windowObjects[index].windowOptions={}),windowObjects[index].windowOptions.osdBounds=options.osdBounds)}),_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("ANNOTATIONS_LIST_UPDATED",function(event,options){_this.windowsAnnotationsLists||(_this.windowsAnnotationsLists={}),_this.windowsAnnotationsLists[options.windowId]=options.annotationsList,_this.eventEmitter.publish("annotationListLoaded."+options.windowId)}),_this.eventEmitter.subscribe("WINDOW_ELEMENT_UPDATED",function(event,options){_this.windowsElements||(_this.windowsElements={}),_this.windowsElements[options.windowId]=options.element}),_this.eventEmitter.subscribe("windowSlotAddressUpdated",function(event,options){var windowObjects=_this.currentConfig.windowObjects;windowObjects&&windowObjects.length>0?jQuery.each(windowObjects,function(index,window){window.id===options.id&&jQuery.extend(windowObjects[index],options)}):windowObjects=[options],_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("manifestQueued",function(event,manifestObject,repository){var data=_this.currentConfig.data,objectInConfig=!1,url=manifestObject.uri;jQuery.each(data,function(index,manifestObject){manifestObject.manifestUri===url&&(objectInConfig=!0)}),objectInConfig||(data.push({manifestUri:url,location:repository}),_this.set("data",data,{parent:"currentConfig"}));var manifests=_this.currentConfig.manifests;manifests[url]=manifestObject,_this.set("manifests",manifests,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("slotsUpdated",function(event,options){_this.slots=options.slots}),_this.eventEmitter.subscribe("layoutChanged",function(event,layoutDescription){var serialisedLayout=JSON.stringify(layoutDescription,function(key,value){if("parent"!==key)return value});_this.set("layout",serialisedLayout,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("windowSlotAdded",function(event,options){var windowObjects=_this.currentConfig.windowObjects,inArray=jQuery.grep(windowObjects,function(windowObj){return windowObj.id===options.id});0===inArray.length&&(windowObjects.push({id:options.id,slotAddress:options.slotAddress}),_this.set("windowObjects",windowObjects,{parent:"currentConfig"}))}),_this.eventEmitter.subscribe("windowsRemoved",function(event){_this.set("windowObjects",[],{parent:"currentConfig"})}),_this.eventEmitter.subscribe("windowRemoved",function(event,windowID){var windowObjects=jQuery.grep(_this.currentConfig.windowObjects,function(window,index){return window.id!==windowID});_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("DELETE_FROM_CONFIG",function(event,options){var windowObjects=jQuery.grep(_this.currentConfig.windowObjects,function(window,index){return window.loadedManifest!==options.loadedManifest||window.id});_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("etc...",function(junk){})},save:function(){var _this=this;localStorage.setItem(_this.sessionID,JSON.stringify(_this.currentConfig))}}}(Mirador),function($){$.trimString=function(str){return str.replace(/^\s+|\s+$/g,"")},$.getImageIndexById=function(imagesList,id){var imgIndex=0;return jQuery.each(imagesList,function(index,img){$.trimString(img["@id"])===$.trimString(id)&&(imgIndex=index)}),imgIndex},$.getThumbnailForCanvas=function(canvas,width){var service,thumbnailUrl,version="1.1",compliance=-1;if(width=parseInt(width,10),canvas.hasOwnProperty("thumbnail"))"string"==typeof canvas.thumbnail?thumbnailUrl=canvas.thumbnail:canvas.thumbnail.hasOwnProperty("service")?(service=canvas.thumbnail.service,service.hasOwnProperty("profile")&&(compliance=$.Iiif.getComplianceLevelFromProfile(service.profile)),0===compliance?thumbnailUrl=canvas.thumbnail["@id"]:(service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version))):thumbnailUrl=canvas.thumbnail["@id"];else{var resource=canvas.images[0].resource;service=resource.default?resource.default.service:resource.service,service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version)}return thumbnailUrl},$.getQueryParams=function(url){var assoc={},decode=function(s){return decodeURIComponent(s.replace(/\+/g," "))},queryString=url.split("?")[1];if("undefined"==typeof queryString)return{};
79
+ module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":45}],51:[function(require,module,exports){(function(process){var Stream=function(){try{return require("stream")}catch(_){}}();exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=Stream||exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),!process.browser&&"disable"===process.env.READABLE_STREAM&&Stream&&(module.exports=Stream)}).call(this,require("_process"))},{"./lib/_stream_duplex.js":44,"./lib/_stream_passthrough.js":45,"./lib/_stream_readable.js":46,"./lib/_stream_transform.js":47,"./lib/_stream_writable.js":48,_process:42}],52:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":47}],53:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":48}],54:[function(require,module,exports){module.exports=function(string){return string.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")}},{}],55:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter,inherits=require("inherits");inherits(Stream,EE),Stream.Readable=require("readable-stream/readable.js"),Stream.Writable=require("readable-stream/writable.js"),Stream.Duplex=require("readable-stream/duplex.js"),Stream.Transform=require("readable-stream/transform.js"),Stream.PassThrough=require("readable-stream/passthrough.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&options.end===!1||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:28,inherits:38,"readable-stream/duplex.js":43,"readable-stream/passthrough.js":50,"readable-stream/readable.js":51,"readable-stream/transform.js":52,"readable-stream/writable.js":53}],56:[function(require,module,exports){function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding))throw new Error("Unknown encoding: "+encoding)}function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2,this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3,this.charLength=this.charReceived?3:0}var Buffer=require("buffer").Buffer,isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},StringDecoder=exports.StringDecoder=function(encoding){switch(this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,""),assertEncoding(encoding),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=base64DetectIncompleteChar;break;default:return void(this.write=passThroughWrite)}this.charBuffer=new Buffer(6),this.charReceived=0,this.charLength=0};StringDecoder.prototype.write=function(buffer){for(var charStr="";this.charLength;){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived<this.charLength)return"";buffer=buffer.slice(available,buffer.length),charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(!(charCode>=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:5}],57:[function(require,module,exports){(function(global){function deprecate(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],58:[function(require,module,exports){function extend(){for(var target={},i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source)hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target}module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty},{}]},{},[1])(1)}),function(global){function Mirador(config){return this instanceof Mirador?(this.eventEmitter=new Mirador.EventEmitter,this.saveController=new Mirador.SaveController(jQuery.extend(!0,{},config,{eventEmitter:this.eventEmitter})),this.viewer=new Mirador.Viewer({state:this.saveController,eventEmitter:this.eventEmitter}),this):new Mirador(config)}global.Mirador=global.Mirador||Mirador}(window),function($){$.Handlebars=function(){return Handlebars.create()}()}(Mirador),function($){$.DEFAULT_SETTINGS={workspaceType:"singleObject",saveSession:!1,workspaces:{singleObject:{label:"Single Object",addNew:!1,move:!1,iconClass:"image"},compare:{label:"Compare",iconClass:"columns"},bookReading:{defaultWindowOptions:{},label:"Book Reading",addNew:!0,move:!1,iconClass:"book"}},manifests:[],data:[],layout:"1x1",openManifestsPage:!1,preserveManifestOrder:!1,windowSettings:{availableViews:["ThumbnailsView","ImageView","ScrollView","BookView"],viewType:"ImageView",bottomPanel:!0,bottomPanelVisible:!0,sidePanel:!0,sidePanelOptions:{toc:!0,annotations:!1},sidePanelVisible:!0,overlay:!0,canvasControls:{annotations:{annotationLayer:!0,annotationCreation:!0,annotationState:"off",annotationRefresh:!1},imageManipulation:{manipulationLayer:!0,controls:{rotate:!0,brightness:!0,contrast:!0,saturate:!0,grayscale:!0,invert:!0}}},fullScreen:!0,displayLayout:!0,layoutOptions:{newObject:!0,close:!0,slotRight:!0,slotLeft:!0,slotAbove:!0,slotBelow:!0}},windowObjects:[],autoHideControls:!0,fadeDuration:400,timeoutDuration:3e3,availableAnnotationModes:[],availableAnnotationDrawingTools:["Rectangle","Ellipse","Freehand","Polygon","Pin"],availableAnnotationStylePickers:["StrokeColor","FillColor","StrokeType"],drawingToolsSettings:{doubleClickReactionTime:300,strokeColor:"deepSkyBlue",fillColor:"deepSkyBlue",fillColorAlpha:0,shapeHandleSize:10,fixedShapeSize:10,newlyCreatedShapeStrokeWidthFactor:5,hoverColor:"yellow"},availableExternalCommentsPanel:!1,shapeHandleSize:10,availableCanvasTools:[],mainMenuSettings:{show:!0,buttons:{bookmark:!1,layout:!0,options:!1,fullScreenViewer:!0}},workspacePanelSettings:{maxRows:5,maxColumns:5,preserveWindows:!0},showAddFromURLBox:!0,buildPath:"build/mirador/",i18nPath:"locales/",imagesPath:"images/",annotationEndpoint:{},annotationBodyEditor:{module:"TinyMCEAnnotationBodyEditor",options:{config:{plugins:"image link media directionality",toolbar:"bold italic | bullist numlist | link image media | removeformat | ltr rtl"}}},jsonStorageEndpoint:{name:"JSONBlob API Endpoint",module:"JSONBlobAPI",options:{ssl:!0,port:"443",host:"jsonblob.com"}},sharingEndpoint:{url:"",storeId:123,APIKey:"23983hf98j3f9283jf2983fj"},lockController:{lockProfile:"lazyZoom",notifyMaxMin:!0}}}(Mirador),function($){$.Viewer=function(options){jQuery.extend(!0,this,{id:null,data:null,element:null,canvas:null,workspaceType:null,layout:null,workspace:null,mainMenu:null,workspaceAutoSave:null,windowSize:{},resizeRatio:{},currentWorkspaceVisible:!0,state:null,eventEmitter:null,overlayStates:{workspacePanelVisible:!1,manifestsPanelVisible:!1,optionsPanelVisible:!1,bookmarkPanelVisible:!1},manifests:[]},options),this.id=this.state.getStateProperty("id"),this.data=this.state.getStateProperty("data"),this.element=this.element||jQuery("#"+this.id),options.availableAnnotationDrawingTools&&options.availableAnnotationDrawingTools.length>0&&(this.availableAnnotationDrawingTools=options.availableAnnotationDrawingTools),this.data&&this.init()},$.Viewer.prototype={init:function(){var _this=this;i18next.use(i18nextXHRBackend).use(i18nextBrowserLanguageDetector).init({fallbackLng:"en",load:"unspecific",debug:!1,backend:{loadPath:_this.state.getStateProperty("buildPath")+_this.state.getStateProperty("i18nPath")+"{{lng}}/{{ns}}.json"}},_this.setupViewer.bind(_this))},setupViewer:function(){var _this=this,backgroundImage=_this.state.getStateProperty("buildPath")+_this.state.getStateProperty("imagesPath")+"debut_dark.png";this.element.css("background-color","#333").css("background-image","url("+backgroundImage+")").css("background-position","left top").css("background-repeat","repeat"),$.Handlebars.registerHelper("t",function(i18n_key){var result=i18next.t(i18n_key);return new $.Handlebars.SafeString(result)});var showMainMenu=!1;jQuery.each(this.state.getStateProperty("mainMenuSettings").buttons,function(key,value){value&&(showMainMenu=!0)}),this.state.getStateProperty("mainMenuSettings").userButtons&&this.state.getStateProperty("mainMenuSettings").userButtons.length>0&&(showMainMenu=!0),this.state.getStateProperty("mainMenuSettings").userLogo&&!jQuery.isEmptyObject(this.state.getStateProperty("mainMenuSettings").userLogo)&&(showMainMenu=!0),this.state.getStateProperty("mainMenuSettings").show===!1&&(showMainMenu=!1),showMainMenu&&(this.mainMenu=new $.MainMenu({appendTo:this.element,state:this.state,eventEmitter:this.eventEmitter})),this.canvas=jQuery("<div/>").addClass("mirador-viewer").appendTo(this.element),showMainMenu||this.canvas.css("top","0px"),this.layout="string"!=typeof this.state.getStateProperty("layout")?JSON.stringify(this.state.getStateProperty("layout")):this.state.getStateProperty("layout"),this.workspace=new $.Workspace({layoutDescription:"{"===this.layout.charAt(0)?JSON.parse(this.layout):$.layoutDescriptionFromGridString(this.layout),appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter}),this.workspacePanel=new $.WorkspacePanel({appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter}),this.manifestsPanel=new $.ManifestsPanel({appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter}),showMainMenu&&this.state.getStateProperty("mainMenuSettings").buttons.bookmark&&(this.bookmarkPanel=new $.BookmarkPanel({appendTo:this.element.find(".mirador-viewer"),state:this.state,eventEmitter:this.eventEmitter})),this.set("currentWorkspaceVisible",!0),this.bindEvents(),this.listenForActions(),this.getManifestsData(),0===this.state.getStateProperty("windowObjects").length&&this.state.getStateProperty("openManifestsPage")&&this.workspace.slots[0].addItem()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("manifestReceived",function(event,newManifest){if(_this.state.getStateProperty("windowObjects")){var check=jQuery.grep(_this.state.getStateProperty("windowObjects"),function(object,index){return object.loadedManifest===newManifest.uri});jQuery.each(check,function(index,config){_this.loadManifestFromConfig(config)})}}),_this.eventEmitter.subscribe("TOGGLE_WORKSPACE_PANEL",function(event){_this.toggleWorkspacePanel()}),_this.eventEmitter.subscribe("TOGGLE_BOOKMARK_PANEL",function(event){_this.toggleBookmarkPanel()}),_this.eventEmitter.subscribe("TOGGLE_FULLSCREEN",function(event){$.fullscreenElement()?($.exitFullscreen(),_this.eventEmitter.publish("ENABLE_WINDOW_FULLSCREEN")):($.enterFullscreen(_this.element[0]),_this.eventEmitter.publish("DISABLE_WINDOW_FULLSCREEN"))}),jQuery(document).on("webkitfullscreenchange mozfullscreenchange fullscreenchange",function(){_this.eventEmitter.publish("MAINMENU_FULLSCREEN_BUTTON"),$.fullscreenElement()||_this.eventEmitter.publish("ENABLE_WINDOW_FULLSCREEN")}),_this.eventEmitter.subscribe("TOGGLE_LOAD_WINDOW",function(event){_this.toggleLoadWindow()}),_this.eventEmitter.subscribe("ADD_MANIFEST_FROM_URL",function(event,url,location){_this.addManifestFromUrl(url,location)}),_this.eventEmitter.subscribe("TOGGLE_OVERLAYS_FALSE",function(event){jQuery.each(_this.overlayStates,function(oState,value){_this.set(oState,!1,{parent:"overlayStates"})})})},bindEvents:function(){},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){var _this=this;options?this[options.parent][prop]=value:this[prop]=value,_this.eventEmitter.publish(prop+".set",value)},toggleOverlay:function(state){var _this=this;jQuery.each(this.overlayStates,function(oState,value){state!==oState&&_this.set(oState,!1,{parent:"overlayStates"})});var currentState=this.get(state,"overlayStates");this.set(state,!currentState,{parent:"overlayStates"})},toggleLoadWindow:function(){this.toggleOverlay("manifestsPanelVisible")},toggleWorkspacePanel:function(){this.toggleOverlay("workspacePanelVisible")},toggleBookmarkPanel:function(){this.toggleOverlay("bookmarkPanelVisible")},getManifestsData:function(){var _this=this;_this.data.forEach(function(manifest){if(manifest.hasOwnProperty("manifestContent")){var content=manifest.manifestContent;_this.addManifestFromUrl(content["@id"],manifest.location?manifest.location:"",content)}else if(manifest.hasOwnProperty("manifestUri")){var url=manifest.manifestUri;_this.addManifestFromUrl(url,manifest.location?manifest.location:"",null)}else manifest.hasOwnProperty("collectionUri")&&jQuery.getJSON(manifest.collectionUri).done(function(data,status,jqXHR){data.hasOwnProperty("manifests")?jQuery.each(data.manifests,function(ci,mfst){_this.addManifestFromUrl(mfst["@id"],"",null)}):data.hasOwnProperty("members")&&jQuery.each(data.members,function(ci,mfst){_this.addManifestFromUrl(mfst["@id"],"",null)})}).fail(function(jqXHR,status,error){console.log(jqXHR,status,error)})})},hasWidgets:function(collection){return"undefined"!=typeof collection.widgets&&collection.widgets&&!jQuery.isEmptyObject(collection.widgets)&&collection.widgets.length>0},addManifestFromUrl:function(url,location,content){var manifest,_this=this;_this.state.getStateProperty("manifests")[url]||(manifest=new $.Manifest(url,location,content),_this.eventEmitter.publish("manifestQueued",manifest,location),manifest.request.done(function(){_this.eventEmitter.publish("manifestReceived",manifest)}))},loadManifestFromConfig:function(options){var _this=this,windowConfig=jQuery.extend(!0,{},options);_this.eventEmitter.publish("DELETE_FROM_CONFIG",options),_this.eventEmitter.publish("ADD_WINDOW",windowConfig)}}}(Mirador),function($){$.Workspace=function(options){jQuery.extend(!0,this,{workspaceSlotCls:"slot",focusedSlot:null,slots:[],windows:[],appendTo:null,layoutDescription:null,state:null,eventEmitter:null},options);var uid=$.genUUID();this.element=this.element||jQuery('<div class="workspace-container" id="workspace-'+uid+'">'),this.init()},$.Workspace.prototype={init:function(){this.element.appendTo(this.appendTo),this.calculateLayout(),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("resizeMirador",function(event){_this.calculateLayout()}),_this.eventEmitter.subscribe("manifestQueued",function(event,manifestPromise){var targetSlot;if(_this.state.getStateProperty("windowObjects")){_this.state.getStateProperty("windowObjects").forEach(function(windowConfig,index){targetSlot=windowConfig.slotAddress?_this.getSlotFromAddress(windowConfig.slotAddress):_this.focusedSlot||_this.slots.filter(function(slot){return!!slot.hasOwnProperty("window")})[0]})}}),_this.eventEmitter.subscribe("REMOVE_WINDOW",function(event,windowId){_this.removeWindow(windowId)}),_this.eventEmitter.subscribe("REMOVE_NODE",function(event,node){_this.removeNode(node)}),_this.eventEmitter.subscribe("ADD_SLOT_ITEM",function(event,slot){_this.addItem(slot)}),_this.eventEmitter.subscribe("ADD_WINDOW",function(event,windowConfig){_this.addWindow(windowConfig)}),_this.eventEmitter.subscribe("SPLIT_RIGHT",function(event,slot){_this.splitRight(slot)}),_this.eventEmitter.subscribe("SPLIT_LEFT",function(event,slot){_this.splitLeft(slot)}),_this.eventEmitter.subscribe("SPLIT_DOWN",function(event,slot){_this.splitDown(slot)}),_this.eventEmitter.subscribe("SPLIT_UP",function(event,slot){_this.splitUp(slot)}),_this.eventEmitter.subscribe("RESET_WORKSPACE_LAYOUT",function(event,options){_this.resetLayout(options.layoutDescription)})},bindEvents:function(){var _this=this;d3.select(window).on("resize",function(event){_this.calculateLayout()})},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){var _this=this;options?this[options.parent][prop]=value:this[prop]=value,_this.eventEmitter.publish(prop+".set",value)},calculateLayout:function(resetting){function cell(){this.style("left",function(d){return d.x+"px"}).style("top",function(d){return d.y+"px"}).style("width",function(d){return Math.max(0,d.dx)+"px"}).style("height",function(d){return Math.max(0,d.dy)+"px"})}var layout,_this=this;_this.layout=layout=new Isfahan({containerId:_this.element.attr("id"),layoutDescription:_this.layoutDescription,configuration:null,padding:3});var data=layout.filter(function(d){return!d.children}),divs=d3.select("#"+_this.element.attr("id")).selectAll(".layout-slot").data(data,function(d){return d.id});divs.call(cell).each(function(d){_this.slots.forEach(function(slot){slot.slotID===d.id&&(slot.layoutAddress=d.address)})}),divs.enter().append("div").attr("class","layout-slot").attr("data-layout-slot-id",function(d){return d.id}).call(cell).each(function(d){var appendTo=_this.element.children("div").filter('[data-layout-slot-id="'+d.id+'"]')[0];_this.slots.push(new $.Slot({slotID:d.id,layoutAddress:d.address,focused:!0,appendTo:appendTo,state:_this.state,eventEmitter:_this.eventEmitter}))}),divs.exit().remove("div").each(function(d){var slotMap=_this.slots.reduce(function(map,temp_slot){return d.id===temp_slot.slotID&&(map[d.id]=temp_slot),map},{}),slot=slotMap[d.id];slot&&slot.window&&!resetting&&_this.eventEmitter.publish("REMOVE_WINDOW",slot.window.id),slot.window=null,_this.slots.splice(_this.slots.indexOf(slot),1)});var root=jQuery.grep(_this.layout,function(node){return!node.parent})[0];_this.eventEmitter.publish("layoutChanged",root),_this.eventEmitter.publish("slotsUpdated",{slots:_this.slots}),_this.slots.length<=1?_this.eventEmitter.publish("HIDE_REMOVE_SLOT"):_this.eventEmitter.publish("SHOW_REMOVE_SLOT")},split:function(targetSlot,direction){function addSibling(node,indexDifference){if(nodeIsNotRoot){var siblingIndex=nodeIndex+indexDifference,newSibling=_this.newNode(node.type,node);return node.parent.children.splice(siblingIndex,0,newSibling),_this.layout.push(newSibling),newSibling}node.type="row"===node.type?"column":"row",mutateAndAdd(node,indexDifference)}function mutateAndAdd(node,indexDifference){var newParent=_this.newNode(node.type,node.parent);node.type="row"===node.type?"column":"row",newSibling=_this.newNode(node.type,newParent),newParent.children=[],newParent.children.push(node),newParent.children.splice(indexDifference,0,newSibling),nodeIsNotRoot&&(newParent.parent=node.parent,newParent.parent.children[nodeIndex]=newParent),node.parent=newParent,_this.layout.push(newParent,newSibling)}var _this=this,node=jQuery.grep(_this.layout,function(node){return node.id===targetSlot.slotID})[0];nodeIndex=node.parent?node.parent.children.indexOf(node):0,nodeIsNotRoot=node.parent,"column"===node.type?"r"===direction||"l"===direction?(indexDifference="r"===direction?1:0,addSibling(node,indexDifference)):(indexDifference="d"===direction?1:0,mutateAndAdd(node,indexDifference)):"r"===direction||"l"===direction?(indexDifference="r"===direction?1:0,mutateAndAdd(node,indexDifference)):(indexDifference="d"===direction?1:0,addSibling(node,indexDifference));var root=jQuery.grep(_this.layout,function(node){return!node.parent})[0];_this.layoutDescription=root,_this.calculateLayout()},splitRight:function(targetSlot){var _this=this;_this.split(targetSlot,"r")},splitLeft:function(targetSlot){var _this=this;_this.split(targetSlot,"l")},splitUp:function(targetSlot){var _this=this;_this.split(targetSlot,"u")},splitDown:function(targetSlot){var _this=this;_this.split(targetSlot,"d")},removeNode:function(targetSlot){var remainingNode,_this=this,node=jQuery.grep(_this.layout,function(node){return node.id===targetSlot.slotID})[0],nodeIndex=node.parent.children.indexOf(node),root=jQuery.grep(_this.layout,function(node){return!node.parent})[0];2===node.parent.children.length?(node.parent.children.splice(nodeIndex,1),remainingNode=node.parent.children[0],remainingNode.parent.id=remainingNode.id,delete node.parent):1===node.parent.children.length||node.parent.children.splice(nodeIndex,1),_this.layoutDescription=root,_this.calculateLayout(),_this.eventEmitter.publish("slotRemoved",targetSlot)},newNode:function(type,parent){return"undefined"==typeof parent?{type:type,id:$.genUUID()}:{type:type,id:$.genUUID(),parent:parent}},getSlotFromAddress:function(address){var _this=this;return _this.slots.filter(function(slot){return slot.layoutAddress===address})[0]},resetLayout:function(layoutDescription){this.layoutDescription=layoutDescription,this.calculateLayout(!0),this.placeWindows()},placeWindows:function(){var _this=this;_this.windows.length>_this.slots.length&&_this.windows.slice(0,_this.windows.length-_this.slots.length).forEach(function(removedWindow){_this.eventEmitter.publish("REMOVE_WINDOW",removedWindow.id)}),_this.windows.forEach(function(window){var slot=_this.getAvailableSlot();slot.window=window,window.update({id:window.id,slotAddress:slot.layoutAddress,state:_this.state,appendTo:slot.element,canvasID:window.canvasID,viewType:window.viewType})})},getAvailableSlot:function(){return this.slots.filter(function(slot){return!slot.window})[0]},clearSlot:function(slotId){this.slots[slotId].windowElement&&this.slots[slotId].windowElement.remove(),this.slots[slotId].window=null},addItem:function(slot){var _this=this;this.focusedSlot=slot,_this.eventEmitter.publish("TOGGLE_LOAD_WINDOW")},addWindow:function(windowConfig){var newWindow,targetSlot,_this=this;_this.eventEmitter.publish("TOGGLE_OVERLAYS_FALSE"),targetSlot=windowConfig.slotAddress?_this.getSlotFromAddress(windowConfig.slotAddress):_this.focusedSlot||_this.getAvailableSlot(),windowConfig.appendTo=targetSlot.element,windowConfig.state=_this.state,windowConfig.eventEmitter=_this.eventEmitter,targetSlot.window&&_this.eventEmitter.publish("REMOVE_WINDOW",targetSlot.window.id),windowConfig.slotAddress=targetSlot.layoutAddress,windowConfig.id=windowConfig.id||$.genUUID(),_this.eventEmitter.publish("windowSlotAdded",{id:windowConfig.id,slotAddress:windowConfig.slotAddress});var mergedConfig=jQuery.extend(!0,{},_this.state.getStateProperty("windowSettings"),windowConfig);mergedConfig.hasOwnProperty("loadedManifest")&&(mergedConfig.manifest=_this.state.getStateProperty("manifests")[mergedConfig.loadedManifest],delete mergedConfig.loadedManifest),mergedConfig.hasOwnProperty("bottomPanel")&&(mergedConfig.bottomPanelAvailable=mergedConfig.bottomPanel,delete mergedConfig.bottomPanel),mergedConfig.hasOwnProperty("sidePanel")&&(mergedConfig.sidePanelAvailable=mergedConfig.sidePanel,delete mergedConfig.sidePanel),mergedConfig.hasOwnProperty("overlay")&&(mergedConfig.overlayAvailable=mergedConfig.overlay,delete mergedConfig.overlay),newWindow=new $.Window(mergedConfig),_this.windows.push(newWindow),targetSlot.window=newWindow,_this.eventEmitter.publish("windowAdded",{id:windowConfig.id,slotAddress:windowConfig.slotAddress})},removeWindow:function(windowId){var _this=this;_this.windows=_this.windows.filter(function(window){return window.id!==windowId}),_this.eventEmitter.publish("windowRemoved",windowId)}}}(Mirador),function($){$.BookmarkPanel=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,state:null,eventEmitter:null},options),this.init()},$.BookmarkPanel.prototype={init:function(){this.element=jQuery(this.template()).appendTo(this.appendTo);var jsonStorageEndpoint=this.state.getStateProperty("jsonStorageEndpoint"),saveModule=jsonStorageEndpoint.module,saveOptions=jsonStorageEndpoint.options;this.storageModule=new $[saveModule](saveOptions),this.bindEvents(),this.listenForActions()},bindEvents:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("bookmarkPanelVisible.set",function(_,stateValue){_this.onPanelVisible(_,stateValue)}),_this.eventEmitter.subscribe("saveControllerConfigUpdated",function(){_this.onConfigUpdated()})},onPanelVisible:function(_,stateValue){var _this=this;return stateValue?void _this.show():void _this.hide()},onConfigUpdated:function(){var _this=this;_this.storageModule.save(_this.state.currentConfig).then(function(blobId){var bookmarkURL=window.location.href.replace(window.location.hash,"")+"?json="+blobId;_this.element.find("#share-url").val(bookmarkURL).focus().select()})},hide:function(){jQuery(this.element).hide({effect:"slide",direction:"up",duration:300,easing:"swing"})},show:function(){jQuery(this.element).show({effect:"slide",direction:"up",duration:300,easing:"swing"})},template:$.Handlebars.compile(['<div id="bookmark-panel">','<h3>{{t "bookmarkTitle"}}</h3>',"<span>",'{{t "url"}}: <input id="share-url" type="text"></input>','<a href="javascript:;" class="mirador-btn mirador-icon-copy" data-clipboard-target="share-url"><i class="fa fa-files-o fa-lg"></i></a>',"</span>","</div>"].join(""))}}(Mirador),function($){$.MainMenu=function(options){jQuery.extend(!0,this,{element:null,mainMenuHeight:null,mainMenuWidth:null,windowOptionsMenu:null,loadWindow:null,clearLocalStorage:"",viewerCls:"mirador-viewer",mainMenuBarCls:"mirador-main-menu-bar",mainMenuCls:"mirador-main-menu",windowOptionsMenuCls:"mirador-window-options-menu",clearLocalStorageCls:"clear-local-storage",clearLocalStorageDialogCls:"mirador-main-menu-clear-local-storage",collectionsListingCls:"mirador-listing-collections",state:null,eventEmitter:null},options),this.element=this.element||jQuery("<div/>"),this.init()},$.MainMenu.prototype={init:function(){this.element.addClass(this.mainMenuBarCls).appendTo(this.appendTo),this.element.append(this.template({mainMenuCls:this.mainMenuCls,showBookmark:this.state.getStateProperty("mainMenuSettings").buttons.bookmark,showLayout:this.state.getStateProperty("mainMenuSettings").buttons.layout,showOptions:this.state.getStateProperty("mainMenuSettings").buttons.options,showFullScreenViewer:this.state.getStateProperty("mainMenuSettings").buttons.fullScreenViewer,userButtons:this.state.getStateProperty("mainMenuSettings").userButtons,userLogo:this.state.getStateProperty("mainMenuSettings").userLogo})),this.element.find(".mainmenu-button").each(function(){jQuery(this).qtip({content:{text:jQuery(this).attr("title")},position:{my:"top center",at:"bottom center"},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}})}),this.listenForActions(),this.bindEvents()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("MAINMENU_FULLSCREEN_BUTTON",function(event){var fullScreenButton=_this.element.find(".fullscreen-viewer span");fullScreenButton.hasClass("fa-expand")?fullScreenButton.removeClass("fa-expand").addClass("fa-compress"):fullScreenButton.removeClass("fa-compress").addClass("fa-expand")})},bindEvents:function(){var _this=this;this.element.find(".change-layout").on("click",function(){_this.eventEmitter.publish("TOGGLE_WORKSPACE_PANEL"),_this.element.find(".bookmark-workspace").removeClass("active"),jQuery(this).hasClass("active")?jQuery(this).removeClass("active"):jQuery(this).addClass("active")}),this.element.find(".bookmark-workspace").on("click",function(){_this.eventEmitter.publish("TOGGLE_BOOKMARK_PANEL"),_this.element.find(".change-layout").removeClass("active"),jQuery(this).hasClass("active")?jQuery(this).removeClass("active"):jQuery(this).addClass("active")}),this.element.find(".window-options").on("click",function(){}),this.element.find(".fullscreen-viewer").on("click",function(){_this.eventEmitter.publish("TOGGLE_FULLSCREEN")})},template:$.Handlebars.compile(["{{#if userLogo}}",'<ul class="user-logo {{mainMenuCls}}">',"{{userlogo userLogo}}","</ul>","{{/if}}",'<ul class="{{mainMenuCls}}">',"{{#if showBookmark}}","<li>",'<a href="javascript:;" class="bookmark-workspace mainmenu-button" title="{{t "bookmarkTooltip"}}" aria-label="{{t "bookmarkTooltip"}}">','<span class="fa fa-bookmark fa-lg fa-fw"></span> {{t "bookmark"}}',"</a>","</li>","{{/if}}","{{#if showLayout}}","<li>",'<a href="javascript:;" class="change-layout mainmenu-button" title="{{t "changeLayoutTooltip"}}" aria-label="{{t "changeLayoutTooltip"}}">','<span class="fa fa-th-large fa-lg fa-fw"></span> {{t "changeLayout"}}',"</a>","</li>","{{/if}}","{{#if showFullScreenViewer}}","<li>",'<a href="javascript:;" class="fullscreen-viewer mainmenu-button" title="{{t "fullScreenTooltip"}}" aria-label="{{t "fullScreenTooltip"}}">','<span class="fa fa-expand fa-lg fa-fw"></span> {{t "fullScreen"}}',"</a>","</li>","{{/if}}","</ul>","{{#if userButtons}}","{{userbtns userButtons}}","{{/if}}"].join(""))};var processUserButtons=function(btns){for(var output=[],btns_len=btns.length,i=0;i<btns_len;i++)output.push(processUserBtn(btns[i]));return output},processUserBtn=function(btn){var $sub_ul,$li=jQuery("<li>"),$a=jQuery("<a>");try{if(btn.li_attributes&&$li.attr(btn.li_attributes),!btn.label)throw"userButtons must have labels";return $a.text(btn.label),btn.iconClass&&$a.prepend('<span class="'+btn.iconClass+'"></span> '),btn.attributes&&$a.attr(btn.attributes),$li.append($a),btn.sublist&&($sub_ul=jQuery("<ul>"),btn.ul_attributes&&$sub_ul.attr(btn.ul_attributes),
80
+ $sub_ul.append(processUserButtons(btn.sublist)),$li.append($sub_ul)),$li}catch(err){return console&&console.log&&console.log(err),jQuery()}};$.Handlebars.registerHelper("userbtns",function(userButtons){return new $.Handlebars.SafeString(jQuery('<ul class="user-buttons '+this.mainMenuCls+'"></ul>').append(processUserButtons(userButtons)).get(0).outerHTML)}),$.Handlebars.registerHelper("userlogo",function(userLogo){return new $.Handlebars.SafeString(processUserBtn(userLogo).get(0).outerHTML)})}(Mirador),function($){$.ManifestListItem=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,loadStatus:null,thumbHeight:80,urlHeight:150,resultsWidth:0,maxPreviewImagesWidth:0,repoWidth:80,metadataWidth:450,margin:15,remainingWidth:20,imagesTotalWidth:0,tplData:null,allImages:[],remaining:0,state:null,eventEmitter:null},options),this.init()},$.ManifestListItem.prototype={init:function(){var _this=this;if(this.maxPreviewImagesWidth=this.resultsWidth-(this.repoWidth+this.margin+this.metadataWidth+this.margin+this.remainingWidth),this.maxPreviewImagesWidth=.95*this.maxPreviewImagesWidth,$.Handlebars.registerHelper("pluralize",function(count,singular,plural){return 1===count?singular:plural}),this.fetchTplData(this.manifestId),_this.state.getStateProperty("preserveManifestOrder"))if(0===this.appendTo.children().length)this.element=jQuery(this.template(this.tplData)).prependTo(this.appendTo).hide().fadeIn("slow");else{var liList=_this.appendTo.find("li");jQuery.each(liList,function(index,item){var prev=parseFloat(jQuery(item).attr("data-index-number")),next=parseFloat(jQuery(liList[index+1]).attr("data-index-number")),current=_this.tplData.index;return current<=prev&&(next>current||isNaN(next))?(_this.element=jQuery(_this.template(_this.tplData)).insertBefore(jQuery(item)).hide().fadeIn("slow"),!1):current>prev&&(current<next||isNaN(next))?(_this.element=jQuery(_this.template(_this.tplData)).insertAfter(jQuery(item)).hide().fadeIn("slow"),!1):void 0})}else this.element=jQuery(this.template(this.tplData)).prependTo(this.appendTo).hide().fadeIn("slow");this.bindEvents(),this.listenForActions()},fetchTplData:function(){var _this=this,location=_this.manifest.location,manifest=_this.manifest.jsonLd;this.tplData={label:$.JsonLd.getTextValue(manifest.label),repository:location,canvasCount:manifest.sequences[0].canvases.length,images:[],index:_this.state.getManifestIndex(manifest["@id"])},this.tplData.repoImage=function(){_this.tplData.repository;if(manifest.logo){if("string"==typeof manifest.logo)return manifest.logo;if("undefined"!=typeof manifest.logo["@id"])return manifest.logo["@id"]}return""}();for(var i=0;i<manifest.sequences[0].canvases.length;i++){var canvas=manifest.sequences[0].canvases[i];if(0!==canvas.width){var aspectRatio=canvas.height/canvas.width,width=_this.thumbHeight/aspectRatio;url=_this.manifest.getThumbnailForCanvas(canvas,width),_this.allImages.push({url:url,width:width,height:_this.thumbHeight,id:canvas["@id"],index:i})}}jQuery.each(_this.allImages,function(index,value){var width=value.width;return _this.imagesTotalWidth+=width+_this.margin,_this.imagesTotalWidth>=_this.maxPreviewImagesWidth?(value.width>_this.maxPreviewImagesWidth&&_this.tplData.images.push(value),_this.imagesTotalWidth-=width+_this.margin,!1):void _this.tplData.images.push(value)}),_this.remaining=this.tplData.remaining=function(){var remaining=_this.allImages.length-_this.tplData.images.length;if(remaining>0)return remaining}()},render:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("manifestPanelWidthChanged",function(event,newWidth){_this.updateDisplay(newWidth)})},bindEvents:function(){var _this=this;this.element.find("img").on("load",function(){jQuery(this).hide().fadeIn(600)}),this.element.on("click",function(){var windowConfig={manifest:_this.manifest,canvasID:null,viewType:"ThumbnailsView"};_this.eventEmitter.publish("ADD_WINDOW",windowConfig)}),this.element.find(".preview-image").on("click",function(e){e.stopPropagation();var windowConfig={manifest:_this.manifest,canvasID:jQuery(this).attr("data-image-id"),viewType:_this.state.getStateProperty("windowSettings").viewType};_this.eventEmitter.publish("ADD_WINDOW",windowConfig)})},updateDisplay:function(newWidth){var _this=this,newMaxPreviewWidth=newWidth-(_this.repoWidth+_this.margin+_this.metadataWidth+_this.margin+_this.remainingWidth);newMaxPreviewWidth*=.95;var image=null;if(newMaxPreviewWidth<_this.maxPreviewImagesWidth){for(;_this.imagesTotalWidth>=newMaxPreviewWidth&&(image=_this.tplData.images.pop());)_this.imagesTotalWidth-=image.width+_this.margin,_this.element.find('img[data-image-id="'+image.id+'"]').remove();0===_this.remaining&&_this.allImages.length-_this.tplData.images.length>0&&_this.element.find(".preview-images").after('<i class="fa fa fa-ellipsis-h remaining"></i>'),_this.remaining=_this.allImages.length-_this.tplData.images.length}else if(newMaxPreviewWidth>_this.maxPreviewImagesWidth){var currentLastImage=_this.tplData.images[_this.tplData.images.length-1],index=currentLastImage?currentLastImage.index+1:0;if(image=_this.allImages[index]){for(;_this.imagesTotalWidth+image.width+_this.margin<newMaxPreviewWidth&&(_this.tplData.images.push(image),_this.imagesTotalWidth+=image.width+_this.margin,_this.element.find(".preview-images").append('<img src="'+image.url+'" width="'+image.width+'" height="'+image.height+'" class="preview-image flash" data-image-id="'+image.id+'">'),index++,image=_this.allImages[index]););_this.remaining>0&&_this.allImages.length-_this.tplData.images.length===0&&_this.element.find(".remaining").remove(),_this.remaining=_this.allImages.length-_this.tplData.images.length}}_this.maxPreviewImagesWidth=newMaxPreviewWidth,_this.eventEmitter.publish("manifestListItemRendered")},hide:function(){},show:function(){},template:$.Handlebars.compile(["<li data-index-number={{index}}>",'<div class="repo-image">',"{{#if repoImage}}",'<img src="{{repoImage}}" alt="repoImg">',"{{else}}",'<span class="default-logo"></span>',"{{/if}}","</div>",'<div class="select-metadata">','<div class="manifest-title">','<h3 title="{{{label}}}">{{{label}}}</h3>',"</div>",'<div class="item-info">','<div class="item-info-row">',"{{#if repository}}",'<div class="repo-label">{{repository}}</div>',"{{/if}}",'<div class="canvas-count">{{canvasCount}} {{pluralize canvasCount (t "item") (t "items")}}</div>',"</div>","</div>","</div>",'<div class="preview-thumb">','<div class="preview-images">',"{{#each images}}",'<img src="{{url}}" width="{{width}}" height="{{height}}" class="preview-image flash" data-image-id="{{id}}">',"{{/each}}","</div>","{{#if remaining}}",'<i class="fa fa fa-ellipsis-h remaining"></i>',"{{/if}}","</div>","</li>"].join(""))}}(Mirador),function($){$.ManifestsPanel=function(options){jQuery.extend(!0,this,{element:null,listItems:null,appendTo:null,manifestListItems:[],manifestListElement:null,manifestLoadStatusIndicator:null,resultsWidth:0,state:null,eventEmitter:null},options);var _this=this;_this.init()},$.ManifestsPanel.prototype={init:function(){this.element=jQuery(this.template({showURLBox:this.state.getStateProperty("showAddFromURLBox")})).appendTo(this.appendTo),this.manifestListElement=this.element.find("ul");var clone=this.element.clone().css("visibility","hidden").css("display","block").appendTo(this.appendTo);this.resultsWidth=clone.find(".select-results").outerWidth(),this.controlsHeight=clone.find(".manifest-panel-controls").outerHeight(),this.paddingListElement=this.controlsHeight,this.manifestListElement.css("padding-bottom",this.paddingListElement),clone.remove(),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("manifestsPanelVisible.set",function(_,stateValue){_this.onPanelVisible(_,stateValue)}),_this.eventEmitter.subscribe("manifestReceived",function(event,newManifest){_this.onManifestReceived(event,newManifest)})},bindEvents:function(){var _this=this;this.element.find("form#url-load-form").on("submit",function(event){event.preventDefault(),_this.addManifestUrl(jQuery(this).find("input").val())}),this.element.find(".remove-object-option").on("click",function(event){_this.togglePanel(event)}),this.element.find("#manifest-search").on("keyup input",function(event){_this.filterManifests(this.value)}),this.element.find("#manifest-search-form").on("submit",function(event){event.preventDefault()}),jQuery(window).resize($.throttle(function(){_this.resizePanel()},50,!0))},hide:function(){jQuery(this.element).hide({effect:"fade",duration:160,easing:"easeOutCubic"})},show:function(){jQuery(this.element).show({effect:"fade",duration:160,easing:"easeInCubic"})},addManifestUrl:function(url){var _this=this;_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[url,"(Added from URL)"])},togglePanel:function(event){var _this=this;_this.eventEmitter.publish("TOGGLE_LOAD_WINDOW")},filterManifests:function(value){var _this=this;value.length>0?_this.element.find(".items-listing li").show().filter(function(){return jQuery(this).text().toLowerCase().indexOf(value.toLowerCase())===-1}).hide():_this.element.find(".items-listing li").show()},resizePanel:function(){var _this=this,clone=_this.element.clone().css("visibility","hidden").css("display","block").appendTo(_this.appendTo);_this.resultsWidth=clone.find(".select-results").outerWidth(),clone.remove(),_this.eventEmitter.publish("manifestPanelWidthChanged",_this.resultsWidth)},onPanelVisible:function(_,stateValue){var _this=this;return stateValue?void _this.show():void _this.hide()},onManifestReceived:function(event,newManifest){var _this=this;_this.manifestListItems.push(new $.ManifestListItem({manifest:newManifest,resultsWidth:_this.resultsWidth,state:_this.state,eventEmitter:_this.eventEmitter,appendTo:_this.manifestListElement})),_this.element.find("#manifest-search").keyup()},template:$.Handlebars.compile(['<div id="manifest-select-menu">','<div class="container">','<div class="manifest-panel-controls">','<a class="remove-object-option"><i class="fa fa-times fa-lg fa-fw"></i>{{t "close"}}</a>','<div id="load-controls">',"{{#if showURLBox}}",'<form action="" id="url-load-form">','<label for="url-loader">{{t "addNewObject"}}:</label>','<input type="text" id="url-loader" name="url-load" placeholder="http://...">','<input type="submit" value="{{t "load"}}">',"</form>","{{/if}}",'<form action="" id="manifest-search-form">','<label for="manifest-search">{{t "filterObjects"}}:</label>','<input id="manifest-search" type="text" name="manifest-filter">',"</form>","</div>","</div>",'<div class="select-results">','<ul class="items-listing">',"</ul>","</div>","</div>","</div>"].join(""))}}(Mirador),function($){$.WorkspacePanel=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,workspace:null,state:null,eventEmitter:null},options),this.init()},$.WorkspacePanel.prototype={init:function(){var _this=this,templateData={rows:$.layoutDescriptionFromGridString(_this.state.getStateProperty("workspacePanelSettings").maxColumns+"x"+_this.state.getStateProperty("workspacePanelSettings").maxRows).children.map(function(column,rowIndex){return column.columns=column.children.map(function(row,columnIndex){return row.gridString=rowIndex+1+"x"+(columnIndex+1),row}),column})};this.element=jQuery(this.template(templateData)).appendTo(this.appendTo);var backgroundImage=_this.state.getStateProperty("buildPath")+_this.state.getStateProperty("imagesPath")+"debut_dark.png";this.element.css("background-image","url("+backgroundImage+")").css("background-repeat","repeat"),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("workspacePanelVisible.set",function(_,stateValue){_this.onPanelVisible(_,stateValue)})},bindEvents:function(){var _this=this;_this.element.find(".grid-item").on("click",function(){var gridString=jQuery(this).data("gridstring");_this.select(gridString)}),_this.element.find(".grid-item").on("mouseover",function(){var gridString=jQuery(this).data("gridstring");_this.hover(gridString)}),_this.element.find(".select-grid").on("mouseout",function(){_this.reset()})},select:function(gridString){var _this=this,layoutDescription=$.layoutDescriptionFromGridString(gridString);_this.eventEmitter.publish("RESET_WORKSPACE_LAYOUT",{layoutDescription:layoutDescription}),_this.eventEmitter.publish("TOGGLE_WORKSPACE_PANEL")},hover:function(gridString){var _this=this,highestRow=gridString.charAt(0),highestColumn=gridString.charAt(2),gridItems=_this.element.find(".grid-item");gridItems.removeClass("hovered"),gridItems.filter(function(index){var gridString=jQuery(this).data("gridstring"),change=gridString.charAt(0)<=highestRow&&gridString.charAt(2)<=highestColumn;return change}).addClass("hovered"),_this.element.find(".grid-instructions").hide(),_this.element.find(".grid-text").text(gridString).show()},reset:function(){var _this=this;_this.element.find(".grid-item").removeClass("hovered"),_this.element.find(".grid-instructions").show(),_this.element.find(".grid-text").hide()},hide:function(){jQuery(this.element).hide({effect:"fade",duration:160,easing:"easeOutCubic"})},show:function(){var onComplete=function(){jQuery(this).css("display","block")};jQuery(this.element).show({effect:"fade",duration:160,easing:"easeInCubic",complete:onComplete})},onPanelVisible:function(_,stateValue){var _this=this;return stateValue?void _this.show():void _this.hide()},template:$.Handlebars.compile(['<div id="workspace-select-menu">','<h1>{{t "changeLayout"}}</h1>','<h3 class="grid-text"></h3>','<h3 class="grid-instructions">{{t "selectGrid"}}</h3>','<div class="select-grid">',"{{#each rows}}",'<div class="grid-row">',"{{#each columns}}",'<a class="grid-item" data-gridString="{{gridString}}">','<div class="grid-icon"></div>',"</a>","{{/each}}","</div>","{{/each}}","</div>","</div>"].join(""))}}(Mirador),function($){$.Manifest=function(manifestUri,location,manifestContent){manifestContent?(jQuery.extend(!0,this,{jsonLd:null,location:location,uri:manifestUri,request:null}),this.initFromManifestContent(manifestContent)):manifestUri.indexOf("info.json")!==-1?(jQuery.extend(!0,this,{jsonLd:null,location:location,uri:manifestUri,request:null}),this.initFromInfoJson(manifestUri)):(jQuery.extend(!0,this,{jsonLd:null,location:location,uri:manifestUri,request:null}),this.init(manifestUri))},$.Manifest.prototype={init:function(manifestUri){var _this=this;this.request=jQuery.ajax({url:manifestUri,dataType:"json",async:!0}),this.request.done(function(jsonLd){_this.jsonLd=jsonLd})},initFromInfoJson:function(infoJsonUrl){var _this=this;this.request=jQuery.ajax({url:infoJsonUrl,dataType:"json",async:!0}),this.request.done(function(jsonLd){_this.jsonLd=_this.generateInfoWrapper(jsonLd)})},initFromManifestContent:function(manifestContent){var _this=this;this.request=jQuery.Deferred(),this.request.done(function(jsonLd){_this.jsonLd=jsonLd}),_this.request.resolve(manifestContent)},getThumbnailForCanvas:function(canvas,width){var service,thumbnailUrl,version="1.1",compliance=-1;if(width=parseInt(width,10),canvas.hasOwnProperty("thumbnail"))"string"==typeof canvas.thumbnail?thumbnailUrl=canvas.thumbnail:canvas.thumbnail.hasOwnProperty("service")?(service=canvas.thumbnail.service,service.hasOwnProperty("profile")&&(compliance=$.Iiif.getComplianceLevelFromProfile(service.profile)),0===compliance?thumbnailUrl=canvas.thumbnail["@id"]:(service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version))):thumbnailUrl=canvas.thumbnail["@id"];else{var resource=canvas.images[0].resource;service=resource.default?resource.default.service:resource.service,service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version)}return thumbnailUrl},getVersion:function(){var versionMap={"http://www.shared-canvas.org/ns/context.json":"1","http://iiif.io/api/presentation/1/context.json":"1","http://iiif.io/api/presentation/2/context.json":"2","http://iiif.io/api/presentation/2.1/context.json":"2.1"};return versionMap[this.jsonLd["@context"]]},getCanvases:function(){var _this=this;return _this.jsonLd.sequences[0].canvases},getAnnotationsListUrls:function(canvasId){var _this=this,canvas=jQuery.grep(_this.getCanvases(),function(canvas,index){return canvas["@id"]===canvasId})[0],annotationsListUrls=[];if(canvas&&canvas.otherContent)for(var i=0;i<canvas.otherContent.length;i++)annotationsListUrls.push(canvas.otherContent[i]["@id"]);return annotationsListUrls},getStructures:function(){var _this=this;return _this.jsonLd.structures},generateInfoWrapper:function(infoJson){var dummyManifest={"@context":"http://www.shared-canvas.org/ns/context.json","@id":infoJson["@id"],"@type":"sc:Manifest",label:infoJson["@id"].split("/")[infoJson["@id"].split("/").length-1],sequences:[{"@id":infoJson["@id"]+"/sequence/1","@type":"sc:Sequence",canvases:[{"@id":infoJson["@id"]+"/sequence/1/canvas/1","@type":"sc:Canvas",width:infoJson.width,height:infoJson.height,images:[{"@id":infoJson["@id"]+"/sequence/1/canvas/1/image/1","@type":"sc:image",motivation:"sc:painting",resource:{"@id":infoJson,"@type":"dctypes:Image",format:"image/jpeg",height:infoJson.height,width:infoJson.width,service:{"@id":infoJson["@id"],"@context":infoJson["@context"],profile:infoJson.profile}}}]}]}]};return dummyManifest}}}(Mirador),function($){function PaperItem(item){this.item=item}function Group(paperScope,opts){var item=new paperScope.Group(opts);PaperItem.call(this,item)}function PointText(paperScope,opts){var text=new paperScope.PointText(opts);PaperItem.call(this,text)}function PointTextIcon(paperScope,opts){this.paperScope=paperScope,opts.justification="center",opts.font="FontAwesome",this.content=opts.content,PointText.call(this,paperScope,opts),this.rasterMask.addData("self",this)}function DeleteActionIcon(paperScope,opts){this.paperScope=paperScope,opts.fillColor=opts.fillColor||"black",opts.fontSize=opts.size||24/paperScope.view.zoom,opts.content="",this.rasterMask=new Icon(paperScope,{name:opts.name.replace("delete","Delete_mask"),size:new paperScope.Size(opts.fontSize,opts.fontSize)}),PointTextIcon.call(this,paperScope,opts)}function RotationIcon(paperScope,opts){this.paperScope=paperScope,opts.justification="center",opts.fillColor=opts.fillColor||"black",opts.fontSize=opts.size||16/paperScope.view.zoom,opts.content="",this.rasterMask=new Icon(paperScope,{name:opts.name.replace("rotation","Rotation_mask"),size:new paperScope.Size(opts.fontSize,opts.fontSize)}),PointTextIcon.call(this,paperScope,opts)}$.AnnotationUtils=function(){},PaperItem.prototype={getItem:function(){return this.item},translateByXY:function(x,y){this.item.position.x+=x,this.item.position.y+=y},translateByPoint:function(point){this.item.position=this.item.position.add(point)},setOnMouseDownListener:function(callback){this.mouseDown=callback},onMouseDown:function(){this.mouseDown.call(this,this.item)},remove:function(){this.item.remove()},rotate:function(angle,pivot){pivot?this.item.rotate(angle,pivot):this.item.rotate(angle)},setPosition:function(point){this.item.position=point},getWidth:function(){return this.item.width},getHeight:function(){return this.item.height},addData:function(key,data){this.item.data[key]=data},getData:function(key){return this.item.data[key]},resize:function(size){this.item.size=size}},Group.prototype=Object.create(PaperItem.prototype,{}),Group.constructor=Group;var Icon=function(paperScope,opts){this.paperScope=paperScope;var item=new paperScope.Raster(opts);PaperItem.call(this,item),opts&&opts.onLoad&&(this.item.onLoad=opts.onLoad)};Icon.prototype=Object.create(PaperItem.prototype,{}),Icon.constructor=Icon,PointText.prototype=Object.create(PaperItem.prototype),PointText.prototype.resize=function(newSize){this.item.fontSize=newSize},PointText.constructor=PointText,PointTextIcon.prototype=Object.create(PointText.prototype,{}),PointTextIcon.prototype.setPosition=function(point){this.rasterMask.setPosition(point),PointText.prototype.setPosition.call(this,point)},PointTextIcon.prototype.rotate=function(angle,pivot){this.rasterMask.rotate(angle,pivot),PointText.prototype.rotate.call(this,angle,pivot)},PointTextIcon.prototype.translateByPoint=function(point){this.rasterMask.translateByPoint(point),PointText.prototype.translateByPoint.call(this,point)},PointTextIcon.prototype.translateByXY=function(x,y){this.rasterMask.translateByXY(x,y),PointText.prototype.translateByXY.call(this,x,y)},PointTextIcon.prototype.remove=function(){this.rasterMask.remove(),PointText.prototype.remove.call(this)},PointTextIcon.prototype.resize=function(size){this.rasterMask.resize(new this.paperScope.Size(size,size)),PointText.prototype.resize.call(this,size)},PointTextIcon.prototype.getMask=function(){return this.rasterMask},PointTextIcon.prototype.constructor=PointTextIcon,DeleteActionIcon.prototype=Object.create(PointTextIcon.prototype,{}),DeleteActionIcon.prototype.setOnMouseDownListener=function(overlay){this.mouseDown=function(){overlay.eventEmitter.publish("deleteShape."+overlay.windowId,[this.getData("parent")]),overlay.mode="delete"}},RotationIcon.prototype=Object.create(PointTextIcon.prototype,{}),RotationIcon.prototype.setOnMouseDownListener=function(overlay){this.mouseDown=function(){overlay.mode="rotate"}},$.AnnotationUtils.prototype={Icon:Icon,PointText:PointText,DeleteActionIcon:DeleteActionIcon,RotationIcon:RotationIcon,Group:Group}}(Mirador),function($){$.AnnotationTooltip=function(options){jQuery.extend(this,{targetElement:null,annotations:[],windowId:"",eventEmitter:null},options),this.init()},$.AnnotationTooltip.prototype={init:function(){this.editor=$[this.state.currentConfig.annotationBodyEditor.module],this.editorOptions=this.state.currentConfig.annotationBodyEditor.options,this.activeEditor=null,this.activeEditorTip=null,this.inEditOrCreateMode=!1},showEditor:function(params){var _this=this;if(!_this.activeEditor){var editorContainer=_this.editorTemplate({id:jQuery.isEmptyObject(params.annotation)?"":params.annotation["@id"],windowId:_this.windowId}),selector="#annotation-editor-"+_this.windowId;_this.activeEditor=new _this.editor(jQuery.extend({},_this.editorOptions,{annotation:params.annotation,windowId:_this.windowId})),_this.activeEditorTip=_this.targetElement.qtip({content:{text:editorContainer},position:{my:"center",at:"center",container:_this.targetElement,viewport:_this.targetElement},style:{classes:"qtip-bootstrap qtip"+_this.windowId},show:{event:!1},hide:{fixed:!0,delay:300,event:!1},events:{render:function(event,api){_this.eventEmitter.publish("disableTooltips."+_this.windowId),api.elements.tooltip.draggable(),jQuery(selector).on("submit",function(event){event.preventDefault(),jQuery(selector+" a.save").click()}),jQuery(selector+" a.cancel").on("click",function(event){event.preventDefault();var cancelCallback=function(){api.destroy()};_this.eventEmitter.publish("onAnnotationCreatedCanceled."+_this.windowId,[cancelCallback,!_this.activeEditor.isDirty()])}),jQuery(selector+" a.save").on("click",function(event){if(event.preventDefault(),params.onSaveClickCheck()){var annotation=_this.activeEditor.createAnnotation();params.onAnnotationCreated&&params.onAnnotationCreated(annotation),api.destroy(),_this.activeEditor=null,_this.activeEditorTip=null}}),_this.activeEditor.show(selector),_this.eventEmitter.publish("annotationEditorAvailable."+_this.windowId)}}}),_this.activeEditorTip.qtip("show")}},initializeViewerUpgradableToEditor:function(params){var _this=this;_this.activeEditorTip=jQuery(_this.targetElement).qtip({overwrite:!1,content:{text:""},position:{target:"mouse",my:"bottom left",at:"top right",adjust:{mouse:!1,method:"shift"},container:params.container,viewport:params.viewport},style:{classes:"qtip-bootstrap qtip-viewer",tip:!1},hide:{fixed:!0,delay:300,event:!1},events:{shown:function(event,api){params.onTooltipShown&&params.onTooltipShown(event,api)},hidden:function(event,api){params.onTooltipHidden&&params.onTooltipHidden(event,api),_this.removeAllEvents(api,params)},visible:function(event,api){_this.removeAllEvents(api,params),_this.addViewerEvents(api,params)},move:function(event,api){api.cache.contentUpdated&&(_this.removeAllEvents(api,params),_this.addViewerEvents(api,params)),api.cache.contentUpdated=!1}}});var api=jQuery(_this.targetElement).qtip("api");api.cache.annotations=[],api.cache.hidden=!0},removeAllEvents:function(api,viewerParams){var _this=this,editorSelector="#annotation-editor-"+_this.windowId,viewerSelector="#annotation-viewer-"+_this.windowId;jQuery(viewerSelector+" a.delete").off("click"),jQuery(viewerSelector+" a.edit").off("click"),jQuery(editorSelector+" a.save").off("click"),jQuery(editorSelector+" a.cancel").off("click")},addViewerEvents:function(api,viewerParams){var _this=this,selector="#annotation-viewer-"+_this.windowId;jQuery(selector+" a.delete").on("click",function(event){event.preventDefault();var elem=this;new $.DialogBuilder(viewerParams.container).dialog({message:i18next.t("deleteAnnotation"),closeButton:!1,buttons:{no:{label:i18next.t("no"),className:"btn-default",callback:function(){}},yes:{label:i18next.t("yes"),className:"btn-primary",callback:function(){var display=jQuery(elem).parents(".annotation-display"),id=display.attr("data-anno-id"),callback=function(){api.hide(),display.remove()};_this.eventEmitter.publish("onAnnotationDeleted."+_this.windowId,[id,callback])}}}})}),jQuery(selector+" a.edit").on("click",function(event){event.preventDefault();var display=jQuery(this).parents(".annotation-display"),id=display.attr("data-anno-id"),oaAnno=viewerParams.getAnnoFromRegion(id)[0];_this.state.getStateProperty("availableExternalCommentsPanel")?(_this.eventEmitter.publish("annotationInEditMode."+_this.windowId,[oaAnno]),api.destroy(),jQuery(api.tooltip).remove()):(_this.freezeQtip(api,oaAnno,viewerParams),_this.removeAllEvents(api,viewerParams),_this.addEditorEvents(api,viewerParams)),_this.eventEmitter.publish("SET_ANNOTATION_EDITING."+_this.windowId,{annotationId:id,isEditable:!0,tooltip:_this}),_this.eventEmitter.publish("modeChange."+_this.windowId,"editingAnnotation")})},addEditorEvents:function(api,viewerParams){var _this=this,selector="#annotation-editor-"+_this.windowId;jQuery(selector).on("submit",function(event){event.preventDefault(),jQuery(selector+" a.save").click()}),jQuery(selector+" a.save").on("click",function(event){event.preventDefault();var display=jQuery(this).parents(".annotation-editor"),id=display.attr("data-anno-id"),oaAnno=viewerParams.getAnnoFromRegion(id)[0];_this.activeEditor.updateAnnotation(oaAnno),_this.eventEmitter.publish("annotationEditSave."+_this.windowId,[oaAnno])}),jQuery(selector+" a.cancel").on("click",function(event){event.preventDefault();var display=jQuery(this).parents(".annotation-editor"),id=display.attr("data-anno-id"),oaAnno=viewerParams.getAnnoFromRegion(id)[0];_this.unFreezeQtip(api,oaAnno,viewerParams),_this.eventEmitter.publish("annotationEditCancel."+_this.windowId,[id])})},showViewer:function(params){var _this=this,api=jQuery(_this.targetElement).qtip("api");if(api&&(!params.shouldDisplayTooltip||params.shouldDisplayTooltip(api)))if(0===params.annotations.length)api.cache.hidden||(api.disable(!1),api.hide(params.triggerEvent),api.cache.annotations=[],api.cache.hidden=!0,api.disable(!0));else{var oldAnnotations=api.cache.annotations,isTheSame=oldAnnotations.length==params.annotations.length;if(isTheSame)for(var i=0;i<params.annotations.length;i++)if(oldAnnotations[i]!=params.annotations[i]){isTheSame=!1;break}!api.cache.hidden&&isTheSame||(api.disable(!1),api.cache.contentUpdated=!1,_this.setTooltipContent(params.annotations),api.cache.origin=params.triggerEvent,api.reposition(params.triggerEvent,!0),api.show(params.triggerEvent),api.cache.annotations=params.annotations,api.cache.hidden=!1,api.disable(!0))}},setTooltipContent:function(annotations){var _this=this,api=jQuery(this.targetElement).qtip("api");api&&(api.cache.contentUpdated=!0,api.set({"content.text":this.getViewerContent(annotations)}),_this.eventEmitter.publish("tooltipViewerSet."+this.windowId))},getViewerContent:function(annotations){var annoText,tags=[],htmlAnnotations=[];jQuery.each(annotations,function(index,annotation){tags=[],jQuery.isArray(annotation.resource)?jQuery.each(annotation.resource,function(index,value){"oa:Tag"===value["@type"]?tags.push(value.chars):annoText=value.chars}):annoText=annotation.resource.chars;var username="";annotation.annotatedBy&&annotation.annotatedBy.name&&(username=annotation.annotatedBy.name);var showUpdate=!1;"manifest"!==annotation.endpoint&&(showUpdate=annotation.endpoint.userAuthorize("update",annotation));var showDelete=!1;"manifest"!==annotation.endpoint&&(showDelete=annotation.endpoint.userAuthorize("delete",annotation)),htmlAnnotations.push({annoText:$.sanitizeHtml(annoText),tags:tags,id:annotation["@id"],username:username,showUpdate:showUpdate,showDelete:showDelete})});var template=this.viewerTemplate({annotations:htmlAnnotations,windowId:this.windowId});return template},freezeQtip:function(api,oaAnno,viewerParams){var _this=this;if(this.inEditOrCreateMode)throw"AnnotationTooltip already in edit mode";this.inEditOrCreateMode=!0,_this.eventEmitter.publish("disableRectTool."+this.windowId);var editorContainer=this.editorTemplate({id:jQuery.isEmptyObject(oaAnno)?"":oaAnno["@id"],windowId:this.windowId});api.set({"content.text":editorContainer,"hide.event":!1}),this.activeEditor=new this.editor(jQuery.extend({},this.editorOptions,{annotation:oaAnno,windowId:this.windowId})),this.activeEditor.show("form#annotation-editor-"+this.windowId),_this.eventEmitter.publish("annotationEditorAvailable."+this.windowId),jQuery(api.elements.tooltip).removeClass("qtip-viewer"),api.elements.tooltip.draggable(),viewerParams.onEnterEditMode&&viewerParams.onEnterEditMode(api,oaAnno)},unFreezeQtip:function(api,oaAnno,viewerParams){var _this=this;if(!this.inEditOrCreateMode)throw"AnnotationTooltip not in edit mode";this.inEditOrCreateMode=!1,_this.eventEmitter.publish("enableRectTool."+this.windowId),api.set({"content.text":this.getViewerContent([oaAnno]),"hide.event":"mouseleave"}).hide(),jQuery(api.elements.tooltip).addClass("qtip-viewer"),viewerParams.onExitEditMode&&viewerParams.onExitEditMode(api,oaAnno)},editorTemplate:$.Handlebars.compile(['<form id="annotation-editor-{{windowId}}" class="annotation-editor annotation-tooltip" {{#if id}}data-anno-id="{{id}}"{{/if}}>',"<div>",'<div class="button-container">','<a href="#cancel" class="cancel"><i class="fa fa-times-circle-o fa-fw"></i>{{t "cancel"}}</a>','<a href="#save" class="save"><i class="fa fa-database fa-fw"></i>{{t "save"}}</a>',"</div>","</div>","</form>"].join("")),viewerTemplate:$.Handlebars.compile(['<div class="all-annotations" id="annotation-viewer-{{windowId}}">',"{{#each annotations}}",'<div class="annotation-display annotation-tooltip" data-anno-id="{{id}}">','<div class="button-container">','{{#if showUpdate}}<a href="#edit" class="edit"><i class="fa fa-pencil-square-o fa-fw"></i>{{t "edit"}}</a>{{/if}}','{{#if showDelete}}<a href="#delete" class="delete"><i class="fa fa-trash-o fa-fw"></i>{{t "delete"}}</a>{{/if}}',"</div>",'<div class="text-viewer">','{{#if username}}<p class="user">{{username}}:</p>{{/if}}',"<p>{{{annoText}}}</p>","</div>",'<div id="tags-viewer-{{windowId}}" class="tags-viewer">',"{{#each tags}}",'<span class="tag">{{this}}</span>',"{{/each}}","</div>","</div>","{{/each}}","</div>"].join(""))}}(Mirador),function($){$.CatchEndpoint=function(options){jQuery.extend(this,{token:null,prefix:null,params:"",dfd:null,context_id:"None",collection_id:"None",userid:"test@mirador.org",username:"mirador-test",annotationsList:[],annotationsListCatch:null,windowID:null,eventEmitter:null},options),this.init()},$.CatchEndpoint.prototype={init:function(){this.catchOptions={user:{id:this.userid,
81
+ name:this.username},permissions:{read:[],update:[this.userid],delete:[this.userid],admin:[this.userid]}}},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},search:function(options,successCallback,errorCallback){var _this=this;this.annotationsList=[],jQuery.ajax({url:this.prefix+"/search"+this.params,type:"GET",dataType:"json",headers:{"x-annotator-auth-token":this.token},data:{uri:options.uri,userid:options.userid?options.userid:void 0,username:options.username?options.username:void 0,text:options.text?options.text:void 0,tag:options.tag?options.tag:void 0,parentid:options.parentid?options.parentid:void 0,contextId:_this.context_id,collectionId:_this.collection_id,media:options.media?options.media:"image",limit:options.limit?options.limit:-1},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback?successCallback(data):(_this.annotationsListCatch=data.rows,jQuery.each(_this.annotationsListCatch,function(index,value){_this.annotationsList.push(_this.getAnnotationInOA(value))}),_this.dfd.resolve(!0),_this.eventEmitter.publish("catchAnnotationsLoaded."+_this.windowID,_this.annotationsListCatch))},error:function(){"function"==typeof errorCallback?errorCallback():console.log("There was an error searching this endpoint")}})},deleteAnnotation:function(annotationID,successCallback,errorCallback){var _this=this;jQuery.ajax({url:this.prefix+"/destroy/"+annotationID+this.params,type:"DELETE",dataType:"json",headers:{"x-annotator-auth-token":this.token},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(),_this.eventEmitter.publish("catchAnnotationDeleted."+_this.windowID,annotationID)},error:function(){"function"==typeof errorCallback&&errorCallback()}})},update:function(oaAnnotation,successCallback,errorCallback){var annotations=this.getAnnotationInEndpoint(oaAnnotation),_this=this;annotations.forEach(function(annotation){var annotationID=annotation.id;jQuery.ajax({url:_this.prefix+"/update/"+annotationID+_this.params,type:"POST",dataType:"json",headers:{"x-annotator-auth-token":_this.token},data:JSON.stringify(annotation),contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(_this.getAnnotationInOA(data)),_this.eventEmitter.publish("catchAnnotationUpdated."+_this.windowID,annotation)},error:function(){"function"==typeof errorCallback&&errorCallback()}})})},create:function(oaAnnotation,successCallback,errorCallback){var _this=this,annotations=this.getAnnotationInEndpoint(oaAnnotation);annotations.forEach(function(annotation){_this.createCatchAnnotation(annotation,successCallback,errorCallback)})},createCatchAnnotation:function(catchAnnotation,successCallback,errorCallback){var _this=this;jQuery.ajax({url:this.prefix+"/create"+this.params,type:"POST",dataType:"json",headers:{"x-annotator-auth-token":this.token},data:JSON.stringify(catchAnnotation),contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(_this.getAnnotationInOA(data)),_this.eventEmitter.publish("catchAnnotationCreated."+_this.windowID,data)},error:function(){"function"==typeof errorCallback&&errorCallback()}})},userAuthorize:function(action,annotation){if(this.roles&&(this.roles.indexOf("Instructor")!==-1||this.roles.indexOf("Administrator")!==-1))return!0;if(annotation.permissions){var permissionUserIds=annotation.permissions[action]||[];return 0===permissionUserIds.length||permissionUserIds.indexOf(this.userid)!==-1}return!annotation.user||this.userid===annotation.user.userid},getAnnotationInOA:function(annotation){var id,on,annotatedBy,motivation=[],resource=[];if(id=annotation.id,annotation.tags.length>0&&(motivation.push("oa:tagging"),jQuery.each(annotation.tags,function(index,value){resource.push({"@type":"oa:Tag",chars:value})})),annotation.parent&&"0"!==annotation.parent)motivation.push("oa:replying"),on=annotation.parent;else{var value;motivation.push("oa:commenting"),jQuery.isArray(annotation.rangePosition)?on=annotation.rangePosition:"object"==typeof annotation.rangePosition?(value="xywh="+annotation.rangePosition.x+","+annotation.rangePosition.y+","+annotation.rangePosition.width+","+annotation.rangePosition.height,on={"@type":"oa:SpecificResource",full:annotation.uri,selector:{"@type":"oa:FragmentSelector",value:value}}):(value=annotation.rangePosition,on={"@type":"oa:SpecificResource",full:annotation.uri,selector:{"@type":"oa:SvgSelector",value:value}})}resource.push({"@type":"dctypes:Text",format:"text/html",chars:annotation.text}),annotatedBy={"@id":annotation.user.id,name:annotation.user.name};var oaAnnotation={"@context":"http://iiif.io/api/presentation/2/context.json","@id":String(id),"@type":"oa:Annotation",motivation:motivation,resource:resource,on:on,annotatedBy:annotatedBy,annotatedAt:annotation.created,serializedAt:annotation.updated,permissions:annotation.permissions,endpoint:this};return oaAnnotation},getAnnotationInEndpoint:function(oaAnnotation){var _this=this,uris=[];oaAnnotation.on.forEach(function(value){jQuery.inArray(value.full,uris)===-1&&uris.push(value.full)});var annotations=[];return uris.forEach(function(uri){var text,annotation={},tags=[];oaAnnotation["@id"]&&(annotation.id=oaAnnotation["@id"]),annotation.media="image",jQuery.each(oaAnnotation.resource,function(index,value){"oa:Tag"===value["@type"]?tags.push(value.chars):"dctypes:Text"===value["@type"]&&(text=value.chars)}),annotation.tags=tags,annotation.text=text,annotation.uri=uri,annotation.contextId=_this.context_id,annotation.collectionId=_this.collection_id,annotation.rangePosition=oaAnnotation.on;var coordsArray=[];oaAnnotation.on.forEach(function(value){var xywh=value.selector.default.value.split("=")[1].split(",");coordsArray.push(xywh.map(function(i){return parseInt(i)}))});var left=coordsArray.map(function(i){return i[0]}),top=coordsArray.map(function(i){return i[1]}),right=coordsArray.map(function(i){return i[0]+i[2]}),bottom=coordsArray.map(function(i){return i[1]+i[3]}),newRect={x:Math.min.apply(null,left),y:Math.min.apply(null,top),width:Math.max.apply(null,right)-Math.min.apply(null,left),height:Math.max.apply(null,bottom)-Math.min.apply(null,top)},canvas=_this.imagesList[$.getImageIndexById(_this.imagesList,uri)],imageUrl=$.getThumbnailForCanvas(canvas,300);imageUrl=imageUrl.replace("full",newRect.x+","+newRect.y+","+newRect.width+","+newRect.height),annotation.thumb=imageUrl,annotation.bounds={x:newRect.x,y:newRect.y,width:newRect.width,height:newRect.height},annotation.updated=(new Date).toISOString(),oaAnnotation.annotatedAt?annotation.created=oaAnnotation.annotatedAt:annotation.created=annotation.updated,annotation.user={},oaAnnotation.annotatedBy?(annotation.user.name=oaAnnotation.annotatedBy.name,annotation.user.id=oaAnnotation.annotatedBy["@id"]):annotation.user=_this.catchOptions.user,annotation.permissions=_this.catchOptions.permissions,annotation.archived=!1,annotation.ranges=[],annotation.parent="0",annotations.push(annotation)}),annotations}}}(Mirador),function($){$.Endpoint=function(options){jQuery.extend(this,{dfd:null,annotationsList:[],windowID:null,eventEmitter:null},options),this.init()},$.Endpoint.prototype={init:function(){},search:function(options,successCallback,errorCallback){var _this=this;jQuery.ajax({url:"",type:"GET",dataType:"json",headers:{},data:{},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback?successCallback(data):(jQuery.each(data,function(index,value){_this.annotationsList.push(_this.getAnnotationInOA(value))}),_this.dfd.resolve(!0))},error:function(){"function"==typeof errorCallback&&errorCallback()}})},deleteAnnotation:function(annotationID,successCallback,errorCallback){jQuery.ajax({url:"",type:"DELETE",dataType:"json",headers:{},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback()},error:function(){"function"==typeof errorCallback&&errorCallback()}})},update:function(oaAnnotation,successCallback,errorCallback){this.getAnnotationInEndpoint(oaAnnotation);jQuery.ajax({url:"",type:"POST",dataType:"json",headers:{},data:"",contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback()},error:function(){"function"==typeof errorCallback&&errorCallback()}})},create:function(oaAnnotation,successCallback,errorCallback){var _this=this;jQuery.ajax({url:"",type:"POST",dataType:"json",headers:{},data:"",contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback&&successCallback(_this.getAnnotationInOA(data))},error:function(){"function"==typeof errorCallback&&errorCallback()}})},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},getAnnotationInOA:function(annotation){},getAnnotationInEndpoint:function(oaAnnotation){}}}(Mirador),function($){$.LegacyOpenAnnotationStrategy=function(options){jQuery.extend(this,{},options),this.init()},$.LegacyOpenAnnotationStrategy.prototype={init:function(){},isThisType:function(annotation){return!(!annotation.on||"string"!=typeof annotation.on)&&annotation.on.indexOf("xywh=")!==-1},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay,bounds=overlay.draftPaths[0].bounds;return oaAnno.on=win.canvasID+"#xywh="+Math.round(bounds.x)+","+Math.round(bounds.y)+","+Math.round(bounds.width)+","+Math.round(bounds.height),oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation))return osdRegionDrawTool.parseRectangle(annotation.on,annotation)}}}(Mirador),function($){$.LocalStorageEndpoint=function(options){jQuery.extend(this,{token:null,prefix:null,dfd:null,annotationsList:[],windowID:null,eventEmitter:null},options),this.init()},$.LocalStorageEndpoint.prototype={init:function(){},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},search:function(options,successCallback,errorCallback){var _this=this;this.annotationsList=[];try{_this.annotationsList=_this.getAnnotationList(options.uri),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback?successCallback(_this.annotationsList):_this.dfd.resolve(!0)}catch(e){"function"==typeof errorCallback?errorCallback():console.log("There was an error searching this endpoint")}},deleteAnnotation:function(annotationID,successCallback,errorCallback){var _this=this,keys=[];jQuery.each(_this.annotationsList[0].on,function(index,value){jQuery.inArray(value.full,keys)===-1&&keys.push(value.full)}),0===keys.length&&"function"==typeof errorCallback&&errorCallback(),jQuery.each(keys,function(index,key){try{_this.annotationsList=jQuery.grep(_this.annotationsList,function(value,index){return value["@id"]!==annotationID}),jQuery.each(_this.annotationsList,function(index,value){delete value.endpoint}),localStorage.setItem(key,JSON.stringify(_this.annotationsList)),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback&&successCallback()}catch(e){"function"==typeof errorCallback&&errorCallback()}})},update:function(oaAnnotation,successCallback,errorCallback){var _this=this,annotationID=oaAnnotation["@id"],keys=[];jQuery.each(oaAnnotation.on,function(index,value){jQuery.inArray(value.full,keys)===-1&&keys.push(value.full)}),0===keys.length&&"function"==typeof errorCallback&&errorCallback(),jQuery.each(keys,function(index,key){try{0===_this.annotationsList.length&&(_this.annotationsList=_this.getAnnotationList(key)),jQuery.each(_this.annotationsList,function(index,value){if(value["@id"]===annotationID)return _this.annotationsList[index]=oaAnnotation,!1}),jQuery.each(_this.annotationsList,function(index,value){delete value.endpoint}),localStorage.setItem(key,JSON.stringify(_this.annotationsList)),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback&&successCallback(oaAnnotation)}catch(e){"function"==typeof errorCallback&&errorCallback()}})},create:function(oaAnnotation,successCallback,errorCallback){var _this=this,keys=[];jQuery.each(oaAnnotation.on,function(index,value){jQuery.inArray(value.full,keys)===-1&&keys.push(value.full)}),0===keys.length&&"function"==typeof errorCallback&&errorCallback(),jQuery.each(keys,function(index,key){try{0===_this.annotationsList.length&&(_this.annotationsList=_this.getAnnotationList(key)),oaAnnotation["@id"]=$.genUUID(),_this.annotationsList.push(oaAnnotation),jQuery.each(_this.annotationsList,function(index,value){delete value.endpoint}),localStorage.setItem(key,JSON.stringify(_this.annotationsList)),jQuery.each(_this.annotationsList,function(index,value){value.endpoint=_this}),"function"==typeof successCallback&&successCallback(oaAnnotation)}catch(e){"function"==typeof errorCallback&&errorCallback()}})},getAnnotationList:function(key){var data=localStorage.getItem(key);return data?JSON.parse(data):[]},userAuthorize:function(action,annotation){return!0}}}(Mirador),function($){$.Mirador21Strategy=function(options){jQuery.extend(this,{},options),this.init()},$.Mirador21Strategy.prototype={init:function(){},isThisType:function(annotation){return!!(annotation.on&&"object"==typeof annotation.on&&annotation.on.selector&&"object"==typeof annotation.on.selector&&annotation.on.selector.value&&"string"==typeof annotation.on.selector.value&&"oa:SvgSelector"===annotation.on.selector["@type"])},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay,svg=overlay.getSVGString(overlay.draftPaths);return oaAnno.on={"@type":"oa:SpecificResource",full:win.canvasID,selector:{"@type":"oa:SvgSelector",value:svg},within:{"@id":win.loadedManifest,"@type":"sc:Manifest"}},oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation))return osdRegionDrawTool.svgOverlay.parseSVG(annotation.on.selector.value,annotation)}}}(Mirador),function($){$.MiradorDualStrategy=function(options){jQuery.extend(this,{},options),this.init()},$.MiradorDualStrategy.prototype={init:function(){},isThisType:function(annotation){return!!(annotation.on&&jQuery.isArray(annotation.on)&&annotation.on.length>0&&"object"==typeof annotation.on[0]&&annotation.on[0].selector&&"object"==typeof annotation.on[0].selector&&"oa:Choice"===annotation.on[0].selector["@type"]&&annotation.on[0].selector.default&&"object"==typeof annotation.on[0].selector.default&&annotation.on[0].selector.default.value&&"string"==typeof annotation.on[0].selector.default.value&&annotation.on[0].selector.item&&"object"==typeof annotation.on[0].selector.item&&annotation.on[0].selector.item.value&&"string"==typeof annotation.on[0].selector.item.value)&&(0===annotation.on[0].selector.default.value.indexOf("xywh=")&&0===annotation.on[0].selector.item.value.indexOf("<svg"))},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay;return oaAnno.on=[],jQuery.each(overlay.draftPaths,function(index,path){var svg=overlay.getSVGString([path]),bounds=path.bounds;oaAnno.on.push({"@type":"oa:SpecificResource",full:win.canvasID,selector:{"@type":"oa:Choice",default:{"@type":"oa:FragmentSelector",value:"xywh="+Math.round(bounds.x)+","+Math.round(bounds.y)+","+Math.round(bounds.width)+","+Math.round(bounds.height)},item:{"@type":"oa:SvgSelector",value:svg}},within:{"@id":win.loadedManifest,"@type":"sc:Manifest"}})}),oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation)){var regionArray=[];return jQuery.each(annotation.on,function(index,target){regionArray=regionArray.concat(osdRegionDrawTool.svgOverlay.parseSVG(target.selector.item.value,annotation))}),regionArray}}}}(Mirador),function($){$.MiradorLegacyStrategy=function(options){jQuery.extend(this,{},options),this.init()},$.MiradorLegacyStrategy.prototype={init:function(){},isThisType:function(annotation){return!!(annotation.on&&"object"==typeof annotation.on&&annotation.on.selector&&"object"==typeof annotation.on.selector&&annotation.on.selector.value&&"string"==typeof annotation.on.selector.value&&"oa:FragmentSelector"===annotation.on.selector["@type"])&&0===annotation.on.selector.value.indexOf("xywh=")},buildAnnotation:function(options){var oaAnno=options.annotation,win=options.window,overlay=options.overlay,bounds=overlay.draftPaths[0].bounds;return oaAnno.on={"@type":"oa:SpecificResource",full:win.canvasID,selector:{"@type":"oa:FragmentSelector",value:"xywh="+Math.round(bounds.x)+","+Math.round(bounds.y)+","+Math.round(bounds.width)+","+Math.round(bounds.height)}},oaAnno},parseRegion:function(annotation,osdRegionDrawTool){if(this.isThisType(annotation))return osdRegionDrawTool.parseRectangle(annotation.on.full+"#"+annotation.on.selector.value,annotation)}}}(Mirador),function($){$.OsdRegionDrawTool=function(options){jQuery.extend(this,{osdViewer:null,parent:null,osd:null,list:null,annotationsToShapesMap:{},eventEmitter:null},options),this.eventsSubscriptions=[],this.init()},$.OsdRegionDrawTool.prototype={init:function(){this.svgOverlay=this.osdViewer.svgOverlay(this.osdViewer.id,this.windowId,this.state,this.eventEmitter),this.svgOverlay.show(),this.svgOverlay.disable(),this.listenForActions()},enterDisplayAnnotations:function(){this.svgOverlay.setMouseTool(),this.svgOverlay.inEditOrCreateMode?this.svgOverlay.checkToRemoveFocus():(this.exitEditMode(!0),this.render())},enterCreateAnnotation:function(){this.svgOverlay.inEditOrCreateMode?this.svgOverlay.checkToRemoveFocus():(this.osdViewer.setMouseNavEnabled(!1),this.svgOverlay.show(),this.svgOverlay.enable(),this.render())},enterCreateShape:function(){this.svgOverlay.inEditOrCreateMode?this.svgOverlay.checkToRemoveFocus():(this.osdViewer.setMouseNavEnabled(!1),this.svgOverlay.show(),this.svgOverlay.enable())},enterEditAnnotation:function(){this.osdViewer.setMouseNavEnabled(!1),this.svgOverlay.show(),this.svgOverlay.enableEdit()},enterDefault:function(){this.svgOverlay.removeMouseTool(),this.exitEditMode(!1)},exitEditMode:function(showAnnotations){this.osdViewer.setMouseNavEnabled(!0),this.svgOverlay.disable(),showAnnotations?this.svgOverlay.show():this.svgOverlay.hide()},render:function(){if(this.parent.mode===$.AnnotationsLayer.DISPLAY_ANNOTATIONS){this.svgOverlay.restoreEditedShapes(),this.svgOverlay.paperScope.activate(),this.svgOverlay.paperScope.project.clear();var _this=this;_this.annotationsToShapesMap={};for(var strategies=[new $.Mirador21Strategy,new $.LegacyOpenAnnotationStrategy,new $.MiradorLegacyStrategy,new $.MiradorDualStrategy],i=0;i<this.list.length;i++){var shapeArray,annotation=this.list[i];if("object"==typeof annotation&&annotation.on){var j;for(j=0;j<strategies.length;j++)if(strategies[j].isThisType(annotation)){shapeArray=strategies[j].parseRegion(annotation,_this);break}if(j===strategies.length)continue}_this.svgOverlay.restoreLastView(shapeArray),_this.annotationsToShapesMap[annotation["@id"]]=shapeArray}var windowElement=_this.state.getWindowElement(_this.windowId);this.annoTooltip=new $.AnnotationTooltip({targetElement:jQuery(this.osdViewer.element),state:_this.state,eventEmitter:_this.eventEmitter,windowId:_this.windowId}),this.annoTooltip.initializeViewerUpgradableToEditor({container:windowElement,viewport:windowElement,getAnnoFromRegion:_this.getAnnoFromRegion.bind(this)}),this.svgOverlay.paperScope.view.draw(),_this.eventEmitter.publish("annotationsRendered."+_this.windowId)}},parseRectangle:function(rectString,annotation){var shapeArray=rectString.split("=")[1].split(","),shape={x:parseInt(shapeArray[0]),y:parseInt(shapeArray[1]),width:parseInt(shapeArray[2]),height:parseInt(shapeArray[3])};return this.svgOverlay.createRectangle(shape,annotation)},showTooltipsFromMousePosition:function(event,location,absoluteLocation){var _this=this,hitOptions={fill:!0,stroke:!0,segments:!0},hoverColor=this.state.getStateProperty("drawingToolsSettings").hoverColor,annotations=[];for(var key in _this.annotationsToShapesMap)if(_this.annotationsToShapesMap.hasOwnProperty(key))for(var shapeArray=_this.annotationsToShapesMap[key],idx=0;idx<shapeArray.length;idx++){var shapeTool=this.svgOverlay.getTool(shapeArray[idx]);if(shapeArray[idx].hitTest(location,hitOptions)){if(annotations.push(shapeArray[idx].data.annotation),shapeTool.onHover)for(var k=0;k<shapeArray.length;k++)shapeTool.onHover(!0,shapeArray[k],hoverColor);break}shapeTool.onHover&&shapeTool.onHover(!1,shapeArray[idx])}this.svgOverlay.paperScope.view.draw(),_this.annoTooltip.showViewer({annotations:annotations,triggerEvent:event,shouldDisplayTooltip:function(api){if(api.elements.tooltip){var cursorWithinTooltip=!0,leftSide=api.elements.tooltip.offset().left-_this.svgOverlay.hitOptions.tolerance,rightSide=api.elements.tooltip.offset().left+api.elements.tooltip.width()+_this.svgOverlay.hitOptions.tolerance;(absoluteLocation.x<leftSide||rightSide<absoluteLocation.x)&&(cursorWithinTooltip=!1);var topSide=api.elements.tooltip.offset().top-_this.svgOverlay.hitOptions.tolerance,bottomSide=api.elements.tooltip.offset().top+api.elements.tooltip.height()+_this.svgOverlay.hitOptions.tolerance;return(absoluteLocation.y<topSide||bottomSide<absoluteLocation.y)&&(cursorWithinTooltip=!1),!cursorWithinTooltip}return!0}})},listenForActions:function(){var _this=this;this._thisDestroy=function(){_this.destroy()},_this.osdViewer.addHandler("close",this._thisDestroy),this.eventsSubscriptions.push(this.eventEmitter.subscribe("DESTROY_EVENTS."+this.windowId,function(event){_this.destroy()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("updateTooltips."+_this.windowId,function(event,location,absoluteLocation){_this.annoTooltip&&!_this.annoTooltip.inEditOrCreateMode&&_this.showTooltipsFromMousePosition(event,location,absoluteLocation)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("removeTooltips."+_this.windowId,function(){jQuery(_this.osdViewer.element).qtip("destroy",!0)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("disableTooltips."+_this.windowId,function(){_this.annoTooltip&&(_this.annoTooltip.inEditOrCreateMode=!0)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("enableTooltips."+_this.windowId,function(){_this.annoTooltip&&(_this.annoTooltip.inEditOrCreateMode=!1),_this.svgOverlay.restoreDraftShapes()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("SET_ANNOTATION_EDITING."+_this.windowId,function(event,options){jQuery.each(_this.annotationsToShapesMap,function(key,paths){key===options.annotationId?(options.isEditable?_this.eventEmitter.publish("SET_OVERLAY_TOOLTIP."+_this.windowId,{tooltip:options.tooltip,visible:!0,paths:paths}):_this.eventEmitter.publish("SET_OVERLAY_TOOLTIP."+_this.windowId,{tooltip:null,visible:!1,paths:[]}),jQuery.each(paths,function(index,path){var tool=_this.svgOverlay.getTool(path);tool.onHover(!1,path),path.data.editable=options.isEditable,options.isEditable?(path.data.currentStrokeValue=path.data.editStrokeValue,path.strokeWidth=path.data.currentStrokeValue/_this.svgOverlay.paperScope.view.zoom):(path.data.currentStrokeValue=path.data.defaultStrokeValue,path.strokeWidth=path.data.currentStrokeValue/_this.svgOverlay.paperScope.view.zoom)})):jQuery.each(paths,function(index,path){path.data.editable=!1})}),_this.svgOverlay.paperScope.view.draw()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("refreshOverlay."+_this.windowId,function(event){_this.render()}))},getAnnoFromRegion:function(regionId){return this.list.filter(function(annotation){return annotation["@id"]===regionId})},destroy:function(){var _this=this;this.eventsSubscriptions.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)}),this.osdViewer.removeHandler("close",this._thisDestroy)}}}(Mirador),function($){$.Ellipse=function(options){jQuery.extend(this,{name:"Ellipse",logoClass:"radio_button_unchecked",idPrefix:"ellipse_",tooltip:"ellipseTooltip"},options),this.init()},$.Ellipse.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var segments=[],pixel=1/overlay.paperScope.view.zoom;segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-(Math.sqrt(2)+1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-(Math.sqrt(2)+1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-(Math.sqrt(2)+1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x+(Math.sqrt(2)-1)*pixel,initialPoint.y-1*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y+(Math.sqrt(2)-1)*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-(Math.sqrt(2)+1)*pixel,initialPoint.y-1*pixel));var _this=this,shape=new overlay.paperScope.Path({segments:segments,name:overlay.getName(_this)});return shape.dashArray=overlay.dashArray,shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape.strokeColor=overlay.strokeColor,shape.fillColor=overlay.fillColor,shape.fillColor.alpha=overlay.fillColorAlpha,shape.closed=!0,shape.data.rotation=0,overlay.segment=shape.segments[6],this.updateSelection(!0,shape,overlay),shape},updateSelection:function(selected,item,overlay){if(item._name.toString().indexOf(this.idPrefix)!=-1){item.segments.length>10&&item.removeSegment(10),item.smooth({from:-7,to:1}),item.selected=selected,item.segments[2].selected=selected;var inHandle=item.segments[7].handleIn.clone();inHandle=inHandle.multiply(-1);var outHandle=item.segments[7].handleOut.clone();if(outHandle=outHandle.multiply(-1),item.segments[1].handleIn=inHandle,item.segments[1].handleOut=new overlay.paperScope.Point(0,0),item.segments[2].handleIn=new overlay.paperScope.Point(0,0),item.segments[2].handleOut=new overlay.paperScope.Point(0,0),item.segments[3].handleIn=new overlay.paperScope.Point(0,0),item.segments[3].handleOut=outHandle,selected){var point=item.segments[2].point.clone();point=point.add(item.segments[2].handleOut),item.contains(point)&&(item.segments[2].handleOut=item.segments[2].handleOut.rotate(180,item.segments[2])),item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.addData("pivot",item.segments[7].point),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.setOnMouseDownListener(overlay)),item.data.rotationIcon||(item.data.rotationIcon=new overlay.annotationUtils.RotationIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"rotation",fillColor:item.selectedColor}),item.data.rotationIcon.addData("pivot",item.segments[3].point),item.data.rotationIcon.addData("type","rotationIcon"),item.data.rotationIcon.addData("self",item.data.rotationIcon),item.data.rotationIcon.addData("parent",item),item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.setOnMouseDownListener(overlay)),item.data.group||(item.data.group=new overlay.annotationUtils.Group(overlay.paperScope,[item,item.data.deleteIcon.getItem(),item.data.deleteIcon.getMask().getItem(),item.data.rotationIcon.getItem(),item.data.rotationIcon.getMask().getItem()])),item.contains(item.data.deleteIcon.getItem().position)&&(item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.rotate(180,item.data.deleteIcon.getData("pivot")),item.data.deleteIcon.rotate(180)),item.contains(item.data.rotationIcon.getItem().position)&&(item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.rotate(180,item.data.rotationIcon.getData("pivot")),item.data.rotationIcon.rotate(180))}else item.data.group&&(item.data.group.remove(),item.data.group=null,overlay.paperScope.project.activeLayer.addChild(item)),item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null),item.data.rotationIcon&&(item.data.rotationIcon.remove(),item.data.rotationIcon=null),item.segments[2].handleOut=new overlay.paperScope.Point(0,0)}},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&(item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(24/overlay.paperScope.view.zoom)),item._name.toString().indexOf("rotation")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(16/overlay.paperScope.view.zoom)))},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){"create"==overlay.mode&&overlay.path?overlay.onDrawFinish():("translate"===overlay.mode||"deform"===overlay.mode&&overlay.path)&&overlay.onEditFinish()},translate:function(event,overlay){for(var i=0;i<overlay.path.segments.length;i++)overlay.path.segments[i].point.x+=event.delta.x,overlay.path.segments[i].point.y+=event.delta.y;overlay.path.data.rotationIcon.translateByXY(event.delta.x,event.delta.y),overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y)},rotate:function(event,overlay){var center=overlay.path.position,rotation=Math.atan2(event.point.y-center.y+event.delta.y,event.point.x-center.x+event.delta.x)-Math.atan2(event.point.y-center.y,event.point.x-center.x);rotation*=180/Math.PI,overlay.path.data.group.rotate(rotation,overlay.path.position),overlay.path.data.deleteIcon.rotate(-rotation),overlay.path.data.rotationIcon.rotate(-rotation),overlay.path.data.rotation+=rotation},onMouseDrag:function(event,overlay){if("translate"==overlay.mode)return void this.translate(event,overlay);if("rotate"===overlay.mode)return void this.rotate(event,overlay);if("create"==overlay.mode||"deform"==overlay.mode){for(var idx=-1,l=0;l<overlay.path.segments.length;l++)if(overlay.path.segments[l]==overlay.segment){idx=l;break}var translation=new overlay.paperScope.Point(event.delta.x,event.delta.y),rot=overlay.path.data.rotation;translation=translation.rotate(-rot);var translationX=new overlay.paperScope.Point(translation.x,0);
82
+ translationX=translationX.rotate(rot);var translationY=new overlay.paperScope.Point(0,translation.y);translationY=translationY.rotate(rot),0!==idx&&4!==idx&&6!==idx&&8!==idx||(translationX=translationX.multiply(2/(1+Math.sqrt(.5))),translationY=translationY.multiply(2/(1+Math.sqrt(.5))));var moveTopSize=0===idx||1===idx||2===idx||3===idx||4===idx,moveBottomSize=6===idx||7===idx||8===idx,moveRightSize=4===idx||5===idx||6===idx,moveLeftSize=0===idx||8===idx||9===idx;if(moveTopSize){overlay.path.data.rotationIcon.translateByPoint(translationY),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationY),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationY),overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationY);var trTop=translationY.clone();trTop=trTop.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trTop),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trTop),trTop=trTop.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trTop),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trTop)}if(moveBottomSize){overlay.path.data.deleteIcon.translateByPoint(translationY),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationY);var trBottom=translationY.clone();trBottom=trBottom.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trBottom),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trBottom),trBottom=trBottom.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trBottom),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trBottom)}if((moveTopSize||moveBottomSize)&&(translationY=translationY.multiply(.5),overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationY),overlay.path.segments[9].point=overlay.path.segments[9].point.add(translationY)),moveRightSize){overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationX);var trRight=translationX.clone();trRight=trRight.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trRight),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trRight),trRight=trRight.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trRight),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trRight)}if(moveLeftSize){overlay.path.segments[9].point=overlay.path.segments[9].point.add(translationX);var trLeft=translationX.clone();trLeft=trLeft.multiply((1+Math.sqrt(.5))/2),overlay.path.segments[0].point=overlay.path.segments[0].point.add(trLeft),overlay.path.segments[8].point=overlay.path.segments[8].point.add(trLeft),trLeft=trLeft.multiply((1-Math.sqrt(.5))/(1+Math.sqrt(.5))),overlay.path.segments[4].point=overlay.path.segments[4].point.add(trLeft),overlay.path.segments[6].point=overlay.path.segments[6].point.add(trLeft)}(moveRightSize||moveLeftSize)&&(translationX=translationX.multiply(.5),overlay.path.data.rotationIcon.translateByPoint(translationX),overlay.path.data.deleteIcon.translateByPoint(translationX),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationX),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationX),overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationX),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationX));var point=overlay.path.segments[2].point.clone();point=point.add(overlay.path.segments[2].handleOut),overlay.path.contains(point)&&(overlay.path.segments[2].handleOut=overlay.path.segments[2].handleOut.rotate(180,overlay.path.segments[2])),overlay.path.contains(overlay.path.data.deleteIcon.getItem().position)&&(overlay.path.data.deleteIcon.rotate(180,overlay.path.data.deleteIcon.getData("pivot")),overlay.path.data.deleteIcon.rotate(180)),overlay.path.contains(overlay.path.data.rotationIcon.getItem().position)&&(overlay.path.data.rotationIcon.rotate(180,overlay.path.data.rotationIcon.getData("pivot")),overlay.path.data.rotationIcon.rotate(180)),overlay.path.segments.length>10&&overlay.path.removeSegment(10),overlay.path.smooth({from:-7,to:1})}},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type||"handle-in"===hitResult.type||"handle-out"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1&&"deform"!=overlay.mode&&"translate"!=overlay.mode&&"create"!=overlay.mode){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return hitResult.item.data.self.onMouseDown(),void("rotate"===overlay.mode&&(overlay.path=hitResult.item.data.self.getItem().data.parent));"segment"===hitResult.type&&(overlay.mode="deform",overlay.segment=null,overlay.path=null,this.setCursor(hitResult,overlay)),"stroke"!==hitResult.type&&"handle-in"!==hitResult.type&&"handle-out"!==hitResult.type||(overlay.mode="translate",overlay.segment=null,overlay.path=null)}return"translate"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):overlay.path=hitResult.item):"deform"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):(overlay.path=hitResult.item,overlay.segment=hitResult.segment)):void(overlay.path=this.createShape(event.point,overlay))},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.Freehand=function(options){jQuery.extend(this,{name:"Freehand",logoClass:"gesture",idPrefix:"smooth_path_",tooltip:"freehandTooltip"},options),this.init()},$.Freehand.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var _this=this,shape=new overlay.paperScope.Path({segments:[initialPoint],dashArray:overlay.dashArray,strokeColor:overlay.strokeColor,name:overlay.getName(_this)});return shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape},updateSelection:function(selected,item,overlay){item._name.toString().indexOf(this.idPrefix)!==-1&&(item.selected=selected,selected?item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(item))),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.deleteIcon.setOnMouseDownListener(overlay)):item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null))},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.self.resize(24/overlay.paperScope.view.zoom))},getPivotPointForDeleteIcon:function(item){for(var points=[],i=0;i<item.segments.length;i++)points.push(item.segments[i].point);return{x:this.getGeometricCenterOfPoints(points).x,y:this.getLowestPoint(points).y}},getLowestPoint:function(points){for(var lx=0,ly=0,i=0;i<points.length;i++)lx=Math.max(lx,points[i].x),ly=Math.max(ly,points[i].y);return{x:lx,y:ly}},getGeometricCenterOfPoints:function(points){for(var cx=0,cy=0,i=0;i<points.length;i++)cx+=points[i].x,cy+=points[i].y;return{x:cx/points.length,y:cy/points.length}},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){"create"===overlay.mode&&overlay.path&&(overlay.path.simplify(),overlay.onDrawFinish())},onMouseDrag:function(event,overlay){if("deform"!==overlay.mode)return"translate"===overlay.mode?void(overlay.path&&(overlay.path.position.x+=event.delta.x,overlay.path.position.y+=event.delta.y,overlay.path.data.deleteIcon&&overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y))):void("create"===overlay.mode&&(overlay.path.add(event.point),overlay.path.data.deleteIcon&&(overlay.path.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(overlay.path))),overlay.path.data.deleteIcon.setPosition(overlay.path.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))))));if(overlay.segment){overlay.segment.point.x+=event.delta.x,overlay.segment.point.y+=event.delta.y,overlay.path.smooth();var path=overlay.segment.path;path.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(path))),path.data.deleteIcon.setPosition(path.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom)))}},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"handle-in"===hitResult.type||"handle-out"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return void hitResult.item.data.self.onMouseDown();if("create"!==overlay.mode){if("stroke"===hitResult.type)return overlay.mode="translate",void(overlay.path=hitResult.item);if("segment"===hitResult.type||"handle-out"===hitResult.type||"handle-in"===hitResult.type)return event.modifiers.shift&&hitResult.item.segments.length>2?void hitResult.segment.remove():(overlay.mode="deform",overlay.segment=hitResult.segment,void(overlay.path=hitResult.item))}}else"create"!==overlay.mode&&(overlay.mode="");if(""===overlay.mode)return void(overlay.path=this.createShape(event.point,overlay))},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.getTools=function(options){return this.svgOverlayTools?this.svgOverlayTools:(options.partOfPrefix="_partOf",this.svgOverlayTools=[new $.Rectangle(options),new $.Freehand(options),new $.Polygon(options),new $.Ellipse(options),new $.Pin(options)],this.svgOverlayTools)},OpenSeadragon.Viewer.prototype.svgOverlay=function(osdViewerId,windowId,state,eventEmitter){return new $.Overlay(this,osdViewerId,windowId,state,eventEmitter)};var FILL_COLOR_ALPHA_WORKAROUND=1e-5;$.Overlay=function(viewer,osdViewerId,windowId,state,eventEmitter){var drawingToolsSettings=state.getStateProperty("drawingToolsSettings");this.drawingToolsSettings=drawingToolsSettings;var availableAnnotationDrawingTools=state.getStateProperty("availableAnnotationDrawingTools"),availableExternalCommentsPanel=state.getStateProperty("availableExternalCommentsPanel");jQuery.extend(this,{disabled:!0,inEditOrCreateMode:!1,osdViewerId:osdViewerId,windowId:windowId,commentPanel:null,mode:"",draftPaths:[],editedPaths:[],hoveredPath:null,path:null,segment:null,latestMouseDownTime:-1,doubleClickReactionTime:drawingToolsSettings.doubleClickReactionTime,availableAnnotationDrawingTools:availableAnnotationDrawingTools,availableExternalCommentsPanel:availableExternalCommentsPanel,dashArray:[],fixedShapeSize:drawingToolsSettings.fixedShapeSize,selectedColor:drawingToolsSettings.selectedColor||"#004c66",shapeHandleSize:drawingToolsSettings.shapeHandleSize,partOfPrefix:"_partOf",hitOptions:{handles:!0,stroke:!0,segments:!0,tolerance:5}}),this.tools=$.getTools(drawingToolsSettings),this.currentTool=null,this.dashArray=[],this.strokeColor=drawingToolsSettings.strokeColor,this.fillColor=drawingToolsSettings.fillColor,this.fillColorAlpha=drawingToolsSettings.fillColorAlpha,this.viewer=viewer,this.canvas=document.createElement("canvas"),jQuery(this.canvas).attr("tabindex","0").mousedown(function(){jQuery(this).focus()}),this.canvas.id="draw_canvas_"+this.windowId,this.viewer.canvas.appendChild(this.canvas);this.slotWindowElement=state.getWindowElement(this.windowId),this.state=state,this.eventEmitter=eventEmitter,this.eventsSubscriptions=[],this.resize(),this.show(),this.init()},$.Overlay.prototype={init:function(){var _this=this;this.lastAngle=0,this.paperScope=new paper.PaperScope,this.paperScope.setup("draw_canvas_"+_this.windowId),this.paperScope.activate(),this.paperScope.project.options.handleSize=_this.state.getStateProperty("shapeHandleSize"),jQuery(_this.canvas).attr("keepalive","true"),this.annotationUtils=new $.AnnotationUtils,this.paperScope.view.onFrame=function(event){if(_this.paperScope.snapPoint&&(_this.paperScope.snapPoint.remove(),_this.paperScope.snapPoint=null),_this.path&&!_this.path.closed&&_this.cursorLocation&&_this.currentTool&&_this.currentTool.idPrefix.indexOf("rough_path_")!=-1){var distanceToFirst=_this.path.segments[0].point.getDistance(_this.cursorLocation);_this.path.segments.length>1&&distanceToFirst<_this.hitOptions.tolerance&&(_this.paperScope.snapPoint=new _this.paperScope.Path.Circle({name:"snapPoint",center:_this.path.segments[0].point,radius:_this.hitOptions.tolerance/_this.paperScope.view.zoom,fillColor:_this.path.strokeColor,strokeColor:_this.path.strokeColor}))}},this.mouseToolKey="draw_canvas_"+_this.windowId,this.setMouseTool(),this.listenForActions()},setMouseTool:function(){this.removeMouseTool(),this.paperScope.activate();var mouseTool=new this.paperScope.Tool;mouseTool.overlay=this,mouseTool.onMouseUp=this.onMouseUp,mouseTool.onMouseDrag=this.onMouseDrag,mouseTool.onMouseMove=this.onMouseMove,mouseTool.onMouseDown=this.onMouseDown,mouseTool.onDoubleClick=this.onDoubleClick,mouseTool.onKeyDown=function(event){},jQuery.data(document.body,this.mouseToolKey,mouseTool)},removeMouseTool:function(){var mouseTool=jQuery.data(document.body,this.mouseToolKey);mouseTool&&(mouseTool.remove(),jQuery.removeData(document.body,this.mouseToolKey))},handleDeleteShapeEvent:function(event,shape){var _this=this;new $.DialogBuilder(this.slotWindowElement).dialog({message:i18next.t("deleteShape"),closeButton:!1,className:"mirador-dialog",buttons:{no:{label:i18next.t("no"),className:"btn-default",callback:function(){}},yes:{label:i18next.t("yes"),className:"btn-primary",callback:function(){_this.deleteShape(shape)}}}})},listenForActions:function(){var _this=this;this._thisResize=function(){_this.resize()},this._thisRotate=function(event){_this.rotate(event),_this.resize()},this.viewer.addHandler("animation",this._thisResize),this.viewer.addHandler("open",this._thisResize),this.viewer.addHandler("animation-finish",this._thisResize),this.viewer.addHandler("update-viewport",this._thisResize),this.viewer.addHandler("resize",this._thisResize),this.viewer.addHandler("rotate",this._thisRotate),this.viewer.addHandler("constrain",this._thisResize),this._thisDestroy=function(){_this.destroy()},this.viewer.addHandler("close",this._thisDestroy),this.eventsSubscriptions.push(this.eventEmitter.subscribe("DESTROY_EVENTS."+this.windowId,function(event){_this.destroy()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("toggleDrawingTool."+_this.windowId,function(event,tool){if(!_this.disabled){_this.currentTool=null,_this.mode="";for(var i=0;i<_this.tools.length;i++)_this.tools[i].logoClass===tool&&(_this.currentTool=_this.tools[i])}}));var _thisHandleDeleteShapeEvent=function(event,shape){_this.handleDeleteShapeEvent(event,shape)};this.eventsSubscriptions.push(_this.eventEmitter.subscribe("deleteShape."+_this.windowId,_thisHandleDeleteShapeEvent)),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("changeBorderColor."+_this.windowId,function(event,color){_this.strokeColor=color,_this.hoveredPath&&(_this.hoveredPath.strokeColor=color,_this.paperScope.view.draw())})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("changeFillColor."+_this.windowId,function(event,color,alpha){_this.fillColor=color,0===alpha&&(alpha=FILL_COLOR_ALPHA_WORKAROUND),_this.fillColorAlpha=alpha,_this.hoveredPath&&_this.hoveredPath.closed&&(_this.hoveredPath.fillColor=color,_this.hoveredPath.fillColor.alpha=alpha,_this.paperScope.view.draw())})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("toggleBorderType."+_this.windowId,function(event,type){"solid"==type?_this.dashArray=[]:"dashed"==type?_this.dashArray=[5,5]:"dotdashed"==type&&(_this.dashArray=[2,5,7,5]),_this.hoveredPath&&(_this.hoveredPath.dashArray=_this.dashArray,_this.paperScope.view.draw())})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("annotationEditSave."+_this.windowId,function(event,oaAnno){var onAnnotationSaved=jQuery.Deferred();if(_this.draftPaths.length){var writeStrategy=new $.MiradorDualStrategy;writeStrategy.buildAnnotation({annotation:oaAnno,window:_this.state.getWindowObjectById(_this.windowId),overlay:_this}),_this.eventEmitter.publish("annotationUpdated."+_this.windowId,[oaAnno]),onAnnotationSaved.resolve()}else new $.DialogBuilder(_this.slotWindowElement).dialog({message:i18next.t("editModalSaveAnnotationWithNoShapesMsg"),closeButton:!1,className:"mirador-dialog",buttons:{success:{label:i18next.t("editModalBtnSaveWithoutShapes"),className:"btn-success",callback:function(){oaAnno.on={"@type":"oa:SpecificResource",full:_this.state.getWindowObjectById(_this.windowId).canvasID},_this.eventEmitter.publish("annotationUpdated."+_this.windowId,[oaAnno]),onAnnotationSaved.resolve()}},danger:{label:i18next.t("editModalBtnDeleteAnnotation"),className:"btn-danger",callback:function(){_this.eventEmitter.publish("annotationDeleted."+_this.windowId,[oaAnno["@id"]]),onAnnotationSaved.resolve()}},main:{label:i18next.t("cancel"),className:"btn-default",callback:function(){onAnnotationSaved.reject()}}}});jQuery.when(onAnnotationSaved.promise()).then(function(){_this.eventEmitter.publish("annotationEditSaveSuccessful."+_this.windowId),_this.eventEmitter.publish("SET_ANNOTATION_EDITING."+_this.windowId,{annotationId:oaAnno["@id"],isEditable:!1,tooltip:_this}),_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId)},function(){})})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("annotationEditCancel."+_this.windowId,function(event,id){_this.eventEmitter.publish("SET_ANNOTATION_EDITING."+_this.windowId,{annotationId:id,isEditable:!1,tooltip:_this.annoTooltip}),_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId)})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("clearDraftPaths."+_this.windowId,function(){_this.clearDraftData()})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("onAnnotationCreated."+_this.windowId,function(event,oaAnno){for(var i=0;i<_this.draftPaths.length;i++)_this.draftPaths[i].data&&_this.draftPaths[i].data.newlyCreated&&(_this.draftPaths[i].strokeWidth/=_this.draftPaths[i].data.newlyCreatedStrokeFactor,_this.draftPaths[i].data.currentStrokeValue/=_this.draftPaths[i].data.newlyCreatedStrokeFactor,delete _this.draftPaths[i].data.newlyCreated,delete _this.draftPaths[i].data.newlyCreatedStrokeFactor);var writeStrategy=new $.MiradorDualStrategy;writeStrategy.buildAnnotation({annotation:oaAnno,window:_this.state.getWindowObjectById(_this.windowId),overlay:_this}),_this.eventEmitter.publish("annotationCreated."+_this.windowId,[oaAnno,function(){_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId),_this.eventEmitter.publish("enableTooltips."+_this.windowId),_this.clearDraftData(),_this.annoTooltip=null,_this.annoEditorVisible=!1}])})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("onAnnotationCreatedCanceled."+_this.windowId,function(event,cancelCallback,immediate){var cancel=function(){_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId),_this.clearDraftData(),_this.annoTooltip=null,_this.annoEditorVisible=!1};immediate?cancel():new $.DialogBuilder(_this.slotWindowElement).dialog({message:i18next.t("cancelAnnotation"),closeButton:!1,className:"mirador-dialog",buttons:{no:{label:i18next.t("no"),className:"btn-default",callback:function(){}},yes:{label:i18next.t("yes"),className:"btn-primary",callback:function(){cancel(),cancelCallback&&cancelCallback()}}}})})),this.eventsSubscriptions.push(_this.eventEmitter.subscribe("onAnnotationDeleted."+_this.windowId,function(event,id,callback){_this.inEditOrCreateMode=!1,_this.eventEmitter.publish("annotationDeleted."+_this.windowId,[id]),_this.eventEmitter.publish("SET_STATE_MACHINE_POINTER."+_this.windowId),callback&&callback()})),this.eventsSubscriptions.push(this.eventEmitter.subscribe("SET_OVERLAY_TOOLTIP."+this.windowId,function(event,options){_this.annoTooltip=options.tooltip,_this.annoEditorVisible=options.visible,_this.draftPaths=options.paths})),this.eventsSubscriptions.push(this.eventEmitter.subscribe("CANCEL_ACTIVE_ANNOTATIONS."+this.windowId,function(event){_this.clearDraftData(),_this.annoTooltip=null,_this.annoEditorVisible=!1})),this.eventsSubscriptions.push(this.eventEmitter.subscribe("ANNOTATIONS_LIST_UPDATED",function(event,options){options.windowId&&_this.eventEmitter.publish("refreshOverlay."+_this.windowId)}))},deleteShape:function(shape){for(var i=0;i<this.draftPaths.length;i++)if(this.draftPaths[i]._name.toString()===shape._name.toString()){this.draftPaths.splice(i,1);break}this.removeFocus(),shape.remove()},getMousePositionInImage:function(mousePosition){return mousePosition.x<0&&(mousePosition.x=0),mousePosition.x>this.viewer.tileSources.width&&(mousePosition.x=this.viewer.tileSources.width),mousePosition.y<0&&(mousePosition.y=0),mousePosition.y>this.viewer.tileSources.height&&(mousePosition.y=this.viewer.tileSources.height),mousePosition},adjustDeltaForShape:function(lastPoint,currentPoint,delta,bounds){return lastPoint.x<currentPoint.x?bounds.x+bounds.width>this.viewer.tileSources.width&&(delta.x=this.viewer.tileSources.width-(bounds.x+bounds.width)):bounds.x<0&&(delta.x=Math.abs(bounds.x)),lastPoint.y<currentPoint.y?bounds.y+bounds.height>this.viewer.tileSources.height&&(delta.y=this.viewer.tileSources.height-(bounds.y+bounds.height)):bounds.y<0&&(delta.y=Math.abs(bounds.y)),delta},onMouseUp:function(event){this.overlay.disabled||(event.stopPropagation(),this.overlay.currentTool&&this.overlay.currentTool.onMouseUp(event,this.overlay))},onMouseDrag:function(event){if(this.overlay.disabled){var absolutePoint={x:event.event.clientX,y:event.event.clientY};this.overlay.eventEmitter.publish("updateTooltips."+this.overlay.windowId,[event.point,absolutePoint])}else if(event.stopPropagation(),this.overlay.currentTool){if("Freehand"===this.overlay.currentTool.name&&"create"===this.overlay.mode)event.point=this.overlay.getMousePositionInImage(event.point),event.delta=event.point-event.lastPoint;else if(this.overlay.path){var bounds=this.overlay.path.bounds;event.delta=this.overlay.adjustDeltaForShape(event.lastPoint,event.point,event.delta,bounds)}this.overlay.currentTool.onMouseDrag(event,this.overlay)}this.overlay.paperScope.view.draw()},onMouseMove:function(event){if(this.overlay.disabled){var absolutePoint={x:event.event.clientX,y:event.event.clientY};this.overlay.eventEmitter.publish("updateTooltips."+this.overlay.windowId,[event.point,absolutePoint])}else this.overlay.paperScope.project.hitTest(event.point,this.overlay.hitOptions)?this.overlay.eventEmitter.publish("POINTER_CURSOR."+this.overlay.windowId):this.overlay.currentTool&&!this.overlay.path?this.overlay.eventEmitter.publish("CROSSHAIR_CURSOR."+this.overlay.windowId):this.overlay.eventEmitter.publish("DEFAULT_CURSOR."+this.overlay.windowId),event.stopPropagation(),this.overlay.currentTool&&this.overlay.currentTool.onMouseMove(event,this.overlay);this.overlay.paperScope.view.draw()},onMouseDown:function(event){if(!this.overlay.disabled){event.stopPropagation();var date=new Date,time=date.getTime();if(time-this.overlay.latestMouseDownTime<this.overlay.doubleClickReactionTime)this.overlay.latestMouseDownTime=time,this.onDoubleClick(event);else{this.overlay.latestMouseDownTime=time;var hitResult=this.overlay.paperScope.project.hitTest(event.point,this.overlay.hitOptions);if("create"!==this.overlay.mode&&""!==this.overlay.mode&&(this.overlay.mode="",this.overlay.currentTool=null),hitResult&&"create"!==this.overlay.mode){var overlayEditable=!1;if("undefined"!=typeof hitResult.item.data.editable&&(overlayEditable=hitResult.item.data.editable),hitResult.item._name.toString().indexOf(this.overlay.partOfPrefix)!==-1&&(overlayEditable=!0),!overlayEditable)return}if(hitResult&&(!this.overlay.currentTool||hitResult.item._name.toString().indexOf(this.overlay.currentTool.idPrefix)===-1&&""===this.overlay.mode)){var prefix=hitResult.item._name.toString();prefix=prefix.substring(0,prefix.indexOf("_")+1);var longPrefix=hitResult.item._name.toString().split("_");longPrefix=longPrefix[0]+"_"+longPrefix[1]+"_";for(var j=0;j<this.overlay.tools.length;j++)if(this.overlay.tools[j].idPrefix===prefix||this.overlay.tools[j].idPrefix===longPrefix){this.overlay.eventEmitter.publish("toggleDrawingTool."+this.overlay.windowId,this.overlay.tools[j].logoClass);break}}this.overlay.currentTool&&(this.overlay.eventEmitter.publish("HUD_REMOVE_CLASS."+this.overlay.windowId,[".hud-dropdown","hud-disabled"]),event.point=this.overlay.getMousePositionInImage(event.point),this.overlay.currentTool.onMouseDown(event,this.overlay))}this.overlay.hover(),this.overlay.paperScope.view.draw()}},onDoubleClick:function(event){event.stopPropagation(),this.overlay.currentTool&&this.overlay.currentTool.onDoubleClick(event,this.overlay)},fitFixedSizeShapes:function(shape){if(shape.data.fixedSize=!0,shape.name.toString().indexOf("pin_")!=-1){var scale=1/shape.bounds.width;scale*=this.fixedShapeSize/this.paperScope.view.zoom,shape.scale(scale,shape.segments[0].point)}},updateSelection:function(selected,item){if(item&&item._name){var shapeTool=this.getTool(item);shapeTool&&(item.selectedColor=this.selectedColor,shapeTool.updateSelection(selected,item,this))}},rotate:function(event){this.paperScope&&this.paperScope.view&&(this.paperScope.view._matrix.rotate(event.degrees-this.lastAngle,this.paperScope.view.center),this.lastAngle=event.degrees)},resize:function(){var viewportBounds=this.viewer.viewport.getBounds(!0);this.canvas.width=this.viewer.viewport.containerSize.x,this.canvas.height=this.viewer.viewport.containerSize.y;var transform="translate(0px,0px)";if(this.canvas.style.WebkitTransform=transform,this.canvas.style.msTransform=transform,this.canvas.style.transform=transform,this.canvas.style.marginLeft="0px",this.canvas.style.marginTop="0px",this.paperScope&&this.paperScope.view){this.paperScope.view.viewSize=new this.paperScope.Size(this.canvas.width,this.canvas.height),this.paperScope.view.zoom=this.viewer.viewport.viewportToImageZoom(this.viewer.viewport.getZoom(!0)),this.paperScope.view.center=new this.paperScope.Size(this.viewer.world.getItemAt(0).source.dimensions.x*viewportBounds.x+this.paperScope.view.bounds.width/2,this.viewer.world.getItemAt(0).source.dimensions.x*viewportBounds.y+this.paperScope.view.bounds.height/2),this.paperScope.view.update(!0);for(var allItems=this.paperScope.project.getItems({name:/_/}),j=0;j<allItems.length;j++)allItems[j].data.fixedSize&&this.fitFixedSizeShapes(allItems[j]),this.getTool(allItems[j]).onResize&&this.getTool(allItems[j]).onResize(allItems[j],this),allItems[j].strokeWidth=allItems[j].data.currentStrokeValue/this.paperScope.view.zoom,allItems[j].style&&(allItems[j].style.strokeWidth=allItems[j].data.currentStrokeValue/this.paperScope.view.zoom)}},hover:function(){if(this.currentTool)if(!this.currentTool&&this.hoveredPath&&(this.updateSelection(!1,this.hoveredPath),this.hoveredPath=null),this.hoveredPath){if(this.hoveredPath._name.toString().indexOf(this.currentTool.idPrefix)===-1&&(this.updateSelection(!1,this.hoveredPath),this.hoveredPath=null),this.path&&this.path._name.toString().indexOf(this.currentTool.idPrefix)!==-1){if(this.currentTool.partOfPrefix&&this.path._name.toString().indexOf(this.currentTool.partOfPrefix)!==-1)return;if(this.hoveredPath){if(this.hoveredPath._name.toString()===this.path._name.toString())return;this.updateSelection(!1,this.hoveredPath)}this.hoveredPath=this.path,this.updateSelection(!0,this.hoveredPath)}}else this.path&&this.path._name.toString().indexOf(this.currentTool.idPrefix)!=-1&&(this.hoveredPath=this.path,this.updateSelection(!0,this.hoveredPath))},removeFocus:function(){this.hoveredPath&&(this.updateSelection(!1,this.hoveredPath),this.hoveredPath=null),this.path&&(this.updateSelection(!1,this.path),this.path=null)},restoreEditedShapes:function(){this.editedPaths=[],this.removeFocus()},restoreDraftShapes:function(){this.clearDraftData(),this.removeFocus()},getTool:function(shape){for(var i=0;i<this.tools.length;i++)if(shape.name.toString().indexOf(this.tools[i].idPrefix)!==-1)return this.tools[i]},replaceShape:function(shape,annotation){var shapeTool=this.getTool(shape);shapeTool&&shapeTool.SEGMENT_POINTS_COUNT&&shapeTool.SEGMENT_POINTS_COUNT!==shape.segments.length&&shapeTool.adaptSegments(shape,this);var cloned=new this.paperScope.Path({segments:shape.segments,name:shape.name});return cloned.data.defaultStrokeValue=1,cloned.data.editStrokeValue=5,cloned.data.currentStrokeValue=cloned.data.defaultStrokeValue,cloned.strokeWidth=cloned.data.currentStrokeValue/this.paperScope.view.zoom,cloned.strokeColor=shape.strokeColor,cloned.dashArray=shape.dashArray,shape.fillColor&&(cloned.fillColor=shape.fillColor,0===shape.fillColor.alpha&&(shape.fillColor.alpha=FILL_COLOR_ALPHA_WORKAROUND),shape.fillColor.alpha&&(cloned.fillColor.alpha=shape.fillColor.alpha)),cloned.closed=shape.closed,cloned.data.rotation=shape.data.rotation,cloned.data.fixedSize=shape.data.fixedSize,cloned.data.annotation=annotation,cloned.data.fixedSize&&this.fitFixedSizeShapes(cloned),shape.remove(),cloned},createRectangle:function(shape,annotation){var paperItems=[],rect=new $.Rectangle,initialPoint={x:shape.x,y:shape.y},currentMode=this.mode,currentPath=this.path,strokeColor=this.strokeColor,fillColor=this.fillColor,fillColorAlpha=this.fillColorAlpha||FILL_COLOR_ALPHA_WORKAROUND;this.strokeColor=this.state.getStateProperty("drawingToolsSettings").strokeColor,
83
+ this.fillColor=this.state.getStateProperty("drawingToolsSettings").fillColor,this.fillColorAlpha=this.state.getStateProperty("drawingToolsSettings").fillColorAlpha||FILL_COLOR_ALPHA_WORKAROUND,this.mode="create",this.path=rect.createShape(initialPoint,this);var eventData={delta:{x:shape.width,y:shape.height}};return rect.onMouseDrag(eventData,this),paperItems.push(this.path),paperItems[0].data.annotation=annotation,this.updateSelection(!1,paperItems[0]),this.strokeColor=strokeColor,this.fillColor=fillColor,this.fillColorAlpha=fillColorAlpha,this.path=currentPath,this.mode=currentMode,paperItems},parseSVG:function(svg,annotation){var paperItems=[],svgParser=new DOMParser,svgDOM=svgParser.parseFromString(svg,"text/xml");if("parsererror"!=svgDOM.documentElement.nodeName){var svgTag=this.paperScope.project.importSVG(svg),body=svgTag.removeChildren()[0];if(svgTag.remove(),"Group"==body.className){for(var items=body.removeChildren(),itemIdx=0;itemIdx<items.length;itemIdx++)paperItems.push(this.replaceShape(items[itemIdx],annotation));body.remove()}else paperItems.push(this.replaceShape(body,annotation));return this.paperScope.view.update(!0),paperItems}},restoreLastView:function(shapeArray){for(var i=0;i<this.editedPaths.length;i++)for(var idx=0;idx<shapeArray.length;idx++)shapeArray[idx].name==this.editedPaths[i].name&&(shapeArray[idx].segments=this.editedPaths[i].segments,shapeArray[idx].name=this.editedPaths[i].name,shapeArray[idx].strokeWidth=shapeArray[idx].data.currentStrokeValue/this.paperScope.view.zoom,shapeArray[idx].strokeColor=this.editedPaths[i].strokeColor,shapeArray[idx].dashArray=this.editedPaths[i].dashArray,this.editedPaths[i].fillColor&&(shapeArray[idx].fillColor=this.editedPaths[i].fillColor,this.editedPaths[i].fillColor.alpha&&(shapeArray[idx].fillColor.alpha=this.editedPaths[i].fillColor.alpha)),this.editedPaths[i].style&&(shapeArray[idx].style=this.editedPaths[i].style,shapeArray[idx].style.strokeWidth=shapeArray[idx].data.currentStrokeValue/this.paperScope.view.zoom),shapeArray[idx].closed=this.editedPaths[i].closed,shapeArray[idx].data.rotation=this.editedPaths[i].data.rotation,shapeArray[idx].data.fixedSize=this.editedPaths[i].data.fixedSize,shapeArray[idx].data.annotation=this.editedPaths[i].data.annotation,shapeArray[idx].data.fixedSize&&this.fitFixedSizeShapes(shapeArray[idx]))},deselectAll:function(){this.paperScope&&this.paperScope.view&&this.paperScope.project&&(this.paperScope.project.deselectAll(),this.paperScope.view.update(!0),this.destroyCommentPanel())},hide:function(){this.canvas.style.display="none",this.deselectAll()},show:function(){this.canvas.style.display="block"},checkToRemoveFocus:function(){this.currentTool="",this.inEditOrCreateMode&&this.path&&this.removeFocus()},disable:function(){this.disabled=!0,this.inEditOrCreateMode=!1,this.eventEmitter.publish("enableTooltips."+this.windowId),this.deselectAll()},enableEdit:function(){this.disabled=!1,this.inEditOrCreateMode=!0,this.eventEmitter.publish("disableTooltips."+this.windowId)},enable:function(){this.disabled=!1,this.eventEmitter.publish("disableTooltips."+this.windowId)},refresh:function(){this.paperScope.view.update(!0)},destroyCommentPanel:function(){this.eventEmitter.publish("removeTooltips."+this.windowId),jQuery(this.canvas).parents(".mirador-osd").qtip("destroy",!0),this.commentPanel=null},getName:function(tool){return tool.idPrefix+$.genUUID()},getSVGString:function(shapes){var svg="<svg xmlns='http://www.w3.org/2000/svg'>";if(shapes.length>1){svg+="<g>";for(var i=0;i<shapes.length;i++){this.updateSelection(!1,shapes[i]),shapes[i].data.fixedSize&&this.fitFixedSizeShapes(shapes[i]);var anno=shapes[i].data.annotation;shapes[i].data.annotation=null,svg+=shapes[i].exportSVG({asString:!0}),shapes[i].data.annotation=anno}svg+="</g>"}else{this.updateSelection(!1,shapes[0]),shapes[0].data.fixedSize&&this.fitFixedSizeShapes(shapes[0]);var annoSingle=shapes[0].data.annotation;shapes[0].data.annotation=null,svg+=shapes[0].exportSVG({asString:!0}),shapes[0].data.annotation=annoSingle}return svg+="</svg>"},onDrawFinish:function(){var shape=this.path;if(shape){this.inEditOrCreateMode=!0,this.hoveredPath&&this.updateSelection(!1,this.hoveredPath);var newlyCreatedStrokeFactor=this.drawingToolsSettings.newlyCreatedShapeStrokeWidthFactor||5;if(shape.data.newlyCreatedStrokeFactor=newlyCreatedStrokeFactor,shape.data.newlyCreated=!0,shape.data.currentStrokeValue*=newlyCreatedStrokeFactor,shape.strokeWidth*=newlyCreatedStrokeFactor,this.hoveredPath=shape,this.segment=null,this.path=null,this.mode="",this.draftPaths.push(shape),shape.data.editable=!0,this.updateSelection(!0,this.hoveredPath),"undefined"!=typeof this.annoTooltip&&this.annoTooltip||(this.annoTooltip=new $.AnnotationTooltip({targetElement:jQuery(this.canvas).parents(".mirador-osd"),state:this.state,eventEmitter:this.eventEmitter,windowId:this.windowId})),this.availableExternalCommentsPanel)return void this.eventEmitter.publish("annotationShapeCreated."+this.windowId,[this,shape]);var _this=this;"undefined"!=typeof this.annoEditorVisible&&this.annoEditorVisible||(this.annoTooltip.showEditor({annotation:{},onSaveClickCheck:function(){return _this.draftPaths.length},onAnnotationCreated:function(oaAnno){_this.eventEmitter.publish("onAnnotationCreated."+_this.windowId,[oaAnno])}}),_this.annoEditorVisible=!0)}},onEditFinish:function(){var _this=this;jQuery.each(this.draftPaths,function(index,value){_this.path.name===value.name&&(_this.draftPaths[index]=_this.path)})},clearDraftData:function(){for(var _this=this,idx=0;idx<_this.draftPaths.length;idx++)_this.updateSelection(!1,this.draftPaths[idx]),_this.draftPaths[idx].remove();_this.draftPaths=[],_this.path&&_this.path.remove(),_this.paperScope.view.update(!0),_this.hoveredPath=null,_this.segment=null,_this.path=null,_this.mode=""},destroy:function(){var _this=this;this.eventsSubscriptions.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)}),this.viewer.removeHandler("animation",this._thisResize),this.viewer.removeHandler("open",this._thisResize),this.viewer.removeHandler("animation-finish",this._thisResize),this.viewer.removeHandler("update-viewport",this._thisResize),this.viewer.removeHandler("resize",this._thisResize),this.viewer.removeHandler("rotate",this._thisResize),this.viewer.removeHandler("constrain",this._thisResize),this.viewer.removeHandler("close",this._thisDestroy)}}}(Mirador),function($){$.Pin=function(options){jQuery.extend(this,{name:"Pin",logoClass:"room",idPrefix:"pin_",tooltip:"pinTooltip"},options),this.init()},$.Pin.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var _this=this,size=overlay.fixedShapeSize,pathData="";pathData+="M"+initialPoint.x+","+initialPoint.y,pathData+=" Q"+initialPoint.x+","+(initialPoint.y-size),pathData+=" "+(initialPoint.x+size)+","+(initialPoint.y-2*size),pathData+=" A"+size+","+size+" 0 1 0",pathData+=" "+(initialPoint.x-size)+","+(initialPoint.y-2*size),pathData+=" Q"+initialPoint.x+","+(initialPoint.y-size),pathData+=" "+initialPoint.x+","+initialPoint.y;var shape=new overlay.paperScope.Path(pathData);return shape.name=overlay.getName(_this),shape.dashArray=overlay.dashArray,shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape.strokeColor=overlay.strokeColor,shape.fillColor=overlay.fillColor,shape.fillColor.alpha=overlay.fillColorAlpha,shape.closed=!0,overlay.fitFixedSizeShapes(shape),shape},updateSelection:function(selected,item,overlay){item._name.toString().indexOf(this.idPrefix)!==-1&&(selected?(item.strokeColor=overlay.selectedColor,item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",item.segments[0].point),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.deleteIcon.setOnMouseDownListener(overlay))):(item.strokeColor=overlay.strokeColor,item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null)))},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&item._name.toString().indexOf("delete")&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.self.resize(24/overlay.paperScope.view.zoom))},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){},onMouseDrag:function(event,overlay){"translate"===overlay.mode&&overlay.path&&(overlay.path.position.x+=event.delta.x,overlay.path.position.y+=event.delta.y,overlay.path.data.deleteIcon&&overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y))},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type||"handle-in"===hitResult.type||"handle-out"===hitResult.type||"segment"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void 0},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return void hitResult.item.data.self.onMouseDown();"translate"!==overlay.mode&&(overlay.mode="translate",overlay.segment=null,overlay.path=null)}return"translate"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):overlay.path=hitResult.item):(overlay.path=this.createShape(event.point,overlay),void overlay.onDrawFinish())},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.Polygon=function(options){jQuery.extend(this,{name:"Polygon",logoClass:"timeline",idPrefix:"rough_path_",tooltip:"polygonTooltip"},options),this.init()},$.Polygon.prototype={init:function(){},createShape:function(initialPoint,overlay){overlay.mode="create";var _this=this,shape=new overlay.paperScope.Path({segments:[initialPoint],dashArray:overlay.dashArray,strokeColor:overlay.strokeColor,name:overlay.getName(_this)});return shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape},updateSelection:function(selected,item,overlay){item._name.toString().indexOf(this.idPrefix)!=-1&&(item.selected=selected,selected?item.data.deleteIcon||"create"===overlay.mode||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(item))),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.deleteIcon.setOnMouseDownListener(overlay)):item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null))},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom))),item.data.self.resize(24/overlay.paperScope.view.zoom))},getPivotPointForDeleteIcon:function(item){for(var points=[],i=0;i<item.segments.length;i++)points.push(item.segments[i].point);return{x:this.getGeometricCenterOfPoints(points).x,y:this.getLowestPoint(points).y}},getLowestPoint:function(points){for(var lx=0,ly=0,i=0;i<points.length;i++)lx=Math.max(lx,points[i].x),ly=Math.max(ly,points[i].y);return{x:lx,y:ly}},getGeometricCenterOfPoints:function(points){for(var cx=0,cy=0,i=0;i<points.length;i++)cx+=points[i].x,cy+=points[i].y;return{x:cx/points.length,y:cy/points.length}},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},onMouseUp:function(event,overlay){},onMouseDrag:function(event,overlay){if("deform"===overlay.mode&&overlay.segment){overlay.segment.point.x+=event.delta.x,overlay.segment.point.y+=event.delta.y;var path=overlay.segment.path;return void(path.data.deleteIcon&&(path.data.deleteIcon.addData("pivot",new overlay.paperScope.Point(this.getPivotPointForDeleteIcon(path))),path.data.deleteIcon.setPosition(path.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom)))))}"translate"===overlay.mode&&overlay.path&&(overlay.path.position.x+=event.delta.x,overlay.path.position.y+=event.delta.y,overlay.path.data.deleteIcon&&overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y))},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"handle-in"===hitResult.type||"handle-out"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return void hitResult.item.data.self.onMouseDown();if("create"!==overlay.mode){if(overlay.path?document.body.style.cursor="default":(overlay.mode="edit",overlay.segment=null,overlay.path=null,document.body.style.cursor="move"),"stroke"===hitResult.type)return overlay.mode="translate",void(overlay.path=hitResult.item);if("segment"===hitResult.type)return event.modifiers.shift&&hitResult.item.segments.length>2?void hitResult.segment.remove():(overlay.mode="deform",overlay.segment=hitResult.segment,void(overlay.path=hitResult.item))}}else"create"!==overlay.mode&&(overlay.mode="");return""===overlay.mode?void(overlay.path=this.createShape(event.point,overlay)):"create"===overlay.mode?void overlay.path.add(event.point):void 0},onDoubleClick:function(event,overlay){"create"===overlay.mode&&overlay.path&&overlay.path.segments.length>1&&(overlay.path.segments[0].point.getDistance(overlay.path.segments[overlay.path.segments.length-1].point)*overlay.paperScope.view.zoom<overlay.hitOptions.tolerance&&(overlay.path.closed=!0,overlay.path.fillColor=overlay.fillColor,overlay.path.fillColor.alpha=overlay.fillColorAlpha,overlay.path.segments[overlay.path.segments.length-1].remove()),overlay.onDrawFinish())}}}(Mirador),function($){$.Rectangle=function(options){jQuery.extend(this,{name:"Rectangle",logoClass:"check_box_outline_blank",idPrefix:"rectangle_",tooltip:"rectangleTooltip"},options),this.init()},$.Rectangle.prototype={init:function(){this.SEGMENT_POINTS_COUNT=9},createShape:function(initialPoint,overlay){overlay.mode="create";var pixel=1/overlay.paperScope.view.zoom,segments=this._createSegments(initialPoint,pixel,overlay),shape=new overlay.paperScope.Path({segments:segments,fullySelected:!0,name:overlay.getName(this)});return shape.dashArray=overlay.dashArray,shape.data.defaultStrokeValue=1,shape.data.editStrokeValue=5,shape.data.currentStrokeValue=shape.data.defaultStrokeValue,shape.strokeWidth=shape.data.currentStrokeValue/overlay.paperScope.view.zoom,shape.strokeColor=overlay.strokeColor,shape.fillColor=overlay.fillColor,shape.fillColor.alpha=overlay.fillColorAlpha,shape.closed=!0,shape.data.rotation=0,overlay.segment=shape.segments[5],this.updateSelection(!0,shape,overlay),shape},_createSegments:function(initialPoint,pixel,overlay){var segments=[];return segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y-2*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y-1*pixel)),segments.push(new overlay.paperScope.Point(initialPoint.x,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-1*pixel,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y)),segments.push(new overlay.paperScope.Point(initialPoint.x-2*pixel,initialPoint.y-1*pixel)),segments},updateSelection:function(selected,item,overlay){if(item._name.toString().indexOf(this.idPrefix)!=-1){if(item._name.toString().indexOf(this.partOfPrefix)!=-1)return;if(item.selected=selected,selected){item.data.deleteIcon||(item.data.deleteIcon=new overlay.annotationUtils.DeleteActionIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"delete",fillColor:item.selectedColor}),item.data.deleteIcon.addData("pivot",item.segments[6].point),item.data.deleteIcon.addData("type","deleteIcon"),item.data.deleteIcon.addData("self",item.data.deleteIcon),item.data.deleteIcon.addData("parent",item),item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.setOnMouseDownListener(overlay)),item.data.rotationIcon||(item.data.rotationIcon=new overlay.annotationUtils.RotationIcon(overlay.paperScope,{name:item.name+this.partOfPrefix+"rotation",fillColor:item.selectedColor}),item.data.rotationIcon.addData("pivot",item.segments[1].point),item.data.rotationIcon.addData("type","rotationIcon"),item.data.rotationIcon.addData("self",item.data.rotationIcon),item.data.rotationIcon.addData("parent",item),item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.setOnMouseDownListener(overlay)),item.data.group||(item.data.group=new overlay.annotationUtils.Group(overlay.paperScope,[item,item.data.deleteIcon.getItem(),item.data.deleteIcon.getMask().getItem(),item.data.rotationIcon.getItem(),item.data.rotationIcon.getMask().getItem()]));var point=item.segments[1].point.clone();point=point.add(item.segments[1].handleOut),item.contains(point)&&(item.segments[1].handleOut=item.segments[1].handleOut.rotate(180,item.segments[1])),item.contains(item.data.deleteIcon.getItem().position)&&(item.data.deleteIcon.setPosition(item.data.deleteIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.deleteIcon.rotate(180,item.data.deleteIcon.getData("pivot")),item.data.deleteIcon.rotate(180)),item.contains(item.data.rotationIcon.getItem().position)&&(item.data.rotationIcon.setPosition(item.data.rotationIcon.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.rotation))),item.data.rotationIcon.rotate(180,item.data.rotationIcon.getData("pivot")),item.data.rotationIcon.rotate(180)),item.segments[1].handleOut.selected=!1}else item.data.group&&(item.data.group.remove(),item.data.group=null,overlay.paperScope.project.activeLayer.addChild(item)),item.data.deleteIcon&&(item.data.deleteIcon.remove(),item.data.deleteIcon=null),item.data.rotationIcon&&(item.data.rotationIcon.remove(),item.data.rotationIcon=null),item.segments[1].handleOut=new overlay.paperScope.Point(0,0)}},onHover:function(activate,shape,hoverColor){activate&&!shape.data.hovered&&(shape.data.nonHoverStroke=shape.strokeColor.clone(),shape.data.hovered=!0,shape.strokeColor=hoverColor),!activate&&shape.data.hovered&&(shape.strokeColor=shape.data.nonHoverStroke.clone(),delete shape.data.nonHoverStroke,delete shape.data.hovered)},adaptSegments:function(shape,overlay){var handleSegment=shape.segments[1].clone();shape.segments.splice(1,0,handleSegment)},onMouseUp:function(event,overlay){"create"===overlay.mode&&overlay.path?overlay.onDrawFinish():("translate"===overlay.mode||"deform"===overlay.mode&&overlay.path)&&overlay.onEditFinish()},translate:function(event,overlay){for(var i=0;i<overlay.path.segments.length;i++)overlay.path.segments[i].point.x+=event.delta.x,overlay.path.segments[i].point.y+=event.delta.y;overlay.path.data.rotationIcon.translateByXY(event.delta.x,event.delta.y),overlay.path.data.deleteIcon.translateByXY(event.delta.x,event.delta.y)},rotate:function(event,overlay){var center=overlay.path.position,rotation=Math.atan2(event.point.y-center.y+event.delta.y,event.point.x-center.x+event.delta.x)-Math.atan2(event.point.y-center.y,event.point.x-center.x);rotation*=180/Math.PI,overlay.path.data.group.rotate(rotation,overlay.path.position),overlay.path.data.deleteIcon.rotate(-rotation),overlay.path.data.rotationIcon.rotate(-rotation),overlay.path.data.rotation+=rotation},onMouseDrag:function(event,overlay){if("translate"==overlay.mode)return void this.translate(event,overlay);if("rotate"===overlay.mode)return void this.rotate(event,overlay);if("create"==overlay.mode||"deform"==overlay.mode){for(var idx=-1,l=0;l<overlay.path.segments.length;l++)if(overlay.path.segments[l]==overlay.segment){idx=l;break}var translation=new overlay.paperScope.Point(event.delta.x,event.delta.y),rot=overlay.path.data.rotation;translation=translation.rotate(-rot);var translationX=new overlay.paperScope.Point(translation.x,0);translationX=translationX.rotate(rot);var translationY=new overlay.paperScope.Point(0,translation.y);translationY=translationY.rotate(rot);var moveTopSize=0===idx||1===idx||2===idx||3===idx,moveBottomSize=5===idx||6===idx||7===idx,moveRightSize=3===idx||4===idx||5===idx,moveLeftSize=0===idx||7===idx||8===idx;moveTopSize&&(overlay.path.data.rotationIcon.translateByPoint(translationY),overlay.path.segments[0].point=overlay.path.segments[0].point.add(translationY),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationY),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationY),overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationY)),moveBottomSize&&(overlay.path.data.deleteIcon.translateByPoint(translationY),overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationY),overlay.path.segments[6].point=overlay.path.segments[6].point.add(translationY),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationY)),(moveTopSize||moveBottomSize)&&(translationY=translationY.multiply(.5),overlay.path.segments[4].point=overlay.path.segments[4].point.add(translationY),overlay.path.segments[8].point=overlay.path.segments[8].point.add(translationY)),moveRightSize&&(overlay.path.segments[3].point=overlay.path.segments[3].point.add(translationX),overlay.path.segments[4].point=overlay.path.segments[4].point.add(translationX),overlay.path.segments[5].point=overlay.path.segments[5].point.add(translationX)),moveLeftSize&&(overlay.path.segments[0].point=overlay.path.segments[0].point.add(translationX),overlay.path.segments[7].point=overlay.path.segments[7].point.add(translationX),overlay.path.segments[8].point=overlay.path.segments[8].point.add(translationX)),(moveRightSize||moveLeftSize)&&(translationX=translationX.multiply(.5),overlay.path.data.rotationIcon.translateByPoint(translationX),overlay.path.data.deleteIcon.translateByPoint(translationX),overlay.path.segments[1].point=overlay.path.segments[1].point.add(translationX),overlay.path.segments[2].point=overlay.path.segments[2].point.add(translationX),overlay.path.segments[6].point=overlay.path.segments[6].point.add(translationX));var point=overlay.path.segments[1].point.clone();point=point.add(overlay.path.segments[1].handleOut),overlay.path.contains(point)&&(overlay.path.segments[1].handleOut=overlay.path.segments[1].handleOut.rotate(180,overlay.path.segments[1])),overlay.path.contains(overlay.path.data.deleteIcon.getItem().position)&&(overlay.path.data.deleteIcon.rotate(180,overlay.path.data.deleteIcon.getData("pivot")),overlay.path.data.deleteIcon.rotate(180)),overlay.path.contains(overlay.path.data.rotationIcon.getItem().position)&&(overlay.path.data.rotationIcon.rotate(180,overlay.path.data.rotationIcon.getData("pivot")),overlay.path.data.rotationIcon.rotate(180))}},onResize:function(item,overlay){item._name.toString().indexOf(this.partOfPrefix)!==-1&&(item._name.toString().indexOf("delete")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(24/overlay.paperScope.view.zoom)),item._name.toString().indexOf("rotation")!==-1&&(item.data.self.setPosition(item.data.self.getData("pivot").add(new overlay.paperScope.Point(0,21/overlay.paperScope.view.zoom).rotate(item.data.parent.data.rotation))),item.data.parent.contains(item.position)&&(item.data.self.rotate(180,item.data.self.getData("pivot")),item.data.self.rotate(180)),item.data.self.resize(16/overlay.paperScope.view.zoom)))},onMouseMove:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!==-1&&!overlay.disabled&&overlay.hoveredPath&&hitResult.item._name.toString().indexOf(overlay.hoveredPath._name.toString())!==-1&&this.setCursor(hitResult,overlay)},setCursor:function(hitResult,overlay){return"stroke"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","move"):"pixel"===hitResult.type?void jQuery(overlay.viewer.canvas).css("cursor","pointer"):void(hitResult.segment&&jQuery(overlay.viewer.canvas).css("cursor","pointer"))},onMouseDown:function(event,overlay){var hitResult=overlay.paperScope.project.hitTest(event.point,overlay.hitOptions);if(hitResult&&hitResult.item._name.toString().indexOf(this.idPrefix)!=-1&&"deform"!==overlay.mode&&"translate"!==overlay.mode&&"create"!==overlay.mode){if(hitResult.item._name.toString().indexOf(this.partOfPrefix)!==-1)return hitResult.item.data.self.onMouseDown(),void("rotate"===overlay.mode&&(overlay.path=hitResult.item.data.self.getItem().data.parent));"segment"===hitResult.type&&(overlay.mode="deform",overlay.segment=null,overlay.path=null,this.setCursor(hitResult,overlay)),"stroke"===hitResult.type&&(overlay.mode="translate",overlay.segment=null,overlay.path=null)}return"translate"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):overlay.path=hitResult.item):"deform"===overlay.mode?void(overlay.path?(overlay.segment=null,overlay.path=null,overlay.mode=""):(overlay.path=hitResult.item,overlay.segment=hitResult.segment)):void(overlay.path=this.createShape(event.point,overlay))},onDoubleClick:function(event,overlay){}}}(Mirador),function($){$.SimpleASEndpoint=function(options){jQuery.extend(this,{token:null,uri:null,url:options.url,dfd:null,annotationsList:[],idMapper:{}},options),this.init()},$.SimpleASEndpoint.prototype={init:function(){this.catchOptions={user:{id:this.userid,name:this.username},permissions:{read:[],update:[this.userid],delete:[this.userid],admin:[this.userid]}}},search:function(options,successCallback,errorCallback){var _this=this;this.annotationsList=[],jQuery.ajax({url:_this.url+"/search",cache:!1,type:"GET",dataType:"json",headers:{},data:{uri:options.uri,APIKey:_this.APIKey,media:"image",limit:1e4},contentType:"application/json; charset=utf-8",success:function(data){"function"==typeof successCallback?successCallback(data):(_this.annotationsList=data,jQuery.each(_this.annotationsList,function(index,value){value.fullId=value["@id"],value["@id"]=$.genUUID(),_this.idMapper[value["@id"]]=value.fullId,value.endpoint=_this}),_this.dfd.resolve(!1))},error:function(){"function"==typeof errorCallback?errorCallback():console.log("The request for annotations has caused an error for endpoint: "+options.uri)}})},deleteAnnotation:function(annotationID,returnSuccess,returnError){var _this=this;jQuery.ajax({url:_this.url+"/destroy?uri="+encodeURIComponent(_this.idMapper[annotationID])+"&APIKey="+_this.APIKey,type:"DELETE",dataType:"json",headers:{},data:{uri:annotationID},contentType:"application/json; charset=utf-8",success:function(data){returnSuccess()},error:function(){returnError()}})},update:function(oaAnnotation,returnSuccess,returnError){var annotation=oaAnnotation,_this=this;shortId=annotation["@id"],annotation["@id"]=annotation.fullId,annotationID=annotation.fullId,delete annotation.fullId,delete annotation.endpoint,jQuery.ajax({url:_this.url+"/update/"+encodeURIComponent(annotationID)+"?APIKey="+_this.APIKey,type:"POST",dataType:"json",headers:{},data:JSON.stringify(annotation),contentType:"application/json; charset=utf-8",success:function(data){returnSuccess()},error:function(){returnError()}}),annotation.endpoint=_this,annotation.fullId=annotation["@id"],annotation["@id"]=shortId},create:function(oaAnnotation,returnSuccess,returnError){var annotation=oaAnnotation,_this=this;jQuery.ajax({url:_this.url+"/create?APIKey="+_this.APIKey,type:"POST",dataType:"json",headers:{},data:JSON.stringify(annotation),contentType:"application/json; charset=utf-8",success:function(data){data.fullId=data["@id"],data["@id"]=$.genUUID(),data.endpoint=_this,_this.idMapper[data["@id"]]=data.fullId,returnSuccess(data)},error:function(){returnError()}})},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},userAuthorize:function(action,annotation){return!0}}}(Mirador),function($){$.TinyMCEAnnotationBodyEditor=function(options){jQuery.extend(this,{annotation:null,windowId:null,config:{plugins:"",toolbar:""}},options),this.init()},$.TinyMCEAnnotationBodyEditor.prototype={init:function(){var _this=this,annoText="",tags=[];jQuery.isEmptyObject(_this.annotation)||(jQuery.isArray(_this.annotation.resource)?jQuery.each(_this.annotation.resource,function(index,value){"oa:Tag"===value["@type"]?tags.push(value.chars):annoText=value.chars}):annoText=_this.annotation.resource.chars),this.editorMarkup=this.editorTemplate({content:annoText,tags:tags.join(" "),windowId:_this.windowId})},show:function(selector){this.editorContainer=jQuery(selector).prepend(this.editorMarkup),
84
+ tinymce.init({selector:selector+" textarea",plugins:this.config.plugins,menubar:!1,statusbar:!1,toolbar_items_size:"small",toolbar:this.config.toolbar,default_link_target:"_blank",setup:function(editor){editor.on("init",function(args){tinymce.execCommand("mceFocus",!1,args.target.id)})}})},isDirty:function(){return tinymce.activeEditor.isDirty()},createAnnotation:function(){var tagText=this.editorContainer.find(".tags-editor").val(),resourceText=tinymce.activeEditor.getContent(),tags=[];tagText=$.trimString(tagText),tagText&&(tags=tagText.split(/\s+/));var motivation=[],resource=[];return tags&&tags.length>0&&(motivation.push("oa:tagging"),jQuery.each(tags,function(index,value){resource.push({"@type":"oa:Tag",chars:value})})),motivation.push("oa:commenting"),resource.push({"@type":"dctypes:Text",format:"text/html",chars:resourceText}),{"@context":"http://iiif.io/api/presentation/2/context.json","@type":"oa:Annotation",motivation:motivation,resource:resource}},updateAnnotation:function(oaAnno){var tagText=this.editorContainer.find(".tags-editor").val(),resourceText=tinymce.activeEditor.getContent(),tags=[];tagText=$.trimString(tagText),tagText&&(tags=tagText.split(/\s+/));oaAnno.motivation=jQuery.grep(oaAnno.motivation,function(value){return"oa:tagging"!==value}),oaAnno.resource=jQuery.grep(oaAnno.resource,function(value){return"oa:Tag"!==value["@type"]}),tags.length>0&&(oaAnno.motivation.push("oa:tagging"),jQuery.each(tags,function(index,value){oaAnno.resource.push({"@type":"oa:Tag",chars:value})})),jQuery.each(oaAnno.resource,function(index,value){"dctypes:Text"===value["@type"]&&(value.chars=resourceText)})},editorTemplate:$.Handlebars.compile(['<textarea class="text-editor" placeholder="{{t "comments"}}…">{{#if content}}{{content}}{{/if}}</textarea>','<input id="tags-editor-{{windowId}}" class="tags-editor" placeholder="{{t "addTagsHere"}}…" {{#if tags}}value="{{tags}}"{{/if}}>'].join(""))}}(Mirador),function($){$.Slot=function(options){jQuery.extend(!0,this,{workspaceSlotCls:"slot",slotID:null,layoutAddress:null,focused:null,appendTo:null,window:null,windowElement:null,state:null,eventEmitter:null},options),this.init()},$.Slot.prototype={init:function(){this.events=[],this.element=jQuery(this.template({workspaceSlotCls:this.workspaceSlotCls,slotID:this.slotId})),this.element.appendTo(this.appendTo),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;this.events=[_this.eventEmitter.subscribe("slotRemoved",function(event,slot){_this.slotID===slot.slotID&&_this.clearSlot()}),_this.eventEmitter.subscribe("layoutChanged",function(event,layoutRoot){_this.window&&(_this.window.slotAddress=_this.layoutAddress,_this.eventEmitter.publish("windowSlotAddressUpdated",{id:_this.window.id,slotAddress:_this.window.slotAddress}))}),_this.eventEmitter.subscribe("HIDE_REMOVE_SLOT",function(event){_this.element.find(".remove-slot-option").hide(),_this.window&&_this.eventEmitter.publish("HIDE_REMOVE_OBJECT."+_this.window.id)}),_this.eventEmitter.subscribe("SHOW_REMOVE_SLOT",function(event){_this.element.find(".remove-slot-option").show(),_this.window&&_this.eventEmitter.publish("SHOW_REMOVE_OBJECT."+_this.window.id)}),_this.eventEmitter.subscribe("ADD_ITEM_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.addItem()}),_this.eventEmitter.subscribe("REMOVE_SLOT_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("REMOVE_NODE",_this)}),_this.eventEmitter.subscribe("SPLIT_RIGHT_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_RIGHT",_this)}),_this.eventEmitter.subscribe("SPLIT_LEFT_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_LEFT",_this)}),_this.eventEmitter.subscribe("SPLIT_DOWN_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_DOWN",_this)}),_this.eventEmitter.subscribe("SPLIT_UP_FROM_WINDOW",function(event,id){_this.window&&_this.window.id===id&&_this.eventEmitter.publish("SPLIT_UP",_this)})]},bindEvents:function(){var _this=this,dropTarget=this.element.find(".dropMask");this.element.find(".addItemLink").on("click",function(){_this.addItem()}),this.element.find(".remove-slot-option").on("click",function(){_this.eventEmitter.publish("REMOVE_NODE",_this)}),this.element.on("dragover",function(e){e.preventDefault(),dropTarget.show()}),dropTarget.on("dragenter",function(e){e.preventDefault(),_this.element.addClass("draggedOver")}),dropTarget.on("dragleave",function(e){e.preventDefault(),_this.element.removeClass("draggedOver"),dropTarget.hide()}),this.element.on("drop",function(e){_this.dropItem(e)})},dropItem:function(e){var _this=this;e.preventDefault();var text_url=e.originalEvent.dataTransfer.getData("text/plain");text_url?_this.handleDrop(text_url):e.originalEvent.dataTransfer.items[0].getAsString(function(url){_this.handleDrop(url)})},handleDrop:function(url){var _this=this;url=url||text_url;var windowConfig,manifestUrl=$.getQueryParams(url).manifest||url,collectionUrl=$.getQueryParams(url).collection,canvasId=$.getQueryParams(url).canvas,imageInfoUrl=$.getQueryParams(url).image;"undefined"!=typeof _this.state.getStateProperty("manifests")[manifestUrl]?(windowConfig={manifest:_this.state.getStateProperty("manifests")[manifestUrl],slotAddress:_this.getAddress()},canvasId&&(windowConfig.canvasID=canvasId,windowConfig.viewType="ImageView"),_this.eventEmitter.publish("ADD_WINDOW",windowConfig)):"undefined"!=typeof imageInfoUrl?_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[imageInfoUrl,"(Added from URL)"]):"undefined"!=typeof collectionUrl?(jQuery.getJSON(collectionUrl).done(function(data,status,jqXHR){data.hasOwnProperty("manifests")?jQuery.each(data.manifests,function(ci,mfst){_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[mfst["@id"],"(Added from URL)"])}):data.hasOwnProperty("members")&&jQuery.each(data.members,function(ci,mfst){_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[mfst["@id"],"(Added from URL)"])})}),_this.addItem()):_this.state.getStateProperty("manifests")[imageInfoUrl]||_this.eventEmitter.publish("ADD_MANIFEST_FROM_URL",[manifestUrl,"(Added from URL)"]),_this.eventEmitter.subscribe("manifestReceived",function(event,manifest){var windowConfig;manifest.jsonLd["@id"]!==manifestUrl&&manifest.jsonLd["@id"]+"/info.json"!==imageInfoUrl||(windowConfig={manifest:manifest,slotAddress:_this.getAddress()},manifest.jsonLd["@id"]+"/info.json"===imageInfoUrl&&(canvasId=manifest.jsonLd.sequences[0].canvases[0]["@id"]),canvasId&&(windowConfig.canvasID=canvasId,windowConfig.viewType="ImageView"),_this.eventEmitter.publish("ADD_WINDOW",windowConfig))})},destroyEvents:function(){var _this=this;this.events.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)})},clearSlot:function(){this.destroyEvents(),this.window&&delete this.window},getAddress:function(){return this.layoutAddress},addItem:function(){var _this=this;_this.focused=!0,_this.eventEmitter.publish("ADD_SLOT_ITEM",_this)},template:$.Handlebars.compile(['<div id="{{slotID}}" class="{{workspaceSlotCls}}">','<div class="slotIconContainer">','<h1 class="plus" role="presentation" aria-label="Add item using Link">',"<span>+</span>",'<div class="dropIcon">','<i class="fa fa-level-down"></i>',"</div>","</h1>",'<h1 class="addItemText">{{t "addItem"}}</h1>','<h1 class="dropMeMessage">{{t "dropToLoad"}}</h1>',"</div>",'<a class="addItemLink" role="button" aria-label="Add item"></a>','<a class="remove-slot-option"><i class="fa fa-times fa-lg fa-fw"></i> {{t "close"}}</a>','<a class="dropMask"></a>',"</div>"].join(""))}}(Mirador),function($){$.Window=function(options){jQuery.extend(this,{state:null,eventEmitter:null,element:null,scrollImageRatio:.9,canvasID:null,focusImages:[],imagesList:null,annotationsList:[],endpoint:null,currentImageMode:"ImageView",imageModes:["ImageView","BookView"],originalImageModes:["ImageView","BookView"],focuses:["ThumbnailsView","ImageView","ScrollView","BookView"],focusModules:{ThumbnailsView:null,ImageView:null,ScrollView:null,BookView:null},focusOverlaysAvailable:{ThumbnailsView:{overlay:{MetadataView:!1},bottomPanel:{"":!1}},ImageView:{overlay:{MetadataView:!1},bottomPanel:{ThumbnailsView:!0}},ScrollView:{overlay:{MetadataView:!1},bottomPanel:{"":!1}},BookView:{overlay:{MetadataView:!1},bottomPanel:{ThumbnailsView:!0}}},windowOptions:null,sidePanel:null,annotationsAvailable:{ThumbnailsView:!1,ImageView:!0,ScrollView:!1,BookView:!1},bottomPanel:null,overlay:null,annoEndpointAvailable:!1,iconClasses:{ImageView:"fa fa-photo fa-lg fa-fw",BookView:"fa fa-columns fa-lg fa-fw",ScrollView:"fa fa-ellipsis-h fa-lg fa-fw",ThumbnailsView:"fa fa-th fa-lg fa-rotate-90 fa-fw"}},options),this.init(),this.bindAnnotationEvents()},$.Window.prototype={init:function(){var _this=this,manifest=_this.manifest.jsonLd,focusState=_this.viewType,templateData={};for(this.events=[];_this.annotationsList.length>0;)_this.annotationsList.pop();switch(_this.eventEmitter.unsubscribe("currentCanvasIDUpdated."+_this.id),_this.eventEmitter.publish("DESTROY_EVENTS."+_this.id),_this.removeBookView(),this.imageModes=this.originalImageModes,this.imageModes=jQuery.map(this.imageModes,function(value,index){return jQuery.inArray(value,_this.focuses)===-1?null:value}),_this.imagesList=_this.manifest.getCanvases(),_this.canvasID||(_this.canvasID=_this.imagesList[0]["@id"]),this.annoEndpointAvailable=!jQuery.isEmptyObject(_this.state.getStateProperty("annotationEndpoint")),this.canvasControls.annotations.annotationLayer||(this.canvasControls.annotations.annotationCreation=!1,this.annoEndpointAvailable=!1,this.canvasControls.annotations.annotationState="off"),_this.getAnnotations(),this.canvasControls.imageManipulation.manipulationLayer&&(this.canvasControls.imageManipulation.manipulationLayer=!Object.keys(this.canvasControls.imageManipulation.controls).every(function(element,index,array){return _this.canvasControls.imageManipulation.controls[element]===!1})),_this.eventEmitter.publish("windowUpdated",{id:_this.id,annotationsAvailable:this.annotationsAvailable}),"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable||jQuery.each(this.focusOverlaysAvailable,function(key,value){_this.focusOverlaysAvailable[key].bottomPanel={"":!1}}),templateData.sidePanel=this.sidePanelAvailable,this.sidePanelAvailable&&(templateData.sidePanel=!Object.keys(this.sidePanelOptions).every(function(element,index,array){return _this.sidePanelOptions[element]===!1})),"undefined"==typeof this.overlayAvailable||this.overlayAvailable?templateData.MetadataView=!0:jQuery.each(this.focusOverlaysAvailable,function(key,value){_this.focusOverlaysAvailable[key].overlay={"":!1}}),templateData.iconClasses={},jQuery.each(this.focuses,function(index,value){templateData[value]=!0,templateData.iconClasses[value]=_this.iconClasses[value]}),templateData.title=$.JsonLd.getTextValue(manifest.label),templateData.displayLayout=this.displayLayout,templateData.layoutOptions=this.layoutOptions,this.displayLayout&&(templateData.displayLayout=!Object.keys(this.layoutOptions).every(function(element,index,array){return _this.layoutOptions[element]===!1})),templateData.currentFocusClass=_this.iconClasses[_this.viewType],templateData.showFullScreen=_this.fullScreen,_this.element=jQuery(this.template(templateData)).appendTo(_this.appendTo),this.element.find(".manifest-info .mirador-tooltip").each(function(){jQuery(this).qtip({content:{text:jQuery(this).attr("title")},position:{my:"top center",at:"bottom center",adjust:{method:"shift",y:-11},container:_this.element,viewport:!0},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}})}),this.element.find(".manifest-info .window-manifest-title").qtip({content:{text:jQuery(this).attr("title")},position:{my:"top center",at:"bottom left",adjust:{method:"shift",x:20,y:1},container:_this.element,viewport:!0},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}}),_this.eventEmitter.publish("WINDOW_ELEMENT_UPDATED",{windowId:_this.id,element:_this.element}),_this.clearViews(),_this.clearPanelsAndOverlay(),this.listenForActions(),_this.bindNavigation(),focusState){case"ThumbnailsView":_this.toggleThumbnails(_this.canvasID);break;case"ImageView":_this.toggleImageView(_this.canvasID);break;case"BookView":_this.toggleBookView(_this.canvasID);break;case"ScrollView":_this.toggleScrollView(_this.canvasID)}_this.state.getSlots().length<=1&&_this.element.find(".remove-object-option").hide(),this.bindEvents(),1===this.imagesList.length?this.bottomPanelVisibility(!1):this.bottomPanelVisibility(this.bottomPanelVisible),this.sidePanelVisibility(this.sidePanelVisible,"0s"),this.events.push(this.eventEmitter.subscribe("windowRemoved",function(event,id){_this.id===id&&_this.destroy()}))},destroy:function(){var _this=this;this.events.forEach(function(event){_this.eventEmitter.unsubscribe(event.name,event.handler)}),this.element.remove()},update:function(options){jQuery.extend(this,options),this.windowOptions&&(this.windowOptions.osdBounds=null,this.windowOptions.zoomLevel=null),this.init()},removeBookView:function(){this.focuses=this.availableViews;var manifest=this.manifest.jsonLd;manifest.sequences[0].viewingHint&&"paged"!==manifest.sequences[0].viewingHint.toLowerCase()&&(this.focuses=jQuery.grep(this.focuses,function(value){return"BookView"!==value}))},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("bottomPanelSet."+_this.id,function(event,visible){var panel=_this.element.find(".bottomPanel");visible===!0?panel.css({transform:"translateY(0)"}):panel.css({transform:"translateY(100%)"})}),_this.events.push(_this.eventEmitter.subscribe("HIDE_REMOVE_OBJECT."+_this.id,function(event){_this.element.find(".remove-object-option").hide()})),_this.events.push(this.eventEmitter.subscribe("SHOW_REMOVE_OBJECT."+_this.id,function(event){_this.element.find(".remove-object-option").show()})),_this.events.push(_this.eventEmitter.subscribe("sidePanelStateUpdated."+this.id,function(event,state){state.open?(_this.element.find(".mirador-icon-toc").addClass("selected"),_this.element.find(".view-container").removeClass("maximised")):(_this.element.find(".mirador-icon-toc").removeClass("selected"),_this.element.find(".view-container").addClass("maximised"))})),_this.events.push(_this.eventEmitter.subscribe("sidePanelVisibilityByTab."+this.id,function(event,visible){_this.sidePanelVisibility(visible,"0s")})),_this.events.push(_this.eventEmitter.subscribe("SET_CURRENT_CANVAS_ID."+this.id,function(event,canvasID){_this.setCurrentCanvasID(canvasID)})),_this.events.push(_this.eventEmitter.subscribe("REMOVE_CLASS."+this.id,function(event,className){_this.element.find(".view-container").removeClass(className)})),_this.events.push(_this.eventEmitter.subscribe("ADD_CLASS."+this.id,function(event,className){_this.element.find(".view-container").addClass(className)})),_this.events.push(_this.eventEmitter.subscribe("UPDATE_FOCUS_IMAGES."+this.id,function(event,images){_this.updateFocusImages(images.array)})),_this.events.push(_this.eventEmitter.subscribe("HIDE_ICON_TOC."+this.id,function(event){_this.element.find(".mirador-icon-toc").hide()})),_this.events.push(_this.eventEmitter.subscribe("SHOW_ICON_TOC."+this.id,function(event){_this.element.find(".mirador-icon-toc").show()})),_this.events.push(_this.eventEmitter.subscribe("SET_BOTTOM_PANEL_VISIBILITY."+this.id,function(event,visibility){"undefined"!=typeof visibility&&null!==visibility?_this.bottomPanelVisibility(visibility):_this.bottomPanelVisibility(_this.bottomPanelVisible)})),_this.events.push(_this.eventEmitter.subscribe("TOGGLE_BOTTOM_PANEL_VISIBILITY."+this.id,function(event){var visible=!_this.bottomPanelVisible;_this.bottomPanelVisibility(visible)})),_this.events.push(_this.eventEmitter.subscribe("DISABLE_WINDOW_FULLSCREEN",function(event){_this.element.find(".mirador-osd-fullscreen").hide()})),_this.events.push(_this.eventEmitter.subscribe("ENABLE_WINDOW_FULLSCREEN",function(event){_this.element.find(".mirador-osd-fullscreen").show()}))},bindEvents:function(){var _this=this;jQuery(window).resize($.debounce(function(){if(_this.focusModules.ScrollView){var containerHeight=_this.element.find(".view-container").height(),triggerShow=!1;"ScrollView"===_this.viewType&&(triggerShow=!0),_this.focusModules.ScrollView.reloadImages(Math.floor(containerHeight*_this.scrollImageRatio),triggerShow)}},300)),this.element.find(".mirador-osd-fullscreen").on("click",function(){$.fullscreenElement()?$.exitFullscreen():$.enterFullscreen(_this.element[0])}),jQuery(document).on("webkitfullscreenchange mozfullscreenchange fullscreenchange",function(){_this.toggleFullScreen()})},bindAnnotationEvents:function(){var _this=this;_this.eventEmitter.subscribe("annotationCreated."+_this.id,function(event,oaAnno,eventCallback){var annoID;_this.endpoint.create(oaAnno,function(data){annoID=String(data["@id"]),_this.annotationsList.push(data),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList}),eventCallback()},function(){console.log("There was an error saving this new annotation")})}),_this.eventEmitter.subscribe("annotationUpdated."+_this.id,function(event,oaAnno){_this.endpoint.update(oaAnno,function(data){jQuery.each(_this.annotationsList,function(index,value){if(value["@id"]===data["@id"])return _this.annotationsList[index]=data,!1}),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})},function(){console.log("There was an error updating this annotation")})}),_this.eventEmitter.subscribe("annotationDeleted."+_this.id,function(event,annoId){_this.endpoint.deleteAnnotation(annoId,function(){_this.annotationsList=jQuery.grep(_this.annotationsList,function(e){return e["@id"]!==annoId}),_this.eventEmitter.publish("removeOverlay."+_this.id,annoId),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})},function(){})}),_this.eventEmitter.subscribe("updateAnnotationList."+_this.id,function(event){for(;_this.annotationsList.length>0;)_this.annotationsList.pop();_this.getAnnotations()})},clearViews:function(){var _this=this;jQuery.each(_this.focusModules,function(key,value){_this.focusModules[key]=null})},clearPanelsAndOverlay:function(){this.sidePanel=null,this.bottomPanel=null,this.overlay=null},updatePanelsAndOverlay:function(state){var _this=this;jQuery.each(this.focusOverlaysAvailable[state],function(panelType,viewOptions){jQuery.each(viewOptions,function(view,displayed){""!==view&&null===_this[panelType]&&(_this[panelType]=new $[view]({manifest:_this.manifest,appendTo:_this.element.find("."+panelType),state:_this.state,eventEmitter:_this.eventEmitter,windowId:_this.id,panel:!0,canvasID:_this.canvasID,imagesList:_this.imagesList,thumbInfo:{thumbsHeight:80,listingCssCls:"panel-listing-thumbs",thumbnailCls:"panel-thumbnail-view"}})),displayed=_this.focusOverlaysAvailable[state][panelType][view],""!==view&&displayed&&_this.togglePanels(panelType,displayed,view,state),""===view&&_this[panelType]&&_this.togglePanels(panelType,displayed,view,state),""===view&&_this.adjustFocusSize(panelType,displayed)})})},updateSidePanel:function(){if(this.sidePanelAvailable){var _this=this,tocAvailable=_this.sidePanelOptions.toc,annotationsTabAvailable=_this.sidePanelOptions.annotations,layersTabAvailable=_this.sidePanelOptions.layers,hasStructures=!0,structures=_this.manifest.getStructures();structures&&0!==structures.length||(hasStructures=!1),null===this.sidePanel?this.sidePanel=new $.SidePanel({windowId:_this.id,state:_this.state,eventEmitter:_this.eventEmitter,appendTo:_this.element.find(".sidePanel"),manifest:_this.manifest,canvasID:_this.canvasID,layersTabAvailable:layersTabAvailable,tocTabAvailable:tocAvailable,annotationsTabAvailable:annotationsTabAvailable,hasStructures:hasStructures}):this.sidePanel.update("annotations",annotationsTabAvailable)}},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){options?this[options.parent][prop]=value:this[prop]=value},togglePanels:function(panelType,panelState,viewType,focusState){this.focusOverlaysAvailable[focusState][panelType][viewType]=panelState,this[panelType].toggle(panelState),this.adjustFocusSize(panelType,panelState)},sidePanelVisibility:function(visible,transitionDuration){var _this=this;_this.sidePanelVisible=visible,tocIconElement=this.element.find(".mirador-icon-toc"),sidePanelElement=this.element.find(".sidePanel"),viewContainerElement=this.element.find(".view-container"),sidePanelElement.css("transition-duration",transitionDuration),viewContainerElement.css("transition",transitionDuration),visible&&sidePanelElement.hasClass("minimized")?(tocIconElement.addClass("selected"),sidePanelElement.removeClass("minimized").width(280).css("border-right","1px solid lightgray"),viewContainerElement.css("margin-left",280)):visible||sidePanelElement.hasClass("minimized")||(tocIconElement.removeClass("selected"),viewContainerElement.css("margin-left",0),sidePanelElement.addClass("minimized").css("border","none").width(0)),_this.eventEmitter.publish("windowUpdated",{id:_this.id,sidePanelVisible:visible})},bottomPanelVisibility:function(visible){var _this=this;_this.bottomPanelVisible=visible,_this.eventEmitter.publish("bottomPanelSet."+_this.id,visible),_this.eventEmitter.publish("windowUpdated",{id:_this.id,bottomPanelVisible:visible})},adjustFocusSize:function(panelType,panelState){"bottomPanel"===panelType?this.focusModules[this.viewType].adjustHeight("focus-max-height",panelState):"sidePanel"===panelType&&this.focusModules[this.viewType].adjustWidth("focus-max-width",panelState)},toggleMetadataOverlay:function(focusState){var currentState=this.focusOverlaysAvailable[focusState].overlay.MetadataView;currentState?this.element.find(".mirador-icon-metadata-view").removeClass("selected"):this.element.find(".mirador-icon-metadata-view").addClass("selected"),jQuery.each(this.focusOverlaysAvailable,function(focusType,options){focusState!==focusType&&(this.overlay.MetadataView=!currentState)}),this.togglePanels("overlay",!currentState,"MetadataView",focusState)},toggleFocus:function(focusState,imageMode){var _this=this;this.viewType=focusState,imageMode&&jQuery.inArray(imageMode,this.imageModes)>-1&&(this.currentImageMode=imageMode),jQuery.each(this.focusModules,function(focusKey,module){module&&focusState!==focusKey&&module.toggle(!1)}),this.focusModules[focusState].toggle(!0),this.updateManifestInfo(),this.updatePanelsAndOverlay(focusState),this.updateSidePanel(),_this.eventEmitter.publish("focusUpdated"),_this.eventEmitter.publish("windowUpdated",{id:_this.id,viewType:_this.viewType,canvasID:_this.canvasID,imageMode:_this.currentImageMode,loadedManifest:_this.manifest.jsonLd["@id"],slotAddress:_this.slotAddress})},toggleThumbnails:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.ThumbnailsView)this.focusModules.ThumbnailsView=new $.ThumbnailsView({manifest:this.manifest,appendTo:this.element.find(".view-container"),state:this.state,eventEmitter:this.eventEmitter,windowId:this.id,canvasID:this.canvasID,imagesList:this.imagesList});else{var view=this.focusModules.ThumbnailsView;view.updateImage(canvasID)}this.toggleFocus("ThumbnailsView","")},toggleImageView:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.ImageView)this.focusModules.ImageView=new $.ImageView({manifest:this.manifest,appendTo:this.element.find(".view-container"),qtipElement:this.element,windowId:this.id,state:this.state,eventEmitter:this.eventEmitter,canvasID:canvasID,imagesList:this.imagesList,osdOptions:this.windowOptions,bottomPanelAvailable:this.bottomPanelAvailable,annoEndpointAvailable:this.annoEndpointAvailable,canvasControls:this.canvasControls,annotationState:this.canvasControls.annotations.annotationState});else{var view=this.focusModules.ImageView;view.updateImage(canvasID)}this.toggleFocus("ImageView","ImageView")},toggleBookView:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.BookView)this.focusModules.BookView=new $.BookView({manifest:this.manifest,appendTo:this.element.find(".view-container"),windowId:this.id,state:this.state,eventEmitter:this.eventEmitter,canvasID:canvasID,imagesList:this.imagesList,osdOptions:this.windowOptions,bottomPanelAvailable:this.bottomPanelAvailable});else{var view=this.focusModules.BookView;view.updateImage(canvasID)}this.toggleFocus("BookView","BookView")},toggleScrollView:function(canvasID){if(this.canvasID=canvasID,null===this.focusModules.ScrollView){var containerHeight=this.element.find(".view-container").height();this.focusModules.ScrollView=new $.ScrollView({manifest:this.manifest,appendTo:this.element.find(".view-container"),state:this.state,eventEmitter:this.eventEmitter,windowId:this.id,canvasID:this.canvasID,imagesList:this.imagesList,thumbInfo:{thumbsHeight:Math.floor(containerHeight*this.scrollImageRatio),listingCssCls:"scroll-listing-thumbs",thumbnailCls:"scroll-view"}})}else{var view=this.focusModules.ScrollView;view.updateImage(canvasID)}this.toggleFocus("ScrollView","")},updateFocusImages:function(imageList){this.focusImages=imageList,this.bottomPanel&&this.bottomPanel.updateFocusImages(this.focusImages)},setCurrentCanvasID:function(canvasID){var _this=this;for(this.canvasID=canvasID,_this.eventEmitter.publish("removeTooltips."+_this.id),_this.eventEmitter.unsubscribe("annotationListLoaded."+_this.id);_this.annotationsList.length>0;)_this.annotationsList.pop();switch(this.getAnnotations(),this.currentImageMode){case"ImageView":this.toggleImageView(this.canvasID);break;case"BookView":this.toggleBookView(this.canvasID)}_this.eventEmitter.publish("currentCanvasIDUpdated."+_this.id,canvasID)},replaceWindow:function(newSlotAddress,newElement){this.slotAddress=newSlotAddress,this.appendTo=newElement,this.update()},setCursorFrameStart:function(canvasID){},updateManifestInfo:function(){var _this=this;_this.element.find(".mirador-icon-view-type > i:first").removeClass().addClass(_this.iconClasses[_this.viewType]),this.focusOverlaysAvailable[this.viewType].overlay.MetadataView&&this.element.find(".mirador-icon-metadata-view").addClass("selected")},getAnnotations:function(){var _this=this,urls=_this.manifest.getAnnotationsListUrls(_this.canvasID);if(0!==urls.length&&jQuery.each(urls,function(index,url){jQuery.get(url,function(list){var annotations=list.resources;jQuery.each(annotations,function(index,value){"undefined"==typeof value["@id"]&&(value["@id"]=$.genUUID()),value.endpoint="manifest"}),_this.annotationsList=_this.annotationsList.concat(annotations),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})})}),this.annoEndpointAvailable){var dfd=jQuery.Deferred(),module=_this.state.getStateProperty("annotationEndpoint").module,options=_this.state.getStateProperty("annotationEndpoint").options||{};options.name=_this.state.getStateProperty("annotationEndpoint").name,_this.endpoint&&null!==_this.endpoint?_this.endpoint.set("dfd",dfd):(options.dfd=dfd,options.windowID=_this.id,options.imagesList=_this.imagesList,options.eventEmitter=_this.eventEmitter,_this.endpoint=new $[module](options)),_this.endpoint.search({uri:_this.canvasID}),dfd.done(function(loaded){_this.annotationsList=_this.annotationsList.concat(_this.endpoint.annotationsList),_this.annotationsList=jQuery.grep(_this.annotationsList,function(value,index){return"undefined"!=typeof value.on}),_this.eventEmitter.publish("ANNOTATIONS_LIST_UPDATED",{windowId:_this.id,annotationsList:_this.annotationsList})})}},toggleFullScreen:function(){var _this=this;OpenSeadragon.isFullScreen()?(this.element.find(".mirador-osd-fullscreen i").removeClass("fa-expand").addClass("fa-compress"),this.element.find(".mirador-osd-toggle-bottom-panel").hide(),_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.id,!1)):(this.element.find(".mirador-osd-fullscreen i").removeClass("fa-compress").addClass("fa-expand"),this.element.find(".mirador-osd-toggle-bottom-panel").show(),_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.id,!0))},bindNavigation:function(){var _this=this;this.element.find(".mirador-icon-view-type").on("mouseenter",function(){_this.element.find(".image-list").stop().slideFadeToggle(300)}).on("mouseleave",function(){_this.element.find(".image-list").stop().slideFadeToggle(300)}),this.element.find(".mirador-icon-window-menu").on("mouseenter",function(){_this.element.find(".slot-controls").stop().slideFadeToggle(300)}).on("mouseleave",function(){_this.element.find(".slot-controls").stop().slideFadeToggle(300)}),this.element.find(".single-image-option").on("click",function(){_this.toggleImageView(_this.canvasID)}),this.element.find(".book-option").on("click",function(){_this.toggleBookView(_this.canvasID)}),this.element.find(".scroll-option").on("click",function(){_this.toggleScrollView(_this.canvasID)}),this.element.find(".thumbnails-option").on("click",function(){_this.toggleThumbnails(_this.canvasID)}),this.element.find(".mirador-icon-metadata-view").on("click",function(){_this.toggleMetadataOverlay(_this.viewType)}),this.element.find(".mirador-icon-toc").on("click",function(){_this.sidePanelVisibility(!_this.sidePanelVisible,"0.3s")}),this.element.find(".new-object-option").on("click",function(){_this.eventEmitter.publish("ADD_ITEM_FROM_WINDOW",_this.id)}),this.element.find(".remove-object-option").on("click",function(){_this.eventEmitter.publish("REMOVE_SLOT_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-right").on("click",function(){_this.eventEmitter.publish("SPLIT_RIGHT_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-left").on("click",function(){_this.eventEmitter.publish("SPLIT_LEFT_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-below").on("click",function(){_this.eventEmitter.publish("SPLIT_DOWN_FROM_WINDOW",_this.id)}),this.element.find(".add-slot-above").on("click",function(){_this.eventEmitter.publish("SPLIT_UP_FROM_WINDOW",_this.id)})},template:$.Handlebars.compile(['<div class="window">','<div class="manifest-info">','<div class="window-manifest-navigation">','<a href="javascript:;" class="mirador-btn mirador-icon-view-type" role="button" title="{{t "viewTypeTooltip"}}" aria-label="{{t "viewTypeTooltip"}}">','<i class="{{currentFocusClass}}"></i>','<i class="fa fa-caret-down"></i>','<ul class="dropdown image-list">',"{{#if ImageView}}",'<li class="single-image-option"><i class="{{iconClasses.ImageView}}"></i> {{t "imageView"}}</li>',"{{/if}}","{{#if BookView}}",'<li class="book-option"><i class="{{iconClasses.BookView}}"></i> {{t "bookView"}}</li>',"{{/if}}","{{#if ScrollView}}",'<li class="scroll-option"><i class="{{iconClasses.ScrollView}}"></i> {{t "scrollView"}}</li>',"{{/if}}","{{#if ThumbnailsView}}",'<li class="thumbnails-option"><i class="{{iconClasses.ThumbnailsView}}"></i> {{t "thumbnailsView"}}</li>',"{{/if}}","</ul>","</a>","{{#if MetadataView}}",'<a href="javascript:;" class="mirador-btn mirador-icon-metadata-view mirador-tooltip" role="button" title="{{t "metadataTooltip"}}" aria-label="{{t "metadataTooltip"}}">','<i class="fa fa-info-circle fa-lg fa-fw"></i>',"</a>","{{/if}}","{{#if showFullScreen}}",'<a class="mirador-btn mirador-osd-fullscreen mirador-tooltip" role="button" title="{{t "fullScreenWindowTooltip"}}" aria-label="{{t "fullScreenWindowTooltip"}}">','<i class="fa fa-lg fa-fw fa-expand"></i>',"</a>","{{/if}}","</div>","{{#if layoutOptions.close}}",'<a href="javascript:;" class="mirador-btn mirador-close-window remove-object-option mirador-tooltip" title="{{t "closeTooltip"}}" aria-label="{{t "closeTooltip"}}"><i class="fa fa-times fa-lg fa-fw"></i></a>',"{{/if}}","{{#if displayLayout}}",'<a href="javascript:;" class="mirador-btn mirador-icon-window-menu" title="{{t "changeLayoutTooltip"}}" aria-label="{{t "changeLayoutTooltip"}}"><i class="fa fa-th-large fa-lg fa-fw"></i><i class="fa fa-caret-down"></i>','<ul class="dropdown slot-controls">',"{{#if layoutOptions.newObject}}",'<li class="new-object-option"><i class="fa fa-refresh fa-lg fa-fw"></i> {{t "newObject"}}</li>','<hr class="menu-divider"/>',"{{/if}}","{{#if layoutOptions.slotRight}}",'<li class="add-slot-right"><i class="fa fa-arrow-circle-right fa-lg fa-fw"></i> {{t "addSlotRight"}}</li>',"{{/if}}","{{#if layoutOptions.slotLeft}}",'<li class="add-slot-left"><i class="fa fa-arrow-circle-left fa-lg fa-fw"></i> {{t "addSlotLeft"}}</li>',"{{/if}}","{{#if layoutOptions.slotAbove}}",'<li class="add-slot-above"><i class="fa fa-arrow-circle-up fa-lg fa-fw"></i> {{t "addSlotAbove"}}</li>',"{{/if}}","{{#if layoutOptions.slotBelow}}",'<li class="add-slot-below"><i class="fa fa-arrow-circle-down fa-lg fa-fw"></i> {{t "addSlotBelow"}}</li>',"{{/if}}","</ul>","</a>","{{/if}}","{{#if sidePanel}}",'<a href="javascript:;" class="mirador-btn mirador-icon-toc selected mirador-tooltip" title="{{t "sidePanelTooltip"}}" aria-label="{{t "sidePanelTooltip"}}"><i class="fa fa-bars fa-lg fa-fw"></i></a>',"{{/if}}",'<h3 class="window-manifest-title" title="{{{title}}}" aria-label="{{{title}}}">{{{title}}}</h3>',"</div>",'<div class="content-container">',"{{#if sidePanel}}",'<div class="sidePanel">',"</div>","{{/if}}",'<div class="overlay"></div>','<div class="view-container {{#unless sidePanel}}focus-max-width{{/unless}}">','<div class="bottomPanel">',"</div>","</div>","</div>","</div>"].join(""))
85
+ }}(Mirador),function($){$.AnnotationsLayer=function(options){jQuery.extend(!0,this,{annotationsList:null,viewer:null,drawTool:null,selected:null,hovered:null,windowId:null,mode:"default",element:null,eventEmitter:null},options),this.init()},$.AnnotationsLayer.DISPLAY_ANNOTATIONS="displayAnnotations",$.AnnotationsLayer.prototype={init:function(){var _this=this;_this.eventEmitter.unsubscribe("modeChange."+_this.windowId),this.createStateMachine(),this.createRenderer(),this.bindEvents(),this.listenForActions()},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("modeChange."+_this.windowId,function(event,modeName){_this.mode=modeName,_this.modeSwitch()}),_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(event){_this.annotationsList=_this.state.getWindowAnnotationsList(_this.windowId),_this.updateRenderer()})},bindEvents:function(){},createStateMachine:function(){var _this=this;this.layerState=StateMachine.create({events:[{name:"startup",from:"none",to:"default"},{name:"defaultState",from:["default","display","create","edit"],to:"default"},{name:"displayAnnotations",from:["default","display","create","edit","newShape"],to:"display"},{name:"createAnnotation",from:["default","display"],to:"create"},{name:"createShape",from:"edit",to:"newShape"},{name:"editAnnotation",from:["default","display","newShape"],to:"edit"}],callbacks:{onstartup:function(event){_this.drawTool.enterDefault()},ondefaultState:function(event){_this.drawTool.enterDefault()},ondisplayAnnotations:function(event){_this.drawTool.enterDisplayAnnotations()},oncreateAnnotation:function(event){_this.drawTool.enterCreateAnnotation()},oncreateShape:function(event){_this.drawTool.enterCreateShape()},oneditAnnotation:function(event){_this.drawTool.enterEditAnnotation()}}})},createRenderer:function(){var _this=this;this.drawTool=new $.OsdRegionDrawTool({osdViewer:_this.viewer,parent:_this,list:_this.annotationsList,visible:!1,windowId:_this.windowId,state:_this.state,eventEmitter:_this.eventEmitter}),this.layerState.startup()},updateRenderer:function(){this.drawTool.list=this.annotationsList},modeSwitch:function(){"displayAnnotations"===this.mode?this.layerState.displayAnnotations():"editingAnnotation"===this.mode?this.layerState.editAnnotation():"creatingAnnotation"===this.mode?"edit"!==this.layerState.current?this.layerState.createAnnotation():this.layerState.createShape():"default"===this.mode&&this.layerState.defaultState()}}}(Mirador),function($){$.AnnotationsTab=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,visible:null,state:null,eventEmitter:null},options),this.init()},$.AnnotationsTab.prototype={init:function(){this.windowId=this.windowId,this.localState({id:"annotationsTab",visible:this.visible,annotationLists:[],selectedList:null,empty:!0,focusedList:null},!0),this.listenForActions(),this.render(this.localState()),this.loadTabComponents(),this.bindEvents()},localState:function(state,initial){var _this=this;return arguments.length?(this.annoTabState=state,initial||_this.eventEmitter.publish("annotationsTabStateUpdated."+this.windowId,this.annoTabState),this.annoTabState):this.annoTabState},loadTabComponents:function(){},tabStateUpdated:function(visible){var localState=this.localState();localState.visible=!localState.visible,this.localState(localState)},annotationListLoaded:function(){var _this=this,annotationSources=[],localState=this.localState();jQuery.each(_this.state.getWindowAnnotationsList(_this.windowId),function(index,value){"string"==typeof value.endpoint?annotationSources.push("manifest"):annotationSources.push(value.endpoint.name)}),annotationSources=annotationSources.filter(function(itm,i,annotationSources){return i==annotationSources.indexOf(itm)}),localState.annotationLists=annotationSources.map(function(annotationSource){return{annotationSource:annotationSource,layer:null,selected:annotationSource===localState.selectedList,focused:!1}}),localState.annotationLists.length&&(localState.empty=!1),this.localState(localState)},deselectList:function(listId){var localState=this.localState();localState.selectedList=null,localState.annotationLists.forEach(function(list){list.selected=!1}),this.localState(localState)},selectList:function(listId){var localState=this.localState();localState.selectedList=listId,localState.annotationLists.forEach(function(list){list.selected=list.annotationSource===listId}),this.localState(localState)},focusList:function(listId){var localState=this.localState();localState.focusedList=listId,localState.annotationLists.forEach(function(list){list.focused=list.annotationSource===listId}),this.localState(localState)},toggle:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("annotationsTabStateUpdated."+_this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("tabStateUpdated."+_this.windowId,function(_,data){_this.tabStateUpdated(data.annotationsTab)}),_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(_,data){_this.annotationListLoaded()}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event){_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(event){_this.annotationListLoaded()}),_this.selectList(_this.localState().selectedList)}),_this.eventEmitter.subscribe("listSelected."+_this.windowId,function(event,listId){_this.selectList(listId)}),_this.eventEmitter.subscribe("listDeselected."+_this.windowId,function(event,listId){_this.deselectList(listId)})},bindEvents:function(){var _this=this,listItems=this.element.find(".annotationListItem");listItems.on("click",function(event){var listClicked=jQuery(this).data("id");_this.localState().selectedList===listClicked?_this.eventEmitter.publish("listDeselected."+_this.windowId,listClicked):_this.eventEmitter.publish("listSelected."+_this.windowId,listClicked)})},render:function(state){var _this=this,templateData={annotationSources:state.annotationLists};this.element?(_this.appendTo.find(".annotationsPanel").remove(),this.element=jQuery(_this.template(templateData)).appendTo(_this.appendTo)):this.element=jQuery(_this.template(templateData)).appendTo(_this.appendTo),_this.bindEvents(),state.visible?this.element.show():this.element.hide()},template:$.Handlebars.compile(['<div class="annotationsPanel">','<ul class="annotationSources">',"{{#each annotationSources}}",'<li class="annotationListItem {{#if this.selected}}selected{{/if}} {{#if this.focused }}focused{{/if}}" data-id="{{this.annotationSource}}">',"<span>{{this.annotationSource}}</span>","</li>","{{/each}}","</ul>","</div>"].join(""))}}(Mirador),function($){$.BookView=function(options){jQuery.extend(this,{currentImg:null,windowId:null,currentImgIndex:0,stitchList:[],canvasID:null,imagesList:[],element:null,focusImages:[],manifest:null,viewingDirection:"left-to-right",viewingHint:"paged",osd:null,osdCls:"mirador-osd",osdOptions:{osdBounds:null,zoomLevel:null},stitchTileMargin:10,eventEmitter:null},options),this.init()},$.BookView.prototype={init:function(){var _this=this;null!==this.canvasID&&(this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID)),this.osdOptions||(this.osdOptions={osdBounds:null,zoomLevel:null}),this.currentImg=this.imagesList[this.currentImgIndex],this.element=jQuery(this.template()).appendTo(this.appendTo),this.hud=new $.Hud({appendTo:this.element,bottomPanelAvailable:this.bottomPanelAvailable,windowId:this.windowId,annotationLayerAvailable:!1,showNextPrev:1!==this.imagesList.length,eventEmitter:this.eventEmitter,showAnno:!1,showImageControls:!1}),this.manifest.jsonLd.sequences[0].viewingDirection&&(this.viewingDirection=this.manifest.jsonLd.sequences[0].viewingDirection.toLowerCase()),this.manifest.jsonLd.sequences[0].viewingHint&&(this.viewingHint=this.manifest.jsonLd.sequences[0].viewingHint.toLowerCase()),this.stitchList=this.getStitchList(),this.createOpenSeadragonInstance(),this.bindEvents(),this.listenForActions(),"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable?_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,null):_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,!1)},template:$.Handlebars.compile(['<div class="book-view">',"</div>"].join("")),listenForActions:function(){var _this=this,firstCanvasId=_this.imagesList[0]["@id"],lastCanvasId=_this.imagesList[_this.imagesList.length-1]["@id"];_this.eventEmitter.subscribe("bottomPanelSet."+_this.windowId,function(event,visible){var dodgers=_this.element.find(".mirador-osd-toggle-bottom-panel, .mirador-pan-zoom-controls"),arrows=_this.element.find(".mirador-osd-next, .mirador-osd-previous");visible===!0?(dodgers.addClass("bottom-panel-open"),arrows.addClass("bottom-panel-open")):(dodgers.removeClass("bottom-panel-open"),arrows.removeClass("bottom-panel-open"))}),_this.eventEmitter.subscribe("fitBounds."+_this.windowId,function(event,bounds){var rect=_this.osd.viewport.imageToViewportRectangle(Number(bounds.x),Number(bounds.y),Number(bounds.width),Number(bounds.height));_this.osd.viewport.fitBoundsWithConstraints(rect,!1)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasId){canvasId===firstCanvasId?(_this.element.find(".mirador-osd-previous").hide(),_this.element.find(".mirador-osd-next").show()):canvasId===lastCanvasId?(_this.element.find(".mirador-osd-next").hide(),_this.element.find(".mirador-osd-previous").show()):(_this.element.find(".mirador-osd-next").show(),_this.element.find(".mirador-osd-previous").show())})},bindEvents:function(){var _this=this;this.element.find(".mirador-osd-next").on("click",function(){_this.next()}),this.element.find(".mirador-osd-previous").on("click",function(){_this.previous()}),this.element.find(".mirador-osd-go-home").on("click",function(){_this.osd.viewport.goHome()}),this.element.find(".mirador-osd-up").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,-panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-right").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-down").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-left").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(-panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-zoom-in").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(osd.zoomPerClick/1),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-zoom-out").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(1/osd.zoomPerClick),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-toggle-bottom-panel").on("click",function(){_this.eventEmitter.publish("TOGGLE_BOTTOM_PANEL_VISIBILITY."+_this.windowId)})},getPanByValue:function(){var bounds=this.osd.viewport.getBounds(!0),panBy={x:.5*bounds.width,y:.5*bounds.height};return panBy},setBounds:function(){var _this=this;this.osdOptions.osdBounds=this.osd.viewport.getBounds(!0),_this.eventEmitter.publish("imageBoundsUpdated",{id:_this.windowId,osdBounds:{x:_this.osdOptions.osdBounds.x,y:_this.osdOptions.osdBounds.y,width:_this.osdOptions.osdBounds.width,height:_this.osdOptions.osdBounds.height}})},toggle:function(stateValue){stateValue?this.show():this.hide()},hide:function(){jQuery(this.element).hide({effect:"fade",duration:300,easing:"easeOutCubic"})},show:function(){jQuery(this.element).show({effect:"fade",duration:300,easing:"easeInCubic",complete:function(){jQuery(this).css("display","block")}})},adjustWidth:function(className,hasClass){var _this=this;hasClass?_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,className):_this.eventEmitter.publish("ADD_CLASS."+this.windowId,className)},adjustHeight:function(className,hasClass){hasClass?this.element.removeClass(className):this.element.addClass(className)},updateImage:function(canvasID){this.canvasID=canvasID,this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID),this.currentImg=this.imagesList[this.currentImgIndex];var newList=this.getStitchList(),is_same=this.stitchList.length==newList.length&&this.stitchList.every(function(element,index){return element===newList[index]});is_same||(this.stitchList=newList,this.osdOptions={osdBounds:null,zoomLevel:null},this.osd.close(),this.createOpenSeadragonInstance())},createOpenSeadragonInstance:function(){var elemOsd,uniqueID=$.genUUID(),osdId="mirador-osd-"+uniqueID,tileSources=[],_this=this,toolbarID="osd-toolbar-"+uniqueID,dfd=jQuery.Deferred();this.element.find("."+this.osdCls).remove(),jQuery.each(this.stitchList,function(index,image){var imageUrl=$.Iiif.getImageUrl(image),infoJsonUrl=imageUrl+"/info.json";jQuery.getJSON(infoJsonUrl).done(function(data,status,jqXHR){tileSources.splice(index,0,data),tileSources.length===_this.stitchList.length&&dfd.resolve()})}),dfd.done(function(){var aspectRatio=tileSources[0].height/tileSources[0].width;elemOsd=jQuery("<div/>").addClass(_this.osdCls).attr("id",osdId).appendTo(_this.element),_this.osd=$.OpenSeadragon({id:elemOsd.attr("id"),toolbarID:toolbarID}),_this.osd.addHandler("open",function(){_this.addLayer(tileSources.slice(1),aspectRatio);var addItemHandler=function(event){if(_this.osd.world.removeHandler("add-item",addItemHandler),_this.osdOptions.osdBounds){var rect=new OpenSeadragon.Rect(_this.osdOptions.osdBounds.x,_this.osdOptions.osdBounds.y,_this.osdOptions.osdBounds.width,_this.osdOptions.osdBounds.height);_this.osd.viewport.fitBounds(rect,!0)}else _this.osd.viewport.goHome(!0)};_this.osd.world.addHandler("add-item",addItemHandler),_this.osd.addHandler("zoom",$.debounce(function(){_this.setBounds()},300)),_this.osd.addHandler("pan",$.debounce(function(){_this.setBounds()},300))}),_this.osd.open(tileSources[0],{opacity:1,x:0,y:0,width:1})})},addLayer:function(tileSources,aspectRatio){var _this=this;jQuery.each(tileSources,function(index,value){var newAR=value.height/value.width,options={tileSource:value,opacity:1,x:1.01,y:0,width:aspectRatio/newAR};_this.osd.addTiledImage(options)})},next:function(){var next,_this=this;next=this.currentImgIndex%2===0?this.currentImgIndex+1:this.currentImgIndex+2,next<this.imagesList.length&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[next]["@id"])},previous:function(){var prev,_this=this;prev=this.currentImgIndex%2===0?this.currentImgIndex-2:this.currentImgIndex-1,prev>=0&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[prev]["@id"])},getStitchList:function(){var stitchList=[],leftIndex=[],rightIndex=[],topIndex=[],bottomIndex=[],_this=this;if(this.focusImages=[],"individuals"===this.viewingHint)stitchList=[this.currentImg];else if("paged"===this.viewingHint)if(0===this.currentImgIndex||this.currentImgIndex===this.imagesList.length-1)stitchList=[this.currentImg];else if(this.currentImgIndex%2===0)switch(this.viewingDirection){case"left-to-right":leftIndex[0]=this.currentImgIndex-1,stitchList=[this.imagesList[this.currentImgIndex-1],this.currentImg];break;case"right-to-left":rightIndex[0]=this.currentImgIndex-1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex-1]];break;case"top-to-bottom":topIndex[0]=this.currentImgIndex-1,stitchList=[this.imagesList[this.currentImgIndex-1],this.currentImg];break;case"bottom-to-top":bottomIndex[0]=this.currentImgIndex-1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex-1]]}else switch(this.viewingDirection){case"left-to-right":rightIndex[0]=this.currentImgIndex+1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex+1]];break;case"right-to-left":leftIndex[0]=this.currentImgIndex+1,stitchList=[this.imagesList[this.currentImgIndex+1],this.currentImg];break;case"top-to-bottom":bottomIndex[0]=this.currentImgIndex+1,stitchList=[this.currentImg,this.imagesList[this.currentImgIndex+1]];break;case"bottom-to-top":topIndex[0]=this.currentImgIndex+1,stitchList=[this.imagesList[this.currentImgIndex+1],this.currentImg]}else"continuous"===this.viewingHint;return jQuery.each(stitchList,function(index,image){_this.focusImages.push(image["@id"])}),_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:this.focusImages}),stitchList}}}(Mirador),function($){$.ContextControls=function(options){jQuery.extend(this,{element:null,container:null,mode:null,windowId:null,annoEndpointAvailable:!1,eventEmitter:null},options),this.init()},$.ContextControls.prototype={init:function(){var _this=this,showStrokeStyle=!1,showStrokeColor=!1,showFillColor=!1;this.availableAnnotationStylePickers.forEach(function(picker){"StrokeType"===picker&&(showStrokeStyle=!0),"FillColor"===picker&&(showFillColor=!0),"StrokeColor"===picker&&(showStrokeColor=!0)}),this.setBackground={solid:function(el){_this.setBackgroundImage(el,"border_type_1.png")},dashed:function(el){_this.setBackgroundImage(el,"border_type_2.png")},dotdashed:function(el){_this.setBackgroundImage(el,"border_type_3.png")}};var annotationProperties=this.canvasControls.annotations;annotationProperties.annotationLayer&&this.annoEndpointAvailable&&(this.annotationElement=jQuery(this.annotationTemplate({tools:_this.availableAnnotationTools,showEdit:annotationProperties.annotationCreation,showStrokeStyle:showStrokeStyle,showStrokeColor:showStrokeColor,showFillColor:showFillColor,showRefresh:annotationProperties.annotationRefresh})).appendTo(this.container.find(".mirador-osd-annotation-controls")),this.annotationElement.hide(),this.setQtips(this.container.find(".mirador-osd-annotation-controls")),this.setBorderFillColorPickers()),showStrokeStyle&&this.addStrokeStylePicker(),this.canvasControls.imageManipulation.manipulationLayer&&(this.manipulationElement=jQuery(this.manipulationTemplate({filtersSupported:Modernizr.cssfilters,showRotate:this.canvasControls.imageManipulation.controls.rotate,showBrightness:this.canvasControls.imageManipulation.controls.brightness,showContrast:this.canvasControls.imageManipulation.controls.contrast,showSaturate:this.canvasControls.imageManipulation.controls.saturate,showGrayscale:this.canvasControls.imageManipulation.controls.grayscale,showInvert:this.canvasControls.imageManipulation.controls.invert})).appendTo(this.container.find(".mirador-manipulation-controls")),this.setQtips(this.container.find(".mirador-manipulation-controls")),this.manipulationElement.hide()),this.bindEvents()},setQtips:function(element){var _this=this;element.find("a").each(function(){jQuery(this).qtip({content:{text:jQuery(this).attr("title")},position:{my:"bottom center",at:"top center",viewport:!0,container:_this.qtipElement},style:{classes:"qtip-dark qtip-shadow qtip-rounded"}})})},addColorPicker:function(selector,options){this.container.find(selector).spectrum(options)},getImagePath:function(imageName){return this.state.getStateProperty("buildPath")+this.state.getStateProperty("imagesPath")+imageName},setBackgroundImage:function(el,imageName){el.css("background-image","url("+this.getImagePath(imageName)+")")},removeBackgroundImage:function(el){el.css("background-image","")},addStrokeStylePicker:function(){this.setBackground.solid(this.container.find(".mirador-line-type .solid")),this.setBackground.dashed(this.container.find(".mirador-line-type .dashed")),this.setBackground.dotdashed(this.container.find(".mirador-line-type .dotdashed"))},setBorderFillColorPickers:function(){var _this=this,defaultBorderColor=_this.state.getStateProperty("drawingToolsSettings").strokeColor,defaultFillColor=_this.state.getStateProperty("drawingToolsSettings").fillColor,defaultAlpha=_this.state.getStateProperty("drawingToolsSettings").fillColorAlpha,colorObj=tinycolor(defaultFillColor);colorObj.setAlpha(defaultAlpha),this.addColorPicker(".borderColorPicker",{showInput:!0,showInitial:!1,showPalette:!0,showButtons:!1,showSelectionPalette:!0,hideAfterPaletteSelect:!0,appendTo:"parent",containerClassName:"borderColorPickerPop"+_this.windowId,preferredFormat:"rgb",hide:function(color){_this.eventEmitter.publish("changeBorderColor."+_this.windowId,color.toHexString()),jQuery(this).spectrum("set",color.toHexString())},move:function(color){_this.eventEmitter.publish("changeBorderColor."+_this.windowId,color.toHexString())},show:function(color){_this.setColorPickerInCanvas(".borderColorPicker")},maxSelectionSize:4,color:defaultBorderColor,palette:[[defaultBorderColor,"black","red","green"],["white","blue","magenta","yellow"]]}),_this.container.find(".borderColorPicker").next(".sp-replacer").prepend("<i class='material-icons'>border_color</i>"),_this.addColorPicker(".fillColorPicker",{showInput:!0,showInitial:!1,showAlpha:!0,showPalette:!0,showButtons:!1,showSelectionPalette:!0,appendTo:"parent",clickoutFiresChange:!0,containerClassName:"fillColorPickerPop"+_this.windowId,preferredFormat:"rgb",hide:function(color){_this.eventEmitter.publish("changeFillColor."+_this.windowId,[color.toHexString(),color.getAlpha()]),jQuery(this).spectrum("set",color)},move:function(color){_this.eventEmitter.publish("changeFillColor."+_this.windowId,[color.toHexString(),color.getAlpha()])},show:function(color){_this.setColorPickerInCanvas(".fillColorPicker")},maxSelectionSize:4,color:colorObj,palette:[[colorObj,"black","red","green"],["white","blue","magenta","yellow"]]}),_this.container.find(".fillColorPicker").next(".sp-replacer").prepend("<i class='material-icons'>format_color_fill</i>")},setColorPickerInCanvas:function(selector){var pickerContainer=this.container.find(selector).siblings(".sp-container").first(),pickerOffset=pickerContainer.offset(),windowWidth=this.state.windowsElements[this.windowId].width();pickerContainer.width()+pickerOffset.left>windowWidth&&pickerContainer.offset({top:pickerOffset.top,left:windowWidth-pickerContainer.width()})},annotationShow:function(){this.annotationElement.fadeIn("150")},annotationHide:function(){this.annotationElement.fadeOut("150")},manipulationShow:function(){this.manipulationElement.fadeIn("150")},manipulationHide:function(){this.manipulationElement.fadeOut("150")},bindEvents:function(){var _this=this;this.container.find(".mirador-line-type").on("mouseenter",function(){return!jQuery(this).hasClass("hud-disabled")&&void _this.container.find(".type-list").stop().slideFadeToggle(300)}),this.container.find(".mirador-line-type").on("mouseleave",function(){return!jQuery(this).hasClass("hud-disabled")&&void _this.container.find(".type-list").stop().slideFadeToggle(300)}),this.container.find(".mirador-line-type").find("ul li").on("click",function(){if(jQuery(this).hasClass("hud-disabled"))return!1;var className=jQuery(this).find("i").attr("class").replace(/fa/,"").replace(/ /,"");_this.removeBackgroundImage(_this.container.find(".mirador-line-type .border-type-image")),_this.setBackground[className](_this.container.find(".mirador-line-type .border-type-image")),_this.eventEmitter.publish("toggleBorderType."+_this.windowId,className)})},annotationTemplate:$.Handlebars.compile(["{{#if showEdit}}",'<a class="mirador-osd-pointer-mode hud-control selected" title="{{t "pointerTooltip"}}">','<i class="fa fa-mouse-pointer"></i>',"</a>","{{#each tools}}",'<a class="mirador-osd-{{this.logoClass}}-mode hud-control mirador-osd-edit-mode" title="{{t this.tooltip}}">','<i class="material-icons">{{this.logoClass}}</i>',"</a>","{{/each}}","{{#if showStrokeStyle}}",'<a class="hud-control hud-dropdown hud-disabled mirador-line-type" aria-label="{{t "borderTypeTooltip"}}" title="{{t "borderTypeTooltip"}}">','<i class="material-icons mirador-border-icon">create</i>','<i class="border-type-image solid"></i>','<i class="fa fa-caret-down dropdown-icon"></i>','<ul class="dropdown type-list">','<li><i class="fa solid"></i> {{t "solid"}}</li>','<li><i class="fa dashed"></i> {{t "dashed"}}</li>','<li><i class="fa dotdashed"></i> {{t "dotDashed"}}</li>',"</ul>","</a>","{{/if}}","{{#if showStrokeColor}}",'<a class="hud-control hud-dropdown hud-disabled mirador-osd-color-picker" title="{{t "borderColorTooltip"}}">','<input type="text" class="borderColorPicker"/>',"</a>","{{/if}}","{{#if showFillColor}}",'<a class="hud-control hud-dropdown hud-disabled mirador-osd-color-picker" title="{{t "fillColorTooltip"}}">','<input type="text" class="fillColorPicker"/>',"</a>","{{/if}}","{{#if showRefresh}}",'<a class="hud-control mirador-osd-refresh-mode">','<i class="fa fa-lg fa-refresh"></i>',"</a>","{{/if}}","{{/if}}"].join("")),manipulationTemplate:$.Handlebars.compile(["{{#if showRotate}}",'<a class="hud-control mirador-osd-rotate-right" title="{{t "rotateRightTooltip"}}">','<i class="fa fa-lg fa-rotate-right"></i>',"</a>",'<a class="hud-control mirador-osd-rotate-left" title="{{t "rotateLeftTooltip"}}">','<i class="fa fa-lg fa-rotate-left"></i>',"</a>","{{/if}}","{{#if filtersSupported}}","{{#if showBrightness}}",'<a class="hud-control mirador-osd-brightness" title="{{t "brightnessTooltip"}}">','<i class="material-icons">wb_sunny</i>','<i class="fa fa-caret-down"></i>','<div class="mirador-osd-brightness-slider mirador-slider"/>',"</a>","{{/if}}","{{#if showContrast}}",'<a class="hud-control mirador-osd-contrast" title="{{t "contrastTooltip"}}">','<i class="material-icons">brightness_6</i>','<i class="fa fa-caret-down"></i>','<div class="mirador-osd-contrast-slider mirador-slider"/>',"</a>","{{/if}}","{{#if showSaturate}}",'<a class="hud-control mirador-osd-saturation" title="{{t "saturationTooltip"}}">','<i class="material-icons">gradient</i>','<i class="fa fa-caret-down"></i>','<div class="mirador-osd-saturation-slider mirador-slider"/>',"</a>","{{/if}}","{{#if showGrayscale}}",'<a class="hud-control mirador-osd-grayscale" title="{{t "grayscaleTooltip"}}">','<i class="material-icons">filter_b_and_w</i>',"</a>","{{/if}}","{{#if showInvert}}",'<a class="hud-control mirador-osd-invert" title="{{t "invertTooltip"}}">','<i class="material-icons">invert_colors</i>',"</a>","{{/if}}",'<a class="hud-control mirador-osd-reset" title="{{t "resetTooltip"}}">','<i class="fa fa-lg fa-refresh"></i>',"</a>","{{/if}}"].join("")),editorTemplate:$.Handlebars.compile(['<div class="mirador-osd-context-controls hud-container">','<a class="mirador-osd-back hud-control" role="button">','<i class="fa fa-lg fa-arrow-left"></i>',"</a>",'<a class="mirador-osd-rect-tool hud-control" role ="buton">','<i class="fa fa-lg fa-pencil-square"></i>',"</a>",'<a class="mirador-osd-rect-tool hud-control" role="button">','<i class="fa fa-lg fa-ellipsis-h"></i>',"</a>",'<a class="mirador-osd-rect-tool hud-control" role="button">','<i class="fa fa-lg fa-gear"></i>',"</a>","</div>"].join(""))}}(Mirador),function($){$.Hud=function(options){jQuery.extend(this,{element:null,windowId:null,annoState:null,annoEndpointAvailable:!1,eventEmitter:null},options),this.init()},$.Hud.prototype={init:function(){this.createStateMachines();var showAnno="undefined"!=typeof this.showAnno?this.showAnno:this.canvasControls.annotations.annotationLayer,showImageControls="undefined"!=typeof this.showImageControls?this.showImageControls:this.canvasControls.imageManipulation.manipulationLayer;this.element=jQuery(this.template({showNextPrev:this.showNextPrev,showBottomPanel:"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable,showAnno:showAnno,showImageControls:showImageControls})).appendTo(this.appendTo),(showAnno||showImageControls)&&(this.contextControls=new $.ContextControls({element:null,container:this.element.find(".mirador-osd-context-controls"),qtipElement:this.qtipElement,mode:"displayAnnotations",windowId:this.windowId,canvasControls:this.canvasControls,annoEndpointAvailable:this.annoEndpointAvailable,availableAnnotationTools:this.availableAnnotationTools,availableAnnotationStylePickers:this.availableAnnotationStylePickers,state:this.state,eventEmitter:this.eventEmitter})),this.listenForActions(),this.bindEvents()},listenForActions:function(){var _this=this;this.eventEmitter.subscribe("DISABLE_TOOLTIPS_BY_CLASS."+this.windowId,function(event,className){_this.element.find(className).qtip("disable")}),this.eventEmitter.subscribe("ENABLE_TOOLTIPS_BY_CLASS."+this.windowId,function(event,className){_this.element.find(className).qtip("enable")}),this.eventEmitter.subscribe("SET_STATE_MACHINE_POINTER."+this.windowId,function(event){"none"===_this.annoState.current?_this.annoState.startup():"off"===_this.annoState.current?_this.annoState.displayOn():_this.annoState.choosePointer()})},bindEvents:function(){},createStateMachines:function(){var _this=this;this.annoState=StateMachine.create({events:[{name:"startup",from:"none",to:"off"},{name:"displayOn",from:"off",to:"pointer"},{name:"displayOff",from:["pointer","shape"],to:"off"},{name:"choosePointer",from:["pointer","shape"],to:"pointer"},{name:"chooseShape",from:"pointer",to:"shape"},{name:"changeShape",from:"shape",to:"shape"},{name:"refresh",from:"pointer",to:"pointer"},{name:"refresh",from:"shape",to:"shape"}],callbacks:{onstartup:function(event,from,to){_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},ondisplayOn:function(event,from,to){_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-annotations-layer","selected"]),_this.annoEndpointAvailable&&_this.contextControls.annotationShow(),_this.eventEmitter.publish("modeChange."+_this.windowId,"displayAnnotations"),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("DISABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("DEFAULT_CURSOR."+_this.windowId),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},ondisplayOff:function(event,from,to){_this.annoEndpointAvailable&&(_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("CANCEL_ACTIVE_ANNOTATIONS."+_this.windowId),_this.contextControls.annotationHide()),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-annotations-layer","selected"]),_this.eventEmitter.publish("modeChange."+_this.windowId,"default"),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onchoosePointer:function(event,from,to){_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("DISABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("modeChange."+_this.windowId,"displayAnnotations"),_this.eventEmitter.publish("DEFAULT_CURSOR."+_this.windowId),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onchooseShape:function(event,from,to,shape){_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("ENABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-"+shape+"-mode","selected"]),_this.eventEmitter.publish("modeChange."+_this.windowId,"creatingAnnotation"),_this.eventEmitter.publish("CROSSHAIR_CURSOR."+_this.windowId),
86
+ _this.eventEmitter.publish("toggleDrawingTool."+_this.windowId,shape),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onchangeShape:function(event,from,to,shape){_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-pointer-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-osd-edit-mode","selected"]),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".hud-dropdown","hud-disabled"]),_this.eventEmitter.publish("ENABLE_TOOLTIPS_BY_CLASS."+_this.windowId,".hud-dropdown"),_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-osd-"+shape+"-mode","selected"]),_this.eventEmitter.publish("CROSSHAIR_CURSOR."+_this.windowId),_this.eventEmitter.publish("toggleDrawingTool."+_this.windowId,shape),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,annotationState:to})},onrefresh:function(event,from,to){}}}),this.manipulationState=StateMachine.create({events:[{name:"startup",from:"none",to:"manipulationOff"},{name:"displayOn",from:"manipulationOff",to:"manipulationOn"},{name:"displayOff",from:"manipulationOn",to:"manipulationOff"}],callbacks:{onstartup:function(event,from,to){_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,manipulationState:to})},ondisplayOn:function(event,from,to){_this.eventEmitter.publish("HUD_ADD_CLASS."+_this.windowId,[".mirador-manipulation-toggle","selected"]),_this.contextControls.manipulationShow(),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,manipulationState:to})},ondisplayOff:function(event,from,to){_this.contextControls.manipulationHide(),_this.eventEmitter.publish("HUD_REMOVE_CLASS."+_this.windowId,[".mirador-manipulation-toggle","selected"]),_this.eventEmitter.publish("windowUpdated",{id:_this.windowId,manipulationState:to})}}})},template:$.Handlebars.compile(['<div class="mirador-hud">',"{{#if showNextPrev}}",'<a class="mirador-osd-previous hud-control ">','<i class="fa fa-3x fa-chevron-left "></i>',"</a>","{{/if}}",'<div class="mirador-osd-context-controls hud-container">',"{{#if showAnno}}",'<div class="mirador-osd-annotation-controls">','<a class="mirador-osd-annotations-layer hud-control" role="button" title="{{t "annotationTooltip"}}" aria-label="{{t "annotationTooltip"}}">','<i class="fa fa-lg fa-comments"></i>',"</a>","</div>","{{/if}}","{{#if showImageControls}}",'<div class="mirador-manipulation-controls">','<a class="mirador-manipulation-toggle hud-control" role="button" title="{{t "imageManipulationTooltip"}}" aria-label="{{t "imageManipulationTooltip"}}">','<i class="material-icons">tune</i>',"</a>","</div>","{{/if}}","</div>","{{#if showNextPrev}}",'<a class="mirador-osd-next hud-control ">','<i class="fa fa-3x fa-chevron-right"></i>',"</a>","{{/if}}","{{#if showBottomPanel}}",'<a class="mirador-osd-toggle-bottom-panel hud-control" role="button" aria-label="Toggle Bottom Panel">','<i class="fa fa-2x fa-ellipsis-h"></i>',"</a>","{{/if}}",'<div class="mirador-pan-zoom-controls hud-control">','<a class="mirador-osd-up hud-control" role="button" aria-label="Move image up">','<i class="fa fa-chevron-circle-up"></i>',"</a>",'<a class="mirador-osd-right hud-control" role="button" aria-label="Move image right">','<i class="fa fa-chevron-circle-right"></i>',"</a>",'<a class="mirador-osd-down hud-control" role="button" aria-label="Move image down">','<i class="fa fa-chevron-circle-down"></i>',"</a>",'<a class="mirador-osd-left hud-control" role="button" aria-label="Move image left">','<i class="fa fa-chevron-circle-left"></i>',"</a>",'<a class="mirador-osd-zoom-in hud-control" role="button" aria-label="Zoom in">','<i class="fa fa-plus-circle"></i>',"</a>",'<a class="mirador-osd-zoom-out hud-control" role="button" aria-label="Zoom out">','<i class="fa fa-minus-circle"></i>',"</a>",'<a class="mirador-osd-go-home hud-control" role="button" aria-label="Reset image bounds">','<i class="fa fa-home"></i>',"</a>","</div>","</div>"].join(""))}}(Mirador),function($){$.ImageView=function(options){jQuery.extend(this,{currentImg:null,windowId:null,currentImgIndex:0,canvasID:null,imagesList:[],element:null,elemOsd:null,manifest:null,osd:null,osdOptions:{osdBounds:null,zoomLevel:null},osdCls:"mirador-osd",elemAnno:null,annoCls:"annotation-canvas",annotationsLayer:null,forceShowControls:!1,eventEmitter:null},options),this.init()},$.ImageView.prototype={init:function(){var _this=this;null!==this.canvasID&&(this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID)),this.osdOptions||(this.osdOptions={osdBounds:null,zoomLevel:null}),this.currentImg=this.imagesList[this.currentImgIndex],this.element=jQuery(this.template()).appendTo(this.appendTo),this.elemAnno=jQuery("<div/>").addClass(this.annoCls).appendTo(this.element),this.createOpenSeadragonInstance($.Iiif.getImageUrl(this.currentImg)),_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:[this.canvasID]});var allTools=$.getTools(this.state.getStateProperty("drawingToolsSettings"));this.availableAnnotationTools=[];for(var i=0;i<this.state.getStateProperty("availableAnnotationDrawingTools").length;i++)for(var j=0;j<allTools.length;j++)if(this.state.getStateProperty("availableAnnotationDrawingTools")[i]==allTools[j].name){var values={};values.logoClass=allTools[j].logoClass,values.tooltip=allTools[j].tooltip,this.availableAnnotationTools.push(values)}this.hud=new $.Hud({appendTo:this.element,qtipElement:this.qtipElement,bottomPanelAvailable:this.bottomPanelAvailable,windowId:this.windowId,canvasControls:this.canvasControls,annoEndpointAvailable:this.annoEndpointAvailable,showNextPrev:1!==this.imagesList.length,availableAnnotationStylePickers:this.state.getStateProperty("availableAnnotationStylePickers"),availableAnnotationTools:this.availableAnnotationTools,state:this.state,eventEmitter:this.eventEmitter}),this.bindEvents(),this.listenForActions(),"undefined"==typeof this.bottomPanelAvailable||this.bottomPanelAvailable?_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,null):_this.eventEmitter.publish("SET_BOTTOM_PANEL_VISIBILITY."+this.windowId,!1)},template:$.Handlebars.compile(['<div class="image-view">',"</div>"].join("")),listenForActions:function(){var _this=this,firstCanvasId=_this.imagesList[0]["@id"],lastCanvasId=_this.imagesList[_this.imagesList.length-1]["@id"];_this.eventEmitter.subscribe("bottomPanelSet."+_this.windowId,function(event,visible){var dodgers=_this.element.find(".mirador-osd-toggle-bottom-panel, .mirador-pan-zoom-controls"),arrows=_this.element.find(".mirador-osd-next, .mirador-osd-previous");visible===!0?(dodgers.addClass("bottom-panel-open"),arrows.addClass("bottom-panel-open")):(dodgers.removeClass("bottom-panel-open"),arrows.removeClass("bottom-panel-open"))}),_this.eventEmitter.subscribe("fitBounds."+_this.windowId,function(event,bounds){var rect=_this.osd.viewport.imageToViewportRectangle(Number(bounds.x),Number(bounds.y),Number(bounds.width),Number(bounds.height));_this.osd.viewport.fitBoundsWithConstraints(rect,!1)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasId){canvasId===firstCanvasId?(_this.element.find(".mirador-osd-previous").hide(),_this.element.find(".mirador-osd-next").show()):canvasId===lastCanvasId?(_this.element.find(".mirador-osd-next").hide(),_this.element.find(".mirador-osd-previous").show()):(_this.element.find(".mirador-osd-next").show(),_this.element.find(".mirador-osd-previous").show())}),_this.eventEmitter.subscribe("HUD_REMOVE_CLASS."+_this.windowId,function(event,elementSelector,className){_this.element.find(elementSelector).removeClass(className)}),_this.eventEmitter.subscribe("HUD_ADD_CLASS."+_this.windowId,function(event,elementSelector,className){_this.element.find(elementSelector).addClass(className)}),_this.eventEmitter.subscribe("HUD_FADE_IN."+_this.windowId,function(event,elementSelector,duration){_this.element.find(elementSelector).fadeIn(duration)}),_this.eventEmitter.subscribe("HUD_FADE_OUT."+_this.windowId,function(event,elementSelector,duration,complete){_this.element.find(elementSelector).fadeOut(duration,complete)}),_this.eventEmitter.subscribe("DEFAULT_CURSOR."+_this.windowId,function(event){jQuery(_this.osd.canvas).css("cursor","default")}),_this.eventEmitter.subscribe("CROSSHAIR_CURSOR."+_this.windowId,function(event){jQuery(_this.osd.canvas).css("cursor","crosshair")}),_this.eventEmitter.subscribe("POINTER_CURSOR."+_this.windowId,function(event){jQuery(_this.osd.canvas).css("cursor","pointer")})},bindEvents:function(){function setFilterCSS(){var filterCSS=jQuery.map(filterValues,function(value,key){return value}).join(" "),osdCanvas=jQuery(_this.osd.drawer.canvas);osdCanvas.css({filter:filterCSS,"-webkit-filter":filterCSS,"-moz-filter":filterCSS,"-o-filter":filterCSS,"-ms-filter":filterCSS})}function resetImageManipulationControls(){_this.osd&&_this.osd.viewport.setRotation(0),filterValues.brightness="brightness(100%)",_this.element.find(".mirador-osd-brightness-slider").slider("option","value",100),_this.element.find(".mirador-osd-brightness-slider").find(".percent").text("100%"),filterValues.contrast="contrast(100%)",_this.element.find(".mirador-osd-contrast-slider").slider("option","value",100),_this.element.find(".mirador-osd-contrast-slider").find(".percent").text("100%"),filterValues.saturate="saturate(100%)",_this.element.find(".mirador-osd-saturation-slider").slider("option","value",100),_this.element.find(".mirador-osd-saturation-slider").find(".percent").text("100%"),filterValues.grayscale="grayscale(0%)",_this.element.find(".mirador-osd-grayscale").removeClass("selected"),filterValues.invert="invert(0%)",_this.element.find(".mirador-osd-invert").removeClass("selected"),setFilterCSS()}var _this=this;this.element.find(".mirador-osd-next").on("click",function(){_this.next()}),this.element.find(".mirador-osd-previous").on("click",function(){_this.previous()}),this.element.find(".mirador-osd-annotations-layer").on("click",function(){"none"===_this.hud.annoState.current&&_this.hud.annoState.startup(this),"off"===_this.hud.annoState.current?(_this.hud.annoState.displayOn(this),_this.annotationState="on"):(_this.forceShowControls=!1,_this.hud.annoState.displayOff(this),_this.annotationState="off")}),this.element.find(".mirador-manipulation-toggle").on("click",function(){"none"===_this.hud.manipulationState.current&&_this.hud.manipulationState.startup(this),"manipulationOff"===_this.hud.manipulationState.current?_this.hud.manipulationState.displayOn(this):_this.hud.manipulationState.displayOff(this)}),this.element.find(".mirador-osd-go-home").on("click",function(){_this.osd.viewport.goHome()}),this.element.find(".mirador-osd-up").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,-panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-right").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-down").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(0,panBy.y)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-left").on("click",function(){var panBy=_this.getPanByValue();_this.osd.viewport.panBy(new OpenSeadragon.Point(-panBy.x,0)),_this.osd.viewport.applyConstraints()}),this.element.find(".mirador-osd-zoom-in").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(osd.zoomPerClick/1),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-zoom-out").on("click",function(){var osd=_this.osd;osd.viewport&&(osd.viewport.zoomBy(1/osd.zoomPerClick),osd.viewport.applyConstraints())}),this.element.find(".mirador-osd-toggle-bottom-panel").on("click",function(){_this.eventEmitter.publish("TOGGLE_BOTTOM_PANEL_VISIBILITY."+_this.windowId)}),this.element.find(".mirador-osd-edit-mode").on("click",function(){var shape=jQuery(this).find(".material-icons").html();"pointer"===_this.hud.annoState.current?_this.hud.annoState.chooseShape(shape):_this.hud.annoState.changeShape(shape),_this.forceShowControls=!0,_this.element.find(".hud-control").stop(!0,!0).removeClass("hidden",_this.state.getStateProperty("fadeDuration"))}),this.element.find(".mirador-osd-pointer-mode").on("click",function(){"shape"===_this.hud.annoState.current&&(_this.hud.annoState.choosePointer(),_this.forceShowControls=!1)}),this.element.find(".mirador-osd-refresh-mode").on("click",function(){_this.eventEmitter.publish("updateAnnotationList."+_this.windowId)});var filterValues={brightness:"brightness(100%)",contrast:"contrast(100%)",saturate:"saturate(100%)",grayscale:"grayscale(0%)",invert:"invert(0%)"};this.element.find(".mirador-osd-rotate-right").on("click",function(){if(_this.osd){var currentRotation=_this.osd.viewport.getRotation();_this.osd.viewport.setRotation(currentRotation+90)}}),this.element.find(".mirador-osd-rotate-left").on("click",function(){if(_this.osd){var currentRotation=_this.osd.viewport.getRotation();_this.osd.viewport.setRotation(currentRotation-90)}}),this.element.find(".mirador-osd-brightness-slider").slider({orientation:"vertical",range:"min",min:0,max:200,value:100,create:function(event,ui){var v=jQuery(this).slider("value"),span=jQuery('<span class="percent">').text(v+"%");jQuery(this).find(".ui-slider-handle").append(span)},slide:function(event,ui){filterValues.brightness="brightness("+ui.value+"%)",setFilterCSS(),jQuery(this).find(".percent").text(ui.value+"%")}}).hide(),this.element.find(".mirador-osd-brightness").on("mouseenter",function(){_this.element.find(".mirador-osd-brightness-slider").stop(!0,!0).show()}).on("mouseleave",function(){_this.element.find(".mirador-osd-brightness-slider").stop(!0,!0).hide()}),this.element.find(".mirador-osd-contrast-slider").slider({orientation:"vertical",range:"min",min:0,max:200,value:100,create:function(event,ui){var v=jQuery(this).slider("value"),span=jQuery('<span class="percent">').text(v+"%");jQuery(this).find(".ui-slider-handle").append(span)},slide:function(event,ui){filterValues.contrast="contrast("+ui.value+"%)",setFilterCSS(),jQuery(this).find(".percent").text(ui.value+"%")}}).hide(),this.element.find(".mirador-osd-contrast").on("mouseenter",function(){_this.element.find(".mirador-osd-contrast-slider").stop(!0,!0).show()}).on("mouseleave",function(){_this.element.find(".mirador-osd-contrast-slider").stop(!0,!0).hide()}),this.element.find(".mirador-osd-saturation-slider").slider({orientation:"vertical",range:"min",min:0,max:200,value:100,create:function(event,ui){var v=jQuery(this).slider("value"),span=jQuery('<span class="percent">').text(v+"%");jQuery(this).find(".ui-slider-handle").append(span)},slide:function(event,ui){filterValues.saturate="saturate("+ui.value+"%)",setFilterCSS(),jQuery(this).find(".percent").text(ui.value+"%")}}).hide(),this.element.find(".mirador-osd-saturation").on("mouseenter",function(){_this.element.find(".mirador-osd-saturation-slider").stop(!0,!0).show()}).on("mouseleave",function(){_this.element.find(".mirador-osd-saturation-slider").stop(!0,!0).hide()}),this.element.find(".mirador-osd-grayscale").on("click",function(){jQuery(this).hasClass("selected")?(filterValues.grayscale="grayscale(0%)",jQuery(this).removeClass("selected")):(filterValues.grayscale="grayscale(100%)",jQuery(this).addClass("selected")),setFilterCSS()}),this.element.find(".mirador-osd-invert").on("click",function(){jQuery(this).hasClass("selected")?(filterValues.invert="invert(0%)",jQuery(this).removeClass("selected")):(filterValues.invert="invert(100%)",jQuery(this).addClass("selected")),setFilterCSS()}),this.element.find(".mirador-osd-reset").on("click",function(){resetImageManipulationControls()}),this.eventEmitter.subscribe("resetImageManipulationControls."+this.windowId,function(){resetImageManipulationControls()})},getPanByValue:function(){var bounds=this.osd.viewport.getBounds(!0),panBy={x:.5*bounds.width,y:.5*bounds.height};return panBy},setBounds:function(){var _this=this;this.osdOptions.osdBounds=this.osd.viewport.getBounds(!0),_this.eventEmitter.publish("imageBoundsUpdated",{id:_this.windowId,osdBounds:{x:_this.osdOptions.osdBounds.x,y:_this.osdOptions.osdBounds.y,width:_this.osdOptions.osdBounds.width,height:_this.osdOptions.osdBounds.height}});var rectangle=this.osd.viewport.viewportToImageRectangle(this.osdOptions.osdBounds);_this.eventEmitter.publish("imageRectangleUpdated",{id:_this.windowId,osdBounds:{x:Math.round(rectangle.x),y:Math.round(rectangle.y),width:Math.round(rectangle.width),height:Math.round(rectangle.height)}})},toggle:function(stateValue){stateValue?this.show():this.hide()},hide:function(){jQuery(this.element).hide({effect:"fade",duration:300,easing:"easeOutCubic"})},show:function(){jQuery(this.element).show({effect:"fade",duration:300,easing:"easeInCubic",complete:function(){jQuery(this).css("display","block")}})},adjustWidth:function(className,hasClass){var _this=this;hasClass?_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,className):_this.eventEmitter.publish("ADD_CLASS."+this.windowId,className)},adjustHeight:function(className,hasClass){hasClass?this.element.removeClass(className):this.element.addClass(className)},createOpenSeadragonInstance:function(imageUrl){var infoJsonUrl=imageUrl+"/info.json",uniqueID=$.genUUID(),osdID="mirador-osd-"+uniqueID,_this=this;this.element.find("."+this.osdCls).remove(),jQuery.getJSON(infoJsonUrl).done(function(infoJson,status,jqXHR){_this.elemOsd=jQuery("<div/>").addClass(_this.osdCls).attr("id",osdID).appendTo(_this.element),_this.osd=$.OpenSeadragon({id:osdID,tileSources:infoJson,uniqueID:uniqueID}),_this.osd.addHandler("zoom",$.debounce(function(){var point={x:-1e7,y:-1e7};_this.eventEmitter.publish("updateTooltips."+_this.windowId,[point,point])},30)),_this.osd.addHandler("pan",$.debounce(function(){var point={x:-1e7,y:-1e7};_this.eventEmitter.publish("updateTooltips."+_this.windowId,[point,point])},30)),_this.osd.addHandler("open",function(){if(_this.eventEmitter.publish("osdOpen."+_this.windowId),_this.osdOptions.osdBounds){var rect=new OpenSeadragon.Rect(_this.osdOptions.osdBounds.x,_this.osdOptions.osdBounds.y,_this.osdOptions.osdBounds.width,_this.osdOptions.osdBounds.height);_this.osd.viewport.fitBounds(rect,!0)}else _this.setBounds();_this.addAnnotationsLayer(_this.elemAnno);var originalState=_this.hud.annoState.current,selected=_this.element.find(".mirador-osd-edit-mode.selected"),shape=null;selected&&(shape=selected.find(".material-icons").html()),"none"===originalState?_this.hud.annoState.startup():"off"===originalState||"off"===_this.annotationState||_this.hud.annoState.displayOff(),"pointer"===originalState||"on"===_this.annotationState?_this.hud.annoState.displayOn():"shape"===originalState&&(_this.hud.annoState.displayOn(),_this.hud.annoState.chooseShape(shape)),_this.osd.addHandler("zoom",$.debounce(function(){_this.setBounds()},500)),_this.osd.addHandler("pan",$.debounce(function(){_this.setBounds()},500))})})},addAnnotationsLayer:function(element){var _this=this;_this.annotationsLayer=new $.AnnotationsLayer({state:_this.state,annotationsList:_this.state.getWindowAnnotationsList(_this.windowId)||[],viewer:_this.osd,windowId:_this.windowId,element:element,eventEmitter:_this.eventEmitter})},updateImage:function(canvasID){var _this=this;this.canvasID!==canvasID?(this.canvasID=canvasID,this.currentImgIndex=$.getImageIndexById(this.imagesList,canvasID),this.currentImg=this.imagesList[this.currentImgIndex],this.osdOptions={osdBounds:null,zoomLevel:null},this.eventEmitter.publish("resetImageManipulationControls."+this.windowId),this.osd.close(),this.createOpenSeadragonInstance($.Iiif.getImageUrl(this.currentImg)),_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:[canvasID]})):_this.eventEmitter.publish("UPDATE_FOCUS_IMAGES."+this.windowId,{array:[canvasID]})},next:function(){var _this=this,next=this.currentImgIndex+1;next<this.imagesList.length&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[next]["@id"])},previous:function(){var _this=this,prev=this.currentImgIndex-1;prev>=0&&_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+this.windowId,this.imagesList[prev]["@id"])}}}(Mirador),function($){$.LayersTab=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,visible:null,state:null,eventEmitter:null},options),this.init()},$.LayersTab.prototype={init:function(){this.windowId=this.windowId,this.localState({id:"layersTab",visible:this.visible,selectedList:null,empty:!0},!0),this.listenForActions(),this.render(this.localState()),this.loadTabComponents(),this.bindEvents()},localState:function(state,initial){var _this=this;return arguments.length?(this.layerTabState=state,initial||_this.eventEmitter.publish("layersTabStateUpdated."+this.windowId,this.layerTabState),this.layerTabState):this.layerTabState},loadTabComponents:function(){},tabStateUpdated:function(visible){var localState=this.localState();localState.visible=!localState.visible,this.localState(localState)},toggle:function(){},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("layersTabStateUpdated."+_this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("tabStateUpdated."+_this.windowId,function(_,data){_this.tabStateUpdated(data.layersTab)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasID){})},bindEvents:function(){},render:function(state){var _this=this,templateData={};this.element&&_this.appendTo.find(".layersPanel").remove(),this.element=jQuery(_this.template(templateData)).appendTo(_this.appendTo),_this.bindEvents(),state.visible?this.element.show():this.element.hide()},template:$.Handlebars.compile(['<div class="layersPanel">',"</div>"].join(""))}}(Mirador),function($){$.MetadataView=function(options){jQuery.extend(this,{manifest:null,element:null,metadataTypes:null,metadataListingCls:"metadata-listing"},options),this.init()},$.MetadataView.prototype={init:function(){var _this=this,tplData={metadataListingCls:this.metadataListingCls};if(_this.manifest=_this.manifest.jsonLd,this.metadataTypes={},this.metadataTypes.details=_this.getMetadataDetails(_this.manifest),this.metadataTypes.rights=_this.getMetadataRights(_this.manifest),this.metadataTypes.links=_this.getMetadataLinks(_this.manifest),jQuery.each(this.metadataTypes,function(metadataKey,metadataValues){tplData[metadataKey]=[],jQuery.each(metadataValues,function(idx,itm){"object"==typeof itm.value&&(itm.value=_this.stringifyObject(itm.value)),"string"==typeof itm.value&&""!==itm.value&&tplData[metadataKey].push({label:_this.extractLabelFromAttribute(itm.label),value:"links"===metadataKey?itm.value:_this.addLinksToUris(itm.value)})})}),_this.manifest.logo){var logo="";"string"==typeof _this.manifest.logo?logo=_this.manifest.logo:"undefined"!=typeof _this.manifest.logo["@id"]&&(logo=_this.manifest.logo["@id"]),tplData.logo=logo}this.element=jQuery(this.template(tplData)).appendTo(this.appendTo),this.bindEvents()},stringifyObject:function(obj,nestingMargin){var str,_this=this,first=!0,increment=15,delimiter="<br/>";if(obj instanceof RegExp)return"/"+obj.source+"/";if("undefined"==typeof nestingMargin&&(nestingMargin=0),obj instanceof Array)return str="[ ",jQuery.each(obj,function(i,item){str+=(0===i?"":", ")+_this.stringifyObject(item,nestingMargin+increment)}),str+" ]";if("object"==typeof obj&&"sc:Collection"===obj["@type"]){var collectionUrl=obj["@id"],collectionLabel=obj.label||collectionUrl;return'<a href="'+collectionUrl+'" target="_blank">'+collectionLabel+"</a>"}if("object"==typeof obj){str='<div style="margin-left:'+nestingMargin+'px">';for(var i in obj)obj.hasOwnProperty(i)&&(str+=(first?"":delimiter)+i+": "+_this.stringifyObject(obj[i],nestingMargin+increment),first=!1);return str+"</div>"}return obj.toString()},stringifyRelated:function(obj){var str,next,label,format,_this=this;return obj instanceof Array?(str="",jQuery.each(obj,function(i,item){next=_this.stringifyRelated(item),""!==next&&(str+=(0===i?"":"<br/>")+next)}),str):"object"==typeof obj&&"@id"in obj?(label="label"in obj?obj.label:obj["@id"],format="format"in obj&&"text/html"!==obj.format?"("+obj.format+")":"",'<a href="'+obj["@id"]+'" target="_blank">'+label+"</a> "+format):_this.addLinksToUris(obj.toString())},getMetadataDetails:function(jsonLd){var mdList=[{label:"label",value:"<b>"+($.JsonLd.getTextValue(jsonLd.label)||"")+"</b>"},{label:"description",value:$.JsonLd.getTextValue(jsonLd.description)||""}];return jsonLd.metadata&&(value="",label="",jQuery.each(jsonLd.metadata,function(index,item){label=$.JsonLd.getTextValue(item.label),value=$.JsonLd.getTextValue(item.value),mdList.push({label:label,value:value})})),mdList},getMetadataRights:function(jsonLd){return[{label:i18next.t("license"),value:jsonLd.license||""},{label:i18next.t("attribution"),value:$.JsonLd.getTextValue(jsonLd.attribution)||""}]},getMetadataLinks:function(jsonLd){return[{label:i18next.t("related"),value:this.stringifyRelated(jsonLd.related||"")},{label:i18next.t("seeAlso"),value:this.stringifyRelated(jsonLd.seeAlso||"")},{label:i18next.t("within"),value:this.getWithin(jsonLd.within||"")}]},getWithin:function(within){if("object"==typeof within&&"sc:Collection"===within["@type"]){var collectionUrl=within["@id"],collectionLabel=within.label||collectionUrl;return'<a href="'+collectionUrl+'" target="_blank">'+collectionLabel+"</a>"}return within instanceof Array?within.map(this.getWithin).join("<br/>"):this.stringifyObject(within)},extractLabelFromAttribute:function(attr){var label=attr;return label=label.replace(/^@/,""),label=label.replace(/\s{2,}/g," ")},bindEvents:function(){},toggle:function(stateValue){stateValue?this.show():this.hide()},show:function(){var element=jQuery(this.element);this.panel&&(element=element.parent()),element.show({effect:"slide",direction:"right",duration:300,easing:"swing"})},hide:function(){var element=jQuery(this.element);this.panel&&(element=element.parent()),element.hide({effect:"slide",direction:"right",duration:300,easing:"swing"})},addLinksToUris:function(text){var matches,parsedTextWithLinks,regexUrl=/(http|ftp|https):\/\/[\w\-]+(\.[\w\-]+)+([\w.,@?\^=%&amp;:\/~+#\-]*[\w@?\^=%&amp;\/~+#\-])?/gi,textWithLinks=text;return"string"==typeof text&&(textWithLinks.indexOf("<a ")===-1?(matches=text.match(regexUrl),matches&&jQuery.each(matches,function(index,match){textWithLinks=textWithLinks.replace(match,'<a href="'+match+'" target="_blank">'+match+"</a>")})):(parsedTextWithLinks=jQuery("<div />").append(textWithLinks),jQuery(parsedTextWithLinks[0]).find("a").attr("target","_blank"),textWithLinks=parsedTextWithLinks[0].innerHTML)),textWithLinks},template:$.Handlebars.compile(['<div class="sub-title">{{t "details"}}:</div>','<div class="{{metadataListingCls}}">',"{{#each details}}",'<div class="metadata-item"><div class="metadata-label">{{label}}:</div><div class="metadata-value">{{{value}}}</div></div>',"{{/each}}","</div>",'<div class="sub-title">{{t "rights"}}:</div>',"{{#if rights}}",'<div class="{{metadataListingCls}}">',"{{#each rights}}",'<div class="metadata-item"><div class="metadata-label">{{label}}:</div><div class="metadata-value">{{{value}}}</div></div>',"{{/each}}","{{#if logo}}",'<div class="metadata-item"><div class="metadata-label">{{t "logo"}}:</div><img class="metadata-logo" src="{{logo}}"/></div>',"{{/if}}","</div>","{{else}}",'<div class="{{metadataListingCls}}">','<div class="metadata-item"><div class="metadata-label">{{t "rightsStatus"}}:</div><div class="metadata-value">{{t "unspecified"}}</div></div>',"</div>","{{/if}}","{{#if links}}",'<div class="sub-title">{{t "links"}}:</div>','<div class="{{metadataListingCls}}">',"{{#each links}}",'<div class="metadata-item"><div class="metadata-label">{{label}}:</div><div class="metadata-value">{{{value}}}</div></div>',"{{/each}}","</dl>","{{/if}}"].join(""),{noEscape:!0})}}(Mirador),function($){$.ScrollView=function(options){jQuery.extend(this,{currentImgIndex:0,canvasID:null,focusImages:[],manifest:null,element:null,imagesList:[],appendTo:null,thumbInfo:{thumbsHeight:150,listingCssCls:"listing-thumbs",thumbnailCls:"thumbnail-view"},windowId:null,panel:!1,lazyLoadingFactor:1.5},options),jQuery.extend($.ScrollView.prototype,$.ThumbnailsView.prototype),this.init()}}(Mirador),function($){$.SidePanel=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,manifest:null,panelState:{},tocTabAvailable:!1,annotationsTabAvailable:!1,layersTabAvailable:!1,toolsTabAvailable:!1,hasStructures:!1,state:null,eventEmitter:null},options),this.init()},$.SidePanel.prototype={init:function(){var _this=this;this.updateState({tabs:[{name:"toc",options:{available:_this.tocTabAvailable,id:"tocTab",label:"Index"}},{name:"layers",options:{available:_this.layersTabAvailable,id:"layersTab",label:"Layers"}}],width:280,open:!0},!0),this.listenForActions(),this.render(this.updateState()),this.loadSidePanelComponents()},loadSidePanelComponents:function(){var _this=this;new $.Tabs({windowId:this.windowId,appendTo:this.appendTo,tabs:this.panelState.tabs,hasStructures:this.hasStructures,eventEmitter:this.eventEmitter}),this.tocTabAvailable&&new $.TableOfContents({structures:this.manifest.getStructures(),appendTo:this.element.find(".tabContentArea"),windowId:this.windowId,canvasID:this.canvasID,manifestVersion:this.manifest.getVersion(),eventEmitter:this.eventEmitter}),_this.annotationsTabAvailable&&new $.AnnotationsTab({manifest:_this.manifest,windowId:this.windowId,appendTo:_this.element.find(".tabContentArea"),state:_this.state,eventEmitter:_this.eventEmitter}),_this.layersTabAvailable&&new $.LayersTab({manifest:_this.manifest,windowId:this.windowId,appendTo:_this.element.find(".tabContentArea"),canvasID:this.canvasID,state:_this.state,eventEmitter:_this.eventEmitter})},update:function(name,availability){var updatedState=this.panelState;jQuery.each(updatedState.tabs,function(index,value){value.name===name&&(value.options.available=availability)}),this.updateState(updatedState)},updateState:function(newState,initial){var _this=this;return arguments.length?(jQuery.extend(!0,this.panelState,newState),initial||_this.eventEmitter.publish("sidePanelStateUpdated."+this.windowId,this.panelState),this.panelState):this.panelState},panelToggled:function(){var currentState=this.updateState(),open=!currentState.open;currentState.open=open,this.updateState(currentState)},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("sidePanelStateUpdated."+this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("sidePanelResized",function(){}),_this.eventEmitter.subscribe("sidePanelToggled."+this.windowId,function(){_this.panelToggled()}),_this.eventEmitter.subscribe("annotationListLoaded."+_this.windowId,function(event){var windowObject=_this.state.getWindowObjectById(_this.windowId);windowObject.annotationsAvailable[windowObject.viewType]&&_this.state.getWindowAnnotationsList(_this.windowId).length>0&&_this.update("annotations",!0)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,newCanvasId){_this.canvasID=newCanvasId})},render:function(renderingData){var _this=this;if(!this.element)return this.element=this.appendTo,void jQuery(_this.template(renderingData)).appendTo(_this.appendTo)},template:$.Handlebars.compile(['<div class="tabContentArea">','<ul class="tabGroup">',"</ul>","</div>"].join("")),toggle:function(enableSidePanel){var _this=this;enableSidePanel?(jQuery(this.appendTo).show({effect:"fade",duration:300,easing:"easeInCubic"}),_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,"focus-max-width"),_this.eventEmitter.publish("SHOW_ICON_TOC."+this.windowId)):(jQuery(this.appendTo).hide(),_this.eventEmitter.publish("ADD_CLASS."+this.windowId,"focus-max-width"),_this.eventEmitter.publish("HIDE_ICON_TOC."+this.windowId));
87
+ }}}(Mirador),function($){$.WidgetStatusBar=function(options){jQuery.extend(!0,this,{},$.DEFAULT_SETTINGS,options)},$.WidgetStatusBar.prototype={}}(Mirador),function($){$.Tabs=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,windowId:null,tabState:{},tabs:[],eventEmitter:null},options),this.init()},$.Tabs.prototype={init:function(){this.state({tabs:this.tabs,selectedTabIndex:0},!0),this.listenForActions(),this.render(this.state()),this.bindEvents()},state:function(state,initial){var _this=this;return arguments.length?(jQuery.extend(!0,this.tabState,state),initial||_this.eventEmitter.publish("tabStateUpdated."+this.windowId,this.tabState),this.tabState):this.tabState},tabSelected:function(index){var state=this.state();state.selectedTabIndex=index,this.state(state)},getTemplateData:function(){return{annotationsTab:this.state().annotationsTab,tocTab:this.state().tocTab}},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("tabStateUpdated."+this.windowId,function(_,data){_this.render(data)}),_this.eventEmitter.subscribe("tabSelected."+this.windowId,function(_,data){_this.tabSelected(data)}),_this.eventEmitter.subscribe("tabFocused.",function(){})},bindEvents:function(){var _this=this;this.element.find(".tab").on("click",function(event){_this.eventEmitter.publish("tabSelected."+_this.windowId,jQuery(this).index())})},render:function(renderingData){var _this=this;if(!this.element){var tabs=jQuery.grep(renderingData.tabs,function(value,index){return value.options.available});return renderingData.tabs=tabs,1===renderingData.tabs.length&&("toc"!==renderingData.tabs[0].name||_this.hasStructures||_this.eventEmitter.publish("sidePanelVisibilityByTab."+_this.windowId,!1),renderingData.tabs=[]),void(this.element=jQuery(_this.template(renderingData)).prependTo(_this.appendTo))}this.element.find(".tab").removeClass("selected");var tabClass="."+renderingData.tabs[renderingData.selectedTabIndex].options.id;this.element.find(tabClass).addClass("selected")},template:$.Handlebars.compile(['<ul class="tabGroup">',"{{#each tabs}}",'<li class="tab {{this.options.id}} {{#unless @index}}selected{{/unless}}" data-tabId="{{this.options.id}}">',"{{this.options.label}}","</li>","{{/each}}","</ul>"].join("")),toggle:function(){}}}(Mirador),function($){$.ThumbnailsView=function(options){jQuery.extend(this,{currentImgIndex:0,canvasID:null,focusImages:[],manifest:null,element:null,imagesList:[],appendTo:null,thumbInfo:{thumbsHeight:150,listingCssCls:"listing-thumbs",thumbnailCls:"thumbnail-view"},defaultThumbHeight:150,windowId:null,panel:!1,lazyLoadingFactor:1.5,eventEmitter:null},options),this.init()},$.ThumbnailsView.prototype={init:function(){null!==this.canvasID&&(this.currentImgIndex=$.getImageIndexById(this.imagesList,this.canvasID)),this.loadContent(),this.bindEvents(),this.listenForActions()},loadContent:function(){var _this=this,tplData={defaultHeight:this.thumbInfo.thumbsHeight,listingCssCls:this.thumbInfo.listingCssCls,thumbnailCls:this.thumbInfo.thumbnailCls};tplData.thumbs=jQuery.map(this.imagesList,function(canvas,index){if(0===canvas.width)return{};var aspectRatio=canvas.height/canvas.width,width=_this.thumbInfo.thumbsHeight/aspectRatio,thumbnailUrl=$.getThumbnailForCanvas(canvas,width);return{thumbUrl:thumbnailUrl,title:$.JsonLd.getTextValue(canvas.label),id:canvas["@id"],width:width,highlight:_this.currentImgIndex===index?"highlight":""}}),this.element=jQuery(_this.template(tplData)).appendTo(this.appendTo)},updateImage:function(canvasId){this.currentImgIndex=$.getImageIndexById(this.imagesList,canvasId),this.element.find(".highlight").removeClass("highlight"),this.element.find("img[data-image-id='"+canvasId+"']").addClass("highlight"),this.element.find("img[data-image-id='"+canvasId+"']").parent().addClass("highlight")},updateFocusImages:function(focusList){var _this=this;this.element.find(".highlight").removeClass("highlight"),jQuery.each(focusList,function(index,canvasId){_this.element.find("img[data-image-id='"+canvasId+"']").addClass("highlight"),_this.element.find("img[data-image-id='"+canvasId+"']").parent().addClass("highlight")})},currentImageChanged:function(){var scrollPosition,_this=this,target=_this.element.find(".highlight"),windowObject=this.state.getWindowObjectById(this.windowId);scrollPosition=windowObject&&"BookView"===windowObject.viewType?_this.element.scrollLeft()+(target.position().left+(target.next().width()+target.outerWidth())/2)-_this.element.width()/2:_this.element.scrollLeft()+(target.position().left+target.width()/2)-_this.element.width()/2,_this.element.scrollTo(scrollPosition,900)},listenForActions:function(){var _this=this;_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event){_this.currentImageChanged()}),_this.eventEmitter.subscribe("windowResize",$.debounce(function(){_this.loadImages()},100))},bindEvents:function(){var _this=this;_this.element.find("img").on("load",function(){jQuery(this).hide().fadeIn(750,function(){jQuery(this).css("display","block")})}),jQuery(_this.element).scroll(function(){_this.loadImages()}),_this.element.find(".thumbnail-image").on("click",function(){var canvasID=jQuery(this).attr("data-image-id");_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+_this.windowId,canvasID)})},toggle:function(stateValue){stateValue?this.show():this.hide()},loadImages:function(){var _this=this;jQuery.each(_this.element.find("img"),function(key,value){if($.isOnScreen(value,_this.lazyLoadingFactor)&&!jQuery(value).attr("src")){var url=jQuery(value).attr("data");_this.loadImage(value,url)}})},loadImage:function(imageElement,url){var imagePromise=$.createImagePromise(url);imagePromise.done(function(image){jQuery(imageElement).attr("src",image)})},reloadImages:function(newThumbHeight,triggerShow){var _this=this;this.thumbInfo.thumbsHeight=newThumbHeight,jQuery.each(this.imagesList,function(index,image){var aspectRatio=image.height/image.width,width=_this.thumbInfo.thumbsHeight/aspectRatio,newThumbURL=$.getThumbnailForCanvas(image,width),id=image["@id"],imageElement=_this.element.find('img[data-image-id="'+id+'"]');imageElement.attr("data",newThumbURL).attr("height",_this.thumbInfo.thumbsHeight).attr("width",width).attr("src","")}),triggerShow&&this.show()},template:$.Handlebars.compile(['<div class="{{thumbnailCls}}">','<ul class="{{listingCssCls}}" role="list" aria-label="Thumbnails">',"{{#thumbs}}",'<li class="{{highlight}}" role="listitem" aria-label="Thumbnail">','<img class="thumbnail-image {{highlight}}" title="{{title}}" data-image-id="{{id}}" src="" data="{{thumbUrl}}" height="{{../defaultHeight}}" width="{{width}}">','<div class="thumb-label">{{title}}</div>',"</li>","{{/thumbs}}","</ul>","</div>"].join("")),hide:function(){var element=jQuery(this.element);this.panel&&(element=element.parent()),element.hide({effect:"fade",duration:300,easing:"easeOutCubic"})},show:function(){var element=jQuery(this.element);this.panel&&(element=element.parent());var _this=this;element.show({effect:"fade",duration:300,easing:"easeInCubic",complete:function(){jQuery(this).css("display","block"),_this.loadImages()}})},adjustWidth:function(className,hasClass){var _this=this;hasClass?_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,className):_this.eventEmitter.publish("ADD_CLASS."+this.windowId,className)},adjustHeight:function(className,hasClass){hasClass?this.element.removeClass(className):this.element.addClass(className)}}}(Mirador),function($){$.TableOfContents=function(options){jQuery.extend(!0,this,{element:null,appendTo:null,windowId:null,structures:[],manifestVersion:null,previousSelectedElements:[],selectedElements:[],previousOpenElements:[],openElements:[],hoveredElement:[],selectContext:null,tocData:{},active:null,eventEmitter:null},options),this.init();var self=this;window.render=function(){self.render()}},$.TableOfContents.prototype={init:function(){var _this=this;_this.structures&&0!==_this.structures.length?(this.element=jQuery(this.template({ranges:this.getTplData()})).appendTo(this.appendTo),this.tocData=_this.initTocData(),this.setSelectedElements($.getRangeIDByCanvasID(_this.structures,_this.canvasID)),this.element.find(".has-child ul").hide(),this.render()):this.element=jQuery(this.emptyTemplate()).appendTo(this.appendTo),this.bindEvents()},tabStateUpdated:function(data){"tocTab"===data.tabs[data.selectedTabIndex].options.id?this.element.show():this.element.hide()},getTplData:function(){var ranges,_this=this;_this.structures.map(function(structure){return structure.id=structure["@id"],structure});switch(_this.manifestVersion){case"1":ranges=_this.extractV1RangeTrees(_this.structures);break;case"2":ranges=_this.extractV2RangeTrees(_this.structures)}return ranges.length<2&&ranges[0].children&&(ranges=ranges[0].children),ranges},initTocData:function(){var _this=this,tocData={};return _this.structures.forEach(function(structure){var rangeID=structure["@id"],attrString='[data-rangeid="'+rangeID+'"]';tocData[structure["@id"]]={element:_this.element.find(attrString).closest("li")}}),tocData},extractV1RangeTrees:function(rangeList){function unflatten(flatRanges,parent,tree){tree="undefined"!=typeof tree?tree:[],parent="undefined"!=typeof parent?parent:{"@id":"root",label:"Table of Contents"};var children=jQuery.grep(flatRanges,function(child){return child.within||(child.within="root"),child.within==parent["@id"]});return children.length&&("root"===parent["@id"]?(children.forEach(function(child){child.level=0}),tree=children):(children.forEach(function(child){child.level=parent.level+1}),parent.children=children),jQuery.each(children,function(index,child){unflatten(flatRanges,child)})),tree}return unflatten(rangeList)},extractV2RangeTrees:function(rangeList){function unflatten(flatRanges,parent,tree){tree="undefined"!=typeof tree?tree:[],parent="undefined"!=typeof parent?parent:{"@id":"root",label:"Table of Contents"};var children=[];if(parent.ranges)jQuery.each(parent.ranges,function(index,id){id="object"==typeof id?id["@id"]:id;var child=jQuery.grep(flatRanges,function(range,index){if(range["@id"]===id)return range})[0];child&&children.push(child)});else if("root"===parent["@id"]){var top=jQuery.grep(flatRanges,function(range,index){if(range.hasOwnProperty("viewingHint")&&"top"===range.viewingHint)return range})[0];top&&children.push(top),0===children.length&&(jQuery.each(flatRanges,function(index,range){if(range.ranges)return children.push(range),!1}),0===children.length&&children.push({ranges:flatRanges}))}return children.length&&("root"===parent["@id"]?(children.forEach(function(child){child.level=0}),tree=children):(children.forEach(function(child){child.level=parent.level+1}),parent.children=children),jQuery.each(children,function(index,child){unflatten(flatRanges,child)})),tree}return unflatten(rangeList)},render:function(){var _this=this,toDeselect=_this.previousSelectedElements.map(function(rangeID){return _this.tocData[rangeID].element}),toSelect=_this.selectedElements.map(function(rangeID){return _this.tocData[rangeID].element}),toOpen=_this.openElements.filter(function(rangeID){return jQuery.inArray(rangeID,_this.previousOpenElements)===-1}).map(function(rangeID){return _this.tocData[rangeID].element}),toClose=_this.previousOpenElements.filter(function(rangeID){return jQuery.inArray(rangeID,_this.openElements)===-1}).map(function(rangeID){return _this.tocData[rangeID].element});_this.previousSelectedElements!==_this.selectedElements?(toDeselect.forEach(function(element){element.removeClass("selected")}),toSelect.forEach(function(element){element.addClass("selected")}),toClose.forEach(function(element){element.removeClass("open"),element.find("ul:first").slideFadeToggle()}),toOpen.forEach(function(element){element.addClass("open").find("ul:first").slideFadeToggle()})):(toOpen.forEach(function(element){element.addClass("open").find("ul:first").slideFadeToggle()}),toClose.forEach(function(element){element.removeClass("open").find("ul:first").slideFadeToggle()}))},bindEvents:function(){var _this=this;_this.eventEmitter.subscribe("tabStateUpdated."+_this.windowId,function(_,data){_this.tabStateUpdated(data)}),_this.eventEmitter.subscribe("currentCanvasIDUpdated."+_this.windowId,function(event,canvasID){_this.structures&&(_this.setSelectedElements($.getRangeIDByCanvasID(_this.structures,canvasID)),_this.render())}),_this.element.find(".toc-link").on("click",function(event){event.stopPropagation();var rangeID=jQuery(this).data().rangeid,canvasID=jQuery.grep(_this.structures,function(item){return item["@id"]==rangeID})[0].canvases[0];_this.eventEmitter.publish("SET_CURRENT_CANVAS_ID."+_this.windowId,canvasID)}),_this.element.find(".toc-caret").on("click",function(event){event.stopPropagation();var rangeID=jQuery(this).parent().data().rangeid;_this.setOpenItem(rangeID),_this.render()})},setActive:function(active){var _this=this;_this.active=active},setOpenItem:function(rangeID){var _this=this,alreadyOpen=jQuery.inArray(rangeID,_this.openElements)!==-1;_this.previousOpenElements=_this.openElements,_this.openElements=function(){return alreadyOpen?_this.openElements.filter(function(elementID){return elementID!==rangeID}):_this.openElements.map(function(elementID){return elementID}).concat([rangeID])}()},setSelectedElements:function(rangeIDs){var _this=this;_this.previousSelectedElements=_this.selectedElements,_this.selectedElements=rangeIDs,_this.previousOpenElements=_this.openElements,_this.openElements=_this.openElements.filter(function(openElementID){return jQuery.inArray(openElementID,_this.previousSelectedElements)===-1}).concat(rangeIDs).filter(function(openElementID,index,openElements){return index===openElements.indexOf(openElementID)})},emptyTemplate:$.Handlebars.compile(['<ul class="toc">','<li class="leaf-item open">','<h2><span>{{t "noIndex"}}</span></h2>',"</ul>"].join("")),template:function(tplData){var previousTemplate,template=$.Handlebars.compile(['<ul class="toc">',"{{#nestedRangeLevel ranges}}",'<li class="{{#if children}}has-child{{else}}leaf-item{{/if}}">',"{{{tocLevel id label level children}}}","{{#if children}}","<ul>","{{{nestedRangeLevel children}}}","</ul>","{{/if}}","<li>","{{/nestedRangeLevel}}","</ul>"].join(""));return $.Handlebars.registerHelper("nestedRangeLevel",function(children,options){var out="";return void 0!==options.fn&&(previousTemplate=options.fn),children.forEach(function(child){child.label=$.JsonLd.getTextValue(child.label),out+=previousTemplate(child)}),out}),$.Handlebars.registerHelper("tocLevel",function(id,label,level,children){var caret='<i class="fa fa-caret-right toc-caret"></i>',cert='<i class="fa fa-certificate star"></i>';return"<h"+(level+1)+'><a class="toc-link" data-rangeID="'+id+'">'+caret+cert+"<span>"+label+"</span></a></h"+(level+1)+">"}),template(tplData)},hide:function(){var _this=this;jQuery(this.appendTo).hide(),_this.eventEmitter.publish("ADD_CLASS."+this.windowId,"focus-max-width")},show:function(){var _this=this;jQuery(this.appendTo).show({effect:"fade",duration:300,easing:"easeInCubic"}),_this.eventEmitter.publish("REMOVE_CLASS."+this.windowId,"focus-max-width")}}}(Mirador),function($){$.DialogBuilder=function(container){this.container=container||jQuery(".window"),bootbox.setDefaults({container:this.container})},$.DialogBuilder.prototype={confirm:function(message,callback){return this._attachEvents(bootbox.confirm(message,callback))},dialog:function(opts){this._attachEvents(bootbox.dialog(opts))},_attachEvents:function(el){var _this=this;jQuery(el).on("shown.bs.modal",function(){var zIndex=2e4;jQuery(el).css("z-index",zIndex),jQuery(".modal-backdrop").prependTo(_this.container).css("z-index",zIndex)}),jQuery(el).on("hidden.bs.modal",function(){jQuery(".modal-backdrop").remove()})}}}(Mirador),function($){$.EventEmitter=function(config){jQuery.extend(!0,this,{debug:$.EventEmitter.debug,trace:$.EventEmitter.trace,debugExclude:$.EventEmitter.excludePatterns},config),this.emitterId=$.EventEmitter.nextId(),this.debug&&(this.logger=new $.EventEmitter.Logger({trace:this.trace,debugExclude:this.debugExclude}))},$.EventEmitter.id=0,$.EventEmitter.nextId=function(){return $.EventEmitter.id++,$.EventEmitter.id},$.EventEmitter.debug=!1,$.EventEmitter.trace=!1,$.EventEmitter.excludePatterns=[],$.EventEmitter.Logger=function(options){this.trace=options.trace,this.debugExclude=options.debugExclude,this.scaffoldMap={}},$.EventEmitter.Logger.prototype={log:function(){this.trace?console.trace.apply(console,arguments):console.log.apply(console,arguments)},exclude:function(str){for(var patterns=this.debugExclude,i=0;i<patterns.length;++i)if(str.match(patterns[i]))return!0;return!1},scaffoldHandler:function(eventId,handler){var _this=this,scaffold=function(){_this.log("EventEmitter:handler:",eventId,handler,Array.prototype.slice.call(arguments)),handler.apply(null,arguments)};return this.scaffoldMap[handler]=scaffold,scaffold},unscaffold:function(handler){var scaffold=this.scaffoldMap[handler];return delete this.scaffoldMap[handler],scaffold}},["subscribe","unsubscribe","publish"].forEach(function(action){$.EventEmitter.prototype[action]=function(){var event,args=Array.prototype.slice.call(arguments),eventId=args[0],globalEventId=this.emitterId.toString()+"::"+eventId,logging=this.logger&&!this.logger.exclude(globalEventId);if("subscribe"===action&&(event={name:eventId,handler:args[1]},logging&&(args[1]=this.logger.scaffoldHandler(globalEventId,args[1]))),"unsubscribe"===action&&logging&&(args[1]=this.logger.unscaffold(args[1])),args[0]=globalEventId,logging&&this.logger.log("EventEmitter:"+action+":",args),jQuery[action].apply(jQuery,args),event)return event}})}(Mirador),function($){$.Iiif={getImageUrl:function(image){if(!image.images[0].resource.service)return id=image.images[0].resource.default.service["@id"],id=id.replace(/\/$/,"");var id=image.images[0].resource.service["@id"];return id=id.replace(/\/$/,"")},getVersionFromContext:function(context){return"http://iiif.io/api/image/2/context.json"==context?"2.0":"1.1"},getComplianceLevelFromProfile:function(profile){var compliance=-1,complianceString=null;if(profile)switch("string"==typeof profile?complianceString=profile:"object"==typeof profile&&(complianceString=profile[0]),complianceString){case"http://iiif.io/api/image/2/level0.json":compliance=0;break;case"http://iiif.io/api/image/2/level1.json":compliance=1;break;case"http://iiif.io/api/image/2/level2.json":compliance=2}return compliance},makeUriWithWidth:function(uri,width,version){return uri=uri.replace(/\/$/,""),"1"==version[0]?uri+"/full/"+width+",/0/native.jpg":uri+"/full/"+width+",/0/default.jpg"},getImageHostUrl:function(json){var regex,matches=[];return json.hasOwnProperty("image_host")||(json.image_host=json.tilesUrl||json["@id"]||"",json.hasOwnProperty("identifier")?(regex=new RegExp("/?"+json.identifier+"/?$","i"),json.image_host=json.image_host.replace(regex,"")):(regex=new RegExp("(.*)/(.*)$"),matches=regex.exec(json.image_host),matches.length>1&&(json.image_host=matches[1],json.identifier=matches[2]))),json.image_host}}}(Mirador),function($){function getAPIUri(host,port,ssl,body){var proto="http";port=port?port:"80",ssl&&(proto="https",port=port?port:"443"),host=host?host:"jsonblob.com";var path=JSONBLOB_API_ENDPOINT;return("string"==typeof body||body instanceof String)&&(path+="/"+body),proto+"://"+host+":"+port+path}function initSettings(method,host,port,ssl,requestBody){var ajaxSettings={type:method,url:getAPIUri(host,port,ssl,requestBody),contentType:"application/json; charset=UTF-8",accept:"application/json",dataType:"json",processData:!1};return"string"==typeof requestBody||requestBody instanceof String||(ajaxSettings.data=JSON.stringify(requestBody)),ajaxSettings}function syncRequest(method,host,port,ssl,requestBody){var result,settings=initSettings(method,host,port,ssl,requestBody);return settings.async=!1,settings.success=function(data,textStatus,request){result=data},jQuery.ajax(settings),result}function asyncRequest(method,host,port,ssl,requestBody,cb){var settings=initSettings(method,host,port,ssl,requestBody);settings.success=cb,jQuery.ajax(settings)}var JSONBLOB_API_ENDPOINT="/api/jsonBlob";$.JSONBlobAPI=function(options){this.options=options},$.JSONBlobAPI.prototype={readSync:function(blobId){return syncRequest("GET",this.options.host,this.options.port,this.options.ssl,blobId)},save:function(blob){var deferred=jQuery.Deferred();return asyncRequest("POST",this.options.host,this.options.port,this.options.ssl,blob,function(data,textStatus,request){var blobid=request.getResponseHeader("X-Jsonblob");deferred.resolve(blobid)}),deferred.promise()}}}(Mirador),function($){function getDisplayLanguage(languages,items){var itemLanguages=items.map(function(itm){return"string"==typeof itm?null:itm["@language"]}),bestLanguageMatch=null;return jQuery.each(languages,function(idx,lang){return null===bestLanguageMatch&&void(itemLanguages.indexOf(lang)!==-1&&(bestLanguageMatch=lang))}),null===bestLanguageMatch&&itemLanguages.indexOf(null)===-1&&(bestLanguageMatch=itemLanguages[0]),bestLanguageMatch}$.JsonLd={getTextValue:function(propertyValue,language){var languages=window.navigator.languages||["en"];if("string"==typeof language?languages=[language].concat(languages):Array.isArray(language)&&(languages=language.concat(languages)),"undefined"==typeof propertyValue||null===propertyValue)return"";if("string"==typeof propertyValue)return $.sanitizeHtml(propertyValue);if(Array.isArray(propertyValue)){var displayLanguage=getDisplayLanguage(languages,propertyValue),text="";return jQuery.each(propertyValue,function(idx,item){var textToAdd="";"string"==typeof item&&null===displayLanguage?textToAdd=item:item["@language"]===displayLanguage&&(textToAdd=item["@value"]),""!==textToAdd&&""!==text&&(text+="<br/>"),text+=textToAdd}),$.sanitizeHtml(text)}return $.sanitizeHtml(propertyValue["@value"])}}}(Mirador),function($){function generateUUID(){var d=(new Date).getTime(),uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"===c?r:3&r|8).toString(16)});return uuid}$.LocalJSONBlobAPI=function(opts){this.options={storage:window.localStorage},jQuery.extend(this.options,opts)},$.LocalJSONBlobAPI.prototype={readSync:function(blobId){return JSON.parse(this.options.storage.getItem(blobId))},save:function(blob){var deferred=jQuery.Deferred(),uuid=generateUUID();return this.options.storage.setItem("BM-"+uuid,JSON.stringify(blob)),deferred.resolve("BM-"+uuid),deferred.promise()}}}(Mirador),function($){$.OpenSeadragon=function(options){var osd=OpenSeadragon(jQuery.extend({preserveViewport:!0,visibilityRatio:1,minZoomLevel:0,defaultZoomLevel:0,blendTime:.1,alwaysBlend:!1,prefixUrl:"images/openseadragon/",showNavigationControl:!1},options));return osd}}(Mirador),function($){$.SaveController=function(config){function index(previousValue,currentValue,currentIndex){var newObj={};return newObj[currentValue]=previousValue,newObj}function iterateStringify(object){for(var property in object)object.hasOwnProperty(property)&&(object[property]instanceof Array?object[property]=JSON.stringify(object[property]):"object"==typeof object[property]&&iterateStringify(object[property]))}function iterateParse(object){for(var property in object)object.hasOwnProperty(property)&&("string"==typeof object[property]&&"["===object[property][0]?object[property]=JSON.parse(object[property]):"object"==typeof object[property]&&iterateParse(object[property]))}jQuery.extend(!0,this,{currentConfig:null,originalConfig:null,shareEndpoint:null,historySize:null,sessionID:null,slots:[],eventEmitter:null}),config.availableAnnotationDrawingTools&&(config.availableAnnotationDrawingTools=jQuery.grep(config.availableAnnotationDrawingTools,function(element,index){return jQuery.inArray(element,$.DEFAULT_SETTINGS.availableAnnotationDrawingTools)>=0})),config.mainMenuSettings&&!config.mainMenuSettings.buttons&&(config.mainMenuSettings.buttons={}),jQuery.each(config,function(key,value){if("string"==typeof key&&key.indexOf(".")!==-1){var array=key.split(".").reverse(),object=array.reduce(index,value);delete config[key],jQuery.extend(!0,config,object)}}),iterateStringify(config);var newConfig=jQuery.extend(!0,{},$.DEFAULT_SETTINGS,config);iterateParse(newConfig),this.init(newConfig)},$.SaveController.prototype={init:function(config){var _this=this;if(this.eventEmitter=config.eventEmitter,config.saveSession===!1)return this.currentConfig=config,this.bindEvents(),!1;saveModule=config.jsonStorageEndpoint.module,saveOptions=config.jsonStorageEndpoint.options,_this.storageModule=new $[saveModule](saveOptions);var sessionID=window.location.hash.substring(1);if(sessionID?this.sessionID=sessionID:this.sessionID=$.genUUID(),localStorage.getItem(this.sessionID))this.currentConfig=JSON.parse(localStorage.getItem(sessionID));else{var paramURL=window.location.search.substring(1);if(paramURL){var params=paramURL.split("="),jsonblob=params[1];this.currentConfig=this.storageModule.readSync(jsonblob)||config}else this.currentConfig=config}this.currentConfig.windowObjects=jQuery.map(this.currentConfig.windowObjects,function(value,index){return 0===Object.keys(value).length?null:value}),this.currentConfig.windowObjects&&jQuery.each(this.currentConfig.windowObjects,function(index,window){window.id||(window.id=$.genUUID())});var cleanURL=window.location.href.replace(window.location.search,"");window.location.hash?history.replaceState(this.currentConfig,"Mirador Session",cleanURL):history.replaceState(this.currentConfig,"Mirador Session",cleanURL+"#"+this.sessionID),this.bindEvents()},getWindowObjectById:function(windowId){var returnObject=null;return jQuery.each(this.currentConfig.windowObjects,function(index,window){if(window.id===windowId)return returnObject=window,!1}),returnObject},getWindowAnnotationsList:function(windowId){return this.windowsAnnotationsLists?this.windowsAnnotationsLists[windowId]:null},getSlots:function(){return this.slots},getWindowElement:function(windowId){return this.windowsElements?this.windowsElements[windowId]:null},getStateProperty:function(prop){return this.get(prop,"currentConfig")},getManifestIndex:function(manifestUri){var manifestIndex=-1;return jQuery.each(this.currentConfig.data,function(index,dataObj){if(dataObj.manifestUri===manifestUri)return manifestIndex=index,!1}),manifestIndex},get:function(prop,parent){return parent?this[parent][prop]:this[prop]},set:function(prop,value,options){var _this=this;options?this[options.parent][prop]=value:this[prop]=value,this.currentConfig.saveSession&&this.save(),_this.eventEmitter.publish("saveControllerConfigUpdated")},bindEvents:function(){var _this=this;_this.eventEmitter.subscribe("manifestsPanelVisible.set",function(event,manifestPanelVisible){_this.set("manifestPanelVisible",manifestPanelVisible,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("windowUpdated",function(event,options){var windowObjects=_this.currentConfig.windowObjects;windowObjects&&windowObjects.length>0?jQuery.each(windowObjects,function(index,window){window.id===options.id&&jQuery.extend(windowObjects[index],options)}):windowObjects=[options],_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("imageBoundsUpdated",function(event,options){var windowObjects=_this.currentConfig.windowObjects;windowObjects&&windowObjects.length>0&&jQuery.each(windowObjects,function(index,window){window.id===options.id&&(windowObjects[index].windowOptions||(windowObjects[index].windowOptions={}),windowObjects[index].windowOptions.osdBounds=options.osdBounds)}),_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("ANNOTATIONS_LIST_UPDATED",function(event,options){_this.windowsAnnotationsLists||(_this.windowsAnnotationsLists={}),_this.windowsAnnotationsLists[options.windowId]=options.annotationsList,_this.eventEmitter.publish("annotationListLoaded."+options.windowId)}),_this.eventEmitter.subscribe("WINDOW_ELEMENT_UPDATED",function(event,options){_this.windowsElements||(_this.windowsElements={}),_this.windowsElements[options.windowId]=options.element}),_this.eventEmitter.subscribe("windowSlotAddressUpdated",function(event,options){var windowObjects=_this.currentConfig.windowObjects;windowObjects&&windowObjects.length>0?jQuery.each(windowObjects,function(index,window){window.id===options.id&&jQuery.extend(windowObjects[index],options)}):windowObjects=[options],_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("manifestQueued",function(event,manifestObject,repository){var data=_this.currentConfig.data,objectInConfig=!1,url=manifestObject.uri;jQuery.each(data,function(index,manifestObject){manifestObject.manifestUri===url&&(objectInConfig=!0)}),objectInConfig||(data.push({manifestUri:url,location:repository}),_this.set("data",data,{parent:"currentConfig"}));var manifests=_this.currentConfig.manifests;manifests[url]=manifestObject,_this.set("manifests",manifests,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("slotsUpdated",function(event,options){_this.slots=options.slots}),_this.eventEmitter.subscribe("layoutChanged",function(event,layoutDescription){var serialisedLayout=JSON.stringify(layoutDescription,function(key,value){if("parent"!==key)return value});_this.set("layout",serialisedLayout,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("windowSlotAdded",function(event,options){var windowObjects=_this.currentConfig.windowObjects,inArray=jQuery.grep(windowObjects,function(windowObj){return windowObj.id===options.id});0===inArray.length&&(windowObjects.push({id:options.id,slotAddress:options.slotAddress}),_this.set("windowObjects",windowObjects,{parent:"currentConfig"}))}),_this.eventEmitter.subscribe("windowsRemoved",function(event){_this.set("windowObjects",[],{parent:"currentConfig"})}),_this.eventEmitter.subscribe("windowRemoved",function(event,windowID){var windowObjects=jQuery.grep(_this.currentConfig.windowObjects,function(window,index){return window.id!==windowID});_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("DELETE_FROM_CONFIG",function(event,options){var windowObjects=jQuery.grep(_this.currentConfig.windowObjects,function(window,index){return window.loadedManifest!==options.loadedManifest||window.id});_this.set("windowObjects",windowObjects,{parent:"currentConfig"})}),_this.eventEmitter.subscribe("etc...",function(junk){})},save:function(){var _this=this;localStorage.setItem(_this.sessionID,JSON.stringify(_this.currentConfig))}}}(Mirador),function($){$.trimString=function(str){return str.replace(/^\s+|\s+$/g,"")},$.getImageIndexById=function(imagesList,id){var imgIndex=0;return jQuery.each(imagesList,function(index,img){$.trimString(img["@id"])===$.trimString(id)&&(imgIndex=index)}),imgIndex},$.getThumbnailForCanvas=function(canvas,width){var service,thumbnailUrl,version="1.1",compliance=-1;if(width=parseInt(width,10),canvas.hasOwnProperty("thumbnail"))"string"==typeof canvas.thumbnail?thumbnailUrl=canvas.thumbnail:canvas.thumbnail.hasOwnProperty("service")?(service=canvas.thumbnail.service,service.hasOwnProperty("profile")&&(compliance=$.Iiif.getComplianceLevelFromProfile(service.profile)),0===compliance?thumbnailUrl=canvas.thumbnail["@id"]:(service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version))):thumbnailUrl=canvas.thumbnail["@id"];else{var resource=canvas.images[0].resource;service=resource.default?resource.default.service:resource.service,service.hasOwnProperty("@context")&&(version=$.Iiif.getVersionFromContext(service["@context"])),thumbnailUrl=$.Iiif.makeUriWithWidth(service["@id"],width,version)}return thumbnailUrl},$.getQueryParams=function(url){var assoc={},decode=function(s){return decodeURIComponent(s.replace(/\+/g," "))},queryString=url.split("?")[1];if("undefined"==typeof queryString)return{};
88
88
  var keyValues=queryString.split("&");for(var i in keyValues){var key=keyValues[i].split("=");key.length>1&&(assoc[decode(key[0])]=decode(key[1]))}return assoc},$.genUUID=function(){var idNum="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0,v="x"==c?r:3&r|8;return v.toString(16)});return idNum},jQuery.fn.slideFadeToggle=function(speed,easing,callback){return this.animate({opacity:"toggle",height:"toggle"},speed,easing,callback)},$.throttle=function(func,wait,options){var context,args,result,timeout=null,previous=0;"undefined"!=typeof options&&(options={});var later=function(){previous=options.leading===!1?0:new Date,timeout=null,result=func.apply(context,args)};return function(){var now=new Date;previous||options.leading!==!1||(previous=now);var remaining=wait-(now-previous);return context=this,args=arguments,remaining<=0?(clearTimeout(timeout),timeout=null,previous=now,result=func.apply(context,args)):timeout||options.trailing===!1||(timeout=setTimeout(later,remaining)),result}},$.debounce=function(func,wait,immediate){var timeout,args,context,timestamp,result;return function(){context=this,args=arguments,timestamp=new Date;var later=function(){var last=new Date-timestamp;last<wait?timeout=setTimeout(later,wait-last):(timeout=null,immediate||(result=func.apply(context,args)))},callNow=immediate&&!timeout;return timeout||(timeout=setTimeout(later,wait)),callNow&&(result=func.apply(context,args)),result}},$.isOnScreen=function(elem,outsideViewportFactor){var factor=1;outsideViewportFactor&&(factor=outsideViewportFactor);var win=jQuery(window),viewport={top:win.scrollTop()*factor,left:win.scrollLeft()*factor};viewport.bottom=(viewport.top+win.outerHeight())*factor,viewport.right=(viewport.left+win.outerWidth())*factor;var el=jQuery(elem),bounds=el.offset();return bounds.bottom=bounds.top+el.height(),bounds.right=bounds.left+el.width(),!(viewport.right<bounds.left||viewport.left>bounds.right||viewport.bottom<bounds.top||viewport.top>bounds.bottom)},$.getRangeIDByCanvasID=function(structures,canvasID){var ranges=jQuery.grep(structures,function(range){return jQuery.inArray(canvasID,range.canvases)>-1}),rangeIDs=jQuery.map(ranges,function(range){return range["@id"]});return rangeIDs},$.layoutDescriptionFromGridString=function(gridString){var columns=parseInt(gridString.substring(gridString.indexOf("x")+1,gridString.length),10),rowsPerColumn=parseInt(gridString.substring(0,gridString.indexOf("x")),10),layoutDescription={type:"row"};if("1x1"===gridString)return layoutDescription;layoutDescription.children=[];for(var i=0,c=columns;i<c;i++){var column={type:"column"};if(rowsPerColumn>1){column.children=[];for(var j=0,r=rowsPerColumn;j<r;j++)column.children.push({type:"row"})}layoutDescription.children.push(column)}return layoutDescription},$.createImagePromise=function(imageUrl){var img=new Image,dfd=jQuery.Deferred();return img.onload=function(){dfd.resolve(img.src)},img.onerror=function(){dfd.reject(img.src)},dfd.fail(function(){console.log("image failed to load: "+img.src)}),img.src=imageUrl,dfd.promise()},$.enterFullscreen=function(el){el.requestFullscreen?el.requestFullscreen():el.mozRequestFullScreen?el.mozRequestFullScreen():el.webkitRequestFullscreen?el.webkitRequestFullscreen():el.msRequestFullscreen&&el.msRequestFullscreen()},$.exitFullscreen=function(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()},$.isFullscreen=function(){var fullscreen=$.fullscreenElement();return fullscreen.length>0},$.fullscreenElement=function(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement},$.sanitizeHtml=function(dirty){return sanitizeHtml(dirty,{allowedTags:["a","b","br","i","img","p","span","strong","em"],allowedAttributes:{a:["href","target"],img:["src","alt"],p:["dir"]}})}}(Mirador);
89
89
  //# sourceMappingURL=mirador.min.js.map