(function($, window){
'use strict';
window.NggTikTokVideo=window.NggTikTokVideo||{};
let linkHandlersInitialized=false;
const galleryIdCache=new Map();
const DEFAULT_DIMENSIONS={ width: 480, height: 854 };
const ASPECT_RATIO=9 / 16;
const MAX_DEPTH=15;
const INIT_DELAY=100;
NggTikTokVideo.getTikTokSettings=(galleryId)=> {
if(!window.ngg_tiktok_gallery_settings){
window.ngg_tiktok_gallery_settings={
global: {
link: '0',
link_target: '0'
}};}
const settings=window.ngg_tiktok_gallery_settings;
const galleryIdStr=galleryId ? String(galleryId):null;
if(galleryIdStr&&settings[`gallery_${galleryIdStr}`]){
const gallerySettings=settings[`gallery_${galleryIdStr}`];
if(gallerySettings&&(gallerySettings.link!==undefined||gallerySettings.link_target!==undefined)){
return {
link: String(gallerySettings.link ?? '0'),
link_target: String(gallerySettings.link_target ?? '0')
};}}
const globalSettings=settings.global||{};
return {
link: String(globalSettings.link||'0'),
link_target: String(globalSettings.link_target||'0')
};};
const findGalleryId=($anchor, imageId)=> {
const cacheKey=imageId||$anchor[0];
const cachedResult=galleryIdCache.get(cacheKey);
if(cachedResult){
return cachedResult;
}
let $galleryContainer=null;
let galleryId=null;
$galleryContainer=$anchor.closest('[data-gallery-id]');
if($galleryContainer.length){
galleryId=$galleryContainer.attr('data-gallery-id')||$galleryContainer.data('gallery-id');
}
if(!galleryId){
$galleryContainer=$anchor.closest('.ngg-galleryoverview, .ngg-imagebrowser, .ngg-slideshow');
if($galleryContainer.length){
galleryId=$galleryContainer.attr('data-gallery-id') ||
$galleryContainer.data('gallery-id') ||
$galleryContainer.attr('data-nextgen-gallery-id') ||
$galleryContainer.data('nextgen-gallery-id');
}}
if(!galleryId){
let $current=$anchor;
let depth=0;
while (depth < MAX_DEPTH&&$current.length){
if($current.is('[data-gallery-id]')){
galleryId=$current.attr('data-gallery-id')||$current.data('gallery-id');
$galleryContainer=$current;
break;
}
const $sibling=$current.siblings('[data-gallery-id]').first();
if($sibling.length){
galleryId=$sibling.attr('data-gallery-id')||$sibling.data('gallery-id');
$galleryContainer=$sibling;
break;
}
$current=$current.parent();
depth++;
}}
if(!galleryId&&imageId){
const $allContainers=$('[data-gallery-id]');
$allContainers.each(function(){
const $container=$(this);
if($container.find($anchor).length > 0){
galleryId=$container.attr('data-gallery-id')||$container.data('gallery-id');
$galleryContainer=$container;
return false;
}});
}
const result={
galleryId: galleryId ? String(galleryId):null,
$galleryContainer
};
galleryIdCache.set(cacheKey, result);
return result;
};
const getTikTokDataFromAnchor=($anchor, imageId)=> {
if(imageId&&window.ngg_tiktok_images?.[imageId]){
return window.ngg_tiktok_images[imageId];
}
const playUrl=$anchor.attr('data-tiktok-play-url');
const shareUrl=$anchor.attr('data-tiktok-share-url');
const embedUrl=$anchor.attr('data-tiktok-embed-url');
if(playUrl||shareUrl||embedUrl){
return {
playUrl: playUrl||'',
shareUrl: shareUrl||'',
embedUrl: embedUrl||''
};}
return null;
};
const handleTikTokLinkClick=(e)=> {
const anchor=e.target.closest('a[data-image-id]');
if(!anchor){
return;
}
const $anchor=$(anchor);
const imageId=$anchor.attr('data-image-id');
const tiktokData=getTikTokDataFromAnchor($anchor, imageId);
if(!tiktokData){
return;
}
const { galleryId }=findGalleryId($anchor, imageId);
const tiktokSettings=NggTikTokVideo.getTikTokSettings(galleryId);
const linkSetting=String(tiktokSettings.link||'0');
const linkTarget=String(tiktokSettings.link_target||'0');
if(linkSetting!=='1'&&linkSetting!=='2'){
return;
}
if(linkSetting==='1'&&!tiktokData.shareUrl){
return;
}
if(linkSetting==='2'&&!tiktokData.embedUrl&&!tiktokData.shareUrl){
return;
}
e.preventDefault();
e.stopPropagation();
const openNewTab=linkTarget==='1'||linkTarget==='_blank';
let targetUrl='';
if(linkSetting==='1'){
targetUrl=tiktokData.shareUrl||'';
}else if(linkSetting==='2'){
targetUrl=tiktokData.embedUrl||tiktokData.shareUrl||'';
}
if(targetUrl){
if(openNewTab){
window.open(targetUrl, '_blank', 'noopener,noreferrer');
}else{
window.location.href=targetUrl;
}}
};
NggTikTokVideo.initLinkHandlers=()=> {
if(linkHandlersInitialized){
return;
}
linkHandlersInitialized=true;
document.addEventListener('click', handleTikTokLinkClick, true);
};
NggTikTokVideo.isTikTokImage=(element)=> {
const $el=$(element);
const $anchor=$el.is('a') ? $el:$el.closest('a');
if($anchor.attr('data-ngg-tiktok-source')==='true'){
return true;
}
const imageId=$anchor.attr('data-image-id');
if(imageId&&window.ngg_tiktok_images?.[imageId]){
const $galleryContainer=$anchor.closest('[data-gallery-id]');
const galleryId=$galleryContainer.length ? $galleryContainer.attr('data-gallery-id'):null;
const settings=NggTikTokVideo.getTikTokSettings(galleryId);
return String(settings.link||'0')==='0';
}
return false;
};
NggTikTokVideo.getTikTokData=(element)=> {
const $el=$(element);
const $anchor=$el.is('a') ? $el:$el.closest('a');
const playUrl=$anchor.attr('data-ngg-tiktok-play-url');
const shareUrl=$anchor.attr('data-ngg-tiktok-share-url');
const embedUrl=$anchor.attr('data-ngg-tiktok-embed-url');
const tiktokId=$anchor.attr('data-ngg-tiktok-id');
if(playUrl||shareUrl||embedUrl){
return {
tiktokId: tiktokId||'',
playUrl: playUrl||'',
shareUrl: shareUrl||'',
embedUrl: embedUrl||'',
linkSetting: '0'
};}
const imageId=$anchor.attr('data-image-id');
if(imageId&&window.ngg_tiktok_images?.[imageId]){
return window.ngg_tiktok_images[imageId];
}
return null;
};
NggTikTokVideo.getVideoUrl=(tiktokData)=> {
if(!tiktokData){
return '';
}
if(tiktokData.playUrl?.length > 0){
return tiktokData.playUrl;
}
if(tiktokData.shareUrl?.length > 0){
return tiktokData.shareUrl;
}
return '';
};
NggTikTokVideo.getEmbedUrl=(tiktokData)=> {
if(!tiktokData){
return '';
}
if(tiktokData.embedUrl){
return tiktokData.embedUrl;
}
if(tiktokData.shareUrl){
const match=tiktokData.shareUrl.match(/video\/(\d+)/);
if(match?.[1]){
return `https://www.tiktok.com/embed/v2/${match[1]}`;
}}
return '';
};
const createErrorMessage=(message)=> {
return $('<div class="ngg-tiktok-error"></div>')
.text(message)
.css({
color: '#fff',
textAlign: 'center',
padding: '20px'
});
};
const createVideoElement=(videoUrl, autoplay, onReady, onError)=> {
const $video=$('<video></video>').attr({
src: videoUrl,
controls: true,
autoplay: autoplay,
playsinline: true,
preload: 'auto'
}).css({
width: '100%',
height: '100%',
objectFit: 'contain'
});
$video.on('loadeddata', ()=> {
onReady($video[0]);
});
$video.on('error', ()=> {
$video.remove();
onError(new Error('Video failed to load'));
});
return $video;
};
NggTikTokVideo.createPlayer=(options={})=> {
const {
tiktokData,
width=DEFAULT_DIMENSIONS.width,
height=DEFAULT_DIMENSIONS.height,
autoplay=true,
onReady=()=> {},
onError=()=> {}}=options;
const $container=$('<div class="ngg-tiktok-video-container"></div>').css({
position: 'relative',
width,
height,
maxWidth: '100%',
maxHeight: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
});
const videoUrl=NggTikTokVideo.getVideoUrl(tiktokData);
if(videoUrl&&videoUrl.includes('tiktokcdn.com')){
const $video=createVideoElement(videoUrl, autoplay, onReady, (error)=> {
$container.append(createErrorMessage('Video failed to load'));
onError(error);
});
$container.append($video);
}else{
$container.append(createErrorMessage('Video not available'));
onError(new Error('No video URL available'));
}
return $container;
};
NggTikTokVideo._createEmbedPlayer=($container, embedUrl, width, height, autoplay, onReady, onError)=> {
$container.empty();
if(!embedUrl){
$container.append(createErrorMessage('Video not available'));
onError(new Error('No embed URL available'));
return;
}
const url=autoplay
? `${embedUrl}${embedUrl.includes('?') ? '&':'?'}autoplay=1`
: embedUrl;
const $iframe=$('<iframe></iframe>').attr({
src: url,
frameborder: '0',
allowfullscreen: true,
allow: 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture'
}).css({
width: '100%',
height: '100%',
border: 'none'
});
$iframe.on('load', ()=> {
onReady($iframe[0]);
});
$iframe.on('error', ()=> {
onError(new Error('Failed to load TikTok embed'));
});
$container.append($iframe);
};
NggTikTokVideo.replaceImageWithVideo=(imageElement, options={})=> {
const $image=$(imageElement);
const $anchor=$image.closest('a');
const tiktokData=options.tiktokData||NggTikTokVideo.getTikTokData($anchor);
if(!tiktokData){
return null;
}
const width=options.width||$image.width()||DEFAULT_DIMENSIONS.width;
const height=options.height||$image.height()||DEFAULT_DIMENSIONS.height;
const playerOptions={
...options,
tiktokData,
width,
height
};
const $player=NggTikTokVideo.createPlayer(playerOptions);
$image.replaceWith($player);
return $player;
};
NggTikTokVideo.createLightboxPlayer=(tiktokData, lightboxOptions={})=> {
const {
maxWidth=window.innerWidth * 0.8,
maxHeight=window.innerHeight * 0.9,
onReady,
onError
}=lightboxOptions;
let width, height;
if(maxHeight * ASPECT_RATIO <=maxWidth){
height=maxHeight;
width=height * ASPECT_RATIO;
}else{
width=maxWidth;
height=width / ASPECT_RATIO;
}
return NggTikTokVideo.createPlayer({
tiktokData,
width: Math.round(width),
height: Math.round(height),
autoplay: true,
onReady,
onError
});
};
NggTikTokVideo.destroyPlayer=($container)=> {
if(!$container?.length){
return;
}
const $video=$container.find('video');
if($video.length){
$video[0].pause();
$video.attr('src', '');
}
const $iframe=$container.find('iframe');
if($iframe.length){
$iframe.attr('src', '');
}
$container.remove();
};
$(()=> {
setTimeout(()=> {
NggTikTokVideo.initLinkHandlers();
}, INIT_DELAY);
});
})(jQuery, window);
(function($){
"use strict";
window.NextGEN_Video={
detect_platform: function(url){
if(!url) return null;
url=url.trim().toLowerCase();
if(url.match(/youtube\.com|youtu\.be|youtube-nocookie\.com/)){
return 'youtube';
}
if(url.match(/vimeo\.com/)){
return 'vimeo';
}
if(url.match(/dailymotion\.com|dai\.ly/)){
return 'dailymotion';
}
if(url.match(/twitch\.tv/)){
return 'twitch';
}
if(url.match(/videopress\.com|video\.wordpress\.com/)){
return 'videopress';
}
if(url.match(/wistia\.com|wistia\.net/)){
return 'wistia';
}
if(url.match(/\.(mp4|webm|ogg|ogv|mov|avi|wmv|flv|mkv)(\?|$)/i)){
return 'local';
}
return null;
},
extract_youtube_id: function(url){
if(!url) return null;
var patterns=[
/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube-nocookie\.com\/embed\/)([^&\n?#]+)/,
/youtube\.com\/.*[?&]v=([^&\n?#]+)/,
];
for (var i=0; i < patterns.length; i++){
var match=url.match(patterns[i]);
if(match&&match[1]){
return match[1];
}}
return null;
},
extract_vimeo_id: function(url){
if(!url) return null;
var patterns=[
/vimeo\.com\/(\d+)/,
/vimeo\.com\/.*\/(\d+)/,
/player\.vimeo\.com\/video\/(\d+)/,
];
for (var i=0; i < patterns.length; i++){
var match=url.match(patterns[i]);
if(match&&match[1]){
return match[1];
}}
return null;
},
extract_dailymotion_id: function(url){
if(!url) return null;
var patterns=[
/dailymotion\.com\/video\/([^/?]+)/,
/dai\.ly\/([^/?]+)/,
/dailymotion\.com\/embed\/video\/([^/?]+)/,
];
for (var i=0; i < patterns.length; i++){
var match=url.match(patterns[i]);
if(match&&match[1]){
return match[1];
}}
return null;
},
extract_twitch_id: function(url){
if(!url) return null;
var videoMatch=url.match(/twitch\.tv\/videos\/(\d+)/);
if(videoMatch&&videoMatch[1]){
return { videoId: videoMatch[1], type: 'video' };}
var clipMatch=url.match(/(?:twitch\.tv\/|clips\.twitch\.tv\/)([^/?]+)/);
if(clipMatch&&clipMatch[1]){
return { videoId: clipMatch[1], type: 'clip' };}
return null;
},
extract_videopress_id: function(url){
if(!url) return null;
var patterns=[
/videopress\.com\/v\/([^/?]+)/,
/video\.wordpress\.com\/v\/([^/?]+)/,
];
for (var i=0; i < patterns.length; i++){
var match=url.match(patterns[i]);
if(match&&match[1]){
return match[1];
}}
return null;
},
extract_wistia_id: function(url){
if(!url) return null;
var patterns=[
/wistia\.(?:com|net)\/medias\/([^/?]+)/,
/wistia\.(?:com|net)\/embed\/([^/?]+)/,
];
for (var i=0; i < patterns.length; i++){
var match=url.match(patterns[i]);
if(match&&match[1]){
return match[1];
}}
return null;
},
get_embed_url: function(platform, videoId, settings){
if(!platform||!videoId) return null;
settings=settings||{};
var autoplay=settings.autoplay_videos ? 1:0;
var controls=settings.show_video_controls!==false ? 1:0;
switch (platform){
case 'youtube':
var youtubeId=typeof videoId==='string' ? videoId:videoId.videoId;
return 'https://www.youtube.com/embed/' + youtubeId +
'?autoplay=' + autoplay +
'&controls=' + controls +
'&rel=0&modestbranding=1';
case 'vimeo':
var vimeoId=typeof videoId==='string' ? videoId:videoId.videoId;
return 'https://player.vimeo.com/video/' + vimeoId +
'?autoplay=' + autoplay +
'&controls=' + controls;
case 'dailymotion':
var dmId=typeof videoId==='string' ? videoId:videoId.videoId;
return 'https://www.dailymotion.com/embed/video/' + dmId +
'?autoplay=' + autoplay +
'&controls=' + controls;
case 'twitch':
var twitchData=typeof videoId==='object' ? videoId:{ videoId: videoId, type: 'video' };
if(twitchData.type==='clip'){
return 'https://clips.twitch.tv/embed?clip=' + twitchData.videoId +
'&autoplay=' + autoplay +
'&parent=' + window.location.hostname;
}else{
return 'https://player.twitch.tv/?video=v' + twitchData.videoId +
'&autoplay=' + autoplay +
'&parent=' + window.location.hostname;
}
case 'videopress':
var vpId=typeof videoId==='string' ? videoId:videoId.videoId;
return 'https://videopress.com/embed/' + vpId +
'?autoplay=' + autoplay +
'&controls=' + controls;
case 'wistia':
var wistiaId=typeof videoId==='string' ? videoId:videoId.videoId;
return 'https://fast.wistia.net/embed/iframe/' + wistiaId +
'?autoplay=' + autoplay +
'&controlsVisibleOnLoad=' + controls;
case 'local':
return typeof videoId==='string' ? videoId:null;
default:
return null;
}},
create_local_player: function(videoUrl, settings, containerClass, videoClass){
var container=document.createElement("div");
container.className=containerClass||"ngg-video-container";
var video=document.createElement("video");
video.className=videoClass||"ngg-video-player";
video.controls=settings.show_video_controls!==false;
video.autoplay=settings.autoplay_videos===true;
video.playsInline=true;
video.preload="auto";
video.setAttribute("playsinline", "");
video.setAttribute("webkit-playsinline", "");
video.src=videoUrl;
video.addEventListener("error", function(e){
console.error("Video player error:", {
error: e,
videoUrl: videoUrl,
errorCode: video.error ? video.error.code:"unknown",
errorMessage: video.error ? video.error.message:"Unknown error"
});
});
video.addEventListener("loadedmetadata", function (){
var naturalWidth=video.videoWidth;
var naturalHeight=video.videoHeight;
if(naturalWidth&&naturalHeight){
var container=video.closest('.ngg-video-container');
var displayWidth=naturalWidth;
var displayHeight=naturalHeight;
if(container){
var fancyboxContent=container.closest('#fancybox-content');
var tbWindow=container.closest('#TB_window');
var slImage=container.closest('.sl-image');
var shWrap=container.closest('#shWrap');
if(shWrap){
var wiH=window.innerHeight||0;
var dbH=document.body.clientHeight||0;
var deH=document.documentElement ? document.documentElement.clientHeight:0;
var wHeight;
if(wiH > 0){
wHeight=((wiH - dbH) > 1&&(wiH - dbH) < 30) ? dbH:wiH;
wHeight=((wHeight - deH) > 1&&(wHeight - deH) < 30) ? deH:wHeight;
}else{
wHeight=(deH > 0) ? deH:dbH;
}
if(document.getElementsByTagName("body")[0].className.match(/admin-bar/)
&& document.getElementById('wpadminbar')!==null){
wHeight=wHeight - document.getElementById('wpadminbar').offsetHeight;
}
var shHeight=wHeight - 50;
var deW=document.documentElement ? document.documentElement.clientWidth:0;
var dbW=window.innerWidth||document.body.clientWidth;
var wWidth=(deW > 1) ? deW:dbW;
if(displayHeight > shHeight){
displayWidth=displayWidth * (shHeight / displayHeight);
displayHeight=shHeight;
}
if(displayWidth > (wWidth - 16)){
displayHeight=displayHeight * ((wWidth - 16) / displayWidth);
displayWidth=wWidth - 16;
}
video.style.width=displayWidth + "px";
video.style.height=displayHeight + "px";
video.style.maxWidth="none";
video.style.maxHeight="none";
video.setAttribute("width", displayWidth);
video.setAttribute("height", displayHeight);
}else if(fancyboxContent){
setTimeout(function(){
var contentRect=fancyboxContent.getBoundingClientRect();
if(contentRect.width > 10&&contentRect.height > 10){
var maxW=contentRect.width;
var maxH=contentRect.height;
if(displayWidth > maxW||displayHeight > maxH){
var ratio=displayWidth / displayHeight > maxW / maxH
? displayWidth / maxW
: displayHeight / maxH;
displayWidth=displayWidth / ratio;
displayHeight=displayHeight / ratio;
}
video.style.width=displayWidth + "px";
video.style.height=displayHeight + "px";
video.setAttribute("width", displayWidth);
video.setAttribute("height", displayHeight);
}}, 50);
return;
}else if(tbWindow){
var pageWidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;
var pageHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;
var x=pageWidth - 150;
var y=pageHeight - 150;
if(displayWidth > x){
displayHeight=displayHeight * (x / displayWidth);
displayWidth=x;
if(displayHeight > y){
displayWidth=displayWidth * (y / displayHeight);
displayHeight=y;
}}else if(displayHeight > y){
displayWidth=displayWidth * (y / displayHeight);
displayHeight=y;
if(displayWidth > x){
displayHeight=displayHeight * (x / displayWidth);
displayWidth=x;
}}
video.style.width=displayWidth + "px";
video.style.height=displayHeight + "px";
video.setAttribute("width", displayWidth);
video.setAttribute("height", displayHeight);
}else if(slImage){
var widthRatio=0.8;
var heightRatio=0.9;
var windowWidth=window.innerWidth;
var windowHeight=window.innerHeight;
var maxWidth=windowWidth * widthRatio;
var maxHeight=windowHeight * heightRatio;
if(displayWidth > maxWidth||displayHeight > maxHeight){
var ratio=displayWidth / displayHeight > maxWidth / maxHeight
? displayWidth / maxWidth
: displayHeight / maxHeight;
displayWidth /=ratio;
displayHeight /=ratio;
}
video.style.width=displayWidth + "px";
video.style.height=displayHeight + "px";
video.style.maxWidth=maxWidth + "px";
video.style.maxHeight=maxHeight + "px";
}}
}});
if(settings.autoplay_videos){
video.addEventListener("canplay", function (){
video.play().catch(function (error){
console.error("Video autoplay failed:", error);
});
});
}
container.appendChild(video);
return container;
},
create_embed_player: function(embedUrl, settings, containerClass){
var container=document.createElement("div");
container.className=containerClass||"ngg-video-container";
var iframe=document.createElement("iframe");
iframe.src=embedUrl;
iframe.frameBorder="0";
iframe.allowFullscreen=true;
iframe.setAttribute("allow", "autoplay; encrypted-media");
iframe.style.width="100%";
iframe.style.height="100%";
iframe.style.border="none";
iframe.addEventListener("error", function(e){
console.error("Video iframe error:", {
error: e,
embedUrl: embedUrl
});
});
iframe.addEventListener("load", function(){
try {
var iframeDoc=iframe.contentDocument||iframe.contentWindow.document;
} catch (e){
if(e.name!=="SecurityError"){
console.error("Video iframe load error:", e);
}}
});
var aspectRatio=16 / 9;
var maxWidth=window.innerWidth * 0.9;
var maxHeight=window.innerHeight * 0.9;
var width=Math.min(maxWidth, 1080);
var height=width / aspectRatio;
if(height > maxHeight){
height=maxHeight;
width=height * aspectRatio;
}
container.style.width=width + "px";
container.style.height=height + "px";
container.style.maxWidth="100%";
container.style.maxHeight="90vh";
container.appendChild(iframe);
return container;
},
handle_content: function(options){
var self=this;
var videoUrl=options.videoUrl;
var $targetContainer=$(options.container);
var settings=options.settings||{};
if(!videoUrl){
console.error("Video URL is required");
return null;
}
try {
var platform=self.detect_platform(videoUrl);
if(!platform){
console.warn("Unrecognized video URL:", videoUrl);
return null;
}} catch (error){
console.error("Error detecting video platform:", error);
return null;
}
var videoContent=null;
var videoId=null;
switch (platform){
case 'youtube':
videoId=self.extract_youtube_id(videoUrl);
break;
case 'vimeo':
videoId=self.extract_vimeo_id(videoUrl);
break;
case 'dailymotion':
videoId=self.extract_dailymotion_id(videoUrl);
break;
case 'twitch':
videoId=self.extract_twitch_id(videoUrl);
break;
case 'videopress':
videoId=self.extract_videopress_id(videoUrl);
break;
case 'wistia':
videoId=self.extract_wistia_id(videoUrl);
break;
case 'local':
videoId=videoUrl;
break;
}
if(!videoId){
var errorMsg=self.create_error("Could not extract video ID from URL", options.errorClass);
if(typeof options.onBeforeAppend==="function") options.onBeforeAppend(errorMsg);
$targetContainer.append(errorMsg);
return errorMsg;
}
try {
if(platform==='local'){
videoContent=self.create_local_player(videoId, settings, options.containerClass, options.videoClass);
}else{
var embedUrl=self.get_embed_url(platform, videoId, settings);
if(embedUrl){
videoContent=self.create_embed_player(embedUrl, settings, options.containerClass);
}else{
var errorMsg=self.create_error("Could not generate embed URL", options.errorClass);
if(typeof options.onBeforeAppend==="function") options.onBeforeAppend(errorMsg);
$targetContainer.append(errorMsg);
return errorMsg;
}}
if(videoContent){
if(platform==='local'){
var video=videoContent.querySelector("video");
if(video){
video.onerror=function (){
$(videoContent).remove();
var errorMsg=self.create_error("Video failed to load", options.errorClass);
if(typeof options.onBeforeAppend==="function") options.onBeforeAppend(errorMsg);
$targetContainer.append(errorMsg);
};}}
if(typeof options.onBeforeAppend==="function") options.onBeforeAppend(videoContent);
$targetContainer.append(videoContent);
}} catch (error){
console.error("Error creating video player:", error);
var errorMsg=self.create_error("Video player creation failed", options.errorClass);
if(typeof options.onBeforeAppend==="function") options.onBeforeAppend(errorMsg);
$targetContainer.append(errorMsg);
return errorMsg;
}
return videoContent;
},
create_error: function(message, containerClass){
var container=document.createElement("div");
container.className=containerClass||"ngg-video-error";
container.innerHTML =
'<div class="ngg-video-error-content">' +
'<span class="ngg-video-error-icon">&#9888;</span>' +
'<span class="ngg-video-error-text">' +
(message||"Video failed to load") +
"</span>" +
"</div>";
return container;
}};})(jQuery);
function nextgen_lightbox_filter_selector($, selector){
if(nextgen_lightbox_settings&&nextgen_lightbox_settings.context){
var context=nextgen_lightbox_settings.context;
if(context=='all_images'){
selector=selector.add($('a > img').parent());
}
else if(context=='all_images_direct'){
selector=selector.add($('a[href] > img').parent()
.filter(function(){
var href=$(this).attr('href').toLowerCase();
var ext=href.substring(href.length - 3);
var ext2=href.substring(href.length - 4);
return (ext=='jpg'||ext=='gif'||ext=='png'||ext2=='tiff'||ext2=='jpeg'||ext2=='webp');
}));
}
else if(context=='nextgen_and_wp_images'){
selector=selector.add($('a > img[class*="wp-image-"]').parent());
}
selector=selector.not('.gallery_link');
selector=selector.not('.use_imagebrowser_effect');
}
return selector;
};
function parseSrcset(input){
function isSpace(c){
return (c==="\u0020" ||
c==="\u0009" ||
c==="\u000A" ||
c==="\u000C" ||
c==="\u000D");
}
function collectCharacters(regEx){
var chars,
match=regEx.exec(input.substring(pos));
if(match){
chars=match[ 0 ];
pos +=chars.length;
return chars;
}}
var inputLength=input.length,
regexLeadingSpaces=/^[ \t\n\r\u000c]+/,
regexLeadingCommasOrSpaces=/^[, \t\n\r\u000c]+/,
regexLeadingNotSpaces=/^[^ \t\n\r\u000c]+/,
regexTrailingCommas=/[,]+$/,
regexNonNegativeInteger=/^\d+$/,
regexFloatingPoint=/^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
url,
descriptors,
currentDescriptor,
state,
c,
pos=0,
candidates=[];
while (true){
collectCharacters(regexLeadingCommasOrSpaces);
if(pos >=inputLength){
return candidates;
}
url=collectCharacters(regexLeadingNotSpaces);
descriptors=[];
if(url.slice(-1)===","){
url=url.replace(regexTrailingCommas, "");
parseDescriptors();
}else{
tokenize();
}}
function tokenize(){
collectCharacters(regexLeadingSpaces);
currentDescriptor="";
state="in descriptor";
while (true){
c=input.charAt(pos);
if(state==="in descriptor"){
if(isSpace(c)){
if(currentDescriptor){
descriptors.push(currentDescriptor);
currentDescriptor="";
state="after descriptor";
}}else if(c===","){
pos +=1;
if(currentDescriptor){
descriptors.push(currentDescriptor);
}
parseDescriptors();
return;
}else if(c==="\u0028"){
currentDescriptor=currentDescriptor + c;
state="in parens";
}else if(c===""){
if(currentDescriptor){
descriptors.push(currentDescriptor);
}
parseDescriptors();
return;
}else{
currentDescriptor=currentDescriptor + c;
}}else if(state==="in parens"){
if(c===")"){
currentDescriptor=currentDescriptor + c;
state="in descriptor";
}else if(c===""){
descriptors.push(currentDescriptor);
parseDescriptors();
return;
}else{
currentDescriptor=currentDescriptor + c;
}}else if(state==="after descriptor"){
if(isSpace(c)){
}else if(c===""){
parseDescriptors();
return;
}else{
state="in descriptor";
pos -=1;
}}
pos +=1;
}}
function parseDescriptors(){
var pError=false,
w, d, h, i,
candidate={},
desc, lastChar, value, intVal, floatVal;
for (i=0 ; i < descriptors.length; i++){
desc=descriptors[ i ];
lastChar=desc[ desc.length - 1 ];
value=desc.substring(0, desc.length - 1);
intVal=parseInt(value, 10);
floatVal=parseFloat(value);
if(regexNonNegativeInteger.test(value)&&(lastChar==="w")){
if(w||d){pError=true;}
if(intVal===0){pError=true;}else{w=intVal;}}else if(regexFloatingPoint.test(value)&&(lastChar==="x")){
if(w||d || h){pError=true;}
if(floatVal < 0){pError=true;}else{d=floatVal;}}else if(regexNonNegativeInteger.test(value)&&(lastChar==="h")){
if(h||d){pError=true;}
if(intVal===0){pError=true;}else{h=intVal;}}else{pError=true;}}
if(!pError){
candidate.url=url;
if(w){ candidate.w=w;}
if(d){ candidate.d=d;}
if(h){ candidate.h=h;}
candidates.push(candidate);
}else if(window&&window.console&&console.log){
console.log("Invalid srcset descriptor found in '" +
input + "' at '" + desc + "'.");
}}
};
(function($){
"use strict";
function nplModal(){
var core={
debug: false,
debug_level: 1,
state: {
slug: null,
gallery_id: null,
image_id: null,
sidebar: null
},
selector: nextgen_lightbox_filter_selector($, $(".nextgen_pro_lightbox")),
options: {},
defaults: {
speed: 'medium',
initial_url: window.location.toString().split('#')[0],
ajax_url: photocrati_ajax.rest_url,
router_slug: 'gallery'
},
init: function(parameters){
core.methods.log('nplModal.init()', {
parameters: parameters,
defaults: core.defaults,
selector: core.selector,
debug: core.debug,
debug_level: core.debug_level
});
var overlay=$("<div id='npl_overlay'></div>");
var wrapper=$("<div id='npl_wrapper'></div>");
var spinner=$("<div id='npl_spinner_container' class='npl-loading-spinner hidden'><i id='npl_spinner' class='fa fa-spin fa-spinner'></i></div>");
var btn_close=$("<div id='npl_button_close' class='hidden'><i class='fa fa-times'></i></div>");
var content=$("<div id='npl_content'></div>");
var sidebar=$("<div id='npl_sidebar'></div>");
var s_overlay=$("<div id='npl_sidebar_overlay'><i class='fa fa-spin fa-spinner'/></div>");
var toggle=$("<i   id='npl_sidebar_toggle' class='fa fa-arrow-right'/>");
if(core.methods.mobile.browser.ios()){
overlay.addClass('npl_ios_no_opacity');
wrapper.addClass('npl_ios_hack');
}
if(core.methods.is_ie9()){
wrapper.addClass('npl_ie9_flex_hack');
}
$(window).trigger('override_nplModal_methods', core.methods);
overlay.css({background: core.methods.get_setting('background_color')});
spinner.css({color: core.methods.get_setting('icon_color')});
s_overlay.css({color: core.methods.get_setting('icon_color')});
btn_close.css({color: core.methods.get_setting('overlay_icon_color')});
sidebar.css({background: core.methods.get_setting('sidebar_background_color')});
toggle.css({color: core.methods.get_setting('overlay_icon_color')});
var body=$('body');
body.append(overlay);
body.append(wrapper);
wrapper.append(spinner);
wrapper.append(btn_close);
wrapper.append(toggle);
wrapper.append(content);
wrapper.append(sidebar);
wrapper.append(s_overlay);
parameters=$.extend(parameters, {router_slug: core.methods.get_setting('router_slug')});
core.options=$.extend(core.defaults, parameters);
core.methods.bind_images();
core.methods.set_events();
core.methods.mobile.init();
if(parseInt(core.methods.get_setting('padding', '0')) > 0){
var space=core.methods.get_setting('padding', '0');
var space_unit=core.methods.get_setting('padding_unit', 'px');
var maxWidth=window.innerWidth  / 4;
var maxHeight=window.innerHeight / 4;
var maxDimension=Math.min(maxWidth, maxHeight);
if(space_unit==='px'&&space > maxDimension){
space=maxDimension;
}
else if(space_unit==='%'&&space > 25){
space=25;
}
space=space + space_unit;
$("<style type='text/css'>#npl_wrapper.npl_open_with_padding {"
+ 'top: '    + space + ';'
+ 'bottom: ' + space + ';'
+ 'left: '   + space + ';'
+ 'right: '  + space + ';'
+ " } </style>").appendTo("head");
}
core.methods.router.routes.push({
re: new RegExp('^' + core.options.router_slug + '\/(.*)\/(.*)\/(.*)$', 'i'),
handler: core.methods.url_handler
});
core.methods.router.routes.push({
re: new RegExp('^' + core.options.router_slug + '\/(.*)\/(.*)$', 'i'),
handler: core.methods.url_handler
});
core.methods.router.routes.push({
re: new RegExp('^' + core.options.router_slug + '$', 'i'),
handler: core.methods.close_modal
});
core.methods.router.routes.push({
re: '',
handler: core.methods.close_modal
});
['load', 'pageshow'].map(function(eventType){
setTimeout(function(){
core.methods.router.listen();
}, 200);
})
if(core.methods.mobile.browser.ios()
||  core.methods.mobile.browser.android()){
wrapper.addClass('npl_mobile');
}
$(window).trigger('npl_initialization_complete');
},
methods: {
_pre_open_callbacks: [],
_is_open: false,
getDPIRatio: function(){
var ratio=1;
if(window.screen.systemXDPI!==undefined
&&  window.screen.logicalXDPI!==undefined
&&  window.screen.systemXDPI > window.screen.logicalXDPI){
ratio=window.screen.systemXDPI / window.screen.logicalXDPI;
}else if(window.devicePixelRatio!==undefined){
ratio=window.devicePixelRatio;
}
core.methods.log('nplModal.getDPIRatio()', {
result: ratio
});
return ratio;
},
url_handler: function(){
var slug=arguments[0];
var image_id=arguments[1];
var sidebar=null;
if(arguments.length===3){
sidebar=arguments[2];
if(sidebar==='1'){
sidebar='comments';
}}
var gallery_id=this.get_id_from_slug(slug);
if(!gallery_id){
gallery_id=slug;
}
var old_state=this.get_state();
if(parseInt(image_id)===old_state.image_id){
image_id=parseInt(image_id);
}
var state={
gallery_id: gallery_id,
image_id: image_id,
sidebar: sidebar,
slug: slug
};
this.set_state(state);
$('#npl_content').trigger('npl_url_handler', [state]);
if(this.is_open()&&gallery_id===core.state.gallery_id){
return;
}
this.open_modal(gallery_id, image_id, sidebar);
},
run_pre_open_lightbox_callbacks: function(link, params){
for (var i=0; i < this._pre_open_callbacks.length; i++){
var callback=this._pre_open_callbacks[i];
params=callback(link, params);
}
return params;
},
add_pre_open_callback: function(callback){
this._pre_open_callbacks.push(callback);
},
get_state: function(){
return core.state;
},
set_state: function(state){
core.methods.log("nplModal.set_state()", {
state: state
});
core.state=state;
},
get_setting: function (name, def){
var tmp='';
if(typeof nplModalSettings!=='undefined'
&&  typeof nplModalSettings[name]!=='undefined'
&&  nplModalSettings[name]!==''){
tmp=window.nplModalSettings[name];
}else{
tmp=def;
}
if(tmp===1)   tmp=true;
if(tmp===0)   tmp=false;
if(tmp==='1') tmp=true;
if(tmp==='0') tmp=false;
core.methods.log('nplModal.get_setting()', {
name: name,
result: tmp
}, 3);
return tmp;
},
get_slug: function (gallery_id){
var slug=gallery_id;
if('undefined'===typeof window.galleries){ return slug; }
$.each(galleries, function(index, gallery){
if(gallery.slug&&gallery.ID===gallery_id){
slug=gallery.slug;
}});
core.methods.log('nplModal.get_slug()', {
gallery_id: gallery_id,
result: slug
});
return slug;
},
open: function($el){
core.methods.log('nplModal.open()', {
el: $el
});
var params={
show_sidebar: '',
gallery_id: '!',
image_id: '!',
slug: null,
revert_image_id: '!',
open_the_lightbox: true
};
if($el.data('nplmodal-show-comments')){
params.show_sidebar='/comments';
}
if($el.data('nplmodal-gallery-id')){
params.gallery_id=$el.data('nplmodal-gallery-id');
}
if($el.data('nplmodal-image-id')){
params.image_id=parseInt($el.data('nplmodal-image-id'));
}else if($el.data('image-id')){
params.image_id=parseInt($el.data('image-id'));
}else if(params.gallery_id==='!'){
var $image=$el.find('img');
params.image_id=$image.attr('src');
if($image.attr('srcset')){
var sizes=parseSrcset($image.attr('srcset'));
var largest_w=0;
_.each(sizes, function (row){
if(typeof row.w!==undefined&&row.w > largest_w){
largest_w=row.w;
params.image_id=row.url;
}});
}}
if(params.gallery_id!=='!'){
params.slug=this.get_slug(params.gallery_id);
}
params=this.run_pre_open_lightbox_callbacks($el, params);
if(params.open_the_lightbox){
if(params.gallery_id==='!'||!this.get_setting('enable_routing')){
this.open_modal(params.gallery_id, params.image_id, null);
}else{
core.methods.router.front_page_pushstate(params.gallery_id, params.image_id);
core.methods.set_state({
gallery_id: params.gallery_id,
image_id: params.image_id,
sidebar: params.show_sidebar,
slug: params.slug
});
this.router.navigate(core.options.router_slug
+ '/' + params.slug
+ '/' + params.image_id
+ params.show_sidebar
);
if(params.revert_image_id!=='!'){
core.state.image_id=params.revert_image_id;
}}
}},
bind_images: function(){
var selector=nextgen_lightbox_filter_selector($, $(".nextgen_pro_lightbox"));
var new_selector=[];
for (var index=0; index < selector.length; index++){
var el=selector[index];
if(!$(el).hasClass('photocrati_lightbox_always')&&!$(el).hasClass('decoy')){
new_selector.push(el);
}}
new_selector=new_selector.map(function(el){
return $(el).hasClass('nextgen_pro_lightbox')&&el.nodeName!='A'&&$(el).parents('a').length
? $(el).parents('a')[0]
: el;
});
core.selector=$(new_selector);
core.selector.on('click', function (event){
if($.inArray($(this).attr('target'), ['_blank', '_parent', '_top']) > -1){
return;
}
if($(this).data('src')
&&  $(this).data('src').indexOf(core.methods.get_setting('router_slug') + '/image')!==-1
&&  !$(this).data('nplmodal-gallery-id')){
return;
}
event.stopPropagation();
event.preventDefault();
if(event.handled!==true){
event.handled=true;
core.methods.open($(this));
}});
},
set_events: function(){
var self=this;
$(window).on('refreshed', self.bind_images);
$(window).on('keydown', self.handle_keyboard_input);
$('#npl_content').on('npl_images_ready', self.open_modal_final);
$('#npl_overlay, #npl_button_close').on('touchstart click', function(event){
event.stopPropagation();
event.preventDefault();
if(event.handled!==true){
event.handled=true;
self.close_modal();
}});
},
open_modal: function(gallery_id, image_id, sidebar){
core.methods.log('nplModal.open_modal()', {
gallery_id: gallery_id,
image_id: image_id,
sidebar: sidebar
});
this._is_open=true;
$('#npl_content').trigger('npl_opening');
$('html, body').toggleClass('nextgen_pro_lightbox_open');
core.state.image_id=image_id;
core.state.gallery_id=gallery_id;
$('#npl_spinner_container').removeClass('hidden');
$('#npl_button_close').removeClass('hidden');
this.fullsize.exit();
this.mobile.open();
core.methods.fetch_images.fetch_images(gallery_id, image_id);
},
preload_image: function(image_obj){
return new Promise(resolve=> {
const image=new Image();
image.addEventListener('load', ()=> {
resolve();
});
image.src=image_obj.use_hdpi ? image_obj.srcsets.hdpi:image_obj.image;
});
},
open_modal_final: function(event, gallery_id){
var show_ndx=0;
var show_hdpi=core.methods.getDPIRatio() > 1;
var images=core.methods.fetch_images.gallery_image_cache[core.state.gallery_id];
var sidebar=core.state.sidebar;
$.each(images, function(index, element){
if(parseInt(core.state.image_id)===parseInt(element.image_id)){
show_ndx=index;
}
if(typeof core.state.image_id=='string'&&typeof element.image_id=='string'){
if(core.state.image_id===element.image_id){
show_ndx=index;
}}
if(typeof element.full_use_hdpi!=='undefined'){
if(show_hdpi&&element.full_use_hdpi){
element.image=element.full_srcsets.hdpi;
}else{
element.image=element.full_image;
}}
});
var thumbnails=core.methods.get_setting('enable_carousel', 'always');
var thumbnails_limit=core.methods.get_setting('carousel_thumbnails_limit', 250);
var gallery=core.methods.get_gallery_from_id(gallery_id);
if(thumbnails==='always'){
thumbnails='lazy';
}else if(thumbnails==='never'){
thumbnails=false;
}else if(thumbnails==='nomobile'){
if(core.methods.mobile.browser.any()){
thumbnails=false;
}else{
thumbnails='lazy';
}}
if(gallery&&gallery.images_list_count >=thumbnails_limit){
thumbnails=false;
}
if(!thumbnails){
$('#npl_wrapper').addClass('nggpl-carousel-hidden');
}
if(sidebar
|| (core.methods.get_setting('display_cart', false)&&core.methods.get_displayed_gallery_setting(gallery_id, 'is_ecommerce_enabled', false))
|| (core.methods.get_setting('display_comments', false)&&core.methods.get_setting('enable_comments', false))){
$('#npl_wrapper').addClass('npl-sidebar-open npl-sidebar-overlay-open');
}
if(core.methods.get_setting('display_captions', false)){
$('#npl_wrapper').addClass('npl-info-open');
}
if(core.methods.get_setting('style')){
$('#npl_wrapper').addClass('npl-variant-' + core.methods.get_setting('style'))
}
if(!core.methods.get_setting('display_carousel', true)||core.methods.mobile.browser.any()){
$('#npl_wrapper').addClass('npl-carousel-closed');
}
if(images.length >=thumbnails_limit){
thumbnails=false;
}
core.methods.log('nplModal.open_modal() about to invoke Galleria.run()', {
thumbnails: thumbnails,
images: images,
show: show_ndx,
sidebar: sidebar
});
const preloads=images.slice((show_ndx - 3), (show_ndx + 3));
const promises=preloads.map(image=> core.methods.preload_image(image));
Promise.all(promises).then((values)=> {
Galleria.run('#npl_content', {
responsive: true,
thumbQuality: false,
thumbnails: thumbnails,
preload: 0,
theme: 'nextgen_pro_lightbox',
dataSource: images,
show: show_ndx,
variation:           'nggpl-variant-' + core.methods.get_setting('style', ''),
transition:          core.methods.get_setting('transition_effect', 'slide'),
touchTransition:     core.methods.get_setting('touch_transition_effect', 'slide'),
imagePan:            core.methods.get_setting('image_pan', false),
pauseOnInteraction:  core.methods.get_setting('interaction_pause', true),
imageCrop:           core.methods.get_setting('image_crop', true),
transitionSpeed:    (core.methods.get_setting('transition_speed', 0.4) * 1000),
nggSidebar:          sidebar
});
$('#npl_content .galleria-container').css({background: core.methods.get_setting('background_color')});
});
},
mobile: {
meta: null,
original: null,
adjust: true,
ontouch: ('ontouchstart' in window),
init: function(){
if(!this.ontouch){
this.adjust=false;
}
var doc=window.document;
if(!doc.querySelector){ return; }
this.meta=doc.querySelector("meta[name=viewport]");
this.original=this.meta&&this.meta.getAttribute("content");
},
open: function(){
if(this.adjust&&this.meta){
core.methods.log('nplModal.mobile.open()');
this.meta.setAttribute("content", this.original + ', width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=0, shrink-to-fit=no');
}},
close: function(){
if(this.adjust&&this.meta){
core.methods.log('nplModal.mobile.close()');
this.meta.setAttribute("content", this.original);
}},
browser: {
any: function(){
return core.methods.mobile.browser.android()
|| core.methods.mobile.browser.ios()
|| core.methods.mobile.browser.windowsphone()
|| core.methods.mobile.browser.blackberry();
},
android: function(){
return /Android/i.test(navigator.userAgent);
},
ios: function(){
return /crios|iP(hone|od|ad)/i.test(navigator.userAgent);
},
windowsphone: function(){
return /(iemobile|Windows Phone)/i.test(navigator.userAgent);
},
blackberry: function(){
return /(blackberry|RIM Tablet|BB10;)/i.test(navigator.userAgent);
}}
},
is_ie9: function(){
return navigator.appVersion.indexOf("MSIE 9.")!==-1;
},
close_modal: function(){
if(!this._is_open){
return;
}
core.methods.log('nplModal.close_modal()');
var content=$('#npl_content');
content.trigger('npl_closing');
const innerGalleria=content.data('galleria');
if('undefined'!==typeof innerGalleria){
innerGalleria.destroy();
}
this.fullsize.enter();
$('#npl_spinner_container, #npl_button_close').addClass('hidden');
$('html, body').toggleClass('nextgen_pro_lightbox_open');
$('#npl_wrapper').removeClass();
this.mobile.close();
if(this.get_setting('enable_routing')){
if(history.pushState){
history.pushState('', document.title, window.location.pathname + window.location.search);
}else{
window.location.hash='';
}
if(this.get_setting('is_front_page')&&history.pushState){
history.pushState({}, document.title, core.options.initial_url);
}}
this._is_open=false;
},
fullsize: {
_is_fullsize: false,
active: function(){
return this.fullsize._is_fullsize;
},
enter: function(){
core.methods.log('nplModal.fullsize.enter()');
$('#npl_wrapper').removeClass('npl_open_with_padding');
this._is_fullsize=true;
},
exit: function(){
core.methods.log('nplModal.fullsize.exit()');
if(parseInt(core.methods.get_setting('padding', '0')) > 0
&&  !core.methods.mobile.browser.ios()){
$('#npl_wrapper').addClass('npl_open_with_padding');
}
this._is_fullsize=false;
},
toggle: function(){
core.methods.log('nplModal.fullsize.toggle()');
if(this.fullsize._is_fullsize){
this.fullsize.exit();
}else{
this.fullsize.enter();
}
$(window).trigger('resize');
}},
handle_keyboard_input: function(event){
if(core.methods.is_open()){
if(event.which===27){
core.methods.close_modal();
}}
},
is_open: function(){
return this._is_open;
},
log: function(message, table, level){
if(!core.debug){
return;
}
if(typeof level==='undefined'){
level=1;
}
if(level > core.debug_level){
return;
}
if(typeof table==='undefined'){
console.log("NPL Debug:", message)
}else{
console.log("NPL Debug:", message, table);
}},
logging: {
enable: function(){
console.log("Enabling NextGen Pro Lightbox debugging");
core.debug=true;
},
disable: function(){
console.log("Disabling NextGen Pro Lightbox debugging");
core.debug=false;
},
set_level: function(level){
console.log("Setting NextGen Pro Lightbox debug level to " + level);
core.level=parseInt(level);
}},
fetch_images: {
gallery_image_cache: [],
ajax_info: [],
ajax_interval: null,
ajax_delay: 1400,
is_cached: function(gallery_id, image_id){
var found=false;
$.each(this.gallery_image_cache[gallery_id], function (ndx, image){
if(image_id===image.image_id){
found=true;
}});
core.methods.log("nplModal.fetch_images.is_cached()", {
gallery_id: gallery_id,
image_id: image_id,
gallery_cache: this.gallery_image_cache[gallery_id],
found: found
}, 4);
return found;
},
fetch_images: function(gallery_id, image_id){
core.methods.log('nplModal.fetch_images.fetch_images() beginning');
var self=this;
this.ajax_delay=core.methods.get_setting('ajax_delay', 1400);
if(typeof this.gallery_image_cache[gallery_id]==='undefined'){
this.gallery_image_cache[gallery_id]=[];
}
var gallery=core.methods.get_gallery_from_id(gallery_id);
if(gallery===null){
return this.fetch_non_ngg_images(gallery_id);
}
if(this.gallery_image_cache[gallery_id].length===gallery.images_list_count){
return $('#npl_content').trigger('npl_images_ready', [gallery_id]);
}
$.each(gallery.images_list, function(ndx, image){
if(!self.is_cached(gallery_id, image.image_id)){
self.gallery_image_cache[gallery_id].push(image);
}});
if(this.gallery_image_cache[gallery_id].length===gallery.images_list_count){
return $('#npl_content').trigger('npl_images_ready', [gallery_id]);
}
if(this.gallery_image_cache[gallery_id].length < gallery.images_list_count){
return this.fetch_images_from_ajax(gallery_id);
}},
fetch_non_ngg_images: function (gallery_id){
core.methods.log('nplModal.fetch_images.fetch_non_ngg_images() beginning', {
gallery_id: gallery_id
});
var self=this;
core.selector.each(function(){
var anchor=$(this);
if(anchor.hasClass('ngg-trigger')){
return true;
}
if(gallery_id!=='!'&&gallery_id!==anchor.data('nplmodal-gallery-id')){
return true;
}
if(gallery_id!==core.methods.get_state().gallery_id){
return true;
}
if(core.methods.get_state().gallery_id==='!'&&anchor.data('nplmodal-gallery-id')){
return true;
}
var image=$(this).find('img').first();
var gallery_image={};
var expr=/\.(jpeg|jpg|gif|png|bmp)$/i;
gallery_image.image=(anchor.data('fullsize')===undefined) ? anchor.attr('href'):anchor.data('fullsize');
if(typeof gallery_image.image!=='undefined'
&&  !gallery_image.image.match(expr)
&&  image.attr('srcset')){
var sizes=parseSrcset(image.attr('srcset'));
var largest_w=0;
_.each(sizes, function (row){
if(typeof row.w!==undefined&&row.w > largest_w){
largest_w=row.w;
gallery_image.image=row.url;
}});
}
if(!gallery_image.image.match(expr)){
gallery_image.image=image.attr('src');
}
gallery_image.image_id=(anchor.data('image-id')===undefined) ? gallery_image.image:anchor.data('image-id');
if(self.is_cached(gallery_id, gallery_image.image_id)){
return true;
}
if(anchor.data('thumb')!==undefined) gallery_image.thumb=anchor.data('thumb');
else if(anchor.data('thumbnail')!=='undefined') gallery_image.thumb=anchor.data('thumbnail');
if(anchor.data('title')!==undefined){
gallery_image.title=anchor.data('title');
}else if(typeof image.attr('title')!=='undefined'){
gallery_image.title=image.attr('title');
}else if(typeof anchor.siblings('.wp-caption-text').html()!=='undefined'){
gallery_image.title=anchor.siblings('.wp-caption-text').html();
}
if(anchor.data('description')!==undefined){
gallery_image.description=anchor.data('description');
}else{
gallery_image.description=image.attr('alt');
}
self.gallery_image_cache[gallery_id].push(gallery_image);
});
core.methods.log('nplModal.fetch_images.fetch_non_ngg_images() result', {
result: self.gallery_image_cache[gallery_id]
});
$('#npl_content').trigger('npl_images_ready', [gallery_id])
},
create_deferred_ajax: function(gallery_id, gallery, page){
var self=this;
return $.ajax({
async: true,
url: core.options.ajax_url + 'nggpro/v1/Galleria/GetImages',
method: 'POST',
data: {
id: gallery_id,
gallery: gallery,
lang: core.methods.get_setting('lang', null),
page: page
},
dataType: 'json',
success: function(data){
core.methods.log('nplModal.fetch_images.create_deferred_ajax() response', {
response: data
});
$.each(data, function(ndx, newimage){
if(!self.is_cached(gallery_id, newimage.image_id)){
self.gallery_image_cache[gallery_id].push(newimage);
}});
}});
},
fetch_images_from_ajax: function(gallery_id, image_id){
if(!core.methods.is_open()){
return;
}
core.methods.log('nplModal.fetch_images.fetch_images_from_ajax()', {
gallery_id: gallery_id,
image_id: image_id
});
var self=this;
var original_gallery=core.methods.get_gallery_from_id(gallery_id);
var gallery=$.extend({}, original_gallery);
delete gallery.images_list;
delete gallery.display_settings;
var defers=[];
for (i=0; i <=Math.ceil(gallery.images_list_count / core.methods.get_setting('localize_limit')); i++){
defers.push(core.methods.fetch_images.create_deferred_ajax(gallery_id, gallery, i));
}
$.when.apply($, defers).then(function(){
$('#npl_content').trigger('npl_images_ready', [gallery_id]);
});
return self.gallery_image_cache[gallery_id];
}},
get_gallery_from_id: function (gallery_id){
if('undefined'===typeof window.galleries){ return null; }
var retval=null;
$.each(window.galleries, function(index, gallery){
if(gallery.ID===gallery_id||gallery.ID===parseInt(gallery_id)){
retval=gallery;
}});
return retval;
},
get_id_from_slug: function (slug){
var id=slug;
if('undefined'===typeof window.galleries){ return id; }
$.each(window.galleries, function(index, gallery){
if(gallery.slug===slug){
id=gallery.ID;
}});
return id;
},
get_displayed_gallery_setting: function(gallery_id, name, def){
var tmp='';
var gallery=this.get_gallery_from_id(gallery_id);
if(gallery&&typeof gallery.display_settings[name]!=='undefined'){
tmp=gallery.display_settings[name];
}else{
tmp=def;
}
if(tmp==='1') tmp=true;
if(tmp==='0') tmp=false;
if(tmp===1) tmp=true;
if(tmp===0) tmp=false;
core.methods.log('nplModal.get_displayed_gallery_setting()', {
gallery_id: gallery_id,
name: name,
result: tmp
});
return tmp;
},
router: {
routes: [],
interval: null,
listen: function(current){
var self=this;
current=current||'';
var listener=function(){
if(current!==self.get_fragment()){
current=self.get_fragment();
self.match(current);
}};
clearInterval(this.interval);
this.interval=setInterval(listener, 50);
},
get_fragment: function(url){
url=url||window.location.href;
var match=url.match(/#(.*)$/);
var fragment=match ? match[1]:'';
return fragment.toString().replace(/\/$/, '').replace(/^\//, '');
},
navigate: function(path, notrigger){
notrigger=notrigger||false;
if(notrigger){
clearInterval(this.interval);
}
if(!core.methods.get_setting('enable_routing', false)){
return;
}
path=path ? path:'';
window.location.href.match(/#(.*)$/);
window.location.href=window.location.href.replace(/#(.*)$/, '') + '#' + path;
if(notrigger){
this.router.listen(this.router.get_fragment())
}},
match: function(f){
var fragment=f||this.get_fragment();
for (var i=0; i < this.routes.length; i++){
var match=fragment.match(this.routes[i].re);
if(match){
match.shift();
this.routes[i].handler.apply(core.methods, match);
return this;
}}
},
front_page_pushstate: function(gallery_id, image_id){
if(!core.methods.get_setting('is_front_page')||gallery_id===undefined){
return false;
}
if('undefined'===typeof window.galleries){
return false;
}
core.methods.log("beginning nplModal.router.front_page_pushstate()", {
gallery_id: gallery_id,
image_id: image_id
});
var url='';
var slug=gallery_id;
$.each(galleries, function(index, gallery){
if(gallery.ID===gallery_id&&typeof gallery.wordpress_page_root!=='undefined'){
url=gallery.wordpress_page_root;
if(gallery.slug){
slug=gallery.slug;
}}
});
url +='#' + this.get_fragment(core.methods.get_setting('router_slug') + '/' + slug + '/' + image_id);
if(history.pushState){
history.pushState({}, document.title, url);
return true;
}else{
window.location=url;
return false;
}}
}}
};
this.core=core;
}
var nplModalObj=new nplModal();
$.nplModal=function(param){
function getDescendantProp(obj, desc){
var arr=desc.split(".");
while(arr.length){
obj=obj[arr.shift()];
}
return obj;
}
if(typeof param==='undefined'){
return nplModalObj.core.init.apply(nplModalObj, {});
}else if(typeof param==='object'){
return nplModalObj.core.init.apply(nplModalObj, param);
}else{
var method=getDescendantProp(nplModalObj.core.methods, param);
if(method){
return method.apply(nplModalObj.core.methods, Array.prototype.slice.call(arguments, 1));
}else{
console.error('Method ' + param + ' does not exist on jQuery.nplModal');
}}
};})(jQuery);
jQuery(document).ready(function($){
$.nplModal();
});
(function($){
var add_nggpl_theme=function(){
Galleria.addTheme({
name: 'nextgen_pro_lightbox',
author: 'Imagely',
version: 2.0,
defaults: {
debug: false,
responsive: true,
carousel: true,
thumbnails: 'lazy',
fullscreen: false,
trueFullscreen: false,
fullscreenDoubleTap: false,
maxScaleRatio: 1
},
init: function(options){
var self=this;
Galleria.requires(1.41, 'This version of the NextGEN Pro Lightbox theme requires Galleria 1.4.1 or later');
$.nplModal('log', 'theme initialization', {
options: options
});
var methods={
sidebar: {
_is_open: false,
_type: '',
is_open: function(state){
if(typeof state!=='undefined'){
this._is_open=state;
}else{
return this._is_open;
}},
toggle: function(type){
$.nplModal('log', 'theme sidebar.toggle()', {
type: type
});
if(this.is_open()&&type===this.get_type()){
this.close();
}else{
this.open(type);
}},
open: function(type){
$.nplModal('log', 'theme sidebar.open()', {
type: type
});
$('#npl_wrapper').addClass('npl-sidebar-open npl-sidebar-overlay-open');
this.render(type);
methods.sidebar.is_open(true);
var state=$.nplModal('get_state');
state.sidebar=type;
$.nplModal('router.navigate',
$.nplModal('get_setting', 'router_slug')
+ '/' + state.slug
+ '/' + state.image_id
+ '/' + type,
true
);
self.resize();
self.trigger('npl_sidebar_opened');
},
close: function(){
$.nplModal('log', 'theme sidebar.close()');
$('#npl_wrapper').removeClass('npl-sidebar-open npl-sidebar-overlay-open');
methods.sidebar.is_open(false);
var state=$.nplModal('get_state');
state.sidebar=null;
$.nplModal('router.navigate',
$.nplModal('get_setting', 'router_slug')
+ '/' + state.slug
+ '/' + state.image_id,
true
);
self.resize();
self.trigger('npl_sidebar_closed');
},
render: function(type){
$.nplModal('log', 'theme sidebar.render()', {
type: type
});
if(type!==this.get_type()){
this._type=type;
$.nplModal('get_state').sidebar=type;
}
methods.sidebars[type].render(methods.galleria.get_current_image_id());
methods.sidebars[type].init();
},
get_type: function(){
return this._type;
},
events: {
bind: function(){
$.nplModal('log', 'theme sidebar.events.bind()');
$('#npl_content').on('npl_sidebar_rendered', this.rendered);
$('#npl_sidebar_toggle').on('click', function(){
methods.sidebar.close();
});
},
rendered: function(){
$.nplModal('log', 'theme sidebar.events.rendered()');
$('#nggpl-sidebar-thumbnail-img').attr('src', self.getData(self.getIndex()).image);
}}
},
sidebars: {
datacache: {
_cache: [],
_current_image_ndx: null,
_last_image_ndx: null,
events: {
bind: function(){
$.nplModal('log', 'theme sidebars.datacache.events.bind()');
self.bind('loadstart', this.loadstart);
},
loadstart: function(){
$.nplModal('log', 'theme sidebars.datacache.events.image()');
if(methods.sidebars.datacache._current_image_ndx===null){
methods.sidebars.datacache._last_image_ndx=methods.sidebars.datacache._current_image_ndx=self.getIndex();
}else{
methods.sidebars.datacache._last_image_ndx=methods.sidebars.datacache._current_image_ndx;
methods.sidebars.datacache._current_image_ndx=self.getIndex();
}}
},
get_carousel_navigation_direction: function(){
if(this._current_image_ndx===this._last_image_ndx){
return 'same';
}else{
if(this._last_image_ndx===0&&this._current_image_ndx===(self.getDataLength() - 1)){
return 'left';
}else if(this._current_image_ndx===0&&this._last_image_ndx===(self.getDataLength() -1)){
return 'right';
}else{
return (this._current_image_ndx < this._last_image_ndx) ? 'left':'right';
}}
},
get_cache_size: function(){
var size=this._cache.length;
$.nplModal('log', 'theme sidebars.comments.get_cache_size()', {
result: size
});
return size;
},
get_prev_uncached_image_id: function(id, step){
step=step||0;
var prev_image_id=self.getData(self.getPrev(methods.galleria.get_index_from_id(id) - step)).image_id;
if(this._cache[prev_image_id]&&this.get_cache_size() < self.getDataLength()){
prev_image_id=this.get_prev_uncached_image_id(prev_image_id);
}
$.nplModal('log', 'theme sidebars.comments.get_prev_uncached_image_id()', {
id: id,
result: prev_image_id
});
return prev_image_id;
},
get_next_uncached_image_id: function(id, step){
step=step||0;
var next_image_id=self.getData(self.getNext(methods.galleria.get_index_from_id(id) + step)).image_id;
if(this._cache[next_image_id]&&this.get_cache_size() < self.getDataLength()){
next_image_id=this.get_next_uncached_image_id(next_image_id);
}
$.nplModal('log', 'theme sidebars.comments.get_next_uncached_image_id()', {
id: id,
result: next_image_id
});
return next_image_id;
},
expanded_request: function(id, finished){
$.nplModal('log', 'theme sidebars.comments.expanded_request()', {
id: id
});
var id_array=(id instanceof Array) ? id:id.toString().split(',');
if(id_array.length===1){
var key=id_array[0];
var prev=this.get_prev_uncached_image_id(key);
var next=this.get_next_uncached_image_id(key);
if(!this._cache[prev]){
this._cache[prev]='Placeholder stub';
id_array.unshift(prev);
}
if(!this._cache[next]&&prev!==next&&id!==next){
this._cache[next]='Placeholder stub';
id_array.push(next);
}}
id_array=this.sort_uniq(id_array);
this.request(id_array, 0, finished);
},
request: function(id, page, finished){
$.nplModal('log', 'theme sidebars.comments.request()', {
id: id,
page: page
});
var myself=this;
var postdata={
type: 'image',
page: page,
id: id.join(','),
from: window.parent.location.toString(),
};
if($.nplModal('get_setting', 'lang', false)){
postdata.lang=$.nplModal('get_setting', 'lang');
}
$.ajax({
url: photocrati_ajax.rest_url + 'nggpro/v1/Galleria/GetSidebarData',
method: 'POST',
beforeSend: function (xhr){
xhr.setRequestHeader('X-WP-Nonce', window.nextgen_pro_lightbox_authentication.nonce);
},
xhrFields: {
withCredentials: true
},
data: postdata,
success: function(data){
$.nplModal('log', 'theme sidebars.comments.request() response', {
response: data
});
if(typeof(data)!=='object'){
data=JSON.parse(data);
}
for (var ndx in data){
myself._cache[ndx]=data[ndx];
}
if(typeof finished==='function'){
finished(data);
}}
});
},
load_more: function(id){
$.nplModal('log', 'theme sidebars.comments.load_more()', {
id: id
});
if(methods.nplModal.is_nextgen_gallery()
&&  $.nplModal('get_setting', 'enable_routing', false)
&&  $.nplModal('get_setting', 'enable_comments', false)){
var precache_ids=[];
var direction=methods.sidebars.datacache.get_carousel_navigation_direction();
var count=3;
for (var i=0; i <=count; i++){
if(direction==='left'){
var uncached_id=this.get_prev_uncached_image_id(id, i);
}else{
var uncached_id=this.get_next_uncached_image_id(id, i);
}
if(!this._cache[uncached_id]){
this._cache[uncached_id]='Placeholder stub';
precache_ids.push(uncached_id);
}}
precache_ids=this.sort_uniq(precache_ids);
if(precache_ids.length!==0){
this.expanded_request(precache_ids);
}}
},
sort_uniq: function(ids){
return ids.sort().filter(function(item, pos, ary){
return !pos||item!==ary[pos - 1];
})
},
get_cache_by_id: function(id){
return this._cache[id];
}},
comments: {
init: function(){
$.nplModal('log', 'theme sidebars.comments.init()');
if($('#nggpl-comments-wrapper').length!==1){ return; }
var origin_url=document.getElementById("ngg_comment_origin_url");
if(typeof origin_url!=='undefined'&&origin_url!==null){
origin_url.value=window.location.href.toString();
}
$('#npl_sidebar').find('a').each(function(){
if($(this).attr('id')==='nggpl-comment-logout'){
$(this).attr('href', $(this).attr('href') + '?redirect_to=' + window.location.toString());
}else{
$(this).attr('target', '_blank');
}});
$('#nggpl-respond-form').on('submit', function (event){
event.preventDefault();
var commentstatus=$('#nggpl-comment-status');
$('#npl_wrapper').addClass('npl-sidebar-overlay-open');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function (data){
if(data.success===true){
$('#nggpl-comment').val('');
$('#nggpl-comments-title').val('');
var image_id=methods.galleria.get_current_image_id();
methods.sidebars.datacache.expanded_request(image_id, function(){
methods.sidebar.render(methods.sidebars.comments.get_type(), image_id);
});
}else{
commentstatus.addClass('error')
.html(data);
$('#npl_wrapper').removeClass('npl-sidebar-overlay-open');
}},
complete: function (jqXHR, status){
},
error: function (jqXHR){
commentstatus.addClass('error').html(jqXHR.responseText);
$('#npl_wrapper').removeClass('npl-sidebar-overlay-open');
}});
});
$("#npl_sidebar .nggpl-button, #nggpl-comment-form-wrapper input[type='submit']").each(function(){
var $this=$(this);
$this.css({
'color': $.nplModal('get_setting', 'sidebar_button_color'),
'background-color': $.nplModal('get_setting', 'sidebar_button_background')
});
});
$('.nggpl-reply-to-comment').on('click', function(event){
event.preventDefault();
$('#nggpl-comment_parent').val($(this).data('comment-id'));
$('#nggpl-comment-reply-status').removeClass('hidden');
$('#nggpl-commentform').find(':input').filter(':visible').first().trigger('focus');
$('#npl_sidebar').scrollTop($('#nggpl-comments-bottom').offset().top);
});
$('#nggpl-comment-reply-status a').on('click', function(event){
event.preventDefault();
$('#nggpl-comment_parent').val('0');
$('#nggpl-comment-reply-status').addClass('hidden');
});
$('#nggpl-comment-nav-below a').on('click', function(event){
event.preventDefault();
$('#npl_wrapper').addClass('npl-sidebar-overlay-open');
var page_id=$(this).data('page-id');
methods.sidebars.datacache.request([methods.galleria.get_current_image_id()],
page_id,
function(){
methods.sidebar.render('comments', methods.galleria.get_current_image_id());
}
);
});
self.trigger('npl_sidebar_rendered');
if(methods.nplModal.is_nextgen_gallery()
&&  $.nplModal('get_setting', 'enable_routing', false)
&&  $.nplModal('get_setting', 'enable_sharing', false)){
$('#nggpl-comments-image-share-icons').removeClass('disabled');
methods.share_icons.create('#nggpl-comments-image-share-icons',
methods.icons.get_overlay_color()
);
}
methods.sidebars.comments.wait_for_image_to_reveal();
},
wait_for_image_to_reveal: function(){
if(!methods.sidebars.comments.events.between_loadstart_and_finish){
$('#npl_wrapper').removeClass('npl-sidebar-overlay-open');
}else{
methods.sidebars.comments.events.waiting_for_image_to_load=true;
}},
render: function(id){
$.nplModal('log', 'theme sidebars.comments.render()', {
id: id
});
var cache=methods.sidebars.datacache.get_cache_by_id(id);
if(!cache){
$('#npl_wrapper').addClass('npl-sidebar-overlay-open');
methods.sidebars.datacache.expanded_request(id, function(){
cache=methods.sidebars.datacache.get_cache_by_id(id);
$('#npl_sidebar').html(cache.comments['rendered_view']);
methods.sidebars.comments.init();
});
}else if(cache==='Placeholder stub'){
$('#npl_wrapper').addClass('npl-sidebar-overlay-open');
var interval=setInterval(function(){
cache=methods.sidebars.datacache.get_cache_by_id(id);
if(cache!=='Placeholder stub'){
$('#npl_sidebar').html(cache.comments['rendered_view']);
methods.sidebars.comments.init();
clearInterval(interval);
}}, 250);
}else{
$('#npl_sidebar').html(cache.comments['rendered_view']);
$('#npl_wrapper').removeClass('npl-sidebar-overlay-open');
}},
get_type: function(){
return 'comments';
},
events: {
waiting_for_image_to_load: false,
between_loadstart_and_finish: false,
bind: function(){
$.nplModal('log', 'theme sidebars.comments.events.bind()');
if(methods.nplModal.is_nextgen_gallery()
&&  $.nplModal('get_setting', 'enable_routing', false)
&&  $.nplModal('get_setting', 'enable_comments', false)
&&  !methods.nplModal.is_random_source()){
self.bind('loadstart', this.loadstart);
self.bind('npl_init', this.npl_init);
self.bind('npl_init_keys', this.npl_init_keys);
self.bind('image', this.image);
}},
npl_init: function(){
$.nplModal('log', 'theme sidebars.comments.events.npl_init()');
var comment_button=$('<i/>')
.addClass('nggpl-toolbar-button-comment fa fa-comment')
.attr({'title': $.nplModal('get_setting', 'i18n').toggle_social_sidebar});
methods.thumbnails.register_button(comment_button,
function(event){
methods.sidebar.toggle(methods.sidebars.comments.get_type());
event.preventDefault();
}
);
},
image: function(){
methods.sidebars.comments.events.between_loadstart_and_finish=false;
if(methods.sidebars.comments.events.waiting_for_image_to_load){
methods.sidebars.comments.events.waiting_for_image_to_load=false;
$('#npl_wrapper').removeClass('npl-sidebar-overlay-open');
}},
_loadstart_run_once: false,
loadstart: function(e){
$.nplModal('log', 'theme sidebars.comments.events.npl_init_complete()');
methods.sidebars.comments.events.between_loadstart_and_finish=true;
if(methods.nplModal.is_nextgen_gallery()&&!methods.sidebars.comments._loadstart_run_once){
if(($.nplModal('get_state').sidebar&&$.nplModal('get_state').sidebar===methods.sidebars.comments.get_type())
||  $.nplModal('get_setting', 'display_comments')){
methods.sidebar.open(methods.sidebars.comments.get_type());
}
methods.sidebars.comments._loadstart_run_once=true;
}else if(methods.nplModal.is_nextgen_gallery()
&&  $.nplModal('get_setting', 'enable_routing', false)
&&  $.nplModal('get_setting', 'enable_comments', false)){
methods.sidebars.datacache.load_more(methods.galleria.get_current_image_id());
if(methods.sidebar.is_open()&&methods.sidebar.get_type()===methods.sidebars.comments.get_type()){
methods.sidebar.render(methods.sidebars.comments.get_type());
}}
},
npl_init_keys: function(){
$.nplModal('log', 'theme sidebars.comments.events.npl_init_keys()');
var input_types=methods.galleria.get_keybinding_exclude_list();
if(methods.nplModal.is_nextgen_gallery()
&&  $.nplModal('get_setting', 'enable_routing', false)
&&  $.nplModal('get_setting', 'enable_comments', false)){
self.attachKeyboard({
32: function (){
if(!$(document.activeElement).is(input_types)){
methods.sidebar.toggle(methods.sidebars.comments.get_type());
}}
});
}}
}}
},
thumbnails: {
is_open: function(){
return !$('#npl_wrapper').hasClass('npl-carousel-closed');
},
toggle: function(){
$.nplModal('log', 'theme thumbnails.toggle()');
if(this.is_open()){
this.close();
}else{
this.open();
}},
open: function(){
$.nplModal('log', 'theme thumbnails.open()');
$('#npl_wrapper').removeClass('npl-carousel-closed');
$('.galleria-dock-toggle-container i').toggleClass('fa-angle-up fa-angle-down');
$('.galleria-dock-toggle-container').find('[data-fa-i2svg]').toggleClass('fa-angle-up fa-angle-down');
$(window).trigger('resize');
},
close: function(){
$.nplModal('log', 'theme thumbnails.close()');
$('#npl_wrapper').addClass('npl-carousel-closed');
$('.galleria-dock-toggle-container i').toggleClass('fa-angle-up fa-angle-down');
$('.galleria-dock-toggle-container').find('[data-fa-i2svg]').toggleClass('fa-angle-up fa-angle-down');
$(window).trigger('resize');
},
adjust_container: function(){
$.nplModal('log', 'theme thumbnails.adjust_container()');
setTimeout(function(){
var available_width=self.$('thumbnails-container').width()
- self.$('nextgen-buttons').width()
- self.$('thumb-nav-left').width()
- self.$('thumb-nav-right').width();
if(available_width <=(70 * 4)){
self.$('container').addClass('nggpl-carousel-too-small');
}else{
self.$('container').removeClass('nggpl-carousel-too-small');
}}, 250);
},
_buttons: [],
register_button: function(button, callback){
$.nplModal('log', 'theme thumbnails.register_button()', {
button: button
});
var wrapper=$('<span class="nggpl-button nggpl-toolbar-button"/>');
if($.nplModal('get_setting', 'icon_background_enabled', false)
&&  $.nplModal('get_setting', 'icon_background_rounded', false)){
wrapper.addClass('nggpl-rounded');
}
wrapper.html(button);
this._buttons.push(wrapper);
$(self._dom.stage).append(wrapper);
wrapper.on('click', function(event){
callback(event)
});
},
get_registered_buttons: function(){
$.nplModal('log', 'theme thumbnails.get_registered_buttons', {
buttons: this._buttons
});
return this._buttons;
},
events: {
bind: function(){
$.nplModal('log', 'theme thumbnails.events.bind()');
self.bind('loadfinish', methods.thumbnails.adjust_container);
self.bind('loadfinish', this.loadfinish);
self.bind('npl_sidebar_opened', methods.thumbnails.adjust_container);
self.bind('npl_sidebar_closed', methods.thumbnails.adjust_container);
self.bind('npl_init', this.npl_init);
self.bind('npl_init_complete', this.npl_init_complete);
methods.galleria.bind_once('resize', methods.thumbnails.adjust_container, 250);
},
npl_init: function(){
$.nplModal('log', 'theme thumbnails.events.npl_init()');
if('numbers'===options.thumbnails){
self.$('container').addClass('nggpl-carousel-numbers');
self.$('thumbnails-list').css('color', methods.icons.get_color());
self.updateCarousel();
}else if('lazy'===options.thumbnails){
self.lazyLoadChunks(10);
}
self.$('thumbnails-container').css({background: $.nplModal('get_setting', 'carousel_background_color')});
var next_thumbs_button=$('<i/>')
.addClass('fa fa-angle-right')
.css({color: methods.icons.get_color()});
var prev_thumbs_button=$('<i/>')
.addClass('fa fa-angle-left')
.css({color: methods.icons.get_color()});
$(self._dom.stage).append(next_thumbs_button);
$(self._dom.stage).append(prev_thumbs_button);
self.append({'thumb-nav-left': prev_thumbs_button});
self.append({'thumb-nav-right': next_thumbs_button});
self.addElement('dock-toggle-container');
var dock_toggle_container=self.$('dock-toggle-container')
.css({background: $.nplModal('get_setting', 'carousel_background_color')});
var dock_toggle_button=$('<i/>').addClass('fa fa-angle-down')
.css({color: $.nplModal('get_setting', 'carousel_text_color')});
if(!methods.thumbnails.is_open()){
dock_toggle_button.toggleClass('fa-angle-up fa-angle-down');
}
$(self._dom.stage).append(dock_toggle_button);
self.append({'dock-toggle-container': dock_toggle_button});
dock_toggle_container.on('click', self.proxy(function(){
methods.thumbnails.toggle();
}));
var play_button=$('<i/>')
.addClass('nggpl-toolbar-button-play fa fa-play')
.attr({'title': $.nplModal('get_setting', 'i18n').play_pause});
if(this._playing){
play_button.removeClass('fa-play').addClass('fa-pause');
}
methods.thumbnails.register_button(play_button,
function(event){
event.preventDefault();
self.playToggle();
var $target=$(event.currentTarget);
$target.find('i').toggleClass('fa-play fa-pause');
$target.find('[data-fa-i2svg]').toggleClass('fa-play fa-pause');
}
);
var info_button=$('<i/>')
.addClass('nggpl-toolbar-button-info fa fa-info')
.attr({'title': $.nplModal('get_setting', 'i18n').toggle_image_info});
methods.thumbnails.register_button(info_button,
function(event){
event.preventDefault();
methods.info.toggle();
}
);
},
npl_init_complete: function(){
$.nplModal('log', 'theme thumbnails.events.npl_init_complete()');
var display_buttons=methods.thumbnails.get_registered_buttons();
for (i=0; i <=(display_buttons.length - 1); i++){
display_buttons[i].css({
'color': methods.icons.get_color(),
'background-color': methods.icons.get_background()
});
}
self.addElement('nextgen-buttons');
self.append({'nextgen-buttons': display_buttons});
self.prependChild('thumbnails-container', 'nextgen-buttons');
self.prependChild('info', 'dock-toggle-container');
if(!$.nplModal('mobile.browser.any')){
self.addIdleState(self.get('dock-toggle-button'), {opacity: 0});
}},
_loadfinish_ran_once: false,
loadfinish: function(){
$.nplModal('log', 'theme thumbnails.events.loadfinish()');
if(methods.thumbnails.events._loadfinish_ran_once){
return;
}
$('#npl_spinner_container').addClass('hidden');
methods.thumbnails.events._loadfinish_ran_once=true;
}}
},
info: {
is_open: function(){
return $('#npl_wrapper').hasClass('npl-info-open');
},
toggle: function(){
$.nplModal('log', 'theme info.toggle()');
if(this.is_open()){
this.close();
}else{
this.open();
}},
open: function(){
$.nplModal('log', 'theme info.open()');
$('#npl_wrapper').addClass('npl-info-open');
},
close: function(){
$.nplModal('log', 'theme info.close()');
$('#npl_wrapper').removeClass('npl-info-open');
},
events: {
bind: function(){
$.nplModal('log', 'theme info.events.bind()');
self.bind('npl_init', this.npl_init);
self.bind('loadfinish', this.loadfinish);
},
npl_init: function(){
$.nplModal('log', 'theme info.events.npl_init()');
var needsnewparent=self.$('info').detach();
self.$('thumbnails-container').append(needsnewparent);
self.prependChild('info-text',
$('<div/>')
.attr('id', 'galleria-image-share-icons')
.attr('class', 'galleria-image-share-icons')
);
if(carousel_text_color=$.nplModal('get_setting', 'carousel_text_color')){
self.$('info-title').css({color: carousel_text_color});
self.$('info-description').css({color: carousel_text_color});
}
self.$('info, info-text, info-title, info-description').css({background: $.nplModal('get_setting', 'carousel_background_color')});
},
_loadfinish_ran_once: false,
loadfinish: function(){
$.nplModal('log', 'theme info.events.loadfinish()');
self.$('info-title, info-description').find('a').each(function(){
$(this).attr('target', '_blank');
$(this).css('color', methods.icons.get_color());
});
methods.info.events._loadfinish_ran_once=true;
}}
},
icons: {
get_color: function(){
return $.nplModal('get_setting', 'icon_color');
},
get_background: function(){
var iconcolor=$.nplModal('get_setting', 'carousel_background_color');
if($.nplModal('get_setting', 'icon_background_enabled', false)){
iconcolor=$.nplModal('get_setting', 'icon_background');
}
return iconcolor;
},
get_overlay_color: function(){
return $.nplModal('get_setting', 'overlay_icon_color');
}},
nplModal: {
close: function(){
$.nplModal('close_modal');
},
is_random_source: function(){
var gallery=$.nplModal('get_gallery_from_id', $.nplModal('get_state').gallery_id);
var result=($.inArray(gallery.source, ['random', 'random_images'])!==-1);
$.nplModal('log', 'theme nplModal.is_random_source()', {
result: result
});
return result;
},
is_nextgen_gallery: function(){
var retval=$.nplModal('get_state').gallery_id!=='!';
$.nplModal('log', 'theme nplModal.is_nextgen_gallery()', {
result: retval
});
return retval;
},
is_nextgen_widget: function(){
var retval=false;
var gallery=$.nplModal('get_gallery_from_id', $.nplModal('get_state').gallery_id);
var slug=gallery.slug;
if(slug){
retval=slug.indexOf('widget-ngg-images')!==-1;
}
$.nplModal('log', 'theme nplModal.is_nextgen_widget()', {
result: retval
});
return retval;
},
events: {
bind: function(){
$.nplModal('log', 'theme nplModal.bind()');
if(Galleria.IPAD||Galleria.IPHONE){
self.$('container').addClass('nggpl-ios-browser');
}
if(methods.nplModal.is_nextgen_gallery()){
self.bind('image', this.image);
}
if(methods.nplModal.is_nextgen_gallery()
&&  $.nplModal('get_setting', 'enable_routing', false)
&&  $.nplModal('get_setting', 'enable_comments', false)){
$('#npl_content').on('npl_url_handler', this.unhandled_url_change);
}
if($.nplModal('get_setting', 'protect_images', false)){
$('.galleria-image').on('dragstart', function(event){
event.preventDefault();
});
self.bind('npl_init', this.npl_init);
self.bind('npl_init_complete', this.npl_init_complete);
}
jQuery('#npl_content').on('npl_closing', this.closing);
},
npl_init: function(){
$.nplModal('log', 'theme nplModal.events.npl_init()');
self.addElement('image-protection');
document.oncontextmenu=function(event){
event=event||window.event;
event.preventDefault();
};},
npl_init_complete: function(){
$.nplModal('log', 'theme nplModal.events.npl_init_complete()');
self.prependChild('images', 'image-protection');
},
_image_ran_once: false,
image: function(){
$.nplModal('log', 'theme nplModal.events.image()');
if(methods.nplModal.events._image_ran_once){
if(!methods.nplModal.is_random_source()){
var image_id=self.getData(self.getIndex()).image_id;
var sidebar_string=methods.sidebar.is_open() ? '/' + methods.sidebar.get_type():'';
var state=$.nplModal('get_state');
state.image_id=image_id;
$.nplModal('set_state', state);
if($.nplModal('get_setting', 'enable_routing', false)){
$.nplModal('router.navigate',
$.nplModal('get_setting', 'router_slug') + '/' + $.nplModal('get_state').slug + '/' + image_id + sidebar_string,
true
);
}}
}
methods.nplModal.events._image_ran_once=true;
},
unhandled_url_change: function(event, state){
$.nplModal('log', 'theme nplModal.unhandled_url_change()', {
event: event,
state: state
});
for (var i=0; i <=(self.getDataLength() - 1); i++){
if(state.image_id===self.getData(i).image_id){
self.show(i);
}}
if(methods.sidebar.is_open()&&state.sidebar==null){
methods.sidebar.close();
}else if(!methods.sidebar.is_open()
&&  typeof state.sidebar!=='undefined'
&&  state.sidebar!==null){
methods.sidebar.open(state.sidebar);
}},
closing: function(){
self.detachKeyboard();
}}
},
galleria: {
bind_once: function(event, callback, timeout){
var timer_id=undefined;
window.addEventListener(event, function(){
if(typeof timer_id==='undefined'){
clearTimeout(timer_id);
timer_id=undefined;
}
timer_id=setTimeout(function(){
timer_id=undefined;
callback();
}, timeout);
});
},
get_displayed_gallery_setting: function(name, def){
var tmp='';
var gallery=$.nplModal('get_gallery_from_id', $.nplModal('get_state').gallery_id);
if(gallery&&typeof gallery.display_settings[name]!=='undefined'){
tmp=gallery.display_settings[name];
}else{
tmp=def;
}
if(tmp==='1') tmp=true;
if(tmp==='0') tmp=false;
if(tmp===1) tmp=true;
if(tmp===0) tmp=false;
$.nplModal('log', 'theme galleria.get_displayed_gallery_setting()', {
name: name,
result: tmp
});
return tmp;
},
get_keybinding_exclude_list: function(){
return 'textarea, input';
},
get_current_image_id: function(){
return self.getData(self.getIndex()).image_id;
},
get_index_from_id: function(id){
var retval=null;
for (var i=0; i <=(self.getDataLength() - 1); i++){
if(id===self.getData(i).image_id){
retval=i;
}}
return retval;
},
events: {
bind: function(){
$.nplModal('log', 'theme galleria.events.bind()');
self.bind('touchmove', this.touchmove);
self.bind('npl_init', this.npl_init);
self.bind('npl_init_keys', this.npl_init_keys);
self.bind('npl_init_complete', this.npl_init_complete);
self.bind('loadstart', this.loadstart);
self.bind('loadfinish', this.loadfinish);
$(window).on('resize orientationchange', this.browserchanged);
},
browserchanged: function(){
$.nplModal('log', 'theme galleria.events.browserchanged()');
setTimeout(function(){
self.rescale();
}, 200);
},
npl_init: function(){
$.nplModal('log', 'theme galleria.events.npl_init()');
self.setPlaytime(($.nplModal('get_setting', 'slideshow_speed', 5) * 1000));
var next_image_button=$('<i/>')
.addClass('fa fa-angle-right')
.css({color: methods.icons.get_overlay_color()});
var prev_image_button=$('<i/>')
.addClass('fa fa-angle-left')
.css({color: methods.icons.get_overlay_color()});
$(self._dom.stage).append(next_image_button);
$(self._dom.stage).append(prev_image_button);
self.append({'image-nav-left': prev_image_button});
self.append({'image-nav-right': next_image_button});
self.$('counter').css({color: methods.icons.get_overlay_color()});
},
npl_init_keys: function(){
$.nplModal('log', 'theme galleria.events.npl_init_keys()');
var input_types=methods.galleria.get_keybinding_exclude_list();
self.attachKeyboard({
left: function(){
if(!$(document.activeElement).is(input_types)){
this.prev();
}},
right: function(){
if(!$(document.activeElement).is(input_types)){
this.next();
}},
down: function(){
if(!$(document.activeElement).is(input_types)){
methods.thumbnails.toggle();
}},
up: function(){
if(!$(document.activeElement).is(input_types)){
methods.info.toggle();
}},
27: function(event){
event.preventDefault();
methods.nplModal.close();
}});
},
npl_init_complete: function(){
$.nplModal('log', 'theme galleria.events.npl_init_complete()');
if(!$.nplModal('mobile.browser.any')){
self.addIdleState(self.get('counter'),            {opacity: 0});
self.addIdleState(self.get('image-nav-left'),     {opacity: 0});
self.addIdleState(self.get('image-nav-right'),    {opacity: 0});
}},
touchmove: function(event){
if(!$('.scrollable').has($(event.target)).length){
$.nplModal('log', 'theme galleria.events.touchmove() prevented scrolling');
event.preventDefault();
}},
loadstart: function(event){
$.nplModal('log', 'theme galleria.events.loadstart()', {
event: event
});
if(!event.cached){
var button=$('#npl_button_close').find('i');
button.removeClass('fa-times-circle');
}},
loadfinish: function(){
$.nplModal('log', 'theme galleria.events.loadfinish()');
var button=$('#npl_button_close').find('i');
button.addClass('fa-times');
}}
},
share_icons: {
strip_html: function(html){
var tmp=document.createElement('div');
tmp.innerHTML=html;
return tmp.textContent||tmp.innerText||"";
},
create: function(target, iconcolor){
$.nplModal('log', 'theme share_icons.create()');
if(methods.nplModal.is_random_source()
||  methods.nplModal.is_nextgen_widget()
||  !methods.nplModal.is_nextgen_gallery()
||  !$.nplModal('get_setting', 'enable_routing', false)){
return false;
}
var id=self.getData(self.getIndex()).image_id;
var data=self.getData(self.getIndex());
var url=encodeURIComponent(window.location.toString());
var twitter_icon=$('<li/>').html($('<a/>', {'href': 'https://twitter.com/share?url=' + methods.share_icons.get_share_url(id, 'full'),
'target': '_blank',
'class': 'nggpl-comment-tweet-button',
'title': $.nplModal('get_setting', 'i18n').share.twitter})
.css({color: iconcolor})
.html($('<i/>', {'class': 'fa-brands fa-square-x-twitter'}))
);
var facebook_icon=$('<li/>').html($('<a/>', {
'class': 'nggpl-comment-facebook-button',
'title': $.nplModal('get_setting', 'i18n').share.facebook
}).css({color: iconcolor})
.html($('<i/>', {'class': 'fa fa-facebook-square'}))
);
if(typeof $.nplModal('get_setting', 'facebook_app_id')!=='undefined'){
facebook_icon.on('click', function(event){
event.preventDefault();
FB.ui({
method: 'share',
href: methods.share_icons.get_share_url(id, 'full'),
link: window.location.toString()
}, function(response){
});
});
}else{
var facebook_url='https://www.facebook.com/share.php';
facebook_url +='?u=' + encodeURIComponent(methods.share_icons.get_share_url(id, 'full'));
var anchor=facebook_icon.find('a');
anchor.attr('href', facebook_url);
anchor.attr('target', '_blank');
}
var pinterest_url=encodeURIComponent(methods.share_icons.get_share_url(id, 'full'));
var summary=methods.share_icons.strip_html(data.description);
if(summary.length >=446){
summary=summary.substring(0, 492);
summary +='...';
}
pinterest_url +='&url=' + url;
pinterest_url +='&media=' + data.image;
pinterest_url +='&description=' + summary;
var pinterest_icon=$('<li/>').html($('<a/>', {'href': 'http://pinterest.com/pin/create/button/?s=100' + pinterest_url,
'target': '_blank',
'class': 'nggpl-comment-pinterest-button',
'title': $.nplModal('get_setting', 'i18n').share.pinterest})
.css({color: iconcolor})
.html($('<i/>', {'class': 'fa fa-pinterest-square'}))
);
var icons=[twitter_icon, facebook_icon, pinterest_icon];
target=$(target);
target.html('');
$('<ul/>').appendTo(target);
target.find('ul').append(icons);
},
get_share_url: function(id, named_size){
if(typeof(named_size)==='undefined'){
named_size='thumb';
}
var gallery_id=$.nplModal('get_state').gallery_id;
var base_url=$.nplModal('get_setting', 'share_url')
.replace('{gallery_id}', gallery_id)
.replace('{image_id}', id)
.replace('{named_size}', named_size);
var site_url_link=$('<a/>').attr('href', $.nplModal('get_setting', 'wp_site_url'))[0];
var parent_link=$('<a/>').attr('href', window.location.toString())[0];
var base_link=$('<a/>').attr('href', base_url)[0];
if(parent_link.pathname.indexOf(site_url_link.pathname) >=0){
parent_link.pathname=parent_link.pathname.substr(site_url_link.pathname.length);
}
if(parent_link.pathname.indexOf(base_link.pathname) >=0){
parent_link.pathname=parent_link.pathname.substr(parent_link.pathname.length);
}
base_link.search=parent_link.search;
if(base_link.search.length > 0){
base_link.search +='&';
}
base_link.search +='uri=' + parent_link.pathname;
$.nplModal('log', 'theme share_icons.get_share_url() result', {
id: id,
named_size: named_size,
result: base_link.href
});
return base_link.href;
},
events: {
bind: function(){
$.nplModal('log', 'theme share_icons.events.bind()');
self.bind('loadfinish', this.loadfinish);
self.bind('npl_init', this.npl_init);
},
npl_init: function(){
if(typeof $.nplModal('get_setting', 'facebook_app_id')!=='undefined'){
if(typeof window.fbAsyncInit==='undefined'){
window.fbAsyncInit=function(){
FB.init({
appId: $.nplModal('get_setting', 'facebook_app_id'),
autoLogAppEvents: true,
xfbml: true,
version: 'v2.12'
});
};
(function(d, s, id){
var js, fjs=d.getElementsByTagName(s)[0];
if(d.getElementById(id)){ return; }
js=d.createElement(s); js.id=id;
js.src="https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}}
},
loadfinish: function(){
$.nplModal('log', 'theme share_icons.events.loadfinish()');
if(methods.nplModal.is_nextgen_gallery()
&&  $.nplModal('get_setting', 'enable_routing', false)
&&  $.nplModal('get_setting', 'enable_sharing', false)){
var iconcolor=$.nplModal('get_setting', 'carousel_text_color') ? $.nplModal('get_setting', 'carousel_text_color'):methods.icons.get_color();
methods.share_icons.create('#galleria-image-share-icons',
iconcolor
);
}}
}}
};
$.nplModal('log', 'theme initialization - about to bind events');
methods.galleria.events.bind();
methods.nplModal.events.bind();
methods.thumbnails.events.bind();
methods.info.events.bind();
methods.share_icons.events.bind();
methods.sidebar.events.bind();
methods.sidebars.datacache.events.bind();
methods.sidebars.comments.events.bind();
$.nplModal('log', 'theme initialization - done binding events');
$.nplModal('log', 'theme initialization - about to trigger npl_ready');
$(self._target).trigger('npl_ready', {galleria_theme: self, methods: methods});
$.nplModal('log', 'theme initialization - about to trigger npl_init');
self.trigger('npl_init');
$.nplModal('log', 'theme initialization - about to trigger npl_init_keys');
self.trigger('npl_init_keys');
$.nplModal('log', 'theme initialization - about to trigger npl_init_complete');
self.trigger('npl_init_complete');
}});
};
var interval=setInterval(function(){
if(typeof window.Galleria!=='undefined'){
clearInterval(interval);
add_nggpl_theme();
}}, 10);
}(jQuery));
(function($){
var user_is_using_ie=false;
if(navigator.appName.indexOf("Internet Explorer")!==-1){
if(navigator.appVersion.indexOf("MSIE 8")!==-1){
return;
}
if(navigator.appVersion.indexOf("MSIE 1")!==-1){
user_is_using_ie=10;
}}
var nggc_get_gallery=function(gallery_id){
if('undefined'==typeof window.galleries){
return null;
}
var retval=null;
$.each(window.galleries, function(index, gallery){
if(typeof gallery!=='object'){
return false;
}
if(gallery.ID===gallery_id){
retval=gallery;
}});
return retval;
};
var nggc_get_setting=function(gallery, name, def){
var tmp=def;
if(typeof gallery.display_settings[name]!='undefined'&&gallery.display_settings[name]!=''){
tmp=gallery.display_settings[name];
}else{
tmp=def;
}
if(tmp==1)       tmp=true;
if(tmp==0)       tmp=false;
if(tmp=='1')     tmp=true;
if(tmp=='0')     tmp=false;
if(tmp=='false') tmp=false;
if(tmp=='true')  tmp=true;
return tmp;
};
var nggc_allowed_tags=[
"EM",
"STRONG",
'B',
'DEL',
'I',
'INS',
'MARK',
'SMALL',
'STRIKE',
'SUB',
'SUP',
'TT',
'U'
];
var nggc_sanitize=function(string){
var element=document.createElement('div');
element.innerHTML=string;
nggc_real_sanitize(element);
return element.innerHTML;
};
var nggc_real_sanitize=function(element){
var allowed_tags=Array.prototype.slice.apply(element.getElementsByTagName("*"), [0]);
for (var i=0; i < allowed_tags.length; i++){
if(nggc_allowed_tags.indexOf(allowed_tags[i].nodeName)==-1){
nggc_sanitize_replace(allowed_tags[i]);
}}
};
var nggc_sanitize_replace=function(element){
var last=element;
for (var i=element.childNodes.length - 1; i >=0; i--){
var tmp=element.removeChild(element.childNodes[i]);
element.parentNode.insertBefore(tmp, last);
last=tmp;
}
element.parentNode.removeChild(element);
};
nggc_share_icons={
strip_html: function(html){
var tmp=document.createElement('div');
tmp.innerHTML=html;
return tmp.textContent||tmp.innerText||"";
},
create: function(target, image){
var image_id=image.data('image-id');
var gallery_id=image.data('nplmodal-gallery-id');
var base_url=encodeURIComponent(this.get_share_url(gallery_id, image_id));
var url=encodeURIComponent(window.location.toString());
var title=this.strip_html(image.data('title'));
var summary=this.strip_html(image.data('description'));
var twitter_icon=$('<i/>', {
'data-href': 'https://twitter.com/share?url=' + this.get_share_url(gallery_id, image_id, 'full'),
'class': 'ngg-caption-icon fa-brands fa-square-x-twitter'
});
var facebook_url='https://www.facebook.com/share.php';
facebook_url +='?u=' + encodeURIComponent(this.get_share_url(gallery_id, image_id, 'full'));
var facebook_icon=$('<i/>', {
'data-href': facebook_url,
'class': 'ngg-caption-icon fa fa-facebook-square'
});
var pinterest_url=encodeURIComponent(this.get_share_url(gallery_id, image_id, 'full'));
pinterest_url +='&url=' + url;
pinterest_url +='&media=' + image.attr('href');
pinterest_url +='&description=' + summary;
var pinterest_icon=$('<i/>', {
'data-href': 'http://pinterest.com/pin/create/button/?s=100' + pinterest_url,
'class': 'ngg-caption-icon fa fa-pinterest-square'
});
var icons=[twitter_icon, facebook_icon, pinterest_icon];
$(icons).each(function(){
$(this).on('click', function(event){
event.preventDefault();
var share_window=window.open($(this).data('href'), '_blank');
share_window.trigger('focus');
return false;
});
});
target.html('').append(icons);
},
get_share_url: function(gallery_id, image_id, named_size){
if(typeof(named_size)=='undefined'){
named_size='thumb';
}
var base_url=$.nplModal('get_setting', 'share_url')
.replace('{gallery_id}', gallery_id)
.replace('{image_id}', image_id)
.replace('{named_size}', named_size);
var site_url_link=$('<a/>').attr('href', $.nplModal('get_setting', 'wp_site_url'))[0];
var parent_link=$('<a/>').attr('href', window.location.toString())[0];
var base_link=$('<a/>').attr('href', base_url)[0];
if(parent_link.pathname.indexOf(site_url_link.pathname) >=0){
parent_link.pathname=parent_link.pathname.substr(site_url_link.pathname.length);
}
if(parent_link.pathname.indexOf(base_link.pathname) >=0){
parent_link.pathname=parent_link.pathname.substr(parent_link.pathname.length);
}
base_link.search=parent_link.search;
if(base_link.search.length > 0){
base_link.search +='&';
}
base_link.search +='uri=' + parent_link.pathname;
return base_link.href;
}};
$.fn.nggcaption=function(){
this.each(function(){
var $this=$(this);
var gallery=nggc_get_gallery($this.data('ngg-captions-id'));
var style=nggc_get_setting(gallery, 'captions_animation', 'slideup');
var $img=$this.find('img').first();
if(!$img.attr('src')&&!$img.attr('srcset')){
return true;
}
var $figure=$('<figure class="ngg-figure"></figure>');
var $figcaption=$('<figcaption class="ngg-figcaption"></figcaption>');
if(nggc_get_setting(gallery, 'captions_display_title', true)){
var $header=$('<h6>' + nggc_sanitize($this.data('title')) + '</h6>');
if(!nggc_get_setting(gallery, 'captions_display_title', true)){
$figure.addClass('nggc_no_title');
}}
var $body_div=$('<div class="nggc-body"/>');
var $body_p=$('<p>' + nggc_sanitize($this.data('description')) + '</p>');
$body_div.append($body_p);
if(!nggc_get_setting(gallery, 'captions_display_description', true)){
$figure.addClass('nggc_no_description');
}
var classList=$this.attr('class');
var inlineStyles=$this.attr('style');
var imageStyles=$img.attr('style');
$this.removeAttr('title');
if(!$this.data('ngg-captions-nostylecopy')){
$this.removeAttr('class');
$this.removeAttr('style');
}
this.classList.add('ngg-captions-processed');
$figure.addClass('ngg-figure-' + style);
$figcaption.addClass('ngg-figcaption-' + style);
if($.inArray(gallery.source, ['albums', 'random', 'random_images'])==-1
&&  typeof window.nplModalSettings!='undefined'
&&  nplModalSettings['enable_routing']=='1'
&&  nplModalSettings['enable_sharing']=='1'
&&  nggc_get_setting(gallery, 'captions_display_sharing', true)){
var slug=gallery.slug;
if(!slug||slug.indexOf('widget-ngg-images')==-1){
var $iconwrapper=$('<div class="nggc-icon-wrapper"/>');
nggc_share_icons.create($iconwrapper, $this);
$(document).trigger('ngg-caption-add-icons', {
el: $iconwrapper,
image_id: $this.data('image-id'),
gallery_id: $this.data('nplmodal-gallery-id')
});
$figcaption.append($iconwrapper);
}}else{
$figure.addClass('nggc_no_sharing');
}
if(nggc_get_setting(gallery, 'captions_display_title', true)){
$figcaption.append($header);
}
if(nggc_get_setting(gallery, 'captions_display_description', true)){
$figcaption.append($body_div);
}
if(user_is_using_ie&&user_is_using_ie===10){
$($figure).addClass("nggc-ie10");
}
if(!$this.data('ngg-captions-nostylecopy')){
$figure.attr('style', imageStyles);
$figure.attr('style', inlineStyles);
}
$img.removeAttr('style');
if(!$this.data('ngg-captions-nostylecopy')){
$figure.css({'max-width': parseInt($img[0].getAttribute('width')) + 'px'});
}
$newfigure=$img.wrap($figure);
$img.after($figcaption);
if(!$this.data('ngg-captions-nostylecopy')){
$newfigure.addClass(classList);
}
$newfigure.imagesLoaded().done(function(){
_unthrottled_nggc_adjust($figcaption);
});
$newfigure.parent('p').before($newfigure);
});
$(document).trigger('ngg-captions-added');
};
const _unthrottled_nggc_adjust=function($elements){
if(typeof $elements=='undefined'){
$elements=$('figcaption.ngg-figcaption');
}
$('div.nextgen_pro_thumbnail_grid a').each(function(){
var $this=$(this);
var $img=$this.find('img');
if($img.hasClass('thickbox')){
$img.removeClass('thickbox');
$this.addClass('thickbox');
}});
$elements.each(function(){
const $self=$(this);
const gallery=nggc_get_gallery($self.parents('a').first().data('ngg-captions-id'));
const style=nggc_get_setting(gallery, 'captions_animation', 'slideup');
const h6=$self.find('h6');
const h6_height=h6.length!==0 ? h6.outerHeight():0;
const total_height=$self.outerHeight();
const icon_wrapper=$self.find('.nggc-icon-wrapper');
const icon_wrapper_height=icon_wrapper.length!==0 ? icon_wrapper.height():0;
const body=$self.find('.nggc-body');
const p=$self.find('.nggc-body p');
if(style==='titlebar'){
if(p.length!==0){
shave(p[0], body.height());
}}else{
if(h6.length!==0){
shave(h6[0], (total_height - icon_wrapper_height));
}
if(p.length!==0){
shave(p[0], (total_height - icon_wrapper_height - h6_height - 20));
}}
});
};
const nggc_adjust=_.debounce(_unthrottled_nggc_adjust, 500, true);
window.ngg_captions_adjust=nggc_adjust;
const nggc_init=function(bind){
bind=bind||false;
$('a[data-ngg-captions-enabled]:not(".ngg-captions-processed")').each(function(){
this.classList.add('ngg-captions-processed');
const $this=$(this);
if(bind){
$(window).on('load', function (){
$this.nggcaption();
});
}else{
$this.nggcaption();
}});
};
nggc_init(true);
$(window).on('refreshed', function(){
nggc_init();
nggc_adjust();
});
$(window).on('resize fullscreenchange mozfullscreenchange webkitfullscreenchange orientationchange', function(){
nggc_adjust();
});
})(jQuery);
(function($){
$(document).on('npl_ready', function(e, data){
var methods=data.methods;
var self=data.galleria_theme;
log=function(message, table, level){
jQuery.nplModal('log', message, table, level)
};
log("ecommerce initializing");
var app=null;
methods.sidebars.cart={
init: function(){
},
run_backbone_app: function(id, cache){
if(app) app.remove();
app=new Ngg_Pro_Cart.Views.Add_To_Cart({
image_id: id,
container: $('#npl_sidebar'),
datacache: cache
});
},
render: function(id){
log("ecommerce sidebars.cart.render()", {
id: id
});
var self=this;
var cache=methods.sidebars.datacache.get_cache_by_id(id);
if(!cache){
$('#npl_wrapper').addClass('npl-sidebar-overlay-open');
methods.sidebars.datacache.expanded_request(id, function(){
cache=methods.sidebars.datacache.get_cache_by_id(id);
self.run_backbone_app(id, cache);
});
}else if(cache==='Placeholder stub'){
$('#npl_wrapper').addClass('npl-sidebar-overlay-open');
var interval=setInterval(function(){
cache=methods.sidebars.datacache.get_cache_by_id(id);
if(cache!=='Placeholder stub'){
self.run_backbone_app(id, cache);
clearInterval(interval);
}}, 250);
}else{
self.run_backbone_app(id, cache);
}},
get_type: function(){
return 'cart';
},
events: {
bind: function(){
log("ecommerce sidebars.cart.events.bind()");
self.bind('npl_init', this.npl_init);
self.bind('npl_init_keys', this.npl_init_keys);
self.bind('image', this.image);
},
_image_ran_once: false,
image: function(){
log("ecommerce sidebars.cart.events.image()");
if(methods.sidebars.cart.events.is_ecommerce_enabled()){
if(!methods.sidebars.cart._image_ran_once){
if(($.nplModal('get_state').sidebar&&$.nplModal('get_state').sidebar==methods.sidebars.cart.get_type())
||  ($.nplModal('get_setting', 'display_cart', false)&&!$.nplModal('get_setting', 'display_comments', false))){
methods.sidebar.open(methods.sidebars.cart.get_type());
}}else if($.nplModal('get_state').sidebar&&$.nplModal('get_state').sidebar==methods.sidebars.cart.get_type()){
methods.sidebar.render(methods.sidebars.cart.get_type());
}
methods.sidebars.cart._image_ran_once=true;
}},
is_ecommerce_enabled: function(){
var retval=false;
var gallery=$.nplModal('get_gallery_from_id', $.nplModal('get_state').gallery_id);
if(gallery&&typeof(gallery.display_settings['is_ecommerce_enabled'])!='undefined'){
retval=gallery.display_settings['is_ecommerce_enabled'];
}
if(gallery&&typeof(gallery.display_settings['original_settings'])!='undefined'){
if(typeof(gallery.display_settings['original_settings']['is_ecommerce_enabled'])!='undefined'){
retval=gallery.display_settings['original_settings']['is_ecommerce_enabled'];
}}
return parseInt(retval);
},
npl_init: function(){
log("ecommerce sidebars.cart.events.npl_init()");
var is_ecommerce_enabled=methods.sidebars.cart.events.is_ecommerce_enabled;
if(is_ecommerce_enabled()){
var cart_button=$('<i/>')
.addClass('nggpl-toolbar-button-cart fa fa-shopping-cart')
.attr({'title': ngg_cart_i18n.nggpl_toggle_sidebar});
methods.thumbnails.register_button(cart_button,
function(event){
methods.sidebar.toggle(methods.sidebars.cart.get_type());
event.preventDefault();
}
);
}},
npl_init_keys: function(event){
log("ecommerce sidebars.cart.events.npl_init_keys");
var input_types=methods.galleria.get_keybinding_exclude_list();
self.attachKeyboard({
69: function(){
var is_ecommerce_enabled=methods.sidebars.cart.events.is_ecommerce_enabled;
if(!$(document.activeElement).is(input_types)&&is_ecommerce_enabled()){
methods.sidebar.toggle(methods.sidebars.cart.get_type());
}}
});
}}
};
methods.sidebars.cart.events.bind();
});
$(document).on('ngg-caption-add-icons', function(event, obj){
if(!$.nplModal('get_displayed_gallery_setting', obj.gallery_id, 'is_ecommerce_enabled', false)){
return;
}
var cart_icon=$('<i/>', {
'class': 'fa fa-shopping-cart nextgen_pro_lightbox ngg-caption-icon',
'data-nplmodal-gallery-id': obj.gallery_id,
'data-nplmodal-image-id': obj.image_id,
'data-image-id': obj.image_id,
'data-nplmodal-show-cart': '1'
}).on('click', function(event){
event.preventDefault();
$.nplModal('open', $(this));
return false;
});
obj.el.append(cart_icon);
});
})(jQuery);
jQuery(function($){
if(typeof ngg_pro_proofing_i18n!='undefined'){
$('#npl_content').on('npl_ready', function (e, data){
var methods=data.methods;
var self=data.galleria_theme;
methods.thumbnails.proofing={
init: function(){},
proofing_button: $('<i/>')
.addClass('nggpl-toolbar-button-proofing fa fa-star')
.attr({'title': ngg_pro_proofing_i18n.nggpl_title}),
get_active_color: function(){
var retval='#ffff00';
if(typeof ngg_proofing_settings!=='undefined'){
retval=ngg_proofing_settings.active_color;
}
return retval;
},
events: {
bind: function(){
if(typeof ngg_image_proofing!=='undefined'){
self.bind('npl_init', this.npl_init);
self.bind('image', this.image);
}},
is_proofing_enabled: function(){
return methods.galleria.get_displayed_gallery_setting('ngg_proofing_display', false);
},
is_image_proofed: function(){
var image_id=methods.galleria.get_current_image_id();
var gallery_id=$.nplModal('get_state').gallery_id;
var proofed_list=ngg_image_proofing.getList(gallery_id);
var index=proofed_list.indexOf(image_id.toString());
return (index > -1);
},
image: function(){
if(methods.thumbnails.proofing.events.is_proofing_enabled()){
var btn=$('.galleria-nextgen-buttons .nggpl-toolbar-button-proofing');
if(methods.thumbnails.proofing.events.is_image_proofed()){
btn.css({color: methods.thumbnails.proofing.get_active_color()});
}else{
btn.removeAttr('style');
}}
},
npl_init: function(){
if(methods.thumbnails.proofing.events.is_proofing_enabled()){
methods.thumbnails.register_button(methods.thumbnails.proofing.proofing_button,
function(event){
methods.thumbnails.proofing.events.button_clicked(event);
}
);
}},
button_clicked: function (event){
var state=$.nplModal('get_state');
ngg_image_proofing.addOrRemoveImage(state.gallery_id, state.image_id);
methods.thumbnails.proofing.events.image();
event.preventDefault();
}}
};
methods.thumbnails.proofing.events.bind();
});
}});
const animateNextGENImage=function (node, animation){
const prefix='animate__';
return new Promise((resolve, reject)=> {
const animationName=`${prefix}${animation}`;
node.classList.remove('nextgen-pro-animate-images-loading');
node.classList.add(`${prefix}animated`, animationName);
function handleAnimationEnd(event){
event.stopPropagation();
node.classList.remove(`${prefix}animated`, animationName);
resolve('Animation ended');
}
node.addEventListener('animationend', handleAnimationEnd, {once: true});
});
};
const processNextGENImageAnimations=function(styleName){
const containers=document.querySelectorAll('.nextgen-pro-animate-images-gallery-container');
containers.forEach(function (container){
if(1===parseInt(container.dataset.animateAll)){
styleName='pagination';
}
const style=container.dataset[`${styleName}Style`];
const duration=parseInt(container.dataset[`${styleName}Duration`]);
const delay=parseInt(container.dataset[`${styleName}Delay`]);
container.querySelectorAll('.nextgen-pro-animate-images-image-container').forEach(function(image, index){
image.style.setProperty('--animate-duration', `${duration}ms`);
setTimeout(()=> {
animateNextGENImage(image, style);
}, (0===index ? 0:index * delay));
}
);
});
};
document.addEventListener('nextgen_page_refreshed', function(){
processNextGENImageAnimations('pagination');
});
processNextGENImageAnimations('firstload');
(function (factory){
if(typeof define==='function'&&define.amd){
define(['jquery'], factory);
}else if(typeof module==='object'&&module.exports){
module.exports=function (root, jQuery){
if(jQuery===undefined){
if(typeof window!=='undefined'){
jQuery=require('jquery');
}else{
jQuery=require('jquery')(root);
}}
factory(jQuery);
return jQuery;
};}else{
factory(jQuery);
}}(function ($){
var JustifiedGallery=function ($gallery, settings){
this.settings=settings;
this.checkSettings();
this.imgAnalyzerTimeout=null;
this.entries=null;
this.buildingRow={
entriesBuff: [],
width: 0,
height: 0,
aspectRatio: 0
};
this.lastFetchedEntry=null;
this.lastAnalyzedIndex=-1;
this.yield={
every: 2,
flushed: 0 
};
this.border=settings.border >=0 ? settings.border:settings.margins;
this.maxRowHeight=this.retrieveMaxRowHeight();
this.suffixRanges=this.retrieveSuffixRanges();
this.offY=this.border;
this.rows=0;
this.spinner={
phase: 0,
timeSlot: 150,
$el: $('<div class="jg-spinner"><span></span><span></span><span></span></div>'),
intervalId: null
};
this.scrollBarOn=false;
this.checkWidthIntervalId=null;
this.galleryWidth=$gallery.width();
this.$gallery=$gallery;
};
JustifiedGallery.prototype.getSuffix=function (width, height){
var longestSide, i;
longestSide=(width > height) ? width:height;
for (i=0; i < this.suffixRanges.length; i++){
if(longestSide <=this.suffixRanges[i]){
return this.settings.sizeRangeSuffixes[this.suffixRanges[i]];
}}
return this.settings.sizeRangeSuffixes[this.suffixRanges[i - 1]];
};
JustifiedGallery.prototype.removeSuffix=function (str, suffix){
return str.substring(0, str.length - suffix.length);
};
JustifiedGallery.prototype.endsWith=function (str, suffix){
return str.indexOf(suffix, str.length - suffix.length)!==-1;
};
JustifiedGallery.prototype.getUsedSuffix=function (str){
for (var si in this.settings.sizeRangeSuffixes){
if(this.settings.sizeRangeSuffixes.hasOwnProperty(si)){
if(this.settings.sizeRangeSuffixes[si].length===0) continue;
if(this.endsWith(str, this.settings.sizeRangeSuffixes[si])) return this.settings.sizeRangeSuffixes[si];
}}
return '';
};
JustifiedGallery.prototype.newSrc=function (imageSrc, imgWidth, imgHeight, image){
var newImageSrc;
if(this.settings.thumbnailPath){
newImageSrc=this.settings.thumbnailPath(imageSrc, imgWidth, imgHeight, image);
}else{
var matchRes=imageSrc.match(this.settings.extension);
var ext=(matchRes!==null) ? matchRes[0]:'';
newImageSrc=imageSrc.replace(this.settings.extension, '');
newImageSrc=this.removeSuffix(newImageSrc, this.getUsedSuffix(newImageSrc));
newImageSrc +=this.getSuffix(imgWidth, imgHeight) + ext;
}
return newImageSrc;
};
JustifiedGallery.prototype.showImg=function ($entry, callback){
if(this.settings.cssAnimation){
$entry.addClass('jg-entry-visible');
if(callback) callback();
}else{
$entry.stop().fadeTo(this.settings.imagesAnimationDuration, 1.0, callback);
$entry.find(this.settings.imgSelector).stop().fadeTo(this.settings.imagesAnimationDuration, 1.0, callback);
}};
JustifiedGallery.prototype.extractImgSrcFromImage=function ($image){
var imageSrc=$image.data('safe-src');
var imageSrcLoc='data-safe-src';
if(typeof imageSrc==='undefined'){
imageSrc=$image.attr('src');
imageSrcLoc='src';
}
$image.data('jg.originalSrc', imageSrc);
$image.data('jg.src', imageSrc);
$image.data('jg.originalSrcLoc', imageSrcLoc);
return imageSrc;
};
JustifiedGallery.prototype.imgFromEntry=function ($entry){
var $img=$entry.find(this.settings.imgSelector);
return $img.length===0 ? null:$img;
};
JustifiedGallery.prototype.captionFromEntry=function ($entry){
var $caption=$entry.find('> .jg-caption');
return $caption.length===0 ? null:$caption;
};
JustifiedGallery.prototype.displayEntry=function ($entry, x, y, imgWidth, imgHeight, rowHeight){
$entry.width(imgWidth);
$entry.height(rowHeight);
$entry.css('top', y);
$entry.css('left', x);
var $image=this.imgFromEntry($entry);
if($image!==null){
$image.css('width', imgWidth);
$image.css('height', imgHeight);
$image.css('margin-left', - imgWidth / 2);
$image.css('margin-top', - imgHeight / 2);
var imageSrc=$image.data('jg.src');
if(imageSrc){
imageSrc=this.newSrc(imageSrc, imgWidth, imgHeight, $image[0]);
$image.one('error', function (){
this.resetImgSrc($image);
});
var loadNewImage=function (){
$image.attr('src', imageSrc);
};
if($entry.data('jg.loaded')==='skipped'&&imageSrc){
this.onImageEvent(imageSrc, (function(){
this.showImg($entry, loadNewImage);
$entry.data('jg.loaded', true);
}).bind(this));
}else{
this.showImg($entry, loadNewImage);
}}
}else{
this.showImg($entry);
}
this.displayEntryCaption($entry);
};
JustifiedGallery.prototype.displayEntryCaption=function ($entry){
var $image=this.imgFromEntry($entry);
if($image!==null&&this.settings.captions){
var $imgCaption=this.captionFromEntry($entry);
if($imgCaption===null){
var caption=$image.attr('alt');
if(!this.isValidCaption(caption)) caption=$entry.attr('title');
if(this.isValidCaption(caption)){
$imgCaption=$('<div class="jg-caption">' + caption + '</div>');
$entry.append($imgCaption);
$entry.data('jg.createdCaption', true);
}}
if($imgCaption!==null){
if(!this.settings.cssAnimation) $imgCaption.stop().fadeTo(0, this.settings.captionSettings.nonVisibleOpacity);
this.addCaptionEventsHandlers($entry);
}}else{
this.removeCaptionEventsHandlers($entry);
}};
JustifiedGallery.prototype.isValidCaption=function (caption){
return (typeof caption!=='undefined'&&caption.length > 0);
};
JustifiedGallery.prototype.onEntryMouseEnterForCaption=function (eventObject){
var $caption=this.captionFromEntry($(eventObject.currentTarget));
if(this.settings.cssAnimation){
$caption.addClass('jg-caption-visible').removeClass('jg-caption-hidden');
}else{
$caption.stop().fadeTo(this.settings.captionSettings.animationDuration,
this.settings.captionSettings.visibleOpacity);
}};
JustifiedGallery.prototype.onEntryMouseLeaveForCaption=function (eventObject){
var $caption=this.captionFromEntry($(eventObject.currentTarget));
if(this.settings.cssAnimation){
$caption.removeClass('jg-caption-visible').removeClass('jg-caption-hidden');
}else{
$caption.stop().fadeTo(this.settings.captionSettings.animationDuration,
this.settings.captionSettings.nonVisibleOpacity);
}};
JustifiedGallery.prototype.addCaptionEventsHandlers=function ($entry){
var captionMouseEvents=$entry.data('jg.captionMouseEvents');
if(typeof captionMouseEvents==='undefined'){
captionMouseEvents={
mouseenter: this.onEntryMouseEnterForCaption.bind(this),
mouseleave: this.onEntryMouseLeaveForCaption.bind(this)
};
$entry.on('mouseenter', undefined, undefined, captionMouseEvents.mouseenter);
$entry.on('mouseleave', undefined, undefined, captionMouseEvents.mouseleave);
$entry.data('jg.captionMouseEvents', captionMouseEvents);
}};
JustifiedGallery.prototype.removeCaptionEventsHandlers=function ($entry){
var captionMouseEvents=$entry.data('jg.captionMouseEvents');
if(typeof captionMouseEvents!=='undefined'){
$entry.off('mouseenter', undefined, captionMouseEvents.mouseenter);
$entry.off('mouseleave', undefined, captionMouseEvents.mouseleave);
$entry.removeData('jg.captionMouseEvents');
}};
JustifiedGallery.prototype.clearBuildingRow=function (){
this.buildingRow.entriesBuff=[];
this.buildingRow.aspectRatio=0;
this.buildingRow.width=0;
};
JustifiedGallery.prototype.prepareBuildingRow=function (isLastRow, hiddenRow){
var i, $entry, imgAspectRatio, newImgW, newImgH, justify=true;
var minHeight=0;
var availableWidth=this.galleryWidth - 2 * this.border - (
(this.buildingRow.entriesBuff.length - 1) * this.settings.margins);
var rowHeight=availableWidth / this.buildingRow.aspectRatio;
var defaultRowHeight=this.settings.rowHeight;
var justifiable=this.buildingRow.width / availableWidth > this.settings.justifyThreshold;
if(hiddenRow||(isLastRow&&this.settings.lastRow==='hide'&&!justifiable)){
for (i=0; i < this.buildingRow.entriesBuff.length; i++){
$entry=this.buildingRow.entriesBuff[i];
if(this.settings.cssAnimation)
$entry.removeClass('jg-entry-visible');
else {
$entry.stop().fadeTo(0, 0.1);
$entry.find('> img, > a > img').fadeTo(0, 0);
}}
return -1;
}
if(isLastRow&&!justifiable&&this.settings.lastRow!=='justify'&&this.settings.lastRow!=='hide'){
justify=false;
if(this.rows > 0){
defaultRowHeight=(this.offY - this.border - this.settings.margins * this.rows) / this.rows;
justify=defaultRowHeight * this.buildingRow.aspectRatio / availableWidth > this.settings.justifyThreshold;
}}
for (i=0; i < this.buildingRow.entriesBuff.length; i++){
$entry=this.buildingRow.entriesBuff[i];
imgAspectRatio=$entry.data('jg.width') / $entry.data('jg.height');
if(justify){
newImgW=(i===this.buildingRow.entriesBuff.length - 1) ? availableWidth:rowHeight * imgAspectRatio;
newImgH=rowHeight;
}else{
newImgW=defaultRowHeight * imgAspectRatio;
newImgH=defaultRowHeight;
}
availableWidth -=Math.round(newImgW);
$entry.data('jg.jwidth', Math.round(newImgW));
$entry.data('jg.jheight', Math.ceil(newImgH));
if(i===0||minHeight > newImgH) minHeight=newImgH;
}
this.buildingRow.height=minHeight;
return justify;
};
JustifiedGallery.prototype.flushRow=function (isLastRow, hiddenRow){
var settings=this.settings;
var $entry, buildingRowRes, offX=this.border, i;
buildingRowRes=this.prepareBuildingRow(isLastRow, hiddenRow);
if(hiddenRow||(isLastRow&&settings.lastRow==='hide'&&buildingRowRes===-1)){
this.clearBuildingRow();
return;
}
if(this.maxRowHeight){
if(this.maxRowHeight < this.buildingRow.height) this.buildingRow.height=this.maxRowHeight;
}
if(isLastRow&&(settings.lastRow==='center'||settings.lastRow==='right')){
var availableWidth=this.galleryWidth - 2 * this.border - (this.buildingRow.entriesBuff.length - 1) * settings.margins;
for (i=0; i < this.buildingRow.entriesBuff.length; i++){
$entry=this.buildingRow.entriesBuff[i];
availableWidth -=$entry.data('jg.jwidth');
}
if(settings.lastRow==='center')
offX +=Math.round(availableWidth / 2);
else if(settings.lastRow==='right')
offX +=availableWidth;
}
var lastEntryIdx=this.buildingRow.entriesBuff.length - 1;
for (i=0; i <=lastEntryIdx; i++){
$entry=this.buildingRow.entriesBuff[this.settings.rtl ? lastEntryIdx - i:i];
this.displayEntry($entry, offX, this.offY, $entry.data('jg.jwidth'), $entry.data('jg.jheight'), this.buildingRow.height);
offX +=$entry.data('jg.jwidth') + settings.margins;
}
this.galleryHeightToSet=this.offY + this.buildingRow.height + this.border;
this.setGalleryTempHeight(this.galleryHeightToSet + this.getSpinnerHeight());
if(!isLastRow||(this.buildingRow.height <=settings.rowHeight&&buildingRowRes)){
this.offY +=this.buildingRow.height + settings.margins;
this.rows +=1;
this.clearBuildingRow();
this.settings.triggerEvent.call(this, 'jg.rowflush');
}};
var galleryPrevStaticHeight=0;
JustifiedGallery.prototype.rememberGalleryHeight=function (){
galleryPrevStaticHeight=this.$gallery.height();
this.$gallery.height(galleryPrevStaticHeight);
};
JustifiedGallery.prototype.setGalleryTempHeight=function (height){
galleryPrevStaticHeight=Math.max(height, galleryPrevStaticHeight);
this.$gallery.height(galleryPrevStaticHeight);
};
JustifiedGallery.prototype.setGalleryFinalHeight=function (height){
galleryPrevStaticHeight=height;
this.$gallery.height(height);
};
JustifiedGallery.prototype.checkWidth=function (){
function proxiedMethod(){
if(!this.$gallery.is(":visible")) return;
var galleryWidth=parseFloat(this.$gallery.width());
if(Math.abs(galleryWidth - this.galleryWidth) > this.settings.refreshSensitivity){
this.galleryWidth=galleryWidth;
this.rewind();
this.rememberGalleryHeight();
this.startImgAnalyzer(true);
}}
this.checkWidthIntervalId=setInterval(proxiedMethod.bind(this), this.settings.refreshTime);
};
JustifiedGallery.prototype.isSpinnerActive=function (){
return this.spinner.intervalId!==null;
};
JustifiedGallery.prototype.getSpinnerHeight=function (){
return this.spinner.$el.innerHeight();
};
JustifiedGallery.prototype.stopLoadingSpinnerAnimation=function (){
clearInterval(this.spinner.intervalId);
this.spinner.intervalId=null;
this.setGalleryTempHeight(this.$gallery.height() - this.getSpinnerHeight());
this.spinner.$el.detach();
};
JustifiedGallery.prototype.startLoadingSpinnerAnimation=function (){
var spinnerContext=this.spinner;
var $spinnerPoints=spinnerContext.$el.find('span');
clearInterval(spinnerContext.intervalId);
this.$gallery.append(spinnerContext.$el);
this.setGalleryTempHeight(this.offY + this.buildingRow.height + this.getSpinnerHeight());
spinnerContext.intervalId=setInterval(function (){
if(spinnerContext.phase < $spinnerPoints.length){
$spinnerPoints.eq(spinnerContext.phase).fadeTo(spinnerContext.timeSlot, 1);
}else{
$spinnerPoints.eq(spinnerContext.phase - $spinnerPoints.length).fadeTo(spinnerContext.timeSlot, 0);
}
spinnerContext.phase=(spinnerContext.phase + 1) % ($spinnerPoints.length * 2);
}, spinnerContext.timeSlot);
};
JustifiedGallery.prototype.rewind=function (){
this.lastFetchedEntry=null;
this.lastAnalyzedIndex=-1;
this.offY=this.border;
this.rows=0;
this.clearBuildingRow();
};
JustifiedGallery.prototype.getSelectorWithoutSpinner=function (){
return this.settings.selector + ', div:not(.jg-spinner)';
};
JustifiedGallery.prototype.getAllEntries=function (){
var selector=this.getSelectorWithoutSpinner();
return this.$gallery.children(selector).toArray();
};
JustifiedGallery.prototype.updateEntries=function (norewind){
var newEntries;
if(norewind&&this.lastFetchedEntry!=null){
var selector=this.getSelectorWithoutSpinner();
newEntries=$(this.lastFetchedEntry).nextAll(selector).toArray();
}else{
this.entries=[];
newEntries=this.getAllEntries();
}
if(newEntries.length > 0){
if(typeof(this.settings.sort)==="function"){
newEntries=this.sortArray(newEntries);
}else if(this.settings.randomize){
newEntries=this.shuffleArray(newEntries);
}
this.lastFetchedEntry=newEntries[newEntries.length - 1];
if(this.settings.filter){
newEntries=this.filterArray(newEntries);
}else{
this.resetFilters(newEntries);
}}
this.entries=this.entries.concat(newEntries);
return true;
};
JustifiedGallery.prototype.insertToGallery=function (entries){
var that=this;
$.each(entries, function (){
$(this).appendTo(that.$gallery);
});
};
JustifiedGallery.prototype.shuffleArray=function (a){
var i, j, temp;
for (i=a.length - 1; i > 0; i--){
j=Math.floor(Math.random() * (i + 1));
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
this.insertToGallery(a);
return a;
};
JustifiedGallery.prototype.sortArray=function (a){
a.sort(this.settings.sort);
this.insertToGallery(a);
return a;
};
JustifiedGallery.prototype.resetFilters=function (a){
for (var i=0; i < a.length; i++) $(a[i]).removeClass('jg-filtered');
};
JustifiedGallery.prototype.filterArray=function (a){
var settings=this.settings;
if(typeof(settings.filter)==='string'){
return a.filter(function (el){
var $el=$(el);
if($el.is(settings.filter)){
$el.removeClass('jg-filtered');
return true;
}else{
$el.addClass('jg-filtered').removeClass('jg-visible');
return false;
}});
}else if(typeof(settings.filter)==="function"){
var filteredArr=a.filter(settings.filter);
for (var i=0; i < a.length; i++){
if(filteredArr.indexOf(a[i])===-1){
$(a[i]).addClass('jg-filtered').removeClass('jg-visible');
}else{
$(a[i]).removeClass('jg-filtered');
}}
return filteredArr;
}};
JustifiedGallery.prototype.resetImgSrc=function ($img){
if($img.data('jg.originalSrcLoc')==='src'){
$img.attr('src', $img.data('jg.originalSrc'));
}else{
$img.attr('src', '');
}};
JustifiedGallery.prototype.destroy=function (){
clearInterval(this.checkWidthIntervalId);
this.stopImgAnalyzerStarter();
function proxiedMethod(_, entry){
var $entry=$(entry);
$entry.css('width', '');
$entry.css('height', '');
$entry.css('top', '');
$entry.css('left', '');
$entry.data('jg.loaded', undefined);
$entry.removeClass('jg-entry jg-filtered jg-entry-visible');
var $img=this.imgFromEntry($entry);
if($img){
$img.css('width', '');
$img.css('height', '');
$img.css('margin-left', '');
$img.css('margin-top', '');
this.resetImgSrc($img);
$img.data('jg.originalSrc', undefined);
$img.data('jg.originalSrcLoc', undefined);
$img.data('jg.src', undefined);
}
this.removeCaptionEventsHandlers($entry);
var $caption=this.captionFromEntry($entry);
if($entry.data('jg.createdCaption')){
$entry.data('jg.createdCaption', undefined);
if($caption!==null) $caption.remove();
}else{
if($caption!==null) $caption.fadeTo(0, 1);
}}
$.each(this.getAllEntries(), proxiedMethod.bind(this));
this.$gallery.css('height', '');
this.$gallery.removeClass('justified-gallery');
this.$gallery.data('jg.controller', undefined);
this.settings.triggerEvent.call(this, 'jg.destroy');
};
JustifiedGallery.prototype.analyzeImages=function (isForResize){
for (var i=this.lastAnalyzedIndex + 1; i < this.entries.length; i++){
var $entry=$(this.entries[i]);
if($entry.data('jg.loaded')===true||$entry.data('jg.loaded')==='skipped'){
var availableWidth=this.galleryWidth - 2 * this.border - (
(this.buildingRow.entriesBuff.length - 1) * this.settings.margins);
var imgAspectRatio=$entry.data('jg.width') / $entry.data('jg.height');
this.buildingRow.entriesBuff.push($entry);
this.buildingRow.aspectRatio +=imgAspectRatio;
this.buildingRow.width +=imgAspectRatio * this.settings.rowHeight;
this.lastAnalyzedIndex=i;
if(availableWidth / (this.buildingRow.aspectRatio + imgAspectRatio) < this.settings.rowHeight){
this.flushRow(false, this.settings.maxRowsCount > 0&&this.rows===this.settings.maxRowsCount);
if(++this.yield.flushed >=this.yield.every){
this.startImgAnalyzer(isForResize);
return;
}}
}else if($entry.data('jg.loaded')!=='error'){
return;
}}
if(this.buildingRow.entriesBuff.length > 0){
this.flushRow(true, this.settings.maxRowsCount > 0&&this.rows===this.settings.maxRowsCount);
}
if(this.isSpinnerActive()){
this.stopLoadingSpinnerAnimation();
}
this.stopImgAnalyzerStarter();
this.setGalleryFinalHeight(this.galleryHeightToSet);
this.settings.triggerEvent.call(this, isForResize ? 'jg.resize':'jg.complete');
};
JustifiedGallery.prototype.stopImgAnalyzerStarter=function (){
this.yield.flushed=0;
if(this.imgAnalyzerTimeout!==null){
clearTimeout(this.imgAnalyzerTimeout);
this.imgAnalyzerTimeout=null;
}};
JustifiedGallery.prototype.startImgAnalyzer=function (isForResize){
var that=this;
this.stopImgAnalyzerStarter();
this.imgAnalyzerTimeout=setTimeout(function (){
that.analyzeImages(isForResize);
}, 0.001);
};
JustifiedGallery.prototype.onImageEvent=function (imageSrc, onLoad, onError){
if(!onLoad&&!onError) return;
var memImage=new Image();
var $memImage=$(memImage);
if(onLoad){
$memImage.one('load', function (){
$memImage.off('load error');
onLoad(memImage);
});
}
if(onError){
$memImage.one('error', function (){
$memImage.off('load error');
onError(memImage);
});
}
memImage.src=imageSrc;
};
JustifiedGallery.prototype.init=function (){
var imagesToLoad=false, skippedImages=false, that=this;
$.each(this.entries, function (index, entry){
var $entry=$(entry);
var $image=that.imgFromEntry($entry);
$entry.addClass('jg-entry');
if($entry.data('jg.loaded')!==true&&$entry.data('jg.loaded')!=='skipped'){
if(that.settings.rel!==null) $entry.attr('rel', that.settings.rel);
if(that.settings.target!==null) $entry.attr('target', that.settings.target);
if($image!==null){
var imageSrc=that.extractImgSrcFromImage($image);
if(that.settings.waitThumbnailsLoad===false||!imageSrc){
var width=parseFloat($image.attr('width'));
var height=parseFloat($image.attr('height'));
if($image.prop('tagName')==='svg'){
width=parseFloat($image[0].getBBox().width);
height=parseFloat($image[0].getBBox().height);
}
if(!isNaN(width)&&!isNaN(height)){
$entry.data('jg.width', width);
$entry.data('jg.height', height);
$entry.data('jg.loaded', 'skipped');
skippedImages=true;
that.startImgAnalyzer(false);
return true;
}}
$entry.data('jg.loaded', false);
imagesToLoad=true;
if(!that.isSpinnerActive()) that.startLoadingSpinnerAnimation();
that.onImageEvent(imageSrc, function (loadImg){
$entry.data('jg.width', loadImg.width);
$entry.data('jg.height', loadImg.height);
$entry.data('jg.loaded', true);
that.startImgAnalyzer(false);
}, function (){
$entry.data('jg.loaded', 'error');
that.startImgAnalyzer(false);
});
}else{
$entry.data('jg.loaded', true);
$entry.data('jg.width', $entry.width() | parseFloat($entry.css('width')) | 1);
$entry.data('jg.height', $entry.height() | parseFloat($entry.css('height')) | 1);
}}
});
if(!imagesToLoad&&!skippedImages) this.startImgAnalyzer(false);
this.checkWidth();
};
JustifiedGallery.prototype.checkOrConvertNumber=function (settingContainer, settingName){
if(typeof(settingContainer[settingName])==='string'){
settingContainer[settingName]=parseFloat(settingContainer[settingName]);
}
if(typeof(settingContainer[settingName])==='number'){
if(isNaN(settingContainer[settingName])) throw 'invalid number for ' + settingName;
}else{
throw settingName + ' must be a number';
}};
JustifiedGallery.prototype.checkSizeRangesSuffixes=function (){
if(typeof(this.settings.sizeRangeSuffixes)!=='object'){
throw 'sizeRangeSuffixes must be defined and must be an object';
}
var suffixRanges=[];
for (var rangeIdx in this.settings.sizeRangeSuffixes){
if(this.settings.sizeRangeSuffixes.hasOwnProperty(rangeIdx)) suffixRanges.push(rangeIdx);
}
var newSizeRngSuffixes={ 0: '' };
for (var i=0; i < suffixRanges.length; i++){
if(typeof(suffixRanges[i])==='string'){
try {
var numIdx=parseInt(suffixRanges[i].replace(/^[a-z]+/, ''), 10);
newSizeRngSuffixes[numIdx]=this.settings.sizeRangeSuffixes[suffixRanges[i]];
} catch (e){
throw 'sizeRangeSuffixes keys must contains correct numbers (' + e + ')';
}}else{
newSizeRngSuffixes[suffixRanges[i]]=this.settings.sizeRangeSuffixes[suffixRanges[i]];
}}
this.settings.sizeRangeSuffixes=newSizeRngSuffixes;
};
JustifiedGallery.prototype.retrieveMaxRowHeight=function (){
var newMaxRowHeight=null;
var rowHeight=this.settings.rowHeight;
if(typeof(this.settings.maxRowHeight)==='string'){
if(this.settings.maxRowHeight.match(/^[0-9]+%$/)){
newMaxRowHeight=rowHeight * parseFloat(this.settings.maxRowHeight.match(/^([0-9]+)%$/)[1]) / 100;
}else{
newMaxRowHeight=parseFloat(this.settings.maxRowHeight);
}}else if(typeof(this.settings.maxRowHeight)==='number'){
newMaxRowHeight=this.settings.maxRowHeight;
}else if(this.settings.maxRowHeight===false||this.settings.maxRowHeight==null){
return null;
}else{
throw 'maxRowHeight must be a number or a percentage';
}
if(isNaN(newMaxRowHeight)) throw 'invalid number for maxRowHeight';
if(newMaxRowHeight < rowHeight) newMaxRowHeight=rowHeight;
return newMaxRowHeight;
};
JustifiedGallery.prototype.checkSettings=function (){
this.checkSizeRangesSuffixes();
this.checkOrConvertNumber(this.settings, 'rowHeight');
this.checkOrConvertNumber(this.settings, 'margins');
this.checkOrConvertNumber(this.settings, 'border');
this.checkOrConvertNumber(this.settings, 'maxRowsCount');
var lastRowModes=[
'justify',
'nojustify',
'left',
'center',
'right',
'hide'
];
if(lastRowModes.indexOf(this.settings.lastRow)===-1){
throw 'lastRow must be one of: ' + lastRowModes.join(', ');
}
this.checkOrConvertNumber(this.settings, 'justifyThreshold');
if(this.settings.justifyThreshold < 0||this.settings.justifyThreshold > 1){
throw 'justifyThreshold must be in the interval [0,1]';
}
if(typeof(this.settings.cssAnimation)!=='boolean'){
throw 'cssAnimation must be a boolean';
}
if(typeof(this.settings.captions)!=='boolean') throw 'captions must be a boolean';
this.checkOrConvertNumber(this.settings.captionSettings, 'animationDuration');
this.checkOrConvertNumber(this.settings.captionSettings, 'visibleOpacity');
if(this.settings.captionSettings.visibleOpacity < 0 ||
this.settings.captionSettings.visibleOpacity > 1){
throw 'captionSettings.visibleOpacity must be in the interval [0, 1]';
}
this.checkOrConvertNumber(this.settings.captionSettings, 'nonVisibleOpacity');
if(this.settings.captionSettings.nonVisibleOpacity < 0 ||
this.settings.captionSettings.nonVisibleOpacity > 1){
throw 'captionSettings.nonVisibleOpacity must be in the interval [0, 1]';
}
this.checkOrConvertNumber(this.settings, 'imagesAnimationDuration');
this.checkOrConvertNumber(this.settings, 'refreshTime');
this.checkOrConvertNumber(this.settings, 'refreshSensitivity');
if(typeof(this.settings.randomize)!=='boolean') throw 'randomize must be a boolean';
if(typeof(this.settings.selector)!=='string') throw 'selector must be a string';
if(this.settings.sort!==false&&typeof(this.settings.sort)!=="function"){
throw 'sort must be false or a comparison function';
}
if(this.settings.filter!==false&&typeof(this.settings.filter)!=="function" &&
typeof(this.settings.filter)!=='string'){
throw 'filter must be false, a string or a filter function';
}};
JustifiedGallery.prototype.retrieveSuffixRanges=function (){
var suffixRanges=[];
for (var rangeIdx in this.settings.sizeRangeSuffixes){
if(this.settings.sizeRangeSuffixes.hasOwnProperty(rangeIdx)) suffixRanges.push(parseInt(rangeIdx, 10));
}
suffixRanges.sort(function (a, b){ return a > b ? 1:a < b ? -1:0; });
return suffixRanges;
};
JustifiedGallery.prototype.updateSettings=function (newSettings){
this.settings=$.extend({}, this.settings, newSettings);
this.checkSettings();
this.border=this.settings.border >=0 ? this.settings.border:this.settings.margins;
this.maxRowHeight=this.retrieveMaxRowHeight();
this.suffixRanges=this.retrieveSuffixRanges();
};
JustifiedGallery.prototype.defaults={
sizeRangeSuffixes: {}, 
thumbnailPath: undefined, 
rowHeight: 120,
maxRowHeight: false,
maxRowsCount: 0,
margins: 1,
border: -1,
lastRow: 'nojustify',
justifyThreshold: 0.90, 
waitThumbnailsLoad: true,
captions: true,
cssAnimation: true,
imagesAnimationDuration: 500,
captionSettings: {
animationDuration: 500,
visibleOpacity: 0.7,
nonVisibleOpacity: 0.0
},
rel: null,
target: null,
extension: /\.[^.\\/]+$/,
refreshTime: 200,
refreshSensitivity: 0,
randomize: false,
rtl: false,
sort: false, 
filter: false, 
selector: 'a',
imgSelector: '> img, > a > img, > svg, > a > svg',
triggerEvent: function (event){
this.$gallery.trigger(event);
}};
$.fn.justifiedGallery=function (arg){
return this.each(function (index, gallery){
var $gallery=$(gallery);
$gallery.addClass('justified-gallery');
var controller=$gallery.data('jg.controller');
if(typeof controller==='undefined'){
if(typeof arg!=='undefined'&&arg!==null&&typeof(arg)!=='object'){
if(arg==='destroy') return;
throw 'The argument must be an object';
}
controller=new JustifiedGallery($gallery, $.extend({}, JustifiedGallery.prototype.defaults, arg));
$gallery.data('jg.controller', controller);
}else if(arg==='norewind'){
}else if(arg==='destroy'){
controller.destroy();
return;
}else{
controller.updateSettings(arg);
controller.rewind();
}
if(!controller.updateEntries(arg==='norewind')) return;
controller.init();
});
};}));
;(function (factory){
if(typeof define==='function'&&define.amd){
define(['jquery'], factory);
}else if(typeof exports==='object'){
module.exports=factory(require('jquery'));
}else{
factory(jQuery);
}}(function ($){
var eventNamespace='waitForImages';
var hasSrcset=(function(img){
return img.srcset&&img.sizes;
})(new Image());
$.waitForImages={
hasImageProperties: [
'backgroundImage',
'listStyleImage',
'borderImage',
'borderCornerImage',
'cursor'
],
hasImageAttributes: ['srcset']
};
$.expr.pseudos['has-src']=function (obj){
return $(obj).is('img[src][src!=""]');
};
$.expr.pseudos.uncached=function (obj){
if(!$(obj).is(':has-src')){
return false;
}
return !obj.complete;
};
$.fn.waitForImages=function (){
var allImgsLength=0;
var allImgsLoaded=0;
var deferred=$.Deferred();
var originalCollection=this;
var allImgs=[];
var hasImgProperties=$.waitForImages.hasImageProperties||[];
var hasImageAttributes=$.waitForImages.hasImageAttributes||[];
var matchUrl=/url\(\s*(['"]?)(.*?)\1\s*\)/g;
var finishedCallback;
var eachCallback;
var waitForAll;
if($.isPlainObject(arguments[0])){
waitForAll=arguments[0].waitForAll;
eachCallback=arguments[0].each;
finishedCallback=arguments[0].finished;
}else{
if(arguments.length===1&&typeof(arguments[0])==='boolean'){
waitForAll=arguments[0];
}else{
finishedCallback=arguments[0];
eachCallback=arguments[1];
waitForAll=arguments[2];
}}
finishedCallback=finishedCallback||$.noop;
eachCallback=eachCallback||$.noop;
waitForAll = !! waitForAll;
if(typeof(finishedCallback)!=="function"||typeof(eachCallback)!=="function"){
throw new TypeError('An invalid callback was supplied.');
}
this.each(function (){
var obj=$(this);
if(waitForAll){
obj.find('*').addBack().each(function (){
var element=$(this);
if(element.is('img:has-src') &&
!element.is('[srcset]')){
allImgs.push({
src: element.attr('src'),
element: element[0]
});
}
$.each(hasImgProperties, function (i, property){
var propertyValue=element.css(property);
var match;
if(!propertyValue){
return true;
}
while (match=matchUrl.exec(propertyValue)){
allImgs.push({
src: match[2],
element: element[0]
});
}});
$.each(hasImageAttributes, function (i, attribute){
var attributeValue=element.attr(attribute);
var attributeValues;
if(!attributeValue){
return true;
}
allImgs.push({
src: element.attr('src'),
srcset: element.attr('srcset'),
element: element[0]
});
});
});
}else{
obj.find('img:has-src')
.each(function (){
allImgs.push({
src: this.src,
element: this
});
});
}});
allImgsLength=allImgs.length;
allImgsLoaded=0;
if(allImgsLength===0){
finishedCallback.call(originalCollection);
deferred.resolveWith(originalCollection);
}
$.each(allImgs, function (i, img){
var image=new Image();
var events =
'load.' + eventNamespace + ' error.' + eventNamespace;
$(image).one(events, function me (event){
var eachArguments=[
allImgsLoaded,
allImgsLength,
event.type=='load'
];
allImgsLoaded++;
eachCallback.apply(img.element, eachArguments);
deferred.notifyWith(img.element, eachArguments);
$(this).off(events, me);
if(allImgsLoaded==allImgsLength){
finishedCallback.call(originalCollection[0]);
deferred.resolveWith(originalCollection[0]);
return false;
}});
if(hasSrcset&&img.srcset){
image.srcset=img.srcset;
image.sizes=img.sizes;
}
image.src=img.src;
});
return deferred.promise();
};}));
var ngg_mosaic_methods={
high_dpi: false,
init: function(){
this.high_dpi=this.getDPIRatio() > 1;
_.each(document.getElementsByClassName('ngg-pro-mosaic-container'), function(self){
var gallery_id=self.getAttribute('data-ngg-pro-mosaic-id');
var gallery=ngg_mosaic_methods.get_gallery(gallery_id);
const container=self.parentElement;
const styleName='firstload';
if(ngg_mosaic_methods.get_setting(gallery_id, 'lazy_load_enable', false, 'bool')){
var initial_load=ngg_mosaic_methods.get_setting(gallery.ID, 'lazy_load_initial', 35, 'int');
gallery.mosaic_loaded=[];
_.each(gallery.images_list,
function(image, index){
if(index < initial_load){
gallery.mosaic_loaded.push(image.image_id);
self.appendChild(ngg_mosaic_methods.create_image(gallery,
image,
undefined,
'1'===self.parentElement.dataset['firstloadEnabled']
));
}}
);
}else{
_.each(gallery.images_list,
function(image){
self.appendChild(ngg_mosaic_methods.create_image(gallery,
image,
undefined,
'1'===self.parentElement.dataset['firstloadEnabled']
));
}
);
}
if('1'===container.dataset[`${styleName}Enabled`]){
const style=container.dataset[`${styleName}Style`];
const duration=parseInt(container.dataset[`${styleName}Duration`]);
const delay=parseInt(container.dataset[`${styleName}Delay`]);
const items=self.querySelectorAll('.ngg-pro-mosaic-item');
items.forEach(function(image, index){
image.style.setProperty('--animate-duration', `${duration}ms`);
if(index===(items.length - 1)){
setTimeout(()=> {
animateNextGENImage(image, style).then((message)=> {
if(ngg_mosaic_methods.get_setting(gallery_id, 'lazy_load_enable', false, 'bool')){
jQuery(window).on('scroll', function(){
window.ngg_mosaic_methods_two.scroll_action(gallery.ID, self);
});
jQuery(window).trigger('scroll');
}
return "Message received";
});
}, (0===index ? 0:index * delay));
}else{
setTimeout(()=> {
animateNextGENImage(image, style);
}, (0===index ? 0:index * delay));
}}
);
}else{
if('1'===container.dataset['paginationEnabled']){
if(ngg_mosaic_methods.get_setting(gallery_id, 'lazy_load_enable', false, 'bool')){
jQuery(window).on('scroll', function(){
window.ngg_mosaic_methods_two.scroll_action(gallery.ID, self);
});
jQuery(window).trigger('scroll');
}}
}});
},
getDPIRatio: function(){
var ratio=1;
if(window.screen.systemXDPI!==undefined
&&  window.screen.logicalXDPI!==undefined
&&  window.screen.systemXDPI > window.screen.logicalXDPI){
ratio=window.screen.systemXDPI / window.screen.logicalXDPI;
}else if(window.devicePixelRatio!==undefined){
ratio=window.devicePixelRatio;
}
return ratio;
},
get_gallery: function (gallery_id){
var result=null;
if('undefined'==typeof window.galleries){
return result;
}
return _.find(galleries, function(gallery){
return (gallery.ID==gallery_id);
});
},
get_setting: function(gallery_id, name, def, type){
type=type||'bool';
var gallery=this.get_gallery(gallery_id);
if(gallery&&typeof gallery.display_settings[name]!='undefined')
def=gallery.display_settings[name];
if(type=='bool'){
if(def==1||def=='1')
def=true;
if(def==0||def=='0')
def=false;
}else if(type=='int'){
def=parseInt(def);
}else if(type=='string'){
}
return def;
},
create_image: function(gallery, image, onload, addAnimationClass){
var self=this;
var div=document.createElement('div');
div.setAttribute('class', 'ngg-pro-mosaic-item');
if(addAnimationClass){
div.classList.add('nextgen-pro-animate-images-loading');
}
var img=document.createElement('img');
var url=image.image;
if(self.high_dpi&&image.use_hdpi){
url=image.srcsets.hdpi;
}
img.setAttribute('title', image.title);
img.setAttribute('alt',   image.title);
img.setAttribute('src',   url);
img.setAttribute('width', image.width);
img.setAttribute('height', image.height);
var anchor=document.createElement('a');
var clauses=gallery.mosaic_effect_code.match(/(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/ig);
if(clauses){
for (var i=0; i < clauses.length; i++){
var claus=clauses[i].match(/(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/i);
anchor.setAttribute(claus[1], claus[2]);
}}
anchor.setAttribute('href',             image.full_image);
anchor.setAttribute('title',            image.description);
anchor.setAttribute('data-image-id',    image.image_id);
anchor.setAttribute('data-src',         image.image);
anchor.setAttribute('data-thumbnail',   image.thumb);
anchor.setAttribute('data-title',       image.title);
anchor.setAttribute('data-description', image.description);
anchor.setAttribute('data-ngg-captions-nostylecopy', '1');
if(typeof onload!='undefined'){
anchor.setAttribute('onload', onload);
}
anchor.appendChild(img);
div.appendChild(anchor);
return div;
}};
(function($){
"use strict";
var mosaic_methods={
image_loaded: function(image_id){
this.scroll_pending=_.without(this.scroll_pending, image_id);
},
scroll_action_running: null,
scroll_timer: null,
scroll_step: 5,
scroll_pending: [],
scroll_more_to_find: true,
scroll_action: function(gallery_id, myself){
if(this.scroll_action_running==true
||  this.scroll_timer
||  !this.scroll_more_to_find
||  (this.scroll_pending.length >=1)){
return;
}
this.scroll_action_running=true;
var self=this;
this.scroll_timer=setTimeout(function(){
clearTimeout(self.scroll_timer);
self.scroll_timer=false;
}, 500);
setTimeout(function(){
var $self=$(myself);
var window_height=$(window).height();
var window_position=$(window).scrollTop();
var window_bottom=window_height + window_position;
var container_bottom=$self.height() + $self.offset().top;
var row_height=$self.find('.ngg-pro-mosaic-item.entry-visible').first().height();
var last_height=$self.find('.ngg-pro-mosaic-item.entry-visible').last().height();
if(window_bottom <=(container_bottom - last_height - (row_height * 2))){
self.scroll_action_running=false;
return;
}
var gallery=ngg_mosaic_methods.get_gallery(gallery_id);
var scroll_step=ngg_mosaic_methods.get_setting(gallery_id, 'lazy_load_batch', this.scroll_step, 'int');
if((gallery.images_list.length - gallery.mosaic_loaded.length) < scroll_step){
scroll_step=gallery.images_list.length - gallery.mosaic_loaded.length;
self.scroll_more_to_find=false;
}
let newImages=[];
const container=myself.parentElement;
const styleName='pagination';
for (var i=0; i < scroll_step; i++){
var image=_.find(gallery.images_list, function(image){
return (_.indexOf(gallery.mosaic_loaded, image.image_id)==-1)
});
gallery.mosaic_loaded.push(image.image_id);
let newImage=ngg_mosaic_methods.create_image(gallery,
image,
self.image_loaded(image.image_id),
'1'===container.dataset[`${styleName}Enabled`]
);
newImages.push(newImage);
$self.append(newImage);
}
$self.justifiedGallery('norewind');
if('1'===container.dataset[`${styleName}Enabled`]){
const style=container.dataset[`${styleName}Style`];
const duration=parseInt(container.dataset[`${styleName}Duration`]);
const delay=parseInt(container.dataset[`${styleName}Delay`]);
newImages.forEach(function(image, index){
image.style.setProperty('--animate-duration', `${duration}ms`);
setTimeout(()=> {
animateNextGENImage(image, style);
}, (0===index ? 0:index * delay));
}
);
}
self.scroll_action_running=false;
}, 60);
}};
window.ngg_mosaic_methods_two=mosaic_methods;
ngg_mosaic_methods.init();
_.each($('.ngg-pro-mosaic-container'), function(self){
var $self=$(self);
var gallery_id=$self.data('ngg-pro-mosaic-id');
var jgoptions={
captions: false,
cssAnimation: true,
waitThumbnailsLoad: false,
justifyThreshold: 0.9,
rowHeight: ngg_mosaic_methods.get_setting(gallery_id, 'row_height', 200, 'int'),
margins:   ngg_mosaic_methods.get_setting(gallery_id, 'margins',    15,  'int'),
lastRow:   ngg_mosaic_methods.get_setting(gallery_id, 'last_row',   'justify', 'string')
};
var gallery=ngg_mosaic_methods.get_gallery(gallery_id);
$self.css({
'min-height': ngg_mosaic_methods.get_setting(gallery_id, 'row_height', 200, 'int') + 'px'
});
if('undefined'===typeof self.parentElement.dataset['paginationEnabled']
||  '0'===self.parentElement.dataset['paginationEnabled']){
if(ngg_mosaic_methods.get_setting(gallery_id, 'lazy_load_enable', false, 'bool')){
$(window).on('scroll', function(){
mosaic_methods.scroll_action(gallery.ID, self);
});
}}
$self.on('jg.complete', function(){
$(window).trigger('ngg.mosaic.complete', [$self]);
$(window).trigger('resize', [$self]);
$self.waitForImages(function(){
$(window).trigger('refreshed');
});
});
$self.justifiedGallery(jgoptions);
$(window).on('npl_initialization_complete', function(){
$('#npl_content').on('npl_opening', function(){
$self.justifiedGallery('disableRefresh');
});
$('#npl_content').on('npl_closing', function(){
$self.justifiedGallery('enableRefresh');
});
});
});
})(jQuery);