Files
IPB/static/js/global/root_framework.js
2025-12-19 19:17:57 -08:00

2225 lines
468 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
ips.templates.set('core.general.loading'," &nbsp;<span class='i-color_soft'><i class='ipsLoadingIcon'></i>&nbsp;&nbsp;&nbsp;</span> {{text}}</span>");ips.templates.set('core.general.ajax'," <div id='elAjaxLoading'><i class='ipsLoading ipsLoading--tiny'></i> {{#lang}}loading{{/lang}}...</div>");ips.templates.set('core.general.flashMsg'," <div id='elFlashMessage'><div data-role='flashMessage' class='i-text-align_center'></div><a href='#' data-action='dismissFlashMessage'>&times;</a></div>");ips.templates.set('core.hovercard.loading'," <i class='ipsLoadingIcon'></i>");ips.templates.set('core.posts.spoiler'," <span class='ipsStyle_spoilerFancy_text'><span class='ipsButton ipsButton--small ipsButton--primary ipsButton--icon'><i class='fa-solid fa-chevron-right'></i></span> {{#lang}}spoilerClickToReveal{{/lang}}</span>");ips.templates.set('core.posts.spoilerOpen'," <span class='ipsStyle_spoilerFancy_text'><span class='ipsButton ipsButton--small ipsButton--primary ipsButton--icon'><i class='fa-solid fa-chevron-down'></i></span> {{#lang}}spoilerClickToHide{{/lang}}</span>");ips.templates.set('core.posts.multiQuoteOff'," <i class='fa-solid fa-plus'></i>");ips.templates.set('core.posts.multiQuoteOn'," <i class='fa-solid fa-check'></i>");ips.templates.set('core.posts.multiQuoter'," <div id='ipsMultiQuoter' data-commentsContainer='{{commentFeedId}}'> <button class='ipsButton ipsButton--soft ipsButton--small' data-role='multiQuote_{{commentFeedId}}'><i class='fa-solid fa-comments'></i> &nbsp;&nbsp;{{{count}}}</button> &nbsp;&nbsp;<a href='#' data-action='clearQuoted_{{commentFeedId}}'><i class='fa-solid fa-xmark'></i></a> </div>");ips.templates.set('core.menus.menuItem'," <li> <a href='{{link}}' {{#checked}}aria-selected='true'{{/checked}} data-ipsMenuValue='{{value}}'>{{title}}</a> </li>");ips.templates.set('core.menus.menuSep'," <li><hr></li>");ips.templates.set('core.posts.quotedSpoiler'," <p><em>{{#lang}}quotedSpoiler{{/lang}}</em></p>");ips.templates.set('core.postNotify.single'," <div class='i-flex i-align-items_center i-gap_2 i-link-color_inherit' data-role='newPostNotification'> <span class='ipsUserPhoto ipsUserPhoto--tiny'><img src='{{photo}}' alt='' loading='lazy'></span> <div> <span class='i-font-weight_500'>{{{text}}}</span>&nbsp;&nbsp; <a href='#' data-action='loadNewPosts' class='i-opacity_8'>{{#lang}}showReply{{/lang}}</a> </div> </div>");ips.templates.set('core.postNotify.multiple'," <div class='i-flex i-align-items_center i-gap_2 i-link-color_inherit' data-role='newPostNotification'> <i class='fa-solid fa-comments'></i> <div> <span class='i-font-weight_500'>{{{text}}}</span>&nbsp;&nbsp; <a href='#' data-action='loadNewPosts' class='i-opacity_8'>{{#lang}}showReplies{{/lang}}</a> </div> </div>");ips.templates.set('core.postNotify.multipleSpillOver'," <div class='i-flex i-align-items_center i-gap_2 i-link-color_inherit' data-role='newPostNotification'> <i class='fa-solid fa-comments'></i> <div> {{text}} {{#canLoadNew}} &nbsp;&nbsp;&nbsp;<a href='#' data-action='loadNewPosts'>{{showFirstX}}</a> &nbsp;&nbsp;&nbsp;<span class='i-opacity_8'>{{#lang}}showRepliesOr{{/lang}}</span> {{/canLoadNew}} &nbsp;&nbsp;&nbsp;<a href='{{spillOverUrl}}'>{{#lang}}goToNewestPage{{/lang}}</a> </div> </div>");ips.templates.set('core.notification.flashSingle'," <a href='{{url}}' data-role='newNotification'> <div class='i-flex i-align-items_center i-gap_2 i-link-color_inherit'> {{#icon}}<div class='i-flex_00'><span class='ipsUserPhoto ipsUserPhoto--tiny'><img src='{{icon}}' alt='' loading='lazy'></span></div>{{/icon}} <div class='i-flex_11 i-text-align_start'> {{text}} <p class='i-opacity_8 ipsTruncate_1 i-font-weight_600'>{{{body}}}</p> </div> </div> </a>");ips.templates.set('core.notification.flashMultiple'," <div class='i-flex i-align-items_center i-gap_2 i-link-color_inherit' data-role='newNotification'> <i class='fa-solid fa-bell'></i> <div class='i-flex_11 i-text-align_start'> {{text}} <p class='i-opacity_8 ipsTruncate_1 i-font-weight_600'>{{{body}}}</p> </div> </div>");ips.templates.set('core.alert.box'," <div class='ipsAlert' style='display: none' role='alertdialog' aria-describedby='{{id}}_message'> <div class='ipsAlert__message' id='{{id}}_message'> <div class='ipsAlert__icon'>{{{icon}}}</div> <strong class='ipsAlert__title'>{{{text}}}</strong> {{{subtext}}} </div> <ul class='ipsButtons ipsButtons--fill'> {{{buttons}}} </ul></div>");ips.templates.set('core.alert.subText'," <div class='ipsAlert__desc'>{{text}}</div>");ips.templates.set('core.alert.subTextHtml'," <div class='ipsAlert__desc'>{{{text}}}</div>");ips.templates.set('core.alert.icon'," <i class='{{icon}}'></i>");ips.templates.set('core.alert.button'," <li><button data-action='{{action}}' class='ipsButton {{extra}}'>{{title}}</button></li>");ips.templates.set('core.alert.prompt'," <br><br><input type='text' value='{{value}}' class='ipsInput ipsInput--text ipsInput--wide' data-role='promptValue'><br><br>");ips.templates.set('core.lightbox.meta',"{{title}}");ips.templates.set('core.lightbox.toolsMenu'," <a href='{{url}}&amp;direction=right' class='ipsButton ipsButton--text ipsButton--small' title='Rotate Right' data-ipsTooltip data-action='rotateImage'> <i class='fa-solid fa-rotate-right'></i></a><a href='{{url}}&amp;direction=left' class='ipsButton ipsButton--text ipsButton--small' title='Rotate Left' data-ipsTooltip data-action='rotateImage'> <i class='fa-solid fa-rotate-left'></i></a>");ips.templates.set('core.dialog.main'," <div class='{{class}} {{#fixed}}{{class}}_fixed{{/fixed}} {{#size}}{{class}}_{{size}}{{/size}} {{extraClass}}' style='display: none' id='{{id}}' role='dialog' aria-label='{{title}}'> <div> {{#title}} <h3 class='{{class}}_title'>{{title}}</h3> <hr class='ipsHr'> {{/title}} {{#close}} <a href='#' class='{{class}}_close' data-action='dialogClose'>&times;</a> {{/close}} <div class='{{class}}_content'> {{content}} </div> <div class='{{class}}_loading {{class}}_large ipsLoading' style='display: none'></div> </div></div>")
ips.templates.set('core.tooltip'," <div id='{{id}}' class='ipsTooltip' role='tooltip' popover='manual'>{{content}}</div>");ips.templates.set('core.search.loadingPanel'," <div id='{{id}}' class='ipsLoading' style='min-height: 100px'> &nbsp; </div>");ips.templates.set('core.editor.panelWrapper'," <div id='{{id}}' class='ipsRTE_panel i-padding_3'> {{content}} </div>");ips.templates.set('core.editor.pixabayThumb',`
<div class='ipsPixabayThumb' {{#width}}{{#height}}style="--i-ratio: {{width}} / {{height}}"{{/height}}{{/width}}>
<img loading="lazy" {{#width}}width='{{width}}'{{/width}} {{#height}}height='{{height}}'{{/height}} src="{{thumb}}" class="ipsPixabayImage" data-url="{{url}}" data-id="{{imgid}}" alt="">
</div>
`);ips.templates.set('core.editor.emoticonSection'," <div data-panel='{{id}}'>{{{content}}}</div>");ips.templates.set('core.editor.emoticonCategory'," <div class='i-background_2 i-padding_2'><strong>{{title}}</strong></div> <div class='ipsEmoticons_category' data-categoryid='{{categoryID}}'>{{{emoticons}}}</div>");ips.templates.set('core.editor.emoticonSearch'," <div class='ipsEmoticons_category'>{{{emoticons}}}</div>");ips.templates.set('core.editor.emoticonRow'," <div class='ipsEmoticons_row ipsEmoji'>{{{emoticons}}}</div>");ips.templates.set('core.editor.emoticonItem'," <div class='ipsEmoticons_item' data-emoticon='{{tag}}' src='{{src}}' data-height='{{height}}' data-width='{{width}}' title='{{tag}}' loading='lazy'>{{{img}}}</div>");ips.templates.set('core.editor.emoji'," <div class='ipsEmoticons_item' title='{{name}}' data-emoji='{{code}}'>{{{display}}}</div>");ips.templates.set('core.editor.emojiNotNative'," <div class='ipsEmoticons_item' title='{{name}}' data-emoji='{{code}}'>{{{img}}}</div>");ips.templates.set('core.editor.emoticonBlank'," <div class='ipsEmoticons_item'>&nbsp;</div>");ips.templates.set('core.editor.emoticonNoResults'," <div class='i-padding_3 i-text-align_center i-color_soft'>{{#lang}}no_results{{/lang}}</div>");ips.templates.set('core.editor.emojiResult'," <li class='ipsMenu_item i-cursor_pointer' title='{{name}}' data-emoji='{{code}}'> <a><span class='ipsEmoji_result'>{{{emoji}}}</span> <span data-role='shortCode'>{{short_code}}</span></a> </li>");ips.templates.set('core.editor.quote',"<blockquote class='ipsQuote' data-ipsQuote data-gramm='false' cite='{{citeurl}}'><div class='ipsQuote_citation'>{{{citation}}}</div><div class='ipsQuote_contents ipsClearfix' data-gramm='false'>{{{contents}}}</div></blockquote>");ips.templates.set('core.editor.legacyQuoteUpcast',"<div class='ipsQuote_citation'>{{citation}}</div><div class='ipsQuote_contents ipsClearfix' data-gramm='false'>{{{contents}}}</div>");ips.templates.set('core.editor.citation'," <div class='ipsQuote_citation ipsQuote_open'> <a href='#' data-action='toggleQuote' aria-label='{{#lang}}toggle_quote{{/lang}}'>&nbsp;</a> {{#contenturl}} <a href='{{contenturl}}' class='ipsQuote_citation-origin'><i class='fa-solid fa-share'></i></a> {{/contenturl}} {{{citation}}} </div>");ips.templates.set('core.editor.citationLink'," <a href='{{baseURL}}?app=core&module=members&controller=profile&id={{userid}}' data-ipsHover data-ipshover-target='{{baseURL}}?app=core&module=members&controller=profile&id={{userid}}&do=hovercard'>{{username}}</a>");ips.templates.set('core.editor.spoiler',"<div class='ipsSpoiler' data-ipsSpoiler><div class='ipsSpoiler_header'><span>{{#lang}}editorSpoiler{{/lang}}</span></div><div class='ipsSpoiler_contents ipsClearfix'></div></div>");ips.templates.set('core.editor.legacySpoilerUpcast',"<div class='ipsSpoiler_header'><span>{{#lang}}editorSpoiler{{/lang}}</span></div><div class='ipsSpoiler_contents ipsClearfix' data-gramm='false'>{{{contents}}}</div>");ips.templates.set('core.editor.spoilerHeader'," <summary class='ipsSpoiler_header ipsSpoiler_closed'> <span>{{#lang}}spoilerClickToReveal{{/lang}}</span> </summary>");ips.templates.set('core.editor.initLoading'," <div class='ipsLoading ipsLoading--tiny'>&nbsp;</div>");ips.templates.set('core.editor.previewLoading'," <div data-role='previewLoading' class='ipsLoading' style='min-height: 100px'> &nbsp; </div>");ips.templates.set('core.attachments.metaInfo'," <span>{{size}}</span> <span>&middot;</span> <span>{{downloads}}</span>");ips.templates.set('core.attachments.attachmentPreview'," <span class='ipsAttachLink_box'><span class='ipsAttachLink_title'>{{title}}</span><span class='ipsAttachLink_metaInfo'>{{#lang}}attachmentPending{{/lang}}</span></span>");ips.templates.set('core.attachments.fileItemWrapper'," <div class='ipsUploader__container ipsUploader__container--files'>{{{content}}}</div>");ips.templates.set('core.attachments.fileItem'," <div class='ipsUploader__row ipsUploader__row--file ipsAttach {{#done}}ipsAttach_done{{/done}}' id='{{id}}' data-role='file' data-fileid='{{id}}' data-filesize='{{sizeRaw}}' data-filekey='{{securityKey}}'> <div class='ipsUploader__rowPreview' data-role='preview' {{#insertable}}data-action='insertFile'{{/insertable}}> {{#thumb}} {{{thumb}}} {{/thumb}} <div class='ipsUploader__rowPreview__generic' {{#thumb}}style='display: none'{{/thumb}}> <i class='fa-solid fa-{{extIcon}}'></i> </div> </div> <div class='ipsUploader_rowMeta' {{#insertable}}data-action='insertFile'{{/insertable}}> <h2 class='ipsUploader_rowTitle' data-role='title'>{{title}}</h2> <p class='ipsUploader_rowDesc'> {{size}} {{#statusText}}&middot; <span class='i-color_soft' data-role='status'>{{statusText}}</span>{{/statusText}} </p> {{#status}}<meter class='ipsMeter' data-role='progressbar' max='100'></meter>{{/status}} <div data-role='insert' class='ipsUploader__rowInsert' {{#insertable}}style='display: none'{{/insertable}}> <a href='#' data-ipsTooltip title='{{#lang}}insertIntoPost{{/lang}}'> {{#lang}}insert{{/lang}} </a> </div> </div> {{#supportsDelete}} <div data-role='deleteFileWrapper' {{#newUpload}}style='display: none'{{/newUpload}}> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' data-role='deleteFile' class='ipsUploader__rowDelete' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'> &times; </a> </div> {{/supportsDelete}} {{^supportsDelete}} <div data-role='deleteFileWrapper' style='display: none'> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' class='ipsUploader__rowDelete' data-role='deleteFile' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'>&times;</a> </div> {{/supportsDelete}} </div>");ips.templates.set('core.attachments.imageItem'," <div class='ipsUploader__row ipsUploader__row--image ipsAttach {{#done}}ipsAttach_done{{/done}}' id='{{id}}' data-role='file' data-fileid='{{id}}' data-fullsizeurl='{{imagesrc}}' data-thumbnailurl='{{thumbnail}}' data-fileType='image'> <div class='ipsUploader__rowPreview' data-role='preview' {{#insertable}}data-action='insertFile'{{/insertable}}> {{#thumb}} {{{thumb}}} {{/thumb}} <div class='ipsUploader__rowPreview__generic' {{#thumb}}style='display: none'{{/thumb}}> <i class='fa-solid fa-{{extIcon}}'></i> </div> </div> <div class='ipsUploader_rowMeta' {{#insertable}}data-action='insertFile'{{/insertable}}> <h2 class='ipsUploader_rowTitle' data-role='title'>{{title}}</h2> <p class='ipsUploader_rowDesc'> {{size}} {{#statusText}}&middot; <span class='i-color_soft' data-role='status'>{{statusText}}</span>{{/statusText}} </p> {{#status}}<meter class='ipsMeter' data-role='progressbar' max='100'></meter>{{/status}} <div data-role='insert' class='ipsUploader__rowInsert' {{#insertable}}style='display: none'{{/insertable}}> <a href='#' data-ipsTooltip title='{{#lang}}insertIntoPost{{/lang}}'> {{#lang}}insert{{/lang}} </a> </div> </div> {{#supportsDelete}} <div data-role='deleteFileWrapper' {{#newUpload}}style='display: none'{{/newUpload}}> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' data-role='deleteFile' class='ipsUploader__rowDelete' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'> &times; </a> </div> {{/supportsDelete}} {{^supportsDelete}} <div data-role='deleteFileWrapper' style='display: none'> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' class='ipsUploader__rowDelete' data-role='deleteFile' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'>&times;</a> </div> {{/supportsDelete}} </div>");ips.templates.set('core.attachments.videoItem'," <div class='ipsUploader__row ipsUploader__row--image ipsAttach {{#done}}ipsAttach_done{{/done}}' id='{{id}}' data-role='file' data-fileid='{{id}}' data-fullsizeurl='{{imagesrc}}' data-thumbnailurl='{{thumbnail}}' data-fileType='video' data-mimeType='{{mime}}'> <div class='ipsUploader__rowPreview' data-role='preview' {{#insertable}}data-action='insertFile'{{/insertable}}> {{#thumb}} <video> <source src='{{{thumb}}}' type='{{mime}}'> </video> {{/thumb}} <div class='ipsUploader__rowPreview__generic' {{#thumb}}style='display: none'{{/thumb}}> <i class='fa-solid fa-{{extIcon}}'></i> </div> </div> <div class='ipsUploader_rowMeta' {{#insertable}}data-action='insertFile'{{/insertable}}> <h2 class='ipsUploader_rowTitle' data-role='title'>{{title}}</h2> <p class='ipsUploader_rowDesc'> {{size}} {{#statusText}}&middot; <span class='i-color_soft' data-role='status'>{{statusText}}</span>{{/statusText}} </p> {{#status}}<meter class='ipsMeter' data-role='progressbar' max='100'></meter>{{/status}} <div data-role='insert' class='ipsUploader__rowInsert' {{#insertable}}style='display: none'{{/insertable}}> <a href='#' data-ipsTooltip title='{{#lang}}insertIntoPost{{/lang}}'> {{#lang}}insert{{/lang}} </a> </div> </div> {{#supportsDelete}} <div data-role='deleteFileWrapper' {{#newUpload}}style='display: none'{{/newUpload}}> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' data-role='deleteFile' class='ipsUploader__rowDelete' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'> &times; </a> </div> {{/supportsDelete}} {{^supportsDelete}} <div data-role='deleteFileWrapper' style='display: none'> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' class='ipsUploader__rowDelete' data-role='deleteFile' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'>&times;</a> </div> {{/supportsDelete}} </div>");ips.templates.set('core.attachments.audioItem'," <div class='ipsUploader__row ipsUploader__row--image ipsAttach {{#done}}ipsAttach_done{{/done}}' id='{{id}}' data-role='file' data-fileid='{{id}}' data-fullsizeurl='{{imagesrc}}' data-thumbnailurl='{{thumbnail}}' data-fileType='audio' data-mimeType='{{mime}}'> <div class='ipsUploader__rowPreview' data-role='preview' {{#insertable}}data-action='insertFile'{{/insertable}}> {{#thumb}} <audio src='{{{thumb}}}' type='{{mime}}'> </audio> {{/thumb}} <div class='ipsUploader__rowPreview__generic' {{#thumb}}style='display: none'{{/thumb}}> <i class='fa-solid fa-{{extIcon}}'></i> </div> </div> <div class='ipsUploader_rowMeta' {{#insertable}}data-action='insertFile'{{/insertable}}> <h2 class='ipsUploader_rowTitle' data-role='title'>{{title}}</h2> <p class='ipsUploader_rowDesc'> {{size}} {{#statusText}}&middot; <span class='i-color_soft' data-role='status'>{{statusText}}</span>{{/statusText}} </p> {{#status}}<meter class='ipsMeter' data-role='progressbar' max='100'></meter>{{/status}} <div data-role='insert' class='ipsUploader__rowInsert' {{#insertable}}style='display: none'{{/insertable}}> <a href='#' data-ipsTooltip title='{{#lang}}insertIntoPost{{/lang}}'> {{#lang}}insert{{/lang}} </a> </div> </div> {{#supportsDelete}} <div data-role='deleteFileWrapper' {{#newUpload}}style='display: none'{{/newUpload}}> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' data-role='deleteFile' class='ipsUploader__rowDelete' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'> &times; </a> </div> {{/supportsDelete}} {{^supportsDelete}} <div data-role='deleteFileWrapper' style='display: none'> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' class='ipsUploader__rowDelete' data-role='deleteFile' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'>&times;</a> </div> {{/supportsDelete}} </div>");ips.templates.set('core.attachments.imageItemWrapper'," <div class='ipsGrid ipsGrid--image-item-wrapper i-basis_160'>{{{content}}}</div>");ips.templates.set('core.forms.validationWrapper'," <ul id='{{id}}' class='i-font-size_-2 ipsForm_errorList'>{{content}}</ul>");ips.templates.set('core.forms.validationItem'," <li class='i-color_warning'>{{message}}</li>");ips.templates.set('core.forms.advicePopup',"<div class='ipsHovercard' data-role='advicePopup' id='elPasswordAdvice_{{id}}'> <div class='i-padding_3'> <h2 class='ipsTitle ipsTitle--h4'>{{#lang}}password_advice_title{{/lang}}</h2> <p class='i-margin-top_2'> {{#min}} {{min}} {{/min}} {{{text}}} </p> </div> <span class='ipsHovercard_stem'></span></div>");ips.templates.set('core.forms.validateOk',"<span> <i class='fa-solid fa-check-circle i-color_positive'></i></span>");ips.templates.set('core.forms.validateFail',"<span data-ipsTooltip data-ipsTooltip-label='{{message}}'> <i class='fa-solid fa-circle-xmark i-color_negative'></i></span>");ips.templates.set('core.forms.validateFailText',"<p data-el='validate-fail' class='i-margin-top_2 i-color_negative i-font-weight_500'> <i class='fa-solid fa-circle-xmark'></i> {{message}}</p>");ips.templates.set('core.truncate.expand'," <button type='button' class='ipsTruncate_more' data-action='expandTruncate'><span>{{text}}</span><i class='fa-solid fa-caret-down'></i></button>");ips.templates.set('core.selectTree.token'," <li><span class='ipsSelectTree_token cToken' data-nodeID='{{id}}'>{{title}}</span></li>");ips.templates.set('core.accessibility.border'," <div id='ipsAccessibility_border'></div>");ips.templates.set('core.accessibility.arrow'," <div id='ipsAccessibility_arrow'></div>");ips.templates.set('core.infScroll.loading'," <li class='i-padding_3 i-text-align_center' data-role='infScroll_loading'> {{#lang}}loading{{/lang}}... </li>");ips.templates.set('core.infScroll.pageBreak'," <li class='i-padding_2 i-background_3' data-role='infScroll_break' data-infScrollPage='{{page}}'> {{#lang}}page{{/lang}} {{page}} </li>");ips.templates.set('core.pageAction.actionMenuItem'," <li> <button type='button' class='ipsPageAction__button' id='{{id}}_{{action}}' popovertarget='{{id}}_{{action}}_menu' data-role='actionMenu' data-action='{{action}}' data-ipsTooltip title='{{title}}'> <span> {{#icon}} <i class='fa-solid fa-{{icon}} ipsPageAction_icon'></i> <i class='fa-solid fa-caret-up'></i> {{/icon}} {{^icon}} <span class='ipsPageAction_text'>{{title}} <i class='fa-solid fa-caret-up'></i></span> {{/icon}} </span> </button> <i-dropdown popover id='{{id}}_{{action}}_menu'> <div class='iDropdown'> <ul class='iDropdown__items'> {{{menucontent}}} </ul> </div> </i-dropdown> </li>");ips.templates.set('core.pageAction.actionItem'," <li> <button type='button' class='ipsPageAction__button' data-role='actionButton' data-action='{{action}}' id='{{id}}_{{action}}' data-ipsTooltip title='{{title}}'> <span> {{#icon}} <i class='fa-solid fa-{{icon}} ipsPageAction_icon' data-ipsTooltip='{{title}}'></i></i> {{/icon}} {{^icon}} <span class='ipsPageAction_text'>{{title}}</span> {{/icon}} </span> </button> </li>");ips.templates.set('core.pageAction.wrapper'," <div class='ipsPageAction' data-role='actionBar' id='{{id}}_bar'> <ul data-role='actionItems'> <li class='ipsPageAction__title'><span>{{{selectedLang}}}</span></li> {{{content}}} </ul> </div>");ips.templates.set('core.carousel.bulletWrapper'," <ul class='ipsCarousel_bullets'>{{content}}</ul>");ips.templates.set('core.carousel.bulletItem'," <li><i class='fa-solid fa-circle'></i></li>");ips.templates.set('core.rating.wrapper'," <div class='ipsRating'> <ul class='{{className}}' data-role='ratingList'> {{{content}}} </ul> <div data-role='ratingStatus' class='i-color_soft i-font-size_-1'>{{status}}</div> </div>")
ips.templates.set('core.rating.star'," <li class='{{className}}' data-ratingValue='{{value}}'><a href='#'><i class='fa-solid fa-star'></i></a></li>");ips.templates.set('core.rating.halfStar'," <li class='ipsRating_half' data-ratingValue='{{value}}'><i class='fa-solid fa-star-half'></i><i class='fa-solid fa-star-half fa-flip-horizontal'></i></li>");ips.templates.set('core.rating.loading'," <i class='ipsLoadingIcon'></span>");ips.templates.set('core.sidebar.managerWrapper',`\
<div id='elSidebarManager' data-role='manager' class='ipsToolbox' hidden>
<div class='ipsToolbox__tools'>
<div class='i-padding_2' id="elSidebarManager_header">
<div data-role="title">
<h3 class='ipsToolbox_title'>{{#lang}}sidebarManager{{/lang}}</h3>
<span data-role="info">
<i class="fa-solid fa-info-circle"></i>
<div data-role="description" class="ipsBox i-padding_2" >
<p class='i-color_soft'>{{#lang}}sidebarManagerDesc{{/lang}}</p>
<p class='i-color_soft i-margin-top_2'>{{#lang}}sidebarManagerDesc2{{/lang}}</p>
</div>
</span>
</div>
<input type="text" data-role="widgetSearch" placeholder="{{#lang}}sidebarManagerSearchPlaceholder{{/lang}}" class="ipsInput ipsInput--widget-search" />
</div>
<div data-role='availableBlocks' data-unloaded="true" class='ipsLoading ipsScrollbar'></div>
<div data-role="emptyMessage" class="i-padding_2" hidden>{{#lang}}sidebarManagerSearchEmpty{{/lang}}</div>
</div>
<div id='elSidebarManager_submit' class='i-flex_00 i-padding_3 ipsButtons i-gap_2'>
<button class='ipsButton ipsButton--positive ipsButton--wide' data-action='closeSidebar'><i class='fa-regular fa-floppy-disk'></i><span>{{#lang}}finishEditing{{/lang}}</span></button>
</div>
</div>
`);ips.templates.set('core.sidebar.blockManage'," <div class='cSidebarBlock_managing'> <h4>{{title}}</h4> <button type='button' id='{{id}}_edit' popovertarget='{{id}}_edit_menu' data-action='manageBlock' class='ipsButton ipsButton--icon ipsButton--primary' data-ipsTooltip title='{{#lang}}editBlock{{/lang}}'> <i class='fa-solid fa-pencil'></i> </button> <button type='button' data-action='removeBlock' class='ipsButton ipsButton--icon ipsButton--inherit' data-ipsTooltip title='{{#lang}}removeBlock{{/lang}}'><i class='fa-solid fa-xmark'></i></button> <i-dropdown popover id='{{id}}_{{action}}_menu'> <div class='iDropdown'></div> </i-dropdown> </div>");ips.templates.set('core.sidebar.blockManageNoConfig'," <div class='cSidebarBlock_managing'> <h4>{{title}}</h4> <button type='button' data-action='removeBlock' class='ipsButton ipsButton--icon ipsButton--inherit' data-ipsTooltip title='{{#lang}}removeBlock{{/lang}}'><i class='fa-solid fa-xmark'></i></button> </div>");ips.templates.set('core.sidebar.blockIsEmpty'," <div class='ipsWidgetBlank'> {{text}} </div>");ips.templates.set('core.follow.loading'," <div class='ipsLoading ipsLoading--tiny'></div>");ips.templates.set('core.statuses.loadingComments'," <i class='ipsLoadingIcon'></i> &nbsp;<span class='i-color_soft'> &nbsp;{{#lang}}loadingComments{{/lang}}</span>");ips.templates.set('core.forms.stack'," <li class='ipsField_stackItem' data-role='stackItem'> <span class='ipsField_stackDrag ipsDrag' data-action='stackDrag'> <i class='fa-solid fa-bars ipsDrag_dragHandle'></i> </span> <a href='#' class='ipsField_stackDelete i-cursor_pointer' data-action='stackDelete'> &times; </a> <div data-ipsStack-wrapper> {{{field}}} </div> </li>");ips.templates.set('core.pollEditor.question'," <div class='' data-role='question' data-questionID='{{questionID}}'> <div class='i-margin-bottom_2'> <input type='text' data-role='questionTitle' name='{{pollName}}[questions][{{questionID}}][title]' placeholder='{{#lang}}questionPlaceholder{{/lang}}' class='ipsInput ipsInput--text ipsInput--wide' value='{{question}}'> </div> <div> <ul class='cPollChoices i-grid' data-role='choices'> <li class='i-padding-block_1 i-flex i-align-items_center i-gap_2 ipsResponsive_hidePhone'> <span class='i-basis_30 i-flex_00'></span> <div class='i-flex_11'><strong>{{#lang}}choicesTitle{{/lang}}</strong></div> {{#showCounts}} <span class='i-flex_00'><strong>{{#lang}}votesTitle{{/lang}}</strong></span> {{/showCounts}} <span class='i-basis_60'></span> </li> {{{choices}}} </ul> <div class='i-padding-block_1 i-flex i-align-items_center i-gap_2 i-flex-wrap_wrap'> <span class='i-basis_30 i-flex_00'></span> <a href='#' data-action='addChoice' class='ipsButton ipsButton--inherit'>{{#lang}}addChoice{{/lang}}</a> <div class='i-flex_11 i-flex i-align-items_center i-gap_1'> <input type='checkbox' id='elPoll_{{pollName}}_{{questionID}}multi' name='{{pollName}}[questions][{{questionID}}][multichoice]' {{#multiChoice}}checked{{/multiChoice}} class='ipsInput ipsInput--toggle'> <label for='elPoll_{{pollName}}_{{questionID}}multi'>{{#lang}}multipleChoiceQuestion{{/lang}}</label></li> </div> {{#removeQuestion}}<div class='i-flex_00'><a href='#' data-action='removeQuestion' class='ipsButton ipsButton--inherit i-color_negative'>{{#lang}}removeQuestion{{/lang}}</a></div>{{/removeQuestion}} </div> </div> </div>");ips.templates.set('core.pollEditor.choice'," <li class='i-padding-block_1 i-flex i-align-items_center i-gap_2' data-choiceID='{{choiceID}}'> <span class='i-basis_30 i-flex_00 i-text-align_center cPollChoiceNumber'> <strong data-role='choiceNumber'>{{choiceID}}</strong> </span> <div class='i-flex_11'> <input type='text' name='{{pollName}}[questions][{{questionID}}][answers][{{choiceID}}][value]' value='{{choiceTitle}}' class='ipsInput ipsInput--text ipsInput--wide'> </div> <div class='i-flex_00'> <a href='#' data-action='removeChoice' class='ipsButton ipsButton--inherit i-color_negative'><i class='fa-solid fa-xmark'></i></a> </div> </li>");ips.templates.set('core.coverPhoto.controls'," <ul class='ipsCoverPhoto__overlay-buttons' data-role='coverPhotoControls'> <li><a href='#' class='ipsButton ipsButton--overlay' data-action='cancelPosition'><i class='fa-solid fa-xmark'></i><span>{{#lang}}cancel{{/lang}}</span></a></li> <li><a href='#' class='ipsButton ipsButton--soft' data-action='savePosition'><i class='fa-solid fa-check'></i><span>{{#lang}}save_position{{/lang}}</span></a></li> </ul>");ips.templates.set('core.editor.preferences'," <div id='editorPreferencesPanel' class='i-padding_3'> <div class='ipsMessage ipsMessage--info'> {{#lang}}papt_warning{{/lang}} </div> <br> <ul class='ipsForm ipsForm--vertical ipsForm--editor-preferences'> <li class='ipsFieldRow'> <div class='ipsFieldRow__content'> <input type='checkbox' {{#checked}}checked{{/checked}} name='papt' id='papt'> <label for='papt'>{{#lang}}papt_label{{/lang}}</label> </div> </li> </ul> <div class='i-padding-top_2 i-text-align_center'> <button class='ipsButton ipsButton--primary' id='papt_submit'>{{#lang}}save_preference{{/lang}}</button> </div> </div> ");ips.templates.set('core.pagination'," <ul class='ipsPagination' data-ipsPagination data-ipsPagination-pages='{{pages}}'> <li class='ipsPagination__prev'> <a href='#' data-page='prev'><i class='fa-solid fa-caret-left'></i> {{#lang}}prev_page{{/lang}}</a> </li> <li class='ipsPagination__next'> <a href='#' data-page='next'>{{#lang}}next_page{{/lang}} <i class='fa-solid fa-caret-right'></i></a> </li> </ul>");ips.templates.set('core.selection.quote'," <div class='ipsTooltip ipsTooltip_{{direction}} ipsTooltip--inlineQuoteTooltip' data-role='inlineQuoteTooltip' popover='manual'> <a href='#' data-action='quoteSelection'> <i class='fa-solid fa-quote-left'></i> {{#lang}}quote_selected_text{{/lang}} </a> </div>");ips.templates.set('core.contentItem.resultItem'," <li class='ipsAutocompleteMenu_item' data-id='{{{id}}}' role='option' role='listitem'> {{{html}}} </li>");ips.templates.set('core.contentItem.field'," <div class='ipsInput ipsField_autocomplete' id='{{id}}_wrapper' role='combobox' aria-autocomplete='list' aria-owns='{{id}}_results'> <span class='ipsField_autocomplete_loading' style='display: none' id='{{id}}_loading'></span> <ul class='ipsList ipsList--inline'><li id='{{id}}_inputItem'>{{content}}</li></ul> </div>");ips.templates.set('core.contentItem.resultWrapper'," <div class='ipsAutocompleteMenu' id='{{id}}_results' aria-expanded='false' style='display: none'> <ul class='ipsAutocompleteMenu_itemWrapper' data-role='items'></ul> </div>");ips.templates.set('core.contentItem.item'," <li data-id='{{id}}'> <span class='cContentItem_delete' data-action='delete'>&times;</span> {{{html}}} </li>");ips.templates.set('promote.imageUpload'," <div class='cPromote_attachImage' id='{{id}}' data-role='file' data-fileid='{{id}}' data-fullsizeurl='{{imagesrc}}' data-thumbnailurl='{{thumbnail}}' data-fileType='image'> <div data-role='preview'> {{#thumbnail}}<img src='{{thumbnail}}' alt='' loading='lazy'>{{/thumbnail}} </div> <ul class='ipsImageAttach_controls'> <li class='' {{#newUpload}}style='display: none'{{/newUpload}} data-role='deleteFileWrapper'> <input type='hidden' name='{{field_name}}_keep[{{id}}]' value='1'> <a href='#' data-role='deleteFile' class='ipsButton ipsButton--small ipsButton--soft' data-ipsTooltip title='{{#lang}}attachRemove{{/lang}}'><i class='fa-regular fa-trash-can'></i></a> </li> </ul> <meter class='ipsMeter' data-role='progressbar' max='100'></meter> </div>");ips.templates.set('table.row.loading',`
<li class='ipsData__item ipsData__item--loading'>
<div class='ipsData__image'></div>
<div class='ipsData__content'>
<div class='ipsData__main'>
<div class='ipsData__title'></div>
<div class='ipsData__meta'></div>
</div>
<div class='ipsData__stats'></div>
<div class='ipsData__last'></div>
</div>
</li>
`);ips.templates.set('licenseRenewal.wrapper'," <div class='acpLicenseRenewal' data-role='licenseRenewal'> <div class='acpLicenseRenewal_wrap'> <div class='acpLicenseRenewal_inner'> <div class='acpLicenseRenewal_content i-padding_3'> <h4 class='i-font-size_3 i-font-weight_600 i-color_hard i-margin-bottom_2' data-role='mainTitle'>{{#lang}}licenseRenewalTitle{{/lang}}</h4> <p class='i-color_soft'>{{#lang}}licenseRenewalText{{/lang}}</p> <div class='i-margin-top_2 i-flex i-align-items_center i-gap_1 i-font-weight_500'><input type='checkbox' checked='checked' name='hideRenewalNotice' id='hideRenewalNotice' class='ipsInput ipsInput--toggle'> <label for='hideRenewalNotice'>{{#lang}}licenseRenewalCheckbox{{/lang}}</label></div> </div> <ul class='ipsButtons i-background_2 i-border-top_1 i-border-end-start-radius_box i-border-end-end-radius_box i-padding_2'> <li> <a href='#' class='ipsButton ipsButton--inherit' data-action='closeLicenseRenewal'>{{#lang}}licenseRenewalNo{{/lang}}</a> </li> <li> <a href='#' class='ipsButton ipsButton--primary' data-role='survey' data-action='closeLicenseRenewal' target='_blank'>{{#lang}}licenseRenewalYes{{/lang}}</a> </li> </ul> </div> </div> </div>");ips.templates.set('core.browserNotification.prompt'," <div class='cNotifcationPrompt'> <div class='i-padding_3'> <div class='ipsPhotoPanel ipsPhotoPanel--mini'> <span class='cNotifcationPrompt_icon'></span> <div> <a href='#' class='cNotifcationPrompt_dismiss' data-role=\"dismissNotification\">×</a> <h3 class='cNotifcationPrompt_title i-font-size_2 ipsType_sectionHead'>{{#lang}}notificationsCallout{{/lang}}</h3> <p class='cNotifcationPrompt_text i-margin-top_2'> {{#lang}}notificationsDefaultBlurb{{/lang}} </p> <div class='ipsButtons i-margin-top_3'> <button data-action='browserNotificationPrompt' class='ipsButton ipsButton--small ipsButton--soft ipsButton--wide'>{{#lang}}notificationsAllow{{/lang}}</button> </div> <p class='i-font-size_-2 i-margin-block_2 ipsHide' data-role='promptMessage'> {{#lang}}notificationsAllowPrompt{{/lang}} </p> </div> </div> </div> </div>");ips.templates.set('core.browserNotification.missingSubscription'," <div class='cNotifcationPrompt'> <div class='i-padding_3'> <div class='ipsPhotoPanel ipsPhotoPanel--mini'> <span class='cNotifcationPrompt_icon'></span> <div> <a href='#' class='cNotifcationPrompt_dismiss' data-role=\"dismissNotification\">×</a> <h3 class='cNotifcationPrompt_title i-font-size_2 ipsType_sectionHead'>{{#lang}}notificationsCalloutPush{{/lang}}</h3> <p class='cNotifcationPrompt_text i-margin-block_2'> {{#lang}}notificationsDefaultBlurb{{/lang}} </p> <div class='ipsButtons i-margin-top_3'> <button data-action='browserNotificationPrompt' class='ipsButton ipsButton--small ipsButton--soft i-flex_11'>{{#lang}}notificationsAllow{{/lang}}</button> <a href='#' data-action='rejectPush' class='ipsButton ipsButton--small ipsButton--text i-color_white i-flex_00'>{{#lang}}notificationsNoThanks{{/lang}}</a> </div> <p class='i-font-size_-2 i-margin-block_2 ipsHide' data-role='promptMessage'> {{#lang}}notificationsAllowPrompt{{/lang}} </p> </div> </div> </div> </div>");ips.templates.set('core.notifications.pending'," <span class='i-color_soft'>{{#lang}}notificationsEnabling{{/lang}}</span>");ips.templates.set('core.notifications.success'," <span class='i-color_positive'><i class='fa-solid fa-check'></i> {{#lang}}notificationsEnabled{{/lang}}</span>");ips.templates.set('core.notifications.fail'," <span class='i-color_negative'><i class='fa-solid fa-xmark'></i> {{#lang}}notificationsFailed{{/lang}}</span>");ips.templates.set('core.notifications.notSupported'," <span class='i-color_soft'><i class='fa-solid fa-xmark'></i> {{#lang}}notificationsNotSupported{{/lang}}</span>");ips.templates.set('core.notifications.checking'," <span class='i-color_soft'>{{#lang}}notificationsChecking{{/lang}}</span>");ips.templates.set('system.warningpenalty.nomodify'," <ul class='ipsList ipsList--bullets' id='elWarningPenalties'> {{#penalties}} <li>{{.}}</li> {{/penalties}} </ul>");ips.templates.set('core.edittags.default'," <div class='i-padding_3'> <span><i class='ipsLoadingIcon'></i> &nbsp;{{#lang}}loading{{/lang}}</span> </div>");ips.templates.set('core.onlineUser.linked',"<li data-memberId='{{memberId}}'> <a href='{{memberUrl}}' data-ipsHover data-ipsHover-target='{{memberHovercardUrl}}'>{{{formattedName}}}</a></li>");ips.templates.set('core.iconpicker.wrap',`
<form action="#" class="ipsIconPicker">
<div class="ipsIconPicker__tabs">
<div data-role="tabs">
{{#allowedTypes}}
<button data-role="tab" data-tab="{{type}}" type="button">{{#lang}}ips_icon_picker__tab_{{type}}{{/lang}}</button>
{{/allowedTypes}}
</div>
<button class="ipsIconPicker__close" data-role="close" aria-label="close" title="{{#lang}}close{{/lang}}" type="button"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="ipsIconPicker__search">
<input type="text" name="icon_picker_search_box" data-role="search" placeholder="{{#lang}}iconpicker_prompt{{/lang}}" class='ipsInput'>
{{#allowedTypes}}
<div data-role="type_selectors">
{{#typeOptions}}
<select value="{{{current}}}" name="icon_type_selector" data-field="{{type}}" class='ipsInput'>
{{#options}}
<option value="{{{value}}}" title="{{title}}" aria-label="{{title}}">{{label}}</option>
{{/options}}
</select>
{{/typeOptions}}
</div>
{{/allowedTypes}}
</div>
<div class="ipsIconPicker__iconWrap">
{{#allowedTypes}}
<article data-role="{{type}}area" class="ipsIconPicker__container" {{#hidden}}style="display: none"{{/hidden}}>
<a href="https://fontawesome.com/v6/search?o=r&m=free" target="_blank" class="ipsIconPicker__fa-attribution" tabindex="-1">Icons by Font Awesome <i class="fa-solid fa-arrow-up-right-from-square"></i></a>
<div data-role="icons"></div>
</article>
{{/allowedTypes}}
</div>
<div data-role="selected_icons"></div>
<div class="ipsSubmitRow">
<button type="submit" aria-label="{{selectlang}}" class="ipsButton ipsButton--primary">{{selectlang}}</button>
</div>
</form>
`)
ips.templates.set('core.iconpicker.category',`\
<section class="ipsIconPicker__category" data-icon-category="{{{name}}}">
<h4 class="ipsIconPicker__category-title">{{name}} ({{icons.length}})</h4>
<div data-role="iconarea">
{{#icons}}
<button
type="button"
data-role="iconpicker_item"
data-ips-tooltip
class="ipsIconPicker__option {{#disabled}}ipsButton--disabled{{/disabled}}"
title="{{#disabled}}{{#lang}}iconpicker_icon_cannot_add{{/lang}}{{/disabled}}{{^disabled}}{{title}}{{/disabled}}"
data-icon-type="{{type}}"
data-icon-title="{{title}}"
data-icon-key="{{key}}"
{{#selected}}data-icon-selected{{/selected}}
data-icon-hair-style="{{hairStyle}}"
data-icon-skin-tone="{{skinTone}}"
>
<!-- <div class="ipsIconPicker__content">-->
{{#raw}}
{{{raw}}}
{{/raw}}
{{#image}}
<span class="ipsEmoji">
<img src="{{{image}}}" alt="" />
</span>
{{/image}}
<!-- </div>-->
<div class="ipsIconPicker__title">{{title}}</div>
</button>
{{/icons}}
</div>
</section>\
`)
ips.templates.set('core.iconpicker.selectedicon',`\
<li
data-role="iconpicker_item"
data-ips-tooltip
title="{{#disabled}}{{#lang}}iconpicker_icon_cannot_add{{/lang}}{{/disabled}}{{^disabled}}{{title}}{{/disabled}}"
data-icon-type="{{type}}"
data-icon-title="{{title}}"
data-icon-key="{{key}}"
data-icon-hair-style="{{hairStyle}}"
data-icon-skin-tone="{{skinTone}}"
>
<div class="ipsIconPicker__content">
{{{raw}}}
</div>
<div class="ipsIconPicker__title">{{title}}</div>
</li>\
`)
ips.templates.set('tableOfContents.linkOptions',`\
<span class="ipsTableOfContents__linkOptions">
<a href="#{{id}}" class="ipsButton ipsButton--text" data-role="link" aria-label="{{#lang}}table_of_contents_link{{/lang}}" data-ipstooltip title="{{#lang}}table_of_contents_link{{/lang}}" >
<i class="fa-solid fa-link"></i>
</a>
{{#canEdit}}
<button type="button" class="ipsButton ipsButton--primary" data-ipstooltip title="{{#lang}}table_of_contents_add{{/lang}}" data-role="add" aria-label="{{#lang}}table_of_contents_add{{/lang}}" >
<i class="fa-solid fa-plus"></i>
</button>
<span class="ipsTableOfContents__incrementOptions">
<button type="button" class="ipsButton ipsButton--text" data-ipstooltip title="{{#lang}}table_of_contents_decrement{{/lang}}" data-role="decrement" aria-label="{{#lang}}table_of_contents_decrement{{/lang}}" >
<i class="fa-solid fa-outdent"></i>
</button>
<button type="button" class="ipsButton ipsButton--text" data-ipstooltip title="{{#lang}}table_of_contents_increment{{/lang}}" data-role="increment" aria-label="{{#lang}}table_of_contents_increment{{/lang}}" >
<i class="fa-solid fa-indent"></i>
</button>
</span>
<button type="button" class="ipsButton ipsButton--negative" data-ipstooltip title="{{#lang}}table_of_contents_remove{{/lang}}" data-role="remove" aria-label="{{#lang}}table_of_contents_remove{{/lang}}" >
<i class="fa-solid fa-times"></i>
</button>
{{/canEdit}}
</span>
`);ips.templates.set('ips.ui.controls.cannot_load',`
<div class="{{{classList}}} ipsControls__fail-message">{{message}}</div>
`,{classList:'ipsMessage ipsMessage--info',get message(){return ips.getString('ips.ui.controls.cannot_load')}});
ips.templates.set('core.autocomplete.field'," <div class='ipsInput ipsField_autocomplete ipsAutoComplete' id='{{id}}_wrapper' role='combobox' aria-autocomplete='list' aria-owns='{{id}}_results'> <span class='ipsField_autocomplete_loading' style='display: none' id='{{id}}_loading'></span> <ul class='ipsAutoComplete__list' role='listbox'><li class='ipsAutoComplete__add' id='{{id}}_inputItem' role='option'>{{content}}</li></ul> </div>");ips.templates.set('core.autocomplete.addToken'," <a href='#' data-action='addToken'><i class='fa-solid fa-tag i-margin-end_icon'></i>{{text}}</a> ");ips.templates.set('core.autocomplete.resultWrapper'," <div class='ipsAutocompleteMenu' id='{{id}}_results' aria-expanded='false' style='display: none'> <ul class='ipsAutocompleteMenu_itemWrapper' role='listbox' aria-expanded='false' data-role='items'></ul> <div class='ipsAutocompleteMenu_empty' data-role='noresults' hidden>{{#lang}}autocomplete_no_results{{/lang}}</div> </div>");ips.templates.set('core.autocomplete.searchTypeAhead'," <div class='ipsAutocompleteMenu__search' data-role='autocompleteSearch'> <input type='search' name='autocompleteSearch' placeholder='{{#lang}}autocomplete_search_placeholder{{/lang}}'> </div>");ips.templates.set('core.autocomplete.resultItem'," <li class='ipsAutocompleteMenu_item' data-value='{{value}}' role='option'> {{{html}}} </li>");ips.templates.set('core.autocomplete.tagsResultItem'," <li class='ipsAutocompleteMenu_item' data-value='{{value}}' role='option'> <div class='i-flex i-align-items_center'> <div class='i-flex_11'>{{{html}}}</div> {{#recommended}} <span class='i-flex_00 i-color_positive'>{{#lang}}tag_recommended{{/lang}} {{/recommended}} </div> </li>");ips.templates.set('core.autocomplete.token'," <li class='cToken' data-value='{{value}}' role='option'> {{{title}}} <span class='cToken_close' data-action='delete'>&times;</span> </li>");ips.templates.set('core.autocomplete.assignmentAddToken'," <a href='#' data-action='addToken'><i class='fa-regular fa-paper-plane'></i> {{text}}</a> ");ips.templates.set('core.autocomplete.assignmentResultItem'," <li class='ipsAutocompleteMenu_item' data-value=\"{{value}}\" role='option'> {{#team}} <div class='ipsPhotoPanel i-align-items_center'> <i class='fa-solid fa-user-group i-font-size_3 i-text-align_center i-color_soft'></i> <div> <div><strong>{{{name}}}</strong></div> <span class='ipsBadge ipsBadge--positive'>{{#lang}}assignment_team{{/lang}}</span> </div> </div> {{/team}} {{^team}} <div class='ipsPhotoPanel'> <span class='ipsUserPhoto ipsUserPhoto--tiny'><img src='{{{photo}}}' alt='' loading='lazy'></span> <div> <strong>{{{name}}}</strong><br> <span class='i-color_soft'>{{{extra}}}</span> </div> </div> {{/team}} </li>");ips.templates.set('core.autocomplete.memberItem'," <li class='ipsAutocompleteMenu_item' data-value=\"{{value}}\" role='option'> <div class='ipsPhotoPanel'> <span class='ipsUserPhoto ipsUserPhoto--tiny'><img src='{{{photo}}}' alt='' loading='lazy'></span> <div> <strong>{{{name}}}</strong><br> <span class='i-color_soft'>{{{extra}}}</span> </div> </div> </li>");ips.templates.set('core.autocomplete.optional'," <a href='#' data-action='showAutocomplete' class='ipsButton i-font-size_-1 ipsButton--inherit'><i class='fa-solid fa-tags'></i><span>{{langString}}...</span></a>");;
;(function($,_,undefined){"use strict";ips.createModule('ips.model',function(){var _models={};var register=function(id,definition){var Base=getBaseModel();$.extend(Base.prototype,definition);var obj=new Base(id);if(_.isFunction(obj.initialize)){obj.initialize.call(obj);}},getBaseModel=function(){var baseModel=function(id){this.modelID=id;};baseModel.method('trigger',function(elem,ev,data){var args=ips.utils.argsToArray(arguments);elem=(!_.isElement(elem))?$(document):$(args.shift());ev=args[0];data=args[1]||{};if(!data.stack){data.stack=[];}
data.stack.push('models.'+this.modelID);elem.trigger(ev,data);});baseModel.method('on',function(elem,ev,delegate,fn){var args=ips.utils.argsToArray(arguments);elem=(!_.isElement(elem)&&elem!=document)?$(document):$(args.shift());ev=args[0];fn=(args.length==3)?args[2]:args[1];delegate=(args.length==3)?args[1]:undefined;if(!_.isFunction(fn)){Debug.warn("Callback function for "+ev+" doesn't exist in "+this.modelID);return;}
fn=_.bind(fn,this);if(delegate){elem.on(ev,delegate,fn);}else{elem.on(ev,fn);}});baseModel.method('getData',function(data,eventData){var self=this;var ajaxObj=ips.getAjax();if(!data.url.startsWith('http')){data.url=ips.getSetting('baseURL')+'index.php?'+data.url;}
if(data.events&&_.isString(data.events)){data.events={loading:data.events+'Loading',done:data.events+'Done',fail:data.events+'Error',always:data.events+'Finished'};}
if(data.namespace&&!data.namespace.startsWith('.')){data.namespace='.'+data.namespace;}
if(data.events.loading){this.trigger(data.events.loading+(data.namespace||''),eventData||{});}
ajaxObj(data.url,{data:data.data||{},dataType:data.dataType||'html',type:data.type||'get'}).done(function(response){if(data.events.done){if(data.dataType=='json'){var doneData=_.extend(eventData||{},response);}else{var doneData=_.extend(eventData||{},{response:response});}
self.trigger(data.events.done+(data.namespace||''),doneData);}}).fail(function(jqXHR){if(data.events.fail){try{if(data.dataType=='json'){var doneData=_.extend(eventData||{},$.parseJSON(jqXHR.responseText));}else{var doneData=_.extend(eventData||{},{response:jqXHR.responseText});}}catch(err){}
self.trigger(data.events.fail+(data.namespace||''),doneData)}}).always(function(){if(data.events.always){self.trigger(data.events.always+(data.namespace||''));}});});return baseModel;};return{register:register};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.loader',function(){var _loadedScripts=[],_loadingScripts=[];const LOADER_STATES={};var init=function(){var scripts=$('script[src][data-ips]');scripts.each(function(){var scriptInfo=ips.utils.url.getURIObject($(this).attr('src'));if(scriptInfo.queryKey.src){var paths=_getPathScripts(scriptInfo.queryKey.src);_.each(paths,function(value){_loadedScripts.push(value);});}else if(scriptInfo.path.indexOf('interface/')!==-1){var interfaces=_getInterfaceScript(scriptInfo.path);if(interfaces){_loadedScripts.push(interfaces);}}else{var other=_getOtherScript(scriptInfo.source);if(other){_loadedScripts.push(other);}}});},_getOtherScript=function(path){path=path.replace(ips.getSetting('baseURL'),'');if(path.startsWith('/')){path=path.substring(1);}
if(path.startsWith('applications/')){path=path.replace(/^applications\//i,'')}
return path;},_getInterfaceScript=function(path){var pieces=_.compact(path.split('/').reverse());var path=[];for(var i=0;i<pieces.length;i++){if(pieces[i]=='interface'){path.push('interface');path.push(pieces[i+1]);break;}
path.push(pieces[i]);}
if(_.indexOf(path,'interface')!==-1){return path.reverse().join('/');}
return false;},_getPathScripts=function(src){return _.compact(src.split(','));},get=function(toLoad){return $.when(_doLoad(_.compact(_.uniq(toLoad))));},_doLoad=function(filePaths){const deferred=$.Deferred();if(!_.isArray(filePaths)){filePaths=[filePaths];}
var done=[];var loading=[];var toLoad=[];for(var i=0;i<filePaths.length;i++){if(_.indexOf(_loadedScripts,filePaths[i])!==-1){done.push(filePaths[i]);continue;}
if(_.indexOf(_loadingScripts,filePaths[i])!==-1){loading.push(filePaths[i]);continue;}
toLoad.push(filePaths[i]);}
if(done.length===filePaths.length){deferred.resolve();return deferred.promise();}
if(loading.length||toLoad.length){$(document).on('scriptLoaded',function(e,files){for(var i=0;i<files.length;i++){if(_.indexOf(filePaths,files[i])===-1){continue;}
done.push(files[i]);}
if(done.length===filePaths.length){setTimeout(function(){deferred.resolve();},100);}});}
if(toLoad.length){var localFiles=[];var remoteFiles=[]
for(var i=0;i<toLoad.length;i++){if(toLoad[i].match(/^(http|\/\/)/i)){remoteFiles.push(toLoad[i]);}else{localFiles.push(toLoad[i]);}}
if(localFiles.length){_insertScript(localFiles);}
if(remoteFiles.length){for(var i=0;i<remoteFiles.length;i++){_insertScript([remoteFiles[i]]);}}}
return deferred.promise();},_insertScript=function(toLoad,cached){for(var i=0;i<toLoad.length;i++){_loadingScripts.push(toLoad[i]);}
Debug.log("Loading: "+toLoad.join(', '));var url='';if(toLoad[0].match(/^(http|\/\/)/i)){url=toLoad[0].match(/^http/)?toLoad[0].replace(/^.+?\/\/(.*)$/,'//$1'):toLoad[0];}else{url=ips.getSetting('jsURL')+'?src='+encodeURIComponent(toLoad.join(','));}
setTimeout(function(){$.ajax({dataType:'script',cache:(_.isUndefined(cached))?true:cached,url:url,data:{antiCache:ips.getSetting('jsAntiCache'),csrfKey:null,}}).fail(function(jqXHR,textStatus,errorThrown){Debug.error("Failed to load: "+toLoad.join(', '));Debug.log(textStatus);}).always(function(){for(var i=0;i<toLoad.length;i++){var index=_.indexOf(_loadingScripts,toLoad[i]);if(index!==-1){_loadingScripts.splice(index,1);}}}).done(function(){for(var i=0;i<toLoad.length;i++){_loadedScripts.push(toLoad[i]);}
$(document).trigger('scriptLoaded',[toLoad]);Debug.log("Loaded: "+toLoad.join(', '));})},500);};return{init:init,get:get,getStatic(paths){if(!Array.isArray(paths)){paths=[paths];}
const uniquePaths=new Set();for(let path of paths){if(path.startsWith('http://')||path.startsWith("https://")){uniquePaths.add(path);}else{path=window.location.protocol+ips.getSetting('baseURL').replace(/\/+$/,'')+"/"+path.replace(/^\/+/,'');uniquePaths.add(path);}}
return Promise.all([...uniquePaths].map(path=>new Promise((resolve,reject)=>{LOADER_STATES[path]=LOADER_STATES[path]||{state:'unloaded',resolvers:new Set(),rejectors:new Set(),err:undefined,}
const{state,resolvers,rejectors,err}=LOADER_STATES[path];if(state==='loaded'){return resolve();}
if(state==='error'){return reject(err);}
resolvers.add(resolve);rejectors.add(reject);if(state==='unloaded'){LOADER_STATES[path].state='loading';const script=document.createElement('script');const url=new URL(path);url.updateSearchParams({param:'antiCache',value:ips.getSetting('jsAntiCache')});script.src=url;script.addEventListener('load',()=>{Debug.log(`Loaded static script ${path}`);LOADER_STATES[path].state='loaded';resolvers.forEach(resolver=>resolver());resolvers.clear();rejectors.clear();},{once:true});script.addEventListener('error',()=>{LOADER_STATES[path].state='error';LOADER_STATES[path].err=new Error(`Failed to load ${path}`);Debug.error(LOADER_STATES[path].err);rejectors.forEach(rejector=>rejector(LOADER_STATES[path].err));rejectors.clear();resolvers.clear();},{once:true});document.body.appendChild(script);}})));}}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.controller',function(){let _controllers={},_autoMixins={},_manualMixins={},_mixins={},_beingLoaded=[],_queue={},_prototypes={},instanceID=1,_controllerCaseMap={'core.front.core.autosizeiframe':'core.front.core.autoSizeIframe'};function register(id,definition){_controllers[id]=definition;_checkQueue(id);}
function isRegistered(id){return _controllers[id]!==undefined;}
function init(){$(document).on('contentChange',function(e,newNode){initializeControllers(newNode);});initializeControllers();}
function mixin(mixinName,controller,auto,mixinFunc){if(_.isFunction(auto)){mixinFunc=auto;auto=false;}
var obj=(auto)?_autoMixins:_manualMixins;if(_.isUndefined(obj[controller])){obj[controller]={};}
obj[controller][mixinName]=mixinFunc;}
function initializeControllers(node){var controllers=_findControllers(node);var needsLoading={};for(var controller in controllers){if(isRegistered(controller)){for(var i=0;i<controllers[controller].length;i++){var elem=controllers[controller][i]['elem'];var mixins=controllers[controller][i]['mixins'];initControllerOnElem(elem,controller,mixins);}}else{needsLoading[controller]=controllers[controller];}}
if(_.size(needsLoading)){_loadControllers(needsLoading)}}
function _checkQueue(id){if(_queue[id]&&_queue[id].length){for(var i=0;i<_queue[id].length;i++){initControllerOnElem(_queue[id][i]['elem'],id,_queue[id][i]['mixins']);}
delete _queue[id];}
if(_.indexOf(_beingLoaded,id)){delete _beingLoaded[_.indexOf(_beingLoaded,id)];}}
function _loadControllers(needsLoading){var filePaths=[];var deferred=$.Deferred();for(var controller in needsLoading){if(_.indexOf(_beingLoaded,controller)!==-1){delete needsLoading[controller];continue;}
_beingLoaded.push(controller);filePaths.push(_buildFilePath(controller));}
if(!_.size(needsLoading)){deferred.resolve();return deferred.promise();}
_.extend(_queue,needsLoading);ips.loader.get(filePaths).then(function(){deferred.resolve();});return deferred.promise();}
function _buildFilePath(controllerName){const bits=controllerName.split('.');if(ips.getSetting('useCompiledFiles')===false){return bits[0]+'/'+bits[1]+'/controllers/'+bits[2]+
'/ips.'+bits[2]+'.'+bits[3]+'.js';}else{try{let url;if(_.indexOf(ips.getSetting('ipsApps'),bits[0])!==-1){url=ips.getSetting('baseURL')+'static/js/'+bits[0]+'/'+bits[1]+'_'+bits[1]+'_'+bits[2]+'.js';}else{url=ipsJsFileMap[bits[0]][bits[1]+'_'+bits[2]];}
if(url.indexOf('?')!=-1){return url+'&v='+ips.getSetting('jsAntiCache');}else{return url+'?v='+ips.getSetting('jsAntiCache');}}catch(err){Debug.log(err);return'';}}}
function _findControllers(node){if(!_.isElement(node)&&!(node instanceof jQuery)){node=document;}
var controllersToLoad={};$(node).find('[data-controller]').addBack().each(function(idx,elem){if(!$(elem).data('_controllers')){$(elem).data('_controllers',[]);}
var controllerString=$(elem).data('controller'),controllerList=$(elem).data('_controllers');if(controllerString){_getControllersAndMixins(controllerString);var controllers=_getControllersAndMixins(controllerString);if(_.size(controllers)){_.each(controllers,function(val,key){if(controllerList.length&&_.indexOf(controllerList,key)!==-1){return;}
if(controllersToLoad[key]){controllersToLoad[key].push({elem:elem,mixins:val});}else{controllersToLoad[key]=[{elem:elem,mixins:val}];}});}}});return controllersToLoad;}
function _getControllersAndMixins(controllerString){var controllers={};var pieces=controllerString.split(',');for(var i=0;i<pieces.length;i++){pieces[i]=pieces[i].trim();if(!_.isUndefined(_controllerCaseMap[pieces[i]])){pieces[i]=_controllerCaseMap[pieces[i]];}
if(pieces[i].indexOf('(')===-1){controllers[pieces[i]]=[];continue;}
var p=pieces[i].match(/([a-zA-Z0-9.]+)\((.+?)\)/i);var mixinPieces=[];_.each(p[2].split(';'),function(val){mixinPieces.push(val.trim());});controllers[p[1]]=mixinPieces;}
return controllers;}
function getInstanceID(){return'ipscontroller'+(++instanceID);}
function cleanContentsOf(elem,destroyWidgets=true){if(destroyWidgets){ips.cleanContentsOf(elem)
return;}
Debug.log('Cleaning controllers from content');$(elem).find('[data-controller]').each(function(){var loopController=$(this);var controllers=loopController.data('_controllerObjs')||[];if(controllers.length){loopController.data('_controllerObjs',[]);for(var i=0;i<controllers.length;i++){controllers[i]._destroy.apply(controllers[i]);delete controllers[i];}}});}
function initControllerOnElem(elem,controllerID,mixins){if(!_controllers[controllerID]){Debug.error("Controller '"+controllerID+"' has not been registered");return;}
if(_.isUndefined($(elem).data('_controllers'))){$(elem).data('_controllers',[]);}
$(elem).data('_controllers').push(controllerID);if(_.isUndefined(_prototypes[controllerID])){_prototypes[controllerID]=getBaseController();$.extend(true,_prototypes[controllerID].prototype,_controllers[controllerID]);}
if(_.isUndefined($(elem).data('_controllerObjs'))){$(elem).data('_controllerObjs',[]);}
var controllers=$(elem).data('_controllerObjs');var obj=new _prototypes[controllerID](elem,controllerID);controllers.push(obj);if(!_.isUndefined(_autoMixins[controllerID])&&_.size(_autoMixins[controllerID])){_.each(_autoMixins[controllerID],function(val,key){_autoMixins[controllerID][key].call(obj);});}
if(mixins.length){for(var i=0;i<mixins.length;i++){if(!_.isUndefined(_manualMixins[controllerID])&&!_.isUndefined(_manualMixins[controllerID][mixins[i]])){_manualMixins[controllerID][mixins[i]].call(obj);}}}
if(_.isFunction(obj.initialize)){try{obj.initialize.call(obj);}catch(e){Debug.error(`Failed to setup the controller '${controllerID}' on an element`);Debug.error(e);$(elem).data('_controllerObj',controllers.filter(inst=>inst!==obj));return;}}
$(elem).removeData('_controller'+controllerID);$(document).trigger('controllerReady',{controllerID:obj.controllerID,controllerType:obj.controllerType,controllerElem:elem});}
function _findSubControllers(controller,node){var results=[];node=(node&&(_.isElement(node)||node.jquery))?node:document;if(controller.indexOf('*')===-1){results=$(node).find('[data-controller*="'+controller+'"]');}else{var pieces=controller.split('.');if(pieces[0]==='*'){pieces.shift();results=$(node).find('[data-controller$="'+pieces.join('.')+'"]');}else if(pieces[pieces.length-1]==='*'){pieces.pop();results=$(node).find('[data-controller^="'+pieces.join('.')+'"]');}}
return results;}
class BaseController{scope;elem;constructor(scope,type){this.controllerType=type;this.controllerID=getInstanceID();this.scope=$(scope);this.elem=this.scope.get(0);this._eventListeners=[];const adviceFuncs={before:function(baseFn,newFn){return function(){newFn.apply(this,arguments);return baseFn.apply(this,arguments);};},after:function(baseFn,newFn){return function(){const toReturn=baseFn.apply(this,arguments);newFn.apply(this,arguments);return toReturn;}},around:function(baseFn,newFn){return function(...args){args.unshift(baseFn.bind(this));return newFn.apply(this,args);}}};for(const[type,generator]of Object.entries(adviceFuncs)){this[type]=(base,fn)=>{if(!(this[base]instanceof Function)){Debug.log("Method '"+base+'" is not present in controller '+this.controllerID);}
this[base]=generator(this[base],fn)}}}
_destroy(){Debug.log('Destroyed instance '+this.controllerID+' of '+this.controllerType);if(this._eventListeners.length){for(var i=0;i<this._eventListeners.length;i++){var data=this._eventListeners[i];if(data['delegate']){data['elem'].off(data['ev'],data['delegate'],data['fn']);}else{data['elem'].off(data['ev'],data['fn']);}}}
if(_.isFunction(this.destroy)){this.destroy.call(this);}
this.scope=null;}
cleanContents(){Debug.log('Cleaning contents of controller');this.scope.find('[data-controller]').each(function(){var loopController=$(this);var controllers=loopController.data('_controllerObjs')||[];if(controllers.length){loopController.data('_controllerObjs',[]);for(var i=0;i<controllers.length;i++){controllers[i]._destroy.apply(controllers[i]);delete controllers[i];}}});ips.ui.destructAllWidgets(this.scope);}
trigger(...args){let elem=(!_.isElement(args[0])&&!args[0].jquery)?this.scope:$(args.shift());let ev=args.shift();let data=args.shift()||{};if(!data.stack){data.stack=[];}
data.stack.push('controllers.'+this.controllerType+'.'+this.controllerID);elem.trigger(ev,data);}
on(elem,ev,delegate,fn){var args=ips.utils.argsToArray(arguments);elem=(!_.isElement(elem)&&elem!=document&&elem!=window)?this.scope:$(args.shift());ev=args[0];fn=(args.length==3)?args[2]:args[1];delegate=(args.length==3)?args[1]:undefined;if(!_.isFunction(fn)){Debug.warn("Callback function for "+ev+" doesn't exist in "+this.controllerType
+" ("+this.controllerID+")");return;}
fn=_.bind(fn,this);if(delegate){elem.on(ev,delegate,fn);this._eventListeners.push({elem:elem,event:ev,delegate:delegate,fn:fn});}else{elem.on(ev,fn);this._eventListeners.push({elem:elem,event:ev,fn:fn});}}
triggerOn(controller,ev,data){const toTrigger=_findSubControllers(controller,this.scope);if(!toTrigger.length){return;}
data=data||{};if(!data.stack){data.stack=[];}
data.stack.push('controllers.'+this.controllerType+'.'+this.controllerID);toTrigger.trigger(ev,data);}}
function getBaseController(){class BaseControllerClone extends BaseController{}
return BaseControllerClone}
return{initControllerOnElem,register,mixin,isRegistered,init,cleanContentsOf};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui',function(){let widgets={},doneInitialInit=false,ziCounter=ips.getSetting('zindex_start')||5000,ziIncrement=ips.getSetting('zindex_inc')||50;const COMPONENT_LAZY_LOAD_SYMBOL=Symbol('i-component-unloaded');const COMPONENT_LAZY_LOAD_ON_EVENT_SYMBOL=Symbol('i-component-load-on-event');const key={BACKSPACE:8,ESCAPE:27,TAB:9,LEFT:37,RIGHT:39,UP:38,DOWN:40,ENTER:13,COMMA:188,SPACE:32};const LOADING_COMPONENTS=new Set();const WEB_COMPONENT_NAMES={};const WEB_COMPONENT_NAMES_REVERSE={};var registerWidget=function(widgetID,handler,acceptedOptions,widgetOptions,fnCallback){if(widgets[widgetID]){Debug.warn("'"+widgetID+"' is already registered as a widget. Skipping...");}
if(typeof handler==='boolean'||isElementConstructor(handler)||Array.isArray(handler)){const name=webComponentName(widgetID);if(widgetID in widgets){Debug.warn(new RangeError(`Cannot define a web component, <${name}/>, from the UI widget system because the widget ID ${widgetID} is already in use.`));}else{widgets[widgetID]=COMPONENT_LAZY_LOAD_SYMBOL;if(isElementConstructor(handler)){if(customElements.get(name)){Debug.warn(new RangeError(`Cannot define the web component <${name}/> because it is already registered.`));return;}
customElements.define(name,handler);widgets[widgetID]=handler;}else if(Array.isArray(handler)){widgets[widgetID]=COMPONENT_LAZY_LOAD_ON_EVENT_SYMBOL;const listener=e=>{if(e.target instanceof HTMLElement&&e.target.tagName?.toLowerCase()===name){handler.forEach(eventType=>document.removeEventListener(eventType,listener,{capture:true}));setTimeout(()=>loadWebComponent(name));}}
handler.forEach(eventType=>document.addEventListener(eventType,listener,{capture:true}));}else if(handler){setTimeout(()=>loadWebComponent(name))}else if(handler===false){document.addEventListener(`ips:loadComponent#${widgetID}`,()=>{if(widgets[widgetID]===COMPONENT_LAZY_LOAD_SYMBOL){setTimeout(()=>loadWebComponent(name));}},{once:true,capture:true});}
customElements.whenDefined(name).then(()=>{widgets[widgetID]=customElements.get(name);document.querySelectorAll(name).forEach(el=>customElements.upgrade(el));Debug.log(`Registered the web component <${name}/>`)});}
return;}
widgetOptions=_.defaults(widgetOptions||{},{'lazyLoad':false,'lazyEvents':'','makejQueryPlugin':true});widgets[widgetID]={handler:handler,callback:fnCallback,acceptedOptions:acceptedOptions||[],widgetOptions:widgetOptions||{}};if(widgetOptions.makejQueryPlugin!==false){buildjQueryPlugin(widgetID,handler,acceptedOptions,widgetOptions,fnCallback);}},getAcceptedOptions=function(widgetID){return widgets[widgetID]['acceptedOptions']||[];},buildjQueryPlugin=function(widgetID,handler,acceptedOptions,widgetOptions){const jQueryKey=widgetOptions.jQueryKey||'ips'+widgetID.charAt(0).toUpperCase()+widgetID.slice(1),dataID='ips'+widgetID;if($.fn[jQueryKey]){Debug.warn("jQuery plugin '"+jQueryKey+"' already exists.");return;}
$.fn[jQueryKey]=function(providedOptions){this.each(function(){let elem=$(this);elem.attr('data-'+dataID,'');for(let[key,value]of Object.entries(providedOptions)){if(acceptedOptions.includes(key)){elem.attr(`data-${dataID}-${key}`,value);}}
if(widgetOptions.lazyLoad===false){_callWidget(widgetID,elem,_getWidgetOptions(widgetID,elem));}});};},_initializeWidgets=function(context){const immediateWidgets=[],lazyWidgets=[],componentWidgets=[];context=context instanceof Element?context:document;_.each(widgets,function(item,key){if(item===COMPONENT_LAZY_LOAD_ON_EVENT_SYMBOL||isElementConstructor(item)){return;}
if(item===COMPONENT_LAZY_LOAD_SYMBOL){componentWidgets.push(key)}else if(_.isUndefined(item.widgetOptions.lazyLoad)||item.widgetOptions.lazyLoad===false){immediateWidgets.push(key);}else{lazyWidgets.push(key);}});_doImmediateWidgets(immediateWidgets,context);if(componentWidgets.length){_doComponentWidgets(componentWidgets,context)}
if(!doneInitialInit&&context===document){_doLazyWidgets(lazyWidgets,context);doneInitialInit=true;}},destructAllWidgets=function(context){const widgetIDs=[...Object.entries(widgets)].filter(([key,widget])=>!(widget===COMPONENT_LAZY_LOAD_SYMBOL||isElementConstructor(widget))).map(([key])=>key);var selector=_.map(widgetIDs,function(item){return"[data-ips"+item+"]";});var foundWidgets=$(context).find(selector.join(','));foundWidgets.each(function(idx,elem){elem=$(elem);for(var i=0;i<widgetIDs.length;i++){if(!_.isUndefined(elem.attr('data-ips'+widgetIDs[i]))){_destructWidget(widgetIDs[i],elem);}}});},_destructWidget=function(widgetID,elem){if(_.isFunction(widgets[widgetID].handler.destruct)){try{widgets[widgetID].handler.destruct.call(widgets[widgetID].handler,elem);}catch(err){Debug.error("Error calling destruct on "+widgetID);Debug.error(err);}}},_doImmediateWidgets=function(widgetsToLoad,context){if(!widgetsToLoad.length){return;}
let selector=widgetsToLoad.map(item=>"[data-ips"+item+"]");const foundWidgets=$(context).find(selector.join(','));for(let elem of foundWidgets){elem=$(elem);for(var i=0;i<widgetsToLoad.length;i++){if(!_.isUndefined(elem.attr('data-ips'+widgetsToLoad[i]))){_callWidget(widgetsToLoad[i],elem,_getWidgetOptions(widgetsToLoad[i],elem));}}}},_doLazyWidgets=function(widgetsToLoad,context){if(!widgetsToLoad.length){return;}
context=context instanceof Element?context:document;for(let i=0;i<widgetsToLoad.length;i++){const widget=widgets[widgetsToLoad[i]];const lazyEvents=widget.widgetOptions.lazyEvents||'click';$(context).on(lazyEvents,"[data-ips"+widgetsToLoad[i]+"]",_.partial(function(widgetKey,e){_callWidget(widgetKey,this,_getWidgetOptions(widgetKey,this),e);},widgetsToLoad[i]));}},_doComponentWidgets=function(widgetsToLoad,context){context=$(context||document).get(0);widgetsToLoad.forEach(widgetID=>{const widget=widgets[widgetID];if(widget!==COMPONENT_LAZY_LOAD_SYMBOL){return;}
try{const name=webComponentName(widgetID);if(context.querySelector(name)){loadWebComponent(name);}}catch(e){}})},_callWidget=function(widgetID,elem,options,e){if(widgets[widgetID].callback instanceof Function){widgets[widgetID].callback.call(widgets[widgetID].handler,elem,options,e);}else if(widgets[widgetID].handler.respond instanceof Function){widgets[widgetID].handler.respond.call(widgets[widgetID].handler,elem,options,e);}else{Debug.error("No callback method specified for "+widgetID);}},_getWidgetOptions=function(widgetID,elem){var options={},optionKeys=widgets[widgetID].acceptedOptions;elem=$(elem);try{if(elem.attr('data-ips'+widgetID+'-options')){var optionsObj=$.parseJSON(elem.attr('data-ips'+widgetID+'-options'));if(_.isObject(optionsObj)){return optionsObj;}}}catch(err){Debug.warn("Invalid options object passed in for a "+widgetID+" widget. Must be valid JSON.");}
if(optionKeys.length){for(var i=0;i<optionKeys.length;i++){var thisOption=elem.attr('data-ips'+widgetID+'-'+optionKeys[i]);if(!_.isUndefined(thisOption)){if(thisOption.match(/^[1-9][0-9]*$/g)){thisOption=parseInt(thisOption,10);}
if(thisOption==='true'){thisOption=true;}else if(thisOption==='false'){thisOption=false;}
if(typeof thisOption==='string'&&thisOption.trim()===''){thisOption=true;}
options[optionKeys[i]]=thisOption;}}}
return options;},zIndex=function(){ziCounter+=ziIncrement;if(document?.body?.style instanceof CSSStyleDeclaration){document.body.style.setProperty('--ips-js-zindex-top',ziCounter.toString());}
return ziCounter.toString();},getModal=function(){return $('<div/>').addClass('ipsModal').hide().appendTo($('body')).identify();},init=function(){$(document).on('contentChange',function(e,newContent){if(newContent instanceof jQuery){newContent.each(function(){if(Debug.isEnabled){Debug.info("contentChange event, reinitializing widgets in "+$(this).identify().attr('id'));}
_initializeWidgets(this);});}else{if(Debug.isEnabled){Debug.info("contentChange event, reinitializing widgets in "+$(newContent).identify().attr('id'));}
_initializeWidgets(newContent);}});_initializeWidgets(document);};if(document?.body?.style instanceof CSSStyleDeclaration){zIndex();}else{window.addEventListener('load',()=>{zIndex();})}
class BaseWidget{static _defaults={};static instances=new WeakMap();constructor(elem,options){this.options=options;this.elem=$(elem);}
_element=undefined;get element(){if(this._element===undefined){this._element=this.elem.get(0);}
return this._element;}
set element(val){Debug.warn(`The field "element" is not settable`);}
destruct(){BaseWidget.instances.delete(this.element);}
reset(){}
on(...args){const cb=args.pop();if(!(cb instanceof Function)){return;}
let base=this.elem;if(typeof args[0]!=='string'){base=$(args.shift());}
base.on(...args,(...ev)=>cb.call(this,...ev))}
static fixOptions(options){return options}
static initializeOnElem(elem,options){elem=elem instanceof Element?elem:$(elem).get(0)
if(!(elem instanceof Element)){return;}
if(!this.getInstance(elem)){options=this.fixOptions({...this._defaults,...options});const instance=new this(elem,options);this.instances.set(elem,instance);}}
static getInstance(elem){elem=elem instanceof Element?elem:$(elem).get(0)
if(elem&&this.instances.has(elem)){return this.instances.get(elem);}
return undefined;}
static buildModuleAndRegisterWidget(name,options=[],widgetOptions=undefined,fnCallback=undefined){if(name){ips.ui.registerWidget(name,ips.ui[name],options,widgetOptions,fnCallback);}
return{respond:(elem,options)=>this.initializeOnElem(elem,options),destruct:(elem)=>this.getInstance(elem)?.destruct(),getObj:elem=>this.getInstance(elem),reset:elem=>this.getInstance(elem)?.reset(),finalClass:this}}}
function isElementConstructor(cls){if(typeof cls!=='function'||!cls.prototype){return false}
return HTMLElement.prototype.isPrototypeOf(cls.prototype);}
async function loadWebComponent(name){if(!LOADING_COMPONENTS.has(name)){const widgetID=webComponentWidgetID(name);LOADING_COMPONENTS.add(name);let urlPath;if(ips.getSetting('useCompiledFiles')===false){urlPath="/applications/core/interface/js/webcomponents.php?component="+widgetID;}else{urlPath='/static/js/global/root_component_'+widgetID+".js";}
const url=window.ips.getSetting('baseURL').replace(/\/+$/,'')+urlPath+(urlPath.includes('?')?'&':'?')+'v='+ips.getSetting('jsAntiCache');const script=document.createElement('script');script.defer=true;script.src=url;script.dataset.ips='';document.body.appendChild(script);}
await customElements.whenDefined(name);LOADING_COMPONENTS.delete(name);}
function registerWebComponent(widgetID,cls){const name=webComponentName(widgetID);if(!isElementConstructor(cls)){throw new TypeError(`Cannot register web component because the provided cls is not a subclass of HTMLElement`);}
if(customElements.get(name)){throw new RangeError(`The web component ${name} is already registered`);}
if(!(widgetID in widgets)){Debug.log(`Registering the web component ${name}, however no widget is currently registered for this component. Registering the widget ${widgetID} now.`);registerWidget(widgetID,cls);}else{customElements.define(name,cls);}}
function webComponentName(widgetID){if(!(widgetID in WEB_COMPONENT_NAMES)){const name='i-'+widgetID.replaceAll(/[A-Z]/g,(match)=>`-${match.toLowerCase()}`).replace(/^-+/,'');try{validateWebComponentName(name);WEB_COMPONENT_NAMES[widgetID]=name;WEB_COMPONENT_NAMES_REVERSE[name]=widgetID;}catch(e){WEB_COMPONENT_NAMES[widgetID]=()=>new RangeError(`The widgetID ${widgetID} converts to a disallowed Web Component name, ${name}`);}}
return WEB_COMPONENT_NAMES[widgetID];}
function webComponentWidgetID(name){if(!(name in WEB_COMPONENT_NAMES_REVERSE)){try{validateWebComponentName(name);const widgetID=name.replace(/^i-/,'').replaceAll(/-([a-z])/g,(match,$1)=>$1.toUpperCase());WEB_COMPONENT_NAMES[widgetID]=name;WEB_COMPONENT_NAMES_REVERSE[name]=widgetID;}catch(e){WEB_COMPONENT_NAMES_REVERSE[name]=()=>new RangeError(`${name} is not a valid web component name`);}}
if(WEB_COMPONENT_NAMES_REVERSE[name]instanceof Function){throw WEB_COMPONENT_NAMES_REVERSE[name]();}
return WEB_COMPONENT_NAMES_REVERSE[name];}
function validateWebComponentName(name){if(typeof name!=='string'||!name.match(/^i-[a-z][a-z-0-9\-]*$/i)){throw new RangeError(`${name} is not a valid web component name`);}}
return{registerWidget,init,zIndex,getModal,getAcceptedOptions,key,destructAllWidgets,BaseWidget,registerWebComponent,loadWebComponent};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.selectTree',function(){var defaults={multiple:false,selected:false,searchable:true,placeholder:ips.getString('select')};var respond=function(elem,options){if(!$(elem).data('_selecttree')){$(elem).data('_selecttree',selectTreeObj($(elem),_.defaults(options,defaults)));}},getObj=function(elem){if($(elem).data('_selecttree')){return $(elem).data('_selecttree');}
return undefined;},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}};function selectTreeObj(elem,options){let results=null,elemID=null,selectedItems=[],name='',autoExpand=false,ro;var init=function(){elemID=elem.identify().attr('id');results=elem.find('.ipsSelectTree_nodes');name=elem.attr('data-name');if($(elem).closest('i-dropdown').length){$(elem).after($(results).get(0));$(results).addClass('ipsSelectTree_nodes--collapsed').removeClass('ipsHide').css({display:""});const inputEl=$(elem).closest('form .ipsForm > .ipsFieldRow').get(0);if(inputEl instanceof HTMLElement&&inputEl.matches(':not([hidden],[hidden] *)')&&![...inputEl.parentElement.querySelectorAll(':scope > .ipsFieldRow')].some(row=>row!==inputEl&&row.querySelector("input:not([hidden], [hidden] *)"))){autoExpand=true;$(results).addClass('ipsSelectTree_nodes--auto-expanded');}}
if(!autoExpand){elem.on('click',_toggleResults);}
results.on('click','[data-action="getChildren"]',_toggleChildren);results.on('click','[data-action="nodeSelect"]',_toggleNodeSelection);elem.on('click','[data-action="nodeLoadMore"] a:not(.ipsButton--disabled)',_nodeLoadMore);results.on('click','[data-action="nodeLoadMore"] a:not(.ipsButton--disabled)',_nodeLoadMore);if($('input[name="'+name+'-zeroVal"]')){$('input[name="'+name+'-zeroVal"]').on('change',_zeroValChange);}
if(options.selected){try{var preSelected=$.parseJSON(options.selected);}catch(err){}
if(preSelected&&_.isObject(preSelected)&&_.size(preSelected)){_buildPreSelected(preSelected);return;}}
elem.find('.ipsSelectTree_value').addClass('ipsSelectTree_placeholder').text((options.placeholder)?options.placeholder:ips.getString('select'));_zeroValChange();if(autoExpand){_showResults();}},destruct=function(){$(document).off('click.'+elemID);},_buildPreSelected=function(preSelected){if(_.size(preSelected)){_.each(preSelected,function(val,key){selectedItems.push(key);if(options.multiple){var id=key;if(val.id){id=val.id;}
_addToken(val.title,id);}else{_setValue(val.title);}
if(results.find('[data-id="'+key+'"]').length){results.find('[data-id="'+key+'"]').addClass('ipsSelectTree_selected');}});_updateSelectedValues();elem.trigger('nodeInitialValues',{selectedItems:selectedItems});}},_zeroValChange=function(e){elem.toggleClass('ipsSelectTree_disabled',$('input[name="'+name+'-zeroVal"]').is(':checked'));if(!$('input[name="'+name+'-zeroVal"]').is(':checked')&&results.is(':visible')){_closeResults();}},_toggleChildren=function(e,ignoreClosed){e.preventDefault();e.stopPropagation();var item=$(e.currentTarget).closest('.ipsSelectTree_item');var listItem=item.closest('li');var id=item.attr('data-id');var url=options.url+'&_nodeSelect=children&_nodeId='+id;if(!item.hasClass('ipsSelectTree_withChildren')){return;}
if(item.hasClass('ipsSelectTree_itemOpen')){if(ignoreClosed!==true){item.removeClass('ipsSelectTree_itemOpen');listItem.find('> [data-role="childWrapper"]').hide();_positionResults();}}else{item.addClass('ipsSelectTree_itemOpen');if(item.attr('data-childrenLoaded')){ips.utils.anim.go('fadeIn fast',listItem.find('> [data-role="childWrapper"]'));_positionResults();}else{listItem.append($('<div/>').attr('data-role','childWrapper').html(ips.templates.render('core.general.loading',{text:ips.getString('loading')})));_positionResults();ips.getAjax()(url).done(function(response){item.attr('data-childrenLoaded',true);listItem.find('[data-role="childWrapper"]').html(response.output);listItem.find('[data-role="childWrapper"] .ipsSelectTree_item').each(function(){if($(this).attr('data-id')&&selectedItems.indexOf($(this).attr('data-id'))!=-1){$(this).addClass('ipsSelectTree_selected');}});_positionResults();});}}},_toggleNodeSelection=function(e){var node=$(e.currentTarget);if(node.hasClass('ipsSelectTree_selected')){_unselectNode(node,e);}else{_selectNode(node,e);}
_updateSelectedValues();},_nodeLoadMore=function(e){e.stopPropagation();var offset=results.find('[data-action="nodeLoadMore"]').attr('data-offset');var url=options.url+'&_nodeSelect=loadMore&_nodeSelectOffset='+offset;results.find('[data-action="nodeLoadMore"] span.ipsLoading').removeClass('ipsHide');results.find('[data-action="nodeLoadMore"] > a.ipsButton').addClass('ipsButton--disabled');ips.getAjax()(url).done(function(response){if(!_.isUndefined(response.globalOutput)){results.find('[data-role="globalNodeList"]').append(response.globalOutput);if(!_.isUndefined(response.clubsOutput)){results.find('[data-role="clubNodeList"]').append(response.clubsOutput);}}
else
{results.find('[data-role="nodeList"]').append(response.output);}
results.find('[data-action="nodeLoadMore"] span.ipsLoading').addClass('ipsHide');if(response.loadMore){results.find('[data-action="nodeLoadMore"]').attr('data-offset',response.loadMore);}
else
{results.find('[data-action="nodeLoadMore"]').addClass('ipsHide');}
results.find('[data-action="nodeLoadMore"] > a.ipsButton').removeClass('ipsButton--disabled');results.find('[data-role="nodeList"]').find('.ipsSelectTree_item').each(function(){if($(this).attr('data-id')&&selectedItems.indexOf($(this).attr('data-id'))!=-1){$(this).addClass('ipsSelectTree_selected');}});_positionResults();});},_selectNode=function(node,e){if(!options.multiple){elem.find('.ipsSelectTree_selected').removeClass('ipsSelectTree_selected');}
node.addClass('ipsSelectTree_selected');var title=node.find('[data-role="nodeTitle"]').text();var id=node.attr('data-id');if(!options.multiple){_setValue(title);}else{_addToken(title,id);}
if(options.multiple){selectedItems.push(node.attr('data-id'));}else{selectedItems=[node.attr('data-id')];}
if(e){_toggleChildren(e,true);}
elem.trigger('nodeItemSelected',{title:title,id:id});if(!options.multiple&&!node.hasClass('ipsSelectTree_withChildren')){setTimeout(function(){_closeResults();},200);}},_unselectNode=function(node,e){node.removeClass('ipsSelectTree_selected');selectedItems=_.without(selectedItems,node.attr('data-id'));elem.trigger('nodeItemUnselected',{title:node.find('[data-role="nodeTitle"]').text(),id:node.attr('data-id')});if(!options.multiple){_setValue();}else{_removeToken(node);}},_addToken=function(title,id){var valueElem=elem.find('.ipsSelectTree_value');var elemHeight=elem.outerHeight();if(!elem.find('[data-role="tokenList"]').length){valueElem.html($('<ul/>').attr('data-role','tokenList'));}
elem.find('[data-role="tokenList"]').append(ips.templates.render('core.selectTree.token',{title:title,id:id}));elem.find('.ipsSelectTree_value').removeClass('ipsSelectTree_placeholder');if(elemHeight!=elem.outerHeight()){_positionResults();}},_removeToken=function(node){var id=node.attr('data-id');var tokenList=elem.find('[data-role="tokenList"]');var elemHeight=elem.outerHeight();var token=tokenList.find('[data-nodeId="'+id+'"]').closest('li').remove();if(!tokenList.find('[data-nodeId]').length){tokenList.remove();_setValue();}
if(elemHeight!=elem.outerHeight()){_positionResults();}},_updateSelectedValues=function(){elem.find('[data-role="nodeValue"]').val(_.uniq(selectedItems).join(','));elem.trigger('nodeSelectedChanged',{selectedItems:selectedItems});},_setValue=function(value){if(value){elem.find('.ipsSelectTree_value').text(value).removeClass('ipsSelectTree_placeholder');}else{elem.find('.ipsSelectTree_value').text((options.placeholder)?options.placeholder:ips.getString('select')).addClass('ipsSelectTree_placeholder');}},_toggleResults=function(e){if(!$(results).get(0).classList.contains('ipsSelectTree_nodes--collapsed')&&results.is(':visible')){_maybeHideResults(e);}else{_showResults(e);}},_maybeHideResults=function(e){var rawResults=results.get(0);if((!$.contains(rawResults,e.target)&&rawResults!=e.target)){_closeResults();}},_closeResults=function(){if($(elem).closest('i-dropdown').length){$(results).addClass('ipsSelectTree_nodes--collapsed');}else{ips.utils.anim.go('fadeOut fast',results);}
$(document).off('click.'+elemID);elem.removeClass('ipsSelectTree_active');elem.trigger('nodeSelectionClosed');},_showResults=function(){if(!autoExpand){$(document).on('click.'+elemID,_closeResultsOnBlur);}
if($(elem).closest('i-dropdown').length){$(results).removeClass("ipsSelectTree_nodes--collapsed");}else{_positionResults();results.show();}
elem.addClass('ipsSelectTree_active');if(elem.find('[data-role="nodeSearch"]')){elem.find('[data-role="nodeSearch"]').focus();}},_positionResults=function(){if($(elem).closest('i-dropdown').length){return;}
var above=false;var elemTop=elem.offset().top;var elemHeight=elem.height();if((elemTop+elemHeight+results.height())>$(window).height()){above=true;var scrollParent=_getScrollParent();var scrollParentTop=$(scrollParent).offset().top;Debug.log("elemTop: "+elemTop);Debug.log("elemTop - resultsHeight: "+(elemTop-results.height()));Debug.log("scrollParentTop: "+scrollParentTop);if((elemTop-results.height())<scrollParentTop){above=false;}}
var positionInfo={trigger:elem,target:results,targetContainer:elem,above:above};var resultsPosition=ips.utils.position.positionElem(positionInfo);results.css({top:resultsPosition.top+'px',zIndex:ips.ui.zIndex()});if(resultsPosition.location.vertical=='top'){results.removeClass('ipsSelectTree_bottom').addClass('ipsSelectTree_top');elem.removeClass('ipsSelectTree_bottom').addClass('ipsSelectTree_top');}else{results.removeClass('ipsSelectTree_top').addClass('ipsSelectTree_bottom');elem.removeClass('ipsSelectTree_top').addClass('ipsSelectTree_bottom');}},_closeResultsOnBlur=function(e){if(!_clickIsInElem(e.target)){_closeResults();}},_clickIsInElem=function(target){var rawElem=elem.get(0);var rawResults=results.get(0);if(target==rawElem||target==rawResults||$.contains(rawResults,target)||$.contains(rawElem,target)){return true;}
return false;},_getScrollParent=function(includeHidden){var element=elem.get(0);var style=getComputedStyle(element);var excludeStaticParent=style.position==="absolute";var overflowRegex=/(auto|scroll|hidden)/;if(style.position==="fixed"){return document.body;}
for(var parent=element;(parent=parent.parentElement);){style=getComputedStyle(parent);if(excludeStaticParent&&style.position==="static"){continue;}
if(overflowRegex.test(style.overflow+style.overflowY+style.overflowX)){return parent;}}
return document.body;}
init();return{destruct};}
ips.ui.registerWidget('selectTree',ips.ui.selectTree,['placeholder','multiple','selected','url','searchable']);return{respond:respond,destruct:destruct};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.stack',function(){var defaults={sortable:true,itemTemplate:'core.forms.stack'};var respond=function(elem,options){if(!$(elem).data('_stack')){$(elem).data('_stack',stackObj(elem,_.defaults(options,defaults)));}};ips.ui.registerWidget('stack',ips.ui.stack,['sortable','maxItems','itemTemplate']);return{respond:respond};});var stackObj=function(elem,options){var stack=null;var currentIndex=0;var init=function(){if(!elem.attr('data-initiated')){stack=elem.find('[data-role="stack"]');currentIndex=_getItemCount();if(options.maxItems&&currentIndex>=options.maxItems){elem.find('[data-action="stackAdd"]').hide();}
elem.on('click','[data-action="stackAdd"]',_addItem);elem.on('click','[data-action="stackDelete"]',_deleteItem);elem.on('keydown','[data-role="stackItem"] input[type="text"]',_keyDown);if(options.sortable){ips.loader.get(['core/interface/jquery/jquery-ui.js']).then(function(){stack.sortable({handle:'[data-action="stackDrag"]'});});}
elem.attr('data-initiated','true');$(elem).trigger('stackInitialized',{count:_getItemCount()});}},_keyDown=function(e){if(e.keyCode==ips.ui.key.ENTER){e.preventDefault();_addItem(null,$(e.currentTarget).closest('[data-role="stackItem"]'));}},_addItem=function(e,after){if(e){e.preventDefault();}
if(options.maxItems&&_getItemCount()>=options.maxItems){return;}
currentIndex++;var field=stack.find('[data-ipsStack-wrapper]').first().html().replace(/(name=['"][a-zA-Z0-9\-_]+?)\[([^\]]+?)?\]/g,'$1['+currentIndex+']').replace(/data-ipsFormData=['"](.+?)['"]/ig,'').replace(/id=['"](.+?)['"]/g,'id="$1_'+currentIndex+'"').replace(/data-toggles=['"](.+?)['"]/g,function(match,p1){var pieces=p1.split(',');var newPieces=[];_.each(pieces,function(val){if(val.match(/_[0-9]+$/g)){newPieces.push(val+'_'+currentIndex);}else{newPieces.push(val);}});return'data-toggles="'+newPieces.join(',')+'"';});field=field.replace(/\<input(.+?)value=['"](.*?)['"](.*?)\>/g,'<input$1value=""$3>');if(stack.find('select').length){field=field.replace(/\<option(.+?)selected(?:=['"]selected["'])?(.*?)\>/g,'<option$1$2>');}
var html=ips.templates.render(options.itemTemplate,{field:field});if(after){after.after(html).next('[data-role="stackItem"]').find('input,textarea').focus();}else{stack.append(html).find('[data-role="stackItem"] input,[data-role="stackItem"] textarea').last().focus();}
if(options.maxItems&&_getItemCount()>=options.maxItems){elem.find('[data-action="stackAdd"]').hide();}
$(document).trigger('contentChange',[elem]);$(elem).trigger('stackRowAdded',{count:_getItemCount()});},_deleteItem=function(e){e.preventDefault();var row=$(e.currentTarget).closest('[data-role="stackItem"]');if(_getItemCount()===1){row.find('input,textarea').val('');row.find("option:selected").removeAttr("selected");return;}
ips.utils.anim.go('fadeOutDown',row).done(function(){row.hide();setTimeout(function(){row.remove();if(options.maxItems&&_getItemCount()<options.maxItems){elem.find('[data-action="stackAdd"]').show();}},100);});},_getItemCount=function(){return stack.find('[data-role="stackItem"]').length;};init();};}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.sideMenu',function(){var defaults={type:'radio',responsive:true,group:false};var respond=function(elem,options){if(!$(elem).data('_sidemenu')){$(elem).data('_sidemenu',sideMenuObj(elem,_.defaults(options,defaults)));}};ips.ui.registerWidget('sideMenu',ips.ui.sideMenu,['responsive','type','group']);var sideMenuObj=function(elem,options){var init=function(){if(options.responsive&&ips.utils.responsive.enabled()){$(elem).on('click','[data-action="openSideMenu"]',_toggleSideMenu);}
$(elem).on('click','.ipsSideMenu_item',_clickEvent);$(elem).on('selectItem.sideMenu',_selectItem);},_clickEvent=function(e){_doSelectItem($(e.currentTarget),e);_toggleSideMenu();},_selectItem=function(e,data){_doSelectItem(elem.find('[data-ipsMenuValue="'+data.value+'"]'),e);},_doSelectItem=function(item,e){if((_.isUndefined(item.attr('data-ipsMenuValue'))&&!item.find('input[type="radio"], input[type="checkbox"]').length)||!item.length){return;}
if(e){e.preventDefault();}
if(item.hasClass('ipsSideMenu_itemDisabled')){return;}
var workingItems;if(!options.group){workingItems=$(elem).find('.ipsSideMenu_item');}else{workingItems=item.closest('.ipsSideMenu__list').find('.ipsSideMenu_item');}
if(options.type==='check'){item=$(item).get(0);item.classList[item.classList.contains('ipsSideMenu_itemActive')?'remove':'add']('ipsSideMenu_itemActive');item.querySelectorAll('input[type="radio"], input[type="checkbox"]').forEach(input=>{input.checked=!input.checked;input.dispatchEvent(new CustomEvent('change',{bubbles:true}));});}else{const items=[...workingItems]
items.forEach(item=>{item.classList.remove('ipsSideMenu_itemActive')
item.querySelectorAll('input[type="radio"], input[type="checkbox"]').forEach(input=>{if(input.checked){input.checked=false;input.dispatchEvent(new CustomEvent('change',{bubbles:true}))}});});item=$(item).get(0);item.classList.add('ipsSideMenu_itemActive')
item.querySelectorAll('input[type="radio"], input[type="checkbox"]').forEach(input=>{if(!input.checked){input.checked=true;input.dispatchEvent(new CustomEvent("change",{bubbles:true}));}});}
var selectedItems=[];workingItems.filter('.ipsSideMenu_itemActive').each(function(){selectedItems.push($(this).attr('data-ipsMenuValue'));});$(elem).trigger('itemClicked.sideMenu',{id:$(elem).identify().attr('id'),menuElem:$(elem),selectedElem:$(item),selectedItemID:$(item).attr('data-ipsMenuValue'),selectedItems:selectedItems});},_toggleSideMenu=function(e){if(e){e.preventDefault();}
$(elem).toggleClass('ipsSideMenu_open');$(elem).find('.ipsSideMenu__view').each(function(){this.scrollIntoView({behavior:"smooth"})});};init();return{};};return{respond};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.wizard',function(){var respond=function(elem,options,e){elem.on('click','[data-action="wizardLink"]',_.bind(refresh,e,elem));elem.on('submit','form',_.bind(refresh,e,elem));};var refresh=function(elem,e){var target=$(e.currentTarget);_showLoading(elem);if(target.is('form')){if(target.attr('data-bypassAjax')){return true;}
e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();var data=target.serialize()+'&_wizardHeight='+elem.find('[data-role="loading"]').outerHeight();if(e.originalEvent&&e.originalEvent.submitter&&e.originalEvent.submitter.name&&e.originalEvent.submitter.value){data+='&'+e.originalEvent.submitter.name+'='+e.originalEvent.submitter.value;}
ips.getAjax()(target.attr('action'),{data:data,type:'post'}).done(function(response){_insertHtml(response,elem);}).fail(function(response,textStatus,errorThrown){target.attr('data-bypassAjax',true);target.submit();})}else{e.preventDefault();ips.getAjax()(target.attr('href')).done(function(response){_insertHtml(response,elem);});}},_insertHtml=function(response,elem){if(_.isObject(response)&&response.redirect){window.location=response.redirect;return;}
var responseDiv=$('<div>'+response+'</div>');var responseWizard=responseDiv.find('[data-ipsWizard]').html();if(!responseWizard){responseWizard=response;}
responseDiv.find("link","script").appendTo('head');ips.controller.cleanContentsOf(elem);elem.html(responseWizard);$(document).trigger('contentChange',[elem]);elem.trigger('wizardStepChanged');},_showLoading=function(elem){var loading=elem.find('[data-role="loading"]');var formContainer=elem.find('[data-role="wizardContent"]');if(!formContainer.is(':visible')){return;}
if(!loading.length){loading=$('<div/>').attr('data-role','loading').addClass('ipsLoading').hide();elem.append(loading);}
var dims={width:formContainer.outerWidth(),height:formContainer.outerHeight()};loading.css({width:dims.width+'px',height:dims.height+'px'}).show();formContainer.hide().after(loading.show());},_hideLoading=function(){var loading=elem.find('[data-role="loading"]');var formContainer=elem.find('[data-role="registerForm"]');loading.remove();formContainer.show();};ips.ui.registerWidget('wizard',ips.ui.wizard);return{respond:respond};});}(jQuery,_));;
;(function($,_){["card","dropdown","pwaInstall","pushNotificationsPrompt","themeEditor","latex","latexNodeview"].forEach(component=>{ips.createModule(`ips.ui.${component}`,function(){ips.ui.registerWidget(component,false);return{};});});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.validation',function(){var defaults={live:true,submit:true,characterLimit:3,displayAs:'list'};var respond=function(elem,options,e){if(!$(elem).data('_validation')){$(elem).data('_validation',validateObj(elem,_.defaults(options,defaults)));}};var validateObj=function(elem,options){var init=function(){if(options.live){$(elem).on('keyup blur','input:not( [type="button"] ):not( [type="checkbox"] ):not( [type="hidden"] )'+
':not( [type="radio"] ):not( [data-validate-bypass] ), textarea:not( [data-validate-bypass] )',_textEvent);$(elem).on('change','select',_selectEvent);}
if(options.submit){$(elem).closest('form').on('submit',_submitEvent);}},_submitEvent=function(e){var errors=0;var elements=$(elem).find('input:not( [type="submit"] ):not( [type="checkbox"] )'+
':not( [type="radio"] ):not( [type="hidden"] ), select, textarea');elements.each(function(){if(!_validate($(this))){errors++;}});if(errors>0){e.preventDefault();$(e.currentTarget).trigger('error.validation',{count:errors});}else{$(e.currentTarget).trigger('success.validation');}},_selectEvent=function(e){},_textEvent=function(e){var field=$(e.currentTarget);if(e.type=='blur'||e.type=='focusout'){if(field.val().length>=options.characterLimit||field.is('[type="number"], [type="range"]')){_validate(field);}}else{if(field.attr('data-hasErrors')){_validate(field);}}},_validate=function(target){var result=ips.utils.validate.validate(target);if(result!==true&&!result.result){_displayErrors(target,result);}else{_clearErrors(target);}
return result.result;},_displayErrors=function(target,results){var id=target.identify().attr('id');var errorList=$('#'+id+'_errors');if(!errorList.length){var wrapper=ips.templates.render('core.forms.validationWrapper',{id:id+'_errors'});target.after(wrapper);errorList=$('#'+id+'_errors');}
errorList.html('');for(var i=0;i<results.messages.length;i++){errorList.append(ips.templates.render('core.forms.validationItem',{message:results.messages[i].message}));}
target.addClass('ipsField_error').attr('data-hasErrors',true);},_clearErrors=function(target){var id=target.identify().attr('id');if($('#'+id+'_errors').length){$('#'+id+'_errors').remove();}
target.removeClass('ipsField_error').removeAttr('data-hasErrors');}
init();return{};};ips.ui.registerWidget('validation',ips.ui.validation);return{respond:respond};});}(jQuery,_));;
;((($,_)=>{"use strict";const accordionMap=new Map();const defaults={defaultopen:'open'}
ips.createModule('ips.ui.accordion',function(){ips.ui.registerWidget('accordion',ips.ui.accordion,['defaultopen','alwaysopen'])
return{respond(elem,options){if($(elem).get(0).closest('.ipsEditor__tiptap-wrap')){return;}
if(!accordionMap.has($(elem).get(0))){accordionMap.set($(elem).get(0),new Accordion($(elem).get(0),options))}},getInstance(elem){if(accordionMap.has($(elem).get(0))){return accordionMap.get($(elem).get(0))}
return null},destroy(elem){if(this.getInstance(elem)){accordionMap.delete($(elem).get(0))}}}})
class Accordion{constructor(elem,options={}){this.options={...defaults,...options}
this.elem=elem
if(this.options.alwaysopen){this.elem.open=true;}
this.elem.addEventListener('toggle',()=>{if(this.elem.open&&!this.options.alwaysopen){this.accordionSiblings.forEach(sibling=>{sibling.open=false})}})
this.summary?.addEventListener('click',e=>{e.preventDefault()
this.open=!this.open})
this.summary?.addEventListener('keyup',e=>{if(['enter','space','return',' '].includes(e.key.toLowerCase())){e.preventDefault()
this.open=!this.open}})}
get summary(){return this.elem.querySelector(':scope > summary')}
get open(){return this.elem.open}
set open(open){open=!!open
if(this.options.alwaysopen){return}
if(open===this.open)return
const content=this.elem.querySelector(':scope > :not(summary)')
if(!content)return;this.elem.open=true;content.animate([{minHeight:'revert',maxHeight:'revert',height:`${open ? 0 : content.getBoundingClientRect().height}px`},{minHeight:'revert',maxHeight:'revert',height:`${!open ? 0 : content.getBoundingClientRect().height}px`},{minHeight:'revert',maxHeight:'revert',height:`${!open ? 0 : content.getBoundingClientRect().height}px`}],{duration:225})
setTimeout(()=>this.elem.open=open,150)}
get accordionSiblings(){let element=this.elem.previousElementSibling
let siblings=[];while(element?.dataset?.ipsaccordion!==undefined){if(ips.ui.accordion.getInstance(element)){siblings.push(ips.ui.accordion.getInstance(element))}
element=element.previousElementSibling}
siblings=siblings.reverse();element=this.elem.nextElementSibling
while(element?.dataset?.ipsaccordion!==undefined){if(ips.ui.accordion.getInstance(element)){siblings.push(ips.ui.accordion.getInstance(element))}
element=element.nextElementSibling}
return siblings}}})(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.addressForm',function(){const defaults={minimize:false,country:"",requireFullAddress:true};function respond(elem,options,e){if(!_.isUndefined(elem.data('initialized'))){return;}
options=_.defaults(options,defaults);if(options.minimize){minimizeAddress(elem,options);}else{init(elem,options,e);}
elem.data('initialized',true);}
function init(elem,options,e){elem.on('change','[data-role="countrySelect"]',_.bind(countryChange,e,elem,options));$(elem).find('[data-role="countrySelect"]').change();recalculateAddAddressLineButton(elem);}
function minimizeAddress(elem,options){const tempInput=$('<input/>').attr('type','text').attr('data-role','minimizedVersion').addClass('ipsInput').attr('placeholder',ips.getString('specifyLocation')).on('focus',function(e){$(this).hide();if(options.country){$(elem).find('[data-role="countrySelect"]').val(options.country);}
init(elem,options,e);elem.show().find('input').first().focus();});const value=[];elem.find('input, select').each(function(){if($(this).val()){if($(this).is('select')){value.push($(this).find('option[value="'+$(this).val()+'"]').text().trim());}else{value.push($(this).val().trim());}}});if(value.length){tempInput.val(value.join(', '));}
elem.hide().after(tempInput);}
function countryChange(elem,options,e){ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=ajax&do=states&country='+$(e.target).val()).done(function(response){let regionSelect;let regionText;if(response.length){if(!$(elem).find('[data-role="regionSelect"]').length){regionText=$(elem).find('[data-role="regionText"]');}
else
{regionText=$(elem).find('[data-role="regionSelect"]');}
regionSelect=$('<select class="ipsInput" data-role="regionSelect" />');regionSelect.attr('name',regionText.attr('name'));if(!options.requireFullAddress){regionSelect.append($('<option />').attr('value','').html($(elem).find('[data-role="regionText"]').attr('placeholder')));}
response.forEach?.(region=>{regionSelect.append($('<option />').attr('value',region).html(region));if(region.toLowerCase()===regionText.val().toLowerCase()){regionSelect.val(region);}})
regionText.replaceWith(regionSelect);}else{if(!$(elem).find('[data-role="regionText"]').length){regionSelect=$(elem).find('[data-role="regionSelect"]');regionText=$('<input type="text" data-role="regionText" placeholder="'+ips.getString('address_region')+'" />');regionText.attr('name',regionSelect.attr('name')).val("");regionSelect.replaceWith(regionText);}}});if(typeof elem.attr('data-ipsAddressForm-googlePlaces')==='string'){ips.ui.map.afterGoogleMapsLoaded(()=>googlePlacesInit(elem))}}
function addAddressLine(elem,value){const lastLine=elem.find('[data-role="addressLine"]').closest('li').last();const newLine=lastLine.clone();if(value){newLine.find('input').focus().val(value);}
lastLine.after(newLine);}
function recalculateAddAddressLineButton(elem){elem.find('[data-role="addAddressLine"]').remove();const button=$('<i class="fa fa-plus" style="cursor:pointer; margin-left: 4px" data-role="addAddressLine">');button.click(function(){addAddressLine(elem,'');recalculateAddAddressLineButton(elem);});elem.find('[data-role="addressLine"]').last().after(button);}
function googlePlacesInit(elem){const googlePlacesInput=$(elem).find('[data-role="addressLine"]').first();const options={types:['geocode'],componentRestrictions:{country:$(elem).find('[data-role="countrySelect"]').val()}};if(!options.componentRestrictions.country){delete options.componentRestrictions}
const autocomplete=new google.maps.places.Autocomplete(googlePlacesInput.get(0),options);googlePlacesInput.on('focus',function(){if(navigator.geolocation){navigator.geolocation.getCurrentPosition(function(position){const geolocation=new google.maps.LatLng(position.coords.latitude,position.coords.longitude);autocomplete.setBounds(new google.maps.LatLngBounds(geolocation,geolocation));});}});googlePlacesInput.on('keypress',function(e){if((e.which&&e.which==13)||(e.keyCode&&e.keyCode==13)){return false;}});google.maps.event.addListener(autocomplete,'place_changed',function(){const place=autocomplete.getPlace();for(let i=0;i<$(elem).find('[data-role="addressLine"]').length;i++){$(elem).find('[data-role="addressLine"]').val('');}
const parsedAddress=$('<div>'+place.adr_address+'</div>');const addressLines=[];let existingAddressLines=$(elem).find('[data-role="addressLine"]').length;if(parsedAddress.find('.post-office-box').length){addressLines.push(parsedAddress.find('.post-office-box').text());}
if(parsedAddress.find('.street-address').length){addressLines.push(parsedAddress.find('.street-address').text());}
if(parsedAddress.find('.extended-address').length){addressLines.push(parsedAddress.find('.extended-address').text());}
for(let i=0;i<addressLines.length;i++){if(existingAddressLines){$(elem).find('[data-role="addressLine"]').slice(i,1).focus().val(addressLines[i]);existingAddressLines--;}else{addAddressLine(elem,addressLines[i]);}}
if(parsedAddress.find('.locality')){elem.find('[data-role="city"]').focus().val(parsedAddress.find('.locality').text());}
if(parsedAddress.find('.region')){elem.find('[data-role="regionText"]').focus().val(parsedAddress.find('.region').text());if(elem.find('[data-role="regionSelect"] option[value="'+parsedAddress.find('.region').text()+'"]').length){elem.find('[data-role="regionSelect"]').val(parsedAddress.find('.region').text());}else{for(let i in place.address_components){if(place.address_components[i].types[0]==='administrative_area_level_1'||place.address_components[i].types[0]==='administrative_area_level_2'){if(elem.find('[data-role="regionSelect"] option[value="'+place.address_components[i].long_name+'"]').length){elem.find('[data-role="regionSelect"]').val(place.address_components[i].long_name);break;}else if(elem.find('[data-role="regionSelect"] option[value="'+place.address_components[i].short_name+'"]').length){elem.find('[data-role="regionSelect"]').val(place.address_components[i].short_name);break;}}}}}
if(parsedAddress.find('.postal-code')){elem.find('[data-role="postalCode"]').focus().val(parsedAddress.find('.postal-code').text());}});}
ips.ui.registerWidget('addressForm',ips.ui.addressForm,['minimize','country','requireFullAddress']);return{respond};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.alert',function(){var respond=function(elem,options){alertObj(options,elem);},show=function(options){alertObj(options);};ips.ui.registerWidget('alert',ips.ui.alert,['message','type','icon','focus']);return{respond:respond,show:show};});var alertObj=function(options){var alert=null,modal=null;var _defaults={type:'alert',message:ips.getString('generic_confirm'),buttons:{ok:ips.getString('ok'),cancel:ips.getString('cancel'),yes:ips.getString('yes'),no:ips.getString('no')},icon:'info',showIcon:true,callbacks:{}};var _icons={warn:'fa-solid fa-triangle-exclamation',success:'fa-solid fa-check-circle',info:'fa-solid fa-circle-info',ok:'fa-solid fa-check-circle',question:'fa-solid fa-circle-question'};options=_.defaults(options||{},_defaults);var init=function(){_buildAlert();_setUpEvents();},_setUpEvents=function(){alert.on('click','[data-action]',_clickButton);$(document).on('keydown',_keyPress);},_keyPress=function(e){if(!alert.get(0)||!document.documentElement.contains(alert.get(0))){$(document).off('click',_keyPress);}
let toClick;switch(e.key){case'Escape':toClick=alert.find(options.type==='alert'?'[data-action="ok"]':'[data-action="cancel"], [data-action="no"]').get(0);break;case'Enter':toClick=alert.find('[data-action="ok"], [data-action="yes"]').get(0);break;}
if(toClick){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation?.();toClick.click();}},_clickButton=function(e){var button=$(e.currentTarget);var action=button.attr('data-action');var value=null;if(options.type=='prompt'){value=alert.find('[data-role="promptValue"]').val();}
if(_.isFunction(options.callbacks[action])){options.callbacks[action](value);}
_remove();},_remove=function(){$(document).off('keydown',_keyPress);modal.remove();ips.utils.anim.go('fadeOutDown fast',alert).done(function(){alert.remove();});},_buildAlert=function(){var parts={},buttons=[];if(options.showIcon){parts.icon=ips.templates.render('core.alert.icon',{icon:_icons[options.icon]||options.icon});}
parts.id='alert_'+(Math.round(Math.random()*10000000));parts.text=options.message;if(options.subText){parts.subtext=ips.templates.render('core.alert.subText',{text:options.subText});}
if(options.subTextHtml){parts.subtext=ips.templates.render('core.alert.subTextHtml',{text:options.subTextHtml});}
switch(options.type){case'alert':buttons.push(ips.templates.render('core.alert.button',{action:'ok',title:options.buttons.ok,extra:'ipsButton--primary'}));break;case'confirm':case'prompt':buttons.push(ips.templates.render('core.alert.button',{action:'ok',title:options.buttons.ok,extra:'ipsButton--primary'}));buttons.push(ips.templates.render('core.alert.button',{action:'cancel',title:options.buttons.cancel,extra:'ipsButton--inherit'}));break;case'verify':buttons.push(ips.templates.render('core.alert.button',{action:'yes',title:options.buttons.yes,extra:'ipsButton--primary'}));if(options.buttons.no){buttons.push(ips.templates.render('core.alert.button',{action:'no',title:options.buttons.no,extra:'ipsButton--inherit'}));}
if(options.buttons.cancel){buttons.push(ips.templates.render('core.alert.button',{action:'cancel',title:options.buttons.cancel,extra:'ipsButton--inherit'}));}
break;}
parts.buttons=buttons.join('');if(options.type=='prompt'){parts.text+=ips.templates.render('core.alert.prompt');}
var tmpAlert=$.parseHTML(ips.templates.render('core.alert.box',parts).trim());alert=$(tmpAlert[0]);$('body').append(alert);modal=ips.ui.getModal();modal.css({zIndex:ips.ui.zIndex()}).show();alert.css({zIndex:ips.ui.zIndex()});ips.utils.anim.go('zoomIn fast',alert);if(options.focus){alert.find('[data-action="'+options.focus+'"]').focus();}else{if(options.type=='prompt'){alert.find('[data-role="promptValue"]').val(options.value||'').focus();}else{alert.find('[data-action="ok"], [data-action="yes"]').focus();}}};init();};}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.ui.alertMessage',()=>{class AlertMessage extends ips.ui.BaseWidget{constructor(...args){super(...args);this.form?.addEventListener('submit',this.remoteSubmit.bind(this),{capture:true});this.element.addEventListener('click',this.remoteSubmit.bind(this),{capture:true});this.element.addEventListener('ips:editorUpdated',()=>{this.element.querySelector('[data-role="reply"]').removeAttribute('disabled')},{once:true})}
get form(){return this.element?.querySelector('form')||(this.element instanceof HTMLFormElement?this.element:undefined);}
get url(){return this.element?.querySelector('[data-role="reply"]')?.getAttribute('href')||this.form?.getAttribute('action');}
async remoteSubmit(e){if(e.type==='submit'||e.target.closest('input[type="submit"],form button:not([type="button"]), a:is([data-role="dismiss"], [data-role="reply"])')){e.preventDefault();if(e.target.closest('[disabled]')){return;}
if(e.type==='submit'||e.target.closest('[data-role="reply"]')){const url=this.url;const form=this.form;if(url&&form){const data=Object.fromEntries((new FormData(form)).entries());try{const response=await ips.fetch(url,{method:form.method||'post',data,bypassRedirect:true,});if(typeof response?.redirect==='string'){setTimeout(()=>{ips.ui.alert.show({message:ips.getString('moderator_alert_reply_ready'),type:'confirm',buttons:{ok:ips.getString('moderator_alert_reply_view'),cancel:ips.getString('ok')},callbacks:{ok(){window.location=response.redirect;}}});});}}catch(e){Debug.warn(e);}}}else{const url=e.target.closest('a[data-role="dismiss"]')?.getAttribute('href');try{if(url){await ips.fetch(url,{method:'get',bypassRedirect:true,});}else{throw new Error(`Failed to get the dismiss ajax url of a notification`);}}catch(e){e.message=`Failed to set the status as dismissed.\n${e.message}`;Debug.warn(e)}}
this.destruct();this.element.remove();}}}
return AlertMessage.buildModuleAndRegisterWidget('alertMessage');})}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.autoCheck',function(){var defaults={};var respond=function(elem,options){if(!$(elem).data('_autoCheck')){$(elem).data('_autoCheck',autoCheckObj(elem,_.defaults(options,defaults)));}},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}},getObj=function(elem){if($(elem).data('_autoCheck')){return $(elem).data('_autoCheck');}
return undefined;};ips.ui.registerWidget('autoCheck',ips.ui.autoCheck,['context']);return{respond:respond,getObj:getObj,destruct:destruct};});var autoCheckObj=function(elem,options){var initialCount=0;var init=function(){if(options.context&&$(options.context).length){elem.on('menuItemSelected',clickedMenu);$(options.context).on('change','input[type="checkbox"][data-state]',_updateCount);}
elem.on('refresh.autoCheck',refresh);elem.on('setInitialCount.autoCheck',setInitialCount);elem.find('[data-role="autoCheckCount"]').hide();},destruct=function(){if(options.context){$(options.context).off('change','input[type="checkbox"][data-state]',_updateCount);}},refresh=function(){_updateCount();},setInitialCount=function(e,data){initialCount=data.count;_updateCount();},clickedMenu=function(e,data=e.detail){if(!_.isUndefined(data.originalEvent)){data.originalEvent.preventDefault();}
if(!data.selectedItemID){return;}
var checkboxes=$(options.context).find(':checkbox[data-state]');if(data.selectedItemID=='all'){checkboxes.prop('checked',true);}else if(data.selectedItemID=='none'){checkboxes.prop('checked',false);}else{checkboxes.prop('checked',false).filter('[data-state~="'+data.selectedItemID+'"]').prop('checked',true);}
checkboxes.trigger('change');var count=_updateCount();elem.trigger('autoChecked',{menu:elem,currentFilter:data.selectedItemID,count:count});},_updateCount=function(){var checkboxes=$(options.context).find(':checkbox[data-state]');var count=$(options.context).find(':checkbox[data-state]:checked');if(count.length==checkboxes.length&&checkboxes.length!==0){elem.find('.cAutoCheckIcon').html('<i class="fa-solid fa-check-square"></i>');}else if(count.length===0){elem.find('.cAutoCheckIcon').html('<i class="fa-regular fa-square"></i>');}else{elem.find('.cAutoCheckIcon').html('<i class="fa-solid fa-minus-square"></i>');}
var countToDisplay=count.length+initialCount;if(countToDisplay){elem.find('[data-role="autoCheckCount"]').text(countToDisplay).show();}else if(elem.find('[data-role="autoCheckCount"]').is(':visible')){setTimeout(function(){if(!initialCount){ips.utils.anim.go('fadeOut',elem.find('[data-role="autoCheckCount"]'));}},300);}
return count.length;};init();return{destruct:destruct,refresh:refresh};};}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.autocomplete',function(){const defaults={multiValues:true,freeChoice:true,itemSep:{chr:',',keycode:188,charcode:44},disallowedCharacters:JSON.stringify(["<",">","'","\""]),unique:false,customValues:true,fieldTemplate:'core.autocomplete.field',resultsTemplate:'core.autocomplete.resultWrapper',resultItemTemplate:'core.autocomplete.resultItem',tokenTemplate:'core.autocomplete.token',addTokenTemplate:'core.autocomplete.addToken',addTokenText:ips.getString('add_tag'),queryParam:'q',forceLower:false,minLength:1,minAjaxLength:1,commaTrigger:true,searchFieldThreshold:10,suggestionsOnly:false};function respond(elem,options){if(!$(elem).data('_autocomplete')){$(elem).data('_autocomplete',autocompleteObj(elem,_.defaults(options,defaults)));}}
function destruct(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}}
function getObj(elem){elem=$(elem);if(elem.data('_autocomplete')){return elem.data('_autocomplete');}else if($('[name="'+elem.attr('name')+'_original'+'"]').length&&$('[name="'+elem.attr('name')+'_original'+'"]').data('_autocomplete')){return $('[name="'+elem.attr('name')+'_original'+'"]').data('_autocomplete');}
return undefined;}
ips.ui.registerWidget('autocomplete',ips.ui.autocomplete,['multiValues','freeChoice','dataSource','maxItems','itemSep','resultsElem','unique','commaTrigger','fieldTemplate','resultsTemplate','resultItemTemplate','tokenTemplate','addTokenTemplate','addTokenText','queryParam','minLength','maxLength','forceLower','disallowedCharacters','minAjaxLength','suggestionsOnly']);return{respond:respond,destruct:destruct,getObj:getObj};});function autocompleteObj(elem,options,e){let timer,blurTimer,lastValue='',originalTextField,valueField,textField,dataSource,elemID=$(elem).identify().attr('id'),wrapper,inputItem,resultsElem,selectedToken,disabled=false,required=false,tooltip=null,tooltipTimer=null,mouseOverResults=false,hasError=false;let _visible=false;let cleanupQueue=[];const _resizeObserver=new ResizeObserver(entries=>{for(const entry of[...entries].reverse()){if(entry.target instanceof HTMLElement&&resultsElem&&resultsElem.get(0)===entry.target){_visible=!!(entry.borderBoxSize?.[0]?.blockSize&&entry.borderBoxSize?.[0]?.inlineSize);break;}}});cleanupQueue.push(()=>_resizeObserver.disconnect());function init(){if($(elem).is('textarea, input[type="text"], input[type="search"]')){originalTextField=$(elem);}else{originalTextField=$(elem).find('textarea, input[type="text"], input[type="search"]').first();}
try{options.disallowedCharacters=$.parseJSON(options.disallowedCharacters);}catch(err){Debug.error("Couldn't parse disallowed characters option");}
_buildWrapper();_getDataSource();originalTextField.removeAttr('list');if(dataSource.type!='none'){_buildResultsList();if(dataSource.type=='local'){_initAutocomplete();}
$([...resultsElem.find('input[type="search"]'),...textField]).each(function(){this.addEventListener('input',_keyupAutocomplete);cleanupQueue.push(()=>this.removeEventListener('input',_keyupAutocomplete));});}
if(originalTextField.is('[required]')){required=true;originalTextField.removeProp('required').removeAttr('aria-required');}
textField.prop('autocomplete','off').prop('spellcheck',false).prop('disabled',disabled).attr('aria-autocomplete','list').attr('aria-haspopup','true').attr('tabindex',originalTextField.attr('tabindex')||'');if(options.maxLength){textField.attr('maxlength',options.maxLength+1);}
wrapper.click(function(e){e.stopPropagation();return false;});textField.on('focus',_focusField).on('blur',_blurField).on('keydown',_keydownField).on('keyup',_keyupField).on('keypress',_keypressField);wrapper.on('click','[data-action="addToken"]',_clickAddToken).on('keydown',_keydownWrapper).on('propChanged',_propChanged).toggleClass('ipsField_autocompleteDisabled',disabled);cleanupQueue.push(()=>{textField.off('focus',_focusField).off('blur',_blurField).off('keydown',_keydownField).off('keyup',_keyupField).off('keypress',_keypressField);wrapper.off('click','[data-action="addToken"]',_clickAddToken).off('keydown',_keydownWrapper).off('propChanged',_propChanged)})
_buildInitialTokens();const onBlur=()=>{if(textField!==elem){textField.trigger('blur');}}
elem.on('blur',onBlur).trigger('autoCompleteReady',{elemID:elemID,elem:elem,currentValues:tokens.getValues()});elem.on('reissueReady',function(){elem.trigger('autoCompleteReady',{elemID:elemID,elem:elem,currentValues:tokens.getValues()});});cleanupQueue.push(()=>{elem.off('blur',onBlur);elem.off('reissueReady');});}
function destruct(){cleanupQueue.forEach(cb=>cb());cleanupQueue=[];$(document).off('click',_documentClick);}
function hasErrors(){return hasError;}
function _propChanged(e){disabled=originalTextField.is(':disabled');wrapper.toggleClass('ipsField_autocompleteDisabled',disabled);}
function _buildInitialTokens(){var value=_getOriginalValue();if(!value){return;}
var splitValues=_.without(value.split("\n"),'');var itemCount=0;itemCount=splitValues.length;originalTextField.val('');if(splitValues.length){for(var i=0;i<itemCount;i++){_addToken(splitValues[i]);}}}
function _getOriginalValue(){return originalTextField.val();}
function _buildResultsList(){if(options.resultsElem&&$(options.resultsElem).length){resultsElem=$(options.resultsElem);_resizeObserver.observe(resultsElem.get(0),{box:'border-box'});return;}
var resultsList=ips.templates.render(options.resultsTemplate,{id:elemID});wrapper.append(resultsList);resultsElem=$('#'+elemID+'_results');resultsElem.on('mouseover','[data-value]',function(e){results.select($(e.currentTarget));}).on('mouseenter',function(){mouseOverResults=true;}).on('mouseleave',function(){mouseOverResults=false;}).on('click','[data-value]',function(e){_addToken($(e.currentTarget).attr('data-value'));textField.focus();}).attr('aria-busy','false');_resizeObserver.observe(resultsElem.get(0),{box:"border-box"});}
function _initAutocomplete(){if(dataSource.totalItems()>options.searchFieldThreshold&&!options.freeChoice){var searchField=ips.templates.render('core.autocomplete.searchTypeAhead',{});$(resultsElem).prepend(searchField);}}
const _keyupAutocomplete=_.throttle(function(e){_loadResults(e.target.value);return true;},200);function _buildWrapper(){var existingClasses=elem[0].className;$(elem).after(ips.templates.render(options.fieldTemplate,{id:elemID})).removeClass(existingClasses);wrapper=$(elem).parent().find('#'+elemID+'_wrapper');inputItem=$(wrapper).find('#'+elemID+'_inputItem');if(!options.freeChoice){var insertElem=ips.templates.render(options.addTokenTemplate,{text:options.addTokenText});textField=elem;}else{var insertElem=$('<input/>').attr({type:'text',id:elemID+'_dummyInput'}).prop('autocomplete','off');textField=insertElem;}
if(options.suggestionsOnly){const form=$(elem).closest('form').get(0)
if(form){const onSubmit=e=>{if(_getCurrentValue()&&!($(elem).get(0).closest('.ipsFieldRow[hidden]'))){e.preventDefault()
e.stopPropagation()
const warning=$(elem).get(0).closest('.ipsFieldRow__content')?.querySelector(".ipsFieldRow__warning")
if(warning){warning.innerHTML=ips.getString('form_autocomplete_bad')}}};form.addEventListener('submit',onSubmit);cleanupQueue.push(()=>form.removeEventListener("submit",onSubmit));}}
var name=originalTextField.attr('name');originalTextField.attr('name',originalTextField.attr('name')+'_original');valueField=$('<textarea/>').attr('name',name).hide();originalTextField.hide();wrapper.addClass(existingClasses).append(elem).append(valueField);inputItem.append(insertElem);wrapper.on('click',handleWrapperClick);cleanupQueue.push(()=>wrapper.off('click',handleWrapperClick));}
function handleWrapperClick(e){if(e.target instanceof HTMLElement&&e.target.dataset.action==='delete'){_deleteToken($(e.target.closest(`[data-value]`)));}else if(e.target instanceof HTMLElement&&e.target.dataset.value!==undefined&&!disabled){tokens.select($(e.target));}}
function _getDataSource(){if((options.dataSource&&options.dataSource.indexOf('#')===0&&$(options.dataSource).length)||originalTextField.is('[list]')){dataSource=localData(originalTextField.is('[list]')?$('#'+originalTextField.attr('list')):options.dataSource,options);}else if(ips.utils.validate.isUrl(options.dataSource)){dataSource=remoteData(options.dataSource,options);}else{dataSource=noData();}}
function _clickWrapper(e){if($(e.target).is('[data-token]')||$(e.target).parents('li[data-token]').length){var token=($(e.target));}else{if(!$(e.target).is(textField)&&(!resultsElem||!$.contains(resultsElem.get(0),e.target))){textField.focus();}}}
function _clickAddToken(e){e.preventDefault();if(_visible){_closeResults();}else{_loadResults('');}}
function focus(e){textField.focus();}
function _focusField(e){if(dataSource.type==='none'||_visible){return;}
_timerFocusField();}
function _blurField(e){if(mouseOverResults){return;}
clearInterval(timer);_.delay(_timerBlurField,300);}
function _timerBlurField(){if(textField.val()){_addTokenFromCurrentInput();}
_closeResults();}
function _timerFocusField(){if(dataSource.type=='none'){return;}
var currentValue=_getCurrentValue();if(currentValue==lastValue){return;}
lastValue=currentValue;_loadResults(currentValue);}
function _show(cb){if(!_visible){_visible=true;resultsElem?.show();return cb?.();}}
function _hide(cb){if(_visible){_visible=false;resultsElem?.hide();return cb?.();}}
async function _loadResults(value){if(dataSource.type==='remote'&&typeof options.minAjaxLength==="number"&&value.length<options.minAjaxLength){_hide(()=>{resultsElem.attr('aria-busy','false');_toggleLoading('hide');});return;}
_show(()=>{_toggleLoading('show');resultsElem.attr('aria-busy','true');});try{let results=(await dataSource.getResults(value));if(dataSource.type==='local'){results=results?.slice(0,100);}
_showResults(_processResults(results,value));}catch(e){Debug.warn(e)}
resultsElem.attr('aria-busy','false');_toggleLoading('hide');}
function _toggleLoading(doWhat){if(doWhat=='show'){wrapper.addClass('ipsField_loading');}else{wrapper.removeClass('ipsField_loading');}}
function _closeResults(e){e?.preventDefault();if(resultsElem&&resultsElem.length){_hide(()=>{resultsElem.attr('aria-expanded','false');});if(resultsElem.find('input[type="search"]').length){resultsElem.find('input[type="search"]').val('');}}
dataSource.stop();$(document).off('click',_documentClick)}
function _documentClick({originalEvent:e}){if(!resultsElem&&!textField){return;}
if(!_visible){return;}
let target=e.target;const _resultElem=resultsElem?$(resultsElem).get(0):undefined;const _textField=textField?$(textField).get(0):undefined;while(target instanceof HTMLElement){if(target===_resultElem||target===_textField){return;}
target=target.parentElement;}
_closeResults();}
function _processResults(results,text){const existingTokens=tokens.getValues(),newResults={};if(options.unique){$.each(results,function(key,data){let processedValue=_.escape(data.value).trim();if(options.forceLower){processedValue=processedValue.toLowerCase();}
if(!data.value||(_.indexOf(existingTokens,data.value)===-1&&_.indexOf(existingTokens,processedValue)===-1)){newResults[key]=data;}});return newResults;}
return results;}
function _showResults(results){var output='';$.each(results,function(idx,value){output+=ips.templates.render(options.resultItemTemplate,value);});if(resultsElem.attr('id')==(elemID+'_results')){_positionResults();}
resultsElem.show().attr('aria-expanded','true').find('[data-role="items"]').html(output);resultsElem.find('[data-role="noresults"]').prop('hidden',Boolean(Object.keys(results).length));if(resultsElem.find('input[type="search"]').length){resultsElem.find('input[type="search"]').focus();}
$(document).off('click',_documentClick)
let timeout=setTimeout(()=>$(document).on('click',_documentClick));cleanupQueue.push(()=>clearTimeout(timeout));}
function _positionResults(){ips.ui.zIndex();}
function _getCurrentValue(){var value=textField.val();if(options.multiValues){if(value.indexOf(options.itemSep.chr)===-1||!options.commaTrigger){return value.trim();}else{var pieces=value.split(options.itemSep.chr);return pieces[pieces.length-1].trim();}}else{return value;}}
function _keydownWrapper(e){if(e.which==ips.ui.key.ESCAPE){keyEvents.escape(e);}}
function _keydownField(e){var ignoreKey=false;if(!_([ips.ui.key.UP,ips.ui.key.DOWN,ips.ui.key.LEFT,ips.ui.key.RIGHT,ips.ui.key.ENTER,ips.ui.key.TAB,ips.ui.key.BACKSPACE,ips.ui.key.ESCAPE]).contains(e.which)){ignoreKey=true;}
var value=textField.val().trim();if(!value.length){hasError=false;}
if(options.maxLength&&value.length==options.maxLength&&ignoreKey){e.preventDefault();return;}
if(_([ips.ui.key.ENTER,ips.ui.key.TAB]).contains(e.which)&&options.unique&&_duplicateValue(value)){e.preventDefault();_showTooltip(ips.getString('ac_dupes'));return;}
if(ignoreKey){return;}
switch(e.which){case ips.ui.key.BACKSPACE:keyEvents.backspace(e);break;case ips.ui.key.TAB:case ips.ui.key.ENTER:keyEvents.enter(e);break;case ips.ui.key.UP:keyEvents.up(e);break;case ips.ui.key.DOWN:keyEvents.down(e);break;case ips.ui.key.ESCAPE:keyEvents.escape(e);break;}}
function _keyupField(e){var i;for(i in options.disallowedCharacters){if(textField.val().indexOf(options.disallowedCharacters[i])!==-1){textField.val(textField.val().replace(options.disallowedCharacters[i],''));_showTooltip(ips.getString('ac_prohibit_special',{chars:options.disallowedCharacters.join(' ')}));e.preventDefault();return;}}
var lastCharIsComma=(textField.val().substr(textField.val().length-1)===',');if(e.which===229&&lastCharIsComma){_addTokenFromCurrentInput();e.preventDefault();}}
function _keypressField(e){if(!options.commaTrigger){return;}
textField.val(textField.val().replace(',',''));if(e.charCode==options.itemSep.charcode&&options.unique&&_duplicateValue(textField.val())){e.preventDefault();_showTooltip(ips.getString('ac_dupes'));return;}
if(e.charCode==options.itemSep.charcode){_addTokenFromCurrentInput();e.preventDefault();}}
function _addToken(value){tokens.add(value);textField.val('');lastValue='';if(options.maxItems&&tokens.total()>=options.maxItems){inputItem.hide();}
if(options.unique&&options.freeChoice==false&&dataSource.totalItems()!==-1&&dataSource.totalItems()<=tokens.total()){wrapper.find('[data-action="addToken"]').hide();}
hasError=false;}
function _deleteToken(token){if(disabled){return;}
tokens.remove(token);}
const keyEvents={backspace(e){if(!textField.val()){if(tokens.selected){tokens.remove(tokens.selected);}else{if(inputItem.prev().length){tokens.select(inputItem.prev());}}}},enter(e){if(e.which==ips.ui.key.TAB&&textField.val()==''){return false;}
e.preventDefault();const currentResult=results.getCurrent();let value='';if(currentResult){value=currentResult.attr('data-value');}else{if(options.commaTrigger){value=_stripHTML(textField.val().replace(options.itemSep.chr,''));}else{value=_stripHTML(textField.val());}}
if(!value){return false;}
_addToken(value);},up(e){if(!resultsElem||!_visible){return;}
e.preventDefault();const selected=results.getCurrent();if(!selected){results.selectLast();}else{const prev=results.getPrevious(selected);if(prev){results.select(prev);}else{results.selectLast();}}},down(e){if(!_visible){return;}
e.preventDefault();const selected=results.getCurrent();if(!selected){results.selectFirst();}else{const next=results.getNext(selected);if(next){results.select(next);}else{results.selectFirst();}}},escape(e){if(_visible){e.stopPropagation?.();_closeResults();}}}
const results={deselectAll(){resultsElem.find('[data-selected]').removeAttr('data-selected');},getCurrent(){if(dataSource.type==='none'){return;}
const cur=resultsElem.find('[data-selected]');if(cur.length&&_visible){return cur;}
return false;},getPrevious(result){const prev=$(result).prev('[data-value]');if(prev.length){return prev;}
return false;},getNext(result){const next=$(result).next('[data-value]');if(next.length){return next;}
return false;},selectFirst(){results.select(resultsElem.find('[data-value]').first());},selectLast(){results.select(resultsElem.find('[data-value]').last());},select(result){results.deselectAll();result.attr('data-selected',true);}}
const tokens={selected:null,add(value){let html='';value=_.escape(value).trim();if(options.minLength&&value.length<options.minLength){return false;}
if(options.maxLength&&value.length>options.maxLength){return false;}
if(options.forceLower){value=value.toLowerCase();}
tokens.deselectAll();inputItem.before(ips.templates.render(options.tokenTemplate,{id:elemID,value:value,title:value}));if(resultsElem){_closeResults();}
valueField.val(tokens.getValues().join("\n"));if(dataSource.type!=='none'){html=resultsElem.find('[data-value="'+value.replace("\\","\\\\")+'"]').html();}else{html=value;}
$(elem).trigger('tokenAdded',{token:value,html:html,tokenList:tokens.getValues(),totalTokens:tokens.total()});return true;},remove(token){if(tokens.selected===token){tokens.selected=null;}
const value=$(token).attr('data-value');$(token).remove();if(options.maxItems&&tokens.total()<options.maxItems){inputItem.show();}
if(options.unique&&!options.freeChoice&&(dataSource.totalItems()===-1||dataSource.totalItems()>tokens.total())){wrapper.find('[data-action="addToken"]').show();}
valueField.val(tokens.getValues().join("\n"));$(elem).trigger('tokenDeleted',{token:value,tokenList:tokens.getValues(),totalTokens:tokens.total()});},removeAll(){const allTokens=inputItem.siblings().filter('[data-value]');allTokens.each(function(){tokens.remove($(this));});},select(token){tokens.deselectAll();tokens.selected=$(token).addClass('cToken_selected');},total(){return inputItem.siblings().filter('[data-value]').length;},getValues(){let values=[];const allTokens=inputItem.siblings().filter('[data-value]');if(allTokens.length){values=_.map(allTokens,function(item){return $(item).attr('data-value');});}
return values;},getSelected(){return tokens.selected.attr('data-value');},deselectAll(){wrapper.find('[data-value]').removeClass('cToken_selected');tokens.selected=null;}}
function _addTokenFromCurrentInput(){let value='';if(options.commaTrigger){value=_stripHTML(textField.val().replace(options.itemSep.chr,''));}else{value=_stripHTML(textField.val());}
if(options.minLength&&value.length<options.minLength||options.maxLength&&value.length>options.maxLength){if(options.commaTrigger){textField.val(textField.val().replace(options.itemSep.chr,''));}
return;}
if(options.suggestionsOnly){if(!resultsElem){return}
const results=[...resultsElem.find('[data-value]')]
let valueInResults=false;for(const result of results){if(result.dataset.value?.toLowerCase().trim()===value.toLowerCase().trim()){valueInResults=true;value=result.dataset.value
break;}}
if(!valueInResults){for(const result of results){if(!options.unique||!_duplicateValue(result.dataset.value)){value=result.dataset.value
valueInResults=true;break;}}}
if(!valueInResults){return}}
if(options.unique&&_duplicateValue(value)){_showTooltip(ips.getString('ac_dupes'));return;}
_addToken(value);}
function _duplicateValue(value){return tokens.getValues().indexOf(value)!==-1;}
function _stripHTML(text){return text.replace(/<|>|"|'/g,'');}
function _showTooltip(msg){if(!tooltip){_buildTooltip();}
hasError=true;if(tooltipTimer){clearTimeout(tooltipTimer);}
tooltip[0].hidePopover();tooltip.text(msg);_positionTooltip();tooltipTimer=setTimeout(function(){_hideTooltip();},2500);}
function _hideTooltip(){if(tooltip&&tooltip.is(':visible')){tooltip[0].hidePopover();}}
function _positionTooltip(){const positionInfo={trigger:wrapper,target:tooltip,center:true,above:true};const tooltipPosition=ips.utils.position.positionElem(positionInfo);$(tooltip).css({left:tooltipPosition.left+'px',top:tooltipPosition.top+'px'});if(tooltipPosition.location.vertical==='top'){tooltip.addClass('ipsTooltip_top');}else{tooltip.addClass('ipsTooltip_bottom');}
tooltip[0].showPopover();}
function _buildTooltip(){const tooltipHTML=ips.templates.render('core.tooltip',{id:'elAutoCompleteTooltip'});ips.getContainer().append(tooltipHTML);tooltip=$('#elAutoCompleteTooltip');}
init();return{init:init,destruct:destruct,hasErrors:hasErrors,addToken:tokens.add,getTokens:tokens.getValues,removeToken:tokens.remove,removeAll:tokens.removeAll,focus:focus};}
function localData(source){const valueOrderMap=new Map();const searchInterface={type:'local',_items:$(source).get(0).querySelectorAll('option'),async getResults(text){return[...ips.utils.search.search(this,text)].sort((val1,val2)=>valueOrderMap.get(val1)-valueOrderMap.get(val2))},totalItems(){return ips.utils.search.getSize(this);},stop:$.noop,};const secondaryTerms=[]
let i=0;for(const item of $(source).get(0).querySelectorAll('option')){const value={id:item.value,value:item.value,html:item.innerHTML}
const searchTerms=item.innerText.trim().replaceAll(/(\p{L}|\p{N})((?:\p{Upper}|_|-)[\p{Lower}\p{N}])/ug,"$1 $2").replaceAll(/(\P{N})(\p{N}{3,})/ug,"$1 $2").trim().toLowerCase().split(/\s+/).map(term=>ips.utils.search.fixTerm(term)).filter(term=>!!term);ips.utils.search.addTerm(searchInterface,searchTerms.join(''),[value])
valueOrderMap.set(value,i++);searchTerms.shift();while(searchTerms.length){secondaryTerms.push([searchTerms.join(''),value])
searchTerms.shift()}}
for(const[searchTerm,item]of secondaryTerms){ips.utils.search.addTerm(searchInterface,searchTerm,[item])}
return searchInterface;}
function remoteData(source,options){const results=new Map();const responseItemCache=new Map();return{type:'remote',async getResults(text){if(!responseItemCache.has(text)){const data={dataType:'json',data:{}}
if(options.freeChoice){if(options.minAjaxLength>text.length){throw new RangeError(`Expected the text to be less than ${options.minAjaxLength} characters, got a string containing ${text.length} characters`);}
data.data[options.queryParam]=text}
const response=await ips.fetch(source,data)
if(!Array.isArray(response)||response.some(item=>!(typeof item==='object'&&'value'in item))){throw new TypeError(`Could not get autocomplete results from response.`);}
response.forEach(item=>{results.set(item.value,item);})
responseItemCache.set(text,response.map(item=>item.value));}
return responseItemCache.get(text).map(value=>results.get(value));},totalItems(){if(!options.freeChoice){return results.size;}
return-1;},stop:$.noop};}
function noData(){return{type:'none',getResults:$.noop,totalItems:-1,stop:$.noop};}}(jQuery,_));;
function recaptcha2Callback(){jQuery(window).trigger('recaptcha2Loaded');};window.turnstileCallback=function(){console.log('CF callback triggered');jQuery(window).trigger('turnstileLoaded');};;(function($,_,undefined){"use strict";ips.createModule('ips.ui.captcha',function(){var defaults={lang:'en-US',theme:'white'};var recaptchaLoaded=false;var turnstileLoaded=false;var respond=function(elem,options){options=_.defaults(options,defaults);if(options.service=='recaptcha'){_recaptcha(elem,options);}else if(options.service=='recaptcha2'){_recaptcha2(elem,options);}else if(options.service=='keycaptcha'){_keycaptcha(elem);}else if(options.service=='recaptcha_invisible'){_recaptcha_invisible(elem);}else if(options.service=='turnstile'){_turnstile(elem);}},_recaptcha=function(elem,options){ips.loader.get([document.location.protocol+'//www.google.com/recaptcha/api/js/recaptcha_ajax.js']).done(function(){var container=$('<div/>');var id=container.identify().attr('id');elem.append(container);Recaptcha.create(options.key,id,{theme:options.theme,lang:options.lang,callback:function(){Debug.log('done')}});});},_recaptcha2=function(elem,options){ips.loader.get(['https://www.google.com/recaptcha/api.js?hl='+$(elem).attr('data-ipsCaptcha-lang')+'&onload=recaptcha2Callback&render=explicit']);var initRecaptcha2=function(){elem.children('[data-captchaContainer]').remove();var container=$('<div data-captchaContainer/>');var id=container.identify().attr('id');elem.append(container);grecaptcha.render(id,{sitekey:$(elem).attr('data-ipsCaptcha-key'),theme:$(elem).attr('data-ipsCaptcha-theme')});};if(recaptchaLoaded){initRecaptcha2();}else{$(window).on('recaptcha2Loaded',function(){recaptchaLoaded=true;initRecaptcha2();});}},_recaptcha_invisible=function(elem,options){ips.loader.get(['https://www.google.com/recaptcha/api.js?hl='+$(elem).attr('data-ipsCaptcha-lang')+'&onload=recaptcha2Callback&render=explicit']);var initRecaptchaInvisible=function(){elem.children('[data-captchaContainer]').remove();var container=$('<div data-captchaContainer/>');var id=container.identify().attr('id');elem.append(container);var form=elem.closest('form');var recaptchaId=grecaptcha.render(id,{sitekey:$(elem).attr('data-ipsCaptcha-key'),size:'invisible',callback:function(){form.attr('data-recaptcha-done','true');form.submit();}});form.on('submit',function(e){if(!form.attr('data-recaptcha-done')){e.stopPropagation();e.preventDefault();grecaptcha.execute(recaptchaId);}});};if(recaptchaLoaded){initRecaptchaInvisible();}else{$(window).on('recaptcha2Loaded',function(){recaptchaLoaded=true;initRecaptchaInvisible();});}},_keycaptcha=function(elem){ips.loader.get([document.location.protocol+'//backs.keycaptcha.com/swfs/cap.js']);},_turnstile=function(elem,options){ips.loader.get(['https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileCallback'])
const initTurnstile=function(){elem.children('[data-captchaContainer]').remove();var container=$('<div data-captchaContainer/>');var id=container.identify().attr('id');elem.append(container);turnstile.render('#'+id,{sitekey:$(elem).attr('data-ipsCaptcha-key'),language:$(elem).attr('data-ipsCaptcha-lang'),theme:$(elem).attr('data-ipsCaptcha-theme')});};if(turnstileLoaded){initTurnstile();}else{$(window).on('turnstileLoaded',function(){turnstileLoaded=true;initTurnstile();});}};ips.ui.registerWidget('captcha',ips.ui.captcha,['service','key','lang','theme']);return{respond:respond};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.ui.carousel',function(){const buttonHandlerMap=new WeakMap();const cleanupCallbacks=new WeakMap();const visibleCarousels=new WeakSet();const visibleCarouselObserver=new IntersectionObserver(entries=>{entries.forEach(entry=>{if(entry.isIntersecting){visibleCarousels.add(entry.target);}else{visibleCarousels.delete(entry.target);}});},{threshold:0});ips.ui.registerWidget('carousel',ips.ui.carousel);return{destruct(elem){$(elem).each(function(){if(cleanupCallbacks.has(this)){try{cleanupCallbacks.get(this)();}catch(e){Debug.error(e);}
cleanupCallbacks.delete(this);}});},respond(elem){let controls=elem[0],scroller=document.getElementById(controls.dataset.ipscarousel);if(!scroller){Debug.warn({warning:`Carousel nav was not setup because its scroller (#${controls.dataset.ipscarousel}) cannot be identified`,controls});return;}
let buttons=controls.querySelectorAll('[data-carousel-arrow]'),interval=controls.dataset.ipscarouselInterval,int,scrollerWidth,scrollerScrollWidth,scrollerGap=0,itemWidths=new WeakMap(),visibleElements=new WeakSet();const callbacks=[];cleanupCallbacks.set(controls,()=>callbacks.forEach(cb=>cb()));if(interval===undefined&&controls.closest('.cWidgetContainer--isWidget[data-widget-interval]:not([data-ipscarousel] *)')){interval=parseInt(controls.closest('.cWidgetContainer--isWidget[data-widget-interval]:not([data-ipscarousel] *)').dataset.widgetInterval)
interval=Number.isNaN(interval)||!Number.isInteger(interval)||!interval?undefined:interval*1000;}
const _ro=new ResizeObserver(entries=>{for(const entry of entries){if(entry.target===scroller){scrollerWidth=entry.borderBoxSize[0]?.inlineSize||scrollerWidth;scrollerScrollWidth=scroller.scrollWidth;const gap=getComputedStyle(scroller).columnGap?.trim?.().match(/^(\d+|\d+\.\d*|\.\d+)px$/)?.[1];if(gap){scrollerGap=parseFloat(gap);}}else if(entry.target?.parentElement===scroller){if(entry.borderBoxSize.length){itemWidths.set(entry.target,entry.borderBoxSize[0].inlineSize);}}else{_ro.unobserve(entry.target);}}});_ro.observe(scroller);callbacks.push(()=>_ro.disconnect());buttons.forEach(carouselButton=>{if(buttonHandlerMap.has(carouselButton)){carouselButton.removeEventListener('click',buttonHandlerMap.get(carouselButton))}
buttonHandlerMap.set(carouselButton,()=>{if(int){clearInterval(int)}
scrollPanels(carouselButton.dataset.carouselArrow);});const cb=buttonHandlerMap.get(carouselButton);carouselButton.addEventListener('click',cb);callbacks.push(()=>carouselButton.removeEventListener('click',cb));});visibleCarouselObserver.observe(scroller);callbacks.push(()=>visibleCarouselObserver.unobserve(scroller));let firstVisible,lastVisible;const scrollerObserver=new IntersectionObserver((entries)=>{entries.forEach((entry)=>{if(entry.isIntersecting){visibleElements.add(entry.target);}else{visibleElements.delete(entry.target);}
if(entry.target===scroller.firstElementChild){firstVisible=entry.isIntersecting;}
if(entry.target===scroller.lastElementChild){lastVisible=entry.isIntersecting;}});requestAnimationFrame(()=>{controls.hidden=firstVisible&&lastVisible;});},{root:scroller,threshold:0.99});const mutationObserver=new MutationObserver(_.throttle(()=>{scrollerObserver.disconnect();[...scroller.children].forEach(child=>{scrollerObserver.observe(child);_ro.observe(child,{box:"border-box"});});},10,{leading:true}));[...scroller.children].forEach(child=>{scrollerObserver.observe(child);_ro.observe(child,{box:'border-box'});});mutationObserver.observe(scroller,{childList:true});callbacks.push(()=>{mutationObserver.disconnect();scrollerObserver.disconnect();});const scrollListener=(e,direction,loop=true)=>{loop='loop'in e.detail||{}?e.detail.loop:loop;direction=e.detail?.direction||direction;scrollPanels(direction,loop)};$(scroller).on('scrollPanels',scrollListener)
callbacks.push(()=>$(scroller).off('scrollPanels',scrollListener));let removeCB;const scrollEnd=()=>{scroller.classList.remove('ipsScrolling');};const scrollStart=()=>{scroller.classList.add('ipsScrolling');clearTimeout(removeCB);removeCB=setTimeout(()=>scrollEnd(),300);};scroller.addEventListener('scroll',scrollStart);callbacks.push(()=>{scroller.removeEventListener('scroll',scrollStart);clearTimeout(removeCB)});if(scroller.onscrollend instanceof Function){scroller.addEventListener('scrollend',scrollEnd);callbacks.push(()=>scroller.removeEventListener('scrollend',scrollEnd));}
if(interval&&!Number.isNaN(parseInt(interval))){int=setInterval(()=>{if(scroller?.closest('body')!==document.body||controls?.closest('body')!==document.body){clearInterval(int)
return;}
if(document.visibilityState!=='visible'){Debug.log(`Not auto-playing carousel "${scroller.id}" because the document isn't focused`);return;}
if(!visibleCarousels.has(scroller)){Debug.log(`Not auto-playing carousel "#${scroller.id}" because it is off-screen.`);return;}
Debug.log(`Auto-playing carousel "#${scroller.id}".`);scrollPanels()},parseInt(interval))
callbacks.push(()=>clearInterval(int));}
const scrollPanels=async(direction="next",loop=true)=>{const currentlyVisibleElements=[];let precedingElement=false;let succeedingElement=false;for(const child of[...scroller.children]){if(visibleElements.has(child)){currentlyVisibleElements.push(child);}else if(!itemWidths.get(child)){continue;}else if(currentlyVisibleElements.length){succeedingElement=child;break;}else{precedingElement=child;}}
const rtl=this.isRTL(scroller);if((direction==='next'&&!succeedingElement)||(direction==='prev'&&!precedingElement)){const amount=(rtl&&direction==='prev')||(!rtl&&direction==='next')?-scrollerScrollWidth:scrollerScrollWidth;scroller.scrollBy({left:amount,behavior:'smooth'});}else if(currentlyVisibleElements.length){let el=currentlyVisibleElements[0];let amount;if(!succeedingElement&&precedingElement instanceof Element&&direction==='prev'){const padding=this.getScrollPadding(scroller);amount=(itemWidths.get(precedingElement)+currentlyVisibleElements.map(el=>itemWidths.get(el)).reduce((prev,cur)=>prev+scrollerGap+cur,0))-(scrollerWidth-padding.left-padding.right);if(!rtl){amount=-amount;}}else{amount=(rtl&&direction==='prev')||(!rtl&&direction==='next')?itemWidths.get(el)+scrollerGap:-(itemWidths.get(el)+scrollerGap);}
scroller.scrollBy({left:amount,behavior:'smooth'});}}},containerAtEnd(scroller,direction='prev'){const _containerBox=scroller.getBoundingClientRect();if(Math.ceil(_containerBox.width)>=Math.floor(scroller.scrollWidth)){return true;}
const scrollPadding=this.getScrollPadding(scroller);const containerBox=new DOMRect(_containerBox.x+scrollPadding.left,_containerBox.y,_containerBox.width-(scrollPadding.left+scrollPadding.right),_containerBox.height);const rtl=this.isRTL(scroller);for(const child of scroller.querySelectorAll(':scope > *')){const box=child.getBoundingClientRect();const computed=getComputedStyle(child);if(['absolute','fixed'].includes(computed.position?.toLowerCase())){continue;}
if(rtl&&((direction==='prev'&&Math.floor(box.right)>=Math.ceil(containerBox.right))||(direction==='next'&&Math.ceil(box.left)<=Math.floor(containerBox.left)))){return false;}
if(!rtl&&((direction==='prev'&&Math.ceil(box.left)<=Math.floor(containerBox.left))||(direction==='next'&&Math.floor(box.right)>=Math.ceil(containerBox.right)))){return false}}
return true;},getScrollPadding(elem){const style=getComputedStyle(elem);const padding={left:0,right:0};for(const dir of['Left','Right']){if(style[`scrollPadding${dir}`]?.match(/^(\d+|\d+\.\d*|\.\d+)px$/)){padding[dir.toLowerCase()]=parseFloat(style[`scrollPadding${dir}`].match(/^(\d+|\d+\.\d*|\.\d+)px$/)[1]);}}
return padding;},isRTL(elem){elem=$(elem||document.body).get(0);while(elem instanceof HTMLElement){if(elem.dir&&elem.dir.toLowerCase()==='rtl'){return true;}
elem=elem.parentElement;}
return document.dir.toLowerCase()==='rtl';}}});}(window.jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.chart',function(){var defaults={};var respond=function(elem,options){var doInit=function(){if(!$(elem).data('_chart')){$(elem).data('_chart',chartObj(elem,_.defaults(options,defaults)));}};try{doInit();}catch(err){ips.loader.get(['https://www.gstatic.com/charts/loader.js']).then(function(){google.charts.load('47',{'packages':['corechart','gauge','table'],'callback':doInit});});}},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}},getObj=function(elem){if($(elem).data('_chart')){return $(elem).data('_chart');}
return undefined;};var chartObj=function(elem,options){var data=new google.visualization.DataTable();var headerTypes={};var extraOptions={};var chartElem=$(elem).next();var chart=null;const table=$(elem).is('table')?$(elem):$(elem).find('table');var init=function(){$(elem).addClass('ipsLoading');table.find('thead th').each(function(idx){headerTypes[idx]=$(this).attr('data-colType');data.addColumn($(this).attr('data-colType'),$(this).text());});table.find('tbody tr').each(function(){var row=[];$(this).find('td').each(function(idx){if(headerTypes[idx]=='number'){var val;if(val=$(this).text()){val=Number(val);}else{val=null;}}else if(headerTypes[idx]=='date'||headerTypes[idx]=='datetime'||headerTypes[idx]=='timeofday'){var val=new Date($(this).text());}else{var val=$(this).text();}
if(!_.isNaN(val)){if($(this).attr('data-key')){val={v:$(this).attr('data-key'),f:val};}
row.push(val);}});data.addRow(row);});if(options.format){var formatter=new google.visualization.NumberFormat({pattern:'# '+options.format});formatter.format(data,1);}
extraOptions=$.parseJSON(options.extraOptions);if(!_.isUndefined(extraOptions.height)){chartElem.css({height:extraOptions.height+'px'});}else{chartElem.css({minHeight:'250px'});}
$(elem).hide().removeClass('ipsLoading').after(chartElem);$(window).on('resize',drawChart);drawChart();google.visualization.events.addListener(chart,'ready',function(){$(elem).trigger('chartInitialized');});$(document).on('tabShown',tabShown);},drawChart=function(e){chart=new google.visualization[options.type](chartElem.get(0));chart.draw(data,extraOptions);},destruct=function(){$(window).off('resize',drawChart);$(document).off('tabShown',tabShown);},tabShown=function(e,data){if($.contains(data.panel.get(0),elem.get(0))){drawChart();}};if(_.isUndefined(google.visualization)){google.setOnLoadCallback(init);}else{init();}
return{init:init,drawChart:drawChart};};ips.ui.registerWidget('chart',ips.ui.chart,['type','extraOptions','format']);return{respond:respond,destruct:destruct,getObj:getObj};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.codebox',function(){ips.ui.registerWidget('codebox',ips.ui.codebox,['allowed-languages','autosave-key']);return{respond(elem,options){if($(elem).data('_editor')){return;}
const instance=editorObj(elem,options)
$(elem).data('_editor',instance)
instance.init()},getObj(elem){if($(elem).data('_editor')){return $(elem).data('_editor');}
return undefined;},getObjWithInit(elem,callback){let obj=this.getObj(elem);if(obj){callback(obj);}else{let initFunction=$(elem).data('_editorInit');if(initFunction){initFunction(callback);}}},destruct(elem){this.getObj(elem)?.destruct();}};});function editorObj(elem,options){let instance;let reactRoot
let allowedLanguages;async function init(){await ips.ui.editorv5.whenLoaded()
const config={'codeMode':true}
if(options['allowed-languages']){allowedLanguages=[...new Set(JSON.parse(options['allowed-languages']))]
config.allowedLanguages=allowedLanguages
config.defaultLanguage=allowedLanguages.includes('plaintext')?'plaintext':allowedLanguages[0]}
const textArea=$(elem).get(0);config.textArea=textArea;if(options['autosave-key']){config.autosaveKey=options['autosave-key'];}else if(!textArea.closest('i-theme-editor')&&textArea.closest('form[action]')&&(textArea.hasAttribute('name')||textArea.closest('.ipsFieldRow[id], .ipsFieldRow [id]'))){config.autosaveKey=ips.utils.crypto.md5(JSON.stringify([textArea.closest('form[action]').getAttribute('action'),textArea.getAttribute('name')||textArea.closest('.ipsFieldRow[id], .ipsFieldRow [id]').id]));}
const editorLocation=document.createElement('div')
editorLocation.dataset.role='reactRoot'
textArea.parentElement.insertBefore(editorLocation,textArea)
config.content=textArea.innerHTML
config.onUpdate=(editor)=>{const value=editor.getValue();textArea.innerHTML="";textArea.appendChild(document.createTextNode(value));textArea.value=value;textArea.dispatchEvent(new CustomEvent('ips:codebox#update',{detail:{instance,elem:textArea},bubbles:true}));}
config.hasTags=!!textArea.closest('[data-controller="core.global.editor.customtags"]');textArea.ipsHide()
let result=await ips.utils.tiptap.editorInstance(editorLocation,config);instance=result[0]
textArea.dispatchEvent(new CustomEvent('ips:codeboxAfterInit',{bubbles:true,cancelable:true,detail:{instance,config}}))
textArea.addEventListener('insertCode',e=>{if(e?.detail?.content){let content=e.detail.content;if(typeof content==='string'){instance.executeEdits("insertCode",[{text:content,range:instance.getSelection()}]);instance.focus();}else{throw new TypeError(`The content property of the event insertCode is expected to be a string`);}}})
reactRoot=result[1]}
function destruct(){instance?.dispose()
reactRoot.unmount();}
return{instance,destruct,init}}}(jQuery,_));;
((($,_)=>{"use strict";ips.createModule('ips.ui._codehighlighting',function(){const LOADER_RESOLVERS=new Set();const LOADER_REJECTS=new Set();let STATE='loading';document.addEventListener('ipsCodehighlightingLoaded',()=>{STATE='loaded';LOADER_RESOLVERS.forEach(resolve=>resolve());LOADER_RESOLVERS.clear();LOADER_REJECTS.clear();});let timeout;let attempts=0;function inject(){clearTimeout(timeout);window.removeEventListener('load',inject);if(typeof ips.ui?.codehighlighting==='object'){STATE='loaded';LOADER_REJECTS.clear();LOADER_RESOLVERS.forEach(resolve=>resolve());;LOADER_RESOLVERS.clear();return;}
if(!document?.body){if(attempts++<5){timeout=setTimeout(inject,100);Debug.log(`Attempting to load the codehighlighting module. Attempt: ${attempts}`);}else{STATE='error';LOADER_RESOLVERS.clear();LOADER_REJECTS.forEach(reject=>reject(new Error(`The codehighlighting module could not be loaded`)));LOADER_RESOLVERS.clear();Debug.warn(`Couldn't load the codehighlighting module after 5 attempts because document.body isn't present!`);}
return;}
const script=document.createElement('script')
document.body.appendChild(script)
script.src=ips.getSetting('baseURL').replace(/\/+$/,"")+"/applications/core/interface/static/codehighlighting/codehighlighting.js?antiCache="+encodeURIComponent(ips.getSetting('jsAntiCache'));}
try{if(!document?.body){throw new Error();}
inject();}catch(e){window.addEventListener('load',inject,{once:true});timeout=setTimeout(()=>{if(typeof ips.ui?.codehighlighting==="object"){STATE='loaded';LOADER_REJECTS.clear();LOADER_RESOLVERS.forEach(resolve=>resolve());LOADER_RESOLVERS.clear();return;}
Debug.warn(`The codehighlighting module was not appended to document.body because the window's \`load\` event didn't fire within 2 seconds after ips.ui._codehighlighting was initialized.`);inject()},2000);}
return{whenLoaded(){return new Promise((resolve,reject)=>{if(STATE==='loaded'){return resolve();}else if(STATE==='error'){return reject();}
LOADER_REJECTS.add(reject);LOADER_RESOLVERS.add(resolve);})}}})})(jQuery,_));
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.contentItem',function(){var defaults={multiValues:true,unique:false,fieldTemplate:'core.contentItem.field',resultsTemplate:'core.contentItem.resultWrapper',resultItemTemplate:'core.contentItem.resultItem',itemTemplate:'core.contentItem.item',queryParam:'q',minAjaxLength:1};var respond=function(elem,options){if(!$(elem).data('_contentItem')){$(elem).data('_contentItem',contentItemObj(elem,_.defaults(options,defaults)));}},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}},getObj=function(elem){elem=$(elem);if(elem.data('_contentItem')){return elem.data('_contentItem');}else if($('[name="'+elem.attr('name')+'_original'+'"]').length&&$('[name="'+elem.attr('name')+'_original'+'"]').data('_contentItem')){return $('[name="'+elem.attr('name')+'_original'+'"]').data('_contentItem');}
return undefined;};ips.ui.registerWidget('contentItem',ips.ui.contentItem,['resultsTemplate','resultItemTemplate','itemTemplate','queryParam','dataSource','maxItems','minAjaxLength']);return{respond:respond,destruct:destruct,getObj:getObj};});var contentItemObj=function(elem,options,e){var timer,blurTimer,lastValue='',originalTextField,valueField,hiddenValueField,itemListWrapper,textField,dataSource,elemID=$(elem).identify().attr('id'),wrapper,inputItem,resultsElem,disabled=false,required=false,tooltip=null,tooltipTimer=null;var init=function(){if($(elem).is('input[type="text"], input[type="search"]')){originalTextField=$(elem);}else{originalTextField=$(elem).find('input[type="text"], input[type="search"]').first();}
_buildWrapper();_getDataSource();originalTextField.removeAttr('list');_buildResultsList();if(originalTextField.is(':disabled')){disabled=true;}
if(originalTextField.is('[required]')){required=true;originalTextField.removeProp('required').removeAttr('aria-required');}
textField.prop('autocomplete','off').prop('spellcheck',false).prop('disabled',disabled).attr('aria-autocomplete','list').attr('aria-haspopup','true').attr('tabindex',originalTextField.attr('tabindex')||'');$(document).on('click',_documentClick);wrapper.click(function(e){e.stopPropagation();return false;});textField.on('focus',_focusField).on('blur',_blurField).on('keydown',_keydownField)
wrapper.on('click',_clickWrapper).on('keydown',_keydownWrapper).on('propChanged',_propChanged).toggleClass('ipsField_autocompleteDisabled',disabled);elem.trigger('autoCompleteReady',{elemID:elemID,elem:elem,currentValues:contentItems.getValues()});},destruct=function(){$(document).off('click',_documentClick);},_propChanged=function(e){disabled=originalTextField.is(':disabled');wrapper.toggleClass('ipsField_autocompleteDisabled',disabled);},_buildResultsList=function(){if(options.resultsElem&&$(options.resultsElem).length){resultsElem=$(options.resultsElem);return;}
var resultsList=ips.templates.render(options.resultsTemplate,{id:elemID});wrapper.append(resultsList);resultsElem=$('#'+elemID+'_results');resultsElem.on('mouseover','[data-id]',function(e){results.select($(e.currentTarget));}).on('click','[data-id]',function(e){_addContentItem($(e.currentTarget));textField.focus();}).attr('aria-busy','false');},_buildWrapper=function(){var existingClasses=elem[0].className;$(elem).after(ips.templates.render(options.fieldTemplate,{id:elemID})).removeClass(existingClasses);wrapper=$('#'+elemID+'_wrapper');inputItem=$('#'+elemID+'_inputItem');var insertElem=$('<input/>').attr({type:'text',id:elemID+'_dummyInput'}).prop('autocomplete','off');textField=insertElem;var name=originalTextField.attr('name');originalTextField.attr('name',originalTextField.attr('name')+'_original');valueField=$('<input/>').attr('name',name).hide();hiddenValueField=$('input[name='+name+'_values]');itemListWrapper=$('[data-contentitem-results='+name+']');originalTextField.hide();wrapper.addClass(existingClasses).append(elem).append(valueField).find('#'+elemID+'_inputItem').append(insertElem);if(options.maxItems&&contentItems.total()>=options.maxItems){wrapper.hide();}
itemListWrapper.on('click','[data-action="delete"]',function(e){_deleteContentItem($(e.currentTarget).parent('[data-id]'));});},_getDataSource=function(){if(ips.utils.validate.isUrl(options.dataSource)){dataSource=remoteData(options.dataSource,options);}else{dataSource=noData();}},_clickWrapper=function(e){if(!$(e.target).is(textField)&&(!resultsElem||!$.contains(resultsElem.get(0),e.target))){textField.focus();}},_focusField=function(e){if(dataSource.type=='none'){return;}
timer=setInterval(_timerFocusField,400);},_blurField=function(e){clearInterval(timer);_.delay(_timerBlurField,300);},_timerBlurField=function(){_closeResults();},_timerFocusField=function(){if(dataSource.type=='none'){return;}
var currentValue=_getCurrentValue();if(currentValue==lastValue){return;}
lastValue=currentValue;_loadResults(currentValue);},_loadResults=function(value){_toggleLoading('show');resultsElem.attr('aria-busy','true');dataSource.getResults(value).done(function(results){_showResults(_processResults(results,value));}).fail(function(){}).always(function(){resultsElem.attr('aria-busy','false');_toggleLoading('hide');});},_toggleLoading=function(doWhat){if(doWhat=='show'){wrapper.addClass('ipsField_loading');}else{wrapper.removeClass('ipsField_loading');}},_closeResults=function(e){if(e){e.preventDefault();}
if(resultsElem&&resultsElem.length){resultsElem.hide().attr('aria-expanded','false');}
dataSource.stop();},_documentClick=function(){_closeResults();},_processResults=function(results,text){var existingItems=contentItems.getValues(),newResults={};$.each(results,function(key,data){if(!data.id||_.indexOf(existingItems,data.id)===-1){newResults[key]=data;}});return newResults;},_showResults=function(results){var output='';$.each(results,function(idx,value){output+=ips.templates.render(options.resultItemTemplate,value);});if(resultsElem.attr('id')==(elemID+'_results')){_positionResults();}
resultsElem.show().html(output).attr('aria-expanded','true');},_positionResults=function(){resultsElem.css({width:wrapper.outerWidth()+'px'});var positionInfo={trigger:wrapper,targetContainer:wrapper,target:resultsElem,center:false};var resultsPosition=ips.utils.position.positionElem(positionInfo);$(resultsElem).css({left:'0px',top:resultsPosition.top+'px',position:(resultsPosition.fixed)?'fixed':'absolute',zIndex:ips.ui.zIndex()});},_getCurrentValue=function(){var value=textField.val();return value;},_keydownWrapper=function(e){if(e.keyCode==ips.ui.key.ESCAPE){keyEvents.escape(e);}},_keydownField=function(e){_expandField();var ignoreKey=false;if(!_([ips.ui.key.UP,ips.ui.key.DOWN,ips.ui.key.ESCAPE,ips.ui.key.ENTER]).contains(e.keyCode)){ignoreKey=true;}
var value=textField.val().trim();if(ignoreKey){return;}
switch(e.keyCode){case ips.ui.key.UP:keyEvents.up(e);break;case ips.ui.key.DOWN:keyEvents.down(e);break;case ips.ui.key.ESCAPE:keyEvents.escape(e);break;case ips.ui.key.ENTER:keyEvents.enter(e);break;}},_addContentItem=function(elem){contentItems.add(elem);textField.val('');lastValue='';_resetField();if(options.maxItems&&contentItems.total()>=options.maxItems){wrapper.hide();}},_deleteContentItem=function(item){if(disabled){return;}
contentItems.remove(item);},keyEvents={up:function(e){if(!resultsElem||!resultsElem.is(':visible')){return;}
e.preventDefault();var selected=results.getCurrent();if(!selected){results.selectLast();}else{var prev=results.getPrevious(selected);if(prev){results.select(prev);}else{results.selectLast();}}},down:function(e){if(!resultsElem||!resultsElem.is(':visible')){return;}
e.preventDefault();var selected=results.getCurrent();if(!selected){results.selectFirst();}else{var next=results.getNext(selected);if(next){results.select(next);}else{results.selectFirst();}}},enter:function(e){e.preventDefault();var currentResult=results.getCurrent();var value='';if(currentResult){value=currentResult.attr('data-id');}
if(!value){return false;}
_addContentItem(currentResult);},escape:function(e){if(resultsElem&&resultsElem.is(':visible')){_closeResults();}}},results={deselectAll:function(){resultsElem.find('[data-selected]').removeAttr('data-selected');},getCurrent:function(){if(dataSource.type=='none'){return;}
var cur=resultsElem.find('[data-selected]');if(cur.length&&resultsElem.is(':visible')){return cur;}
return false;},getPrevious:function(result){var prev=$(result).prev('[data-id]');if(prev.length){return prev;}
return false;},getNext:function(result){var next=$(result).next('[data-id]');if(next.length){return next;}
return false;},selectFirst:function(){results.select(resultsElem.find('[data-id]').first());},selectLast:function(){results.select(resultsElem.find('[data-id]').last());},select:function(result){results.deselectAll();result.attr('data-selected',true);}},contentItems={selected:null,add:function(elem){var html='';var obj=$(elem).find('[data-role=contentItemRow]');html=obj.html();itemListWrapper.append(ips.templates.render(options.itemTemplate,{id:obj.attr('data-itemid'),html:html}));if(resultsElem){_closeResults();}
hiddenValueField.val(contentItems.getValues().join(','));if(options.maxItems&&contentItems.total()>=options.maxItems){wrapper.hide();}
elem.trigger('contentItemAdded',{html:html,itemList:contentItems.getValues(),totalItems:contentItems.total()});return true;},remove:function(item){if(contentItems.selected==item){contentItems.selected=null;}
var value=$(item).attr('data-value');$(item).remove();if(options.maxItems&&contentItems.total()<options.maxItems){wrapper.show();}
hiddenValueField.val(contentItems.getValues().join(','));elem.trigger('contentItemDeleted',{item:item,itemList:contentItems.getValues(),totalItems:contentItems.total()});},total:function(){return itemListWrapper.find('[data-id]').length;},getValues:function(){var values=[];var allContentItems=itemListWrapper.find('[data-id]');if(allContentItems.length){values=_.map(allContentItems,function(item){return $(item).attr('data-id');});}
return values;}},_duplicateValue=function(value){var values=contentItems.getValues();if(values.indexOf(value)!==-1){return true;}
return false;},_expandField=function(){var text=textField.val();var widthOfElem=wrapper.width();widthOfElem-=(parseInt(wrapper.css('padding-left'))+parseInt(wrapper.css('padding-right')));var span=$('<span/>').text(text).css({'font-size':textField.css('font-size'),'letter-spacing':textField.css('letter-spacing'),'position':'absolute','top':'-100px','left':'-300px','opacity':"0.1"});ips.getContainer().append(span);var width=span.width()+20;span.remove();textField.css({width:((width>=widthOfElem)?widthOfElem:width)+'px'});},_resetField=function(){textField.css({width:'15px'});};init();return{init:init,destruct:destruct,addContentItem:contentItems.add,getContentItem:contentItems.getValues,removeContentItem:contentItems.remove};};var remoteData=function(source,options){var ajaxObj,loadedCache=false,cache={};var getResults=function(text){return _remoteSearch(text);},totalItems=function(){return-1;},_remoteSearch=function(text){var deferred=$.Deferred();if(ajaxObj){ajaxObj.abort();}
if(options.minAjaxLength>text.length){deferred.reject();return deferred.promise();}
if(cache[text]){deferred.resolve(cache[text]);}else{ajaxObj=ips.getAjax()(source+'&'+options.queryParam+'='+encodeURIComponent(text),{dataType:'json'}).done(function(response){deferred.resolve(response);cache[text]=response;}).fail(function(jqXHR,status,errorThrown){if(status!='abort'){Debug.log('aborting');}
deferred.reject();});}
return deferred.promise();},_remoteFetch=function(text){var deferred=$.Deferred();if(!loadedCache){if(ajaxObj){return;}
if(options.minAjaxLength>text.length){return;}
ajaxObj=ips.getAjax()(source,{dataType:'json'}).done(function(response){loadedCache=true;cache=response;_remoteFetch(text);}).fail(function(jqXHR,status,errorThrown){if(status!='abort'){Debug.log('aborting');}
deferred.reject();});}
cache.each(function(idx,item){if(item.value.toLowerCase().startsWith(text)){output.push(item);}});return deferred.promise();},stop=function(){if(ajaxObj){ajaxObj.abort();}};return{type:'remote',getResults:getResults,totalItems:totalItems,stop:stop};};var noData=function(){return{type:'none',getResults:$.noop,totalItems:-1,stop:$.noop};};}(jQuery,_));;
;(function($,_){"use strict";const CACHED_REMOTE_RESPONSES=new Map();ips.createModule('ips.ui.controls',function(){document.addEventListener('click',handleEvent);function respond(elem){}
function handleEvent(e){if(e.target.closest('.ipsEditor__toolbar-item, .ipsEditor__toolbar-panel')){return;}
let toggle=e.target.closest('[data-ipscontrols][aria-controls]');const lightDismiss=document.querySelectorAll("[data-ips-hidden-light-dismiss][open], [data-ips-hidden-light-dismiss]:not(dialog):not([hidden])");if(!toggle&&!lightDismiss.length)return;if(toggle){const name=toggle.getAttribute("aria-controls"),contentElementIds=name.split(" "),isExpanded=toggle.getAttribute("aria-expanded");if(!isExpanded){Debug.log("The clicked element has [aria-controls] but no [aria-expanded] value.")
return}
if(contentElementIds.length>1){document.querySelectorAll(`[aria-controls="${name}"]`).forEach(t=>t.setAttribute("aria-expanded",(isExpanded==="true")?"false":"true"));}
for(const id of contentElementIds){const content=document.querySelector(`#${id}`);if(!content){Debug.log(`An element with #${id} was not found and therefore can't be toggled.`);continue;}
showOrHide(content,toggle,!(isExpanded==="true"));const isInGroup=content.getAttribute("data-ips-hidden-group");if(isInGroup){const groupElements=document.querySelectorAll(`[data-ips-hidden-group="${isInGroup}"]:not([hidden])`);for(const groupElement of groupElements){if(groupElement!=content){showOrHide(groupElement,toggle,false);}}}}}
for(const lightDismissEl of lightDismiss){if(lightDismissEl.contains(e.target)&&e.target.tagName.toLowerCase()!=="dialog")continue;showOrHide(lightDismissEl,e.target,false);}}
async function showOrHide(content,trigger,show=true){if(show&&(content.hasAttribute("data-ips-hidden-top-layer")||content.tagName==="DIALOG")){document.getElementById('ipsLayout')?.appendChild(content);}
const contentTag=(content.tagName);document.querySelectorAll(`[data-ipscontrols][aria-controls="${content.id}"]`).forEach(t=>t.setAttribute("aria-expanded",show));if(show){if(contentTag==="DIALOG"){content.showModal();content.addEventListener("close",_closeEvent);}else{content.hidden=false;}
const src=trigger.dataset.ipscontrolsSrc;if(typeof src==='string'&&!content.dataset.ipscontrolsLoaded){if(CACHED_REMOTE_RESPONSES.has(src)&&typeof CACHED_REMOTE_RESPONSES.get(src).html==='string'&&!(typeof CACHED_REMOTE_RESPONSES.get(src).expiresAt==='number'&&CACHED_REMOTE_RESPONSES.get(src).expiresAt<Date.now()/1000)){Debug.log(`ips.ui.controls: Using cached response for ${src}`);content.innerHTML=CACHED_REMOTE_RESPONSES.get(src).html;for(const cls of[...content.classList]){if(cls.startsWith('ipsLoading')){content.classList.remove('ipsLoading');}}
$(document).trigger('contentChange',[$(content)]);content.ipsHide();content.dataset.ipscontrolsLoaded='1';content.querySelector("[data-autofocus]")?.focus();await new Promise(resolve=>setTimeout(resolve,50));content.ipsShow();}else{content.classList.add('ipsLoading');const start=Date.now();loadContent(src).then(html=>new Promise(resolve=>{if(Date.now()-start<700){setTimeout(()=>resolve(html),700-(Date.now()-start))}else{resolve(html)}})).then(html=>{content.innerHTML=html;for(const cls of[...content.classList]){if(cls.startsWith('ipsLoading')){content.classList.remove('ipsLoading');}}
$(document).trigger('contentChange',[$(content)]);content.dataset.ipscontrolsLoaded='1';content.querySelector("[data-autofocus]")?.focus();})}}else{content.querySelector("[data-autofocus]")?.focus();}}
requestAnimationFrame(()=>{content.style.setProperty('--i-animating-height',content.scrollHeight+'px');})
content.setAttribute("data-ips-animating",(show)?'opening':'closing');await Promise.allSettled(content.getAnimations().map((a)=>a.finished));if(!show){(contentTag==="DIALOG")?content.close():content.hidden=true;}
content.removeAttribute("data-ips-animating");const eventNames=['ips:toggleComplete']
if(content.dataset.ipsHiddenEvent){eventNames.push(content.dataset.ipsHiddenEvent)}
eventNames.forEach(eventName=>content.dispatchEvent(new CustomEvent(eventName,{bubbles:true,detail:{hidden:content.hidden,trigger:trigger}})));}
function _closeEvent(e){if(!e.target.getAttribute("open")){showOrHide(e.target,e.target,false);}}
async function loadContent(src,forceRequest=false){src=(new URL(src)).toString();const cachedContents=CACHED_REMOTE_RESPONSES.get(src);if(!forceRequest&&cachedContents&&typeof cachedContents.html==='string'){if(!(typeof cachedContents.expiresAt==='number'&&cachedContents.expiresAt<Date.now()/1000)){Debug.log(`ips.ui.controls: Using cached response for ${src}`);return cachedContents.html;}
CACHED_REMOTE_RESPONSES.delete(src);}
try{const response=await ips.fetch(src);if(typeof response!=='object'||typeof response.html!=='string'){throw new TypeError(`Expected an object with an html:string property`);}
if(!response.noCache){response.expiresAt=response.expiresAt||Math.round(Date.now()/1000+3600);if(typeof response.expiresAt==='string'){response.expiresAt=parseInt(response.expiresAt);}
if(typeof response.expiresAt!=='number'||Number.isNaN(response.expiresAt)){response.expiresAt=Math.round(Date.now()/1000+3600);}
if(!Number.isInteger(response.expiresAt)){response.expiresAt=Math.round(response.expiresAt);}
if(response.expiresAt*1000>Date.now()){CACHED_REMOTE_RESPONSES.set(src,response);}}
return response.html;}catch(e){return ips.templates.render("ips.ui.controls.cannot_load",{message:typeof e.responseJSON?.errorMessage==='string'?e.responseJSON.errorMessage:undefined});}}
ips.ui.registerWidget('controls',ips.ui.controls,['src']);return{respond}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.copy',function(){var respond=function(elem,options,e){ips.loader.getStatic("/applications/core/interface/static/clipboard/clipboard.min.js").then(function(){if(ClipboardJS.isSupported()){elem.find('[data-role="copyButton"]').show();if(elem.find('[data-role="copyButton"]').attr('href')){elem.find('[data-role="copyButton"]').on('click',function(e){e.preventDefault();e.stopPropagation();});}
var clipboard=new ClipboardJS(elem.find('[data-role="copyButton"]').get(0));clipboard.on('success',function(e){if(elem.attr('data-ipsCopy-flashmessage')!==undefined){ips.ui.flashMsg.show(ips.getString('copied'))}else{elem.find('[data-role="copyButton"]').text(ips.getString('copied'));}});}});};ips.ui.registerWidget('copy',ips.ui.copy,[]);return{respond};});}(jQuery,_));;
;(function(){"use strict";ips.createModule('ips.ui.details',function(){var respond=function(elem){document.addEventListener('click',toggleDetails);},toggleDetails=function(e){const summary=e.target.closest('[data-ipsdetails] summary');if(!summary)return;const details=summary.closest('details'),content=details.querySelector('i-details-content'),isOpen=details.open;if(!details||!content)return;e.preventDefault();if(!isOpen)details.open=true;content.style.setProperty('--i-animating-height',content.scrollHeight+'px');content.setAttribute('data-ips-animating',(isOpen)?'closing':'opening');Promise.all(content.getAnimations().map((a)=>a.finished)).then(()=>{if(isOpen)details.open=false;content.removeAttribute('data-ips-animating');});};ips.ui.registerWidget('details',ips.ui.details);return{respond:respond}});}());;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.dialog',function(){var defaults={modal:true,draggable:false,className:'ipsDialog',extraClass:'',close:true,fixed:false,narrow:false,callback:null,forceReload:false,flashMessage:'',flashMessageTimeout:2,flashMessageEscape:true,remoteVerify:true,remoteSubmit:false,destructOnClose:false,ajax:{type:'get',data:{}}};var showStack=[];var respond=function(elem,options,e){e.preventDefault();if(!options.url&&!options.content&&$(elem).attr('href')){options.url=$(elem).attr('href');}
if(!$(elem).data('_dialog')){$(elem).data('_dialog',dialogObj(elem,_.defaults(options,defaults)));}
$(elem).data('_dialog').show();},getObj=function(elem){if($(elem).data('_dialog')){return $(elem).data('_dialog');}
return undefined;},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();$(elem).removeData('_dialog');}},create=function(options){return dialogObj(null,_.defaults(options,defaults));},hasOpenDialogs=function(){return(showStack.length>0);},_init=function(){$(document).on('keydown',function(e){if(e.keyCode==ips.ui.key.ESCAPE){$(document).trigger('closeDialog',{dialogID:showStack[showStack.length-1]});}}).on('openDialog',function(e,data){showStack.push(data.dialogID);}).on('hideDialog',function(e,data){showStack=_.without(showStack,data.dialogID);});};ips.ui.registerWidget('dialog',ips.ui.dialog,['url','modal','draggable','size','title','close','fixed','destructOnClose','extraClass','callback','content','forceReload','flashMessage','flashMessageTimeout','flashMessageEscape','remoteVerify','remoteSubmit'],{lazyLoad:true,lazyEvents:'click'});_init();return{respond:respond,destruct:destruct,getObj:getObj,create:create,hasOpenDialogs:hasOpenDialogs};});var dialogObj=function(elem,options){var modal,dialog,ajaxObj,dialogID='',elemID='',dialogBuilt=false,contentLoaded=false,modalEvent={up:false,down:false},contentProcessors=[];var init=function(){if(elem===null){elemID='elem_'+(Math.round(Math.random()*10000000));}else{elemID=$(elem).identify().attr('id');}
dialogID=elemID+'_dialog';if(options.size=='fullscreen'){options.fixed=true;}
$(document).on('closeDialog',closeDialog);},destruct=function(){clearTimeout(anchorClickTimeout);$(document).off('closeDialog',closeDialog);if(modal){modal.remove();}
if(dialog){dialog.remove();}},anchorClickTimeout,checkForAnchorClicks=e=>{clearTimeout(anchorClickTimeout);if(e.defaultPrevented){return;}
const link=e.target?.closest?.(`a[href*="#"]`);if(!link){return;}
const pageURL=new URL(window.location.href);pageURL.hash="";const linkURL=new URL(link.href,window.location.href);const hash=linkURL.hash;linkURL.hash="";if(!hash||pageURL.toString()!==linkURL.toString()){return;}
const dialogEl=dialog.get(0);if(!dialogEl){return;}
try{if(hash.startsWith('#')&&dialogEl.querySelector(hash)){return;}}catch(e){}
anchorClickTimeout=setTimeout(()=>{if(!e.defaultPrevented){closeDialog(undefined,{dialogID});}},0);},closeDialog=function(e,data){if(data&&data.originalEvent){data.originalEvent.preventDefault();}
if(data&&data.dialogID==dialogID){hide();modalEvent={up:false,down:false};}},hide=function(){return new Promise(resolve=>{try{clearTimeout(anchorClickTimeout);dialog.get(0)?.removeEventListener('click',checkForAnchorClicks);dialog.animationComplete(function(){if(options.forceReload||options.destructOnClose){ips.controller.cleanContentsOf(dialog);dialog.find('.'+options.className+'_content').html('');}
$(elem||document).trigger('hideDialog',{elemID:elemID,dialogID:dialogID,dialog:dialog});if(options.destructOnClose){ips.ui.dialog.destruct(elem);}
resolve()});ips.utils.anim.go('fadeOutDown fast',dialog);if(options.modal){ips.utils.anim.go('fadeOut fast',modal);}
if(options.fixed){$('html').removeClass('ipsNoScroll');}}catch(e){}});},show=function(initOnly){if(options.url&&!contentLoaded){_remoteDialog(initOnly);}else if(!contentLoaded){_localDialog(initOnly);}else{if(initOnly){return;}
if(modal){modal.css({zIndex:ips.ui.zIndex()});}
dialog.css({zIndex:ips.ui.zIndex()});_positionDialog();if(dialog.find('.'+options.className+'_content').length){for(const processor of contentProcessors){processor($(dialog.find('.'+options.className+'_content')).get(0))}}
_showDialog();}},remove=function(hideFirst){var doRemove=function(){if(ajaxObj&&_.isFunction(ajaxObj.abort)){ajaxObj.abort();}
dialog.remove();if(modal){modal.remove();}
dialog=null;modal=null;dialogBuilt=false;contentLoaded=false;ajaxObj=null;};if(hideFirst&&dialog.is(':visible')){hide().done(function(){doRemove();});}else{doRemove();}},setLoading=function(loading){if(loading){dialog.find('.'+options.className+'_loading').show().end().find('.'+options.className+'_content').hide();_positionDialog();}else{dialog.find('.'+options.className+'_loading').hide().end().find('.'+options.className+'_content').show();}},updateContent=function(newContent){dialog.find('.'+options.className+'_content').html(newContent);for(const processor of contentProcessors){if(processor instanceof Function){processor(dialog.get(0))}}
$(document).trigger('contentChange',[dialog]);},addContentProcessor=function(processor){if(!(processor instanceof Function)){throw new TypeError(`A non-function value was passed as a processor`);}
contentProcessors.push(processor)},_showDialog=function(){if(options.fixed){$('html').addClass('ipsNoScroll');}
if(options.modal){ips.utils.anim.go('fadeIn',modal);}
ips.utils.anim.go('fadeInDown',dialog).done(function(){dialog.find('.'+options.className+'_loading');});$(elem||document).trigger('openDialog',{elemID:elemID,dialogID:dialogID,dialog:dialog,contentLoaded:contentLoaded});dialog.get(0)?.addEventListener('click',checkForAnchorClicks);},_remoteDialog=function(initOnly){if(!dialogBuilt){if(options.modal){_buildModal();}
_buildDialog();}
if(initOnly){_fetchContent();}else{setLoading(true);_showDialog();_fetchContent();}
if(!options.forceReload){contentLoaded=true;}},_localDialog=function(initOnly){if(!options.content&&!$(options.content).length){Debug.warn("'content' option not specified for dialog, or element doesn't exist");return;}
if(!dialogBuilt){if(options.modal){_buildModal();}
_buildDialog();}
if(initOnly){return;}
dialog.find('.'+options.className+'_content').html($(options.content).first().show());for(const processor of contentProcessors){processor(dialog.find('.'+options.className+'_content').get(0))}
_showDialog();if(!options.forceReload){contentLoaded=true;}},_fetchContent=function(){var deferred=$.Deferred();setLoading(true);ajaxObj=ips.getAjax()(options.url,{type:options.ajax.type,data:options.ajax.data}).done(function(response){setLoading(false);updateContent(response);deferred.resolve();if(options.callback!==null){options.callback(dialog);}
$(elem||document).trigger('dialogContentLoaded',{elemID:elemID,dialogID:dialogID,dialog:dialog,contentLoaded:true});}).fail(function(jqXHR,status,errorThrown){if(jqXHR.responseJSON){ips.ui.alert.show({message:jqXHR.responseJSON,});setLoading(false);contentLoaded=false;hide();}else if(Debug.isEnabled()){Debug.error("Ajax request failed ("+status+"): "+errorThrown);}else if(elem){window.location=elem.href;}else{ips.ui.alert.show({message:ips.getString('errorLoadingContent'),});setLoading(false);contentLoaded=false;hide();}
deferred.reject();}).always(function(){});return deferred.promise();},_buildDialog=function(){if(dialogBuilt){return;}
var offset=0;$('body').append(ips.templates.render('core.dialog.main',{'class':options.className,title:options.title||'',id:dialogID,fixed:options.fixed,size:options.size,close:options.close,extraClass:options.extraClass}));dialog=$('#'+dialogID);dialog.css({zIndex:ips.ui.zIndex(),});_positionDialog();dialog.on('click','[data-action="dialogClose"]',function(e){$(dialog).trigger('closeDialog',{dialogID:dialogID,originalEvent:e});});$(dialog).on('closeDialog',function(e,data){hide();});if(options.close){dialog.on('mouseup',function(e){if(e.target==dialog.get(0)){modalEvent.up=true;}});dialog.on('mousedown',function(e){if(e.target==dialog.get(0)){modalEvent.down=true;}});dialog.on('click',function(e){if((!modalEvent.up||(dialog.get(0)==e.target&&modalEvent.down))&&dialog.find('> div').get(0)!=e.target&&!$.contains(dialog.find('> div').get(0),e.target)&&$.contains(document,e.target)){$(dialog).trigger('closeDialog',{dialogID:dialogID,originalEvent:e});}
modalEvent={up:false,down:false};});}
dialog.get(0)?.addEventListener('submit',async(e)=>{let target=e.target;while(target instanceof HTMLElement&&target!==dialog.get(0)){if(target instanceof HTMLFormElement&&target.matches('form[data-form-is-download]')){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();const formData=new FormData(target);try{await ips.utils.fileDownload.download({url:target.action,formData,blobName:target.dataset.formDownloadName||dialog.find('.ipsDialog_title').text()||'blob'});await hide();_fetchDataLayerEventsAfterSubmit();}catch(e){try{Debug.log(e);if(e&&e.xhr instanceof XMLHttpRequest){let content;if(e.xhr.responseType==='arraybuffer'){content=await(new Blob([e.xhr.response])).text()}else if(e.xhr.responseType==='document'){content=e.xhr.responseXML;}else if(e.xhr.responseType==='text'){content=e.xhr.responseText;}
if(content&&e.xhr.getResponseHeader('content-type').match(/^text\/html/)){updateContent(content);return;}else if(e.xhr.getResponseHeader('content-type').match(/^(?:text|application)\/json/)){if(content){content=JSON.parse(content)}else if(e.xhr.responseType==='json'){content=e.xhr.response;}
if(typeof content==='object'&&content.message){ips.ui.alert.show({message:content.message,callbacks:{ok(){hide()}}})
return;}}
throw e;}}catch(e){ips.ui.alert.show({message:ips.getString('unexpected_error'),callbacks:{ok(){hide()}}})
Debug.error(e)}}
break;}
target=target.parentElement;}},{capture:true});if(options.remoteVerify||options.remoteSubmit){dialog.find('.'+options.className+'_content').on('submit',function(e){_ajaxFormSubmit(e,$(this));});}
dialogBuilt=true;},_fetchDataLayerEventsAfterSubmit=function(){if(ips.getSetting('memberID')){let redirected=false;const listener=()=>{redirected=true;};window.addEventListener('popstate',listener,{once:true});setTimeout(()=>{window.removeEventListener('popstate',listener);if(!redirected){document.body.dispatchEvent(new CustomEvent('ipsDataLayerSync',{bubbles:true}));}},1000);}},_positionDialog=function(){if(dialog&&!options.fixed){var win=$(window);var offset=win.scrollTop();dialog.css({top:offset+'px'});}},_buildModal=function(){modal=ips.ui.getModal();modal.css({zIndex:ips.ui.zIndex()});},_ajaxFormSubmit=function(e,form){if(!($(form)?.get?.(0)instanceof HTMLFormElement)){form=$(e.target)}
if(!($(form).get(0)instanceof HTMLFormElement)){return;}
if(form.attr('data-bypassValidation')&&!options.remoteSubmit){return;}
e.preventDefault();setLoading(true);var url=form.attr('action');var ajaxUrl=url;if(options.remoteVerify){var joinWith='?';if(ajaxUrl.indexOf('?')!=-1){joinWith='&';}
ajaxUrl=ajaxUrl+joinWith+'ajaxValidate=1';}
ips.getAjax()(ajaxUrl,{data:form.serialize(),type:'post'}).done(function(response,status,jqXHR){if(options.remoteVerify&&!form.attr('data-bypassValidation')){if(jqXHR.getAllResponseHeaders().indexOf('X-IPS-FormError: true')!==-1||jqXHR.getAllResponseHeaders().indexOf('X-IPS-FormNoSubmit: true')!==-1||jqXHR.getAllResponseHeaders().indexOf('x-ips-formerror: true')!==-1||jqXHR.getAllResponseHeaders().indexOf('x-ips-formnosubmit: true')!==-1){Debug.log('Validation failed');setLoading(false);updateContent(response);return;}}
if(options.remoteSubmit){var doneAfterSubmit=function(submitResponse){$(elem||document).trigger('submitDialog',{elemID:elemID,dialogID:dialogID,dialog:dialog,contentLoaded:contentLoaded,response:submitResponse});$(elem||document).get(0)?.dispatchEvent(new DialogSubmissionEvent(elemID,dialogID,dialog,contentLoaded,submitResponse))
setLoading(false);contentLoaded=false;hide();_fetchDataLayerEventsAfterSubmit();if(options.flashMessage){ips.ui.flashMsg.show(options.flashMessage,{timeout:options.flashMessageTimeout,escape:options.flashMessageEscape});}};if(options.remoteVerify){ips.getAjax()(url,{data:form.serialize(),type:'post',bypassRedirect:true}).done(function(response,status,jqXHR){if(jqXHR.getAllResponseHeaders().indexOf('X-IPS-FormError: true')!==-1||jqXHR.getAllResponseHeaders().indexOf('X-IPS-FormNoSubmit: true')!==-1||jqXHR.getAllResponseHeaders().indexOf('x-ips-formerror: true')!==-1||jqXHR.getAllResponseHeaders().indexOf('x-ips-formnosubmit: true')!==-1){form.attr('data-bypassValidation',true).submit();}else{doneAfterSubmit(response);}}).fail(function(jqXHR,status,errorThrown){form.attr('data-bypassValidation',true).submit();});}else{doneAfterSubmit(response);}}else if(jqXHR.getAllResponseHeaders().indexOf('X-IPS-FormNoSubmit: true')!==-1||jqXHR.getAllResponseHeaders().indexOf('x-ips-formnosubmit: true')!==-1){setLoading(false);updateContent(response);}else{form.attr('data-bypassValidation',true).submit();setTimeout(()=>_fetchDataLayerEventsAfterSubmit(),30000);}}).fail(function(){form.attr('data-bypassValidation',true).submit();});};init();return{init:init,show:show,hide:hide,remove:remove,setLoading:setLoading,updateContent:updateContent,dialogID:dialogID,destruct:destruct,addContentProcessor};};class DialogSubmissionEvent extends Event{constructor(elemID,dialogID,dialog,contentLoaded,response){super('dialogSubmission')
this.elemID=elemID;this.dialogID=dialogID;this.dialog=dialog;this.contentLoaded=contentLoaded;this.response=response;}}}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.drawer',function(){var defaults={};var respond=function(elem,options,e){e.preventDefault();if(!$(elem).data('_drawer')){$(elem).data('_drawer',drawerObj(elem,_.defaults(options,defaults)));}
$(elem).data('_drawer').show();};ips.ui.registerWidget('drawer',ips.ui.drawer,['drawerElem'],{lazyLoad:true,lazyEvents:'click'});return{respond:respond};});var drawerObj=function(elem,options){var modal,drawerElem,drawerContent;var init=function(){modal=ips.ui.getModal().addClass('ipsDrawer_modal');drawerElem=$(options.drawerElem),drawerContent=drawerElem.find('.ipsDrawer_menu');drawerElem.on('click','[data-action="close"]',function(e){e.preventDefault();hide();});drawerElem.on('click',function(e){if(!$.contains(drawerContent.get(0),e.target)){hide();}});drawerElem.on('click','.ipsDrawer_itemParent > h4',_showSubMenu).on('click','[data-action="back"]',_subMenuBack).find('.ipsDrawer_itemParent > ul').addClass('ipsDrawer_subMenu').hide();},_showSubMenu=function(e){e.preventDefault();var item=$(e.currentTarget);item.parents('.ipsDrawer_list').animate(($('html').attr('dir')==='rtl')?{marginRight:'-100%'}:{marginLeft:'-100%'}).end().siblings('.ipsDrawer_list').show();drawerElem.find('.ipsDrawer_content').animate({scrollTop:"0px"});},_subMenuBack=function(e){e.preventDefault();var item=$(e.currentTarget),thisMenu=item.parent('.ipsDrawer_list');thisMenu.parents('.ipsDrawer_list').first().animate(($('html').attr('dir')==='rtl')?{marginRight:'0'}:{marginLeft:'0'},function(){thisMenu.hide();});},show=function(){window.scrollTo(0,-1);modal.css({zIndex:ips.ui.zIndex()});drawerElem.find('.ipsDrawer_close').hide();ips.utils.anim.go('fadeIn fast',modal);drawerElem.css({zIndex:ips.ui.zIndex()}).show();if($('html').attr('dir')==='rtl'){ips.utils.anim.go('slideRight fast',drawerElem);}else{ips.utils.anim.go('slideLeft fast',drawerElem);}
drawerElem.find('.ipsDrawer_close').delay(500).fadeIn();$('body')[0].style.setProperty("overflow","hidden");},hide=function(){ips.utils.anim.go('fadeOut fast',modal);drawerElem.hide();$('body')[0].style.setProperty("overflow","");};init();return{init:init,show:show,hide:hide};};}(jQuery,_));;
;(function($,_,undefined){"use strict";let state='unloaded'
let pluginsState='unloaded'
const pluginsCallbacks=new Set()
const resolveCallbacks=new Set()
const _thirdPartyExtensions={};const _thirdPartyNodes={};const _thirdPartyMarks={};const pluginTimeouts=new Set();document.addEventListener('ips:editorPluginsReady',()=>{pluginsState='loaded'
pluginsCallbacks.forEach(cb=>cb())
pluginsCallbacks.clear()
pluginTimeouts.forEach(clearTimeout)
pluginTimeouts.clear()});document.addEventListener('ips:editorPluginsError',()=>{pluginsState='error'
pluginsCallbacks.forEach(cb=>cb())
pluginsCallbacks.clear()
pluginTimeouts.forEach(clearTimeout)
pluginTimeouts.clear()});document.addEventListener('ipsTiptapLoaded',()=>{resolveCallbacks.forEach(cb=>cb())
resolveCallbacks.clear()})
function loadTiptapPlugins(){pluginsState='loading'
const pluginURL=ips.getSetting('baseURL').replace(/\/+$/,'')+'/applications/core/interface/editor/index.php'
const script=document.createElement('script');script.setAttribute("src",pluginURL)
document.body.appendChild(script)
script.dataset.ipsEditorPlugins=''
pluginTimeouts.add(setTimeout(()=>document.dispatchEvent(new CustomEvent('ips:editorPluginsError')),5000))}
function loadTiptap(){state="loading";Debug.log("Loading the editor from the interface");const manifestURL=ips.getSetting('baseURL').replace(/\/+$/,'')+'/applications/core/interface/static/tiptap/manifest.json?antiCache='+encodeURIComponent(ips.getSetting('jsAntiCache'))
ips.fetch(manifestURL).then(response=>{if(typeof response==='object'){for(const details of Object.values(response)){if(details.isEntry){const src=ips.getSetting('baseURL').replace(/\/+$/,'')+'/applications/core/interface/static/tiptap/'+details.file+`?antiCache=${encodeURIComponent(ips.getSetting('jsAntiCache'))}`
const scriptElem=document.createElement('script')
scriptElem.type='module'
document.head.appendChild(scriptElem)
scriptElem.src=src
if(Array.isArray(details.css)){for(const css of details.css){const src=ips.getSetting('baseURL').replace(/\/+$/,'')+'/applications/core/interface/static/tiptap/'+css
const styleElem=document.createElement('link')
styleElem.rel='stylesheet'
styleElem.setAttribute('href',src)
document.head.appendChild(styleElem)}}}}}})}
function whenLoaded(skipPlugins=true){return new Promise((resolve)=>{if(pluginsState==='unloaded'&&!skipPlugins){loadTiptapPlugins()}
const done=()=>{if(skipPlugins||['loaded','error'].includes(pluginsState)){resolve()}else{pluginsCallbacks.add(resolve)}}
if(state==='loaded'||ips.utils.tiptap){state='loaded'
done()}else{resolveCallbacks.add(done)}
if(state==='unloaded'){loadTiptap()}})}
const defaults={postkey:'',minimized:false,autoSaveKey:null,hidebuttons:[],autosubmit:true,giphyenabled:false,stockrepliesenabled:false,minimizeAfterReset:false,name:undefined,restrictions:[],restrictionLevel:0,commenteditor:false,};ips.createModule('ips.ui.editorv5',function(){ips.ui.registerWidget('editorv5',ips.ui.editorv5,['postkey','minimized','autoSaveKey','giphyenabled','stockrepliesenabled','hidebuttons','name','loadplugins','restrictions',"restrictionLevel",'commenteditor']);return{respond(elem,options){if($(elem).data('_editor')!==undefined){return;}
$(elem).data('_editor',null)
if(!('loadplugins'in options)){pluginsState='loaded';document.dispatchEvent(new CustomEvent('ips:editorPluginsReady'))}
delete options.loadplugins;const instance=editorObj(elem,options)
$(elem).data('_editor',instance)
instance.init()},getObj(elem){if($(elem).data('_editor')){return $(elem).data('_editor');}
return undefined;},getObjWithInit(elem,callback){let obj=this.getObj(elem);if(obj){if(callback){callback(obj);}else{return new Promise(resolve=>resolve(obj));}}else{let initFunction=$(elem).data('_editorInit');if(initFunction){if(callback){initFunction(callback);}else{return new Promise(resolve=>initFunction(resolve))}}}
if(!callback){return new Promise(resolve=>resolve(undefined))}},destruct(elem){this.getObj(elem)?.destruct();$(elem).data('_editor',undefined)},whenLoaded,registerExtension(name,definition){definition.name=`ipsCustomExtension__${name}`;if(name in _thirdPartyExtensions){Debug.log(`Replacing tiptap third party extension: ${name}`);}
_thirdPartyExtensions[name]=definition;},registerNode(name,definition){definition.name=`ipsCustomNode__${name}`;if(name in _thirdPartyNodes){Debug.log(`Replacing tiptap third party node: ${name}`);}
_thirdPartyNodes[name]=definition;},registerMark(name,definition){definition.name=`ipsCustomMark__${name}`;if(name in _thirdPartyMarks){Debug.log(`Replacing tiptap third party mark: ${name}`);}
_thirdPartyMarks[name]=definition;},async getExtensionRestrictions(includeDefaults=false){await whenLoaded(false);const restrictions={};for(const collection of[_thirdPartyMarks,_thirdPartyExtensions,_thirdPartyNodes]){for(const name in collection){const definition={...collection[name]};if(Array.isArray(definition.restrictions)){const restrictions={};for(const restriction of definition.restrictions){restrictions[restriction]=-1;}
definition.restrictions=restrictions;}
if(typeof definition.restrictions!=='object'||!Object.keys(definition.restrictions).length){continue;}
const[_,type]=definition.name.match(/^ipsCustom(Node|Mark|Extension)__/);if(!type){continue;}
for(const[restriction,defaultValue]of Object.entries(definition.restrictions)){if(![-1,0,1,2].includes(defaultValue)){Debug.warn(`The restriction ${JSON.stringify(restriction)} from the extension ${definition.name} has an invalid default value (got ${defaultValue}, expected one of -1,0,1,2), so the restriction is being skipped!`);continue;}
const langString=definition.name+'__'+restriction;if(!langString?.match(/^[a-zA-Z_\-0-9]+$/)){Debug.warn(`Skipping the restriction "${restriction}" because it doesn't match the pattern "/^[a-zA-Z0-9_\\-]+$/. (It consists of one or more characters that are not alphanumeric, an underscore, or a dash)"`);continue;}
if(!ips.haveString(langString)){Debug.warn(`The restriction "${restriction}" of the ${type} "${name}" doesn't have a lang string registered (expected a lang string registered as ${langString})!`);ips.setString(langString,langString);}
restrictions[langString]=defaultValue;}}}
return Array.from(includeDefaults?Object.entries(restrictions):Object.keys(restrictions));},buildConfig(options){let config={}
for(const k in defaults){config[k]=options[k]!==undefined?options[k]:defaults[k];}
config.giphyenabled=!!(config.giphyenabled||config.giphyenabled==='');config.stockrepliesenabled=!!(config.stockrepliesenabled||config.stockrepliesenabled==="");config.commenteditor=!!(config.commenteditor||config.commenteditor==="");if(typeof config.hidebuttons==='string'){config.hidebuttons=config.hidebuttons.split(',').map(key=>key.trim()).filter(key=>!!key);}
if(typeof options.restrictions==='string'){config.restrictions=options.restrictions.split(',')}else{config.restrictions=[];}
return config}};});function editorObj(elem,options){let instance=null;let hiddenAtStart=false;let minimized=!!options.minimized;let editorLocation;let originalContent='';let name=options.name||'';let _reactRoot;const config=ips.ui.editorv5.buildConfig(options)
options={...options,...config}
async function fillTiptapInstance(){if(!instance){await whenLoaded(false);const throttledComposeEvent=_.throttle(()=>{try{$(elem).trigger('editor.composing',{elem})}catch(e){Debug.error(e)}},1000)
const textArea=getTextarea();editorLocation=editorLocation||$(elem).get(0).querySelector('[data-role="reactRoot"]')||document.createElement('div')
editorLocation.dataset.role='reactRoot'
editorLocation.classList.add('ipsEditor__react-root')
textArea.parentElement.insertBefore(editorLocation,textArea)
originalContent=textArea.textContent
try{const detail={elem:$(elem).get(0),textArea,content:textArea.textContent,options:config};document.dispatchEvent(new CustomEvent("ips:editorBeforeInit",{bubbles:true,cancelable:false,detail}));textArea.textContent=detail.content;}catch(e){e.message="An event listener on `ips:editorBeforeInit` failed to run\n\n"+e.message
Debug.warn(e)}
if(Array.isArray(config.restrictions)){const allRestrictions=new Set(await ips.ui.editorv5.getExtensionRestrictions());config.restrictions=config.restrictions.filter(restriction=>allRestrictions.has(restriction)||!restriction.match(/^ipsCustom(Node|Mark|Extension)__/))}else{config.restrictions=[];}
const currentOnCreate=config.onCreate;const self=this;config.onCreate=function(...args){instance=instance||args[0]?.editor;if(currentOnCreate instanceof Function){(self===this?currentOnCreate:currentOnCreate.bind(this))(...args);}
setTimeout(()=>fillTextarea())
setTimeout(()=>{try{$(elem).get(0).dispatchEvent(new CustomEvent("ips:editorAfterInit",{bubbles:true,cancelable:false,detail:{elem:$(elem).get(0),textArea,content:textArea.innerText,options:config,instance}}));}catch(e){e.meessage="Something went wrong dispatching ips:editorAfterInit event on the page:\n"+e.message;Debug.error(e);}
fillTextarea();},100)}
const onTransaction=config.onTransaction;config.onTransaction=_.debounce(function(...args){instance=instance||args[0]?.editor;fillTextarea();try{onTransaction?.call?.(this,...args);}catch(e){e.message="Something went wrong in an onTransaction call to the editor"+e.message;Debug.error(e);}},200,{leading:false,trailing:true});const onUpdate=config.onUpdate;config.onUpdate=function(...args){try{onUpdate?.call?.(this,...args);}catch(e){e.message="Failed to run the onUpdate event listener:\n"+e.message;Debug.error(e);}
instance=instance||args[0]?.editor;config.onTransaction?.cancel();setTimeout(()=>{let canceled=false;const event=new CustomEvent('ips:editorUpdated',{bubbles:true,cancelable:true,detail:{elem:$(elem).get(0),textArea,instance,}});throttledComposeEvent();const origStopProp=event.stopPropagation;const origStopImmProp=event.stopImmediatePropagation;event.stopPropagation=(function(){canceled=true;origStopProp();}).bind(event)
event.stopImmediatePropagation=(function(){canceled=true;origStopImmProp();}).bind(event);$(elem).get(0).dispatchEvent(event)
if(canceled){return;}
fillTextarea()})}
const customizedRestrictions={...(ips.getSetting('editor_restrictions')||{})};const filterAndPrepPlugins=extensions=>[...Object.values(extensions)].filter(extension=>!config.restrictions.includes(`${extension.name}__`)).filter(extension=>{if(typeof extension.restrictions!=='object'){extension.restrictions={};}else if(Array.isArray(extension.restrictions)){extension.restrictions=Object.fromEntries(extension.restrictions.map(r=>[r,-1]))}
for(const customizedRestriction in customizedRestrictions){if(customizedRestriction.startsWith(extension.name+"__")){extension.restrictions[customizedRestriction.replace(new RegExp(`^${extension.name}__`),'')]=customizedRestrictions[customizedRestriction];delete customizedRestrictions[customizedRestriction];}}
for(const restriction in extension.restrictions){if(typeof extension.restrictions[restriction]==='number'&&extension.restrictions[restriction]>=(config.restrictionLevel||0)&&!config.restrictions.includes(`${extension.name}__${restriction}`)){config.restrictions.push(`${extension.name}__${restriction}`)}}
return typeof extension.restrictions[""]!=="number"||extension.restrictions[""]<(config.restrictionLevel||0);}).map(extensionDef=>({...extensionDef}));const res=await ips.utils.tiptap.editorInstance(editorLocation,{...config,content:textArea.innerText,jQuery:$,ipsPlugins:{extensions:filterAndPrepPlugins(_thirdPartyExtensions),nodes:filterAndPrepPlugins(_thirdPartyNodes),marks:filterAndPrepPlugins(_thirdPartyMarks),},});instance=res[0]
_reactRoot=res[1]
throttledComposeEvent();instance.on('create',()=>{fillTextarea();})
instance.on('selectionUpdate',()=>{throttledComposeEvent()})
const time=config.autoSaveKey?ips.utils.db.get('editorSave',config.autoSaveKey)?.time:false;if(Number.isInteger(time)&&time>(Date.now()/1000-86400*3)){fillTextarea()}
instance.on('focus',()=>$(elem).trigger('editor.focused',{elem}));instance.on('blur',()=>$(elem).trigger('editor.blurred',{elem}));if(Debug.isEnabled()){instance.on('contentError',(...args)=>{const err=new Error("Failed to insert content using current editor schema");console.warn(err);console.log(args);})}}}
function getTextarea(){return $(elem).find('textarea:not(.tiptap *)').get(0);}
function getInstanceHTML(){if(!instance)return"";const html=instance.getHTML?.();if(typeof html!=='string'||html==='<p></p>'){return"";}
const parserDoc=(new DOMParser()).parseFromString(`<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>${html}</body></html>`,'text/html');let boxContentElement;while((boxContentElement=parserDoc.querySelector('i-richtext-box-content'))&&boxContentElement instanceof Element){boxContentElement.before(...boxContentElement.childNodes);boxContentElement.remove();}
return parserDoc.body.innerHTML.trim();}
const fillTextarea=_.debounce(function(){const textarea=getTextarea();if(textarea&&instance){textarea.innerHTML="";textarea.appendChild(document.createTextNode(getInstanceHTML()))}},10);function clearTextarea(){const textarea=getTextarea();if(textarea){textarea.innerHTML='';textarea.append(document.createTextNode(originalContent))}}
async function init(callback){if(options.minimized){$(elem).find('.ipsComposeArea_dummy').show().on('focus click',function(){$(this).off('focus click');unminimize(function(){focus();});}).end().find('[data-role="mainEditorArea"]').hide().closest('.ipsComposeArea').addClass('ipsComposeArea_minimized').find('[data-ipsEditor-toolList]').attr('hidden',true);$(document).on('initializeEditor',_initializeEditor);hiddenAtStart=true;minimized=true;setTimeout(()=>whenLoaded(false),3000);}else{const mainEditorArea=$(elem).get(0).querySelector('[data-role="mainEditorArea"]')
mainEditorArea?.classList.add('ipsLoading');await fillTiptapInstance();mainEditorArea?.classList.remove('ipsLoading');instance.commands.fireVisibilityChange(true)}
if(callback instanceof Function){callback(this);}
$(document).on('fileDeleted',_deleteFile);_cleanUpStaleAutoSaves();}
function _cleanUpStaleAutoSaves(){for(let[k,v]of Object.entries(ips.utils.db.getByType('editorSave'))){try{let time=v?.time||v?.[1]
if(!time){continue;}
if(time<Math.round(new Date().getTime()/1000)-(86400*3)){ips.utils.db.remove('editorSave',k);}}catch(err){Debug.error("Trying to remove editorSave keys:");Debug.error(err);}}}
let destroyed=false;function destruct(clearAutoSave=false){if(destroyed){return;}
destroyed=true;try{_reactRoot?.unmount()}catch(e){const r=_reactRoot;setTimeout(()=>r.unmount(),100);}
if(clearAutoSave){instance?.commands?.clearAutosave?.();}
instance?.destroy()
clearTextarea()
_reactRoot=undefined;_offEvents();instance=undefined;editorLocation?.remove();editorLocation=null;}
function getInstance(){if(instance){return instance;}
return null;}
function _offEvents(){$(document).off('fileDeleted',_deleteFile);$(document).off('initializeEditor',_initializeEditor);}
function focus(){scrollIntoView();instance.commands.focus();}
function scrollIntoView(options){const element=$(elem).get(0);const container=element.closest('#replyForm,.cTopicPostArea')||element.closest('.ipsComposeArea')||element;const rect=container.getBoundingClientRect();if(rect.top<0||rect.left<0||rect.right>window.innerWidth||rect.bottom>window.innerHeight||rect.left>window.innerWidth){const defaults={behavior:'instant',block:rect.top<0?'start':'end',inline:rect.left<0?"start":"end"};if(options===true){Object.assign(defaults,{behavior:'auto',block:"start",inline:"nearest"});}else if(options===false){Object.assign(defaults,{behavior:'auto',block:"end",inline:"nearest"});}else if(typeof options==='object'){Object.assign(defaults,options);}
container.scrollIntoView(defaults);}}
function unminimize(callback){if(!_.isFunction(callback)){callback=$.noop;}
if(minimized){function _unminimize(){const element=$(elem).get(0)
element.querySelector('.ipsComposeArea_dummy')?.setAttribute('hidden','')
element.closest('.ipsComposeArea')?.classList.remove('ipsComposeArea_minimized')
element.closest('.ipsComposeArea')?.querySelectorAll('[data-ipseditor-toollist]').forEach(toolList=>toolList.ipsShow())
const mainEditorArea=$(elem).get(0).querySelector('[data-role="mainEditorArea"]')
mainEditorArea?.ipsShow()
mainEditorArea?.classList.add('ipsLoading')
fillTiptapInstance().then(()=>{mainEditorArea?.classList.remove('ipsLoading')
instance?.commands.fireVisibilityChange(true)
if(hiddenAtStart){setTimeout(()=>focus(),1);hiddenAtStart=false;}
callback();})
minimized=false;const minimizedUploader=element.querySelector('[data-ipsEditor-toolListMinimized]');if(minimizedUploader){minimizedUploader.ipsShow();ips.fetch(element.closest('form[action]').getAttribute('action'),{'data':{'getUploader':minimizedUploader.dataset.name}}).then(response=>{const responseElement=(new DOMParser()).parseFromString(`${response}`,'text/html').body
for(const el of responseElement.childNodes){minimizedUploader.parentElement.insertBefore(el,minimizedUploader)}
minimizedUploader.remove();$(document).trigger('contentChange',[elem]);}).catch(e=>{e.message=`Failed to unminimize uploader. \n${e.message}`
Debug.error(e)})}}
_unminimize();}else{callback();}}
function minimize(){if(!minimized){const element=$(elem).get(0)
element.querySelectorAll('.ipsComposeArea_dummy').ipsShow();element.querySelectorAll('[data-role="mainEditorArea"]').ipsHide();element.closest('.ipsComposeArea')?.classList.add('ipsComposeArea_minimized')
element.closest('.ipsComposeArea')?.querySelectorAll('[data-ipseditor-toollist]').ipsHide()
$(elem).find('.ipsComposeArea_dummy').on('focus click',function(){$(this).off('focus click');unminimize(function(){focus();});})
instance?.commands.fireVisibilityChange(false)
minimized=true;}}
function insertQuotes(quotes){let isAutoSave=false,draftContent='',_minimized=minimized;const _doInsert=function(){if(!instance)return;let toInsert="";for(const data of quotes){const html=data.quoteHtml.replace(/data-ipsLightbox(-group)?="([\w]+)?"/ig,'').trim();const quote=$(ips.templates.render('core.editor.quote',{citeurl:data.citeurl||'',citation:ips.utils.getCitation(data),contents:html}));for(let attr of['timestamp','userid','username','contentapp','contenttype','contentclass','contentid','contentcommentid']){if(data[attr]){quote.attr('data-ipsQuote-'+attr,data[attr]);}}
toInsert+=quote.get(0).outerHTML}
if(!toInsert){return;}
if(isAutoSave&&draftContent){instance.chain().setContent(draftContent,false).focus().run();setTimeout(()=>{let pos
instance.chain().command(({tr})=>pos=tr.doc.resolve(0).end()).insertContentAt(pos,toInsert+"<p></p>",{parseOptions:{preserveWhitespace:false}}).setMeta('preventUpdate',true).showMessage('autosave').focus().command(({chain,tr})=>chain().setTextSelection(tr.doc.resolve(0).end()-1)).run();},10);return;}else if(_minimized){let to,from;instance.chain().command(({tr})=>{to=tr.doc.resolve(0).end();from=to;if(tr.doc.lastChild?.inlineContent&&![...tr.doc.lastChild.children].some(desc=>desc.nodeSize)){from=tr.doc.resolve(0).posAtIndex(tr.doc.childCount-1);}
return true;}).insertContentAt(to,"<p></p>").setTextSelection(to+1).focus().run();instance.chain().insertContentAt({from,to},toInsert,{parseOptions:{preserveWhitespace:false},updateSelection:false}).focus().run();return;}
instance.chain().insertContent(toInsert+(instance.state.selection.empty&&instance.state.selection.$from.nodeAfter?"":"<p></p>"),{parseOptions:{preserveWhitespace:false}}).focus().run();};if(minimized){const draft=options.autoSaveKey&&ips.utils.db.get('editorSave',options.autoSaveKey);if(typeof draft?.content==='string'&&draft.time&&(Date.now()/1000-86400*3)<parseInt(draft.time)&&!instance){draftContent=draft.content;isAutoSave=true;}
unminimize(function(){_doInsert();});}else{_doInsert();}}
function insertHtml(html){instance.chain().insertContent(html,{parseOptions:{preserveWhitespace:false}}).focus().run();}
function reset(){instance.chain().setContent(originalContent||'<p></p>',{emitUpdate:true}).clearAutosave().run();$(elem).find('[data-ipsUploader]').trigger('resetUploader');if(options.minimized&&options.minimizeAfterReset){minimize();}
clearTextarea();}
function saveAndClearAutosave(){if(instance){instance?.commands.clearAutoSave?.()}else{ips.utils.db.remove('editorSave',options.autoSaveKey);}}
function _belongsToThisEditor(data){return data.editorID!==undefined&&data.editorID===name;}
function _initializeEditor(e,data){if(!_belongsToThisEditor(data)){return;}
unminimize(function(){focus();});}
function _deleteFile(e,data){if(options.postkey&&options.postkey!==data.postkey){return;}
if(!instance){Debug.warn(new Error(`An attachment was deleted for an editor that has not been initialized. This will cause the editor's content to retain the attachment if it is unminimized or initialized`));return;}
const fileId=parseInt(data?.fileElem?.attr?.('data-fileid'));if(!fileId||Number.isNaN(fileId)){Debug.log(`Could not delete a file in the editor because no file id was passed`);return;}
try{instance.chain().removeAttachment(fileId).focus().run();}catch(e){Debug.warn(e);}}
return{init,focus,unminimize,minimize,insertQuotes,insertHtml,reset,destruct,saveAndClearAutosave,getInstance,getInstanceHTML,scrollIntoView};}}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.filterBar',function(){var defaults={on:'phone,tablet',viewDefault:'filterContent'};var respond=function(elem,options){if(!$(elem).data('_filterBar')){$(elem).data('_filterBar',filterBarObj(elem,_.defaults(options,defaults)));}},getObj=function(elem){if($(elem).data('_filterBar')){return $(elem).data('_filterBar');}
return undefined;},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}};ips.ui.registerWidget('filterBar',ips.ui.filterBar,['on','viewDefault']);return{respond:respond,destruct:destruct,getObj:getObj};});var filterBarObj=function(elem,options){var filterBar=null;var filterContent=null;var currentlyShowing=null;var init=function(){filterBar=elem.find('[data-role="filterBar"]');filterContent=elem.find('[data-role="filterContent"]');elem.on('switchTo.filterBar',function(e,data){_switchView(data.switchTo);}).on('click','[data-action="filterBarSwitch"]',_switchToggle);_setUpBar();},destruct=function(){},_setUpBar=function(){if(options.viewDefault=='filterBar'){currentlyShowing='filterBar';}else{currentlyShowing='filterContent';}},_switchToggle=function(e){_switchView($(e.currentTarget).attr('data-switchTo')=='filterBar'?'filterBar':'filterContent');},_switchView=function(switchTo){if(switchTo==currentlyShowing){return;}
if(document.startViewTransition){document.startViewTransition(()=>{elem.attr('data-ipsfilterbar-viewing',switchTo);});}else{elem.attr('data-ipsfilterbar-viewing',switchTo);}
currentlyShowing=switchTo;};init();return{init:init,destruct:destruct};};}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.flashMsg',function(){var _queue=[],_doneInit=false,_box,_content,_isShowing=false,_currentDismissHandler=null;var defaults={timeout:2,extraClasses:'',location:'top',sticky:false,escape:true};var respond=function(elem,options){if(options.text){show(options.text,options);}},init=function(){$(document).ready(function(){if($('body').attr('data-message')){show($('body').attr('data-message'));}
if(ips.utils.url.getParam('flmsg')){show(_.escape(decodeURIComponent(ips.utils.url.getParam('flmsg'))));}
if(ips.utils.cookie.get('flmsg')){show(_.escape(ips.utils.cookie.get('flmsg')));ips.utils.cookie.unset('flmsg');}});$(document).on('closeFlashMsg.flashMsg',hide);},show=function(message,options,update){if(!_doneInit){_initElement();}
options=_.defaults(options||{},defaults);if(options.escape){message=_.escape(message);}
if(_isShowing&&!update){_queue.push([message,options]);return;}
if(update&&_isShowing){_content.html(message);ips.utils.anim.go('pulseOnce',_box);if(!options.sticky){setTimeout(hide,options.timeout*1000);}
return;}
_currentDismissHandler=null;_isShowing=true;_content.html(message);_box.attr('class','').addClass(options.extraClasses).addClass(options.dismissable?'ipsFlashMsg_dismissable':'').addClass(options.position=='bottom'?'ipsFlashMsg--bottom':'ipsFlashMsg--top').on('click','a:not( [data-action="dismissFlashMessage"] )',function(){hide();}).animationComplete(function(){if(!options.sticky){setTimeout(hide,options.timeout*1000);}});if(_.isFunction(options.dismissable)){_currentDismissHandler=options.dismissable;}
ips.utils.anim.go('fadeInDown',_box);},hide=function(){if(_queue.length){var next=_queue.shift();show(next[0],next[1],true);}else{_box.animationComplete(function(){_isShowing=false;_box.hide();if(_queue.length){var next=_queue.shift();show(next[0],next[1]);}});ips.utils.anim.go('fadeOutDown',_box);}},dismiss=function(e){e.preventDefault();hide();if(_.isFunction(_currentDismissHandler)){_currentDismissHandler();_currentDismissHandler=null;}},_initElement=function(){$('body').append(ips.templates.render("core.general.flashMsg"));_box=$('#elFlashMessage').hide();_content=(_box.is('[data-role="flashMessage"]'))?_box:_box.find('[data-role="flashMessage"]');_box.on('click','a[data-action="dismissFlashMessage"]',dismiss);_doneInit=true;};ips.ui.registerWidget('flashMsg',ips.ui.flashMsg,['text','extraClasses','timeout','position','sticky','dismissable']);init();return{respond,show};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.ui.form',function(){const _cmInstances={};const _support={};const formTypes={'unlimited':'[data-control~="unlimited"]','date':'input[type="date"], [data-control~="date"]','range':'input[type="range"], [data-control~="range"]','color':'input[type="color"], [data-control~="color"]','dimensions':'[data-control~="dimensions"]','dimensionsUnlimited':'[data-control~="dimensionsUnlimited"]','jsDisable':'input[data-control~="jsdisable"]','codemirror':'[data-control~="codemirror"]','granularCheckboxset':'[data-control~="granularCheckboxset"]',};const _controlMethods={codemirror(elem){ips.loader.getStatic(['applications/core/interface/static/codemirror/diff_match_patch.js','applications/core/interface/static/codemirror/codemirror.js']).then(function(){const elemId=$(elem).attr('id');if(!_.isUndefined(_cmInstances[elemId])){_cmInstances[elemId].save();$(_cmInstances[elemId].getWrapperElement()).remove();delete _cmInstances[elemId];}
_cmInstances[elemId]=CodeMirror.fromTextArea(document.getElementById(elemId),{mode:$(elem).attr('data-mode'),lineWrapping:true,lineNumbers:false,leaveSubmitMethodAlone:true});if($(elem).attr('data-height')){_cmInstances[elemId].setSize(null,$(elem).attr('data-height'));$('div[data-codemirrorid='+elemId+'] ul[data-role=tagsList]').css('max-height',$(elem).attr('data-height'));}
$('#'+elemId).data('CodeMirrorInstance',_cmInstances[elemId]);$('[data-codemirrorcustomtag]').on('click',function(e){_cmInstances[elemId].replaceRange($(e.currentTarget).attr('data-codemirrorcustomtag'),_cmInstances[elemId].getCursor("end"));});});},range(elem){if(_.isUndefined(_support['range'])){const i=document.createElement("input");i.setAttribute("type","range");_support['range']=!(i.type==='text');}
if(!_support['range']){elem.siblings('[data-role="rangeBoundary"]').hide();}else{const valueElem=$('#'+elem.attr('name')+'_rangeValue');valueElem.text(elem.val());elem.on('change',function(){valueElem.text(elem.val());});}},unlimited(elem){elem=$(elem).get(0);elem.addEventListener('change',()=>_unlimitedCheck());if(!elem.dataset.initialized){elem.dataset.initializd='1';_unlimitedCheck();}
function _unlimitedCheck(){const checkbox=elem;if(checkbox.disabled){return;}
checkbox.closest('.ipsFieldRow__content,[data-role="unlimitedCatch"]')?.querySelectorAll('input:not([type="checkbox"],[type="hidden"]),select,textarea').forEach(input=>{if(input.dataset.control!=='color'){if(checkbox.checked){if(input.value){input.dataset.previousvalue=input.value;}
input.value="";input.setAttribute('disabled','');}else{input.removeAttribute('disabled');if(input.dataset.previousvalue){input.value=input.dataset.previousvalue;}}}
input.querySelectorAll('[data-role="rangeBoundary"]').forEach(boundary=>boundary.style.opacity=checkbox.checked?'0.5':'1');});}},color(elem){if(elem.attr('data-ipsFormData')){return;}
const input=elem.get(0);input.setAttribute("data-ipsFormData","1");const initialColor=input.style.getPropertyValue('--i-co--inverse')||"var(--i-color_root)"
const unlimited=input.closest('.ipsFieldRow__content')?.querySelector(`input[data-control=unlimited]`);const wrap=input.closest('.ipsInput__color-wrap-inner');const iroWrap=wrap.querySelector('[data-role="iro-container"]');const label=input.closest('.ipsInput__color-wrap')?.querySelector('.ipsInput__color-label');let controller='label';let iro;ips.utils.color.loadIro().then(()=>{function buildIro(){iroWrap.innerHTML='';iro=new ips.utils.iro.ColorPicker(iroWrap,{color:input.value,layout:[{component:ips.utils.iro.ui.Box,options:{}},{component:ips.utils.iro.ui.Slider,options:{sliderType:'hue'}}]});iro.on('input:change',(e)=>{controller='picker';input.value=e.hexString;updateColor({target:input});});}
buildIro();wrap?.addEventListener('pointerdown',e=>{if(e.target.closest('[data-role="iro-container"]')){return;}
e.stopPropagation();if(unlimited){const sel=document.getSelection();const activeElement=document.activeElement;const wasFocused=controller==='label'&&((activeElement===label)||(activeElement.parentElement?.closest?.('.ipsInput__color-label')===label));const ranges=[];for(let i=0;i<sel.rangeCount;i++){ranges.push(sel.getRangeAt(i));}
let currentText=label.innerText;unlimited.checked=false;updateColor(e);if(label.innerText!==currentText){e.preventDefault();let sel=document.getSelection();if(!wasFocused||(e instanceof PointerEvent&&e.detail>=2)){sel.removeAllRanges();const range=document.createRange();range.selectNodeContents(label);if(!(e instanceof PointerEvent&&e.detail>2)&&label.innerText.startsWith('#')){const st=document.createTextNode('#');const textNode=document.createTextNode(label.innerText.slice(1));label.innerHTML="";label.appendChild(st);label.appendChild(textNode);range.selectNodeContents(textNode);}else{const text=document.createTextNode(label.innerText);label.innerHTML="";label.append(text);range.selectNodeContents(text);}
sel.addRange(range);}else if(wasFocused){sel.removeAllRanges();ranges.forEach(range=>{sel.addRange(range);})}}}
iroWrap.classList.add('ipsInput__color-iro-container--open');});label.addEventListener('input',e=>{controller='label';const text=label.innerText;try{input.value=(new ips.utils.iro.Color(text)).hexString;buildIro();updateColor({target:input},true);}catch(e){}});function handleDataTransfer(e){const dt=e instanceof ClipboardEvent?e.clipboardData:e.dataTransfer;if(dt instanceof DataTransfer){e.preventDefault();e.stopPropagation();const allTypes=[...dt.types];let textFound;if(allTypes.includes('text/plain')){Debug.log("Using plain text from paste or drop event");textFound=dt.getData('text/plain');}else if(allTypes.includes('text/html')){Debug.log("Using html from paste or drop event");const cleanText=(new DOMParser()).parseFromString(dt.getData('text/html'),'text/html').body.innerText;if(cleanText){textFound=cleanText;}}
if(textFound){textFound=textFound.replaceAll(/\s+/g,' ').trim().slice(0,30).trim();const selection=document.getSelection();const text=document.createTextNode(textFound);let usingExistingRange=false;for(let i=0;i<selection.rangeCount;i++){const existingRange=selection.getRangeAt(i);if(existingRange.intersectsNode(label)){const isDescendant=(descendant,ancestor)=>{while(descendant){if(descendant===ancestor){return true;}
descendant=descendant.parentNode;}
return false;}
if(!isDescendant(existingRange.startContainer,label)){existingRange.setStart(label,0);}
if(!isDescendant(existingRange.endContainer,label)){existingRange.setEnd(label,label.childNodes.length);}
usingExistingRange=true;existingRange.deleteContents();existingRange.insertNode(text);existingRange.collapse(false);break;}}
selection.removeAllRanges();const newRange=document.createRange();if(!usingExistingRange){label.innerHTML="";label.appendChild(text);}
newRange.setStartAfter(text);newRange.setEndAfter(text);selection.addRange(newRange);if(label.innerText.trim().length>30){let precedingTextLength=0;for(let node of label.childNodes){if(node===text){break;}
if(node instanceof Text){precedingTextLength+=node.wholeText.length;}else if(node instanceof Element){precedingTextLength+=node.innerText.length;}}
const replacementTextNode=document.createTextNode(label.innerText.trim().slice(0,30));label.innerHTML="";label.appendChild(replacementTextNode);if(precedingTextLength){const correctedRange=document.createRange();correctedRange.setStart(replacementTextNode,Math.min(30,precedingTextLength));correctedRange.setEnd(replacementTextNode,Math.min(30,precedingTextLength));selection.removeAllRanges();selection.addRange(correctedRange);}}
controller='label';try{input.value=(new ips.utils.iro.Color(label.innerText)).hexString;buildIro();updateColor({target:input},true);}catch(e){Debug.error(e);}
return;}
ips.ui.flashMsg.show(ips.getString('form_color_datatransfer_fail'));}}
label.addEventListener('drop',handleDataTransfer);label.addEventListener('paste',handleDataTransfer);document.addEventListener('pointerdown',e=>{if(e.target.closest('.ipsInput__color-wrap-inner')!==wrap&&iroWrap.classList.contains('ipsInput__color-iro-container--open')){iroWrap.classList.remove('ipsInput__color-iro-container--open');}});});const updateColor=(e,skipLabel=false)=>{if(unlimited&&e?.target===input){unlimited.checked=false;}
if(unlimited?.checked){wrap?.classList.add('ipsInput--color-disabled');if(label){label.innerHTML="";}
return;}
wrap?.classList.remove('ipsInput--color-disabled');let textColor;if(ips.utils.iro?.colorPackage){const color=new ips.utils.iro.colorPackage(input.value);if(color.to('oklab').toGamut().l<0.71){textColor="#fff";}else{textColor="#000";}}else{const[_,__,l]=input.value.match(/#[0-9a-f]{3,8}/i)?ips.utils.color.RGBtoHSL(...ips.utils.color.hexToRGB(input.value.match(/#([0-9a-f]{3,8})/i)[1])):[null,null,null];textColor=typeof l==="number"?(l<0.6?"#fff":"#000"):initialColor;}
input.closest('.ipsInput__color-wrap')?.style.setProperty("--i-co-inverse",textColor);input.closest('.ipsInput__color-wrap')?.style.setProperty("--i-co",`${input.value}`);if(!skipLabel&&label&&label.innerText!==input.value){label.innerHTML="";let textNodes=input.value.match(/^(#)?(.*)/i).slice(1).map(match=>document.createTextNode(match||''));textNodes.forEach(node=>label.append(node));const sel=document.getSelection();sel.removeAllRanges();const range=document.createRange();range.selectNodeContents(textNodes[textNodes.length-1]);sel.addRange(range);}
input.setAttribute('value',input.value);};input.addEventListener("input",updateColor);unlimited?.addEventListener('input',updateColor);updateColor();},dimensions(elem){const container=elem.closest('.ipsWidthHeight_container');elem.resizable({resize:function(event,ui){container.find('input.ipsWidthHeight_width').val(elem.width());container.find('input.ipsWidthHeight_height').val(elem.height());}});container.find('input.ipsWidthHeight_width').on('change',function(){elem.width($(this).val());});container.find('input.ipsWidthHeight_height').on('change',function(){elem.height($(this).val());});},dimensionsUnlimited(elem){$(elem).get(0).addEventListener('change',()=>_dimensionsUnlimitedCheck());_dimensionsUnlimitedCheck();function _dimensionsUnlimitedCheck(){elem=$(elem).get(0);const container=elem.closest('.ipsWidthHeight_container');if(elem.matches(':checked')){container.querySelectorAll('[data-control="dimensions"]').ipsHide();container.querySelectorAll('input.ipsWidthHeight_width, input.ipsWidthHeight_height').forEach(el=>{if(el.value!==''&&!Number.isNaN(parseFloat(el.value))){el.dataset.lastvalue=el.value;}
el.value='';el.setAttribute('disabled','');});}else{container.querySelectorAll('[data-control="dimensions"]').ipsShow();container.querySelectorAll('input.ipsWidthHeight_width, input.ipsWidthHeight_height').forEach(el=>{if(el.dataset.lastvalue!==undefined){el.value=el.dataset.lastvalue;}
el.removeAttribute('disabled');});}}},jsDisable(elem){elem.prop('disabled',true);},granularCheckboxset(elem){elem.find('[data-role="checkboxsetUnlimitedToggle"]').on('change',function(){if($(this).is(':checked')){elem.find('[data-role="checkboxsetGranular"] input:enabled[type="checkbox"]').prop('checked',$(this).is(':checked'));}else{elem.find('[data-role="checkboxsetGranular"] input[type="checkbox"]').prop('checked',$(this).is(':checked'));}});elem.find('[data-action="checkboxsetCustomize"]').on('click',function(){elem.find('[data-role="checkboxsetUnlimited"]').hide();elem.find('[data-role="checkboxsetUnlimitedToggle"]').prop('checked',false);if(elem.find('[data-role="checkboxsetUnlimitedToggle"]').length>0){elem.find('[data-role="checkboxsetGranular"]').slideDown();}});elem.find('[data-action="checkboxsetAll"]').on('click',function(){elem.find('[data-role="checkboxsetGranular"] input:enabled[type="checkbox"]').prop('checked',true);if(elem.find('[data-role="checkboxsetUnlimitedToggle"]').length>0){elem.find('[data-role="checkboxsetUnlimited"]').slideDown();elem.find('[data-role="checkboxsetGranular"]').slideUp();elem.find('[data-role="checkboxsetUnlimitedToggle"]').prop('checked',true);}
$(elem)[0]?.dispatchEvent(new CustomEvent('ips:formChange',{bubbles:true}));});elem.find('[data-action="checkboxsetNone"]').on('click',function(){elem.find('[data-role="checkboxsetGranular"] input:enabled[type="checkbox"]').prop('checked',false);if(elem.find('[data-role="checkboxsetUnlimitedToggle"]').length>0){elem.find('[data-role="checkboxsetUnlimited"]').slideDown();elem.find('[data-role="checkboxsetGranular"]').slideUp();elem.find('[data-role="checkboxsetUnlimitedToggle"]').prop('checked',false).change();}
$(elem)[0]?.dispatchEvent(new CustomEvent('ips:formChange',{bubbles:true}));});elem.find('[data-role="search"]').on('keydown',function(e){if(e.keyCode==13||e.keyCode==38||e.keyCode==40){e.preventDefault();}});elem.find('[data-role="search"]').off('keyup').on('keyup',function(e){const focussedCheckbox=elem.find('[data-role="result"].ipsField__checkboxOverflow__focused');switch(e.keyCode){case 13:focussedCheckbox.find('input').prop('checked',!focussedCheckbox.find('input').prop('checked'));break;case 38:var prev=focussedCheckbox.prevAll(':visible').first();if(prev.length){focussedCheckbox.removeClass('ipsField__checkboxOverflow__focused')
prev.addClass('ipsField__checkboxOverflow__focused');}
break;case 40:var next=focussedCheckbox.nextAll(':visible').first();if(next.length){focussedCheckbox.removeClass('ipsField__checkboxOverflow__focused')
next.addClass('ipsField__checkboxOverflow__focused');}
break;default:focussedCheckbox.removeClass('ipsField__checkboxOverflow__focused');var val=$(this).val().toLowerCase();if(val){elem.find('[data-role="massToggles"]').hide();elem.find('[data-role="result"]').each(function(){const labelText=this.querySelector('label svg[data-ipstooltip]')?.getAttribute('title')||this.querySelector('label svg[data-ipstooltip]')?.getAttribute('_title')||this.querySelector('label')?.innerText
if(labelText?.toLowerCase().includes(val)){$(this).show();}else{$(this).hide();}});elem.find('[data-role="result"]:visible').first().addClass('ipsField__checkboxOverflow__focused');}else{elem.find('[data-role="result"]:hidden').show();elem.find('[data-role="massToggles"]').show();}}});elem.find('[data-role="search"]').on('clear blur',function(e){if($(e.relatedTarget).closest('[data-role="checkboxsetGranular"]').find('[data-role="search"]').is(this)){e.preventDefault();$(this).focus();return;}
$(this).val('');elem.find('[data-role="result"].ipsField__checkboxOverflow__focused').removeClass('ipsField__checkboxOverflow__focused');elem.find('[data-role="result"]:hidden').show();elem.find('[data-role="massToggles"]').show();});const count=parseInt(elem.attr('data-count'));if(count>10){elem.find('.ipsField__checkboxOverflow').addClass('ipsField__checkboxOverflow--scroll');}},diallingCode(elem){const selected=elem.find('option:selected');if(selected.length){selected.html(selected.attr('data-code'));}
elem.on('change mouseleave',function(){elem.find('option').each(function(){$(this).html($(this).attr('data-text'));});elem.find('option:selected').html(elem.find('option:selected').attr('data-code'));$(this).blur();});elem.on('focus',function(){elem.find('option').each(function(){$(this).html($(this).attr('data-text'));});});}}
function localeSort(a,b){let bValue;let aValue;if($(a).prop("tagName")=='OPTGROUP'){aValue=$(a).attr('label');}else{if(!a.value){return-1;}
aValue=a.innerHTML;}
if($(b).prop("tagName")=='OPTGROUP'){bValue=$(b).attr('label');}else{if(!b.value){return 1;}
bValue=b.innerHTML;}
try{return aValue.localeCompare(bValue);}catch(err){return(aValue>bValue)?1:-1;}}
function refreshFormToggles(form){if(!form){return;}
for(let i=0;i<1;i++){const event=new CustomEvent('ips:calculateToggles',{cancelable:false,bubbles:false,detail:{togglesOn:new Set(),togglesOff:new Set(),}});try{form.dispatchEvent(event)}catch(e){e.message='Failed to evaluate form toggles on an element:\n'+e.message;Debug.warn(e);}
const forceStates={togglesOn:new Set([...event.detail.togglesOn]),togglesOff:new Set([...event.detail.togglesOff])}
parseToggleControls(event);forceStates.togglesOn.forEach(el=>{event.detail.togglesOn.add(el);event.detail.togglesOff.delete(el);forceStates.togglesOff.delete(el);})
forceStates.togglesOff.forEach(el=>{event.detail.togglesOff.add(el);event.detail.togglesOn.delete(el);})
const allToggled=new Set([...event.detail.togglesOn,...event.detail.togglesOff]);for(const toggle of allToggled){if(event.detail.togglesOn.has(toggle)){toggle.removeAttribute('hidden');}else{toggle.setAttribute('hidden','');}}
for(const widgetType of['uploader','matrix']){form.querySelectorAll(`[data-ips${widgetType}]`).forEach(elem=>ips.ui[widgetType].refresh($(elem)));}
form.dispatchEvent(new CustomEvent('ips:refreshTogglesDone',{bubbles:true,cancelable:true}));}}
function buildToggleMap(form,togglers,toggledCollection){togglers=[...togglers];const allToggledElementsForForm=new Set();for(const{togglesOn,togglesOff}of toggledCollection.values()){togglesOn.forEach(elem=>allToggledElementsForForm.add(elem));togglesOff.forEach(elem=>allToggledElementsForForm.add(elem));}
const map=new Map();const toggleInputMap=new Map();for(let toggler of togglers){const toggleCollection=toggledCollection.get(toggler);const allToggled=new Set([...toggleCollection.togglesOn,...toggleCollection.togglesOff]);let possibleToggled=toggler;while(possibleToggled&&!allToggledElementsForForm.has(possibleToggled)){possibleToggled=possibleToggled.parentElement;}
toggleInputMap.set(toggler,possibleToggled||toggler);for(let toggled of allToggled){if(!map.has(toggled)){map.set(toggled,{parents:new Set(),ancestors:new Set()});}
map.get(toggled).parents.add(toggler);}}
const allAncestorsMemo=new Map();function getAllAncestors(el,path){if(!allAncestorsMemo.has(el)){path=path||new Set();path.add(el);const ancestors=new Set();if(map.has(el)){for(let parent of map.get(el).parents){if(path.has(parent)){Debug.warn(`Cyclical form toggle detected. #${parent.getAttribute('id')} ultimately toggles itself.`);continue;}
ancestors.add(parent);ancestors.add(toggleInputMap.get(parent))
for(const ancestor of getAllAncestors(parent,new Set(path))){ancestors.add(ancestor);}}}
if(map.has(toggleInputMap.get(el))){for(let parent of map.get(toggleInputMap.get(el)).parents){if(path.has(parent)){Debug.warn(`Cyclical form toggle detected. #${parent.getAttribute('id')} ultimately toggles itself.`);continue;}
ancestors.add(parent);for(const ancestor of getAllAncestors(parent,new Set(path))){ancestors.add(ancestor);}}}
allAncestorsMemo.set(el,ancestors);}
return allAncestorsMemo.get(el);}
for(const toggled of map.keys()){for(const parent of[...map.get(toggled).parents]){for(const ancestor of getAllAncestors(parent)){map.get(toggled).ancestors.add(ancestor);}}}
return{inputMap:map,toggleInputMap};}
function parseToggleControls(e){const form=e.target;if(!form){return;}
const toggleCollectionMap=new Map();const allTogglers=[...form.querySelectorAll('[data-control~="toggle"], [data-action="nodeSelect"][data-toggles]')];allTogglers.forEach(toggler=>toggleCollectionMap.set(toggler,getToggleCollection(toggler,form)));const{inputMap:toggleMap,toggleInputMap}=buildToggleMap(form,allTogglers,toggleCollectionMap);const toggleMapReverse=new Map();for(const toggled of toggleMap.keys()){for(const parent of toggleMap.get(toggled).parents){if(!toggleMap.get(toggled).ancestors.has(parent)){if(!toggleMapReverse.has(parent)){toggleMapReverse.set(parent,new Set())}
toggleMapReverse.get(parent).add(toggled);}}}
const roots=new Set();for(const toggler of toggleMapReverse.keys()){if(!toggleMap.has(toggler)){roots.add(toggler);}}
const toggleStates=new Map();for(const toggle of allTogglers){let eventType;let state;const toggleElements=toggleCollectionMap.get(toggle);if(!toggleElements.togglesOn.size&&!toggleElements.togglesOff.size){continue;}
if(toggle.matches('option')){state=toggleIsOn.select(toggle);}else if(toggle.matches('input[type="checkbox"], input[type="radio"]')){state=toggleIsOn.checkbox(toggle);}else if(toggle.matches('.ipsSelectTree_item')){state=toggleIsOn.node(toggle);eventType='nodeSelectedChanged';}else{state=toggleIsOn.generic(toggle);}
toggleStates.set(toggle,state);}
const checkAncestorMemo=new Map();function checkAncestors(input,path){if(checkAncestorMemo.has(input)){return checkAncestorMemo.get(input);}
path=path||new Set();const toggledEl=toggleInputMap.get(input)||input;path.add(input);if(!toggleMap.has(toggledEl)){checkAncestorMemo.set(toggledEl,false);return false;}
let allDisabled=true;for(const parent of toggleMap.get(toggledEl).parents){if(toggleMap.get(toggledEl).ancestors.has(parent)){continue;}
if(!path.has(parent)&&!checkAncestors(parent,new Set(path))){let relationship='togglesOn';if(toggleCollectionMap.get(parent)&&(toggleCollectionMap.get(parent).togglesOff.has(toggledEl)||toggleCollectionMap.get(parent).togglesOff.has(input))){relationship='togglesOff';}
if(toggleStates.has(parent)&&!(relationship==='togglesOn'?toggleStates.get(parent):!toggleStates.get(parent))){continue;}
allDisabled=false;break;}}
if(allDisabled){checkAncestorMemo.set(input,true);return true;}
checkAncestorMemo.set(input,false);return false;}
for(const toggle of[...toggleStates.keys()]){const disabled=checkAncestors(toggle);const state=disabled?false:toggleStates.get(toggle);const toggleElements=toggleCollectionMap.get(toggle);toggleElements.togglesOn.forEach(elem=>{if(!toggleMap.get(elem).ancestors.has(toggle)){if(state&&!disabled){e.detail.togglesOn.add(elem);}else{e.detail.togglesOff.add(elem);}}});toggleElements.togglesOff.forEach(elem=>{if(!toggleMap.get(elem).ancestors.has(toggle)){if(state||disabled){e.detail.togglesOff.add(elem);}else{e.detail.togglesOn.add(elem);}}});}}
function getToggleCollection(elem,form){const getElements=s=>new Set(form.querySelectorAll(s.split(',').map(c=>"[id='"+c.trim()+"']").join(', ')));return{togglesOn:(elem.dataset.toggles||elem.dataset.toggleson)?getElements(elem.dataset.toggles||elem.dataset.toggleson):new Set(),togglesOff:elem.dataset.togglesoff?getElements(elem.dataset.togglesoff):new Set(),}}
const toggleIsOn={select:elem=>!!elem.selected||elem.closest('select')?.value===elem.value,checkbox:elem=>!!elem.checked,node:elem=>elem.matches('[data-action="nodeSelect"][data-toggles].ipsSelectTree_selected'),generic:elem=>elem.dataset&&'togglereverse'in elem.dataset?!elem.value:!!elem.value,};ips.ui.registerWidget('form',ips.ui.form);return{respond(elem){const form=$(elem).get(0).closest('form, [data-ipsform]');if(form&&!('listenersSetup'in form.dataset)){form.dataset.listenersSetup='';form.addEventListener('nodeSelectedChanged',()=>form.dispatchEvent(new CustomEvent('ips:formChange')));form.addEventListener('change',()=>form.dispatchEvent(new CustomEvent('ips:formChange')));form.addEventListener('ips:formChange',_.debounce(()=>refreshFormToggles(form),20));setTimeout(()=>refreshFormToggles(form));}
for(const type in formTypes){$(elem).find(formTypes[type]).each(function(){_controlMethods[type]?.($(this),elem);});}
$(elem).find('select[data-sort]').each(function(){var value=$(this).val();$(this).children('optgroup').each(function(){$(this).append($(this).children('option').remove().sort(localeSort));});$(this).append($(this).children('optgroup').remove().sort(localeSort));$(this).append($(this).children('option').remove().sort(localeSort));$(this).val(value);});},init(){$(document).on('contentChange',(e,data)=>{if(!_.isUndefined(data)&&$(data[0]).closest('[data-ipsForm]').length){this.respond($(data[0]).closest('[data-ipsform]'));}});$(document).on('menuOpened',(e,data=e.detail)=>{if(data.menu.closest('[data-ipsForm]')&&data.menu.closest('[data-ipsForm]').length){this.respond(data.menu);}});$(document).on('codeMirrorInsert',function(e,data){if(!_.isUndefined(_cmInstances[data.elemID])){_cmInstances[data.elemID].replaceRange(data.tag,_cmInstances[data.elemID].getCursor("end"));}});$(document).on('tabChanged',function(e,data){var form=$('#'+data['barID']).closest('[data-ipsForm]');if($('input[name='+form.attr('data-formId')+'_activeTab]').length){$('input[name='+form.attr('data-formId')+'_activeTab]').val(data['tabID'].replace(form.attr('data-formId')+'_tab_',''));}});}};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.formSubmit',function(){var respond=function(elem,options){var formElement=$(elem).is('form')?$(elem):$(elem).closest('form');formElement.on('submit',function(e){formElement.find('input[type="submit"],button[type="submit"]').prop('disabled',true);});formElement.on('fileStillUploading',function(e){formElement.find('input[type="submit"],button[type="submit"]').prop('disabled',false);});};ips.ui.registerWidget('formSubmit',ips.ui.formSubmit);return{respond:respond};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.hovercard',function(){var defaults={timeout:0.75,showLoading:true,width:450,className:'ipsHovercard',onClick:false,target:null,cache:true};var cache={};var respond=function(elem,options){if(!$(elem).data('_hover')){$(elem).data('_hover',hoverCardObj(elem,_.defaults(options,defaults)));}
if(options.onClick){$(elem).off('.hovercard').on('click.hovercard',function(e){e.preventDefault();$(elem).data('_hover').start();});}else{if(ips.utils.events.isTouchDevice()&&(ips.utils.responsive.currentIs('phone')||ips.utils.responsive.currentIs('tablet'))){return;}
$(elem).data('_hover').start();}},getObj=function(elem){if($(elem).data('_hover')){return $(elem).data('_hover');}
return undefined;},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}},setCache=function(url,content){cache[url]=content;},unCache=function(url){delete cache[url];},getCache=function(url){return cache[url];};ips.ui.registerWidget('hover',ips.ui.hovercard,['timeout','attach','content','width','onClick','target','cache'],{lazyLoad:true,lazyEvents:'mouseover'});return{respond:respond,destruct:destruct,setCache:setCache,getCache:getCache};});var hoverCardObj=function(elem,options){var onTimeout=null,offTimeout=null,ajaxObj,content,target,loading,card,working=false,elemID='';var init=function(){elemID=$(elem).identify().attr('id');},destruct=function(){clearTimeout(offTimeout);$(document).off('click.'+elemID);_removeLoadingWidget();if(card){card.remove();}},start=function(){if(working!==false&&options.onClick){return;}
working=true;target=($(options.attach).length)?$(options.attach):$(elem);clearTimeout(offTimeout);if(!options.onClick){onTimeout=setTimeout(_startShow,(options.timeout*1000));$(elem).off('mouseout.hovercard',_mouseOut).on('mouseout.hovercard',_mouseOut);$(elem).off('mousedown.hovercard',_elemClick).on('mousedown.hovercard',_elemClick);}else{$(document).off('click.'+elemID).on('click.'+elemID,_documentClick);_startShow();}},_elemClick=function(e){if(onTimeout){clearTimeout(onTimeout);}
if(offTimeout){clearTimeout(offTimeout);}
if(ajaxObj&&_.isFunction(ajaxObj.abort)){ajaxObj.abort();}
_removeLoadingWidget();_hideCard();},_documentClick=function(e){if(!$(card).is(':visible')){return;}
if(e.target!=elem&&!$.contains(elem,e.target)&&e.target!=card.get(0)&&!$.contains(card.get(0),e.target)){_hideCard();$(document).off('click.'+elemID);}},_startShow=function(){if(card&&card.length&&_.isElement(card.get(0))){_positionCard();working=false;return;}
if(options.content&&$(options.content).length){_buildLocalContent();_buildCard();_positionCard();working=false;}else{_buildRemoteContent().done(function(){_buildCard();_positionCard();}).fail(function(){}).always(function(){working=false;});}},_hideCard=function(){card[0].hidePopover();},_positionCard=function(){if(!card.length){Debug.warn("_positionCard called before a card element exists");return;}
if(!target.is(':visible')){Debug.info("Can't show hovercard when target isn't visible");return;}
card.css({left:'auto',top:'auto'});if(card.attr('data-originalWidth')){card.css({width:card.attr('data-originalWidth')+'px'});}
var elemPos=ips.utils.position.getElemPosition(target);var tooWide=false;var elemHeight=$(target).height();var elemWidth=$(target).width();var actualWidth=$(card).width();var actualHeight=$(card).height();var win=$(window);var positionInfo={trigger:elem,target:card,above:true,stemOffset:{left:20,top:0}};var location=ips.utils.position.positionElem(positionInfo);card.css({left:location.left+'px',top:location.top+'px'});var newElemPosition=ips.utils.position.getElemPosition(card);if((actualWidth>$(document).width())||newElemPosition.viewportOffset.left<-20){options.noStem=true;card.attr('data-originalWidth',actualWidth).css({left:'10px',width:($(document).width()-20)+'px'});var newLocation=ips.utils.position.positionElem(positionInfo);card.css({top:newLocation.top+'px'});}
card.find('.ipsHovercard_stem').remove();_.each(['Top','Bottom','Left','Right'],function(type){card.removeClass('ipsHovercard_stem'+type);});var stem=$('<span/>').addClass('ipsHovercard_stem');card.append(stem).addClass(options.className+'_stem'+(location.location.vertical.charAt(0).toUpperCase()+location.location.vertical.slice(1)));if(tooWide){stem.css({left:(elemPos.viewportOffset.left-10)+'px'});}else{card.addClass(options.className+'_stem'+(location.location.horizontal.charAt(0).toUpperCase()+location.location.horizontal.slice(1)));}
card[0].showPopover();},_buildCard=function(){var cardId=$(elem).identify().attr('id')+'_hovercard',actualWidth=options.width||300;card=$('<div/>');card.attr("popover","manual").attr({id:cardId}).addClass(options.className).css({width:actualWidth+'px'});if(_.isString(content)){card.append($('<div/>').html(content));}else{card.append(content.show());}
ips.getContainer().append(card);if(!options.onClick){card.on('mouseenter',_cardMouseOver).on('mouseleave',_cardMouseOut);}
$(document).trigger('contentChange',[card]);},_buildLocalContent=function(){content=$(options.content);},_buildRemoteContent=function(){var deferred=$.Deferred();if(!elem.href){deferred.reject();return deferred.promise();}
if(options.cache&&ips.ui.hovercard.getCache(elem.href)){content=ips.ui.hovercard.getCache(elem.href);deferred.resolve();return deferred.promise();}
_buildLoadingWidget();if(options.target){var target=options.target;}else{var target=elem.href;}
ajaxObj=ips.getAjax()(target).done(function(response){content=response;deferred.resolve();if(options.cache){ips.ui.hovercard.setCache(target,content);}}).fail(function(jqXHR,status,errorThrown){if(Debug.isEnabled()){if(status!='abort'){Debug.error("Ajax request failed ("+status+"): "+errorThrown);}else{Debug.warn("Ajax request aborted");}
_removeLoadingWidget();deferred.reject();}else{if(status!='abort'){content=$('<div/>').addClass('i-padding_2 i-color_soft').html(ips.getString('errorLoadingContent'));deferred.resolve();}else{deferred.reject();}}}).always(function(){_removeLoadingWidget();});return deferred.promise();},_buildLoadingWidget=function(){if(!options.showLoading){return;}
loading=$('<div/>').addClass('ipsHovercard_loading').html(ips.templates.render('core.hovercard.loading'));ips.getContainer().append(loading);var loadingDims={width:loading.width(),height:loading.height()};loading.hide();var elemPos=ips.utils.position.getElemPosition(target),dimsToUse=(elemPos.fixed)?'fixedPos':'absPos';loading.css({left:elemPos[dimsToUse].left+'px',top:(elemPos[dimsToUse].top-loadingDims.height-10)+'px',position:(elemPos.fixed)?'fixed':'absolute',zIndex:"50000"});ips.utils.anim.go('fadeIn',loading);},_removeLoadingWidget=function(){if(loading&&loading.length){loading.remove();}},_mouseOut=function(){clearTimeout(onTimeout);if(ajaxObj){ajaxObj.abort();}
_removeLoadingWidget();if(card&&card.is(':visible')){offTimeout=setTimeout(_hideCard,options.timeout*1000);}
$(elem).off('.hovercard',_mouseOut);},_cardMouseOver=function(){clearTimeout(offTimeout);},_cardMouseOut=function(){clearTimeout(offTimeout);offTimeout=setTimeout(_hideCard,options.timeout*1000);};init();return{init:init,destruct:destruct,start:start};};}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.ui.iframelySizing',function(){let loaded=false;function loadIframelyAdHoc(root){if(loaded){return;}
const iframelyCDN=ips.getSetting('iframely_custom_cdn')||"iframe.ly";if(!(root||document).querySelector(`[data-iframely-url], iframe[src*='${iframelyCDN}']`)){return;}
let iframely=window.iframely=window.iframely||{};loaded=true;if(iframely.load){iframely.load();}else{ips.loader.get(["//cdn.iframe.ly/embed.js"]).then(()=>{Debug.log('Iframely embed.js loaded.');});}}
return{loadIframelyAdHoc,init(){loadIframelyAdHoc(document.body);if(!loaded){const contentChange=(elem)=>{$(elem).each(function(){if(this instanceof Element){loadIframelyAdHoc(this);}});if(loaded){$(document).off('contentChange',contentChange);}};$(document).on('contentChange',contentChange);}}}})})(jQuery,_);;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.infiniteScroll',function(){var defaults={distance:50,loadingTpl:'core.infScroll.loading',scrollScope:window,pageParam:'page',pageBreakTpl:'core.infScroll.pageBreak',totalPages:null,disableIn:'phone'};var respond=function(elem,options){if(!$(elem).data('_infinite')){$(elem).data('_infinite',infiniteScrollObj(elem,_.defaults(options,defaults)));}},getObj=function(elem){if($(elem).data('_infinite')){return $(elem).data('_infinite');}
return undefined;};ips.ui.registerWidget('infScroll',ips.ui.infiniteScroll,['container','scrollScope','distance','url','pageParam','loadingTpl','pageBreakTpl','disableIn']);var infiniteScrollObj=function(elem,options){var state='ready',scrollScope=null,container=null,ajaxObj=null,currentPage=1;var init=function(){container=$(options.container);scrollScope=$(options.scrollScope);scrollScope.on('scroll',_scrollEvent);options.disableIn=options.disableIn.split(',');if(_.isString(options.distance)&&options.distance.indexOf('%')!==-1){var percent=parseInt(options.distance);options.distance=(scrollScope.height()/100)*percent;}
if(options.totalPages==null){options.totalPages=_getTotalPages();}
currentPage=_getStartPage();elem.on('refresh.infScroll',_refresh);},_refresh=function(){options.totalPages=_getTotalPages();currentPage=_getStartPage();try{ajaxObj.abort();}catch(err){}},_scrollEvent=function(e){if(ips.utils.responsive.enabled()&&_.indexOf(options.disableIn,ips.utils.responsive.getCurrentKey())!==-1){return;}
if(state=='loading'||state=='done'){return;}
if(currentPage>=_getTotalPages()){return;}
var distanceFromBottom=_getDistance();if(distanceFromBottom<=options.distance){state='loading';_loadMoreResults();}},_loadMoreResults=function(){_showLoadingElem();if(ajaxObj&&ajaxObj.abort){ajaxObj.abort();}
ajaxObj=ips.getAjax()(_getPageURL(currentPage+1)).done(function(response){currentPage++;_insertNewResults(response);state='ready';$(elem).trigger('infScrollPageLoaded',{page:currentPage});}).fail(function(){}).always(function(){_removeLoadingElem();});},_insertNewResults=function(response){var output='';if(options.pageBreakTpl){output+=ips.templates.render(options.pageBreakTpl,{page:currentPage});}
output+=response;var oldChildLength=container.children().length;container.append(output);container.children().slice(oldChildLength).each(function(child){$(document).trigger('contentChange',[$(this)]);});},_showLoadingElem=function(){container.append(ips.templates.render(options.loadingTpl));},_removeLoadingElem=function(){container.find('[data-role="infScroll_loading"]').remove();},_getDistance=function(){if(options.scrollScope==window){var scrollHeight=$(document).height();var distanceFromBottom=scrollHeight-$(window).height()-$(window).scrollTop();}else{var scrollHeight=scrollScope[0].scrollHeight;var distanceFromBottom=scrollHeight-scrollScope.height()-scrollScope.scrollTop();}
return distanceFromBottom;},_getPageURL=function(pageNo){var url=elem.attr('data-ipsInfScroll-url');return url+(url.match(/\?/)?'&':'?')+options.pageParam+'='+parseInt(pageNo);},_getStartPage=function(){var paginationElem=elem.find('.ipsPagination').first();if(!paginationElem.length){return 1;}
var activePage=paginationElem.find('.ipsPagination__active').attr('data-page');if(!activePage){return 1;}else{return parseInt(activePage);}},_getTotalPages=function(){var paginationElem=elem.find('.ipsPagination').first();if(!paginationElem.length){return 1;}
var totalPages=paginationElem.attr('data-pages');if(!totalPages){return 1;}else{return parseInt(totalPages);}};init();return{init:init};};return{respond:respond};});}(jQuery,_));;
;(function($,_,undefined){const imageExtensions=new Set(['jpg','jpeg','jpe','gif','png','webp','avif']),audioExtensions=new Set(['mp3','ogg','wav','m4a']),videoExtensions=new Set(['mp4','3gp','mov','ogg','ogv','mpg','mpeg','flv','webm','wmv','avi','m4v']);const uploadObj=function(elem,options,e){elem=$(elem);let pluploadObj,runtime,listContainer,uploadCount=0,totalSize=0,injectIds={},uploaderID='',sound=null;function init(){uploaderID=$(elem).identify().attr('id');if(options.listContainer){listContainer=$(options.listContainer);}else if($(elem).find('[data-role="fileList"]').length){listContainer=$(elem).find('[data-role="fileList"]');}else{listContainer=$(elem);}
if(ips.templates.get(options.template+'Wrapper')){listContainer.prepend(ips.templates.render(options.template+'Wrapper'));const firstItem=listContainer.children().first();firstItem.append(listContainer.children().not(firstItem));listContainer=firstItem;$(document).trigger('contentChange',[listContainer.parent()]);}
$(document).on('addUploaderFile',_addUploaderFile);$(document).on('removeAllFiles',_removeAllFiles);if(options.existingFiles){try{const files=$.parseJSON(options.existingFiles);if(files.length){_buildExistingFiles(files);}}catch(err){Debug.error("Couldn't build existing files: "+err);}}
ips.utils.cookie.set('editor_supports_drag',_supportsDraggable()?'true':'false');$(elem).find('[data-action="browse"],[data-supports-drag]').attr('data-supports-drag',_supportsDraggable()?'true':'false');const load=ips.getSetting('useCompiledFiles')?['core/interface/plupload/plupload.full.min.js']:['core/interface/plupload/moxie.js','core/interface/plupload/plupload.dev.js'];ips.loader.get(load).then(function(){_setUpUploader();_initUploader();_postInitEvents();_setUpFormEvents();});}
function refresh(){if(pluploadObj){Debug.log("Refreshing");pluploadObj.refresh();}}
function _setUpFormEvents(){const form=_getForm();if(!form.length){return;}
if(options.allowStockPhotos!==false){$(elem).find('[data-action="stockPhoto"]').on('click',function(e){e.preventDefault();e.stopPropagation();const dialogRef=ips.ui.dialog.create({title:ips.getString("stockphoto_header"),fixed:false,destructOnClose:true,url:ips.getSetting('baseURL')+'?app=core&module=system&controller=pixabay&uploader='+$(elem).attr('data-ipsUploader-name'),});dialogRef.show();});}
form.on('submit',function(e){if(pluploadObj.state!==plupload.STOPPED){e.preventDefault();e.stopPropagation();ips.ui.alert.show({type:'alert',message:ips.getString('filesStillUploading'),subText:ips.getString('filesStillUploadingDesc'),icon:'warn'});$(elem).trigger('fileStillUploading');}});}
function _addUploaderFile(e,data){if(data.uploaderID===uploaderID){data.extIcon=ips.ui.uploader.getExtensionIcon(data.title);listContainer.append(ips.templates.render(_getTemplateName(data),data));}}
function _getTemplateName(data){if(options.template!==null){return options.template;}
let type='fileItem';if(data.isImage){type='imageItem';}else if(data.isVideo){type='videoItem';}
return`core.attachments.${type}`;}
function _removeAllFiles(){listContainer.find('[data-role="file"]').remove();}
function _buildExistingFiles(files){if(!files.length){return;}
for(let file of files){const data={id:file.id,imagesrc:file.imagesrc,thumbnail:file.thumbnail?file.thumbnail:'',thumbnail_for_css:file.thumbnail?file.thumbnail.replace('(','\\(').replace(')','\\)'):'',title:file.originalFileName,size:file.size,field_name:$(elem).attr('data-ipsUploader-name'),newUpload:false,insertable:!options.insertable,done:true,'default':file.default?file.default:null,supportsDelete:options.supportsDelete,extIcon:ips.ui.uploader.getExtensionIcon(file.originalFileName)};if(file.id===$(elem).attr('data-ipsUploader-default')){data['checked']="checked";}
if(file.hasThumb){data['thumb']="<img src='"+(file['thumbnail']?file['thumbnail']:file['imagesrc'])+"' class='ipsImage' alt='An uploaded image'>";}
listContainer.append(ips.templates.render(options.template,data));$('#'+file.id).trigger('newItem',[$('#'+file.id)]);}
$(elem).trigger('fileAdded',{count:files.length,uploader:options.name});}
function _setUpUploader(){pluploadObj=new plupload.Uploader(_getUploaderSettings());pluploadObj.bind('Init',events.init);listContainer.find('[data-role="file"]').each(function(){const fileElem=$(this);fileElem.on('click','[data-role="deleteFile"]',_.bind(_deleteFile,fileElem,fileElem));uploadCount++;});}
function _getForm(){let form=$(elem).parentsUntil('','form');if(!form.length&&options.postkey){form=$(`[data-ipseditorv5-postkey="${options.postkey}"]`).closest('form');}
return form;}
function _getUploaderSettings(){const form=_getForm();if(options.action===null){options.action=form.attr('action');}
if(options.key===null){options.key=form.children("[name='plupload']").val();}
const pluploadOptions={runtimes:'html5,flash,silverlight,html4',multi_selection:options.multiple,url:encodeURI(_decodeUrl(options.action)),file_data_name:options.name,flash_swf_url:'applications/core/interface/plupload/Movie.swf',silverlight_xap_url:'applications/core/interface/plupload/Movie.xap',browse_button:$(elem).find(options.button).identify().attr('id'),headers:{'x-plupload':options.key},chunk_size:options.maxChunkSize+'mb'};if(options.dropTarget){pluploadOptions.drop_element=$(options.dropTarget).attr('id');}else if($(elem).hasClass('ipsAttachment_dropZone')){pluploadOptions.drop_element=$(elem).attr('id');}else if($(elem).find('.ipsAttachment_dropZone').length){pluploadOptions.drop_element=$(elem).find('.ipsAttachment_dropZone').identify().attr('id');}
return pluploadOptions;}
function _isEncoded(url){url=url||'';return url!==decodeURI(url);}
function _decodeUrl(url){while(_isEncoded(url)){url=decodeURI(url);}
return url;}
function _initUploader(){pluploadObj.init();}
function _postInitEvents(){pluploadObj.bind('Error',events.error);pluploadObj.bind('FilesAdded',events.filesAdded);pluploadObj.bind('FilesRemoved',events.filesRemoved);pluploadObj.bind('UploadFile',events.uploadFile);pluploadObj.bind('UploadProgress',events.uploadProgress);pluploadObj.bind('FileUploaded',events.fileUploaded);pluploadObj.bind('UploadComplete',events.uploadComplete);$(elem).on('injectFile',function(e,data){data=data===undefined?e.originalEvent?.data:data;if(typeof data!=='object'||!(data.file instanceof File)||!('data'in data)){Debug.log('Cannot handle the file injection because there is no file to inject');return;}
const pluploadFile=new plupload.File(new moxie.file.File(getRuntimeUid(),data.file));injectIds[pluploadFile.id]=data.data;pluploadObj.addFile(pluploadFile);}).on('resetUploader',function(data){_resetUploader();});$(window).on('resize',function(){pluploadObj.refresh();});}
function getRuntimeUid(){if(!runtime){runtime=new(moxie.runtime.Runtime.getConstructor(pluploadObj.runtime))();runtime.init();}
return runtime.uid;}
function _resetUploader(){uploadCount=0;totalSize=0;_updateCount();$(elem).trigger('removeAllFiles',{uploaderID:uploaderID});}
function _startUpload(){Debug.log('Starting upload process...');pluploadObj.start();}
function _getStatus(status){switch(status){case plupload.QUEUED:return ips.getString('attachQueued');case plupload.UPLOADING:return ips.getString('attachUploading');case plupload.FAILED:return ips.getString('attachFailed');case plupload.DONE:return ips.getString('attachDone');}}
function _updateFileElement(file){const fileElem=_findFileElem(file);_removeStatusClasses(fileElem);_updateStatus(fileElem,file.status);_updateCount();return fileElem;}
function _findFileElem(file){return $(elem).find('#'+file.id);}
function _updateStatus(fileElem,status){$(fileElem).find('[data-role="status"]').html(_getStatus(status));$(fileElem).toggleClass('ipsAttach_error',status===plupload.FAILED);}
function _removeStatusClasses(fileElem){_.each(['uploading','done','error','queued'],function(type){fileElem.removeClass('ipsAttach_'+type);});}
function _updateCount(){$(elem).find('[data-role="count"]').text(uploadCount);elem.trigger('uploadedCountChanged',{count:uploadCount,percent:pluploadObj.total.percent,uploader:options.name});}
function _setPercent(fileElem,percent){$(fileElem).find('[data-role="progressbar"]').attr('value',percent);if(percent===100){fileElem.find('.ipsMeter').slideUp();}}
function _buildThumb(fileElem,file,info){let toInsert='';if(info.imagesrc){Debug.log(fileElem.find('[data-role="preview"]'));toInsert=$('<img/>').attr({src:info.thumbnail?info.thumbnail:info.imagesrc,alt:''});fileElem.attr('data-fullsizeurl',info.imagesrc).attr('data-thumbnailurl',info.thumbnail?info.thumbnail:info.imagesrc).find('[data-role="preview"]').html(toInsert);}else if(info.videosrc){toInsert=$('<video/>').append($('<source/>').attr({src:info.videosrc,type:fileElem.attr('data-mimeType')}));fileElem.attr('data-fullsizeurl',info.videosrc).find('[data-role="preview"]').html(toInsert);}
fileElem.attr('data-fileid',info.id);if(info.securityKey){fileElem.attr('data-filekey',info.securityKey);}}
function _deleteFile(fileElem,e){e.preventDefault();e.stopPropagation();let baseUrl=options.action;if(baseUrl.match(/\?/)){if(baseUrl.slice(-1)!=='?'){baseUrl+='&';}}else{baseUrl+='?';}
ips.getAjax()(baseUrl+'getUploader&postKey='+options.postkey+'&deleteFile='+encodeURIComponent(fileElem.attr('data-fileid')));uploadCount--;totalSize=totalSize-fileElem.attr('data-filesize');_updateCount();fileElem.fadeOut(function(){fileElem.remove();elem.trigger('fileDeleted',{fileElem:fileElem,uploader:options.name,count:uploadCount,postkey:options.postkey});});}
function _supportsDraggable(){return'draggable'in document.createElement('span')&&FileReader!==undefined&&!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);}
function _fixZIndex(){$(elem).get(0).querySelector(options.button)?.style.setProperty('z-index','')}
let events={init(up){_fixZIndex();if(_supportsDraggable()){const dropElement=$(up.settings.drop_element);let currentElem=null;$(document).on('dragenter',function(e){if(currentElem&&!$(e.target).is(dropElement)&&!$.contains(dropElement.get(0),currentElem)){dropElement.removeClass('ipsDragging');currentElem=null;}});dropElement.on('dragleave',function(){if(!$(currentElem).is(dropElement)&&!$.contains(dropElement.get(0),currentElem)){dropElement.removeClass('ipsDragging');currentElem=null;}}).on('dragenter',function(e){const target=$(e.target);if(target.is(dropElement)||$.contains(dropElement.get(0),e.target)){dropElement.addClass('ipsDragging');currentElem=e.target;}}).on('drop',function(){dropElement.removeClass('ipsDragging');currentElem=null;});}},filesAdded(up,files){_fixZIndex();if(!options.multiple){listContainer.find('[data-role="deleteFile"]').click();if(files.length>1){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('uploadSingleErr')});for(const file of files){up.removeFile(file);}
return false;}}else if(options.maxFiles){if(files.length>options.maxFiles||(uploadCount+files.length)>options.maxFiles){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.pluralize(ips.getString('uploadMaxFilesErr'),options.maxFiles),callbacks:{}});for(const file of files){up.removeFile(file);}
return false;}}else if(options.maxTotalSize&&totalSize>(options.maxTotalSize*1048576)){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.getString('uploadTotalErr',{size:parseFloat((options.maxTotalSize>=1)?options.maxTotalSize:(options.maxTotalSize*1024)).toLocaleString($('html').attr('lang')),size_suffix:(options.maxTotalSize>=1)?ips.getString('size_mb'):ips.getString('size_kb')}),callbacks:{}});for(const file of files){up.removeFile(file);}
return false;}
const allowedFileTypes=(options.allowedFileTypes!==null)?new Set(JSON.parse(options.allowedFileTypes?.toLowerCase?.())||[]):'';let tooLarge=0,overTotalLimit=0,badType=0,sizeAllowance=options.maxTotalSize?(options.maxTotalSize*1048576)-totalSize:null,fileSizeAllowance=options.maxFileSize?options.maxFileSize*1048576:null
for(let file of files){if(fileSizeAllowance!==null&&file.size>fileSizeAllowance){tooLarge++;up.removeFile(file);continue;}
if(sizeAllowance!==null){if(sizeAllowance<file.size){overTotalLimit++;up.removeFile(file);continue;}
sizeAllowance-=file.size;}
const ext=file.name.split('.').pop().toLowerCase();if(allowedFileTypes?.size&&!allowedFileTypes.has(ext)){badType++;up.removeFile(file);continue;}
const size=plupload.formatSize(file.size),status=_getStatus(file.status);$(elem).trigger('addUploaderFile',{uploaderID:uploaderID,id:file.id,title:file.name,mime:file.type,size:size,sizeRaw:file.size,status,statusCode:file.status,statusText:ips.getString('attachStatus',{size:size,status:status}),field_name:elem.attr('data-ipsUploader-name'),newUpload:true,insertable:true,isImage:imageExtensions.has(ext),isVideo:videoExtensions.has(ext),isAudio:audioExtensions.has(ext),supportsDelete:options.supportsDelete});$('#'+file.id).addClass('ipsAttach_queued').trigger('newItem',[$('#'+file.id)]);}
if(tooLarge){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.pluralize(ips.getString('uploadSizeErr',{max_file_size:parseFloat((options.maxFileSize>1)?options.maxFileSize:(options.maxFileSize*1024)).toLocaleString(document.documentElement.lang),size_suffix:(options.maxFileSize>1)?ips.getString('size_mb'):ips.getString('size_kb')}),[tooLarge,tooLarge])});for(const file of files){up.removeFile(file);}}
if(overTotalLimit){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.pluralize(ips.getString('uploadSizeTotalErr',{max_file_size:parseFloat(options.maxTotalSize>1?options.maxTotalSize:options.maxTotalSize*1024).toLocaleString(document.documentElement.lang),size_suffix:(options.maxTotalSize>1)?ips.getString('size_mb'):ips.getString('size_kb')}),[overTotalLimit,overTotalLimit]),callbacks:{}});}
if(badType){ips.ui.alert.show({type:'alert',icon:'warn',message:ips.pluralize(ips.getString('pluploaderr_-601',{allowed_extensions:[...allowedFileTypes].join(', ')}),[tooLarge,tooLarge]),callbacks:{}});}
if(up.files.length){$(elem).trigger('fileAdded',{count:up.files.length,uploader:options.name});if(options.autoStart){_startUpload();}}},filesRemoved(uploader,files){if(files instanceof Array||Symbol.iterator in files){for(const file of files){if(file.id&&injectIds[file.id]?.error instanceof Function){try{injectIds[file.id].error();}catch(e){console.error(e);}}}}
_fixZIndex();Debug.log('removed');},uploadFile(up,file){_fixZIndex();$(elem).find('.ipsAttachment_loading').show();_updateFileElement(file).addClass('ipsAttach_uploading');},uploadProgress(up,file){_fixZIndex();const fileElem=_updateFileElement(file);fileElem.addClass('ipsAttach_uploading');_setPercent(fileElem,file.percent);elem.trigger('uploadProgress',{count:uploadCount,percent:pluploadObj.total.percent,uploader:options.name});},uploadComplete(up,files){_fixZIndex();let success=0;let error=0;_.each(files,function(file){if(file.status===5){success++;}else if(file.status===4){error++;}});const total=success+error;$(elem).find('.ipsAttachment_loading').hide();elem.trigger('uploadComplete',{success:success,error:error,total:total,uploader:options.name});if(ips.utils.events.getVisibilityProp()!==undefined||!document[ips.utils.events.getVisibilityProp()]){return;}
const text=[];if(!total){return;}
if(success){text.push(ips.pluralize(ips.getString('notifyUploadSuccess'),[success]));}
if(error){text.push(ips.pluralize(ips.getString('notifyUploadError'),[error]));}
if(ips.utils.notification.hasPermission()){ips.utils.notification.create({title:ips.pluralize(ips.getString('yourUploadsFinished'),[total]),body:text.join(' '),icon:ips.getSetting('upload_imgURL'),onClick:function(){try{window.focus();}catch(err){}}}).show();}
if(sound){try{sound.play();}catch(err){}}},fileUploaded(up,file,info){_fixZIndex();uploadCount++;totalSize+=file.size;const fileElem=_updateFileElement(file);fileElem.addClass('ipsAttach_done');if(options.insertable){ips.utils.anim.go('fadeIn',fileElem.find('[data-role="insert"]'));}
fileElem.find('[data-role="deleteFileWrapper"]').slideDown();_setPercent(fileElem,100);try{const jsonInfo=$.parseJSON(info.response);elem.before($('<input type="hidden">').attr('name',elem.attr('data-ipsUploader-name')+'_existing['+file.id+']').attr('value',jsonInfo.id));if(jsonInfo['error']){fileElem.on('click','[data-role="deleteFile"]',_.bind(_deleteFile,fileElem,fileElem));file.status=plupload.FAILED;up.trigger('error',{code:jsonInfo['error'],extra:jsonInfo['extra'],subText:jsonInfo['sub'],file:file,uploader:options.name});return;}
if(jsonInfo){_buildThumb(fileElem,file,jsonInfo);fileElem.on('click','[data-role="deleteFile"]',_.bind(_deleteFile,fileElem,fileElem));}}catch(err){fileElem.on('click','[data-role="deleteFile"]',_.bind(_deleteFile,fileElem,fileElem));file.status=plupload.FAILED;up.trigger('error',{code:'upload_error',extra:err.message,file:file,uploader:options.name});Debug.warn(err);}
if(file.id&&injectIds[file.id]){$(elem).trigger('fileInjected',{'fileElem':fileElem,'data':injectIds[file.id]});delete injectIds[file.id];}},error(up,err){_fixZIndex();if(err.file){const{file}=err;if(file.id&&file.id in injectIds&&injectIds[file.id].error instanceof Function){injectIds[file.id].error();}
_updateFileElement(file);}
if(err.code===-600||err.code===-601){return;}
let errorMessage=ips.getString('pluploaderr_'+err.code,{max_file_size:parseFloat((options.maxFileSize>1)?options.maxFileSize:(options.maxFileSize*1024)).toLocaleString($('html').attr('lang')),size_suffix:(options.maxFileSize>1)?ips.getString('size_mb'):ips.getString('size_kb'),allowed_extensions:(options.allowedFileTypes!==null)?$.parseJSON(options.allowedFileTypes).join(','):'',server_error_code:(err.extra!==null)?err.extra:0,});if(!errorMessage){errorMessage=ips.getString('pluploaderr_SERVER_CONFIGURATION',{server_error_code:err.code});err.subText=ips.getString('pluploaderr_error_code',{code:err.code});}
if(typeof err?.file?.id==='string'){delete injectIds[err.file.id];}
ips.ui.alert.show({type:'alert',icon:'warn',message:errorMessage,callbacks:{},subTextHtml:err.subText?err.subText:null});}};init();return{init,refresh};};"use strict";const iconMap={'txt':'file-lines','rtf':'file-lines','csv':'file-lines','pdf':'file-pdf','doc':'file-word','docx':'file-word','xls':'file-excel','xlsx':'file-excel','xlsm':'file-excel','zip':'file-archive','tar':'file-archive','gz':'file-archive','ppt':'file-powerpoint','pptx':'file-powerpoint','ico':'file-image','gif':'file-image','jpeg':'file-image','jpg':'file-image','jpe':'file-image','png':'file-image','avif':'file-image','psd':'file-image','webp':'file-image','aac':'file-audio','mp3':'file-audio','ogg':'file-audio','ogv':'file-audio','wav':'file-audio','m4a':'file-audio','flv':'file-video','mkv':'file-video','mp4':'file-video','mpg':'file-video','mpeg':'file-video','3gp':'file-video','webm':'file-video','wmv':'file-video','avi':'file-video','m4v':'file-video','mov':'file-video','css':'file-code','html':'file-code','js':'file-code','xml':'file-code',};ips.createModule('ips.ui.uploader',function(){const defaults={multiple:false,allowedFileTypes:null,maxFileSize:null,maxTotalSize:null,maxChunkSize:null,action:null,name:'upload',button:'.ipsButton--primary',key:null,autoStart:true,insertable:false,template:'core.attachments.fileItem',postkey:'',supportsDelete:true,allowStockPhotos:false,};function respond(elem,options){if(!$(elem).data('_uploader')){$(elem).show();$(elem).data('_uploader',uploadObj(elem,_.defaults(options,defaults)));}else{try{const obj=$(elem).data('_uploader');obj.refresh();}catch(err){Debug.log("Couldn't refresh uploader "+$(elem).identify().attr('id'));}}}
function refresh(elem){try{const obj=$(elem).data('_uploader');obj.refresh();}catch(err){Debug.log("Couldn't refresh uploader "+$(elem).identify().attr('id'));}}
function getObj(elem){if($(elem).data('_uploader')){return $(elem).data('_uploader');}
return undefined;}
function getExtensionIcon(filename){const extRegex=/(?:\.([^.]+))?$/;const ext=extRegex.exec(filename);if(!_.isUndefined(iconMap[ext[1]])){return iconMap[ext[1]];}
return'file';}
ips.ui.registerWidget('uploader',ips.ui.uploader,['multiple','allowedFileTypes','maxFileSize','maxTotalSize','maxChunkSize','action','name','button','key','maxFiles','dropTarget','listContainer','autoStart','insertable','template','existingFiles','postkey','supportsDelete','allowStockPhotos']);return{respond:respond,refresh:refresh,getObj:getObj,getExtensionIcon:getExtensionIcon};});}(jQuery,_));;
;(function($,_,undefined){"use strict";const imageDimCache={};const imageResolveCache={};ips.createModule('ips.ui.lightbox',function(){var defaults={className:'ipsLightbox',useEvents:false};var currentLightbox;var respond=function(elem,options,e){options=_.defaults(options,defaults);currentLightbox=new lightboxObj(elem,options,e);},destruct=function(elem){if(currentLightbox){currentLightbox.destruct();currentLightbox=null;}};ips.ui.registerWidget('lightbox',ips.ui.lightbox,['group','commentsURL','className','preload','useEvents'],{lazyLoad:true,lazyEvents:'click'});return{respond:respond,destruct:destruct,getImageDimensions(url){return new Promise(resolve=>{if(url in imageDimCache){resolve(imageDimCache[url])}else if(url in imageResolveCache){imageResolveCache[url].add(resolve)}else{imageResolveCache[url]=new Set();imageResolveCache[url].add(resolve)
const img=document.createElement('img')
let timeout;const loaded=()=>{img.removeEventListener('load',loaded)
img.removeEventListener('error',loaded)
clearTimeout(timeout)
const dims={width:img.naturalWidth,height:img.naturalHeight,solid:!!(img.naturalWidth&&img.naturalHeight)}
img.remove()
imageDimCache[url]=dims
setTimeout(()=>delete imageDimCache[url],300000);imageResolveCache[url].forEach(cb=>cb(dims))
imageResolveCache[url].clear()
delete imageResolveCache[url]}
timeout=setTimeout(loaded,5000)
img.addEventListener('load',loaded)
img.addEventListener('error',loaded)
img.src=url}})}};});var lightboxObj=function(elem,options,e){if(e){e.preventDefault();}
var imageCollection=[],commentsAjax,modal,pieces,currentImage,phoneBreakpoint=false;var init=function(){elem.blur();_getAllImages();_buildModal();_buildWrapper();_setUpEvents();_show();_loadFirstImage();},destruct=function(){$(document).off('keydown',_keyPress);modal.off('click',close);},_setUpEvents=function(){pieces.lightbox.on('click','.'+options.className+'_next',nextImage).on('click','.'+options.className+'_prev',prevImage).on('click','.'+options.className+'_close',close).on('click',clickedLightbox).on('click','[data-action="rotateImage"]',_rotateImage);modal.on('click',close);$(document).on('keydown',_keyPress);$(document).on('imageUpdated',_updateImage);$(document).on('imageLoading',_mainImageLoading);if(options.useEvents){$(document).on('lightboxDisable_next',function(){$('.'+options.className+'_next').hide();});$(document).on('lightboxDisable_prev',function(){$('.'+options.className+'_prev').hide();});$(document).on('lightboxEnable_next',function(){$('.'+options.className+'_next').show();});$(document).on('lightboxEnable_prev',function(){$('.'+options.className+'_prev').show();});}},_mainImageLoading=function(e){_setLoading(true);pieces.imagePanel.find('.'+options.className+'_image ').hide();},_updateImage=function(e,data){if(data.closeLightbox===true){close(e);}
else if(data.updateImage){_showImage(data.updateImage);}},_keyPress=function(e){if(!pieces.lightbox.is(':visible')){return;}
switch(e.keyCode){case ips.ui.key.ESCAPE:close(e);break;case ips.ui.key.RIGHT:nextImage(e);break;case ips.ui.key.LEFT:prevImage(e);break;}},_loadFirstImage=function(){var firstImage=function(){for(var i=0;i<imageCollection.length;i++){if(imageCollection[i].elem==elem){return imageCollection[i];}}}();currentImage=firstImage;_showImage(firstImage);},_showImage=function(image){_setLoading(true);pieces.imagePanel.find('.'+options.className+'_image ').hide();if(image.imageElem){pieces.imagePanel.find('.'+options.className+'_image ').hide()
var thisImage=image.imageElem.css({opacity:"0"}).show();_imageLoaded(thisImage);}else{var thisImage=image.imageElem=$('<img/>').attr('src',image.largeImage).addClass(options.className+'_image').css({opacity:"0"}).imagesLoaded(function(imagesLoaded){try{_imageLoaded($(imagesLoaded.images[0].img));}catch(err){Debug.error("Error loading image");}});if(!_.isUndefined($(image.elem).attr('data-fileId'))){thisImage.attr('data-fileId',$(image.elem).attr('data-fileId'));}
pieces.imagePanel.find('.'+options.className+'_image ').hide().end().append(thisImage);}
var rotatedImage=$('.ipsAttachLink_image img[data-rotate][data-fileId=\''+thisImage.attr('data-fileId')+'\']');if(rotatedImage.length){thisImage.attr('data-rotate',$(rotatedImage).attr('data-rotate'));_applyRotation(thisImage,$(rotatedImage).attr('data-rotate'));}
pieces.fullSize.attr('href',image.largeImage);if(image.commentsURL){_loadComments(image);}else{_hideCommentsPanel();}
if(image.meta){pieces.metaPanel.show().html(ips.templates.render('core.lightbox.meta',{title:image.meta}));}else{pieces.metaPanel.hide();}
$(elem).trigger('lightboxImageShown',{image:image,triggerElem:elem});},_loadComments=function(image){if(commentsAjax){Debug.warn("Aborting comment load");commentsAjax.abort();}
pieces.commentsPanel.html('').show().addClass('ipsLoading');pieces.imagePanel.addClass(options.className+'_withComments');commentsAjax=ips.getAjax()(image.commentsURL).done(function(response){pieces.commentsPanel.html(response).removeClass('ipsLoading');$(document).trigger('contentChange',[pieces.commentsPanel]);$(elem).trigger('lightboxCommentsLoaded',{image:image,triggerElem:elem,commentsArea:pieces.commentsPanel});});},_hideCommentsPanel=function(){pieces.commentsPanel.hide();pieces.imagePanel.removeClass(options.className+'_withComments');},_setLoading=function(status){if(status===true){pieces.imagePanel.addClass('ipsLoading');}else{pieces.imagePanel.removeClass('ipsLoading');$('.'+options.className+'_imagePanel > img, .'+options.className+'_fullSize').on('mouseover',function(){$('.'+options.className+'_fullSize').show();}).on('mouseout',function(){$('.'+options.className+'_fullSize').hide();});}},_imageLoaded=function(image){image.css({opacity:"1"});_setLoading(false);_setButtons(image);if(options.useEvents){return;}
if(imageCollection.length<2){pieces.next.hide();pieces.prev.hide();}else{var curPos=_.indexOf(imageCollection,currentImage);pieces.next.show();pieces.prev.show();if(curPos==0){pieces.prev.hide();}
if(curPos==(imageCollection.length-1)){pieces.next.hide();}}},_setButtons=function(image){if(!_.isUndefined(image.attr('data-fileId'))){$(document).trigger('contentChange',[$('.'+options.className)]);}},clickedLightbox=function(e){if($(e.target).closest('a').length){return;}
var width=$(document).width();var halfPos=width/2;if(e.pageX>=halfPos&&pieces.next.is(':visible')){pieces.next.click();}else if(e.pageX<halfPos&&pieces.prev.is(':visible')){pieces.prev.click();}else{close();}},nextImage=function(e){e.preventDefault();e.stopPropagation();if(options.useEvents){$(document).trigger('lightboxNextImage');return;}
currentImage=_getNextImage();_showImage(currentImage);},prevImage=function(e){e.preventDefault();e.stopPropagation();if(options.useEvents){$(document).trigger('lightboxPrevImage');return;}
currentImage=_getPrevImage();_showImage(currentImage);},_getPrevImage=function(e){var curPos=_.indexOf(imageCollection,currentImage);if(curPos===0){return imageCollection[imageCollection.length-1];}
return imageCollection[curPos-1];},_getNextImage=function(){var curPos=_.indexOf(imageCollection,currentImage);if(curPos==(imageCollection.length-1)){return imageCollection[0];}
return imageCollection[curPos+1];},_rotateImage=function(e){e.preventDefault();var visibleImage=$('img.ipsLightbox_image:visible');var url=$(e.currentTarget).attr('href')+'&current='+$(visibleImage).attr('data-rotate');ips.getAjax()(url,{showLoading:true}).done(function(response){$('img[data-fileId="'+response.fileId+'"]').each(function(){$(visibleImage).attr('data-rotate',response.rotate);_applyRotation(this,response.rotate);if(response.saved==1){$(document).trigger('imageRotated',response);}});ips.ui.flashMsg.show(response.message);}).fail(function(){window.location=url;});},_applyRotation=function(elem,angle){$(elem).css({'transform':'rotate('+angle+'deg)'});if(angle=='90'||angle=='-90'){var panelHeight=$(elem).parents('.ipsLightbox_imagePanel').height();$(elem).css({'max-width':(panelHeight-20).toString()+'px'});}},close=function(e){if(e){e.preventDefault();e.stopPropagation();}
$(document).off('imageUpdated',_updateImage);$(document).off('imageLoading',_mainImageLoading);modal.hide();pieces.lightbox.hide();},_show=function(){ips.utils.anim.go('fadeIn fast',modal);ips.utils.anim.go('fadeIn fast',pieces.lightbox);},_buildWrapper=function(){pieces={lightbox:$('<div/>').addClass(options.className).css({zIndex:ips.ui.zIndex()}),imagePanel:$('<div/>').addClass(options.className+'_imagePanel'),commentsPanel:$('<div/>').addClass(options.className+'_commentsPanel').html('').hide(),toolsPanel:$('<div/>').addClass(options.className+'_toolsPanel').html('').hide(),next:$('<a/>').addClass(options.className+'_next').html("<i class='fa-solid fa-angle-right'></i>"),prev:$('<a/>').addClass(options.className+'_prev').html("<i class='fa-solid fa-angle-left'></i>"),close:$('<a/>').addClass(options.className+'_close').html("&times;"),fullSize:$('<a/>').attr('href','#').attr('target','_blank').addClass(options.className+'_fullSize'),metaPanel:$('<div/>').addClass(options.className+'_meta').hide()};pieces.lightbox.append(pieces.imagePanel.append(pieces.next).append(pieces.prev).append(pieces.fullSize)).append(pieces.metaPanel).append(pieces.commentsPanel).append(pieces.toolsPanel).append(pieces.close);$('body').append(pieces.lightbox);},_getAllImages=function(){if(options.group){var images=$('[data-ipslightbox-group="'+options.group+'"]');}else{var images=$(elem);}
$.each(images,function(i,thisElem){imageCollection.push(_returnImageData(thisElem));});},_returnImageData=function(thisElem){var origImage,largeImage;if(thisElem.tagName!='IMG'){origImage=$(thisElem).find('img').attr('src');}else{origImage=$(thisElem).attr('src');}
if($(thisElem).attr('data-fullURL')){largeImage=$(thisElem).attr('data-fullURL');}else if($(thisElem).is(':is(a, i-lightbox)')&&$(thisElem).attr('href')){largeImage=$(thisElem).attr('href');}
return{elem:thisElem,originalImage:origImage,largeImage:largeImage||origImage,meta:$(thisElem).attr('data-ipsLightbox-meta'),commentsURL:$(thisElem).attr('data-ipsLightbox-commentsURL')};},_buildModal=function(){modal=ips.ui.getModal();modal.css({zIndex:ips.ui.zIndex()});};init();return{destruct:destruct};};}(jQuery,_));;
;(function($,_){ips.createModule('ips.ui.map',function(){const defaults={zoom:2,maxZoom:16,markers:'[]',contentUrl:null};function _mapbox(elem,options){$('head').append("<link rel='stylesheet' type='text/css' media='all' href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css'><link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.css' rel='stylesheet' /><link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.Default.css' rel='stylesheet' />");function handlePopup(e){const popup=e.target.getPopup();const clubID=e.target.options.clubID;ips.getAjax()(options.contentUrl+clubID).done(response=>{popup.setContent(response);popup.update();});}
ips.loader.get(['https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.js']).then(function(){ips.loader.get(['https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/leaflet.markercluster.js']).then(function(){L.mapbox.accessToken=ips.getSetting('mapApiKey');const map=L.mapbox.map(elem.get(0)).setView([45,0],options.zoom).addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));const cluster=new L.MarkerClusterGroup();map.addLayer(cluster);const markers=$.parseJSON(options.markers);for(const id in markers){const marker=L.marker([markers[id].lat,markers[id].long],{icon:L.mapbox.marker.icon({'marker-color':'#0000ff'}),clubID:id,title:markers[id].title,draggable:false});cluster.addLayer(marker);if(options.contentUrl){marker.bindPopup(ips.getString('loading'));marker.on('click',handlePopup);}}
map.fitBounds(cluster.getBounds().pad(0.5));});});}
function _google(elem,options){ips.ui.map.afterGoogleMapsLoaded(()=>{const mapOptions={zoom:options.zoom,maxZoom:options.maxZoom,scrollwheel:false};if(options.zoom){mapOptions.center={lat:45,lng:0};}else{mapOptions.center={lat:30,lng:0};}
const map=new google.maps.Map(elem.get(0),mapOptions);const bounds=new google.maps.LatLngBounds();const infowindow=new google.maps.InfoWindow({content:ips.getString('loading')});const markers=$.parseJSON(options.markers);for(const id in markers){const marker=new google.maps.Marker({position:{lat:markers[id].lat,lng:markers[id].long},map:map,title:markers[id].title,id:id});if(options.contentUrl){marker.addListener('click',function(){infowindow.setContent(ips.getString('loading'))
infowindow.open(map,this);ips.getAjax()(options.contentUrl+this.id).done(function(response){infowindow.setContent(response);});});}
bounds.extend(marker.position);}
map.fitBounds(bounds);})}
let googleMapsState='unloaded';const googleMapsCallbacksQueue=new Set();ips.ui.registerWidget('map',ips.ui.map,['zoom','maxZoom','markers','contentUrl']);return{respond(elem,options){options={...defaults,...options}
const generator={google:_google,mapbox:_mapbox}[ips.getSetting('mapProvider')]
if(ips.getSetting('lazyLoadEnabled')){ips.utils.lazyLoad.observe(elem,{loadCallback(){generator?.(elem,options)}});}else{generator?.(elem,options)}},afterGoogleMapsLoaded(cb){if(!(cb instanceof Function)||googleMapsCallbacksQueue.has(cb)){return;}
if(googleMapsState==='loaded'){cb();}
googleMapsCallbacksQueue.add(cb)
if(googleMapsState==='unloaded'){googleMapsState='loading'
ips.loader.get(['https://maps.googleapis.com/maps/api/js?key='+ips.getSetting('mapApiKey')+'&libraries=places&sensor=false&loading=async']).then(()=>{googleMapsState='loaded'
for(const queuedCallback of googleMapsCallbacksQueue){queuedCallback();}})}}};});}(jQuery,_));;
;(function($,_,undefined){ips.createModule('ips.ui.menu',function(){var defaults={className:'ipsMenu',activeClass:'',closeOnClick:true,closeOnBlur:true,selectable:false,withStem:true,stemOffset:16,stopLinks:false,above:'auto'};var stems=['topLeft','topRight','topCenter','bottomLeft','bottomRight','bottomCenter'];if(!defaults.withStem){defaults.stemOffset=0;}
var _menuRegistry={};var respond=function(elem,options,e){e.preventDefault();var elemID=$(elem).identify().attr('id'),options=_.defaults(options,defaults);if($(elem).attr('data-disabled')||$(elem).is(':disabled')){return;}
if(!$(elem).data('_menuBody')){var menu=_getMenu(elem,elemID,options);$(elem).data('_menuBody',menu);}else{var menu=$(elem).data('_menuBody');}
if(!menu.length){Debug.warn("Couldn't find or build a menu for "+elemID);return;}
$(window).on('resize',function(e){if(menu.is(':visible')){menu.hide();_positionMenu(elem,elemID,options,menu,true);menu.show();}});if(!menu.is(':visible')){_showMenu(elem,elemID,options,menu,e);}else{_hideMenu(elem,elemID,options,menu,false);}},_showMenu=function(elem,elemID,options,menu,e){if(options.closeOnBlur){$(document).on('click.'+elemID,_.partial(_closeOnBlur,elem,menu));}
$(menu).on('closeMenu',_.partial(_hideMenu,elem,elemID,options,menu)).on('mouseenter','.ipsMenu_subItems',_.bind(_showSubMenu,this,elem,elemID,options,menu));$(elem).on('closeMenu',_.partial(_hideMenu,elem,elemID,options,menu,false));menu.get(0).style.opacity=0;menu.show();_positionMenu(elem,elemID,options,menu);menu.get(0).style.opacity='';$(elem).addClass(options.activeClass);$(elem).trigger('menuOpened',{elemID,originalEvent:e,menu});$(elem).each((i,el)=>{$(el).get(0)?.dispatchEvent(new MenuOpenedEvent(elemID,e,menu))})},_showSubMenu=function(elem,elemID,options,menu,e){var menuItem=$(e.currentTarget).find('> a');var subMenu=menuItem.next('.ipsMenu');$(e.currentTarget).on('mouseleave',_.bind(_hideSubMenu,this,elem,elemID,options,menu));var itemPosition=ips.utils.position.getElemPosition(menuItem);var itemSize=ips.utils.position.getElemDims(menuItem);var subMenuSize=ips.utils.position.getElemDims(subMenu);if($('html').attr('dir')=='rtl'){var left=(itemSize.outerWidth-5);var top=menuItem.position()['top']-5;if((itemPosition.viewportOffset.left-subMenuSize.outerWidth-5)<0){if((itemPosition.viewportOffset.right+5+subMenuSize.outerWidth)<=$(window).width()){left=(itemSize.outerWidth+5);}else{left=15-itemPosition.absPos.left;top=menuItem.position()['top']+itemSize.height+15;}}
subMenu.css({left:left+'px',top:top+'px'}).show();}else{var left=(itemSize.outerWidth-5);var top=menuItem.position()['top']-5;if((itemPosition.viewportOffset.left+itemSize.outerWidth+subMenuSize.outerWidth-5)>$(window).width()){if((itemPosition.viewportOffset.left+5-subMenuSize.outerWidth)>=0){left=((subMenuSize.outerWidth*-1)+5);}else{left=($(window).width()-subMenuSize.outerWidth)-itemPosition.absPos.left-15;top=menuItem.position()['top']+itemSize.height+15;}}
subMenu.css({left:left+'px',top:top+'px'}).show();}},_hideSubMenu=function(elem,elemID,options,menu,e){var subMenus=$(e.currentTarget).closest('.ipsMenu_item').find('.ipsMenu');subMenus.hide();},_hideMenu=async function(elem,elemID,options,menu,immediate){if(options.closeOnBlur){$(document).off('click.'+elemID);}
if(!$(menu).is(":visible")){return;}
$(elem).removeClass(options.activeClass);await Promise.all($(menu).get(0).getAnimations().filter(()=>!!immediate).map(animation=>{animation.pending&&animation.cancel();return animation.finished;}));if(!immediate){ips.utils.anim.go('fadeOut fast',menu);await Promise.all($(menu).get(0).getAnimations().map(animation=>animation.finished));}
$(menu).hide();$(elem).off('closeMenu');$(menu).off('closeMenu');$(elem).trigger('menuClosed',{elemID:elemID,menu:menu});},_positionMenu=function(elem,elemID,options,menu,repositioning){ips.utils.position.startCaching();let above=options.above;const element=$(elem).get(0);const menuElement=$(menu).get(0);const{rect:docRect}=ips.utils.position.getElemRectAndStyle(document.documentElement);if(above==='auto'){const{rect}=ips.utils.position.getElemRectAndStyle(element);const{rect:menuRect}=ips.utils.position.getElemRectAndStyle(menuElement);above=(rect.top+menuRect.height>window.innerHeight);}
const positionInfo={trigger:elem,target:menu,center:true,above,stemOffset:{left:options.stemOffset,top:-2}};Object.assign(menuElement.style,{left:menuElement.style.left||'',top:menuElement.style.top||'',});if(menuElement.dataset.originalwidth){Object.assign(menuElement.style,{width:menuElement.dataset.originalwidth+'px'});}
const appendTo=options.appendTo?_getAppendContainer(elem,options.appendTo):undefined;if(options.appendTo&&appendTo?.length){positionInfo.targetContainer=appendTo;}
const menuPosition=ips.utils.position.positionElem(positionInfo);Object.assign(menuElement.style,{left:menuPosition.left+'px',top:menuPosition.top+'px',position:(menuPosition.fixed)?'fixed':'absolute',});ips.utils.position.endCaching(menuElement);const menuDims=ips.utils.position.getElemDims(menu);if(!repositioning){ips.ui.zIndex();}
if((menuDims.width>docRect.clientWidth)||(ips.utils.position.getElemRectAndStyle(menuElement).rect.left<0)){options.noStem=true;let left="10px";if(options.appendTo&&appendTo?.length){left=(10-$(appendTo).get(0).getBoundingClientRect().left)+'px';}
menuElement.dataset.originalwidth=menuDims.width;Object.assign(menuElement.style,{left,width:(docRect.width-20)+'px'})}
_removeExistingStems(menu,options);if(!menuElement.classList.contains(options.className+'_noStem')&&!options.noStem){menuElement.classList.add(options.className+
'_'+
menuPosition.location.vertical+
menuPosition.location.horizontal.charAt(0).toUpperCase()+
menuPosition.location.horizontal.slice(1));}
ips.utils.position.endCaching();},_removeExistingStems=function(menu,options){var stemClasses=[];$.each(stems,function(idx,value){stemClasses[idx]=options.className+'_'+value;});menu.removeClass(stemClasses.join(' '));},_getMenu=function(elem,elemID,options){let menu;if($('#'+options.menuID).length){menu=$('#'+options.menuID);}else if($('#'+elemID+'_menu').length){menu=$('#'+elemID+'_menu');}else if(options.menuContent){menu=buildMenuFromJSON(elem,elemID,options.menuContent);}else{return false;}
if(options.appendTo){var appendTo=_getAppendContainer(elem,options.appendTo);if(appendTo.length){appendTo.append(menu);}}else{ips.getContainer().append(menu);}
$(menu).on('click.'+elemID,_.partial(_menuClicked,elem,elemID,options,menu));$(menu).data('_owner',elem);_menuRegistry[elemID]={elem:elem,options:options,menu:menu};return $(menu);},_closeOnBlur=function(elem,menu,e){if(e?.target?.closest?.('body')!==document.body){return;}
const clickedOnTrigger=function(){if($(e.target).is('[data-ipsMenu]')){return e.target;}else if($(e.target).parent('[data-ipsMenu]')){return $(e.target).parent('[data-ipsMenu]').get(0);}}();$.each(_menuRegistry,function(key,value){var clickInMenu=_clickIsChildOfMenu(e.target,value.elem,value.menu.get(0));if(value.elem){if(clickInMenu||value.elem===clickedOnTrigger||$.contains(value.elem,e.target)){return;}}
if(value.menu.is(':visible')){_hideMenu(value.elem,key,value.options,value.menu,!!clickedOnTrigger);}});},_clickIsChildOfMenu=function(clickTarget,triggerElem,menuElem){if(_.isString($(clickTarget).get(0).className)&&($(clickTarget).get(0).className.startsWith('ui-datepicker')||$(clickTarget).closest('#ui-datepicker-div').length)){return true;}
if(clickTarget==menuElem||$.contains(menuElem,clickTarget)){return true;}
return false;},_menuClicked=function(elem,elemID,options,menu,e){if($(e.target).hasClass(options.className+'_item')){var itemClicked=$(e.target);}else{var itemClicked=$(e.target).parents('.'+options.className+'_item');}
if(itemClicked.length===0){return;}
if(options.stopLinks){e.preventDefault();}
if(itemClicked.hasClass(options.className+'_itemDisabled')||itemClicked.is(':disabled')){return;}
if(options.closeOnClick){if(itemClicked.find('[data-action="ipsMenu_ping"]').length){e.preventDefault();itemClicked.find('[data-action="ipsMenu_ping"]').each(function(){ips.getAjax()($(this).attr('href')).done(function(){$(elem).trigger('menuPingSuccessful',{});});});}
var addItemClicked=function(){itemClicked.addClass(options.className+'_itemClicked');};var removeItemClicked=function(){itemClicked.removeClass(options.className+'_itemClicked');};if(e.button!==1){_.delay(addItemClicked,100);_.delay(removeItemClicked,200);_.delay(_hideMenu,300,elem,elemID,options,menu,false);}}
if(itemClicked.find('[data-role="ipsMenu_selectedText"]').length){$(elem).find('[data-role="ipsMenu_selectedText"]').html(itemClicked.find('[data-role="ipsMenu_selectedText"]').html());}
if(itemClicked.find('[data-role="ipsMenu_selectedIcon"]').length){$(elem).find('[data-role="ipsMenu_selectedIcon"]').replaceWith(itemClicked.find('[data-role="ipsMenu_selectedIcon"]').clone());}
var data={triggerElem:elem,triggerID:elemID,menuElem:$(menu[0]),originalEvent:e};if(options.selectable){_.extend(data,_handleSelectableClick(elem,elemID,options,menu,e));}
if(!_.isUndefined(itemClicked.attr('data-ipsmenuvalue'))){_.extend(data,{selectedItemID:itemClicked.attr('data-ipsmenuvalue')});}
$(elem).trigger('menuItemSelected',data);},_handleSelectableClick=function(elem,elemID,options,menu,e){var thisItem=$(e.target).closest('.'+options.className+'_item');if(!thisItem.length){return;}
if(thisItem.attr('data-noselect')){return;}
if(options.selectable=='radio'){menu.find('.'+options.className+'_itemChecked').removeClass(options.className+'_itemChecked');thisItem.addClass(options.className+'_itemChecked').find('input[type="radio"]').prop('checked',true).change();}else{if(thisItem.hasClass(options.className+'_itemChecked')){thisItem.removeClass(options.className+'_itemChecked').find('input[type="checkbox"]').prop('checked',false).change();}else{thisItem.addClass(options.className+'_itemChecked').find('input[type="checkbox"]').prop('checked',true).change();}}
var selectedItems=menu.find('.'+options.className+'_itemChecked'),selected={};$.each(selectedItems,function(idx,item){selected[$(item).identify().attr('id')]=item;});return{selectedItems:selected};},_getAppendContainer=function(elem,appendTo){const appends=appendTo.split(',');elem=$(elem);for(let append of appends){const selector=append.trim();const jq=elem.closest(selector);if(jq.length){return jq;}
if(selector.startsWith('#')){const jq=$(selector);if(jq.length){return jq;}}}};ips.ui.registerWidget('menu',ips.ui.menu,['className','menuID','closeOnClick','closeOnBlur','menuContent','appendTo','activeClass','selectable','withStem','stemOffset','stopLinks','above'],{lazyLoad:true,lazyEvents:'click'});return{respond};});class MenuOpenedEvent extends Event{constructor(elemID,originalEvent,menu){super('ipsMenuOpened');this.elemID=elemID;this.originalEvent=originalEvent;this.menu=menu}}}(jQuery,_));;
;(function(){"use strict";ips.createModule('ips.ui.offCanvasContent',function(){function respond(elem){let trigger=$(elem).get(0);trigger.addEventListener('click',e=>_loadContent(e,trigger));}
function _loadContent(event,elem){let menuName=elem.getAttribute("aria-controls"),menu=document.getElementById(menuName);$(document).trigger('menuOpened',{elemID:menuName,originalEvent:event,menu:$(menu)});}
ips.ui.registerWidget('offCanvasContent',ips.ui.offCanvasContent);return{respond}});}());;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.pageAction',function(){class PageActionWidget extends ips.ui.BaseWidget{wrapper=null;initialized=false;id="";_checkedItems={};constructor(elem,options){super(elem,options);this._setUpEvents();setTimeout(()=>this.elem.trigger('pageActionReady'))}
reset(){super.reset();this._checkedItems={};this._updateBar();}
_setUpEvents(){this.on('change','input[type="checkbox"][data-actions]',this._toggleCheckbox);this.on('refresh.pageAction',this._refreshPageAction);this.on('addManualItem.pageAction',this._addManualItem);}
_addManualItem(e,data){this._checkedItems[data.id]=data.actions;this._updateBar(true);}
_refreshPageAction(){for(const key in this._checkedItems){if(this.element.querySelector(`input[type="checkbox"][name="${key}"]`)){this.elem.find(`input[type="checkbox"][name="${key}"]`).attr('checked',true).trigger('change');}}}
_toggleCheckbox(e){const checkbox=$(e.currentTarget);if(checkbox.is(':checked')){this._checkedItems[checkbox.attr('name')]=checkbox.attr('data-actions');}else{delete this._checkedItems[checkbox.attr('name')];}
this._updateBar(true);}
_updateBar(doImmediate=false){if(!this.initialized){this._buildActionBar();doImmediate=true;this.initialized=true;}
const possibleValues=this._getActionValues();const size=_.size(this._checkedItems);this._showCorrectButtons(possibleValues);this.wrapper.find('[data-role="count"]').text(ips.pluralize(ips.getString('pageActionText_number'),size));this.wrapper.attr("data-ipspageaction-selected-count",size);if(!size){if(doImmediate){this.wrapper.hide();}else{ips.utils.anim.go('fadeOut fast',this.wrapper);}}else if(this.initialized){if(this.wrapper.is(':visible')){ips.utils.anim.go('pulseOnce fast',this.wrapper);}else{if(doImmediate){this.wrapper.show();}else{ips.utils.anim.go('fadeIn',this.wrapper);}}}}
_showCorrectButtons(possibleValues){this.wrapper.get(0).querySelectorAll('[data-role="actionMenu"], [data-role="actionButton"]').forEach(el=>{let show=false;let action=el.dataset.action;if(el.dataset.role==='actionButton'){if(possibleValues.includes(action)){show=true;}}else{const menuID=this.id+"_"+action+"_menu";document.querySelectorAll(`#${menuID} [data-ipsmenuvalue]`).forEach(menuValItem=>{const menuAction=menuValItem.dataset.ipsmenuvalue;if(possibleValues.includes(menuAction)){show=true;menuValItem.removeAttribute("data-disabled");}else{menuValItem.setAttribute("data-disabled",true);}});}
el.classList.remove('ipsHide');if(show){el.removeAttribute('hidden')}else{el.setAttribute('hidden','')}});}
_selectItem(e){e.preventDefault();this._triggerAction($(e.currentTarget).attr('data-action'));}
_selectMenuItem(e,data=e.detail){e.preventDefault();if(!_.isUndefined(data.originalEvent)){data.originalEvent.preventDefault();}
this._triggerAction(data.selectedItemID);}
_triggerAction(action){const tools=this.elem.find('[data-role="pageActionOptions"]');tools.find('select').val(action);for(const key in this._checkedItems){if(!this.elem.find('input[type="checkbox"][name="'+key+'"]').length&&!this.elem.find('input[type="hidden"][name="'+key+'"]').length){this.elem.append($('<input/>').attr('type','hidden').attr('name',key).attr('data-role',"moderation").val(1));}}
const page=ips.utils.url.getPageNumber('page');if(page!==undefined){const pageNumber=$('<input/>').attr('type','hidden').attr('name','page').attr('value',ips.utils.url.getPageNumber('page'));tools.find('[type="submit"]').before(pageNumber);tools.closest('form').attr('action',tools.closest('form').attr('action')+'&page='+ips.utils.url.getPageNumber('page'));}
tools.find('[type="submit"]').click();}
_buildActionBar(){let content='';const select=this.element.querySelector('[data-role="pageActionOptions"] select');this.id=$(select).identify().attr('id');for(const child of select.querySelectorAll(":scope > *")){if(child.tagName.toLowerCase()==='optgroup'){content+=this._buildOptGroup(child,this.id);}else{content+=this._buildOption(child,this.id);}}
const bar=ips.templates.render('core.pageAction.wrapper',{content,id:this.id,selectedLang:ips.getString('pageActionText')});this.elem.after(bar);this.wrapper=this.elem.next();this.on(this.wrapper,'click','[data-role="actionButton"]',this._selectItem)
this.on(this.wrapper,'menuItemSelected','[data-role="actionMenu"]',this._selectMenuItem);$(document).trigger('contentChange',[this.wrapper]);}
_buildOptGroup(optgroup,id){let content='';for(const option of optgroup.querySelectorAll('option')){content+=ips.templates.render('core.menus.menuItem',{value:option.value,title:option.innerHTML,link:"#"});}
return ips.templates.render('core.pageAction.actionMenuItem',{icon:optgroup.dataset.icon,title:optgroup.getAttribute('label'),id,action:optgroup.dataset.action,menucontent:content});}
_buildOption(option,id){return ips.templates.render('core.pageAction.actionItem',{icon:option.dataset.icon,id,title:option.innerHTML,action:option.value});}
_getActionValues(){const values=new Set();for(const value of Object.values(this._checkedItems)){value.split(" ").forEach(val=>values.add(val));}
return[...values];}
_getCheckedBoxes(){return this.elem.find('input[type="checkbox"][data-actions]:checked');}}
return PageActionWidget.buildModuleAndRegisterWidget('pageAction',[]);});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.pagination',function(){var defaults={ajaxEnabled:true,perPage:25,pageParam:'page',seoPagination:false,};var respond=function(elem,options){options=_.defaults(options,defaults);if(!$(elem).data('_pagination')){$(elem).data('_pagination',paginationObj(elem,_.defaults(options,defaults)));}};ips.ui.registerWidget('pagination',ips.ui.pagination,['ajaxEnabled','perPage','pages','pageParam','seoPagination']);return{respond:respond};});var paginationObj=function(elem,options){var init=function(){if(!options.ajaxEnabled){return;}
elem.on('click','[data-page]',function(e){var targetElem=$(e.currentTarget);$(elem).trigger('paginationClicked',{href:targetElem.attr('href')||'#',hrefTitle:targetElem.attr('title')||'',paginationElem:$(elem),seoPagination:options.seoPagination,pageElem:targetElem,perPage:options.perPage,pageParam:options.pageParam,pageNo:targetElem.attr('data-page'),lastPage:(parseInt(targetElem.attr('data-page'))===parseInt(options.pages)),originalEvent:e||null});});elem.on('menuOpened',function(e,data){$(elem).find('input[type="number"]').focus();});elem.on('submit','[data-role="pageJump"]',function(e){var value=parseInt($(e.currentTarget).find('input[type="number"]').val());var href=$(e.currentTarget).closest('[data-baseURL]').attr('data-baseurl');if(value<1||value>options.pages){ips.ui.alert.show({type:'alert',icon:'warning',message:ips.getString('not_valid_page',[options.pages]),callbacks:{}});return;}
$(elem).trigger('paginationJump',{originalEvent:e||null,href:href||'#',paginationElem:$(elem),seoPagination:options.seoPagination,pageNo:value,perPage:options.perPage,pageParam:options.pageParam,lastPage:(parseInt(value)===parseInt(options.pages))});});};init();return{init:init};};}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.passwordStrength',function(){var defaults={};var respond=function(elem,options){if(!$(elem).data('_passwordStrength')){$(elem).data('__passwordStrength',passwordStrengthObj(elem,_.defaults(options,defaults)));}},destruct=function(elem){var obj=getObj(elem);if(!_.isUndefined(obj)){obj.destruct();}},getObj=function(elem){if($(elem).data('_passwordStrength')){return $(elem).data('_passwordStrength');}
return undefined;};ips.ui.registerWidget('passwordStrength',ips.ui.passwordStrength,['enforced','enforcedStrength','checkAgainstMember','checkAgainstRequest']);return{respond:respond,getObj:getObj,destruct:destruct};});var passwordStrengthObj=function(elem,options){var _popup=null,_passwordBlurred=false,_field=null,_dirty=false,_timer=null,_ajax=ips.getAjax();var init=function(){elem.on('focus','input[type="password"]',_passwordFocus);elem.on('blur','input[type="password"]',_passwordBlur);elem.on('keyup blur','input[type="password"]',_passwordKeyEvent);_field=elem.find('input[type="password"]');_field.after($('<span/>').attr('data-role','validationCheck'));if(_field.val()!==''){_changePassword();}},destruct=function(){if(_timer){clearTimeout(_timer);}
if(_ajax&&_ajax.abort){_ajax.abort();}
elem.off('focus','input[type="password"]',_passwordFocus);elem.off('blur','input[type="password"]',_passwordBlur);elem.off('keyup blur','input[type="password"]',_passwordKeyEvent);},_passwordFocus=function(){if(!elem.is(':visible')){_field.blur();return;}
if(_.isNull(_popup)){_buildAdvicePopup();}
_popup.show();_positionAdvicePopup();_passwordBlurred=false;},_passwordBlur=function(){if(_popup){_popup.hide();}
_passwordBlurred=true;},_clearResult=function(){_field.removeClass('ipsField_error').removeClass('ipsField_success').next('[data-role="validationCheck"]').html('');},_passwordKeyEvent=function(e){if(_timer){clearTimeout(_timer);}
if(_field.val().length>2||e.type!="keyup"){_timer=setTimeout(_changePassword,750);}else{_clearResult();}},_changePassword=function(){var value=_field.val();var resultElem=_field.next('[data-role="validationCheck"]');var wrapper=elem.find('[data-role="strengthInfo"]');var meter=elem.find('[data-role="strengthMeter"]');var text=elem.find('[data-role="strengthText"]');if(_ajax&&_ajax.abort){_ajax.abort();}
if(value.length){_dirty=true;}else{if(!_dirty){return;}}
if(!meter.is(':visible')){ips.utils.anim.go('fadeInDown fast',wrapper);}
_field.addClass('ipsField_loading');var alsoCheckAgainst=new Array;if(options.checkAgainstRequest){var requestNames=JSON.parse(options.checkAgainstRequest);_.each(requestNames,function(value){if(elem.closest('form').find('input[name="'+value+'"]')){alsoCheckAgainst.push(elem.closest('form').find('input[name="'+value+'"]').val());}});}
if(options.checkAgainstMember){var memberValues=JSON.parse(options.checkAgainstMember);_.each(memberValues,function(value){alsoCheckAgainst.push(value);});}
_ajax(ips.getSetting('baseURL')+'?app=core&module=system&controller=ajax&do=passwordStrength',{dataType:'json',data:{input:value,checkAgainstRequest:alsoCheckAgainst},method:'post'}).done(function(response){if(response.result=='ok'){meter.val(response.granular);meter.attr('data-adviceValue',response.score);text.html(ips.getString('strength_'+response.score));if(options.enforced){_clearResult();if(response.score>=parseInt(options.enforcedStrength)){resultElem.hide().html('');_field.addClass('ipsField_success');_field.closest('.ipsFieldRow').removeClass('ipsFieldRow_error').find('.i-color_warning').hide();}else{if(_passwordBlurred){resultElem.show().html(ips.templates.render('core.forms.validateFailText',{message:ips.getString('err_password_strength',{strength:ips.getString('strength_'+options.enforcedStrength)})}));_field.addClass('ipsField_error');}}}}else{resultElem.show().html(ips.templates.render('core.forms.validateFailText',{message:response.message}));_field.removeClass('ipsField_success').addClass('ipsField_error');}}).fail(function(){}).always(function(){_field.removeClass('ipsField_loading');});},_buildAdvicePopup=function(){var text=ips.getString('password_advice');var min=false;if(!_.isNull(_popup)){return;}
if(options.enforced){min=ips.getString('err_password_strength',{strength:ips.getString('strength_'+options.enforcedStrength)});}
var tmpPopup=ips.templates.render('core.forms.advicePopup',{id:elem.identify().attr('id'),min:min,text:text});$('body').append(tmpPopup);_popup=$('body').find('#elPasswordAdvice_'+elem.identify().attr('id'));_popup.css({position:'absolute'});},_positionAdvicePopup=function(){var isRTL=$('html').attr('dir')=='rtl';var position=ips.utils.position.getElemPosition(_field);var fieldWidth=_field.width();var fieldHeight=_field.height();var adviceWidth=_popup.width();var adviceHeight=_popup.height();var windowWidth=$(window).width();var stemOffset=30;_popup.removeClass('cStem_rtl cStem_ltr cStem_above').css({zIndex:ips.ui.zIndex()});if(isRTL&&(position.absPos.left-adviceWidth-stemOffset)>0){_popup.addClass('cStem_rtl').css({top:(position.absPos.top-(stemOffset/2))+'px',left:(position.absPos.left-stemOffset-adviceWidth)+'px'});}else if(!isRTL&&(position.absPos.left+fieldWidth+adviceWidth+stemOffset)<windowWidth){_popup.addClass('cStem_ltr').css({top:(position.absPos.top-(stemOffset/2))+'px',left:(position.absPos.left+fieldWidth+stemOffset)+'px'});}else{_popup.addClass('cStem_above').css({top:(position.absPos.top-(stemOffset/2)-adviceHeight)+'px',left:(position.absPos.left+(fieldWidth/2)-(adviceWidth/2))+'px'});}};init();return{destruct:destruct};};}(jQuery,_));;
;if(navigator.standalone){(function($,_){ips.createModule('ips.ui.pullToRefresh',function(){ips.ui.registerWidget('pullToRefresh',false);});}(jQuery,_));};;
;(function($,_){if(window.matchMedia('(display-mode: standalone)').matches){ips.createModule('ips.ui.pwaLoading',function(){ips.ui.registerWidget('pwaLoading',false);});}}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.quote',function(){var defaults={timestamp:'',userid:0,username:'',contenttype:'',contentclass:'',contentid:0};var respond=function(elem,options){if(elem.data('quoteBuilt')||elem.parents('[data-ipsEditorV5], .tiptap').length){return;}
var existingCitation=elem.children('.ipsQuote_citation');var citation=ips.utils.getCitation(options,true,existingCitation.length?existingCitation.text():ips.getString('editorQuote'));var data={citation:citation,contenturl:options.contentid&&options.contentcommentid?ips.getSetting('baseURL')+"?app=core&module=system&controller=content&do=find&content_class="+options.contentclass+"&content_id="+options.contentid+"&content_commentid="+options.contentcommentid:''};var citation=ips.templates.render('core.editor.citation',data);if(existingCitation.length){existingCitation.replaceWith(citation);}else{elem.prepend(citation);}
elem.find('> .ipsQuote_citation').on('click',_toggleQuote);elem.find('> .ipsQuote_contents').addClass('ipsClearfix').attr('data-ipsTruncate',true).attr('data-ipsTruncate-expandText',ips.getString('expand_quote'));if(elem.is('blockquote.ipsQuote > blockquote.ipsQuote')){elem.find('> *:not( .ipsQuote_citation )').hide().end().find('> .ipsQuote_citation').removeClass('ipsQuote_open').addClass('ipsQuote_closed');}
elem.trigger('quoteBuilt.quote');elem.data('quoteBuilt',true);$(document).trigger('contentChange',[elem]);},_toggleQuote=function(e){var cite=$(e.currentTarget);var target=$(e.target);if(target.is('a:not( [data-action="toggleQuote"] )')||(target.closest('a').length&&!target.closest('a').is('[data-action="toggleQuote"]'))){return;}
e.preventDefault();if(cite.hasClass('ipsQuote_closed')){ips.utils.anim.go('fadeIn',cite.siblings());cite.removeClass('ipsQuote_closed').addClass('ipsQuote_open');}else{cite.siblings().hide();cite.removeClass('ipsQuote_open').addClass('ipsQuote_closed');}
e.stopPropagation();};ips.ui.registerWidget('quote',ips.ui.quote,['timestamp','userid','username','contentapp','contenttype','contentclass','contentid','contentcommentid']);return{respond:respond};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.rating',function(){var defaults={changeRate:true,canRate:true};var respond=function(elem,options){if(!$(elem).data('_rating')){$(elem).data('_rating',ratingObj(elem,_.defaults(options,defaults)));}};ips.ui.registerWidget('rating',ips.ui.rating,['url','changeRate','canRate','size','value','userRated']);var ratingObj=function(elem,options){var selected=null,max=0,ratingElem=null,userRated=false,loading=false;var init=function(){elem.children().hide();if(options.value){selected=options.value;}else{selected=elem.find('input[type="radio"]:checked').val();}
var maxElem=_.max(elem.find('input[type="radio"]'),function(value){return parseInt($(value).attr('value'));});max=$(maxElem).attr('value');_buildRatingElem();ratingElem.on('mouseenter','li',_enterStar);ratingElem.on('mouseleave','li',_leaveStar);ratingElem.on('click','li',_clickStar);},_buildRatingElem=function(){var content='';for(var i=1;i<=max;i++){if(i<=selected){content+=ips.templates.render('core.rating.star',{value:i,className:'ipsRating_on'});}else if((i-0.5)<=selected){content+=ips.templates.render('core.rating.halfStar',{value:i});}else{content+=ips.templates.render('core.rating.star',{value:i,className:'ipsRating_off'});}}
content=ips.templates.render('core.rating.wrapper',{content:content,status:(options.userRated)?ips.pluralize(ips.getString('youRatedThis'),[options.userRated]):''});elem.append(content);ratingElem=elem.find('.ipsRating');if(options.size){ratingElem.addClass('ipsRating_'+options.size);}},_enterStar=function(e){if((selected!=null&&!options.changeRate)||!options.canRate||loading){return;}
_starActive($(e.currentTarget).attr('data-ratingValue'),true);},_leaveStar=function(e){if((selected!=null&&!options.changeRate)||!options.canRate||loading){return;}
_starActive(selected,false);},_clickStar=function(e){e.preventDefault();if((selected!=null&&!options.changeRate)||!options.canRate||loading){return;}
var value=$(e.currentTarget).attr('data-ratingValue');selected=value;userRated=true;_starActive(value);ips.utils.anim.go('pulseOnce',$(e.currentTarget));elem.find('[data-role="ratingStatus"]').text(ips.pluralize(ips.getString('youRatedThis'),[value]));if(options.url){_remoteRating(value);return;}
elem.find('input[type="radio"]').prop('checked',false).filter('input[type="radio"][value="'+value+'"]').prop('checked',true);elem.trigger('ratingSaved',{value:value});},_starActive=function(value,hover){ratingElem.find('> ul[data-role="ratingList"]').toggleClass('ipsRating_mine',(hover||userRated)).end().find('.ipsRating_half').each(function(){$(this).replaceWith(ips.templates.render('core.rating.star',{value:$(this).attr('data-ratingValue'),className:'ipsRating_off'}));}).end().find('li').removeClass('ipsRating_on').removeClass('ipsRating_hover').addClass('ipsRating_off').end().find('li[data-ratingValue="'+value+'"]').prevAll('li').andSelf().removeClass('ipsRating_off').addClass('ipsRating_on');},_remoteRating=function(value){_setLoading(true);var statusElem=elem.find('[data-role="ratingStatus"]');statusElem.html(ips.templates.render('core.rating.loading'));ips.getAjax()(options.url,{data:{rating:parseInt(value)}}).done(function(response){statusElem.text(ips.getString('rating_saved'));elem.trigger('ratingSaved',{value:value});}).fail(function(jqXHR){statusElem.text(ips.getString('rating_failed'));elem.trigger('ratingFailed',{value:value});}).always(function(){});},_setLoading=function(isLoading){loading=isLoading;ratingElem.toggleClass('ipsRating_loading',isLoading);};init();return{};};return{respond:respond};});}(jQuery,_));;
;(function(){"use strict";ips.createModule('ips.ui.readmore',function(){let respond=function(elem){let el=elem[0];let content=el.querySelector('.iReadMore__content--js');Debug.log(content);}
ips.ui.registerWidget('readmore',ips.ui.readmore,['expandText']);return{respond:respond};});}());;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.truncate',function(){const TRUNCATE_CALLBACK_MAP=new WeakMap();document.addEventListener('ips:truncateCollapse',e=>{if(TRUNCATE_CALLBACK_MAP.has(e.target)){TRUNCATE_CALLBACK_MAP.get(e.target)();TRUNCATE_CALLBACK_MAP.delete(e.target);}},{capture:true});var defaults={expandText:ips.getString('show_more'),deferred:false,deferredClasses:undefined,};var respond=function(elem,options){let el=elem[0];if(el.closest('[data-ipseditorv5],.tiptap')){return;}
const collapseIfNeeded=()=>{delete el.dataset.ipstruncateDeferred;if(el.scrollHeight>el.offsetHeight){if(options.deferred&&options.deferredClasses){for(const cls of options.deferredClasses.split(/\s+/)){el.classList.add(cls);}}
_hideTruncate(elem,_.defaults(options,defaults));}}
if(options.deferred){TRUNCATE_CALLBACK_MAP.set(el,collapseIfNeeded);return;}
collapseIfNeeded();},_hideTruncate=function(elem,options){if(elem.attr('data-truncated')){return;}
var showMore=ips.templates.render('core.truncate.expand',{text:options.expandText});$(elem).after(showMore);var expander=elem.next("[data-action='expandTruncate']");elem.attr('data-truncated',true);expander.on('click',function(e){elem.attr('data-truncate-expanded',true);expander.remove();});};ips.ui.registerWidget('truncate',ips.ui.truncate,['expandText','deferred']);return{respond:respond};});}(jQuery,_));;
;(function($,_,undefined){"use strict";const endCachingDebounced=_.throttle((elem)=>{ips.utils.position.endCaching(elem);},100,{leading:false});ips.createModule('ips.ui.tooltip',function(){let _tooltip=null,_timer=[],_currentElem=null,_showTimeout,_visible=false,_lastOptions={},_mo=new MutationObserver(_.throttle(()=>{if(_currentElem&&_tooltip&&_visible&&!_lastOptions.ajax){let mutations=[];if(_currentElem.getAttribute('title')){mutations.push(()=>_currentElem.removeAttribute("_title"));}
const content=_getContent($(_currentElem),_lastOptions);if(_lastOptions.safe){mutations.push(()=>_tooltip.html(content));}else{mutations.push(()=>_tooltip.text(content));}
if(mutations.length){requestAnimationFrame(()=>mutations.forEach(mutation=>mutation()));}}},30));let _frame;const _ro=new ResizeObserver((entries)=>{const tooltipEntry=entries.find(entry=>entry.target===$(_tooltip).get(0));const tooltipHeight=tooltipEntry?.borderBoxSize[0]?.blockSize||0;const tooltipWidth=tooltipEntry?.borderBoxSize[0]?.inlineSize||0;const tooltipEl=$(_tooltip).get(0);const docBox=document.body.getBoundingClientRect();const mutations=[];for(const entry of entries){if(entry.target===$(_tooltip).get(0)){continue;}
if(entry.target!==_currentElem){_currentElem=entry.target;mutations.push(()=>{_tooltip[0].showPopover();_visible=true;_timer.push(setInterval(_checkForElemPresence,100));setTimeout(()=>$(_currentElem).trigger('tooltipShown'),1);});}
break;}
const anchorBox=_currentElem.getBoundingClientRect();if(!anchorBox.width||!anchorBox.height){Debug.log(`Hiding tooltip because the anchor is not visible`);_hide();return;}
if(tooltipWidth===0||tooltipHeight===0){}else{let top=anchorBox.top-tooltipHeight-docBox.top;if(top<-docBox.top){mutations.push(()=>{tooltipEl.classList.remove('ipsTooltip_top');tooltipEl.classList.add('ipsTooltip_bottom')});top=anchorBox.bottom-docBox.top;}else{mutations.push(()=>{tooltipEl.classList.remove('ipsTooltip_bottom');tooltipEl.classList.add('ipsTooltip_top')});}
const leftRaw=(anchorBox.left+anchorBox.right)/2-tooltipWidth/2-docBox.left;let left=leftRaw;if(leftRaw<10-docBox.left){left=(anchorBox.left+anchorBox.right)/2-9;mutations.push(()=>{tooltipEl.classList.remove('ipsTooltip_right');tooltipEl.classList.add('ipsTooltip_left');});}else if(left>window.innerWidth-tooltipWidth-20-docBox.left){left=(anchorBox.left+anchorBox.right)/2-tooltipWidth+9;mutations.push(()=>{tooltipEl.classList.remove('ipsTooltip_left');tooltipEl.classList.add('ipsTooltip_right');});}else{mutations.push(()=>{tooltipEl.classList.remove('ipsTooltip_left');tooltipEl.classList.remove('ipsTooltip_right');});}
mutations.push(()=>{tooltipEl.style.left=Math.round(left*10)/10+'px';tooltipEl.style.top=Math.round(top*10)/10+'px';});}
if(_frame!==undefined){cancelAnimationFrame(_frame);}
_frame=requestAnimationFrame(()=>{mutations.forEach(mutation=>mutation());})});function respond(elem,options,e){clearTimeout(_showTimeout);if(ips.utils.events.isTouchDevice()){return;}
if(!_tooltip){_createTooltipElement();}
if(e.type==='mouseleave'||e.type==='blur'||e.type==='focusout'){_hide();}else{const content=_getContent(elem,options);if(content){ips.utils.position.startCaching();_showTimeout=setTimeout(()=>{_show(elem,options,content);endCachingDebounced();});}}}
function _show(elem,options,content){elem=$(elem);_lastOptions=options;_tooltip[0].hidePopover();if(options.safe){_tooltip.html(content);}else{_tooltip.text(content);}
if(options.ajax&&!elem.data('_tooltip')){ips.getAjax()(options.ajax).done(response=>{$(elem).data('_tooltip',response);if(options.safe){_tooltip.html(response);}else{_tooltip.text(response);}});}else{_mo.observe(elem.get(0),{attributes:true,subtree:true,characterData:true});}
const element=$(elem).get(0);if(element.hasAttribute('title')){element.setAttribute('_title',element.getAttribute('title'));element.removeAttribute('title');}
_ro.observe($(elem).get(0),{box:'border-box'});_ro.observe($(_tooltip).get(0),{box:'border-box'});}
function _hide(){_mo.disconnect();_ro.disconnect();_tooltip[0].hidePopover();_visible=false;_currentElem=null;if(_timer.length){for(var i=0;i<_timer.length;i++){clearInterval(_timer[i]);}
_timer=[];}}
function _checkForElemPresence(){if(!(_currentElem instanceof Element)||_currentElem.ownerDocument!==document){Debug.log(`Hiding the tooltip because there is no current tooltip anchor, or it has been removed from the document.`);_hide();}}
function _getContent(elem,options){elem=$(elem);if(elem.data('_tooltip')){return elem.data('_tooltip');}
else if(options.label){if(options.json){return $.parseJSON(options.label).join("<br>");}else{return options.label;}}else if(elem.attr('aria-label')){return elem.attr('aria-label');}else if(elem.attr('_title')){return elem.attr('_title');}else if(elem.attr('title')){return elem.attr('title');}}
function _createTooltipElement(){var tooltip=ips.templates.render('core.tooltip',{id:'ipsTooltip'});ips.getContainer().append(tooltip);_tooltip=$('#ipsTooltip');}
ips.ui.registerWidget('tooltip',ips.ui.tooltip,['label','extraClass','safe','json','ajax'],{lazyLoad:true,lazyEvents:'mouseenter mouseleave focus blur'});return{respond};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.ui.spoiler',function(){function respond(elem,options,e){elem.contents().hide();const details=document.createElement('details');for(const attr of[...$(elem).get(0).getAttributeNames()]){try{details.setAttribute(attr,$(elem).get(0).getAttribute(attr));}catch(e){Debug.warn(e);}}
$(elem).get(0).after(details);elem.hide();for(const child of[...$(elem).get(0).childNodes]){details.appendChild(child);}
elem=$(details);var existingHeader=elem.children('.ipsSpoiler_header');var header=ips.templates.render('core.editor.spoilerHeader');if(existingHeader.length){existingHeader.replaceWith(header);}else{elem.prepend(header);}
elem.find('> .ipsSpoiler_header').on('click',_toggleSpoiler);}
function _toggleSpoiler(e){var header=$(e.currentTarget);var target=$(e.target);var spoiler=$(e.target).closest('[data-ipsSpoiler]');if(target.is('a:not( [data-action="toggleSpoiler"] )')||(target.closest('a').length&&!target.closest('a').is('[data-action="toggleSpoiler"]'))){return;}
e.preventDefault();if(header.hasClass('ipsSpoiler_closed')){spoiler.attr('open','');ips.utils.anim.go('fadeIn',header.siblings());header.removeClass('ipsSpoiler_closed').addClass('ipsSpoiler_open').find('span').text(ips.getString('spoilerClickToHide'));$(document).trigger('contentChange',[spoiler]);}else{spoiler.attr('open',null);header.siblings().hide();header.removeClass('ipsSpoiler_open').addClass('ipsSpoiler_closed').find('span').text(ips.getString('spoilerClickToReveal'));}
e.stopPropagation();}
ips.ui.registerWidget('spoiler',ips.ui.spoiler);return{respond:respond}});}(jQuery,_));;
;(($,_)=>{"use strict";const defaults={currentitems:[],canEdit:false}
const _globalExclude=()=>`:not(.ipsTableOfContents *, .ipsEdited, aside *, #elPostFeed [data-ips-hook="postWrapper"] :not([data-first-post] *))`;const _pagebuilderContainer=()=>`:is([data-blockid*="app_cms_Wysiwyg"], [data-blockid*="app_cms_Codemirror"], [data-pageid] [data-widgetarea*="col"] [data-blockid]) > .ipsWidget__content`
const _rootTocTextNodes=()=>`:is(p,h1,h2,h3,h4,h5,h6)`;const _doubleNestedTocTextNodes=()=>`:is(details, .ipsRichTextBox) > :is(summary, .ipsRichTextBox__title)`
const _contentFeedItem=()=>`:is(:is(.ipsRichText--user, .ipsRichText--user > [data-ipstruncate]), [data-role="imageDescription"] .ipsRichText, [data-commentid] [data-ips-hook="postContent"]${ips.getSetting('firstPostID') ? `,[data-ips-hook="topicPostFeed"][data-commentid="${ips.getSetting('firstPostID')}"]` : ''})`;const _baseSelector=()=>`
[data-ips-hook="main"] :is(
:is(
:is(${_contentFeedItem()},${_pagebuilderContainer()}) > ${_rootTocTextNodes()},
:is(${_contentFeedItem()},${_pagebuilderContainer()}) > ${_doubleNestedTocTextNodes()},
[data-ips-hook*="entry__"] [data-ips-hook*="contentTitle__"]
)${_globalExclude()}
)`;class TableOfContents{static _instanceMap=new Map()
static get instanceMap(){return this._instanceMap}
static canEdit=false
static _modified=false;static _hashes={}
static __tree=[]
static get _tree(){return this.__tree;}
static set _tree(value){if(!Array.isArray(value)){throw new TypeError(`The tree is not an array`);}
this.__tree=value
const hash=ips.utils.crypto.md5(JSON.stringify(this.__tree))
if(this._hashes.tree===hash){return}
if(this._modified){this._saveState();this._modified=false;}
this._hashes.tree=hash;this.drawLinks()
for(const instance of this._instanceMap.values()){instance._renderTree()}}
static __treeList=[]
static get _treeList(){return this.__treeList}
static set _treeList(value){if(!Array.isArray(value)){throw new TypeError(`Cannot set a tree list to a non-array value`)}
const selectorsBefore=new Set(value.map(item=>item.selector));this.__treeList=this._cleanItems(value)
if(this.__treeList.some(item=>!selectorsBefore.has(item.selector))){Debug.log('Setting table of contents as modified because an item\'s selector was updated.');this._modified=true;}
const currentHash=ips.utils.crypto.md5(JSON.stringify(this.__treeList))
if(this._hashes.treeList===currentHash){return}
this._hashes.treeList=currentHash
this._tree=this.buildTreeFromItems(this.__treeList)}
constructor(elem,options){this.options=options;this.elem=elem;this._renderTree()}
static inTree(tree,searchId){if(!tree){tree=this._tree}
if(typeof searchId==="string"&&!searchId?.match(/^[a-z0-9\-_]+$/i)){return false;}
for(const{id,children,item}of tree){if(item===searchId||id===searchId||TableOfContents.inTree(children,searchId)){return true}}
return false}
static setItems(items,reset=false){if(items===null){const allOptions=this._getOptionsFromRoot();items=[];let lastLevel,minLevel;allOptions.forEach((option)=>{if(option instanceof HTMLHeadingElement){const headingLevel=parseInt(option.tagName.match(/^h(\d)/i)?.[1]||'1')-1;if(minLevel===undefined||minLevel>headingLevel){minLevel=headingLevel;}
if(lastLevel===undefined){lastLevel=headingLevel;}
const itemDef=this.getItemFromElem(option);itemDef.indentLevel=headingLevel;lastLevel=headingLevel;items.push(itemDef);}});items=items.map(item=>({...item,indentLevel:item.indentLevel-(minLevel||0)}));}
if(reset){delete this._hashes.treeList;delete this._hashes.tree;}
this._treeList=items}
static buildTreeFromItems(items){const _items=[]
const ancestorStack=[]
for(let{selector,indentLevel=0,selectorHash}of items){if(!selector){continue;}
const element=document.querySelector(`:is(${selector}):is(${_baseSelector()})`)
if(!element){continue}
indentLevel=Math.round(Math.min(3,Math.max(indentLevel,0)))
selectorHash=element.hasAttribute('id')?element.getAttribute('id'):(selectorHash||ips.utils.md5(selector))
element.setAttribute('id',selectorHash)
const fullText=element.textContent?.trim().slice(0,300).trim();const selectorText=element.textContent.trim().length>150?element.textContent.trim().slice(0,147)+'...':element.textContent.trim()
while(ancestorStack.length>indentLevel){ancestorStack.pop()}
while(ancestorStack.length<indentLevel){ancestorStack.push({title:'',id:'',children:[]})
if(ancestorStack.length>=2){ancestorStack[ancestorStack.length-2].children.push(ancestorStack[ancestorStack.length-1])}}
ancestorStack.push({item:element,title:selectorText,fullText,id:selectorHash,children:[]})
if(ancestorStack.length>1){ancestorStack[ancestorStack.length-2].children.push(ancestorStack[ancestorStack.length-1])}else{_items.push(ancestorStack[0])}}
return _items}
static _cleanItems(items){const bigList=[...document.querySelectorAll(`:is(${_baseSelector()}):is(${items.map(item => `:is(${item.selector})`).join(',')})`)]
const sorted=items.map(item=>({...item,element:document.querySelector(`:is(${_baseSelector()}):is(${item.selector})`)})).filter(({element})=>bigList.includes(element)).sort((a,b)=>bigList.indexOf(a.element)-bigList.indexOf(b.element))
return sorted.map((item,i)=>{if(item.element instanceof Element){item.selector=this.createSelector(item.element);}
delete item.element;if(item.indentLevel){if(i===0){item.indentLevel=0;}else if(item.indentLevel-1>(sorted[i-1].indentLevel||0)){item.indentLevel=(sorted[i-1].indentLevel||0)+1;}}
return{...item}})}
_getTreeHTML(tree){const children=tree.children.map(child=>`<li>${this._getTreeHTML(child)}</li>`)
const encodeHTMLEntities=text=>{const t=document.createElement('textarea');t.innerText=text;return t.innerHTML.replaceAll('"','&quot;');}
if(children.length&&(!tree.id||!tree.title)){return`
<div class="ipsTableOfContents__wrapper">
<ul>
${children.join('\n')}
</ul>
</div>`}else if(tree.id&&tree.title&&children.length){return`
<details class="ipsTableOfContents__expandable" >
<summary class="">
<span data-item-id="${tree.id}" class="ipsTableOfContents__item">
<a href="#${encodeHTMLEntities(tree.id)}" title="${encodeHTMLEntities(tree.fullText || "")}">${encodeHTMLEntities(tree.title)}</a>
</span>
</summary>
<ul>
${children.join('\n')}
</ul>
</details>`}else if(tree.id&&tree.title){return`<span data-item-id="${tree.id}" class="ipsTableOfContents__item">
<a href="#${encodeHTMLEntities(tree.id)}" title="${encodeHTMLEntities(tree.fullText || "")}">${encodeHTMLEntities(tree.title)}</a>
</span>`}
return''}
_renderTree(){if(!TableOfContents._tree.length){this.elem.closest('.ipsWidget').ipsHide();}else{this.elem.closest('.ipsWidget').ipsShow()
const contentArea=this.elem.querySelector('.ipsTableOfContents__content')
contentArea.classList.remove('ipsLoading','ipsLoading--small','ipsWidget__padding')
contentArea.innerHTML=''
for(const tree of TableOfContents._tree){contentArea.innerHTML+=this._getTreeHTML(tree)}}
$("#ipsLayout_sidebar").trigger('managingFinished.widgets')}
static _positionLinkOptions(linkOptions,root){linkOptions.style.zIndex=linkOptions.style.zIndex||`${ips.ui.zIndex() - 1}`;linkOptions.style.top=(((root.getBoundingClientRect().top+root.getBoundingClientRect().bottom-linkOptions.getBoundingClientRect().height)/2)-document.body.getBoundingClientRect().top)+'px'
linkOptions.style.left=(root.getBoundingClientRect().left-(linkOptions.getBoundingClientRect().width)-document.body.getBoundingClientRect().left)+'px'}
static _getOptionsFromRoot(root){this.__tempRoot=root?.parentElement||root;const options=this.options;delete this.__tempRoot;return options;}
static drawLinks(root){for(const el of this._getOptionsFromRoot(root instanceof Element?root:undefined)){if(!this._linkOptions.has(el)){if(TableOfContents.inTree(undefined,el)||this.canEdit){try{el.classList.add('ipsTableOfContents__link')
const dummy=document.createElement('div')
dummy.innerHTML=ips.templates.render('tableOfContents.linkOptions',{canEdit:this.canEdit,id:this._generateId(el)})
const linkOptions=dummy.children[0]
document.body.appendChild(linkOptions)
this._positionLinkOptions(linkOptions,el)
window.addEventListener('resize',()=>this._positionLinkOptions(linkOptions,el))
window.addEventListener('scroll',()=>this._positionLinkOptions(linkOptions,el))
let inEl=false,inLinkOptions=false;const debouncedClose=_.debounce(()=>{if(!inLinkOptions&&!inEl){linkOptions.classList.remove('ipsTableOfContents__linkOptions--visible')}},30)
el.addEventListener('mouseenter',()=>{const box=el.getBoundingClientRect()
if(!box){return;}
const container=el.closest('.cWidgetContainer--carousel')?.getBoundingClientRect()
if(container&&(container.left>box.left||container.right<(box.left+box.right)/2)){return}
inEl=true
linkOptions.classList.add('ipsTableOfContents__linkOptions--visible')
this._positionLinkOptions(linkOptions,el)})
linkOptions.addEventListener('mouseenter',()=>{inLinkOptions=true})
el.addEventListener('mouseleave',()=>{inEl=false
debouncedClose()})
linkOptions.addEventListener('mouseleave',()=>{inLinkOptions=false
debouncedClose()})
linkOptions.querySelector('[data-role="add"]')?.addEventListener('click',()=>this._addElement(el))
linkOptions.querySelector('[data-role="remove"]')?.addEventListener('click',()=>this._removeElement(el))
linkOptions.querySelector('[data-role="increment"]')?.addEventListener('click',()=>this._incrementIndent(el))
linkOptions.querySelector('[data-role="decrement"]')?.addEventListener('click',()=>this._decrementIndent(el))
linkOptions.querySelector('[data-role="link"]')?.addEventListener('click',()=>{const fakeElement=document.createElement('span')
fakeElement.innerHTML=window.location.href.toString().split('#')[0]+`#${el.getAttribute('id')}`
document.body.appendChild(fakeElement)
const currentSelection=[]
for(let i=0;i<document.getSelection().rangeCount;i++){currentSelection.push(document.getSelection().getRangeAt(i))}
const range=document.createRange()
range.setStart(fakeElement,0)
range.setEnd(fakeElement,fakeElement.childNodes.length)
document.getSelection().removeAllRanges()
document.getSelection().addRange(range)
try{document.execCommand('copy')
ips.ui.flashMsg.show(ilang`copied`)}catch(e){}
document.getSelection().removeAllRanges()
fakeElement.remove()
for(const range of currentSelection){document.getSelection().addRange(range)}})
linkOptions.addEventListener('remove',e=>{e.stopPropagation()
this._linkOptions.delete(el)
linkOptions.remove()})
this._linkOptions.set(el,linkOptions)
dummy.remove()}catch(e){e.message='Failed to create a table of contents link!\n\n'+e.message
Debug.warn(e)}}}}
this._updateCurrentItems()
if(window.location.href.split('#')[1]&&document.querySelector(`.ipsTableOfContents__link#${window.location.href.split('#')[1]}`)){setTimeout(async()=>{document.querySelectorAll(`#${window.location.href.split('#')[1]},[data-item-id="${window.location.href.split('#')[1]}"]`).forEach(el=>{let details=el.closest('details')
while(details){details.setAttribute('open','')
details=details.parentElement?.closest('details')}})
await new Promise(resolve=>setTimeout(resolve,10))
document.getElementById(window.location.href.split('#')[1]).scrollIntoView({behavior:'smooth'})},10)}}
static _updateCurrentItems(tree=null){const isRoot=tree===null;tree=tree||this._tree
const visibleElements=new Set();for(let i=0;i<tree.length;i++){const{item,children,id}=tree[i]
if(item instanceof Element){const linkItem=this._linkOptions.get(item)
visibleElements.add(item)
if(linkItem){linkItem.querySelectorAll('[data-role="add"]').ipsHide()
linkItem.querySelectorAll('[data-role="remove"], [data-role="link"], .ipsTableOfContents__incrementOptions').ipsShow()
const treeItem=this._treeList.find(el=>(document.querySelector(`:is(${el.selector}):is(${_baseSelector()})`)===item));if(isRoot&&i===0){linkItem.querySelector(`.ipsTableOfContents__incrementOptions`)?.ipsHide()}else{linkItem.querySelector(`.ipsTableOfContents__incrementOptions`)?.ipsShow()
if(treeItem?.indentLevel<=0){linkItem.querySelector(`[data-role="decrement"]`)?.ipsDisable()}else{linkItem.querySelector(`[data-role="decrement"]`)?.ipsEnable()}
if(treeItem?.indentLevel>=3||i===0){linkItem.querySelector(`[data-role="increment"]`)?.ipsDisable()}else{linkItem.querySelector(`[data-role="increment"]`)?.ipsEnable()}}
linkItem.querySelector('[data-role="link"]').setAttribute('href',`#${id}`)}
item.setAttribute('id',id)}
this._updateCurrentItems(children).forEach(item=>visibleElements.add(item))}
if(!arguments[0]){for(const item of this.options){if(visibleElements.has(item)){continue;}
item.setAttribute('id',this._generateId(item))
const linkItem=this._linkOptions.get(item)
if(linkItem instanceof HTMLElement){linkItem.querySelectorAll(`[data-role="add"]`).ipsShow()
linkItem.querySelectorAll('[data-role="remove"], [data-role="link"], .ipsTableOfContents__incrementOptions').ipsHide()}}}
return visibleElements}
static _generateId(element){const clone=element.cloneNode(true)
const innerText=clone.innerText;clone.remove();return encodeURIComponent(innerText.trim().replaceAll(/[^a-z0-9A-Z]+/g,'_').replaceAll(/(^_)|(_$)/g,''))+'__'+ips.utils.crypto.md5Short(this.createSelector(element))}
static _linkOptions=new Map()
static createSelector(element){let selector=element.tagName.toLowerCase()+`:nth-child(${[...element.parentElement.children].indexOf(element) + 1})`
element=element.parentElement
while(element instanceof Element&&element?.parentElement&&element.parentElement.closest('[data-ips-hook="main"]')){if(element.dataset.blockid?.match(/^(?:app|plugin)_[a-z0-9]{3,}_[a-z0-9]+_[a-z0-9]{6,8}$/i)){selector=`[data-blockid="${element.dataset.blockid}"] > ${selector}`
break;}
if(element.getAttribute('id')==='elCmsPageWrap'){selector=`${element.tagName.toLowerCase()}${element.hasAttribute('id') ? `#${element.getAttribute('id')}` : ''} > ${selector}`
break;}
if(element.dataset.ipsHook){selector=`[data-ips-hook="${element.dataset.ipsHook}"] > ${selector}`
break;}
if(element.matches(".ipsRichText.ipsRichText--user")){selector=`.ipsRichText.ipsRichText--user > ${selector}`;break;}
let nthChild=`:nth-child(${[...element.parentElement.children].indexOf(element) + 1})`
selector=`${element.tagName.toLowerCase()}${element.hasAttribute('id') ? `#${element.getAttribute('id')}` : ''}${nthChild} > ${selector}`
element=element.parentElement}
return selector}
static get options(){const options=[...(this.__tempRoot instanceof Element?this.__tempRoot:document).querySelectorAll(_baseSelector())].map(el=>el.tagName.toLowerCase()==='details'?el.querySelector(':scope > summary'):el).filter(el=>{if(!el.textContent?.trim()){return false;}
return el.matches?.('h1,h2,h3,h4,h5,h6')||el.textContent.trim().length<100;});return options;}
static getItemFromElem(element){return{selector:this.createSelector(element),selectorHash:this._generateId(element),indentLevel:0}}
static _addElement(element){for(const item of this._treeList){if(element===document.querySelector(`:is(${item.selector}):is(${_baseSelector()})`)){return}}
const newItem=this.getItemFromElem(element)
this._modified=true;this._treeList=this._cleanItems([...this._treeList,newItem])}
static _removeElement(idOrElement){const element=idOrElement instanceof Element?idOrElement:document.querySelector(`:is(${_baseSelector()}):is(#${idOrElement})`)
const list=this._treeList
for(let idx=0;idx<list.length;idx++){const item=list[idx]
if(document.querySelector(`:is(${_baseSelector()}):is(${item.selector})`)===element){list.splice(idx,1)
this._modified=true
this._treeList=list;return;}}}
static _incrementIndent(idOrElement){const treeList=this._treeList
for(let i=0;i<treeList.length;i++){if(treeList[i].selectorHash===idOrElement||(idOrElement instanceof Element&&document.querySelector(`:is(${_baseSelector()}):is(${treeList[i].selector})`)===idOrElement)){this._modified=true;treeList[i].indentLevel=Math.max(0,Math.min(3,(treeList[i].indentLevel||0)+1))
this._treeList=[...treeList]
return}}}
static _decrementIndent(idOrElement){const treeList=this._treeList
for(let i=0;i<treeList.length;i++){if(treeList[i].selectorHash===idOrElement||(idOrElement instanceof Element&&document.querySelector(`:is(${_baseSelector()}):is(${treeList[i].selector})`)===idOrElement)){this._modified=true;treeList[i].indentLevel=Math.max(0,Math.min(3,(treeList[i].indentLevel||0)-1))
this._treeList=[...treeList]
return}}}
static async _saveState(){const widget=document.querySelector(`[data-blockid*="app_core_tableofcontents_"]`)
const blockID=widget.dataset.blockid.split('_').pop()
await ips.fetch('/',{method:'post',data:{app:'core',module:'system',controller:'ajax',do:'updateTableOfContents',pageArea:widget.closest('[data-widgetarea]').dataset.widgetarea,blockID,...this.getContentContext(),items:JSON.stringify(this._treeList)}})
this._modified=false;}
static getContentContext(){const context={pageID:window.ips?.getSetting?.('pageID')||parseInt(document.querySelector(`#elCmsPageWrap[data-pageid]`)?.dataset.pageid)||'',pageElse:document.body.dataset.pageid||document.body.dataset.id||'',pageApp:document.body.dataset.pageapp,pageModule:document.body.dataset.pagemodule,pageController:document.body.dataset.pagecontroller,pageContentClass:document.body.dataset.contentclass||null};['pageApp','pageModule','pageController'].forEach(prop=>{if(!context[prop]||typeof context[prop]!=='string'){throw new TypeError(`Cannot determine the ${prop} for the table of contents`);}});return context;}
static openDetailsInWidgets(){const currentId=window.location.href.split('#')[1]?.match(/^.*[^_]__([a-f0-9]{0,6})$/i)?.[1]
if(!currentId)return;for(const item of this._treeList){const el=document.querySelector(`.ipsTableOfContents__link:is(${_baseSelector()}):is(${item.selector})`)
if(el&&el.getAttribute('id')?.endsWith(`__${currentId}`)){const id=el.getAttribute('id')
document.querySelectorAll(`.ipsTableOfContents__root [data-item-id="${id}"]`).forEach(el=>{let details=el.closest('details')
while(details){details.setAttribute('open','')
details=details.parentElement?.closest('details')}})
break;}}}}
window.addEventListener('popstate',()=>{TableOfContents.openDetailsInWidgets()})
let lastItems;ips.createModule('ips.ui.tableOfContents',function(){ips.ui.registerWidget('tableOfContents',ips.ui.tableOfContents,[...Object.keys(defaults)])
return{respond(elem,options){const realElem=$(elem).get(0)
if(realElem.closest('.pageBuilderRoot')){return;}
options={...defaults,...options}
TableOfContents.canEdit=!!options.canEdit
if(realElem&&!TableOfContents.instanceMap.has(realElem)){if(!Array.isArray(options.currentitems)){if(typeof options.currentitems==='string'){try{options.currentitems=JSON.parse(atob(options.currentitems))
if(!Array.isArray(options.currentitems)&&options.currentitems!==null){throw new TypeError();}
lastItems=options.currentitems;TableOfContents.setItems(options.currentitems)}catch(e){options.currentitems=[]}}else{options.currentitems=defaults.currentitems}}else{lastItems=options.currentitems;TableOfContents.setItems(options.currentitems)}
TableOfContents.instanceMap.set(realElem,new TableOfContents(realElem,options))}
return TableOfContents.instanceMap.get(realElem)},refreshElems(){if(Array.isArray(lastItems)||lastItems===null){TableOfContents.setItems(lastItems,true);}},getInstance(elem){if(TableOfContents.instanceMap.has($(elem).get(0))){return TableOfContents.instanceMap.get($(elem).get(0))}
return null;},createSelector(elem){return TableOfContents.createSelector(elem)},getOptions(){return TableOfContents.options},getContext(){return TableOfContents.getContentContext()}}})})(jQuery,_);
;(function($,_){"use strict";ips.createModule('ips.ui.tabbar',function(){const defaults={itemSelector:'.ipsTabs__tab',activeClass:false,loadingClass:'ipsLoading ipsTabs_loadingContent',panelClass:'ipsTabs__panel',updateURL:true,updateTitle:false,disableNav:false};ips.ui.registerWidget('tabbar',ips.ui.tabbar,['contentArea','itemSelector','activeClass','loadingClass','disableNav','panelClass','updateURL','updateTitle']);return{respond(elem,options){if(!$(elem).data('_tabbar')){$(elem).data('_tabbar',tabBarObj(elem,_.defaults(options,defaults)));}}};});function tabBarObj(elem,options){const rawElem=$(elem).get(0);const tabs=$(elem).find(options.itemSelector);let barId=rawElem.id;let active;let ajaxObj;function init(){if(!barId){barId=$(rawElem).identify().attr('id');}
if(!options.contentArea||!$(options.contentArea).length){options.contentArea='#'+$(rawElem).next().identify().attr('id');}
if(!tabs.length){Debug.warn("No tabs found in tab bar"+barId);return;}
active=_getActiveTab();_initializeActive();$(elem).on('click',options.itemSelector,_handleTabClick);let tabbar=elem[0],tablist=tabbar.querySelector('[role="tablist"]'),scrollers=tabbar.querySelector('[data-role="tabScrollers"]');if(scrollers){scrollers.addEventListener("click",e=>_handleScrollerClick(e,tablist));let scrollerObserver=new IntersectionObserver(tabs=>tabs.forEach(tab=>tabbar.querySelector(`[data-direction="${tab.target.matches(':first-child') ? 'prev' : 'next'}"]`).hidden=tab.intersectionRatio>.99),{root:tablist,threshold:0.99});tablist.querySelectorAll(':scope > :first-child, :scope > :last-child').forEach(el=>{scrollerObserver.observe(el)});}}
function _handleScrollerClick(e,tablist){let direction=e.target.closest('button').getAttribute("data-direction"),currentScroll=tablist.scrollLeft,listWidth=tablist.offsetWidth/2;if(direction==="prev"){listWidth=-listWidth;}
tablist.scrollTo({left:currentScroll+listWidth,behavior:"smooth"})}
function _handleTabClick(e){if(options.disableNav){return;}
e.preventDefault();if($(this).attr('aria-selected')==='true'){return;}
let thisId=$(this).identify().attr('id'),thisContent=$('#'+$(this).attr('aria-controls'));if(!thisContent.length){thisContent=$('#'+thisId+'_panel');}
if(!thisContent.length){thisContent=_createTabPanel(thisId);_loadContent(this,thisContent).done(()=>_switchTab(thisId)).fail(()=>Debug.log('failed'));}else{_hideAllPanels();_switchTab(thisId);}
_updateURL(thisId);}
function _switchTab(tabId){_hideAllPanels();const thisContent=$('#'+tabId+'_panel'),thisContentParent=document.querySelector(elem[0].getAttribute("data-ipstabbar-contentarea"));thisContent.removeAttr('hidden');$(elem).trigger('tabShown',{barID:barId,tabID:tabId,tab:active,panel:thisContent});$(document).trigger('contentChange',[thisContent]);if(elem[0].matches(".ipsTabs--sticky")&&thisContentParent&&window.scrollY>thisContentParent.offsetTop){thisContentParent.scrollIntoView({behavior:"smooth"});}
active=$('#'+tabId);_makeTabActive(active);$(elem).trigger('tabChanged',{barID:barId,tabID:tabId,tab:active,panel:thisContent});}
function _updateURL(tabId){if(!options.updateURL){return;}
const tabLink=$(`#${tabId}`);const href=tabLink.attr('href');const title=(options.updateTitle&&tabLink.attr('title'))?tabLink.attr('title'):document.title;if(!_.isEmpty(href)&&!href.startsWith('#')){ips.utils.history.replaceState({},'ips.ui.tabbar',href);document.title=title
ips.utils.analytics.trackPageView(href);}}
function _getActiveTab(){const activeTab=elem.find('[aria-selected="true"]');if(activeTab.length){return activeTab.get(0);}
return $(elem).find(options.itemSelector).first();}
function _initializeActive(){const activeId=$(active).identify().attr('id');if(!$('#'+activeId+'_panel').length){if($(options.contentArea).children().length){$(options.contentArea).wrapInner(_createTabPanel(activeId,true));_switchTab(activeId);}else{var newPanel=_createTabPanel(activeId);_loadContent(active,newPanel).done(function(){_switchTab(activeId);});}}else{_switchTab(activeId);}}
function _makeTabActive(activeTab){$(elem).find(options.itemSelector).attr('aria-selected','false');if(options.activeClass){$(elem).find(options.itemSelector).removeClass(options.activeClass);}
$(activeTab).attr('aria-selected','true');if(options.activeClass){$(activeTab).addClass(options.activeClass);}}
function _loadContent(tab,container){let url;const deferred=$.Deferred();_hideAllPanels();if($(tab).attr('data-tabURL')){url=$(tab).attr('data-tabURL');}else{url=$(tab).attr('href');}
$(options.contentArea).addClass(options.loadingClass);ajaxObj=ips.getAjax();ajaxObj(url).done(response=>{$(container).html(response);deferred.resolve();}).fail(()=>window.location=$(tab).attr('href')).always(()=>$(options.contentArea).removeClass(options.loadingClass));return deferred.promise();}
function _hideAllPanels(){$(options.contentArea).find('> .'+options.panelClass).attr('hidden','');}
function _createTabPanel(tabId,noAppend=false){const newPanel=$('<div/>').attr({'id':tabId+'_panel'}).addClass(options.panelClass).attr({'role':'tabpanel'}).attr({'aria-labelledby':tabId});if(!noAppend){$(options.contentArea).append(newPanel);}
return newPanel;}
init();return{init};}}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils',function(options){var argsToArray=function(obj){return Array.prototype.slice.call(obj);},uppercaseFirst=function(fromString){return fromString.charAt(0).toUpperCase()+fromString.slice(1);},getIDsFromList=function(list){if(!list){return'';}
if(!_.isArray(list)){list=list.toString().split(',');}
list=_.compact(list);if(!list.length){return false;}
return _.map(list,function(val){return'#'+val;}).join(',');},getCitation=function(data,html,defaultValue){let citation=defaultValue||ips.getString('editorQuote');if(data.username){let username=data.username;if(html&&data.userid&&ips.getSetting('viewProfiles')){username=ips.templates.render('core.editor.citationLink',{baseURL:ips.getSetting('baseURL'),userid:data.userid,username:data.username});}else{username=_.escape(username);}
if(data.timestamp){citation=ips.getString('editorQuoteLineWithTime',{date:ips.utils.time.readable(data.timestamp),username:username});}else{citation=ips.getString('editorQuoteLine',{username:username});}}
return citation;},escapeRegexp=function(toEscape){return toEscape.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");},urlBase64ToUint8Array=function(base64String){var padding='='.repeat((4-base64String.length%4)%4);var base64=(base64String+padding).replace(/\-/g,'+').replace(/_/g,'/');var rawData=window.atob(base64);var outputArray=new Uint8Array(rawData.length);for(var i=0;i<rawData.length;++i){outputArray[i]=rawData.charCodeAt(i);}
return outputArray;};return{argsToArray:argsToArray,uppercaseFirst:uppercaseFirst,getIDsFromList:getIDsFromList,getCitation:getCitation,escapeRegexp:escapeRegexp,urlBase64ToUint8Array:urlBase64ToUint8Array};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.utils.search',function(){const nonHumanReadableRegex=/[^\p{L}\p{N}\p{Emoji_Presentation}]/u
class TrieNode{constructor(){this.size=0
this.children=new Map();this.values=new Set();}
static fixTerm(term){return stripAccents(term.toLowerCase().replaceAll(new RegExp(nonHumanReadableRegex,nonHumanReadableRegex.flags+'g'),''))}
search(term){term=TrieNode.fixTerm(term)
if(term===''){const ret=new Set(this.values);for(const child of this.children.values()){child.search('').forEach(item=>ret.add(item))}
return ret;}
const firstChar=term.substring(0,1),childTerm=term.substring(1)
if(this.children.has(firstChar)){return this.children.get(firstChar).search(childTerm)}
return new Set();}
addTerm(term,values=[]){term=TrieNode.fixTerm(term)
if(term===''){const startSize=this.values.size
for(const value of values){this.values.add(value)}
const delta=this.values.size-startSize;this.size+=delta;return delta;}
const firstChar=term.substring(0,1)
const childTerm=term.substring(1)
if(!this.children.has(firstChar)){this.children.set(firstChar,new TrieNode())}
const delta=this.children.get(firstChar).addTerm(childTerm,values)
this.size+=delta;return delta;}}
const staticCache=new Map();function stripAccents(str){return str.normalize("NFD").replace(/[\u0300-\u036f]/g,"");}
return{addTerm(tree,term,values=[]){if(!staticCache.has(tree)){staticCache.set(tree,new TrieNode())}
const trie=staticCache.get(tree)
let added=0;const components=term.toLowerCase().split(nonHumanReadableRegex);for(let i=0;i<components.length;i++){const compoundTerm=components.slice(i).join('')
added+=trie.addTerm(compoundTerm,values);}
return added;},search(tree,term){if(staticCache.has(tree)){return staticCache.get(tree).search(term)}
return new Set();},getSize(tree){if(staticCache.has(tree)){return staticCache.get(tree).size}
return 0;},fixTerm(term){return TrieNode.fixTerm(term)},stripAccents}})}(jQuery,_));
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.selection',function(){var getSelectedText=function(querySelector,container){var text='';var container=container.get(0);var selection=getSelection();if(selection.isCollapsed){return'';}
if(selection.rangeCount>0){var range=selection.getRangeAt(0);var clonedSelection=range.cloneContents().querySelector(querySelector);for(var i=0;i<selection.rangeCount;++i){if(!_isChild(selection.getRangeAt(i).commonAncestorContainer,container)){return'';}}
if(clonedSelection){clonedSelection.querySelectorAll(`.ipsCode[data-ips-text-highlighted="yes"]`).forEach(element=>{const text=element.innerText;element.innerHTML=''
element.innerText=text;})
text=clonedSelection.innerHTML;}else{clonedSelection=range.cloneContents();var startNode=selection.getRangeAt(0).startContainer.parentNode;if(_isChild(startNode,container)){var div=document.createElement('div');div.appendChild(clonedSelection);clonedSelection.querySelectorAll(`.ipsCode[data-ips-text-highlighted="yes"]`).forEach(element=>{const text=element.innerText;element.innerHTML=''
element.innerText=text;})
text=div.innerHTML;}}
return text;}else if(document.selection){return document.selection.createRange().htmlText;}
return'';};var getCommonAncestor=function(){var selection=getSelection();if(selection.isCollapsed){return false;}
var range=selection.getRangeAt(0);return $(range.commonAncestorContainer);};var getRange=function(container){var selection=getSelection();if(selection.isCollapsed){return false;}
var range=selection.getRangeAt(0);var ancestor=$(range.commonAncestorContainer);if(ancestor!=container&&!$(range.commonAncestorContainer).closest(container).length){return{type:'outside',range:range};}
return{type:'inside',range:range};};var getSelection=function(){return(window.getSelection)?window.getSelection():document.getSelection();};var _isChild=function(child,parent){if(child===parent){return true;}
var current=child;while(current){if(current===parent){return true;}
current=current.parentNode;}
return false;};return{getSelectedText:getSelectedText,getSelection:getSelection,getRange:getRange,getCommonAncestor:getCommonAncestor};});}(jQuery,_));;
(function($,_,undefined){"use strict";ips.createModule("ips.utils.serviceWorker",function(){const SERVICE_WORKER_URL=ips.getSetting("baseURL")+"index.php?app=core&module=system&controller=serviceworker&v="+ips.getSetting("jsAntiCache");const supported="serviceWorker"in navigator;const registerServiceWorker=(type)=>{return navigator.serviceWorker.register(`${SERVICE_WORKER_URL}&type=${type}`).then((registration)=>{Debug.log("ServiceWorker registration successful with scope: ",registration.scope);return registration;}).catch((err)=>{Debug.log("ServiceWorker registration failed: ",err);});};const getRegistration=()=>{return navigator.serviceWorker.ready;};return{registerServiceWorker,supported,getRegistration,};});})(jQuery,_);;
(function($,_){"use strict";ips.createModule("ips.utils.sockets",function(){let socketIo;let pingInterval;let refreshToken;let refreshInterval;let refreshTokenUsed=false;let connected=false;function init(){if(!enabled()){return;}
ips.loader.get([`${ips.getSetting('socketUrl')}/socket.io/socket.io.min.js`]).then(function(){initializeSocketIo();});}
function enabled(){let res=!!(ips.getSetting('memberID')&&ips.getSetting('socketEnabled')&&ips.getSetting('page_token'));return res;}
function initializeSocketIo(){if(connected){return;}
socketIo=io(`${ips.getSetting('socketUrl')}/site-${ips.getSetting('siteId')}`,{transports:['websocket'],forceNew:true,multiplex:false,query:{token:ips.getSetting('page_token'),ipsVersion:"v5"}});socketIo.on('connect',_eventConnect(socketIo));socketIo.on('message',_eventMessage);socketIo.on('ping',function(){socketIo.emit('pong');});socketIo.on('ping_interval',interval=>{interval=Number(interval);if(interval&&Number.isInteger(interval)&&interval>0){clearInterval(pingInterval);pingInterval=setInterval(()=>{socketIo.emit('ping');},interval*0.98);}})
socketIo.on('connect_error',_eventConnectError);socketIo.on('disconnect',_eventDisconnect);socketIo.on('refresh_token',token=>{let isJwt=true;if(typeof token!=="string"){isJwt=false;}else{let components=token.split('.');if(components.length<3){isJwt=false;}else{for(let component of components.slice(0,2)){if(typeof JSON.parse(atob(component))!=='object'){isJwt=false;break;}}}}
if(isJwt){refreshToken=token;refreshTokenUsed=false;Debug.log(`Got a refresh token from Node Services`)}else{Debug.warn(`Got a refresh token that is not a valid JWT from Node Services`)}})}
function useRefreshToken(){let attempts=120;if(refreshInterval){clearInterval(refreshInterval);}
refreshInterval=setInterval(()=>{if(!attempts--||refreshTokenUsed||typeof refreshToken!=='string'||typeof ips.getSetting('page_token')!=='string'||connected){clearInterval(refreshInterval);refreshInterval=undefined;}
if(!refreshToken||typeof refreshToken!=='string'){return}
ips.getAjax()(ips.getSetting('baseURL')+'/?app=core&module=system&controller=ajax&do=refreshRealtimeToken',{data:{page_token:ips.getSetting('page_token'),refresh_token:refreshToken},method:"POST"}).done(function(response){if(response.page_token){refreshTokenUsed=true;ips.setSetting('page_token',response.page_token);socketIo.off();socketIo.disconnect();refreshToken=undefined;initializeSocketIo();}}).fail(()=>Debug.log('Failed to exchange IPS Node Services\' refresh token for access token'));},5000);}
function send(event,data={},attempts=50){if(!enabled()||(!socketIo&&!(attempts>1))){return;}else if(!socketIo){setTimeout(()=>send(event,data,attempts-1),1000);}else{socketIo.emit(event,data);}}
function _eventMessage(data={}){if(typeof data!=='object'||data.event===undefined){Debug.log('Invalid message data');return;}
const{event,type=null,...rest}=data;let eventType='';if(type!==null){eventType=`:${type}`;}
$(document).trigger(`socket.${event}${eventType}`,rest);}
const _eventConnect=socket=>function(){connected=true;clearInterval(refreshInterval);refreshInterval=null;Debug.log("Connected to socket server");$(document).trigger('socket.connected');window.ips.socket=socket;}
function _eventConnectError(){connected=false;Debug.log("Error connecting to socket server");$(document).trigger('socket.error');useRefreshToken()}
function _eventDisconnect(){connected=false;Debug.log("Disconnected from socket server");$(document).trigger('socket.disconnected');if(!refreshInterval){useRefreshToken()}}
return{init,enabled,send,connected(){return connected;}};});})(jQuery,_);;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.time',function(){var _supportsLocale=null;var readable=function(timestamp){var date=new Date();var time=date.getTime()/1000;var dst=0;var now=time+dst;var elapsed=now-timestamp;if(ips.getSetting('relativeDates')){if(elapsed<60){return ips.getString('time_just_now');}else if(elapsed<3600){return ips.pluralize(ips.getString('time_minutes_ago'),Math.floor(elapsed/60));}else if(elapsed<5400){return ips.getString('time_1_hour_ago');}else if(elapsed<86400){return ips.pluralize(ips.getString('time_hours_ago'),Math.floor(elapsed/3600));}}
var dateObj=new Date(timestamp*1000);var format=localeTimeFormat($('html').attr('lang'));var time=formatTime(dateObj,format);var timeParts=ips.getString('time_at')?[localeDateString(dateObj),ips.getString('time_at')]:[localeDateString(dateObj)];timeParts.push(time);return ips.getString('time_other',{time:timeParts.join(' ')});},getDateFromInput=function(input){if(!ips.utils.time.supportsHTMLDate()){try{var thisDate=null;if(input.hasClass('hasDatepicker')){thisDate=input.datepicker('getDate');Debug.log('hasDatePicker: '+thisDate.toString()+'('+thisDate.getTime()+')');}else{thisDate=new Date(input.attr('value'));Debug.log('no datepicker yet: '+thisDate.toString()+'('+thisDate.getTime()+')');}
return thisDate;}
catch(err){return new Date(input.attr('value'));}}
else{return new Date(input.val());}},removeTimezone=function(date){if(ips.utils.time.supportsHTMLDate()){date.setTime(new Date(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),0,0,0).getTime());}
var offset=date.getTimezoneOffset();var adjustedOffset=offset*60000;if(offset>0){date.setTime(date.getTime()+adjustedOffset);}else{date.setTime(date.getTime()-adjustedOffset);}
return date;},isDST=function(){var today=new Date();var jan=new Date(today.getFullYear(),0,1);var jul=new Date(today.getFullYear(),6,1);var stdOffset=Math.max(jan.getTimezoneOffset(),jul.getTimezoneOffset());return today.getTimezoneOffset()<stdOffset;},isValidDateObj=function(d){if(Object.prototype.toString.call(d)!=="[object Date]"){return false;}
return!isNaN(d.getTime());},timestamp=function(){return Date.now();},localeDateString=function(date,options){if(!_.isBoolean(_supportsLocale)){_supportsLocale=_checkLocaleSupport();}
if(_supportsLocale&&_.isObject(options)&&$('html').attr('lang')){return date.toLocaleDateString($('html').attr('lang'),options);}
else if(_supportsLocale&&$('html').attr('lang')){return date.toLocaleDateString($('html').attr('lang'));}else{return date.toLocaleDateString();}},supportsHTMLDate=function(){var i=document.createElement('input');i.setAttribute('type','date');return i.type!=='text';},formatTime=function(dateObj,localeFormat){if(!_.isDate(dateObj)){dateObj=timestamp();}
var formatters={"a":function(d){return ips.getString('day_'+d.getDay()+'_short');},"A":function(d){return ips.getString('day_'+d.getDay());},"d":function(d){var day=d.getDate().toString();return((day.length===1)?'0':'')+day;},"e":function(d){var day=d.getDate().toString();return((day.length===1)?' ':'')+day;},"j":function(d){var day=d.getDate();var month=d.getMonth();if(month>0){day+=31;}
if(month>1){day+=28;if(d.getFullYear()%4==0){day+=1;}}
if(month>2){day+=31;}
if(month>3){day+=30;}
if(month>4){day+=31;}
if(month>5){day+=30;}
if(month>6){day+=31;}
if(month>7){day+=31;}
if(month>8){day+=30;}
if(month>9){day+=31;}
if(month>10){day+=30;}
if(month>11){day+=31;}
return day.toString().padStart(3,'0');},"u":function(d){return d.getDay()+1;},"w":function(d){return d.getDay();},"U":function(d){var firstSundayDate=1;var firstSunday=new Date(d.getFullYear(),0,firstSundayDate,0,0,0,0);while(firstSunday.getDay()!=0){firstSundayDate+=1;firstSunday=new Date(d.getFullYear(),0,firstSundayDate,0,0,0,0);}
var now=d.getTime()/1000;var weekNumber=0;var timestamp=firstSunday.getTime()/1000;while(timestamp<now){weekNumber++;timestamp+=604800;}
weekNumber=weekNumber.toString();return((weekNumber.length===1)?'0':'')+weekNumber;},"V":function(d){var firstApplicableDate=1;var firstApplicable=new Date(d.getFullYear(),0,firstApplicableDate,0,0,0,0);while([2,3,4,5].indexOf(firstApplicable.getDay())==-1){firstApplicableDate+=1;firstApplicable=new Date(d.getFullYear(),0,firstApplicableDate,0,0,0,0);}
var now=d.getTime()/1000;var weekNumber=0;var timestamp=firstApplicable.getTime()/1000;while(timestamp<now){weekNumber++;timestamp+=604800;}
weekNumber=weekNumber.toString();return((weekNumber.length===1)?'0':'')+weekNumber;},"W":function(d){var firstMondayDate=1;var firstMonday=new Date(d.getFullYear(),0,firstMondayDate,0,0,0,0);while(firstMonday.getDay()!=1){firstMondayDate+=1;firstMonday=new Date(d.getFullYear(),0,firstMondayDate,0,0,0,0);}
var now=d.getTime()/1000;var weekNumber=0;var timestamp=firstMonday.getTime()/1000;while(timestamp<now){weekNumber++;timestamp+=604800;}
return weekNumber;},"b":function(d){return ips.getString('month_'+d.getMonth()+'_short');},"B":function(d){return ips.getString('month_'+d.getMonth());},"OB":function(d){return ips.getString('month_'+d.getMonth());},"h":function(d){return ips.getString('month_'+d.getMonth()+'_short');},"m":function(d){var month=d.getMonth()+1;var realMonth=month.toString();return((realMonth.length===1)?'0':'')+realMonth;},"C":function(d){return parseInt((d.getFullYear()/100).toString().substr(0,2));},"g":function(d){var year=d.getFullYear();if(d.getMonth()==0&&d.getDate()<3&&d.getDay()<2){year--;}
return parseInt(year.toString().substr(0,2));},"G":function(d){var year=d.getFullYear();if(d.getMonth()==0&&d.getDate()<3&&d.getDay()<2){year--;}
return year;},"y":function(d){return parseInt(d.getFullYear().toString().substr(0,2));},"Y":function(d){return d.getFullYear();},"H":function(d){var hrs=d.getHours().toString();return((hrs.length===1)?'0':'')+hrs;},"k":function(d){var hrs=d.getHours();return((hrs.length===1)?' ':'')+hrs;},"I":function(d){var hrs=d.getHours();hrs=(hrs>12)?hrs-12:hrs;if(hrs==0){hrs=12;}
return((hrs.length===1)?'0':'')+hrs;},"l":function(d){var hrs=d.getHours();hrs=(hrs>12)?hrs-12:hrs;if(hrs==0){hrs=12;}
return((hrs.length===1)?' ':'')+hrs;},"M":function(d){var mins=d.getMinutes().toString();return((mins.length===1)?'0':'')+mins;},"N":function(d){return d.getMinutes();},"p":function(d){var hrs=d.getHours();if(!_.isFunction(localeFormat.meridiem)){return'';}
return localeFormat.meridiem(hrs,false);},"P":function(d){var hrs=d.getHours();if(!_.isFunction(localeFormat.meridiem)){return'';}
return localeFormat.meridiem(hrs,true);},"r":function(d){var hrs=d.getHours();hrs=(hrs>=12)?hrs-12:hrs;var mins=d.getMinutes().toString();var seconds=d.getSeconds().toString();return((hrs.length===1)?'0':'')+hrs+':'+((mins.length===1)?'0':'')+mins+':'+((seconds.length===1)?'0':'')+seconds;},"R":function(d){var hrs=d.getHours().toString();var mins=d.getMinutes().toString();return((hrs.length===1)?'0':'')+hrs+':'+((mins.length===1)?'0':'')+mins;},"S":function(d){var seconds=d.getSeconds().toString();return((seconds.length===1)?'0':'')+seconds;},"T":function(d){var hrs=d.getHours().toString();var mins=d.getMinutes().toString();var seconds=d.getSeconds().toString();return((hrs.length===1)?'0':'')+hrs+':'+((mins.length===1)?'0':'')+mins+':'+((seconds.length===1)?'0':'')+seconds;},"X":function(d){return d.toLocaleTimeString();},"z":function(d){var matches=d.toString().match(/GMT([+\-]\d{4}) \((.+)\)$/);return matches[1];},"Z":function(d){var matches=d.toString().match(/GMT([+\-]\d{4}) \((.+)\)$/);return matches[2];},"c":function(d){var hrs=d.getHours().toString();var mins=d.getMinutes().toString();var seconds=d.getSeconds().toString();return ips.getString('day_'+d.getMonth()+'_short')+' '+ips.getString('month_'+d.getMonth()+'_short')+' '+d.getDate().toString()+' '+((hrs.length===1)?'0':'')+hrs+':'+((mins.length===1)?'0':'')+mins+':'+((seconds.length===1)?'0':'')+seconds+' '+d.getFullYear().toString();},"D":function(d){var month=d.getMonth().toString();var day=d.getDate().toString();return((month.length===1)?'0':'')+month+'/'+((day.length===1)?'0':'')+day+'/'+parseInt(d.getFullYear().toString().substr(0,2)).toString();},"F":function(d){var month=d.getMonth().toString();var day=d.getDate().toString();return d.getFullYear().toString()+'-'+((month.length===1)?'0':'')+month+'-'+((day.length===1)?'0':'')+day;},"s":function(d){return parseInt(d.getTime()/1000);},"x":function(d){return d.toLocaleDateString(0);},"n":function(d){return"\n";},"t":function(d){return"\t";},"%":function(d){return'%';}};return localeFormat.format.replace(/%([aAdejuwUVWbBhmCgGyYHkIlMNPprRSTXzZcDFsxnt%]|OB)/g,function(match0,match1){if(formatters[match1]){return formatters[match1](dateObj);}});},localeTimeFormat=function(locale){var locales=_getLocaleTimeFormat();var language=locale.split('-');if(!_.isUndefined(locales[locale.toLowerCase()])){return locales[locale.toLowerCase()];}else if(!_.isUndefined(locales[language[0].toLowerCase()])){return locales[language[0].toLowerCase()];}else{return locales['en'];}},_checkLocaleSupport=function(){try{new Date().toLocaleDateString("i");}catch(e){return e.name==="RangeError";}
return false;},_getLocaleTimeFormat=function(){var defaultMeridiem=function(hour,lower){if(hour<12){return(lower?'am':'AM');}else{return(lower?'pm':'PM');}};return{'af':{format:'%H:%M'},'ar-ma':{format:'%H:%M'},'ar-sa':{format:'%H:%M'},'ar-tn':{format:'%H:%M'},'ar':{format:'%H:%M'},'az':{format:'%H:%M'},'be':{format:'%H:%M'},'bg':{format:'%k:%M'},'bn':{format:'%p %l:%M সময়',meridiem:function(hour){if(hour<4){return'রাত';}else if(hour<10){return'সকাল';}else if(hour<17){return'দুপুর';}else if(hour<20){return'বিকেল';}else{return'রাত';}}},'bo':{format:'%p %l:%M',meridiem:function(hour){if(hour<4){return'མཚན་མོ';}else if(hour<10){return'ཞོགས་ཀས';}else if(hour<17){return'ཉིན་གུང';}else if(hour<20){return'དགོང་དག';}else{return'མཚན་མོ';}}},'br':{format:'%le%M %p',meridiem:defaultMeridiem},'bs':{format:'%k:%M'},'ca':{format:'%k:%M'},'cs':{format:'%k:%M'},'cv':{format:'%H:%M'},'cy':{format:'%H:%M'},'da':{format:'%H:%M'},'de-at':{format:'%H:%M'},'de':{format:'%H:%M'},'el':{format:'%l:%M %p',meridiem:function(hour,lower){if(hour>11){return lower?'μμ':'ΜΜ';}else{return lower?'πμ':'ΠΜ';}}},'en-au':{format:'%l:%M %p',meridiem:defaultMeridiem},'en-ca':{format:'%l:%M %p',meridiem:defaultMeridiem},'en-gb':{format:'%H:%M'},'en':{format:'%l:%M %p',meridiem:defaultMeridiem},'eo':{format:'%H:%M'},'es':{format:'%k:%M'},'et':{format:'%k:%M'},'eu':{format:'%H:%M'},'fa':{format:'%H:%M'},'fi':{format:'%H.%M'},'fo':{format:'%H:%M'},'fr-ca':{format:'%H:%M'},'fr':{format:'%H:%M'},'fy':{format:'%H:%M'},'gl':{format:'%k:%M'},'he':{format:'%H:%M'},'hi':{format:'%p %l:%M बजे',meridiem:function(hour){if(hour<4){return'रात';}else if(hour<10){return'सुबह';}else if(hour<17){return'दोपहर';}else if(hour<20){return'शाम';}else{return'रात';}}},'hr':{format:'%k:%M'},'hu':{format:'%k:%M'},'hy-am':{format:'%H:%M'},'id':{format:'%H.%M'},'is':{format:'%k:%M'},'it':{format:'%H:%M'},'ja':{format:'%p%l時%N分',meridiem:function(hour){if(hour<12){return'午前';}else{return'午後';}}},'jv':{format:'%H.%M'},'ka':{format:'%l:%M %p',meridiem:defaultMeridiem},'km':{format:'%H:%M'},'ko':{format:'%p %l시 %N분',meridiem:function(hour){return hour<12?'오전':'오후';}},'lb':{format:'%k:%M Auer'},'lt':{format:'%H:%M'},'lv':{format:'%H:%M'},'me':{format:'%k:%M'},'mk':{format:'%k:%M'},'ml':{format:'%p %l:%M -നു',meridiem:function(hour){if(hour<4){return'രാത്രി';}else if(hour<12){return'രാവിലെ';}else if(hour<17){return'ഉച്ച കഴിഞ്ഞ്';}else if(hour<20){return'വൈകുന്നേരം';}else{return'രാത്രി';}}},'mr':{format:'%p %l:%M वाजता',meridiem:function(hour){if(hour<4){return'रात्री';}else if(hour<10){return'सकाळी';}else if(hour<17){return'दुपारी';}else if(hour<20){return'सायंकाळी';}else{return'रात्री';}}},'ms-my':{format:'%H.%M'},'ms':{format:'%H.%M'},'my':{format:'%H:%M'},'nb':{format:'%k.%M'},'ne':{format:'%pको %l:%M बजे',meridiem:function(hour){if(hour<3){return'राती';}else if(hour<10){return'बिहान';}else if(hour<15){return'दिउँसो';}else if(hour<18){return'बेलुका';}else if(hour<20){return'साँझ';}else{return'राती';}}},'nl':{format:'%H:%M'},'nn':{format:'%H:%M'},'pl':{format:'%H:%M'},'pt-br':{format:'%H:%M'},'pt':{format:'%H:%M'},'ro':{format:'%k:%M'},'ru':{format:'%H:%M'},'si':{format:'%P %l:%M',meridiem:function(hours,lower){if(hours>11){return lower?'ප.ව.':'පස් වරු';}else{return lower?'පෙ.ව.':'පෙර වරු';}}},'sk':{format:'%k:%M'},'sl':{format:'%k:%M'},'sq':{format:'%H:%M'},'sr-cyrl':{format:'%k:%M'},'sr':{format:'%k:%M'},'sv':{format:'%H:%M'},'ta':{format:'%H:%M'},'th':{format:'%k นาฬิกา %N นาที'},'tl-ph':{format:'%H:%M'},'tr':{format:'%H:%M'},'tzl':{format:'%H.%M'},'tzm-latn':{format:'%H:%M'},'tzm':{format:'%H:%M'},'uk':{format:'%H:%M'},'uz':{format:'%H:%M'},'vi':{format:'%H:%M'},'zh-cn':{format:'%p%l点%M分',meridiem:defaultMeridiem},'zh-tw':{format:'%p%l點%M分',meridiem:defaultMeridiem}}};return{readable:readable,localeDateString:localeDateString,isValidDateObj:isValidDateObj,timestamp:timestamp,supportsHTMLDate:supportsHTMLDate,localeTimeFormat:localeTimeFormat,formatTime:formatTime,getDateFromInput:getDateFromInput,removeTimezone:removeTimezone};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.utils.url',function(){function getParam(name,url){return parseUri(url||window.location.href).queryKey[name];}
function getPageNumber(param,url=''){const urlObj=url instanceof URL?url:new URL(url,location.href);if(param==='page'){const regex=/\/page\/(\d+)(?:\/|$)/;if(urlObj.pathname.includes('/index.php')){for(let[key,value]of urlObj.searchParams.entries()){let match;if(!value&&(match=key.match(regex))&&match){return parseInt(match[1]);}}}else{let match;if((match=urlObj.pathname.match(regex))&&match){return parseInt(match[1]);}}}
const page=parseInt(urlObj.searchParams.get(param)||"1");return Number.isNaN(page)?1:page;}
function pageParamToPath(url,name,number){const urlObj=new URL(url||"",location.href);number=parseInt(number);if(isNaN(number)){Debug.warn(`Setting the page param in the pageThe number parameter`);number=1;}
removeParam(name,urlObj);const regex=new RegExp(`(^.*)(\\/${name.replaceAll('\\', '\\\\')}\\/\\d+)($|\\/.*$)`);const pageEnding=number>1?`/${name}/${number}`:'';if(urlObj.pathname.includes("/index.php")){const params={[name]:number>1?number.toString():null,};for(const[key,value]of urlObj.searchParams.entries()){if(value){continue;}
if(key.startsWith('/')){delete params[name];const newPath=key.match(pageEnding)?key.replace(regex,`$1${pageEnding}$3`):key.replace(/\/$/,'')+pageEnding+'/';removeParam(key,urlObj);const currentSearch=urlObj.search.replace(/^\?/,'')
urlObj.search='?'+newPath+(currentSearch?`&${currentSearch}`:'');break;}}
if(Object.keys(params).length){urlObj.updateSearchParams({params});}}else{urlObj.pathname=urlObj.pathname.match(regex)?urlObj.pathname.replace(regex,`$1${pageEnding}$3`):urlObj.pathname.replace(/\/$/,'')+pageEnding+'/';}
return urlObj.toString();}
function removeParam(name,url){return removeParams([name],url);}
function removeParams(name,url){if(typeof url==='string'){url=new URL(url,location.href);}
if(!(url instanceof URL)){url=new URL(window.location.href);}
const paramList=new Set([...name,...name.map(name=>encodeURIComponent(name))]);let search=(url.search||"").replace(/^\?/,"").split('&').filter(component=>!paramList.has(component.split('=',2)[0])).join('&');url.search=search.length?"?"+search:"";return url.href;}
function rebuildUriObject(uriObject){let returnUrl=uriObject.protocol+'://'+uriObject.host+((uriObject.port!=='')?':'+uriObject.port:'')+uriObject.path;if(_.keys(uriObject.queryKey).length){var qsParam='?';_.each(uriObject.queryKey,function(value,key){if(value){returnUrl=returnUrl+qsParam+key+'='+value;}
else
{returnUrl=returnUrl+qsParam+key;}
qsParam='&';})}
return returnUrl;}
function getURIObject(url){return parseUri(url||window.location.href);}
let _origin;function getOrigin(){if(!_origin){_origin=location.origin;}
return _origin;}
function parseUri(str){let o,uri;if('URL'in window){try{if(str.indexOf('//')===0){str=location.protocol+str;}
o=new URL(str);uri={'source':o.href,'protocol':o.protocol.substring(0,(o.protocol.length-1)),'userInfo':(o.username?o.username:'')+((o.username&&o.password)?':':'')+(o.password?o.password:''),'user':o.username,'password':o.password,'host':o.hostname,'port':o.port,'relative':o.pathname+(o.search?o.search:''),'path':o.pathname,'directory':'','file':'','query':o.search.substring(1),'anchor':o.hash,'queryKey':{}};uri.authority=uri.userInfo+(uri.userInfo?'@':'')+uri.host;o.searchParams.forEach(function(v,k){uri.queryKey[k]=v;});var urlBits=uri.path.split('/');uri.file=urlBits.pop();uri.directory=urlBits.join('/');return uri;}catch(err){Debug.log("Failed to parse URL: "+str+" ; "+err);}}
o=parseUri.options;uri={};const m=o.parser[o.strictMode?"strict":"loose"].exec(str);let i=14;while(i--)uri[o.key[i]]=m[i]||"";uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){if($1)uri[o.q.name][$1]=$2;});return uri;}
parseUri.options={strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g
},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}};URL.prototype.updateSearchParams=function({params={},param,value="",encode=true,removeCurrent=true}){if(typeof arguments[0]!=='object'){if(typeof arguments[0]!=='string'){throw new TypeError('The first argument must be either an object of options or a string denoting the param');}
param=arguments[0];if(arguments.length>1){value=arguments[1];}}
if(typeof param==='string'){params[param]=value!==null?value:"";}
const paramsToRemove=[];let newParamComp='';for(const k of Object.keys(params)){if(params[k]!==null){try{params[k]=`${params[k]}`;}catch(e){Debug.warn(new TypeError(`Could not convert the value for the param ${k} into a string, so the param is being set to an empty string instead`));params[k]='';}}
if(typeof params[k]!=="string"){paramsToRemove.push(k);delete params[k];continue;}else if(removeCurrent){paramsToRemove.push(k);}
const key=encode?encodeURIComponent(k):k;const value=encode?encodeURIComponent(params[k]):params[k];newParamComp+=`${key}=${value}&`}
newParamComp=newParamComp.replace(/&$/,'');if(paramsToRemove.length){removeParams(paramsToRemove,this);}
const search=(this.search||"").replace(/^\?/,"");if(search||newParamComp){this.search="?"+search+(search.length&&newParamComp.length?`&`:'')+newParamComp;}else{this.search="";}
return this;};return{getPageNumber,getParam,removeParam,removeParams,getURIObject,getOrigin,rebuildUriObject,pageParamToPath,};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.validate',function(options){var formats={email:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))){2,6}$/i,url:/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/,alphanum:/^\w+$/,integer:/^\d+$/,number:/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,creditcard:/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,hex:/^[0-9a-f]+$/i
};var validators={maxlength:function(val,max){return val.length<=max;},minlength:function(val,min){return val.length>=min;},rangelength:function(val,min,max){return validators.maxlength(val,max)&&validators.minlength(val,min);},min:function(val,min){return Number(val)>=min;},max:function(val,max){return Number(val)<=max;},range:function(val,min,max){return validators.min(val,min)&&validators.max(val,max);},required:function(val){return val.length>0},regex:function(val,regex){return new RegExp(regex).test(val);},format:function(val,format){return new RegExp(formats[format]).test(val);},remote:function(val,url){var deferred=$.Deferred();ips.getAjax()(url,{dataType:'json',data:{input:encodeURI(val)}}).done(function(response){if(response.result=='ok'){deferred.resolve();}else{deferred.reject(response.message||null);}}).fail(function(jqHXR,textStatus){deferred.reject(textStatus);});return deferred.promise();}};var addFormat=function(name,format){formats[name]=format;},addValidator=function(name,fn){validators[name]=fn;};var isUrl=function(url){return validators.regex(url,formats.url);},isAllowedUrl=function(url){var returnValue;returnValue=true;if(ips.getSetting('blacklist')){for(var i in ips.getSetting('blacklist')){var blacklistUrl=ips.getSetting('blacklist')[i];blacklistUrl=escapeRegExp(blacklistUrl);blacklistUrl=blacklistUrl.replace(/\\\*/g,'(.+?)');var index=url.search(new RegExp(blacklistUrl,'ig'));if(index>=0){returnValue=false;break;}}}
if(ips.getSetting('whitelist')){returnValue=false;for(var i in ips.getSetting('whitelist')){var whitelistUrl=ips.getSetting('whitelist')[i];whitelistUrl=escapeRegExp(whitelistUrl);whitelistUrl=whitelistUrl.replace(/\\\*/g,'(.+?)');var index=url.search(new RegExp(whitelistUrl,'ig'));if(index>=0){returnValue=true;break;}}}
return returnValue;},isEmail=function(email){return validators.regex(email,formats.email);};var validate=function(field,conditions,ignoreHTML5){if(!ignoreHTML5){conditions=_.extend(_getAutomaticConditions(field),conditions||{});}
if(!_.size(conditions)){return true;}
var validated=true;var messages=[];for(var i in conditions){if(!_.isFunction(validators[i])){continue;}
var value=field.val();var args=[];if(_.isObject(conditions[i])){args=_.values(conditions[i])
args.splice(0,1);}else{args=[conditions[i]];}
args.unshift(value);if(validators[i].apply(this,args)!==true){validated=false;messages.push({condition:i,message:_getMessage(i,args)});}}
return{result:validated,messages:messages}},_getMessage=function(type,args){return ips.pluralize(ips.getString('validation_'+type,{data:args}),[((type=='rangelength')?args[2]:args[1])]);},_getAutomaticConditions=function(field){var conditions={};if(field.is('[required]')){conditions.required=true;}
if(field.is('input[type="number"], input[type="range"], input[type="email"], input[type="url"]')){conditions.format=field.attr('type');}
if(field.is('[max]')){conditions.max=field.attr('max');}
if(field.is('[min]')){conditions.min=field.attr('min');}
if(field.is('[pattern]')){conditions.regex=field.attr('pattern');}
return conditions;};return{isUrl:isUrl,isEmail:isEmail,addFormat:addFormat,addValidator:addValidator,validate:validate,isAllowedUrl:isAllowedUrl}});}(jQuery,_));var escapeRegExp;(function(){var specials=["-","[","]","/","{","}","(",")","*","+","?",".","\\","^","$","|"],regex=RegExp('['+specials.join('\\')+']','g');escapeRegExp=function(str){return str.replace(regex,"\\$&");};}());;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.analytics',function(){var init=function(){},trackPageView=function(url){try{if(ips.getSetting('googleAnalyticsEnabled')){if(!_.isUndefined(window.ga)){var urlObj=ips.utils.url.getURIObject(url||document.location);Debug.log("Manual page view tracked with Google Analytics: "+urlObj.relative);ga('send','pageview',urlObj.relative);}}
if(ips.getSetting('matomoEnabled')){if(!_isUndefined(window._paq)){Debug.log("Manual page view tracked with Matomo");_paq.push(['trackPageView']);}}
if(_.isFunction(ips.getSetting('paginateCode'))){ips.getSetting('paginateCode').call(url);}}catch(err){Debug.log("Error tracking page view: "+err);}};return{init:init,trackPageView:trackPageView};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.anim',function(){var animationSupport=false;var elm=document.createElement('div'),animation=false,animationstring='animation',keyframeprefix='',domPrefixes='Webkit Moz O ms Khtml'.split(' '),pfx='';if(elm.style.animationName){animationSupport=true;}
if(animationSupport===false){for(var i=0;i<domPrefixes.length;i++){if(elm.style[domPrefixes[i]+'AnimationName']!==undefined){pfx=domPrefixes[i];animationstring=pfx+'Animation';keyframeprefix='-'+pfx.toLowerCase()+'-';animationSupport=true;break;}}}
var init=function(){},_transitions={fadeIn:{anim:function(elem,speed){cleanClasses(elem);return elem.show().addClass(['ipsAnim','ipsAnim_fade','ipsAnim_in',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem.fadeIn('fast');}},fadeOut:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_fade','ipsAnim_out',speed].join(' ')).animationComplete(function(){elem.hide();cleanClasses(elem);});},fallback:function(elem){let cb;setTimeout(()=>{elem.fadeOut('fast',()=>elem.forEach(function(){cb?.(this)}));});return{done:callback=>cb=callback,}}},fadeInDown:{anim:function(elem,speed){cleanClasses(elem);return elem.show().addClass(['ipsAnim','ipsAnim_fade','ipsAnim_in','ipsAnim_down',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem.fadeIn('fast');}},fadeOutDown:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_fade','ipsAnim_out','ipsAnim_down',speed].join(' ')).animationComplete(function(){elem.hide();cleanClasses(elem);});},fallback:function(elem){return elem.fadeOut('fast');}},slideLeft:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_slide','ipsAnim_left',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem.show();}},blindDown:{anim:function(elem,speed){cleanClasses(elem);return elem.show().addClass(['ipsAnim','ipsAnim_blind','ipsAnim_down',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem.show();}},blindUp:{anim:function(elem,speed){cleanClasses(elem);return elem.show().addClass(['ipsAnim','ipsAnim_blind','ipsAnim_up',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem.hide();}},zoomIn:{anim:function(elem,speed){cleanClasses(elem);return elem.show().addClass(['ipsAnim','ipsAnim_zoom','ipsAnim_in',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem.show();}},zoomOut:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_zoom','ipsAnim_out',speed].join(' ')).animationComplete(function(){elem.hide();cleanClasses(elem);});},fallback:function(elem){return elem.hide();}},wobble:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_wobble',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem;}},jiggle:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_jiggle'].join(' ')).animationComplete(function(){cleanClasses(elem);})},fallback:function(elem){return elem;}},pulseOnce:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_pulseOnce',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem;}},pulseAndJiggle:{anim:function(elem,speed){cleanClasses(elem);return elem.addClass(['ipsAnim','ipsAnim_pulseAndJiggle',speed].join(' ')).animationComplete(function(){cleanClasses(elem);});},fallback:function(elem){return elem;}}},go=function(animationInfo){var thisArgs=arguments,run='anim';thisArgs=ips.utils.argsToArray(thisArgs);thisArgs.shift();animationInfo=animationInfo.split(' ');var animName=animationInfo[0];var animSpeed=(animationInfo[1])?'ipsAnim_'+animationInfo[1]:'';if(!_transitions[animName]){Debug.warn("The animation '"+animName+"' doesn't exist");return;}
if(!animationSupport){run='fallback';}
thisArgs.push(animSpeed);var elem=$(thisArgs[0]);var deferred=$.Deferred();var done=0;var _checkCount=function(){done++;if(done>=elem.length){deferred.resolve();}};_.each(elem,function(){_addToQueue(elem,animName,run,thisArgs).always(_checkCount);_checkQueue(elem);});return deferred.promise();},_addToQueue=function(elem,animName,toRun,args){var deferred=$.Deferred();if(!elem.data('animQueue')||!_.isArray(elem.data('animQueue'))){elem.data('animQueue',[]);}
elem.data('animQueue').push({animName:animName,run:toRun,args:args,deferred:deferred});return deferred.promise();},_checkQueue=function(elem){var queue=elem.data('animQueue');if(elem.attr('animating')==true||!queue||!_.isArray(queue)||!queue.length){return;}
const item=queue.shift();let done=false;item.deferred.then(()=>{if(!done){done=true;_checkQueue(elem)}});if(item.run==='anim'){elem.animationComplete(function(){elem.attr('animating',false);item.deferred.resolve();});requestAnimationFrame(()=>{elem.attr('animating',true);_transitions[item.animName][item.run].apply(this,item.args);});}else{requestAnimationFrame(()=>{_transitions[item.animName][item.run].apply(this,item.args);item.deferred.resolve();});}
setTimeout(async()=>{await Promise.allSettled(elem.get(0).getAnimations().map(anim=>anim.finished));await new Promise(resolve=>setTimeout(resolve,1));if(!done){item.deferred.resolve();}},7);},cleanClasses=function(elem){$(elem).removeClass('ipsAnim').removeClass(function(index,css){return(css.match(/ipsAnim[0-9a-z_\-]+/gi)||[]).join(' ');});return elem;},isTransition=function(name){return!_.isUndefined(_transitions[name]);},addTransition=function(name,cssAnimation,fallbackAnimation){if(_transitions[name]){Debug.warn("A transition with the name '"+name+"' already exists");return;}
_transitions[name]={anim:cssAnimation,fallback:fallbackAnimation};};return{init:init,cleanClasses:cleanClasses,animationSupport:animationSupport,isTransition:isTransition,addTransition:addTransition,go:go,cancel:cleanClasses};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.utils.broadcastChannel',()=>{const channel='BroadcastChannel'in window?new window.BroadcastChannel("ipsBroadcastChannel"):undefined;return{channel:channel,enabled:'BroadcastChannel'in window}})})(jQuery,_);;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.color',function(){var init=function(){};var convertHex=function(hex,toHue,toSat){hex=hex.replace('#','');if(hex.length===3){hex=hex.slice(0,1)+hex.slice(0,1)+hex.slice(1,2)+hex.slice(1,2)+hex.slice(2,3)+hex.slice(2,3);}
if(hex.length!==6){Debug.write(hex+" isn't a valid hex color");return false;}
var r=(hexToRGB(hex.slice(0,2))/255);var g=(hexToRGB(hex.slice(2,4))/255);var b=(hexToRGB(hex.slice(4,6))/255);var hsl=RGBtoHSL(r,g,b);hsl[0]=(1/360)*toHue;hsl[1]=(1/100)*toSat;var rgb=HSLtoRGB(hsl[0],hsl[1],hsl[2]);return RGBtoHex(rgb[0],rgb[1],rgb[2]);},HSLtoRGB=function(h,s,l){var red=0;var green=0;var blue=0;var v2=0;if(s==0){red=l*255;green=l*255;blue=l*255;}else{if(l<0.5){v2=l*(1+s);}else{v2=(l+s)-(s*l);}
var v1=2*l-v2;red=255*hueToRGB(v1,v2,(h+(1/3)));green=255*hueToRGB(v1,v2,h);blue=255*hueToRGB(v1,v2,(h-(1/3)));}
return[Math.round(red),Math.round(green),Math.round(blue)];},hueToRGB=function(v1,v2,h){if(h<0){h+=1;}
if(h>1){h-=1;}
if((6*h)<1){return(v1+(v2-v1)*6*h);}
if((2*h)<1){return v2;}
if((3*h)<2){return(v1+(v2-v1)*((2/3)-h)*6);}
return v1;},RGBtoHSL=function(r,g,b){var lightness,hue,saturation=0;var min=_.min([r,g,b]);var max=_.max([r,g,b]);var delta=max-min;lightness=(max+min)/2;if(delta==0){hue=0;saturation=0;}else{if(lightness<0.5){saturation=delta/(max+min);}else{saturation=delta/(2-max-min);}
var delta_r=(((max-r)/6)+(delta/2))/delta;var delta_g=(((max-g)/6)+(delta/2))/delta;var delta_b=(((max-b)/6)+(delta/2))/delta;if(r==max){hue=delta_b-delta_g;}else if(g==max){hue=(1/3)+delta_r-delta_b;}else if(b==max){hue=(2/3)+delta_g-delta_r;}
if(hue<0){hue+=1;}
if(hue>1){hue-=1;}}
return[hue,saturation,lightness];},hexToRGB=function(hex){if(hex.length===2){return parseInt(hex,16);}
hex=hex.replace('#','');if(hex.length===3){hex=hex.slice(0,1)+hex.slice(0,1)+hex.slice(1,2)+hex.slice(1,2)+hex.slice(2,3)+hex.slice(2,3);}
if(hex.length!==6){Debug.write(hex+" isn't a valid hex color");return[0,0,0];}
return[hexToRGB(hex.slice(0,2))/255,hexToRGB(hex.slice(2,4))/255,hexToRGB(hex.slice(4,6))/255];},RGBtoHex=function(r,g,b){var hex=[r.toString(16),g.toString(16),b.toString(16)];_.each(hex,function(val,nr){if(val.length==1){hex[nr]='0'+val;}});return hex.join('');};let iroState='unloaded';const iroCallbacks=new Set();return{convertHex:convertHex,HSLtoRGB:HSLtoRGB,hueToRGB:hueToRGB,RGBtoHSL:RGBtoHSL,hexToRGB:hexToRGB,RGBtoHex:RGBtoHex,loadIro(){return new Promise((resolve,reject)=>{if(iroState==='loaded'||ips.utils.iro){iroState='loaded';resolve();return;}
iroCallbacks.add([resolve,reject]);if(iroState==='loading'){return;}
iroState='loading';function failed(e){if(iroState==='loading'){iroState='error';}
iroCallbacks.forEach(cb=>cb[1](e||new Error('Could not load iro js dependency after 10s')));iroCallbacks.clear();}
window.addEventListener('ips:iroLoaded',()=>{iroState='loaded';Debug.log("Loaded color picker");iroCallbacks.forEach(cb=>cb[0]());iroCallbacks.clear();},{once:true});if(document.querySelector('script[data-iro-loader]')){iroState='loading';}else{const manifestURL=ips.getSetting('baseURL').replace(/\/+$/,'')+`/applications/core/interface/static/iro/manifest.json?antiCache=${encodeURIComponent(ips.getSetting('jsAntiCache'))}`;ips.fetch(manifestURL).then(response=>{for(const detail of Object.values(response)){if(detail.isEntry){const script=document.createElement('script');script.setAttribute('data-iro-loader','');script.setAttribute('type','module')
document.body.appendChild(script);script.src=ips.getSetting('baseURL').replace(/\/+$/,'')+'/applications/core/interface/static/iro/'+detail.file+"?antiCache="+encodeURIComponent(ips.getSetting('jsAntiCache'));}}}).catch(failed);}
setTimeout(()=>failed(),10000);});}};});}(jQuery,_));;
(function($,_,undefined){"use strict";ips.createModule("ips.utils.contentViews",()=>({_viewsCache:{},_onRemoveCache:{},init(){},enabled(){let res=!!(ips.getSetting('memberID')&&ips.getSetting('socketEnabled')&&ips.getSetting('page_token'));return res;},registerEntity(key,isViewed=false,otherData={},force=false,onRemove=null){if(key in this._viewsCache){if(!force){throw new RangeError(`The key, '${key}' is already registered!`);}
if(this._onRemoveCache[key]){this._onRemoveCache[key]();delete this._onRemoveCache[key];}}
if(onRemove instanceof Function){this._onRemoveCache[key]=onRemove;}
try{if(!JSON.stringify(otherData)){throw new Error();}}catch(e){throw new TypeError(`The otherData argument for a viewEntity is not JSON serializable (or is a false-y value)`);}
this._viewsCache[key]={start:isViewed?Math.floor(Date.now()/1000):null,end:null,otherData}
ips.utils.sockets.send('view:entity',{key,data:this._viewsCache[key]});},setIsViewing(key,isViewing){if(!(key in this._viewsCache)){throw new RangeError(`The key '${key}' is not registered`);}
const entity=this._viewsCache[key];const isCurrentlyViewed=(entity.start&&entity.end&&(!entity.end||entity.end<entity.start));if(isCurrentlyViewed!==isViewing){this._viewsCache[key][isViewing?'start':'end']=Math.floor(Date.now()/1000);ips.utils.sockets.send('view:entity',{key,data:this._viewsCache[key]});}},isViewing(key){if(!(key in this._viewsCache)){Debug.warn('Checking to see if an unregistered entity is being viewed');return false;}
const entity=this._viewsCache[key];return(entity.start&&(!entity.end||entity.end<entity.start));},}));})(jQuery,_);;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.cookie',function(){var _store={},_init=false;var init=function(){var cookies=_parseCookies(document.cookie.replace(" ",'')),cookieID=ips.getSetting('cookie_prefix')||false;$.each(cookies,function(key,cookie){if(cookieID){if(key.startsWith(cookieID)){key=key.replace(cookieID,'');_store[key]=unescape(cookie||'');}}});_init=true;},get=function(cookieKey){if(!_init){init();}
if(_store[cookieKey]){return _store[cookieKey];}
return undefined;},set=function(cookieKey,value,sticky){var expires='',path='/',domain='',ssl='',prefix='';if(!cookieKey){return;}
let allowOptional=true;if($('#elGuestTerms[data-role="cookieConsentBar"]').length>0){allowOptional=!!(ips.utils.cookie.get('cookie_consent')&&ips.utils.cookie.get('cookie_consent_optional'));}
if(!allowOptional&&ips.getSetting('essential_cookies').indexOf(cookieKey)===-1){return;}
if(!_.isUndefined(sticky)){if(sticky===true){var expirationDate=new Date();expirationDate.setFullYear(expirationDate.getFullYear()+100);expires="; expires="+expirationDate.toUTCString();}else if(sticky===-1){expires="; expires=Thu, 01-Jan-1970 00:00:01 GMT";}else if(sticky.length>10){expires="; expires="+sticky;}}
if(!_.isUndefined(ips.getSetting('cookie_domain'))&&ips.getSetting('cookie_domain')!=''){domain="; domain="+ips.getSetting('cookie_domain');}
if(!_.isUndefined(ips.getSetting('cookie_path'))&&ips.getSetting('cookie_path')!=''){path=ips.getSetting('cookie_path');}
if(!_.isUndefined(ips.getSetting('cookie_prefix'))&&ips.getSetting('cookie_prefix')!=''){prefix=ips.getSetting('cookie_prefix');}
if(!_.isUndefined(ips.getSetting('cookie_ssl'))&&ips.getSetting('cookie_ssl')!=''){ssl='; secure';}
document.cookie=prefix+cookieKey+"="+escape(value)+"; path="+path+expires+domain+ssl+';';_store[cookieKey]=value;},unset=function(cookieKey){if(_store[cookieKey]){set(cookieKey,'',-1);}},_parseCookies=function(cookieString){var pairs=cookieString.split(";"),cookies={};for(var i=0;i<pairs.length;i++){var pair=pairs[i].split("=");cookies[pair[0].trim()]=unescape(pair[1]).trim();}
return cookies;};return{init:init,get:get,set:set,unset:unset};});}(jQuery,_));;
(($,_)=>{'use strict';ips.createModule('ips.utils.crypto',function(){return{md5(text){function md5cycle(x,k){let a=x[0],b=x[1],c=x[2],d=x[3];a=ff(a,b,c,d,k[0],7,-680876936);d=ff(d,a,b,c,k[1],12,-389564586);c=ff(c,d,a,b,k[2],17,606105819);b=ff(b,c,d,a,k[3],22,-1044525330);a=ff(a,b,c,d,k[4],7,-176418897);d=ff(d,a,b,c,k[5],12,1200080426);c=ff(c,d,a,b,k[6],17,-1473231341);b=ff(b,c,d,a,k[7],22,-45705983);a=ff(a,b,c,d,k[8],7,1770035416);d=ff(d,a,b,c,k[9],12,-1958414417);c=ff(c,d,a,b,k[10],17,-42063);b=ff(b,c,d,a,k[11],22,-1990404162);a=ff(a,b,c,d,k[12],7,1804603682);d=ff(d,a,b,c,k[13],12,-40341101);c=ff(c,d,a,b,k[14],17,-1502002290);b=ff(b,c,d,a,k[15],22,1236535329);a=gg(a,b,c,d,k[1],5,-165796510);d=gg(d,a,b,c,k[6],9,-1069501632);c=gg(c,d,a,b,k[11],14,643717713);b=gg(b,c,d,a,k[0],20,-373897302);a=gg(a,b,c,d,k[5],5,-701558691);d=gg(d,a,b,c,k[10],9,38016083);c=gg(c,d,a,b,k[15],14,-660478335);b=gg(b,c,d,a,k[4],20,-405537848);a=gg(a,b,c,d,k[9],5,568446438);d=gg(d,a,b,c,k[14],9,-1019803690);c=gg(c,d,a,b,k[3],14,-187363961);b=gg(b,c,d,a,k[8],20,1163531501);a=gg(a,b,c,d,k[13],5,-1444681467);d=gg(d,a,b,c,k[2],9,-51403784);c=gg(c,d,a,b,k[7],14,1735328473);b=gg(b,c,d,a,k[12],20,-1926607734);a=hh(a,b,c,d,k[5],4,-378558);d=hh(d,a,b,c,k[8],11,-2022574463);c=hh(c,d,a,b,k[11],16,1839030562);b=hh(b,c,d,a,k[14],23,-35309556);a=hh(a,b,c,d,k[1],4,-1530992060);d=hh(d,a,b,c,k[4],11,1272893353);c=hh(c,d,a,b,k[7],16,-155497632);b=hh(b,c,d,a,k[10],23,-1094730640);a=hh(a,b,c,d,k[13],4,681279174);d=hh(d,a,b,c,k[0],11,-358537222);c=hh(c,d,a,b,k[3],16,-722521979);b=hh(b,c,d,a,k[6],23,76029189);a=hh(a,b,c,d,k[9],4,-640364487);d=hh(d,a,b,c,k[12],11,-421815835);c=hh(c,d,a,b,k[15],16,530742520);b=hh(b,c,d,a,k[2],23,-995338651);a=ii(a,b,c,d,k[0],6,-198630844);d=ii(d,a,b,c,k[7],10,1126891415);c=ii(c,d,a,b,k[14],15,-1416354905);b=ii(b,c,d,a,k[5],21,-57434055);a=ii(a,b,c,d,k[12],6,1700485571);d=ii(d,a,b,c,k[3],10,-1894986606);c=ii(c,d,a,b,k[10],15,-1051523);b=ii(b,c,d,a,k[1],21,-2054922799);a=ii(a,b,c,d,k[8],6,1873313359);d=ii(d,a,b,c,k[15],10,-30611744);c=ii(c,d,a,b,k[6],15,-1560198380);b=ii(b,c,d,a,k[13],21,1309151649);a=ii(a,b,c,d,k[4],6,-145523070);d=ii(d,a,b,c,k[11],10,-1120210379);c=ii(c,d,a,b,k[2],15,718787259);b=ii(b,c,d,a,k[9],21,-343485551);x[0]=add32(a,x[0]);x[1]=add32(b,x[1]);x[2]=add32(c,x[2]);x[3]=add32(d,x[3]);}
function cmn(q,a,b,x,s,t){a=add32(add32(a,q),add32(x,t));return add32((a<<s)|(a>>>(32-s)),b);}
function ff(a,b,c,d,x,s,t){return cmn((b&c)|((~b)&d),a,b,x,s,t);}
function gg(a,b,c,d,x,s,t){return cmn((b&d)|(c&(~d)),a,b,x,s,t);}
function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t);}
function ii(a,b,c,d,x,s,t){return cmn(c^(b|(~d)),a,b,x,s,t);}
function md51(s){var n=s.length,state=[1732584193,-271733879,-1732584194,271733878],i;for(i=64;i<=s.length;i+=64){md5cycle(state,md5blk(s.substring(i-64,i)));}
s=s.substring(i-64);var tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i<s.length;i++)
tail[i>>2]|=s.charCodeAt(i)<<((i%4)<<3);tail[i>>2]|=0x80<<((i%4)<<3);if(i>55){md5cycle(state,tail);for(i=0;i<16;i++)tail[i]=0;}
tail[14]=n*8;md5cycle(state,tail);return state;}
function md5blk(s){let md5blks=[],i;for(i=0;i<64;i+=4){md5blks[i>>2]=s.charCodeAt(i)
+(s.charCodeAt(i+1)<<8)
+(s.charCodeAt(i+2)<<16)
+(s.charCodeAt(i+3)<<24);}
return md5blks;}
const hex_chr='0123456789abcdef'.split('');function rhex(n){let s='',j=0;for(;j<4;j++)
s+=hex_chr[(n>>(j*8+4))&0x0F]
+hex_chr[(n>>(j*8))&0x0F];return s;}
function hex(x){for(let i=0;i<x.length;i++)
x[i]=rhex(x[i]);return x.join('');}
function _md5(s){return hex(md51(s));}
let add32=(a,b)=>{return(a+b)&0xFFFFFFFF;}
if(_md5('hello')!='5d41402abc4b2a76b9719d911017c592'){add32=(x,y)=>{const lsw=(x&0xFFFF)+(y&0xFFFF),msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);}}
return _md5(text)},md5Short(text){return this.md5(text).slice(0,6)}}})})(jQuery,_);
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.css',function(){var prefixes=['webkit','moz','ms','o','w3c'];var init=function(){},buildStyleBlock=function(selector,styles,important){var output=selector+" {\n";var getValue=function(key,value){return"\t"+key+': '+value+((important)?' !important':'')+";\n";};_.each(styles,function(value,key){if(_.isArray(value)){for(var i=0;i<value.length;i++){output+=getValue(key,value[i]);}}else{output+=getValue(key,value);}});output+="}";return output;},supportsTransform=function(){var bs=document.body.style;if(!_.isUndefined(bs.transform)||!_.isUndefined(bs.WebkitTransform)||!_.isUndefined(bs.MozTransform)||!_.isUndefined(bs.OTransform)){return true;}
return false;},replaceStyle=function(stylesheetID,selector,styles){var stylesheet=getStylesheetRef(stylesheetID);var styleBlock=buildStyleBlock(selector,styles);var rulesKey=(stylesheet['cssRules'])?'cssRules':'rules';var done=false;for(var rules=0;rules<stylesheet[rulesKey].length;rules++){if(stylesheet[rulesKey][rules].selectorText==selector){stylesheet.deleteRule(rules);stylesheet.insertRule(styleBlock,rules);done=true;}}
if(!done){var idx=stylesheet.insertRule(styleBlock,stylesheet[rulesKey].length);}},getStylesheetRef=function(stylesheetID){var stylesheets=document.styleSheets;for(var sheet=0;sheet<stylesheets.length;sheet++){if(stylesheets[sheet].ownerNode.id==stylesheetID){return stylesheets[sheet];}}
return false;},escapeSelector=function(selector){return selector.replace(/(:|\.|\[|\]|,)/g,"\\$1");},generateGradient=function(angle,stops,asPureCSS){var stops=_buildStops(stops);var angles=_buildAngles(angle);var output=[];for(var i=0;i<prefixes.length;i++){output.push(_buildPrefix(prefixes[i],'linear-gradient')+
'('+angles[prefixes[i]]+', '+stops+')');}
if(!asPureCSS){return output;}else{var prefixOutput=[];for(var i=0;i<output.length;i++){prefixOutput.push('background-image: '+output[i]+';');}
return prefixOutput.join("\n");}},_buildStops=function(stops){var line=[];for(var i=0;i<stops.length;i++){if(stops[i][0].charAt(0)!='#'){stops[i][0]='#'+stops[i][0];}
line.push(stops[i][0]+' '+stops[i][1]+'%');}
return line.join(',');},_buildAngles=function(angle){var mapDegrees={'0':'right','90':'top','-90':'bottom','180':'left'};var opposites={'0':'180','90':'-90','-90':'90','180':'0'};var output={};for(var i=0;i<prefixes.length;i++){if(!_.isUndefined(mapDegrees[angle])){if(prefixes[i]=='w3c'){output[prefixes[i]]='to '+mapDegrees[opposites[angle]];}else{output[prefixes[i]]=mapDegrees[angle];}}else{output[prefixes[i]]=angle+'deg';}}
return output;},_buildPrefix=function(vendor,style){return((vendor!='w3c')?'-'+vendor+'-':'')+style;};return{generateGradient:generateGradient,replaceStyle:replaceStyle,getStylesheetRef:getStylesheetRef,buildStyleBlock:buildStyleBlock,escapeSelector:escapeSelector};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.db',function(){let enabled=null;let sessionStorageSupported=null;const expirations={};function init(queryString){enabled=isEnabled();}
function set(type,key,value,isPrivate,expire=null){if(enabled){var storageEngine=localStorage;if(isPrivate&&(!_.isUndefined(ips.getSetting('isAcp'))||(_.isUndefined(ips.utils.cookie.get('login_key'))&&_.isUndefined(ips.getSetting('cookie_prefix')+ips.utils.cookie.get('login_key'))))&&sessionStorageIsSupported()){storageEngine=sessionStorage;}
if(value){try{storageEngine.setItem(type+'.'+key,JSON.stringify(value));}catch(err){}
if(!type.startsWith('__expirations__:')){setExpiration(type,key,typeof expire==='number'?expire:undefined);}}else{storageEngine.removeItem(type+'.'+key);}}}
function get(type,key){if(!type.startsWith('__expirations__:')){const{[key]:expiration}=getExpirations(type);if(typeof expiration==='number'&&expiration<Date.now()/1000){setExpiration(type,key,expiration);return null;}}
if(_.isUndefined(key)){return getByType(type);}
var val=localStorage.getItem(type+'.'+key);if(_.isNull(val)&&sessionStorageIsSupported()){val=sessionStorage.getItem(type+'.'+key);}
try{return JSON.parse(val);}catch(err){return val;}}
function getExpirations(type){if(!expirations[type]){try{expirations[type]=get("__expirations__:"+type,'');if(!expirations[type]||typeof expirations[type]!=='object'){throw new TypeError();}}catch(e){expirations[type]={};}}
return expirations[type];}
function setExpiration(type,key,expiration){const _expirations=getExpirations(type);if(typeof expiration==='number'){_expirations[key]=expiration;if(expiration<Date.now()/1000){delete _expirations[key];remove(type,key);}}else{delete _expirations[key];}
expirations[type]=_expirations
if(Object.keys(_expirations).length){set("__expirations__:"+type,'',_expirations);}else{remove('__expirations__:'+type);}}
function remove(type,key){if(_.isUndefined(key)){removeByType(type);return;}
localStorage.removeItem(type+'.'+key);if(sessionStorageIsSupported()){sessionStorage.removeItem(type+'.'+key);}}
function getByType(type){try{var results={};if(sessionStorageIsSupported()&&sessionStorage.length){for(var key in sessionStorage){if(key.startsWith(type+'.')){var actualKey=key.replace(type+'.','');results[actualKey]=get(type,actualKey);}}}
if(localStorage.length){for(var key in localStorage){if(key.startsWith(type+'.')){var actualKey=key.replace(type+'.','');results[actualKey]=get(type,actualKey);}}}
return results;}catch(e){return{};}}
function removeByType(type){var count=0;for(var key in getByType(type)){remove(type,key);count++;}
return count;}
function isEnabled(){if(!_.isBoolean(enabled)){try{if('localStorage'in window&&window['localStorage']!==null&&window.JSON){return _testEnabled();}else{return false;}}catch(e){return false;}}else{return enabled;}}
function _testEnabled(){try{localStorage.setItem('test',1);localStorage.removeItem('test');}catch(err){Debug.log("Writing to localstorage failed");return false;}
return true;}
function sessionStorageIsSupported(){if(!_.isBoolean(sessionStorageSupported)){try{sessionStorageSupported=!!('sessionStorage'in window&&window['sessionStorage']!==null&&window.JSON);}catch(e){sessionStorageSupported=false;}}
return sessionStorageSupported;}
init();return{set,get:get,getByType:getByType,remove:remove,removeByType:removeByType,enabled:enabled,isEnabled:isEnabled};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.events',function(){var manualEvent=function(element,ev){if(_.isObject(element)){element.each(function(){_fireEvent(this,ev);});}else{_fireEvent(element,ev);}},isTouchDevice=function(){return(('ontouchstart'in window)||(navigator.MaxTouchPoints>0)||(navigator.msMaxTouchPoints>0));},getVisibilityEvent=function(){if(!_.isUndefined(document.hidden)){return'visibilitychange';}else if(!_.isUndefined(document.mozHidden)){return'mozvisibilitychange';}else if(!_.isUndefined(document.msHidden)){return'msvisibilitychange';}else if(!_.isUndefined(document.webkitHidden)){return'webkitvisibilitychange';}
return'_unsupported';},getVisibilityProp=function(){if(!_.isUndefined(document.hidden)){return'hidden';}else if(!_.isUndefined(document.mozHidden)){return'mozHidden';}else if(!_.isUndefined(document.msHidden)){return'msHidden';}else if(!_.isUndefined(document.webkitHidden)){return'webkitHidden';}
return undefined;},_fireEvent=function(element,ev){if(document.createEvent){var evObj=document.createEvent('MouseEvents');evObj.initEvent(ev,true,false);element.dispatchEvent(evObj);}else if(document.createEventObject){var evObj=document.createEventObject();element.fireEvent('on'+evt,evObj);}};return{manualEvent:manualEvent,isTouchDevice:isTouchDevice,getVisibilityEvent:getVisibilityEvent,getVisibilityProp:getVisibilityProp};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.utils.fileDownload',function(){class DownloadError extends RangeError{sourceErr=undefined
xhr=undefined
constructor(message,xhr){super(message);this.sourceErr=this;this.xhr=xhr;}
static fromError(err,xhr){const downloadError=new DownloadError(`Failed to download - ${err.message}`,xhr);downloadError.sourceErr=err;return downloadError;}}
return{download({url,blobName,onProgress,formData,forceBlobName=false,forceDownload=false}){return new Promise((resolve,_reject)=>{const xhr=new XMLHttpRequest();let blob;xhr.open(formData?'POST':'GET',url,true);const reject=e=>{_reject(DownloadError.fromError(e,xhr));}
xhr.responseType="arraybuffer";xhr.onload=function(e){blob=new Blob([this.response]);};xhr.onprogress=function(e){onProgress?.call(this,e);};xhr.onerror=function(e){reject(e);}
xhr.onloadend=function(e){try{if(xhr.responseType!=='arraybuffer'&&xhr.responseType!=='blob'&&xhr.responseType!=='text'){throw new RangeError(`Cannot download data from response of type ${xhr.responseType}`);}
if(!xhr.status?.toString().match(/^2\d\d$/)){throw new RangeError(`Response did not receive a 2xx response status. Got status code ${xhr.status}`);}
const tempLink=document.createElement('a');let href=window.URL.createObjectURL(blob);tempLink.href=href;tempLink.setAttribute('hidden','');let contentDispositionName=this.getResponseHeader('content-disposition')?.match(/filename="(.+)"/i)?.[1];if(!contentDispositionName&&!forceDownload){throw new RangeError(`There is no content-disposition name in the response`);}
if(forceBlobName||!contentDispositionName){contentDispositionName=blobName;}else{contentDispositionName=decodeURIComponent(contentDispositionName);}
tempLink.setAttribute('download',contentDispositionName);document.body.appendChild(tempLink);tempLink.click();window.URL.revokeObjectURL(href);setTimeout(()=>{tempLink.remove();resolve();});}catch(e){reject(e);}};xhr.setRequestHeader('X-REQUESTED-WITH','XMLHttpRequest');if(formData){xhr.send(formData);}else{xhr.send();}});}};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.form',function(){var serializeAsObject=function(jQueryObj,customSerializers){var asArray=jQueryObj.serializeArray();var output={};_.each(asArray,function(val){var outValue=val.value;if(customSerializers&&!_.isUndefined(customSerializers[val.name])&&_.isFunction(customSerializers[val.name])){outValue=customSerializers[val.name](val.name,val.value);}
var keys=_splitFieldName(val.name);_addValueToKey(output,keys,outValue);});return output;};var _splitFieldName=function(name){var parts=name.split('[');parts=_.map(parts,function(part){return part.replace(/\]/g,'')});if(parts[0]===''){parts.shift();}
return parts;},_addValueToKey=function(output,keys,value){if(!_.isObject(output)){output={};}
var currentPath=output;if(_.isArray(keys)){for(var i=0;i<keys.length;i++){if(_.isUndefined(currentPath[keys[i]])){currentPath[keys[i]]=(i==keys.length-1)?value:{};}
currentPath=currentPath[keys[i]];}}else{output[keys]=value;}};return{serializeAsObject:serializeAsObject};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.geolocation',function(){const permissions={GRANTED:'granted',DENIED:'denied',PROMPT:'prompt'},type='geolocation',getGeolocationIsAllowed=function(){if(!"geolocation"in navigator)return false;const permission=ips.utils.db.get(type,`permission.${ipsSettings.memberID}`);if(permission==permissions.GRANTED)return true;return false;},setGeolocationIsAllowed=function(status){if(!_.values(permissions).includes(status))return;ips.utils.db.set(type,`permission.${ipsSettings.memberID}`,status,false);},getCurrentPosition=function(){return new Promise((res,rej)=>{navigator.geolocation.getCurrentPosition(position=>{setGeolocationIsAllowed(permissions.GRANTED);res(position.coords);},error=>{if(error.code==error.PERMISSION_DENIED){setGeolocationIsAllowed(permissions.DENIED);}
rej(error);});});},generalLocation=function(){return new Promise((res,rej)=>{if(!ipsSettings.memberID){const ipLocation=ips.utils.db.get(type,`iplocation`);if(ipLocation){res(ipLocation);}}
res({'latitude':0,'longitude':0});});}
return{getGeolocationIsAllowed,getCurrentPosition,setGeolocationIsAllowed,permissions};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.utils.history',function(){const _state={current:window.history.state?.state instanceof Object?{"":{},...window.history.state.state}:{"":{}},lastKey:window.history.state?.lastKey||''}
window.history.replaceState({..._state},'',window.location.href)
function ipsHistoryChange(e,type){const detail={state:_state.current,unused:null,url:window.location.href,title:document.title,originalEvent:e,type}
const event=new CustomEvent("historychange",{detail,bubbles:true})
window.dispatchEvent(event)
const key=_state.lastKey
Debug.log(`IPS History: Firing historychange${key ? `and historychange:${key}` : ``} event(s) with type ${type}`)
if(key){const event=new CustomEvent(`historychange:${key}`,{detail,bubbles:true})
window.dispatchEvent(event)}}
window.addEventListener('popstate',e=>{setTimeout(()=>{if(window.history.state instanceof Object){if(window.history.state.current instanceof Object){_state.current=window.history.state.current}else{_state.current={..._state.current}}
_state.lastKey=window.history.state.lastKey||''}
ipsHistoryChange(e,'pop')})});ipsHistoryChange(undefined,'load');return{getLastChangeType(){return _state.lastKey},getState(key){return key?(_state.current[key]||{}):_state.current},pushState(state,key,url,e){_state.current={..._state.current,[key]:state}
_state.lastKey=key
window.history.pushState({..._state},'',url);ipsHistoryChange(e,'push')},replaceState(state,key,url,e){_state.current={..._state.current,[key]:state}
_state.lastKey=key
window.history.replaceState({..._state},'',url)
ipsHistoryChange(e,'replace')}};});}(jQuery,_));;
;(function($,_){"use strict";const UI_CALLBACKS={resolvers:new Set(),rejects:new Set(),timeout:null,};let UI_STATE='unloaded';let UI_ERR;document.addEventListener("ips:iconpickerUILoaded",()=>{UI_STATE="loaded";clearTimeout(UI_CALLBACKS.timeout);for(const cb of UI_CALLBACKS.resolvers){cb();}
UI_CALLBACKS.resolvers.clear();UI_CALLBACKS.rejects.clear();})
function loadIconPickerUI(){return new Promise((resolve,reject)=>{if(UI_STATE==='loaded'||ips.ui.iconpicker){UI_STATE='loaded';resolve();return;}else if(UI_STATE==='error'){UI_ERR?reject(UI_ERR):reject();return;}
UI_CALLBACKS.resolvers.add(resolve);UI_CALLBACKS.rejects.add(reject);if(UI_STATE==='unloaded'){UI_STATE='loading';UI_CALLBACKS.timeout=setTimeout(()=>{UI_STATE='error';UI_CALLBACKS.resolvers.clear();for(const cb of UI_CALLBACKS.rejects){cb()}
UI_CALLBACKS.rejects.clear();},30000);ips.fetch(ips.getSetting('baseURL').replace(/\/+$/,'')+'/applications/core/interface/static/iconpicker/manifest.json').then(response=>{if(typeof response!=='object'){throw new TypeError(`The response from ${ips.getSetting('baseURL').replace(/\/+$/, '') + '/applications/core/interface/static/iconpicker/manifest.json'} was not an object`);}
for(const key in response){const entry=response[key];if(entry.isEntry){const src=ips.getSetting('baseURL').replace(/\/+$/,"")+"/applications/core/interface/static/iconpicker/"+entry.file.replace(/^\/+/,'');if(entry.css){const el=document.createElement('link');el.setAttribute('rel','stylesheet');el.href=src;document.head.appendChild(el);}else{const el=document.createElement('script');el.setAttribute('type','module');el.src=src;document.body.appendChild(el);}}}}).catch(err=>{clearTimeout(UI_CALLBACKS.timeout);UI_STATE='error';UI_ERR=err;for(const cb of UI_CALLBACKS.rejects){cb(err);}
UI_CALLBACKS.rejects.clear();UI_CALLBACKS.resolvers.clear();})}})}
ips.createModule("ips.utils.iconpicker",function(){const fileToLoad='/applications/core/interface/static/fontawesome/js/fontawesome.js';let faLoaded='unloaded';let faAvailable=false;let faLoadAttempts=0;function resolveWhenLoaded(){return new Promise(resolve=>{if(ips.utils.fontawesome?.searchIcons instanceof Function){resolve(true);}
else if(++faLoadAttempts>200){resolve(false)}else{setTimeout(()=>{resolveWhenLoaded().then(resolve);},100)}})}
function loadFa6(){return new Promise(resolve=>{if(faLoaded==='loaded'||ips.utils.fontawesome?.searchIcons instanceof Function){faLoaded='loaded';resolve(true)}else{if(faLoaded!=='loading'){faLoaded='loading';const script=document.createElement('script');script.type="module";script.src=ips.getSetting('baseURL').replace(/\/+$/,'')+fileToLoad;document.body.appendChild(script);}
resolveWhenLoaded().then(_loaded=>{if(_loaded){faLoaded=true;faAvailable=true;resolve(true)}else{faLoaded=true;faAvailable=false;resolve(true)}})}})}
async function faIconsEnabled(){return!!((await loadFa6())||faAvailable)}
function getValuesFromOptions(options){const{defaultValue=null,defaultTab='fa',anchor,allowedTypes=['emoji','fa'],maxIcons=null,minIcons=null,rootElement=null,svgIcons=false,panelMode,submitOnClick=false,afterOpen,afterHide,shortCodeFixer,container,nativeEmoji=true,customEmoji}=options
return{defaultValue,defaultTab,allowedTypes,maxIcons,rootElement,svgIcons,anchor,panelMode,submitOnClick,afterOpen,afterHide,shortCodeFixer,container,customEmoji,nativeEmoji};}
let iconPicker;let lastOpened;return{pick(options={}){options=getValuesFromOptions(options)
return new Promise(_resolve=>{if(lastOpened&&Date.now()-100<lastOpened){return;}
lastOpened=Date.now();if(iconPicker instanceof IconPicker){iconPicker.remove();}
const resolve=icons=>{_resolve((Array.isArray(icons)&&icons.length)?icons.map(icon=>({key:icon.key,hairStyle:icon.hairStyle,type:icon.type,raw:icon.raw,title:icon.title,image:icon.image,})):null)}
iconPicker=new IconPicker(options);iconPicker.show(resolve,resolve);})},create(options){options=getValuesFromOptions(options)
return new IconPicker(options)},faIconsEnabled,loadFa6,compileEmojiSearchIndex(custom=false){EmojiSearchTree.instance(custom);},async hasCustomEmoji(){const store=await EmojiSearchTree.loadCustomEmojiStore()
return!!Object.keys(store).length;},whenLoaded:resolveWhenLoaded,getEmojiSearchTree(){return EmojiSearchTree},}});class IconPicker{_queuedSearch=undefined;container=undefined;_visible=false;_base;defaultValue=null;defaultTab='fa';defaultSearch=undefined;submitOnClick=false;panelMode=false;_searchString='';allowedTypes=['fa','emoji'];get _emojiSkinTone(){return Number(ips.utils.db.get('emoji','skinTone'))||null;}
get _emojiHairStyle(){return Number(ips.utils.db.get('emoji','hairStyle'))||null;}
svgIcons=false;anchor=null;_resultsCount=0
_selected={emoji:{},fa:{}}
rootElement;_onClose;_onSubmit;afterOpen=undefined;afterHide=undefined;_customEmoji=undefined;get customEmoji(){if(this._customEmoji===undefined){const allowed=this.allowedTypes.includes('emoji')&&(this.panelMode||this.anchor||this.container);if(this._options){this._customEmoji=allowed;}
return allowed;}
return this._customEmoji;}
set customEmoji(allowed){this._customEmoji=!!allowed;}
constructor(options){Object.assign(this,options)
if(options.defaultSearch){this._searchString=options.defaultSearch;}
this._options=options;if(this.allowedTypes.includes('emoji')&&!this.customEmoji&&this.nativeEmoji===false){this.allowedTypes=this.allowedTypes.filter(type=>type!=='emoji');this._options.allowedTypes=this.allowedTypes;}
if(!this.allowedTypes.length){throw new RangeError(`Need either emoji or fa tab to use the icon picker`);}
if(!this.allowedTypes.includes('emoji')&&this.defaultTab==='emoji'){this.defaultTab='fa';this._options.defaultTab='fa';}
this.selected=this.defaultValue}
get selected(){const out=[];for(const[key,group]of Object.entries(this._selected)){if(this.allowedTypes.includes(key)){for(const value of Object.values(group)){out.push(value);}}}
return out.length?out:null;}
set selected(items){if(items!==null&&!Array.isArray(items)){Debug.error(new Error(`The items passed is not an array or null.`))
return}
this._selected.fa={};this._selected.emoji={};if(Array.isArray(items)){for(const item of items){if(!this.allowedTypes.includes(item.type)){continue;}
this._selected[item.type][item.key]=item;}}}
async show(onSubmit=null,onClose=null){await loadIconPickerUI();this._onSubmit=onSubmit;this._onClose=onClose;if(!this.container){document.dispatchEvent(new CustomEvent('ipsIconPicker:show',{bubbles:true,detail:{instance:this}}))
this._visible=true}
await this.getElem()
try{this.afterOpen?.(this)}catch(e){e.message=e.message+'An error occurred when running the after open hook of the icon picker'
Debug.error(e)}}
getElemSync(){return this._base instanceof Element?this._base:null;}
getElem(){return this.getEmojiTypes().then(emojiTypes=>new Promise(resolve=>{if(this._base&&this._base.closest('body')!==document.body){this._closeReactRoot?.();delete this._base;}
if(!this._base){const container=this.container||document.body;let resolved=false;const{close}=ips.ui.iconpicker.getIconPickerUI(container,{...this._options,searchFaIcons:async(searchString)=>{if(typeof searchString!=="string"){searchString="";}
this._searchString=searchString;return await this.searchFontAwesome();},searchEmojis:async(searchString)=>{if(typeof searchString!=="string"){searchString="";}
this._searchString=searchString;return await this.searchEmojis();},setSelectedIcons:(icons)=>{this.selected=icons?.length?icons:null},hairStyleOptions:emojiTypes.find(type=>type.type==="hair").options,skinToneOptions:emojiTypes.find(type=>type.type==="skin").options,onRender:({elem,setSearchString,setOption,incrementHighlight,decrementHighlight})=>{this._base=elem;if(!resolved){resolved=true;resolve(this._base);try{this.afterOpen?.(this)}catch(e){Debug.warn(e);}}
this.setSearchString=setSearchString;this.setOption=setOption;this.incrementHighlight=incrementHighlight;this.decrementHighlight=decrementHighlight;if(typeof this._queuedSearch==='string'){setSearchString(this._queuedSearch);delete this._queuedSearch;}},onSubmit:this._onSubmit,onClose:this._onClose,afterHide:()=>{try{this.afterHide?.(this)}catch(e){Debug.warn(e)}},});this._closeReactRoot=close;}else{resolve(this._base);}}));}
updateSearch(query){if(typeof query!=='string'){throw new TypeError(`The search query for the icon picker must be a string, got a ${typeof query}`);}
if(this.setSearchString instanceof Function){this.setSearchString(query);}else{this._queuedSearch=query;}}
async searchEmojis(){let store=await EmojiSearchTree.search(this._searchString,this.customEmoji,this.panelMode?20:null,!!this.panelMode,this.nativeEmoji!==false);const out={};for(const category in store){out[category]=[...Object.keys(store[category].emojis)].map(unicode=>{const emojiData=store[category].emojis[unicode]
let hairStyle=this._emojiHairStyle||'';let skinTone=this._emojiSkinTone||'';return{raw:EmojiSearchTree.codePointsToString(emojiData.unicode,Number(skinTone)||null,Number(hairStyle)||null),skinTone,hairStyle,image:emojiData.image?.image2x||emojiData.image?.image,key:`${unicode}:${emojiData.skinTones ? skinTone : ''}:${emojiData.hairStyles ? hairStyle : ''}`,title:emojiData.description,type:'emoji'}})}
return out}
async getEmojiTypes(){await EmojiSearchTree.loadEmojiStore(this.panelMode||this.anchor||this.container);const stUnicode=EmojiSearchTree.emojiCodepointMap['270B'].unicode;const hsUnicode=EmojiSearchTree.emojiCodepointMap['1F9D1'].unicode;return[{type:'skin',current:this._emojiSkinTone||'',options:[['',''],...Object.entries(EmojiSearchTree.skinTones)].map(i=>({value:i[0].toString(),label:EmojiSearchTree.codePointsToString(stUnicode,i[0]?`${Number(i[0]).toString(16)}`:null,this._emojiHairStyle),title:i[1]}))},{type:'hair',current:this._emojiHairStyle||'',options:[['',''],...Object.entries(EmojiSearchTree.hairStyles)].map(i=>({value:i[0].toString(),label:EmojiSearchTree.codePointsToString(hsUnicode,this._emojiSkinTone,i[0]?`${Number(i[0]).toString(16)}`:null),title:i[1]}))}];}
async searchFontAwesome(){const icons=[];if(await ips.utils.iconpicker.faIconsEnabled()){for(const[_,iconBase]of ips.utils.fontawesome.searchIcons(this._searchString,{limit:this._searchString?1500:null})){for(const[iconSet,icon]of iconBase){icons.push({...icon,raw:ips.utils.fontawesome.renderIcon({iconName:icon.iconName,prefix:iconSet,useSvg:!!this.svgIcons}).outerHTML,title:iconBase.size>1?`${icon.iconName} (${ips.getString('ipsFa__' + iconSet)})`:icon.iconName,key:`${icon.iconName}:${iconSet}`,selected:(`${icon.iconName}:${iconSet}`in this._selected.fa),type:'fa'})}}}
return{'All icons':icons};}
hide(){this._closeReactRoot?.();}
remove(){return this.hide();}}
class EmojiSearchTree{constructor(){this.children={};this.results=new Set();}
static fixKey(key){return key.trim().toLowerCase().replaceAll(/[^\p{L}\p{N}\p{P}\p{S}_]/ugi,'')}
_addTerm(key,result){key=EmojiSearchTree.fixKey(key)
if(!key.length){this.results.add(result);return;}
if(!this.children[key[0]]){this.children[key[0]]=new EmojiSearchTree();}
this.children[key[0]]._addTerm(key.slice(1),result);}
_search(key){key=EmojiSearchTree.fixKey(key)
if(!key.length){const results=new Set();for(const result of this.results){results.add(result);}
for(const child of Object.values(this.children)){for(const result of child._search('')){results.add(result);}}
return results;}else if(key[0]in this.children){return this.children[key[0]]._search(key.slice(1));}
return new Set();}
static _root=undefined;static async instance(custom=false,includeNative=true){if(!custom&&!includeNative){throw new RangeError(`Need to use at least one of custom or native emojis for the emoji search`);}
const key=(custom?'_rootCustom':'_root')+(includeNative?'':"-no-native")
if(!this[key]){const store=includeNative?{...(await this.loadEmojiStore(custom))}:{...(await this.loadCustomEmojiStore())};this[key]=new EmojiSearchTree();const termMap={}
for(const category in store){const{emojis}=store[category];for(const code in emojis){emojis[code].indexCode=code;emojis[code].shortcode=this.getShortCode(emojis[code].description);termMap[emojis[code].description]=code;}}
for(const name of[...Object.keys(termMap)].sort()){const normalizedName=ips.utils.search.stripAccents(name);const code=termMap[name];const added=new Set();added.add(normalizedName);const shortCode=this.getShortCode(name);if(shortCode){added.add(ips.utils.search.stripAccents(shortCode))}
for(const pattern of[/[^\p{L}\p{N}\p{S}\p{P}_]+/u,/[^\p{L}\p{N}]+/u
]){const components=normalizedName.trim().toLowerCase().split(pattern);for(let i=0;i<components.length;i++){if(!components[i]){continue;}
added.add(components.slice(i).join(''));}}
added.forEach(term=>{this[key]._addTerm(term,code);if(term.includes('smiling')){this[key]._addTerm(term.replace('smiling','smile'),code)}})}}
return this[key];}
static _shortCodeMap={}
static getShortCode(term){if(!(term in this._shortCodeMap)){this._shortCodeMap[term]=term.toLowerCase().trim().replaceAll(/[^\p{L}\p{N}\s]+/gu,'').replaceAll(/\s+/g,'_').replaceAll(/_+/g,'_');}
return this._shortCodeMap[term];}
static async search(key,custom=false,limit=null,mergeCategories=false,includeNative=true){const instance=await this.instance(custom,includeNative);if(!key){const categories=(!includeNative&&custom)?this.customEmojiStoreUnmerged:{...this.emojiStore,...(custom?this.customEmojiStoreMerged:{})}
const out={};for(const name in categories){out[name]={emojis:{},}
for(const unicode in categories[name].emojis){out[name].emojis[unicode]=this.emojiCodepointMap[unicode]||this.customEmojiCodepointMap[unicode];}}
return out;}
key=ips.utils.search.stripAccents(key);const results=instance._search(key);const ret=mergeCategories?{"Search Results":{name:'Search Results',emojis:{}}}:{};let count=0;for(const result of results){if(limit!==null&&count++>limit){break;}
const emojiData=this.emojiCodepointMap[result]||this.customEmojiCodepointMap[result];if(!mergeCategories){const category=this.emojiCategoryMap[result]||this.customEmojiCategoryMap[result];ret[category]=ret[category]||{name:category,emojis:{}}
ret[category].emojis[result]=emojiData;}else{ret['Search Results'].emojis[result]=emojiData;}}
if(!mergeCategories){const sorted={};for(const k in this.emojiStore){if(k in ret){sorted[k]=ret[k]}}
if(custom){for(const k in this.customEmojiStore){if(k in ret){delete sorted[k];sorted[k]=ret;}}}
return sorted;}
return ret;}
static emojiStore=undefined;static customEmojiStore=undefined;static customEmojiStoreMerged=undefined;static customEmojiStoreUnmerged=undefined;static emojiCodepointMap={};static customEmojiCodepointMap={};static hairStyles={};static skinTones={};static emojiCategoryMap={};static customEmojiCategoryMap={};static emojiIndices={};static customEmojiIndices={};static async loadEmojiStore(loadCustom=false){if(this.emojiStore===undefined){try{this.emojiStore=await ips.fetch(ips.getSetting('baseURL')+'/applications/core/interface/static/emoji/emojiIndex.json');for(const[key,{emojis}]of Object.entries(this.emojiStore)){let idx=0;for(const unicode in emojis){const codebase=Number('0x'+unicode.split(/\s+/)[0])
if(0x1f46b<=codebase&&0x1f46d>=codebase){delete this.emojiStore[key].emojis[unicode];continue;}
this.emojiCodepointMap[unicode]=emojis[unicode];this.emojiCategoryMap[unicode]=key;this.emojiIndices[unicode]=idx++;}}}catch(e){Debug.error(e)}
try{const skinTones=await ips.fetch(ips.getSetting('baseURL')+'/applications/core/interface/static/emoji/skinTones.json');for(let code in skinTones){const numeric=this.hex2dec(code);this.skinTones[numeric]=skinTones[code];}}catch(e){Debug.error(e)}
try{const hairStyles=await ips.fetch(ips.getSetting('baseURL')+'/applications/core/interface/static/emoji/hairStyles.json')
for(let code in hairStyles){const numeric=this.hex2dec(code);this.hairStyles[numeric]=hairStyles[code];}}catch(e){Debug.error(e)}}
if(loadCustom){await this.loadCustomEmojiStore()
if(this.customEmojiStoreMerged===undefined){this.customEmojiStoreMerged={...this.emojiStore};for(const k in this.customEmojiStore){let actualKey=k;let i=1;while(actualKey in this.customEmojiStoreMerged){actualKey=k+` ${i++}`}
this.customEmojiStoreMerged[actualKey]={name:actualKey,emojis:this.customEmojiStore[k]}}}
return this.customEmojiStoreMerged}
return this.emojiStore;}
static async loadCustomEmojiStore(){if(this.customEmojiStore===undefined||this.customEmojiStoreUnmerged===undefined){try{this.customEmojiStore=await ips.fetch(ips.getSetting('baseURL'),{data:{app:'core',module:'system',controller:'editor',do:'emoji'}});this.customEmojiStoreUnmerged={};for(const k in this.customEmojiStore){this.customEmojiStoreUnmerged[k]={name:k,emojis:this.customEmojiStore[k]};let idx=0;for(const[unicode,data]of Object.entries(this.customEmojiStore[k])){this.customEmojiCodepointMap[unicode]=data;this.customEmojiCategoryMap[unicode]=k;this.customEmojiIndices[unicode]=idx++;}}}catch(e){Debug.error(e)}}
return this.customEmojiStoreUnmerged||{};}
static zwj(){return this.hex2dec('200D');}
static hex2dec(hex){return typeof hex==="string"?Number('0x'+hex):hex;}
static EMOJI_MAP={}
static codePointsToString(codePoints,skinTone=null,hairStyle=null){if(!Array.isArray(codePoints)){codePoints=codePoints.split(' ');}
const key=JSON.stringify([codePoints,skinTone,hairStyle]);if(!(key in this.EMOJI_MAP)){if(skinTone){skinTone=this.hex2dec(skinTone);if(!(skinTone in EmojiSearchTree.skinTones)){Debug.warn(`A skin tone was given for an emoji that is not a valid supported skin tone`);}}
if(hairStyle){hairStyle=this.hex2dec(hairStyle);if(!(hairStyle in EmojiSearchTree.hairStyles)){Debug.warn(`A hair style was given for an emoji that is not a valid supported hair style`);}}
this.EMOJI_MAP[key]=String.fromCodePoint(...codePoints.map(codePoint=>{if(codePoint==='[[st]]'){return skinTone}
if(codePoint==='[[hs]]'){return hairStyle?[EmojiSearchTree.zwj(),hairStyle]:null}
return this.hex2dec(codePoint)}).flat().filter(i=>!!i))}
return this.EMOJI_MAP[key]}}}(jQuery,_));;
;(function($,_){"use strict";ips.createModule("ips.utils.lazyload",function(){const fixedElements=new WeakSet();const imgDimsCache={_cache:new Map(),get(key){let value;if(!this._cache.has(key)){try{value=ips.utils.db.get('ips.utils.lazyloadImgDims',key);}catch(e){}}else{value=this._cache.get(key);}
return value;},set(key,value){ips.utils.db.set('ips.utils.lazyloadImgDims',key,value,false,Math.round(Date.now()/1000)+86400);return this._cache.set(key,value);},has(key){return this._cache.has(key);},delete(key){ips.utils.db.remove('ips.utils.lazyloadImgDims',key);return this._cache.delete(key);}};return{init(){this.parseLazyLoadElements();$(document).on('contentChange',function(changedElement){try{$(changedElement).each(function(){fixedElements.delete(this);ips.utils.lazyload.parseLazyLoadElements(this);});}catch(e){Debug.warn(`Something went wrong when processing lazy load images`);Debug.warn(e);}})},parseLazyLoadElements(root,useNativeDims=true){root=root instanceof Element?root:document.body;if(root!==document.body&&fixedElements.has(root)){return;}
fixedElements.add(root);root.querySelectorAll(":is([data-src], [data-embed-src]):is(img, audio, video, iframe, object, embed):not(.tiptap *)").forEach(element=>{if(fixedElements.has(element)){return;}
element.dataset.ipsLazyloadProcessed='1'
fixedElements.add(element);const dataSrc=(element.dataset.src||element.dataset.embedSrc)?.trim();if(element.getAttribute('src')?.trim()===dataSrc){delete element.dataset.src;delete element.dataset.embedSrc;return;}
Debug.log(`Found legacy lazy loading ${element.tagName.toLowerCase()}. src: ${dataSrc}`);element.setAttribute('loading','lazy');element.setAttribute('src',dataSrc);delete element.dataset.src;delete element.dataset.embedSrc;if(element.matches('img')){let width=parseFloat(element.getAttribute('width')||'');let height=parseFloat(element.getAttribute('height')||'');if(width&&height&&!Number.isNaN(width)&&!Number.isNaN(height)){return;}else if(element.style.height||element.style.width){return;}else if(parseFloat(width?.toString()||element.dataset.width||'')&&parseFloat(height?.toString()||element.dataset.height||'')){width=Math.round(parseFloat(width?.toString()||element.dataset.width)*100)/100;height=Math.round(parseFloat(height?.toString()||element.dataset.height)*100)/100;}else if(parseFloat(width?.toString()||element.dataset.width||'')&&parseFloat(element.dataset.ratio||'')){width=Math.round(parseFloat(width?.toString()||element.dataset.width)*100)/100;height=Math.round((width/parseFloat(element.dataset.ratio))*100)/100;}else if(parseFloat(height?.toString()||element.dataset.height||'')&&parseFloat(element.dataset.ratio||'')){height=Math.round(parseFloat(height?.toString()||element.dataset.height)*100)/100;width=Math.round(height*parseFloat(element.dataset.ratio)*100)/100;}
if(typeof height==="number"&&typeof width==="number"&&height>0&&width>0){Debug.log(`Determined the width and height from data- attributes as ${width} and ${height}`);element.setAttribute('width',width.toString());element.setAttribute('height',height.toString());}else if(useNativeDims){this.getNativeImgDims(element.getAttribute('src')).then(dims=>{if(dims){Debug.log(`Determined the width and height from the URL as ${dims.width} and ${dims.height}`);element.setAttribute('width',dims.width.toString());element.setAttribute('height',dims.height.toString());}}).catch(err=>{Debug.warn(`Failed to determine the native dims of the image at the URL ${element.getAttribute('url')}`);Debug.warn(err);})}}});},getNativeImgDims(url){return new Promise(_resolve=>{let done=false;let timeout;const resolve=val=>{if(timeout!==undefined){clearTimeout(timeout);}
if(done){return;}
done=true;_resolve(val);};try{let output={width:0,height:0};url=new URL(url);if(imgDimsCache.has(url.toString())){resolve(imgDimsCache.get(url.toString()));return;}
const img=new Image();timeout=setTimeout(()=>{imgDimsCache.set(url.toString(),undefined);resolve(undefined);},3000);img.addEventListener('load',()=>{output.width=img.naturalWidth;output.height=img.naturalHeight;if(Number.isNaN(output.width)||Number.isNaN(output.height)||output.width<=0||output.height<=0){imgDimsCache.set(url.toString(),undefined);resolve(undefined);return;}
output.height=Math.max(1,Math.round(output.height*100)/100);output.width=Math.max(1,Math.round(output.width*100)/100);imgDimsCache.set(url.toString(),output);resolve(output);});img.addEventListener('error',()=>{imgDimsCache.set(url.toString(),undefined);resolve(undefined);});img.src=url.toString();}catch(e){resolve(undefined);}});}}});})(jQuery,_);;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.links',function(){var updateExternalLinks=function(element){if(ips.getSetting('links_external')){if(_.isUndefined(element)){return;}
element.find('a[rel*="external"]').each(function(index,elem){elem.target="_blank";elem.rel=elem.rel.replace(" noopener","")+" noopener";});}};return{updateExternalLinks:updateExternalLinks};});}(jQuery,_));;
;(function($,_){"use strict";ips.createModule('ips.utils.notification',function(){const supported=!!(window.Notification?.requestPermission instanceof Function&&ips.getSetting('pushPublicKey')!==null);async function requestPermission(){if(supported)
$(document).trigger((await Notification.requestPermission())==='granted'?'permissionGranted.notifications':'permissionDenied.notifications')}
async function subscribeToPush(){$(document).trigger('subscribePending.notifications');const registration=await ips.utils.serviceWorker.registerServiceWorker('front',true);const options={userVisibleOnly:true,applicationServerKey:ips.utils.urlBase64ToUint8Array(ips.getSetting('pushPublicKey'))};const subscription=JSON.stringify(await registration.pushManager.subscribe(options));try{await ips.fetch(ips.getSetting('baseURL')+'index.php?app=core&module=system&controller=notifications&do=subscribeToPush',{method:'POST',data:{subscription,encoding:PushManager.supportedContentEncodings?.[0]||'aesgcm'}})
$(document).trigger('subscribeSuccess.notifications')}catch(e){$(document).trigger('subscribeFail.notifications')}}
function hasPermission(){return supported&&!ips.utils.cookie.get('noBrowserNotifications')&&!['denied','default'].includes(Notification.permission);}
async function getSubscription(){try{const registration=await ips.utils.serviceWorker.getRegistration()
const subscription=await registration.pushManager.getSubscription()
return subscription||false;}catch(e){Debug.log(e)}}
function clearBadgeCount(){if(!this.hasPermission()){return;}
if('clearAppBadge'in navigator){navigator.clearAppBadge().catch((e)=>{Debug.log(e);});}else if('setAppBadge'in navigator){navigator.setAppBadge(0).catch((e)=>{Debug.log(e);});}}
function needsPermission(){return supported&&!ips.utils.cookie.get('noBrowserNotifications')&&Notification.permission==='default';}
function permissionLevel(){return supported?Notification.permission:null;}
function create(options){try{return new IpsNotification(options);}catch(e){}}
class IpsNotification{_notification=null;_options={title:'',body:'',icon:'',timeout:false,tag:'',dir:$('html').attr('dir')||'ltr',lang:$('html').attr('lang')||'',onShow(){},onHide(){},onClick(){},onError(){}}
constructor(options){this._notification=null;Object.assign(this._options,options)
this._options.body=_.unescape(this._options.body.replace(/&#039;/g,"'").replace(/<[^>]*?(?:>|$)/g,''));this._options.title=_.unescape(this._options.title.replace(/&#039;/g,"'"));}
show(){this._notification=new Notification(this._options.title,this._options);this._notification.addEventListener('show',this._options.onShow,false);this._notification.addEventListener('hide',this._options.onHide,false);this._notification.addEventListener('click',this._options.onClick,false);this._notification.addEventListener('error',this._options.onError,false);if(!Number.isNaN(this._options.timeout)){setTimeout(()=>this.hide(),Number(this._options.timeout)*1000);}}
hide(){if(this._notification){this._notification.close();this._notification.removeEventListener('show',this._options.onShow,false);this._notification.removeEventListener('hide',this._options.onHide,false);this._notification.removeEventListener('click',this._options.onClick,false);this._notification.removeEventListener('error',this._options.onError,false);}}}
$(document).on('requestPermission.notifications',requestPermission);$(document).on('permissionGranted.notifications',subscribeToPush);return{supported,subscribeToPush,hasPermission,getSubscription,needsPermission,permissionLevel,requestPermission,create,clearBadgeCount};});}(jQuery,_));;
;((($,_)=>{"use strict";ips.createModule('ips.utils.pagebuildericons',function(){const loadPagebuilder=async()=>{if(!ips.utils.pagebuilder){const url=ips.getSetting('baseURL')+`/applications/core/interface/static/pagebuilder/manifest.json?v=${ips.getSetting('pagebuilderKey')}&antiCache=${encodeURIComponent(ips.getSetting('jsAntiCache'))}`;const data=await ips.fetch(url)
const toLoad=[];for(const key in data){if(data[key].file?.match(/\.css$/i)){const href=ips.getSetting('baseURL')+'/applications/core/interface/static/pagebuilder/'+data[key].file+`?antiCache=${encodeURIComponent(ips.getSetting('jsAntiCache'))}`;if(!document.querySelector(`[href="${encodeURI(href)}"]`)){const style=document.createElement('link')
style.rel='stylesheet'
style.href=href
document.head.appendChild(style)}}else if(data[key].isEntry){toLoad.push(ips.getSetting('baseURL')+'/applications/core/interface/static/pagebuilder/'+data[key].file)}}
if(toLoad.length){await ips.loader.getStatic(toLoad)}}}
const fillIcons=()=>{document.querySelectorAll('[for*="elCheckbox_dev_widget_layouts_"]').forEach(async label=>{if(!label.querySelector('svg.pagebuildericon')){await loadPagebuilder()
const icon=label.getAttribute('for').match(/^elCheckbox_dev_widget_layouts_([a-z\-_]+)$/i)[1]
ips.utils.pagebuilder.fillSemanticIcon(label,icon).then(()=>{label.querySelector('svg.pagebuildericon').dataset.ipstooltip=''
label.querySelector('svg.pagebuildericon').setAttribute('title',ips.getString(`core_pagebuilder_wrap__${icon}`))})}})}
$(document).on('contentChange',fillIcons)
fillIcons()
return{}})})(jQuery,_));
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.position',function(){const CACHED_DATA=new Map();let caching=false;function startCaching(){caching=true;return true;}
function endCaching(elem){elem=elem?$(elem).get(0):elem;if(elem){CACHED_DATA.delete(elem);}else{CACHED_DATA.clear();caching=false;}
return true;}
function getElemPositionOld(elem){let _elem=elem;const ogReturn=ips.logTime(()=>{let elem=_elem;if(!elem){return false;}
var props={};var hidden=!elem.is(':visible');var opacity=elem.css('opacity');if(hidden){elem.css({opacity:"0.0001"}).show();}
var offset=elem.offset();var position=elem.position();var dims=getElemDims(elem);props.absPos={left:offset.left,top:offset.top,right:(offset.left+dims.outerWidth),bottom:(offset.top+dims.outerHeight),};props.offsetPos={left:position.left,top:position.top,right:(position.left+dims.outerWidth),bottom:(position.top+dims.outerHeight)};props.viewportOffset={left:offset.left-window.scrollX,top:offset.top-window.scrollY};props.offsetParent=elem.offsetParent();props.fixed=(hasFixedParents(elem,true));if(hidden){elem.hide().css({opacity:String(opacity)});}
return props;},'Got position with jquery')
const newReturn=ips.logTime(()=>getElemPositionNew(_elem),'Got the position with native js');ips.logTime(()=>{},{ogReturn,newReturn});if(ogReturn){for(const rootKey in ogReturn){if(rootKey==='offsetParent'){if(ogReturn[rootKey].get(0)!==newReturn?.[rootKey]?.get(0)){ips.logTime(()=>{},`${rootKey} is different`);}}else if(typeof ogReturn[rootKey]==="object"){for(const k in ogReturn[rootKey]){if(ogReturn[rootKey][k]!==newReturn?.[rootKey]?.[k]&&!(typeof ogReturn[rootKey][k]==='number'&&typeof newReturn?.[rootKey]?.[k]==="number"&&Math.round(ogReturn[rootKey][k]*100)===Math.round(newReturn[rootKey][k]*100))){ips.logTime(()=>{},`${rootKey}.${k} is different`);}}}else if(ogReturn[rootKey]!==newReturn?.[rootKey]){ips.logTime(()=>{},`${rootKey} is different`);}}}else if(newReturn){ips.logTime(()=>{},'Old and new return differ');}
return ogReturn;}
function getOffsetParent(elem,includeElem=false,eventualStyle={}){elem=$(elem).get(0);if(!includeElem){return elem.offsetParent||document.body;}
let child=document.createElement('span');Object.assign(child.style,eventualStyle);child.style.opacity='0';elem.appendChild(child);setTimeout(()=>child.remove());return child.offsetParent||document.body;}
function getElemPosition(elem){if(!elem){return false;}
elem=$(elem).get(0);const toReturn={};const{rect,style}=getElemRectAndStyle(elem);const{rect:docRect}=getElemRectAndStyle(document.body);toReturn.absPos={left:rect.left-docRect.left,top:rect.top-docRect.top,right:rect.right-docRect.left,bottom:rect.bottom-docRect.top,};const offsetParent=getOffsetParent(elem)||document.body;const marginBlockStart=getPxFromDim(style.marginTop);const marginInlineStart=getPxFromDim(style.marginLeft);const{rect:offsetParentRect,style:offsetParentStyle}=getElemRectAndStyle(offsetParent);const offsetParentBorderLeft=getPxFromDim(offsetParentStyle.borderLeftWidth);const offsetParentBorderTop=getPxFromDim(offsetParentStyle.borderTopWidth);const offsetLeft=offsetParentRect.left+offsetParentBorderLeft;const offsetTop=offsetParentRect.top+offsetParentBorderTop;toReturn.offsetPos={left:rect.left+marginInlineStart-offsetLeft,top:rect.top+marginBlockStart-offsetTop,right:rect.right+marginInlineStart-offsetLeft,bottom:rect.bottom+marginBlockStart-offsetTop,};toReturn.viewportOffset={left:rect.left,top:rect.top,};toReturn.offsetParent=$(offsetParent);toReturn.fixed=hasFixedParents($(elem),true);return toReturn;}
function getPxFromDim(dim){const match=dim?.trim?.().match?.(/^-?(\d+|\d+\.\d*|\.\d+)px$/);if(match){return parseFloat(match[1])}
return 0;}
function positionElem(options){const trigger=$(options.trigger);const triggerPos=getElemPosition(trigger);const triggerDims=getElemDims(trigger);const targetDims=getElemDims(options.target);const toReturn={};const stemOffset=options.stemOffset||{top:0,left:0};let offsetParent;let positioned=false;options.targetContainer=options.targetContainer?getOffsetParent(options.targetContainer,true):$(getOffsetParent(options.target));if(options.targetContainer&&$(options.targetContainer).length){if(hasFixedParents(trigger)){offsetParent=triggerPos.viewportOffset;}else{const containerPos=getElemPosition(options.targetContainer);offsetParent={left:(triggerPos.absPos.left-containerPos.absPos.left),top:(triggerPos.absPos.top-containerPos.absPos.top)};}
positioned=true;}else{offsetParent=triggerPos.viewportOffset;}
const bestFit=_getBestFit(triggerPos.viewportOffset,triggerDims,targetDims,stemOffset,{horizontal:(options.center)?'center':'left',vertical:(options.above===true||options.above==='force')?'top':'bottom'},(options.above==='force')?false:!options.above,!(options.above==='force'));switch(bestFit.horizontal){case'center':toReturn.left=offsetParent.left+(triggerDims.outerWidth/2)-
(targetDims.outerWidth/2);break;case'left':toReturn.left=offsetParent.left-stemOffset.left+(triggerDims.outerWidth/2);break;case'right':toReturn.left=offsetParent.left-targetDims.outerWidth+
(triggerDims.outerWidth/2)+stemOffset.left;break;}
switch(bestFit.vertical){case'top':toReturn.top=offsetParent.top-targetDims.outerHeight+
stemOffset.top;break;case'bottom':toReturn.top=offsetParent.top+triggerDims.outerHeight-
stemOffset.top;break;}
if(!positioned&&!triggerPos.fixed){toReturn.top+=window.scrollY;}
toReturn.fixed=triggerPos.fixed;toReturn.location=bestFit;return toReturn;}
function hasFixedParents(elem,andSelf){elem=$(elem).get(0);if(!andSelf){elem=elem.parentElement;}
while(elem instanceof Element){if(elem.style.position==='fixed'){return true;}
elem=elem.parentElement;}
return false;}
function getElemRectAndStyle(elem){elem=$(elem).get(0);if(!(elem instanceof Element)){const tempel=document.createElement('div');return{style:getComputedStyle(tempel),rect:tempel.getBoundingClientRect(),}}
const cached=caching&&CACHED_DATA.get(elem);if(cached){return cached;}
let style=getComputedStyle(elem);let rect;if(style.display==='contents'){function checkChildren(el){for(const child of el.children){const childStyle=getComputedStyle(child);if(childStyle.position!=='static'){continue;}
if(childStyle.display==='contents'){checkChildren(child);}else{const childRect=getElemRectAndStyle(child).rect;rect=rect||childRect;if(rect!==childRect){rect=new DOMRect(Math.min(rect.left,childRect.left),Math.min(rect.y,childRect.y),Math.max(rect.width,childRect.width),Math.max(rect.height,childRect.height));}}}}
checkChildren(elem);if(!rect){rect=elem.getBoundingClientRect();}}else{rect=elem.getBoundingClientRect();}
const revertValues={};if(!rect.width&&!rect.height&&!rect.top&&!rect.bottom){Debug.warn("Attempting to get the rect and style of an element that is not visible. Will attempt to show the element briefly");const toSet={position:'absolute',visibility:'hidden',display:'block'};for(const k in toSet){revertValues[k]=elem.style[k];elem.style[k]=toSet[k];}
let time=Date.now();while(Date.now()-time<5){continue;}
rect=elem.getBoundingClientRect();style=getComputedStyle(elem);for(const k in revertValues){elem.style[k]=revertValues[k]||"";}
time=Date.now();while(Date.now()-time<5){continue;}}
const ret={rect,style};if(caching){CACHED_DATA.set(elem,ret);}
return ret;}
function _getBestFit(viewportOffset,triggerDims,targetDims,offset,posDefaults,preferBottom,attemptToFit){const position={vertical:'bottom',horizontal:'left',...(posDefaults||{})};if(position.horizontal==='center'){const targetLeft=viewportOffset.left+(triggerDims.outerWidth/2)-(targetDims.outerWidth/2);const targetRight=targetLeft+targetDims.outerWidth;if(targetLeft<0||targetRight>window.innerWidth){position.horizontal='left';}}
if(position.horizontal==='left'){if((viewportOffset.left+(triggerDims.outerWidth/2)+targetDims.outerWidth-offset.left)>window.innerWidth){position.horizontal='right';}}
if(position.horizontal==='right'){if((viewportOffset.right-(triggerDims.outerWidth/2)-targetDims.outerWidth+offset.left)<0){position.horizontal='left';}}
if(attemptToFit){if(position.vertical==='top'||preferBottom){if((viewportOffset.top-targetDims.outerHeight-offset.top)<0){position.vertical='bottom';}}else{if((viewportOffset.top+triggerDims.outerHeight+targetDims.outerHeight+offset.top)>window.innerHeight){position.vertical='top';}}}
return position;}
function getElemDimsOld(_elem){const newReturn=ips.logTime(()=>getElemDimsNew(_elem),'got dims native js');const ogReturn=ips.logTime(()=>{let elem=$(_elem);return{width:elem.width(),height:elem.height(),outerWidth:elem.outerWidth(),outerHeight:elem.outerHeight()};},'got dims jquery')
console.log(ogReturn,newReturn,$(_elem).get(0));for(const rootKey in ogReturn){if(rootKey==='offsetParent'){if(ogReturn[rootKey].get(0)!==newReturn?.[rootKey]?.get(0)){ips.logTime(()=>{},`${rootKey} is different`);}}else if(typeof ogReturn[rootKey]==="object"){for(const k in ogReturn[rootKey]){if(ogReturn[rootKey][k]!==newReturn?.[rootKey]?.[k]&&!(typeof ogReturn[rootKey][k]==='number'&&typeof newReturn?.[rootKey]?.[k]==="number"&&Math.round(ogReturn[rootKey][k]*100)===Math.round(newReturn[rootKey][k]*100))){ips.logTime(()=>{},`${rootKey}.${k} is different`);}}}else if(ogReturn[rootKey]!==newReturn?.[rootKey]&&!(typeof ogReturn[rootKey]==="number"&&typeof newReturn?.[rootKey]==='number'&&Math.round(ogReturn[rootKey]*100)===Math.round(newReturn[rootKey]*100))){ips.logTime(()=>{},`${rootKey} is different ${ogReturn[rootKey]} vs ${newReturn?.[rootKey]}`);}}
return ogReturn;}
function getElemDims(elem){elem=$(elem).get(0);if(!(elem instanceof Element)){return{width:0,height:0,outerWidth:0,outerHeight:0}}
const{rect,style}=getElemRectAndStyle(elem);const paddingLeft=getPxFromDim(style.paddingLeft);const paddingRight=getPxFromDim(style.paddingRight);const paddingTop=getPxFromDim(style.paddingTop);const paddingBottom=getPxFromDim(style.paddingBottom);const borderTopWidth=getPxFromDim(style.borderTopWidth);const borderBottomWidth=getPxFromDim(style.borderBottomWidth);const borderLeftWidth=getPxFromDim(style.borderLeftWidth);const borderRightWidth=getPxFromDim(style.borderRightWidth);return{width:rect.width-paddingLeft-paddingRight-borderLeftWidth-borderRightWidth,height:rect.height-paddingTop-paddingBottom-borderBottomWidth-borderTopWidth,outerWidth:rect.width,outerHeight:rect.height};}
function naturalWidth(elem){return _getNatural(elem,'Width');}
function naturalHeight(elem){return _getNatural(elem,'Height');}
function lineHeight(parent){parent=$(parent).get(0);const text=document.createTextNode('A');parent.append(text);const height=text.getBoundingClientRect().height;parent.removeChild(text);text.remove();return height;}
function _getNatural(elem,type){const ret=elem[0]['natural'+type];if(typeof ret==='number'){return ret;}
return 0;}
return{getElemPosition,getElemDims,positionElem,hasFixedParents,naturalWidth,naturalHeight,lineHeight,getElemRectAndStyle,startCaching,endCaching,};});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.createModule('ips.utils.responsive',function(options){options=$.extend({breakpoints:{980:'desktop',768:'tablet',0:'phone'}});var self=this,previousBreakpoint=[],currentBreakpoint=[],breakpointsBySize={},breakpointsByKey={},callbacks={};var currentIs=function(toCheck){if(_.isNumber(toCheck)){return currentBreakpoint[0]==toCheck;}else{return toCheck&&currentBreakpoint[1]==toCheck;}},getCurrentKey=function(){return currentBreakpoint[1];},getAllBreakpoints=function(){return breakpointsBySize;},addBreakpoint=function(breakpoint,name){breakpointsBySize[breakpoint]=name;breakpointsByKey[name]=breakpoint;callbacks[breakpoint]={enter:[],exit:[]};},addCallback=function(breakpoint,type,callback){if(!breakpointsBySize[breakpoint]||(type!='enter'&&type!='exit')){return false;}
callbacks[breakpoint][type].push(callback);},checkForBreakpointChange=function(){var newBreak=getCurrentBoundary();if(newBreak!=currentBreakpoint[0]){executeCallbacks(newBreak,currentBreakpoint[0]);previousBreakpoint=currentBreakpoint;currentBreakpoint=[newBreak,breakpointsBySize[newBreak]];$(document).trigger('breakpointChange',{curBreakSize:newBreak,curBreakName:breakpointsBySize[newBreak]});}},executeCallbacks=function(enterPoint,exitPoint){if(!_.isUndefined(enterPoint)&&!_.isUndefined(callbacks[enterPoint])&&!_.isUndefined(callbacks[enterPoint]['enter'])&&callbacks[enterPoint]['enter'].length){$.each(callbacks[enterPoint]['enter'],function(idx,thisCallback){thisCallback();});}
if(!_.isUndefined(exitPoint)&&!_.isUndefined(callbacks[exitPoint])&&!_.isUndefined(callbacks[exitPoint]['exit'])&&callbacks[exitPoint]['exit'].length){$.each(callbacks[exitPoint]['exit'],function(idx,thisCallback){thisCallback();});}},getCurrentBoundary=function(){var curWidth=window.innerWidth||$(window).width();var curBreak;var possibleSizes=_.filter(breakpointsByKey,function(num){return curWidth>=num;});if(possibleSizes.length){curBreak=_.max(possibleSizes,function(num){return parseInt(num);});}else{curBreak=_.min(breakpointsByKey,function(num){return parseInt(num);});}
return curBreak;},init=function(){$.each(options.breakpoints,function(size,name){addBreakpoint(size,name);});$(window).on('resize',windowResize);checkForBreakpointChange();},windowResize=function(){checkForBreakpointChange();},enabled=function(){return true;};init();return{addBreakpoint:addBreakpoint,addCallback:addCallback,currentIs:currentIs,getCurrentKey:getCurrentKey,getAllBreakpoints:getAllBreakpoints,enabled:enabled}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.stockart.pixabay',{initialize:function(){this.on('click','.ipsPixabayImage',this.selectImage);this.on('focus','[data-role="pixabaySearch"]',this.searchPixabay);this.on('blur','[data-role="pixabaySearch"]',this.stopSearchPixabay);$('[data-role="pixabayResults"]').on('scroll',this.scrollEvent.bind(this));this.setup();},_typeTimer:null,_lastVal:'',_perPage:20,_status:'init',setup:function(){this.uploader=$(document).find('[data-ipsUploader-name="'+this.scope.attr('data-uploader')+'"]');this._doSearch(null);},searchPixabay:function(e){this._typeTimer=setInterval(_.bind(this._typing,this),1500);},scrollEvent:function(e){var scrollScope=$('[data-role="pixabayResults"]');var scrollHeight=scrollScope[0].scrollHeight;const height=scrollScope.height();var distanceFromBottom=scrollHeight-scrollScope.height()-scrollScope.scrollTop();if(this._status!='ready'){return;}
if(distanceFromBottom<=height*1.2){this._status='loading';var offset=parseInt(this.scope.find('[data-role="pixabayMore"]').attr('data-offset'));this.scope.find('[data-role="pixabayMore"]').attr('data-offset',offset+this._perPage);this.scope.find('[data-role="pixabayMoreLoading"]').removeClass('ipsHide');this._doSearch(this._lastVal);}},stopSearchPixabay:function(e){if(this._typeTimer){clearInterval(this._typeTimer);this._typeTimer=null;}},_typing:function(){var textElem=this.scope.find('[data-role="pixabaySearch"]');if(this._lastVal==textElem.val()){return;}
this.scope.find('[data-role="pixabayMore"]').attr('data-offset',0);this._doSearch(textElem.val());this._lastVal=textElem.val();},async _doSearch(value){var resultsbox=this.scope.find('[data-role="pixabayLoading"]');var offset=parseInt(this.scope.find('[data-role="pixabayMore"]').attr('data-offset'));const changed=value!==this._lastVal
this.elem.classList.add('ipsLoading');if(changed){this.elem.classList.add('ipsPixabay--loading-new-search');}
this._status='loading';value=typeof value==='string'?value.trim():value;let response;const cacheKey=JSON.stringify({value,offset,perPage:this._perPage});if(ips.utils.db.get('pixabaySearch',cacheKey)){response=ips.utils.db.get('pixabaySearch',cacheKey);}else{response=await ips.fetch(ips.getSetting('baseURL')+'?app=core&module=system&controller=pixabay&do=search&offset='+offset+'&limit='+this._perPage,{type:'POST',data:{'search':value}});ips.utils.db.set('pixabaySearch',cacheKey,response,false,Date.now()/1000+900);}
this.elem.classList.remove('ipsLoading');this.elem.classList.remove('ipsPixabay--loading-new-search');if(response.error){resultsbox.html(`<div class="ipsMessage ipsMessage--warning">${response.error}</div>`);this.status='error';}
else
{if(changed){resultsbox.html('');this.elem.scrollTo({top:0});}
_.each(response.images,function(term){const div=document.createElement('div');div.innerHTML=ips.templates.render('core.editor.pixabayThumb',{thumb:term.thumb,url:term.url,imgid:term.imgid,height:term.thumbHeight,width:term.thumbWidth,ratio:term.thumbWidth/term.thumbHeight,});const content=div.querySelector('.ipsPixabayThumb');if(content){resultsbox.append(content);}});if(offset>0||response.pagination.total_count>offset+this._perPage){this.scope.find('[data-role="pixabayMoreLoading"]').addClass('ipsHide');this._status='ready';}
if(response.pagination.total_count<=offset+this._perPage){this.scope.find('[data-role="pixabayMoreLoading"]').addClass('ipsHide');this._status='done';}}},selectImage:function(e){var image=$(e.target);var pluploadObj=this.uploader.get(0);ips.getAjax()(ips.getSetting('baseURL')+'?app=core&module=system&controller=pixabay&do=getById&id='+image.attr('data-id')).done(async function(response){var randomId=Math.random().toString(36).substring(7);var bstr=atob(response.content);var n=bstr.length;var u8arr=new Uint8Array(n);while(n--){u8arr[n]=bstr.charCodeAt(n);}
var file=new File([u8arr],response.filename,{type:response.type});const editorObj=await ips.ui.editorv5.getObjWithInit(pluploadObj.closest('.ipsComposeArea')?.querySelector('[data-ipseditorv5]'))
if(editorObj){editorObj.getInstance().commands.injectAttachments([file])}else{pluploadObj.dispatchEvent(new AttachmentInsertEvent({file,data:{ready(content,data){const insertable=pluploadObj.querySelector(`[data-fileid="${data.fileID}"] [data-action="insertFile"]`)
insertable?.click();}}}));}});this._status='init';this.scope.find('[data-role="pixabaySearch"]').val('');this.scope.find('[data-role="pixabayLoading"]').html('');this.elem.classList.add('ipsLoading');this.scope.trigger('closeDialog');}});class AttachmentInsertEvent extends Event{constructor(data){super('injectFile')
this.data=data;}}}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('core.global.editor.censorBlock',{initialize(){this._words=JSON.parse(this.scope.attr('data-censorblockwords'));this._editorId=$(this.scope).data('editorid');this.setup();},_editorId:null,_editor:null,setup(){Debug.log('setup the censorblock')
this.scope.parent().find('[data-ipseditorv5]').on('editorWidgetInitialized',()=>{this._editor=this.scope.parent().find('[data-ipseditorv5]').data('_editor').getInstance();this._form=this.scope.closest('form');this.on($(this._form).get(0),'submit',this.checkCensorBlock);})},checkCensorBlock(e){let value=this._editor.getHTML();const tempElement=document.createElement('div');tempElement.innerHTML=value;const valueText=tempElement.innerText.toLowerCase();let found=false;let display=this.scope.find('[data-role="editorCensorBlockMessageInternal"]').get(0);display.innerHTML=value
if(this._words.length){display.querySelectorAll('blockquote, pre').forEach(child=>child.remove())
let index=0;const words=[];for(const{word,type}of this._words){if(valueText.includes(word.toLowerCase())){words.push(type==='exact'?word:`[^\\b]*(?:${word})[^\\b]*`);}}
const reggie=new RegExp(`(?:\\b|\\s|^)(?:${ words.join('|') })(?:\\b|\\s|$)`,'ig')
Debug.log(reggie);if(words.length&&$(value).text().match(reggie)){$(display).contents().filter(function(){return this.nodeType===3}).each(function(){const mark='<mark class="ipsMatchWarning i-font-weight_bold i-font-size_2 ipsMatch${index}">'
$(this).replaceWith(_.escape($(this).text().replace(reggie,`${mark}$1</mark>`)).replace(new RegExp(_.escape(mark),'ig'),mark).replace(/&lt;\/mark&gt;/ig,"</mark>").trim());});found=true;}}
if(found){e.preventDefault();e.stopPropagation();this._form.find('input[type="submit"],button[type="submit"]').prop('disabled',false);display.innerHTML=display.innerHTML.replace(/((\s+?)?(\r\n|\r|\n)(\s+?)?)+/g,'<br><br>')
this.scope.show();this._editor?.commands?.focus();}else{this.scope.find('[data-role="editorCensorBlockMessage"]').html('<div data-role="editorCensorBlockMessageInternal"></div>');this.scope.hide();}
return!found},});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.editor.customtags',{editorWrap:null,editorSidebar:null,editorSidebarHeader:null,editorSidebarList:null,initialize:function(){this.on('click','[data-tagKey]',this.insertTag);this.setup();},setup:function(){this.editorWrap=this.scope.find('[data-role="editor"]');this.editorSidebar=this.scope.find('.ipsComposeArea_sidebar');this.editorSidebarList=this.editorSidebar.find('[data-role="tagsList"]');this.editorSidebarHeader=this.editorSidebar.find('[data-role="tagsHeader"]');this.reloadTags();},insertTag:function(e){const content=$(e.currentTarget).attr('data-tagKey');if(this.scope.attr('data-tagFieldType')==='editor'){$('textarea[name="'+this.scope.attr('data-tagFieldID')+'"]').closest('[data-ipsEditorv5]').data('_editor').insertHtml(content);}else if(this.scope.attr('data-tagFieldType')==='codemirror'){this.scope.trigger('codeMirrorInsert',{elemID:$(e.currentTarget).closest('[data-codemirrorid]').attr('data-codemirrorid'),tag:content});}else if(this.scope.attr('data-tagfieldtype')==='codebox'){this.scope.find('[data-ipscodebox]').get(0).dispatchEvent(new CustomEvent('insertCode',{detail:{content}}))}else{const textField=$('#'+this.scope.attr('data-tagFieldID')).get(0);const focused=document.activeElement===textField
if(!focused){textField.setSelectionRange(textField.value.length,textField.value.length)}
textField.setRangeText(content)
textField.focus()}},reloadTags:function(){if(this.scope.attr('data-tagSource')){ips.getAjax()(this.scope.attr('data-tagSource')).done((response,status,jqXHR)=>{this.scope.find('ul[data-role="tagsList"]').html(response)
$(document).trigger('contentChange',[this.scope.find('ul[data-role="tagsList"]')])
this.elem.querySelectorAll('[data-customtags-dialog]').forEach(el=>{el.addEventListener('dialogSubmission',(e)=>{this.reloadTags()})});});}}});}(jQuery,_));;
;(function($,_){"use strict";ips.controller.register('core.global.editor.icon',{elem:undefined,_allowedTypes:null,_currentValue:undefined,_maxIcons:undefined,initialize(){ips.utils.iconpicker.faIconsEnabled();this.elem.querySelector('button[data-role="launcher"]').onclick=async()=>{this.setCurrentValue(await ips.utils.iconpicker.pick({defaultValue:this.getCurrentValue(),allowedTypes:this.getAllowedTypes(),maxIcons:this.getMaxIcons(),svgIcons:'svgIcons'in this.elem.dataset}))}
this.setCurrentValue(this.getCurrentValue())
this.elem.querySelectorAll('[data-role="clear"]').forEach(element=>{if(!(Array.isArray(this._currentValue)&&this._currentValue.length)){element.ipsHide()}
element.onclick=()=>{this.setCurrentValue(null)}});this.fillIcons();},getInputEl(){return this.elem.querySelector('input[data-ips-icon-picker-input]')},getCurrentValue(){if(this._currentValue===undefined){this._currentValue=JSON.parse(this.getInputEl().value);}
return this._currentValue;},getAllowedTypes(){if(!Array.isArray(this._allowedTypes)){this._allowedTypes=this.elem.dataset.allowedIconTypes?.split(",").map(i=>i.trim().toLowerCase())||[];}
return this._allowedTypes},getMaxIcons(){if(this._maxIcons===undefined){this._maxIcons=parseInt(this.elem.dataset.maxIcons||'');if(!(Number.isInteger(this._maxIcons)&&this._maxIcons>0)){this._maxIcons=null;}}
return this._maxIcons;},setCurrentValue(value){try{if(value===null||(Array.isArray(value)&&!value.length)){this.elem.querySelectorAll('[data-role="clear"]').ipsHide()
this._currentValue=null;}else if(Array.isArray(value)){this.elem.querySelectorAll('[data-role="clear"]').ipsShow()
for(const item of value){if(typeof item!=='object'){throw new Error();}
if(!this.getAllowedTypes().includes(item.type)){throw new Error()}
if(typeof item.raw!=='string'||typeof item.title!=='string'){throw new Error()}}
this._currentValue=value;}else{throw new Error();}}catch(e){e.message+='\n\t(An error occurred while setting the input value.)'
Debug.error(e);return;}
this.getInputEl().setAttribute('value',JSON.stringify(value));this.fillIcons();},fillIcons(){const fillArea=this.elem.querySelector('[data-role="selectedicons"]');if(!(Array.isArray(this._currentValue)&&this._currentValue.length)){fillArea.ipsHide();}else{fillArea.innerHTML="";fillArea.ipsShow();for(const iconData of this._currentValue){fillArea.innerHTML+=ips.templates.render('core.iconpicker.selectedicon',iconData)}}}})}(jQuery,_));
;(function($,_,undefined){"use strict";const IMAGE_CACHE={};ips.controller.register('core.global.editor.insertable',{_editorID:'',_selectedItems:{},_tooltip:null,_tooltipTimer:null,initialize:function(){this.on('click','[data-action="insertFile"]',this.insertFile);this.on('click','[data-action="selectFile"]',this.selectFile);this.on('click','[data-action="insertSelected"]',this.insertSelected);this.on('click','[data-action="clearAll"]',this.clearSelection);this.on('fileInjected',this.fileInjected);this.setup();},setup:function(){this._editorID=this.scope.attr('data-editorID');this._selectedItems={};},destruct:function(){Debug.log('destruct insertable');},selectFile:function(e){e.preventDefault();const thisAttach=$(e.currentTarget);const thisDataRow=thisAttach.closest('.ipsData__item');if(thisAttach.hasClass('ipsAttach_selectionOn')){thisAttach.removeClass('ipsAttach_selectionOn');if(thisDataRow.length){thisDataRow.removeClass('ipsData__item--selected');}else{thisAttach.removeClass('ipsAttach_selected');}
this._removeSelectedItem(thisAttach);}else{thisAttach.addClass('ipsAttach_selectionOn');if(thisDataRow.length){thisDataRow.addClass('ipsData__item--selected');}else{thisAttach.addClass('ipsAttach_selected');}
this._addSelectedItem(thisAttach);}},clearSelection(e){e?.preventDefault?.();if(!Object.keys(this._selectedItems).length){return;}
this._selectedItems={};this.scope.find('.ipsAttach_selectionOn').removeClass('ipsAttach_selectionOn').closest('.ipsAttach').removeClass('ipsAttach_selected').end().closest('.ipsData__item').removeClass('ipsData__item--selected');this._checkSelectedButton();},insertSelected(e){e.preventDefault();if(!Object.keys(this._selectedItems).length){return;}
if(!this.scope.get(0).closest('[data-role="attachmentArea"]')){this.trigger('closeDialog');}
const editor=$(document.querySelector(`textarea[name="${this._editorID}"]`).closest('[data-ipsEditorv5]')).data('_editor');for(const item of Object.values(this._selectedItems)){editor.insertHtml(this._buildInsert(item));}
this.clearSelection(e);},async insertFile(e){e?.preventDefault?.();const editor=$(`textarea[name="${this._editorID}"]`).closest('[data-ipsEditorV5]').data('_editor');const insertData=await this._buildInsertData($(e.target));const insertHtml=this._buildInsert(insertData);editor.insertHtml(insertHtml);if(!this.scope.closest('[data-role="attachmentArea"]').length){this.trigger('closeDialog');}},async fileInjected(e,data){const insertData=await this._buildInsertData(data.fileElem)
const content=this._buildInsert(insertData)
data.data?.ready?.(content,insertData)
$(this.scope).get(0).dispatchEvent(new CustomEvent('injectedFileReadyForInsert',{detail:{content,data:data.data}}));},_addSelectedItem:async function(element){const fileID=$(element).attr('data-fileid');this._selectedItems[fileID]=await this._buildInsertData(element);this._checkSelectedButton();},_removeSelectedItem:function(element){var fileID=element.attr('data-fileid');if(!_.isUndefined(this._selectedItems[fileID])){delete this._selectedItems[fileID];}
this._checkSelectedButton();},_checkSelectedButton:function(){const button=this.scope.find('[data-action="insertSelected"]');this.scope.find('[data-action="clearAll"]').toggleClass('ipsButton--disabled',!(_.size(this._selectedItems)>0));button.toggleClass('ipsButton--disabled',!(_.size(this._selectedItems)>0));if(!_.size(this._selectedItems)){button.text(ips.getString('insertSelected'));}else{button.text(ips.pluralize(ips.getString('insertSelectedNum'),_.size(this._selectedItems)));}},async _buildInsertData(_element){const element=$(_element).get(0).closest('.ipsAttach');if(!element){return{fileID:'',fileKey:'',type:'file',title:'',link:'',fullImage:'',extension:'',naturalWidth:null,naturalHeight:null,}}
const fileID=element.getAttribute('data-fileid')||'';const fileKey=element.getAttribute('data-filekey')||'';const type=element.getAttribute('data-fileType')||'file';let url='',image='',mimeType='',naturalWidth='',naturalHeight='';switch(type){case'image':url=element.getAttribute('data-thumbnailurl')||element.getAttribute('data-fullsizeurl')||url;if(url!==element.getAttribute('data-fullsizeurl')){image=element.getAttribute('data-fullsizeurl')||'';}
break
case'video':image=element.getAttribute('data-fullsizeurl');mimeType=element.getAttribute('data-mimeType');break
case'audio':mimeType=element.getAttribute('data-mimeType');break;default:url=element.getAttribute('data-filelink')||'';}
return{fileID:fileID,fileKey:fileKey,type:type,title:(type!=='image')?element.querySelector('[data-role="title"]')?.innerHTML:'',link:url,fullImage:image,extension:element.closest('[data-extension]')?.getAttribute('data-extension')||'',mimeType:mimeType,naturalWidth,naturalHeight};},_buildInsert:function(item){let element;switch(item.type){case'image':element=$('<img/>').attr({'data-fileid':item.fileID,'src':item.link,'data-unique':Math.random().toString(36).substr(2,9),}).addClass('ipsImage ipsImage_thumbnailed');if(item.fullImage){const link=$('<a>').attr('href',item.fullImage).addClass('ipsAttachLink ipsAttachLink_image');element.addClass('ipsImage_thumbnailed');link.append(element);element=link;}
break;case'video':element=$('<video controls>').attr({'class':'ipsEmbeddedVideo','data-controller':'core.global.core.embeddedvideo','data-fileid':item.fileID,'data-unique':Math.random().toString(36).substr(2,9)});const sourceElement=$('<source>').attr({'src':item.fullImage,'type':item.mimeType});element.append(sourceElement);element.append($('<a>').addClass('ipsAttachLink').attr('href',`${ips.getSetting('baseURL')}applications/core/interface/file/attachment.php?id=${item.fileID}${item.fileKey ? `&key=${item.fileKey}` : ''}`).html(item.title));break;case'audio':element=$('<audio controls>').attr({'data-controller':'core.global.core.embeddedaudio','src':`${ips.getSetting('baseURL')}applications/core/interface/file/attachment.php?id=${item.fileID}${item.fileKey ? `&key=${item.fileKey}` : ''}`,'data-fileid':item.fileID,'data-unique':Math.random().toString(36).substring(2,9),'type':item.mimeType});element.append($('<a>').addClass('ipsAttachLink').attr('href',`${ips.getSetting('baseURL')}applications/core/interface/file/attachment.php?id=${item.fileID}${item.fileKey ? `&key=${item.fileKey}` : ''}`).html(item.title));break;default:element=$('<a>').addClass('ipsAttachLink').html(item.title).attr({'data-fileid':item.fileID,'data-fileext':item.extension,'href':item.link?item.link:`${ips.getSetting('baseURL')}applications/core/interface/file/attachment.php?id=${item.fileID}${item.fileKey ? `&key=${item.fileKey}` : ''}`});}
if(item.extension){element.attr('data-extension',item.extension);}
return $('<div/>').append(element).html();}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.editor.mymediasection',{_timer:null,_ajax:null,_value:'',initialize:function(){this.on('focus','[data-role="myMediaSearch"]',this.focusMediaSearch);this.on('blur','[data-role="myMediaSearch"]',this.blurMediaSearch);this.on('paginationClicked paginationJump',this.paginationClicked);},paginationClicked:function(e,data){var results=this.scope.find('[data-role="myMediaResults"]');data.originalEvent.preventDefault();const urlObj=new URL(data.paginationElem.find('[data-role="pageJump"]').attr('action')||"",location.href);urlObj.updateSearchParams({param:'page',value:data.pageNo});const url=urlObj.toString();this._ajax=ips.getAjax()(url,{showLoading:true,data:{search:this._value}}).done(function(response){results.html(response);$(document).trigger('contentChange',[results]);});},focusMediaSearch:function(){this._timer=setInterval(_.bind(this._checkValue,this),700);},blurMediaSearch:function(){clearInterval(this._timer);},_checkValue:function(){var value=this.scope.find('[data-role="myMediaSearch"]').val();if(value==this._value){return;}
this._value=value;this._loadResults();},_loadResults:function(){var self=this;var url=this.scope.attr('data-url');if(this._ajax&&this._ajax.abort){this._ajax.abort();}
this.scope.find('[data-role="myMediaSearch"]').addClass('ipsField_loading');this._ajax=ips.getAjax()(url,{data:{search:this._value}}).done(function(response){self.scope.find('[data-role="myMediaResults"]').html(response);$(document).trigger('contentChange',[self.scope.find('[data-role="myMediaResults"]')]);}).always(function(){self.scope.find('[data-role="myMediaSearch"]').removeClass('ipsField_loading');});}});}(jQuery,_));;
;(function($,_,undefined){"use strict";ips.controller.register('core.global.editor.uploader',{initialize:function(){this.on('addUploaderFile',this.addUploaderFile);this.on('removeAllFiles',this.removeAllFiles);this.on('fileDeleted',this.fileDeleted);this.setup();},setup:function(){this.scope.find('[data-role="fileContainer"]').each(function(){if($(this).children().length>0){$(this).parent().removeClass('ipsHide');}});},removeAllFiles:function(e,data){this.scope.find('[data-role="files"], [data-role="images"], [data-role="videos"], [data-role="audio"]').hide();this.scope.find('[data-role="fileList"]').hide();},addUploaderFile:function(e,data){e.stopPropagation();var container=null;var template='core.attachments.';this.scope.find('[data-role="fileList"]').show();if(data.isImage){container=this.scope.find('[data-role="images"]');template+='imageItem';}else if(data.isVideo){container=this.scope.find('[data-role="videos"]');template+='videoItem';}else if(data.isAudio){container=this.scope.find('[data-role="audio"]');template+='audioItem';}else{container=this.scope.find('[data-role="files"]');template+='fileItem';}
data.extIcon=ips.ui.uploader.getExtensionIcon(data.title);container.show().find('[data-role="fileContainer"]').append(ips.templates.render(template,data));},fileDeleted:function(e,data){var count=0;this.scope.find('[data-role="fileContainer"]').each(function(){if(!$(this).find('.ipsAttach').length){$(this).closest('[data-role="files"], [data-role="images"], [data-role="videos"], [data-role="audio"]').hide();count++;}});if(count==4){this.scope.find('[data-role="fileList"]').hide();}}});}(jQuery,_));;