diff --git a/README.md b/README.md index 6a2029df6..3e562adee 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,16 @@ https://www.youtube.com/watch?v=dJrykKQGDcs ## Changelog ## +### 4.7.2 + +* FIXED + * Fixed GoDAM Player rendering issue on Multisite. + * Fixed GoDAM Player Skins not loading on Multisite. + +* ENHANCEMENTS + * Better handling of rtMedia Notifications. + * Updated jQuery Deprecated Methods. + ### 4.7.1 * FIXED diff --git a/app/admin/templates/notices/transcoder.php b/app/admin/templates/notices/transcoder.php index 3afab50a7..0706fff23 100644 --- a/app/admin/templates/notices/transcoder.php +++ b/app/admin/templates/notices/transcoder.php @@ -5,6 +5,21 @@ * @package rtMedia */ +// Include plugin.php if not already loaded. +if ( ! function_exists( 'is_plugin_active' ) ) { + include_once ABSPATH . 'wp-admin/includes/plugin.php'; +} + +// If GoDAM is active right now, set a permanent flag. +if ( is_plugin_active( 'godam/godam.php' ) ) { + update_option( 'godam_plugin_activated_once', true ); +} + +// If the permanent flag is set, never show the notice. +if ( get_option( 'godam_plugin_activated_once' ) ) { + return; +} + ?>
diff --git a/app/assets/js/godam-ajax-refresh.js b/app/assets/js/godam-ajax-refresh.js index 52ddada66..627157ce8 100644 --- a/app/assets/js/godam-ajax-refresh.js +++ b/app/assets/js/godam-ajax-refresh.js @@ -1,275 +1,279 @@ -// Enhanced AJAX function with better error handling and retry logic -function refreshSingleComment(commentId, node) { - // Validation checks - if (!commentId || !node) { - return; +/** + * Enhanced AJAX Comment Refresh - GODAM Player Integration + * + * Ensures GODAM player loads properly for comment replies in multisite setups + */ +class CommentRefreshManager { + constructor() { + // Track comments being refreshed (avoid duplicates) + this.refreshingComments = new Set(); + + // Track retry counts for failed requests + this.retryAttempts = new Map(); + + // Max number of retry attempts before giving up + this.maxRetries = 3; + + // How long to wait for GODAMPlayer availability (ms) + this.godamCheckTimeout = 200; } - // Check if GodamAjax object exists - if (typeof GodamAjax === 'undefined' || !GodamAjax.ajax_url || !GodamAjax.nonce) { - return; - } + // Wait until GODAMPlayer is available and functional + waitForGODAMPlayer(timeout = this.godamCheckTimeout) { + return new Promise((resolve) => { + const startTime = Date.now(); + + const checkPlayer = () => { + if (typeof GODAMPlayer === 'function') { + try { + // Create a test element to confirm GODAMPlayer actually works + const testDiv = document.createElement('div'); + testDiv.innerHTML = ''; + document.body.appendChild(testDiv); + GODAMPlayer(testDiv); + document.body.removeChild(testDiv); + resolve(true); + return; + } catch {} + } + + // Timeout reached -> not available + if (Date.now() - startTime > timeout) { + resolve(false); + return; + } + + // Retry check + setTimeout(checkPlayer, 100); + }; - // Check if node is still in the DOM - if (!document.contains(node)) { - return; + checkPlayer(); + }); } - // Prevent duplicate requests - if (node.classList.contains('refreshing')) { - return; + // Ensure request is valid before sending AJAX + validateRequest(commentId, node) { + if (!commentId || !node) return false; + if (typeof GodamAjax === 'undefined' || !GodamAjax.ajax_url || !GodamAjax.nonce) return false; + if (!document.contains(node)) return false; + if (this.refreshingComments.has(commentId)) return false; + return true; } - node.classList.add('refreshing'); - - // Create AbortController for timeout handling - const controller = new AbortController(); - const timeoutId = setTimeout(() => { - controller.abort(); - }, 15000); // 15 second timeout - - fetch(GodamAjax.ajax_url, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - body: new URLSearchParams({ - action: 'get_single_activity_comment_html', - comment_id: commentId, - nonce: GodamAjax.nonce, - }), - signal: controller.signal - }) - .then(response => { - clearTimeout(timeoutId); - - // Check if response is ok - if (!response.ok) { - throw new Error(`HTTP ${response.status}: ${response.statusText}`); - } - // Check content type - const contentType = response.headers.get('content-type'); - if (!contentType || !contentType.includes('application/json')) { - throw new Error('Server returned non-JSON response'); - } + // Initialize GODAM player for comment replies + async initializeGODAMPlayerForReply(node, commentId) { + const isGODAMReady = await this.waitForGODAMPlayer(); + if (!isGODAMReady) return false; - return response.json(); - }) - .then(data => { - if (data && data.success && data.data && data.data.html) { - // Success - handle the response - handleSuccessfulResponse(data, commentId, node); - } else { - // AJAX returned error - const errorMsg = data && data.data ? data.data : 'Unknown AJAX error'; - console.error('AJAX error:', errorMsg); - - // Optional: Retry once after a delay - setTimeout(() => { - retryRefreshComment(commentId, node, 1); - }, 2000); - } - }) - .catch(error => { - clearTimeout(timeoutId); - console.error('Fetch error:', error); - - // Handle specific error types - if (error.name === 'AbortError') { - console.error('Request timed out'); - } else if (error.message.includes('Failed to fetch')) { - console.error('Network error - possible connectivity issue'); - // Retry after network error - setTimeout(() => { - retryRefreshComment(commentId, node, 1); - }, 3000); - } - }) - .finally(() => { - clearTimeout(timeoutId); - // Always remove refreshing class - if (document.contains(node)) { - node.classList.remove('refreshing'); - } - }); -} + const videos = node.querySelectorAll('video'); + const videoContainers = node.querySelectorAll('.easydam-video-container'); -// Retry function with exponential backoff -function retryRefreshComment(commentId, node, attempt = 1) { - const maxRetries = 2; + // If no media, no need to init player + if (videos.length === 0 && videoContainers.length === 0) return true; - if (attempt > maxRetries) { - console.error(`Failed to refresh comment ${commentId} after ${maxRetries} retries`); - return; - } + node.setAttribute('data-godam-reply-processing', 'true'); - // Check if node still exists - if (!document.contains(node)) { - return; - } - - // Exponential backoff delay - const delay = Math.pow(2, attempt) * 1000; // 2s, 4s, 8s... - - setTimeout(() => { - // Remove any existing refreshing class - node.classList.remove('refreshing'); - - // Try again with modified fetch (more conservative approach) - fetch(GodamAjax.ajax_url, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Cache-Control': 'no-cache', - }, - body: new URLSearchParams({ - action: 'get_single_activity_comment_html', - comment_id: commentId, - nonce: GodamAjax.nonce, - retry: attempt.toString() - }), - }) - .then(response => response.json()) - .then(data => { - if (data && data.success && data.data && data.data.html) { - handleSuccessfulResponse(data, commentId, node); - } else { - // Retry again if not max attempts - if (attempt < maxRetries) { - retryRefreshComment(commentId, node, attempt + 1); - } + // Try initializing directly on node + try { + GODAMPlayer(node); + } catch { + // Fallback: try initializing each container individually + for (const container of videoContainers) { + try { GODAMPlayer(container); } catch {} } - }) - .catch(error => { - console.error(`Retry ${attempt} failed:`, error); - if (attempt < maxRetries) { - retryRefreshComment(commentId, node, attempt + 1); + for (const video of videos) { + try { + const videoContainer = video.closest('.easydam-video-container') || video.parentElement; + GODAMPlayer(videoContainer); + } catch {} } - }); - }, delay); -} + } + + // Global re-init (for skins, multiple players, etc.) + try { GODAMPlayer(); } catch {} + + node.removeAttribute('data-godam-reply-processing'); + node.setAttribute('data-godam-reply-initialized', 'true'); + + // Remove loading animation once ready + setTimeout(() => { + node.querySelectorAll('.animate-video-loading') + .forEach(el => el.classList.remove('animate-video-loading')); + }, 300); + + return true; + } -// Handle successful AJAX response -function handleSuccessfulResponse(data, commentId, node) { - try { - // Find parent activity more safely + // Handle successful AJAX response -> replace comment HTML + re-init player + async handleSuccessfulResponse(data, commentId, node) { const activityItem = node.closest('.activity-item'); - if (!activityItem) { - console.error('Could not find parent activity item'); - return; - } + if (!activityItem) return; + // Ensure the parent has a comments container const parentActivityId = activityItem.id.replace('activity-', ''); - - // Locate comment container let commentList = document.querySelector(`#activity-${parentActivityId} .activity-comments`); + if (!commentList) { commentList = document.createElement('ul'); commentList.classList.add('activity-comments'); activityItem.appendChild(commentList); } - // Create temporary container for HTML parsing + // Parse returned comment HTML const tempDiv = document.createElement('div'); tempDiv.innerHTML = data.data.html.trim(); const newCommentNode = tempDiv.firstElementChild; + if (!newCommentNode) return; - if (newCommentNode) { - // Insert new comment - commentList.appendChild(newCommentNode); + // Replace old node with refreshed one + node.replaceWith(newCommentNode); - // Remove old node safely - if (node.parentNode && document.contains(node)) { - node.parentNode.removeChild(node); - } - - // Initialize GODAMPlayer if available - if (typeof GODAMPlayer === 'function') { - try { - GODAMPlayer(newCommentNode); - } catch (playerError) { - console.error('GODAMPlayer initialization failed:', playerError); - } - } + // Try initializing GODAMPlayer (up to 3 attempts with backoff) + let initSuccess = false; + for (let attempt = 1; attempt <= 3; attempt++) { + await new Promise(resolve => setTimeout(resolve, attempt * 100)); + initSuccess = await this.initializeGODAMPlayerForReply(newCommentNode, commentId); + if (initSuccess) break; + } - // Dispatch custom event for other scripts + // Dispatch custom event so other scripts can hook into comment refresh + setTimeout(() => { document.dispatchEvent(new CustomEvent('commentRefreshed', { - detail: { commentId, node: newCommentNode } + detail: { commentId, node: newCommentNode, playerReady: initSuccess, isReply: true }, + bubbles: true })); + }, 200); + } - } else { - console.error('No valid comment node found in response HTML'); + // Refresh a single comment via AJAX + async refreshSingleComment(commentId, node) { + if (!this.validateRequest(commentId, node)) return; + + this.refreshingComments.add(commentId); + node.classList.add('refreshing'); + + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 15000); // 15s max wait + + try { + const response = await fetch(GodamAjax.ajax_url, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + action: 'get_single_activity_comment_html', + comment_id: commentId, + nonce: GodamAjax.nonce, + }), + signal: controller.signal + }); + + clearTimeout(timeoutId); + if (!response.ok) throw new Error(); + + const data = await response.json(); + + // If successful, process and replace comment + if (data && data.success && data.data && data.data.html) { + await this.handleSuccessfulResponse(data, commentId, node); + } else { + this.scheduleRetry(commentId, node); + } + } catch { + clearTimeout(timeoutId); + this.scheduleRetry(commentId, node); + } finally { + clearTimeout(timeoutId); + this.refreshingComments.delete(commentId); + if (document.contains(node)) node.classList.remove('refreshing'); } - } catch (error) { - console.error('Error handling successful response:', error); } -} -// Enhanced DOM observer with debouncing -document.addEventListener('DOMContentLoaded', () => { - const commentsContainers = document.querySelectorAll('.activity-comments'); + // Retry failed refresh with exponential backoff + scheduleRetry(commentId, node) { + const attempts = this.retryAttempts.get(commentId) || 0; + if (attempts >= this.maxRetries) return; + + const delay = Math.pow(2, attempts) * 1000; // 1s, 2s, 4s... + this.retryAttempts.set(commentId, attempts + 1); - if (commentsContainers.length === 0) { - return; + setTimeout(() => { + if (document.contains(node)) this.refreshSingleComment(commentId, node); + }, delay); } - // Debounce function to prevent rapid-fire calls - function debounce(func, wait) { + // Initialize GODAMPlayer for comments already on the page + async initializeExistingComments() { + const existingComments = document.querySelectorAll('li[id^="acomment-"]'); + for (const comment of existingComments) { + const commentId = comment.id.replace('acomment-', ''); + await this.initializeGODAMPlayerForReply(comment, commentId); + } + } + + // Entry point + initialize() { + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', () => this.setupSystem()); + } else { + this.setupSystem(); + } + } + + // System setup: init existing + observe for new ones + async setupSystem() { + await this.initializeExistingComments(); + this.setupMutationObservers(); + } + + // Simple debounce utility + debounce(func, wait) { let timeout; - return function executedFunction(...args) { - const later = () => { - clearTimeout(timeout); - func(...args); - }; + return function (...args) { clearTimeout(timeout); - timeout = setTimeout(later, wait); + timeout = setTimeout(() => func(...args), wait); }; } - commentsContainers.forEach((container) => { - // Initialize GODAMPlayer on existing comments - if (typeof GODAMPlayer === 'function') { - try { - GODAMPlayer(container); - } catch (error) { - console.error('GODAMPlayer initialization failed:', error); - } + // Watch for new comments being added to DOM + setupMutationObservers() { + const commentsContainers = document.querySelectorAll('.activity-comments'); + const debouncedHandler = this.debounce((mutations) => { + this.handleNewComments(mutations); + }, 200); + + // If no containers yet, observe entire body + if (commentsContainers.length === 0) { + const bodyObserver = new MutationObserver(debouncedHandler); + bodyObserver.observe(document.body, { childList: true, subtree: true }); + return; } - // Debounced mutation handler - const debouncedHandler = debounce((mutations) => { - mutations.forEach((mutation) => { - mutation.addedNodes.forEach((node) => { - if (node.nodeType === 1 && node.matches && node.matches('li[id^="acomment-"]')) { - // Initialize GODAMPlayer first - if (typeof GODAMPlayer === 'function') { - try { - GODAMPlayer(node); - } catch (error) { - console.error('GODAMPlayer initialization failed:', error); - } - } - - // Extract comment ID and refresh with delay - const commentId = node.id.replace('acomment-', ''); - - // Add longer delay to ensure DOM stability - setTimeout(() => { - if (document.contains(node)) { - refreshSingleComment(commentId, node); - } - }, 250); - } - }); - }); - }, 100); // 100ms debounce + // Otherwise, attach observers to each comments container + commentsContainers.forEach((container) => { + const observer = new MutationObserver(debouncedHandler); + observer.observe(container, { childList: true, subtree: true }); + }); + } - // Create observer - const observer = new MutationObserver(debouncedHandler); + // Handle new comments inserted into DOM + async handleNewComments(mutations) { + for (const mutation of mutations) { + for (const node of mutation.addedNodes) { + if (node.nodeType === 1 && node.matches('li[id^="acomment-"]')) { + const commentId = node.id.replace('acomment-', ''); + setTimeout(async () => { + if (document.contains(node)) { + await this.initializeGODAMPlayerForReply(node, commentId); + await this.refreshSingleComment(commentId, node); + } + }, 200); + } + } + } + } +} - observer.observe(container, { - childList: true, - subtree: true - }); - }); -}); +// Initialize system +const commentRefreshManager = new CommentRefreshManager(); +commentRefreshManager.initialize(); +window.CommentRefreshManager = commentRefreshManager; diff --git a/app/assets/js/godam-ajax-refresh.min.js b/app/assets/js/godam-ajax-refresh.min.js index 25ba334bc..886addaca 100644 --- a/app/assets/js/godam-ajax-refresh.min.js +++ b/app/assets/js/godam-ajax-refresh.min.js @@ -1 +1 @@ -function refreshSingleComment(e,t){if(!e||!t)return;if("undefined"==typeof GodamAjax||!GodamAjax.ajax_url||!GodamAjax.nonce)return;if(!document.contains(t))return;if(t.classList.contains("refreshing"))return;t.classList.add("refreshing");const o=new AbortController,n=setTimeout((()=>{o.abort()}),15e3);fetch(GodamAjax.ajax_url,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({action:"get_single_activity_comment_html",comment_id:e,nonce:GodamAjax.nonce}),signal:o.signal}).then((e=>{if(clearTimeout(n),!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const t=e.headers.get("content-type");if(!t||!t.includes("application/json"))throw new Error("Server returned non-JSON response");return e.json()})).then((o=>{if(o&&o.success&&o.data&&o.data.html)handleSuccessfulResponse(o,e,t);else{const n=o&&o.data?o.data:"Unknown AJAX error";console.error("AJAX error:",n),setTimeout((()=>{retryRefreshComment(e,t,1)}),2e3)}})).catch((o=>{clearTimeout(n),console.error("Fetch error:",o),"AbortError"===o.name?console.error("Request timed out"):o.message.includes("Failed to fetch")&&(console.error("Network error - possible connectivity issue"),setTimeout((()=>{retryRefreshComment(e,t,1)}),3e3))})).finally((()=>{clearTimeout(n),document.contains(t)&&t.classList.remove("refreshing")}))}function retryRefreshComment(e,t,o=1){if(o>2)return void console.error(`Failed to refresh comment ${e} after 2 retries`);if(!document.contains(t))return;const n=1e3*Math.pow(2,o);setTimeout((()=>{t.classList.remove("refreshing"),fetch(GodamAjax.ajax_url,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"},body:new URLSearchParams({action:"get_single_activity_comment_html",comment_id:e,nonce:GodamAjax.nonce,retry:o.toString()})}).then((e=>e.json())).then((n=>{n&&n.success&&n.data&&n.data.html?handleSuccessfulResponse(n,e,t):o<2&&retryRefreshComment(e,t,o+1)})).catch((n=>{console.error(`Retry ${o} failed:`,n),o<2&&retryRefreshComment(e,t,o+1)}))}),n)}function handleSuccessfulResponse(e,t,o){try{const n=o.closest(".activity-item");if(!n)return void console.error("Could not find parent activity item");const r=n.id.replace("activity-","");let a=document.querySelector(`#activity-${r} .activity-comments`);a||(a=document.createElement("ul"),a.classList.add("activity-comments"),n.appendChild(a));const c=document.createElement("div");c.innerHTML=e.data.html.trim();const i=c.firstElementChild;if(i){if(a.appendChild(i),o.parentNode&&document.contains(o)&&o.parentNode.removeChild(o),"function"==typeof GODAMPlayer)try{GODAMPlayer(i)}catch(e){console.error("GODAMPlayer initialization failed:",e)}document.dispatchEvent(new CustomEvent("commentRefreshed",{detail:{commentId:t,node:i}}))}else console.error("No valid comment node found in response HTML")}catch(e){console.error("Error handling successful response:",e)}}document.addEventListener("DOMContentLoaded",(()=>{const e=document.querySelectorAll(".activity-comments");0!==e.length&&e.forEach((e=>{if("function"==typeof GODAMPlayer)try{GODAMPlayer(e)}catch(e){console.error("GODAMPlayer initialization failed:",e)}const t=function(e,t){let o;return function(...n){clearTimeout(o),o=setTimeout((()=>{clearTimeout(o),e(...n)}),t)}}((e=>{e.forEach((e=>{e.addedNodes.forEach((e=>{if(1===e.nodeType&&e.matches&&e.matches('li[id^="acomment-"]')){if("function"==typeof GODAMPlayer)try{GODAMPlayer(e)}catch(e){console.error("GODAMPlayer initialization failed:",e)}const t=e.id.replace("acomment-","");setTimeout((()=>{document.contains(e)&&refreshSingleComment(t,e)}),250)}}))}))}),100);new MutationObserver(t).observe(e,{childList:!0,subtree:!0})}))})); \ No newline at end of file +class CommentRefreshManager{constructor(){this.refreshingComments=new Set,this.retryAttempts=new Map,this.maxRetries=3,this.godamCheckTimeout=200}waitForGODAMPlayer(e=this.godamCheckTimeout){return new Promise((t=>{const i=Date.now(),n=()=>{if("function"==typeof GODAMPlayer)try{const e=document.createElement("div");return e.innerHTML="",document.body.appendChild(e),GODAMPlayer(e),document.body.removeChild(e),void t(!0)}catch{}Date.now()-i>e?t(!1):setTimeout(n,100)};n()}))}validateRequest(e,t){return!(!e||!t)&&(!("undefined"==typeof GodamAjax||!GodamAjax.ajax_url||!GodamAjax.nonce)&&(!!document.contains(t)&&!this.refreshingComments.has(e)))}async initializeGODAMPlayerForReply(e,t){if(!await this.waitForGODAMPlayer())return!1;const i=e.querySelectorAll("video"),n=e.querySelectorAll(".easydam-video-container");if(0===i.length&&0===n.length)return!0;e.setAttribute("data-godam-reply-processing","true");try{GODAMPlayer(e)}catch{for(const e of n)try{GODAMPlayer(e)}catch{}for(const e of i)try{const t=e.closest(".easydam-video-container")||e.parentElement;GODAMPlayer(t)}catch{}}try{GODAMPlayer()}catch{}return e.removeAttribute("data-godam-reply-processing"),e.setAttribute("data-godam-reply-initialized","true"),setTimeout((()=>{e.querySelectorAll(".animate-video-loading").forEach((e=>e.classList.remove("animate-video-loading")))}),300),!0}async handleSuccessfulResponse(e,t,i){const n=i.closest(".activity-item");if(!n)return;const a=n.id.replace("activity-","");let o=document.querySelector(`#activity-${a} .activity-comments`);o||(o=document.createElement("ul"),o.classList.add("activity-comments"),n.appendChild(o));const s=document.createElement("div");s.innerHTML=e.data.html.trim();const r=s.firstElementChild;if(!r)return;i.replaceWith(r);let c=!1;for(let e=1;e<=3&&(await new Promise((t=>setTimeout(t,100*e))),c=await this.initializeGODAMPlayerForReply(r,t),!c);e++);setTimeout((()=>{document.dispatchEvent(new CustomEvent("commentRefreshed",{detail:{commentId:t,node:r,playerReady:c,isReply:!0},bubbles:!0}))}),200)}async refreshSingleComment(e,t){if(!this.validateRequest(e,t))return;this.refreshingComments.add(e),t.classList.add("refreshing");const i=new AbortController,n=setTimeout((()=>i.abort()),15e3);try{const a=await fetch(GodamAjax.ajax_url,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({action:"get_single_activity_comment_html",comment_id:e,nonce:GodamAjax.nonce}),signal:i.signal});if(clearTimeout(n),!a.ok)throw new Error;const o=await a.json();o&&o.success&&o.data&&o.data.html?await this.handleSuccessfulResponse(o,e,t):this.scheduleRetry(e,t)}catch{clearTimeout(n),this.scheduleRetry(e,t)}finally{clearTimeout(n),this.refreshingComments.delete(e),document.contains(t)&&t.classList.remove("refreshing")}}scheduleRetry(e,t){const i=this.retryAttempts.get(e)||0;if(i>=this.maxRetries)return;const n=1e3*Math.pow(2,i);this.retryAttempts.set(e,i+1),setTimeout((()=>{document.contains(t)&&this.refreshSingleComment(e,t)}),n)}async initializeExistingComments(){const e=document.querySelectorAll('li[id^="acomment-"]');for(const t of e){const e=t.id.replace("acomment-","");await this.initializeGODAMPlayerForReply(t,e)}}initialize(){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>this.setupSystem())):this.setupSystem()}async setupSystem(){await this.initializeExistingComments(),this.setupMutationObservers()}debounce(e,t){let i;return function(...n){clearTimeout(i),i=setTimeout((()=>e(...n)),t)}}setupMutationObservers(){const e=document.querySelectorAll(".activity-comments"),t=this.debounce((e=>{this.handleNewComments(e)}),200);if(0!==e.length)e.forEach((e=>{new MutationObserver(t).observe(e,{childList:!0,subtree:!0})}));else{new MutationObserver(t).observe(document.body,{childList:!0,subtree:!0})}}async handleNewComments(e){for(const t of e)for(const e of t.addedNodes)if(1===e.nodeType&&e.matches('li[id^="acomment-"]')){const t=e.id.replace("acomment-","");setTimeout((async()=>{document.contains(e)&&(await this.initializeGODAMPlayerForReply(e,t),await this.refreshSingleComment(t,e))}),200)}}}const commentRefreshManager=new CommentRefreshManager;commentRefreshManager.initialize(),window.CommentRefreshManager=commentRefreshManager; \ No newline at end of file diff --git a/app/assets/js/godam-integration.js b/app/assets/js/godam-integration.js index cb5299c4f..e81d8420c 100644 --- a/app/assets/js/godam-integration.js +++ b/app/assets/js/godam-integration.js @@ -1,88 +1,287 @@ /** * GODAMPlayer Integration Script * - * Initializes GODAMPlayer safely across the site, including: - * - Initial load + * Safely initializes GODAMPlayer across the site, including: + * - Initial load with retry mechanism * - Popups using Magnific Popup - * - Dynamically added elements (e.g., via BuddyPress activities) - * - * Ensures robust handling of null or invalid elements and minimizes the risk of runtime errors. + * - Dynamically added elements (BuddyPress activities, comments, replies) + * - Robust error handling and performance optimization */ -const safeGODAMPlayer = (element = null) => { +(function() { + 'use strict'; + + // Configuration + const CONFIG = { + DEBOUNCE_DELAY: 200, + RETRY_DELAY: 100, + MAX_RETRIES: 3, + INIT_DELAY: 1000, + POPUP_DELAY: 500 + }; + + // State tracking + let isInitialized = false; + + // Helper: Removes shimmer class from video containers (debounced) + const removeLoadingShimmer = (() => { + let timeoutId; + return () => { + clearTimeout(timeoutId); + timeoutId = setTimeout(() => { + try { + const videoContainers = document.querySelectorAll('.easydam-video-container.animate-video-loading'); + videoContainers.forEach(container => container.classList.remove('animate-video-loading')); + } catch (error) {} + }, CONFIG.DEBOUNCE_DELAY); + }; + })(); + + // Safe GODAMPlayer initialization with retry logic + const safeGODAMPlayer = (element = null, retryCount = 0) => { + if (typeof GODAMPlayer !== 'function') { + if (retryCount < CONFIG.MAX_RETRIES) { + setTimeout(() => safeGODAMPlayer(element, retryCount + 1), CONFIG.RETRY_DELAY * (retryCount + 1)); + } + return false; + } + try { - if (element) { - if (element.nodeType === 1 && element.isConnected) { - GODAMPlayer(element); - } else { - GODAMPlayer(); - } - } else { - GODAMPlayer(); - } - return true; + if (element && (element.nodeType !== 1 || !element.isConnected)) { + element = null; // fallback to global init + } + element ? GODAMPlayer(element) : GODAMPlayer(); + return true; } catch (error) { - return false; + if (retryCount < CONFIG.MAX_RETRIES) { + setTimeout(() => safeGODAMPlayer(element, retryCount + 1), CONFIG.RETRY_DELAY * (retryCount + 1)); + } + return false; } -}; + }; -// Initial load -safeGODAMPlayer(); - -// Debounced popup initializer -let popupInitTimeout = null; -const initializePopupVideos = () => { + // Initialize videos inside Magnific Popup + let popupInitTimeout = null; + const initializePopupVideos = () => { clearTimeout(popupInitTimeout); popupInitTimeout = setTimeout(() => { + try { const popupContent = document.querySelector('.mfp-content'); - if (popupContent) { - const videos = popupContent.querySelectorAll('video'); - if (videos.length > 0) { - if (!safeGODAMPlayer(popupContent)) { - safeGODAMPlayer(); - } - } + if (!popupContent) return; + if (!safeGODAMPlayer(popupContent)) { + safeGODAMPlayer(); // fallback } - }, 200); -}; + removeLoadingShimmer(); + } catch (error) {} + }, CONFIG.DEBOUNCE_DELAY); + }; -document.addEventListener('DOMContentLoaded', () => { - safeGODAMPlayer(); + // Handle DOM changes (BuddyPress activities, comments, popups, etc.) + const handleMutations = (mutations) => { + const nodesToProcess = new Set(); + let hasNewVideos = false; - const observer = new MutationObserver((mutations) => { - for (const mutation of mutations) { - for (const node of mutation.addedNodes) { - if (node.nodeType === 1) { - const isPopup = node.classList?.contains('mfp-content') || - node.querySelector?.('.mfp-content'); - const hasVideos = node.tagName === 'VIDEO' || - node.querySelector?.('video'); - - if (isPopup || (hasVideos && node.closest('.mfp-content'))) { - initializePopupVideos(); - } - - // Check for either 'activity' or 'groups' class. - if (node.classList?.contains('activity') || node.classList?.contains('groups')) { - setTimeout(() => safeGODAMPlayer(node), 100); - } - } - } + for (const mutation of mutations) { + for (const node of mutation.addedNodes) { + if (node.nodeType !== 1) continue; + nodesToProcess.add(node); + + if (node.tagName === 'VIDEO' || node.querySelector?.('video')) { + hasNewVideos = true; } - }); + } + } - observer.observe(document.body, { - childList: true, - subtree: true - }); + if (hasNewVideos) { + setTimeout(() => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY); + + setTimeout(() => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 3); + } + + for (const node of nodesToProcess) { + try { + const isPopup = node.classList?.contains('mfp-content') || node.querySelector?.('.mfp-content'); + const hasVideos = node.tagName === 'VIDEO' || node.querySelector?.('video'); + + if (isPopup || (hasVideos && node.closest('.mfp-content'))) { + initializePopupVideos(); + } + + if ( + node.classList?.contains('activity') || + node.classList?.contains('groups') || + node.classList?.contains('bp-activity-item') || + node.classList?.contains('activity-comment') || + node.classList?.contains('acomment-reply') || + node.classList?.contains('comment-item') || + node.querySelector?.('.activity-comment') || + node.querySelector?.('.acomment-reply') || + node.querySelector?.('.comment-item') + ) { + setTimeout(() => { + if (safeGODAMPlayer(node)) removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY); + + setTimeout(() => { + safeGODAMPlayer(node); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 2); + } + + if (hasVideos) { + setTimeout(() => { + const container = node.closest('.activity') || + node.closest('.activity-comment') || + node.closest('.comment-item') || + node; + if (safeGODAMPlayer(container)) removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY); + + setTimeout(() => { + const container = node.closest('.activity') || + node.closest('.activity-comment') || + node.closest('.comment-item') || + node; + safeGODAMPlayer(container); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 4); + } + } catch (error) {} + } + }; + + // Main initialization + const initialize = () => { + if (isInitialized) return; + + safeGODAMPlayer(); + + setTimeout(() => { + if (safeGODAMPlayer()) { + removeLoadingShimmer(); + isInitialized = true; + } + }, CONFIG.INIT_DELAY); + + if (typeof MutationObserver !== 'undefined') { + const observer = new MutationObserver(handleMutations); + observer.observe(document.body, { childList: true, subtree: true, attributeFilter: ['class'] }); + } if (typeof $ !== 'undefined' && $.magnificPopup) { - $(document).on('mfpOpen mfpChange', () => { - initializePopupVideos(); - }); + $(document).on('mfpOpen mfpChange', () => { + initializePopupVideos(); + removeLoadingShimmer(); + }); + $(document).on('mfpOpen', () => { + setTimeout(() => { + initializePopupVideos(); + removeLoadingShimmer(); + }, CONFIG.POPUP_DELAY); + }); + } + }; + + // Init when DOM is ready + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', initialize); + } else { + initialize(); + } + + // Handle comment refresh + document.addEventListener('commentRefreshed', (event) => { + try { + const element = event?.detail?.node || null; + if (safeGODAMPlayer(element)) removeLoadingShimmer(); + } catch (error) {} + }); + + // BuddyPress events + document.addEventListener('bp_activity_loaded', () => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }); - $(document).on('mfpOpen', () => { - setTimeout(initializePopupVideos, 500); - }); + document.addEventListener('bp_activity_comment_posted', (event) => { + setTimeout(() => { + safeGODAMPlayer(event.target || document); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY); + + setTimeout(() => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 3); + }); + + document.addEventListener('bp_activity_reply_posted', (event) => { + setTimeout(() => { + safeGODAMPlayer(event.target || document); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY); + + setTimeout(() => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 3); + }); + + // Generic BuddyPress AJAX complete + if (typeof $ !== 'undefined') { + $(document).ajaxComplete(function(event, xhr, settings) { + if (settings.url && ( + settings.url.includes('bp-nouveau') || + settings.url.includes('buddypress') || + settings.url.includes('activity') || + settings.url.includes('comment') + )) { + setTimeout(() => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY); + + setTimeout(() => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 4); + + setTimeout(() => { + safeGODAMPlayer(); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 8); + } + }); + + // Replace deprecated DOMNodeInserted with MutationObserver + const observer = new MutationObserver(function(mutationsList) { + for (const mutation of mutationsList) { + for (const node of mutation.addedNodes) { + if (node.nodeType === 1) { // Element + if (node.tagName === 'VIDEO' || node.querySelector?.('video')) { + setTimeout(() => { + safeGODAMPlayer(node); + removeLoadingShimmer(); + }, CONFIG.RETRY_DELAY * 2); + } + } + } + } + }); + observer.observe(document.body, { childList: true, subtree: true }); + } + + // Global error handler + window.addEventListener('unhandledrejection', (event) => { + if (event.reason && event.reason.toString().includes('GODAM')) { + event.preventDefault(); // prevent noisy logs } -}); + }); + +})(); diff --git a/app/assets/js/godam-integration.min.js b/app/assets/js/godam-integration.min.js index 5a0727ecf..2f6d9cab9 100644 --- a/app/assets/js/godam-integration.min.js +++ b/app/assets/js/godam-integration.min.js @@ -1 +1 @@ -const safeGODAMPlayer=(e=null)=>{try{return e&&1===e.nodeType&&e.isConnected?GODAMPlayer(e):GODAMPlayer(),!0}catch(e){return!1}};safeGODAMPlayer();let popupInitTimeout=null;const initializePopupVideos=()=>{clearTimeout(popupInitTimeout),popupInitTimeout=setTimeout((()=>{const e=document.querySelector(".mfp-content");if(e){e.querySelectorAll("video").length>0&&(safeGODAMPlayer(e)||safeGODAMPlayer())}}),200)};document.addEventListener("DOMContentLoaded",(()=>{safeGODAMPlayer();new MutationObserver((e=>{for(const t of e)for(const e of t.addedNodes)if(1===e.nodeType){const t=e.classList?.contains("mfp-content")||e.querySelector?.(".mfp-content"),o="VIDEO"===e.tagName||e.querySelector?.("video");(t||o&&e.closest(".mfp-content"))&&initializePopupVideos(),(e.classList?.contains("activity")||e.classList?.contains("groups"))&&setTimeout((()=>safeGODAMPlayer(e)),100)}})).observe(document.body,{childList:!0,subtree:!0}),"undefined"!=typeof $&&$.magnificPopup&&($(document).on("mfpOpen mfpChange",(()=>{initializePopupVideos()})),$(document).on("mfpOpen",(()=>{setTimeout(initializePopupVideos,500)})))})); \ No newline at end of file +!function(){"use strict";const e=200,t=100,o=3,n=1e3,c=500;let i=!1;const s=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout((()=>{try{document.querySelectorAll(".easydam-video-container.animate-video-loading").forEach((e=>e.classList.remove("animate-video-loading")))}catch(e){}}),e)}})(),a=(e=null,n=0)=>{if("function"!=typeof GODAMPlayer)return na(e,n+1)),t*(n+1)),!1;try{return!e||1===e.nodeType&&e.isConnected||(e=null),e?GODAMPlayer(e):GODAMPlayer(),!0}catch(c){return na(e,n+1)),t*(n+1)),!1}};let u=null;const m=()=>{clearTimeout(u),u=setTimeout((()=>{try{const e=document.querySelector(".mfp-content");if(!e)return;a(e)||a(),s()}catch(e){}}),e)},r=e=>{const o=new Set;let n=!1;for(const t of e)for(const e of t.addedNodes)1===e.nodeType&&(o.add(e),("VIDEO"===e.tagName||e.querySelector?.("video"))&&(n=!0));n&&(setTimeout((()=>{a(),s()}),t),setTimeout((()=>{a(),s()}),3*t));for(const e of o)try{const o=e.classList?.contains("mfp-content")||e.querySelector?.(".mfp-content"),n="VIDEO"===e.tagName||e.querySelector?.("video");(o||n&&e.closest(".mfp-content"))&&m(),(e.classList?.contains("activity")||e.classList?.contains("groups")||e.classList?.contains("bp-activity-item")||e.classList?.contains("activity-comment")||e.classList?.contains("acomment-reply")||e.classList?.contains("comment-item")||e.querySelector?.(".activity-comment")||e.querySelector?.(".acomment-reply")||e.querySelector?.(".comment-item"))&&(setTimeout((()=>{a(e)&&s()}),t),setTimeout((()=>{a(e),s()}),2*t)),n&&(setTimeout((()=>{const t=e.closest(".activity")||e.closest(".activity-comment")||e.closest(".comment-item")||e;a(t)&&s()}),t),setTimeout((()=>{const t=e.closest(".activity")||e.closest(".activity-comment")||e.closest(".comment-item")||e;a(t),s()}),4*t))}catch(e){}},d=()=>{if(!i){if(a(),setTimeout((()=>{a()&&(s(),i=!0)}),n),"undefined"!=typeof MutationObserver){new MutationObserver(r).observe(document.body,{childList:!0,subtree:!0,attributeFilter:["class"]})}"undefined"!=typeof $&&$.magnificPopup&&($(document).on("mfpOpen mfpChange",(()=>{m(),s()})),$(document).on("mfpOpen",(()=>{setTimeout((()=>{m(),s()}),c)})))}};if("loading"===document.readyState?document.addEventListener("DOMContentLoaded",d):d(),document.addEventListener("commentRefreshed",(e=>{try{a(e?.detail?.node||null)&&s()}catch(e){}})),document.addEventListener("bp_activity_loaded",(()=>{a(),s()})),document.addEventListener("bp_activity_comment_posted",(e=>{setTimeout((()=>{a(e.target||document),s()}),t),setTimeout((()=>{a(),s()}),3*t)})),document.addEventListener("bp_activity_reply_posted",(e=>{setTimeout((()=>{a(e.target||document),s()}),t),setTimeout((()=>{a(),s()}),3*t)})),"undefined"!=typeof $){$(document).ajaxComplete((function(e,o,n){n.url&&(n.url.includes("bp-nouveau")||n.url.includes("buddypress")||n.url.includes("activity")||n.url.includes("comment"))&&(setTimeout((()=>{a(),s()}),t),setTimeout((()=>{a(),s()}),4*t),setTimeout((()=>{a(),s()}),8*t))}));new MutationObserver((function(e){for(const o of e)for(const e of o.addedNodes)1===e.nodeType&&("VIDEO"===e.tagName||e.querySelector?.("video"))&&setTimeout((()=>{a(e),s()}),2*t)})).observe(document.body,{childList:!0,subtree:!0})}window.addEventListener("unhandledrejection",(e=>{e.reason&&e.reason.toString().includes("GODAM")&&e.preventDefault()}))}(); \ No newline at end of file diff --git a/app/assets/js/rtMedia.backbone.js b/app/assets/js/rtMedia.backbone.js index 5ea033882..1c99c12bf 100755 --- a/app/assets/js/rtMedia.backbone.js +++ b/app/assets/js/rtMedia.backbone.js @@ -7,1184 +7,1448 @@ var objUploadView; var rtmedia_load_template_flag = true; var rtmedia_add_media_button_post_update = false; +jQuery(document).ready(function () { + // Need to pass the object[key] as global variable. + if ("object" === typeof rtmedia_backbone) { + for (var key in rtmedia_backbone) { + window[key] = rtmedia_backbone[key]; + } + } + if ("object" === typeof rtMedia_plupload) { + for (var key in rtMedia_plupload) { + window[key] = rtMedia_plupload[key]; + } + } + if ("object" === typeof rtmedia_template) { + for (var key in rtmedia_template) { + window[key] = rtmedia_template[key]; + } + } + if ("object" === typeof rtMedia_activity) { + for (var key in rtMedia_activity) { + window[key] = rtMedia_activity[key]; + } + } + if ("object" === typeof rtmedia_bp) { + for (var key in rtmedia_bp) { + window[key] = rtmedia_bp[key]; + } + } + if ("object" === typeof rtmedia_main) { + for (var key in rtmedia_main) { + window[key] = rtmedia_main[key]; + } + } +}); -jQuery( document ).ready( function () { - - // Need to pass the object[key] as global variable. - if ( 'object' === typeof rtmedia_backbone ) { - for ( var key in rtmedia_backbone ) { - window[key] = rtmedia_backbone[key]; - } - } - if ( 'object' === typeof rtMedia_plupload ) { - for( var key in rtMedia_plupload ) { - window[key] = rtMedia_plupload[key]; - } - } - if ( 'object' === typeof rtmedia_template ) { - for( var key in rtmedia_template ) { - window[key] = rtmedia_template[key]; - } - } - if ( 'object' === typeof rtMedia_activity ) { - for( var key in rtMedia_activity ) { - window[key] = rtMedia_activity[key]; - } - } - if ( 'object' === typeof rtmedia_bp ) { - for( var key in rtmedia_bp ) { - window[key] = rtmedia_bp[key]; - } - } - if ( 'object' === typeof rtmedia_main ) { - for( var key in rtmedia_main ) { - window[key] = rtmedia_main[key]; - } - } -} ); - -jQuery( function( $ ) { - /** - * Issue 1059 fixed: negative comment count - */ - $( document ).ready( function () { - /** - * Bind dynamic event on delete button to remove media ul - */ - $( '#activity-stream' ).on( 'click', '.acomment-delete', function () { - /** - * get media ul - */ - let media_children = $( this ).closest('li').find( 'div.acomment-content ul.rtmedia-list' ); - if ( media_children.length > 0 ) { - /** - * remove ul if exists, so buddypress comment js doesn't get confused between media ul and child comment ul - */ - media_children.remove(); - } - }); - - /** - * Remove imageEdit.save function call and add it only when image is being modified in WP editor. - */ - $( '#rtmedia_media_single_edit .rtm-button-save' ).on( 'click', function() { - var $media_id = $( '#rtmedia-editor-media-id' ).val(); - var $nonce = $( '#rtmedia-editor-nonce' ).val(); - if ( 'undefined' === typeof $nonce || '' === $nonce.trim() || 'undefined' === typeof $media_id || '' === $media_id.trim() ) { - return; - } - $media_id = parseInt( $media_id ); - $media_head = $( '#media-head-' + $media_id ); - if ( ! $media_head.length || 'undefined' === typeof $media_head.css( 'display' ) || 'none' !== $media_head.css( 'display' ).trim() ) { - return; - } - - imageEdit.save( $media_id, $nonce ); - } ); - - /** - * Reload page when rtmedia_update type of activity is edited. - */ - function filterBeaSaveSuccess() { - location.reload(); - } - /** - * Prefilters ajax call which saves edited activity content. - * Needed with BuddyPress Edit Activity plugin. - * https://wordpress.org/plugins/buddypress-edit-activity/ - */ - $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { - // Modify options, control originalOptions, store jqXHR, etc - try { - if ( null === originalOptions.data || typeof ( originalOptions.data ) === 'undefined' || typeof ( originalOptions.data.action ) === 'undefined' || 'buddypress-edit-activity-save' !== originalOptions.data.action ) { - return true; - } - } catch ( e ) { - return true; - } - - if ( ! $( '#activity-' + originalOptions.data.activity_id ).hasClass( 'rtmedia_update' ) ) { - return; - } - - // Change the callback function to our own function, which reloads the page. - originalOptions.success = filterBeaSaveSuccess; - options.success = filterBeaSaveSuccess; - } ); - }); - /** - * End of issue 1059 fix - */ - - - var o_is_album, o_is_edit_allowed; - if ( typeof ( is_album ) == 'undefined' ) { - o_is_album = new Array( '' ); - } else { - o_is_album = is_album; - } - if ( typeof ( is_edit_allowed ) == 'undefined' ) { - o_is_edit_allowed = new Array( '' ); - } else { - o_is_edit_allowed = is_edit_allowed; - } - - rtMedia = window.rtMedia || { }; - - rtMedia = window.rtMedia || { }; - - rtMedia.Context = Backbone.Model.extend( { - url: function() { - var url = rtmedia_media_slug + '/'; - - if ( ! upload_sync && nextpage > 0 ) { - url += 'pg/' + nextpage + '/'; - } - - return url; - }, - defaults: { - 'context': 'post', - 'context_id': false - } - } ); +jQuery(function ($) { + /** + * Issue 1059 fixed: negative comment count + */ + $(document).ready(function () { + /** + * Bind dynamic event on delete button to remove media ul + */ + $("#activity-stream").on("click", ".acomment-delete", function () { + /** + * get media ul + */ + let media_children = $(this) + .closest("li") + .find("div.acomment-content ul.rtmedia-list"); + if (media_children.length > 0) { + /** + * remove ul if exists, so buddypress comment js doesn't get confused between media ul and child comment ul + */ + media_children.remove(); + } + }); + + /** + * Remove imageEdit.save function call and add it only when image is being modified in WP editor. + */ + $("#rtmedia_media_single_edit .rtm-button-save").on("click", function () { + var $media_id = $("#rtmedia-editor-media-id").val(); + var $nonce = $("#rtmedia-editor-nonce").val(); + if ( + "undefined" === typeof $nonce || + "" === $nonce.trim() || + "undefined" === typeof $media_id || + "" === $media_id.trim() + ) { + return; + } + $media_id = parseInt($media_id); + $media_head = $("#media-head-" + $media_id); + if ( + !$media_head.length || + "undefined" === typeof $media_head.css("display") || + "none" !== $media_head.css("display").trim() + ) { + return; + } + + imageEdit.save($media_id, $nonce); + }); + + /** + * Reload page when rtmedia_update type of activity is edited. + */ + function filterBeaSaveSuccess() { + location.reload(); + } + /** + * Prefilters ajax call which saves edited activity content. + * Needed with BuddyPress Edit Activity plugin. + * https://wordpress.org/plugins/buddypress-edit-activity/ + */ + $.ajaxPrefilter(function (options, originalOptions, jqXHR) { + // Modify options, control originalOptions, store jqXHR, etc + try { + if ( + null === originalOptions.data || + typeof originalOptions.data === "undefined" || + typeof originalOptions.data.action === "undefined" || + "buddypress-edit-activity-save" !== originalOptions.data.action + ) { + return true; + } + } catch (e) { + return true; + } + + if ( + !$("#activity-" + originalOptions.data.activity_id).hasClass( + "rtmedia_update" + ) + ) { + return; + } + + // Change the callback function to our own function, which reloads the page. + originalOptions.success = filterBeaSaveSuccess; + options.success = filterBeaSaveSuccess; + }); + }); + /** + * End of issue 1059 fix + */ + + var o_is_album, o_is_edit_allowed; + if (typeof is_album == "undefined") { + o_is_album = new Array(""); + } else { + o_is_album = is_album; + } + if (typeof is_edit_allowed == "undefined") { + o_is_edit_allowed = new Array(""); + } else { + o_is_edit_allowed = is_edit_allowed; + } + + rtMedia = window.rtMedia || {}; + + rtMedia = window.rtMedia || {}; + + rtMedia.Context = Backbone.Model.extend({ + url: function () { + var url = rtmedia_media_slug + "/"; + + if (!upload_sync && nextpage > 0) { + url += "pg/" + nextpage + "/"; + } + + return url; + }, + defaults: { + context: "post", + context_id: false, + }, + }); + + rtMedia.Media = Backbone.Model.extend({ + defaults: { + id: 0, + blog_id: false, + media_id: false, + media_author: false, + media_title: false, + album_id: false, + media_type: "photo", + activity_id: false, + privacy: 0, + views: 0, + downloads: 0, + ratings_average: 0, + ratings_total: 0, + ratings_count: 0, + likes: 0, + dislikes: 0, + guid: false, + width: 0, + height: 0, + rt_permalink: false, + duration: "0:00", + //"next": -1, + //"prev": -1 + }, + }); + + rtMedia.Gallery = Backbone.Collection.extend({ + model: rtMedia.Media, + url: function () { + var temp = window.location.pathname; + var url = ""; + if (temp.indexOf("/" + rtmedia_media_slug + "/") == -1) { + url = rtmedia_media_slug + "/"; + } else { + if (temp.indexOf("pg/") == -1) { + url = temp; + } else { + url = window.location.pathname.substr( + 0, + window.location.pathname.lastIndexOf("pg/") + ); + } + } + if (!upload_sync && nextpage >= 1) { + if (url.substr(url.length - 1) != "/") { + url += "/"; + } - rtMedia.Media = Backbone.Model.extend( { - defaults: { - 'id': 0, - 'blog_id': false, - 'media_id': false, - 'media_author': false, - 'media_title': false, - 'album_id': false, - 'media_type': 'photo', - 'activity_id': false, - 'privacy': 0, - 'views': 0, - 'downloads': 0, - 'ratings_average': 0, - 'ratings_total': 0, - 'ratings_count': 0, - 'likes': 0, - 'dislikes': 0, - 'guid': false, - 'width': 0, - 'height': 0, - 'rt_permalink': false, - 'duration': '0:00' - //"next": -1, - //"prev": -1 - } + url += "pg/" + nextpage + "/"; + } - } ); + return url; + }, + getNext: function (page, el, element) { + if (jQuery(".rtmedia-no-media-found").length > 0) { + var rtmediaListUl = jQuery("
    ", { + class: "rtmedia-list rtmedia-list-media rtm-pro-allow-action", + }); + jQuery(".rtmedia-no-media-found").replaceWith(rtmediaListUl); + } + that = this; + if (rtmedia_load_template_flag == true) { + if ( + jQuery(".rtmedia_gallery_wrapper").find("input[name=media_title]") + .length > 0 + ) { + template_url += + "&media_title=" + + jQuery(".rtmedia_gallery_wrapper") + .find("input[name=media_title]") + .val(); + } + if ( + jQuery(".rtmedia_gallery_wrapper").find("input[name=lightbox]") + .length > 0 + ) { + template_url += + "&lightbox=" + + jQuery(".rtmedia_gallery_wrapper") + .find("input[name=lightbox]") + .val(); + } + $("#rtmedia-gallery-item-template").load( + template_url, + { + backbone: true, + is_album: o_is_album, + is_edit_allowed: o_is_edit_allowed, + }, + function () { + rtmedia_load_template_flag = false; + that.getNext(page, el, element); + } + ); + } + + if (!rtmedia_load_template_flag) { + var query = { + json: true, + }; + + //media search + if (check_condition("search")) { + if ("" !== $("#media_search_input").val()) { + var search = check_url("search"); + if (search) { + query.search = search; + } + if (check_condition("search_by")) { + var search_by = check_url("search_by"); + if (search_by) { + query.search_by = search_by; + } + } + } + } - rtMedia.Gallery = Backbone.Collection.extend( { - model: rtMedia.Media, - url: function() { - var temp = window.location.pathname; - var url = ''; - if ( temp.indexOf( '/' + rtmedia_media_slug + '/' ) == -1 ) { - url = rtmedia_media_slug + '/'; - } else { - if ( temp.indexOf( 'pg/' ) == -1 ) { - url = temp; - } else { - url = window.location.pathname.substr( 0, window.location.pathname.lastIndexOf( 'pg/' ) ); - } - } - if ( ! upload_sync && nextpage >= 1 ) { - if ( url.substr( url.length - 1 ) != '/' ) { - url += '/'; - } - - url += 'pg/' + nextpage + '/'; - } - - return url; - }, - getNext: function( page, el, element) { - - if ( jQuery( '.rtmedia-no-media-found' ).length > 0 ) { - var rtmediaListUl = jQuery( '
      ', { - 'class': 'rtmedia-list rtmedia-list-media rtm-pro-allow-action', - }); - jQuery( '.rtmedia-no-media-found' ).replaceWith( rtmediaListUl ); - } - that = this; - if ( rtmedia_load_template_flag == true ) { - if ( jQuery( '.rtmedia_gallery_wrapper' ).find( 'input[name=media_title]' ).length > 0 ) { - template_url += '&media_title=' + jQuery( '.rtmedia_gallery_wrapper' ).find( 'input[name=media_title]' ).val(); - } - if ( jQuery( '.rtmedia_gallery_wrapper' ).find( 'input[name=lightbox]' ).length > 0 ) { - template_url += '&lightbox=' + jQuery( '.rtmedia_gallery_wrapper' ).find( 'input[name=lightbox]' ).val(); - } - $( '#rtmedia-gallery-item-template' ).load( template_url, { backbone: true, is_album: o_is_album, is_edit_allowed: o_is_edit_allowed }, function() { - rtmedia_load_template_flag = false; - that.getNext( page, el, element); - } ); - } - - if ( ! rtmedia_load_template_flag ) { - var query = { - json: true, - }; - - //media search - if( check_condition( 'search' ) ) { - if ( '' !== $( '#media_search_input' ).val() ) { - var search = check_url( 'search' ); - if ( search ) { - query.search = search; - } - if ( check_condition( 'search_by' ) ) { - var search_by = check_url( 'search_by' ); - if ( search_by ) { - query.search_by = search_by; - } - } - } - } - - query.rtmedia_page = nextpage; - - if ( el == undefined ) { - el = jQuery( '.rtmedia-list' ).parent().parent(); - } - - if ( el != undefined ) { - if ( element != undefined ) { - $( element ).parent().parent().prevAll( 'input[type=hidden]' ).not( 'input[name=_wp_http_referer], input[name=rtmedia_media_delete_nonce], input[name=rtmedia_bulk_delete_nonce], input[name=bulk-action], input[name=rtmedia_create_album_nonce], input[name=rtmedia_media_nonce], input[name=rtmedia_upload_nonce], input[name=rtmedia_allow_upload_attribute]' ).each( function( e ) { - if ( $( this ).attr( 'name' ) ) { - query[ $( this ).attr( 'name' ) ] = $( this ).val(); - } - } ); - } - - $( el ).find( 'input[type=hidden]' ).not( 'input[name=_wp_http_referer], input[name=rtmedia_media_delete_nonce], input[name=rtmedia_bulk_delete_nonce], input[name=bulk-action], input[name=rtmedia_create_album_nonce], input[name=rtmedia_media_nonce], input[name=rtmedia_upload_nonce], input[name=rtmedia_allow_upload_attribute]' ).each( function( e ) { - if ( $( this ).attr( 'name' ) ) { - query[ $( this ).attr( 'name' ) ] = $( this ).val(); - } - } ); - } - this.fetch( { - data: query, - success: function( model, response ) { - - jQuery( '.rtm-media-loading' ).hide(); - var list_el = ''; - - if ( typeof ( element ) === 'undefined' ) { - if ( jQuery( el ).find( '.rtmedia-list' ).length > 0 ) { - list_el = jQuery( el ).find( '.rtmedia-list' ); - } else { - list_el = $( '.rtmedia-list' )[0]; - } - } else { - list_el = element.parent().siblings( '.rtmedia-list' ); - } - nextpage = response.next; - - if ( nextpage < 1 ) { - if ( typeof el == 'object' ) { - jQuery( el ).find( '.rtmedia_next_prev' ).children( '#rtMedia-galary-next' ).hide(); - } - } - - rtMedia.gallery = {}; - rtMedia.gallery.page = page; - - var galleryViewObj = new rtMedia.GalleryView( { - collection: new rtMedia.Gallery( response.data ), - el: list_el, - } ); - //Element.show(); - - // get current gallery container object - var current_gallery = galleryViewObj.$el.parents( '.rtmedia-container' ); - var current_gallery_id = current_gallery.attr( 'id' ); - - rtMediaHook.call( 'rtmedia_after_gallery_load' ); - - jQuery( '#' + current_gallery_id + ' .rtmedia_next_prev .rtm-pagination' ).remove(); - jQuery( '#' + current_gallery_id + ' .rtmedia_next_prev .clear' ).remove(); - jQuery( '#' + current_gallery_id + ' .rtmedia_next_prev .rtm-media-loading' ).remove(); - jQuery( '#' + current_gallery_id + ' .rtmedia_next_prev br' ).remove(); - jQuery( '#' + current_gallery_id + ' .rtmedia_next_prev' ).append( response.pagination ); - - // Update the media count in user profile & group's media tab. - jQuery( '#user-media span, #media-groups-li #media span, #rtmedia-nav-item-all span' ).text( response.media_count.all_media_count ); - - - // Update the count on sub navigations (Albums) - // jQuery( '#rtmedia-nav-item-albums span' ).text( response.media_count.albums_count ); - - // Update the count on sub navigations (Photo, Video & Music) - jQuery( '#rtmedia-nav-item-photo span' ).text( response.media_count.photos_count ); - jQuery( '#rtmedia-nav-item-music span' ).text( response.media_count.music_count ); - jQuery( '#rtmedia-nav-item-video span' ).text( response.media_count.videos_count ); - jQuery( '#rtmedia-nav-item-document span' ).text( response.media_count.docs_count ); - - - if ( jQuery( 'li#rtm-url-upload' ).length === 0 ) { - jQuery( '#' + current_gallery_id + ' .rtmedia-list' ).css( { 'opacity': 1, 'height': 'auto', 'overflow': 'auto' } ); - if ( rtMediaHook.call( 'rtmedia_js_uploader_slide_after_gallery_reload' ) ) { - jQuery( '#rtm-media-gallery-uploader' ).slideUp(); - } - } - } - } ); - } - - }, - reloadView: function( parent_el ) { - upload_sync = true; - nextpage = 1; - jQuery( '.rtmedia-container .rtmedia-list' ).css( 'opacity', '0.5' ); - this.getNext( undefined, parent_el, undefined ); - } - } ); + query.rtmedia_page = nextpage; - rtMedia.MediaView = Backbone.View.extend( { - tagName: 'li', - className: 'rtmedia-list-item', - initialize: function() { - this.template = _.template( $( '#rtmedia-gallery-item-template' ).html() ); - this.model.bind( 'change', this.render ); - this.model.bind( 'remove', this.unrender ); - this.render(); - }, - render: function() { - $( this.el ).html( this.template( this.model.toJSON() ) ); - return this.el; - }, - unrender: function() { - $( this.el ).remove(); - }, - remove: function() { - this.model.destroy(); - } - } ); + if (el == undefined) { + el = jQuery(".rtmedia-list").parent().parent(); + } - rtMedia.GalleryView = Backbone.View.extend( { - tagName: 'ul', - className: 'rtmedia-list', - initialize: function() { - - this.template = _.template( $( '#rtmedia-gallery-item-template' ).html() ); - this.render(); - }, - render: function() { - - that = this; - var rtmedia_gallery_container_nodata = $( 'div[id^="rtmedia_gallery_container_"] .rtmedia-nodata' ); - if ( upload_sync ) { - $( that.el ).html( '' ); - } - - if ( typeof ( rtmedia_load_more_or_pagination ) != 'undefined' && rtmedia_load_more_or_pagination == 'pagination' || ( 1 == rtMedia.gallery.page ) ) { - $( that.el ).html( '' ); - } - - // Remove no data found message if it's there. - if ( rtmedia_gallery_container_nodata.length > 0 ) { - rtmedia_gallery_container_nodata.remove(); - } - if ( 0 === this.collection.length ) { - $( 'div[id^="rtmedia_gallery_container_"]' ).append( '

      ' + rtmedia_no_media_found + '

      ' ); - } else { - $.each( this.collection.toJSON(), function( key, media ) { - $( that.el ).append( that.template( media ) ); - } ); - } - - if ( upload_sync ) { - upload_sync = false; - } - if ( nextpage > 1 ) { - $( that.el ).siblings( '.rtmedia_next_prev' ).children( '#rtMedia-galary-next' ).show(); - //$("#rtMedia-galary-next").show(); - } - if ( 'undefined' != typeof rtmedia_masonry_layout && 'true' == rtmedia_masonry_layout && 0 == jQuery( '.rtmedia-container .rtmedia-list.rtm-no-masonry' ).length ) { - rtm_masonry_reload( rtm_masonry_container ); - } - $( '#media_fatch_loader' ).removeClass('load'); - }, - appendTo: function( media ) { - var mediaView = new rtMedia.MediaView( { - model: media - } ); - $( this.el ).append( mediaView.render().el ); - } - } ); + if (el != undefined) { + if (element != undefined) { + $(element) + .parent() + .parent() + .prevAll("input[type=hidden]") + .not( + "input[name=_wp_http_referer], input[name=rtmedia_media_delete_nonce], input[name=rtmedia_bulk_delete_nonce], input[name=bulk-action], input[name=rtmedia_create_album_nonce], input[name=rtmedia_media_nonce], input[name=rtmedia_upload_nonce], input[name=rtmedia_allow_upload_attribute]" + ) + .each(function (e) { + if ($(this).attr("name")) { + query[$(this).attr("name")] = $(this).val(); + } + }); + } + + $(el) + .find("input[type=hidden]") + .not( + "input[name=_wp_http_referer], input[name=rtmedia_media_delete_nonce], input[name=rtmedia_bulk_delete_nonce], input[name=bulk-action], input[name=rtmedia_create_album_nonce], input[name=rtmedia_media_nonce], input[name=rtmedia_upload_nonce], input[name=rtmedia_allow_upload_attribute]" + ) + .each(function (e) { + if ($(this).attr("name")) { + query[$(this).attr("name")] = $(this).val(); + } + }); + } + this.fetch({ + data: query, + success: function (model, response) { + jQuery(".rtm-media-loading").hide(); + var list_el = ""; + + if (typeof element === "undefined") { + if (jQuery(el).find(".rtmedia-list").length > 0) { + list_el = jQuery(el).find(".rtmedia-list"); + } else { + list_el = $(".rtmedia-list")[0]; + } + } else { + list_el = element.parent().siblings(".rtmedia-list"); + } + nextpage = response.next; + + if (nextpage < 1) { + if (typeof el == "object") { + jQuery(el) + .find(".rtmedia_next_prev") + .children("#rtMedia-galary-next") + .hide(); + } + } - galleryObj = new rtMedia.Gallery(); + rtMedia.gallery = {}; + rtMedia.gallery.page = page; - $( 'body' ).append( '' ); + var galleryViewObj = new rtMedia.GalleryView({ + collection: new rtMedia.Gallery(response.data), + el: list_el, + }); + //Element.show(); + + // get current gallery container object + var current_gallery = + galleryViewObj.$el.parents(".rtmedia-container"); + var current_gallery_id = current_gallery.attr("id"); + + rtMediaHook.call("rtmedia_after_gallery_load"); + + jQuery( + "#" + current_gallery_id + " .rtmedia_next_prev .rtm-pagination" + ).remove(); + jQuery( + "#" + current_gallery_id + " .rtmedia_next_prev .clear" + ).remove(); + jQuery( + "#" + + current_gallery_id + + " .rtmedia_next_prev .rtm-media-loading" + ).remove(); + jQuery( + "#" + current_gallery_id + " .rtmedia_next_prev br" + ).remove(); + jQuery("#" + current_gallery_id + " .rtmedia_next_prev").append( + response.pagination + ); + + // Update the media count in user profile & group's media tab. + jQuery( + "#user-media span, #media-groups-li #media span, #rtmedia-nav-item-all span" + ).text(response.media_count.all_media_count); + + // Update the count on sub navigations (Albums) + // jQuery( '#rtmedia-nav-item-albums span' ).text( response.media_count.albums_count ); + + // Update the count on sub navigations (Photo, Video & Music) + jQuery("#rtmedia-nav-item-photo span").text( + response.media_count.photos_count + ); + jQuery("#rtmedia-nav-item-music span").text( + response.media_count.music_count + ); + jQuery("#rtmedia-nav-item-video span").text( + response.media_count.videos_count + ); + jQuery("#rtmedia-nav-item-document span").text( + response.media_count.docs_count + ); + + if (jQuery("li#rtm-url-upload").length === 0) { + jQuery("#" + current_gallery_id + " .rtmedia-list").css({ + opacity: 1, + height: "auto", + overflow: "auto", + }); + if ( + rtMediaHook.call( + "rtmedia_js_uploader_slide_after_gallery_reload" + ) + ) { + jQuery("#rtm-media-gallery-uploader").slideUp(); + } + } + }, + }); + } + }, + reloadView: function (parent_el) { + upload_sync = true; + nextpage = 1; + jQuery(".rtmedia-container .rtmedia-list").css("opacity", "0.5"); + this.getNext(undefined, parent_el, undefined); + }, + }); + + rtMedia.MediaView = Backbone.View.extend({ + tagName: "li", + className: "rtmedia-list-item", + initialize: function () { + this.template = _.template($("#rtmedia-gallery-item-template").html()); + this.model.on("change", this.render); + this.model.on("remove", this.unrender); + this.render(); + }, + render: function () { + $(this.el).html(this.template(this.model.toJSON())); + return this.el; + }, + unrender: function () { + $(this.el).remove(); + }, + remove: function () { + this.model.destroy(); + }, + }); + + rtMedia.GalleryView = Backbone.View.extend({ + tagName: "ul", + className: "rtmedia-list", + initialize: function () { + this.template = _.template($("#rtmedia-gallery-item-template").html()); + this.render(); + }, + render: function () { + that = this; + var rtmedia_gallery_container_nodata = $( + 'div[id^="rtmedia_gallery_container_"] .rtmedia-nodata' + ); + if (upload_sync) { + $(that.el).html(""); + } + + if ( + (typeof rtmedia_load_more_or_pagination != "undefined" && + rtmedia_load_more_or_pagination == "pagination") || + 1 == rtMedia.gallery.page + ) { + $(that.el).html(""); + } + + // Remove no data found message if it's there. + if (rtmedia_gallery_container_nodata.length > 0) { + rtmedia_gallery_container_nodata.remove(); + } + if (0 === this.collection.length) { + $('div[id^="rtmedia_gallery_container_"]').append( + '

      ' + rtmedia_no_media_found + "

      " + ); + } else { + $.each(this.collection.toJSON(), function (key, media) { + $(that.el).append(that.template(media)); + }); + } + + if (upload_sync) { + upload_sync = false; + } + if (nextpage > 1) { + $(that.el) + .siblings(".rtmedia_next_prev") + .children("#rtMedia-galary-next") + .show(); + //$("#rtMedia-galary-next").show(); + } + if ( + "undefined" != typeof rtmedia_masonry_layout && + "true" == rtmedia_masonry_layout && + 0 == jQuery(".rtmedia-container .rtmedia-list.rtm-no-masonry").length + ) { + rtm_masonry_reload(rtm_masonry_container); + } + $("#media_fatch_loader").removeClass("load"); + }, + appendTo: function (media) { + var mediaView = new rtMedia.MediaView({ + model: media, + }); + $(this.el).append(mediaView.render().el); + }, + }); + + galleryObj = new rtMedia.Gallery(); + + $("body").append( + '' + ); + + $(document).on("click", "#rtMedia-galary-next", function (e) { + if (jQuery(".rtm-media-loading").length == 0) { + $(this).before( + "
      " + ); + } else { + jQuery(".rtm-media-loading").show(); + } + $(this).hide(); + e.preventDefault(); + + //commented beacuse it was creating a problem when gallery shortcode was used with bulk edit + //galleryObj.getNext( nextpage, $( this ).parent().parent().parent(), $( this ) ); + + //Added beacuse it was creating a problem when gallery shortcode was used with bulk edit + var parent_object = $(this).closest(".rtmedia-container").parent(); + galleryObj.getNext(nextpage, parent_object, $(this)); + }); + + /** + * onClick Show all comment + */ + $(document).on("click", "#rtmedia_show_all_comment", function () { + var show_comment = $("#rtmedia_show_all_comment").parent().next(); + $(show_comment).each(function () { + $(this) + .find("li") + .each(function () { + $(this).removeClass("hide"); + }); + }); + $(this).parent().remove(); + + /** Scroll function called */ + rtMediaScrollComments(); + }); + + $(document).on("keypress", "#rtmedia_go_to_num", function (e) { + if (e.keyCode == 13) { + e.preventDefault(); + + var current_gallery = $(this).parents(".rtmedia-container"); + var current_gallery_id = current_gallery.attr("id"); + + if ($("#" + current_gallery_id + " .rtm-media-loading").length == 0) { + $("#" + current_gallery_id + " .rtm-pagination").before( + "
      " + ); + } else { + $("#" + current_gallery_id + " .rtm-media-loading").show(); + } + + if ( + parseInt($("#" + current_gallery_id + " #rtmedia_go_to_num").val()) > + parseInt($("#" + current_gallery_id + " #rtmedia_last_page").val()) + ) { + nextpage = parseInt( + $("#" + current_gallery_id + " #rtmedia_last_page").val() + ); + } else { + nextpage = parseInt( + $("#" + current_gallery_id + " #rtmedia_go_to_num").val() + ); + } + + var page_base_url = $( + "#" + current_gallery_id + " .rtmedia-page-no .rtmedia-page-link" + ).data("page-base-url"); + var href = page_base_url + nextpage; + + change_rtBrowserAddressUrl(href, ""); + + galleryObj.getNext( + nextpage, + $(this).parents(".rtmedia_gallery_wrapper"), + $(this).parents(".rtm-pagination") + ); + return false; + } + }); - $( document ).on( 'click', '#rtMedia-galary-next', function( e ) { - if ( jQuery( '.rtm-media-loading' ).length == 0 ) { - $( this ).before( '
      ' ); - } else { - jQuery( '.rtm-media-loading' ).show(); - } - $( this ).hide(); - e.preventDefault(); + $(document).on("click", ".rtmedia-page-link", function (e) { + /* Get current clicked href value */ + href = $(this).attr("href"); - //commented beacuse it was creating a problem when gallery shortcode was used with bulk edit - //galleryObj.getNext( nextpage, $( this ).parent().parent().parent(), $( this ) ); + var current_gallery = $(this).parents(".rtmedia-container"); + var current_gallery_id = current_gallery.attr("id"); - //Added beacuse it was creating a problem when gallery shortcode was used with bulk edit - var parent_object = $( this ).closest( '.rtmedia-container' ).parent(); - galleryObj.getNext( nextpage, parent_object, $( this ) ); - } ); + if ($("#" + current_gallery_id + " .rtm-media-loading").length == 0) { + $("#" + current_gallery_id + " .rtm-pagination").before( + "
      " + ); + } else { + $("#" + current_gallery_id + " .rtm-media-loading").show(); + } - /** - * onClick Show all comment - */ - $( document ).on( 'click', '#rtmedia_show_all_comment', function() { - var show_comment = $( '#rtmedia_show_all_comment' ).parent().next(); - $( show_comment ).each(function() { - $( this ).find('li').each(function() { - $(this).removeClass('hide'); - } ); - } ); - $( this ).parent().remove(); - - /** Scroll function called */ - rtMediaScrollComments(); - } ); + e.preventDefault(); + if ($(this).data("page-type") == "page") { + nextpage = $(this).data("page"); + } else if ($(this).data("page-type") == "prev") { + if (nextpage == -1) { + nextpage = + parseInt($("#" + current_gallery_id + " #rtmedia_last_page").val()) - + 1; + } else { + nextpage -= 2; + } + } else if ($(this).data("page-type") == "num") { + if ( + parseInt($("#" + current_gallery_id + " #rtmedia_go_to_num").val()) > + parseInt($("#rtmedia_last_page").val()) + ) { + nextpage = parseInt( + $("#" + current_gallery_id + " #rtmedia_last_page").val() + ); + } else { + nextpage = parseInt( + $("#" + current_gallery_id + " #rtmedia_go_to_num").val() + ); + } + + /* Set page url for input type num pagination */ + page_base_url = $(this).data("page-base-url"); + href = page_base_url + nextpage; + } - $( document ).on( 'keypress', '#rtmedia_go_to_num', function( e ) { - if ( e.keyCode == 13 ) { - e.preventDefault(); - - var current_gallery = $(this).parents( '.rtmedia-container' ); - var current_gallery_id = current_gallery.attr( 'id' ); - - - if ( $( '#' + current_gallery_id + ' .rtm-media-loading' ).length == 0 ) { - $( '#' + current_gallery_id + ' .rtm-pagination' ).before( '
      ' ); - } else { - $( '#' + current_gallery_id + ' .rtm-media-loading' ).show(); - } - - if ( parseInt( $( '#' + current_gallery_id + ' #rtmedia_go_to_num' ).val() ) > parseInt( $( '#' + current_gallery_id + ' #rtmedia_last_page' ).val() ) ) { - nextpage = parseInt( $( '#' + current_gallery_id + ' #rtmedia_last_page' ).val() ); - } else { - nextpage = parseInt( $( '#' + current_gallery_id + ' #rtmedia_go_to_num' ).val() ); - } - - var page_base_url = $( '#' + current_gallery_id + ' .rtmedia-page-no .rtmedia-page-link' ).data( 'page-base-url' ); - var href = page_base_url + nextpage; - - change_rtBrowserAddressUrl( href, '' ); - - galleryObj.getNext( nextpage, $( this ).parents( '.rtmedia_gallery_wrapper' ), $( this ).parents( '.rtm-pagination' ) ); - return false; - } - } ); - - $( document ).on( 'click', '.rtmedia-page-link', function( e ) { - - /* Get current clicked href value */ - href = $( this ).attr( 'href' ); - - var current_gallery = $(this).parents( '.rtmedia-container' ); - var current_gallery_id = current_gallery.attr( 'id' ); - - if ( $( '#' + current_gallery_id + ' .rtm-media-loading' ).length == 0 ) { - $( '#' + current_gallery_id + ' .rtm-pagination' ).before( '
      ' ); - } else { - $( '#' + current_gallery_id + ' .rtm-media-loading' ).show(); - } - - e.preventDefault(); - if ( $( this ).data( 'page-type' ) == 'page' ) { - nextpage = $( this ).data( 'page' ); - } else if ( $( this ).data( 'page-type' ) == 'prev' ) { - if ( nextpage == -1 ) { - nextpage = parseInt( $( '#' + current_gallery_id + ' #rtmedia_last_page' ).val() ) - 1; - } else { - nextpage -= 2; - } - } else if ( $( this ).data( 'page-type' ) == 'num' ) { - if ( parseInt( $( '#' + current_gallery_id + ' #rtmedia_go_to_num' ).val() ) > parseInt( $( '#rtmedia_last_page' ).val() ) ) { - nextpage = parseInt( $( '#' + current_gallery_id + ' #rtmedia_last_page' ).val() ); - } else { - nextpage = parseInt( $( '#' + current_gallery_id + ' #rtmedia_go_to_num' ).val() ); - } - - /* Set page url for input type num pagination */ - page_base_url = $( this ).data( 'page-base-url' ); - href = page_base_url + nextpage; - } - - var media_search_input = $( '#media_search_input' ); - if( check_condition( 'search' ) ) { - if ( media_search_input.length > 0 && '' !== media_search_input.val() ) { - var search_val = check_url( 'search' ); - href += '?search=' + search_val; - - if( check_condition( 'search_by' ) ) { - var search_by = check_url( 'search_by' ); - href += '&search_by=' + search_by; - } - } - } - - change_rtBrowserAddressUrl( href, '' ); - galleryObj.getNext( nextpage, $( this ).closest( '.rtmedia-container' ).parent(), $( this ).closest( '.rtm-pagination' ) ); - } ); - - $( document ).on( 'submit', 'form#media_search_form', function( e ) { - e.preventDefault(); - - var $media_search_input = $( '#media_search_input' ).val(); - var $media_search = $( '#media_search' ); - var $media_fatch_loader = $( '#media_fatch_loader' ); - var $media_type = $( 'input[type="hidden"][name="media_type"]' ); - - if ( '' === $media_search_input ) { - return false; - } - - $media_search.css( 'cursor', 'pointer'); - $media_fatch_loader.addClass('load'); - nextpage = 1; - - var href = window.location.href; - // Remove query string. - if ( href.indexOf('?') > -1) { - href = window.location.pathname; - } - - href += '?search=' + $media_search_input; - if ( $( '#search_by' ).length > 0 ) { - href += '&search_by=' + $( '#search_by' ).val(); - } - - if ( $media_type.length > 0 && 'album' === $media_type.val() ) { - href += '&media_type=' + $media_type.val(); - } - - href = encodeURI( href ); - - change_rtBrowserAddressUrl( href, '' ); - galleryObj.getNext( nextpage, $( this ).closest( '.rtmedia-container' ).parent() ); - - $( '#media_search_remove' ).show(); - } ); - - // media search remove - $( document ).on( 'click', '#media_search_remove', function( e ) { - $( '#media_search' ).css( 'cursor', 'not-allowed'); - $( '#media_fatch_loader' ).addClass('load'); - jQuery( '#media_search_input' ).val(''); - nextpage = 1; - var href = window.location.pathname; - if ( check_condition( '/pg' ) ) { - remove_index = href.indexOf('pg'); - remove_href = href.substring( remove_index ); - href = href.replace( remove_href, '' ); - } - - change_rtBrowserAddressUrl( href, '' ); - galleryObj.getNext( nextpage, $( this ).parent().parent().parent().parent().parent()); - $( '#media_search_remove' ).hide(); - } ); - - if ( window.location.pathname.indexOf( rtmedia_media_slug ) != -1 ) { - var tempNext = window.location.pathname.substring( window.location.pathname.lastIndexOf( 'pg/' ) + 5, window.location.pathname.lastIndexOf( '/' ) ); - if ( isNaN( tempNext ) === false ) { - nextpage = parseInt( tempNext ) + 1; - } - } - - window.UploadView = Backbone.View.extend( { - events: { - 'click #rtMedia-start-upload': 'uploadFiles' - }, - initialize: function( config ) { - this.uploader = new plupload.Uploader( config ); - /* - * 'ext_enabled' will get value of enabled media types if nothing is enabled, - * then an error message will be displayed. - */ - var ext_enabled = config.filters[0].extensions.length; - if ( ext_enabled === 0 ) { - this.uploader.bind( 'Browse', function( up ) { - rtmedia_gallery_action_alert_message( rtmedia_media_disabled_error_message, 'warning' ); - } ); - } - }, - render: function() { - - }, - initUploader: function( a ) { - if ( typeof ( a ) !== 'undefined' ) { - a = false;// If rtmediapro widget calls the function, dont show max size note. - } this.uploader.init(); - //The plupload HTML5 code gives a negative z-index making add files button unclickable - $( '.plupload.html5' ).css( { - zIndex: 0 - } ); - $( '#rtMedia-upload-button' ).css( { - zIndex: 2 - } ); - if ( a !== false ) { - window.file_size_info = rtmedia_max_file_msg + this.uploader.settings.max_file_size_msg; - if ( rtmedia_version_compare( rtm_wp_version, '3.9' ) ) { // Plupload getting updated in 3.9 - file_extn = this.uploader.settings.filters.mime_types[0].extensions; - } else { - file_extn = this.uploader.settings.filters[0].extensions; - } - window.file_extn_info = rtmedia_allowed_file_formats + ' : ' + file_extn.split( ',' ).join( ', ' ); - - var info = window.file_size_info + '\n' + window.file_extn_info; - $( '.rtm-file-size-limit' ).attr( 'title', info ); - //$("#rtMedia-upload-button").after("( " + rtmedia_max_file_msg + " "+ this.uploader.settings.max_file_size_msg + ")"); - } - - return this; - }, - uploadFiles: function( e ) { - if ( e != undefined ) { - e.preventDefault(); - } - this.uploader.start(); - return false; - } - - } ); - - if ( $( '#rtMedia-upload-button' ).length > 0 ) { - if ( typeof rtmedia_upload_type_filter == 'object' && rtmedia_upload_type_filter.length > 0 ) { - rtMedia_plupload_config.filters[0].extensions = rtmedia_upload_type_filter.join(); - } - uploaderObj = new UploadView( rtMedia_plupload_config ); - uploaderObj.initUploader(); - - var rtnObj = ''; - var redirect_request = false; - - jQuery( document ).ajaxComplete(function() { - if( redirect_request ) { - redirect_request = false; - window.location = rtnObj.redirect_url; - } - }); - - uploaderObj.uploader.bind( 'UploadComplete', function( up, files ) { - - activity_id = -1; - var hook_respo = rtMediaHook.call( 'rtmedia_js_after_files_uploaded' ); - if ( typeof rtmedia_gallery_reload_on_upload != 'undefined' && rtmedia_gallery_reload_on_upload == '1' ) { //Reload gallery view when upload completes if enabled( by default enabled) - if ( hook_respo != false ) { - galleryObj.reloadView(); - } - } - jQuery( '#rtmedia_uploader_filelist li.plupload_queue_li' ).remove(); - jQuery( '.start-media-upload' ).hide(); - apply_rtMagnificPopup( jQuery( '.rtmedia-list-media, .rtmedia-activity-container ul.rtmedia-list, #bp-media-list,.widget-item-listing,.bp-media-sc-list, li.media.album_updated ul,ul.bp-media-list-media, li.activity-item div.activity-content div.activity-inner div.bp_media_content' ) ); - - var redirection = $( '#rt_upload_hf_redirect' ); - - if( '' !== rtnObj && 'undefined' !== typeof( rtnObj.redirect_url ) && null !== rtnObj.redirect_url ) { - if ( uploaderObj.upload_count === up.files.length - && 0 < redirection.length - && 'true' === redirection.val() - && 0 === rtnObj.redirect_url.indexOf( 'http' ) ) { - redirect_request = true; - } - } - - window.onbeforeunload = null; - } ); - - uploaderObj.uploader.bind( 'FilesAdded', function( up, files ) { - var upload_size_error = false; - var upload_error = ''; - var upload_error_sep = ''; - var upload_remove_array = [ ]; - - var select_btn = jQuery( '.rtmedia-upload-input' ); - var upload_start_btn = jQuery('.start-media-upload'); - - $.each( files, function( i, file ) { - //Set file title along with file - rtm_file_name_array = file.name.split( '.' ); - file.title = rtm_file_name_array[0]; - - var hook_respo = rtMediaHook.call( 'rtmedia_js_file_added', [ up, file, '#rtmedia_uploader_filelist' ] ); - - if ( hook_respo == false ) { - file.status = -1; - upload_remove_array.push( file.id ); - return true; - } - - select_btn.attr( 'value', rtmedia_add_more_files_msg ); - if ( typeof rtmedia_direct_upload_enabled != 'undefined' && rtmedia_direct_upload_enabled == '1' ) { - upload_start_btn.hide(); - } else { - upload_start_btn.show(); - } - if ( uploaderObj.uploader.settings.max_file_size < file.size ) { - return true; - } - var tmp_array = file.name.split( '.' ); - if ( rtmedia_version_compare( rtm_wp_version, '3.9' ) ) { // Plupload getting updated in 3.9 - var ext_array = uploaderObj.uploader.settings.filters.mime_types[0].extensions.split( ',' ); - } else { - var ext_array = uploaderObj.uploader.settings.filters[0].extensions.split( ',' ); - } - if ( tmp_array.length > 1 ) { - var ext = tmp_array[tmp_array.length - 1]; - ext = ext.toLowerCase(); - if ( jQuery.inArray( ext, ext_array ) === -1 ) { - return true; - } - } else { - return true; - } - - if ( rtmedia_version_compare( rtm_wp_version, '3.9' ) ) { // Plupload getting updated in 3.9 - uploaderObj.uploader.settings.filters.mime_types[0].title; - } else { - uploaderObj.uploader.settings.filters[0].title; - } - - // Creating list of media to preview selected files - rtmedia_selected_file_list( plupload, file, '', '' ); - - //Delete Function - $( '#' + file.id + ' .plupload_delete .remove-from-queue' ).click( function( e ) { - e.preventDefault(); - uploaderObj.uploader.removeFile( up.getFile( file.id ) ); - $( '#' + file.id ).remove(); - rtMediaHook.call( 'rtmedia_js_file_remove', [ up, file ] ); - return false; - } ); - - // To change the name of the uploading file - $( '#label_' + file.id ).click( function( e ) { - e.preventDefault(); - - rtm_file_label = this; - - rtm_file_title_id = 'text_' + file.id; - rtm_file_title_input = '#' + rtm_file_title_id; - rtm_file_title_wrapper_id = 'rtm_title_wp_' + file.id; - rtm_file_title_wrapper = '#' + rtm_file_title_wrapper_id; - - rtm_file_desc_id = 'rtm_desc_' + file.id; - rtm_file_desc_input = '#' + rtm_file_desc_id; - rtm_file_desc_wrapper_id = 'rtm_desc_wp_' + file.id; - rtm_file_desc_wrapper = '#' + rtm_file_desc_wrapper_id; - - rtm_file_save_id = 'save_' + file.id; - rtm_file_save_el = '#' + rtm_file_save_id; - - jQuery( rtm_file_label ).hide(); - jQuery( rtm_file_label ).siblings( '.plupload_file_name_wrapper' ).hide(); - - // Show/create text box to edit media title - if ( jQuery( rtm_file_title_input ).length === 0 ) { - jQuery( rtm_file_label ).parent( '.plupload_file_name' ).prepend( '
      ' ); - } else { - jQuery( rtm_file_title_wrapper ).show(); - jQuery( rtm_file_desc_wrapper ).show(); - jQuery( rtm_file_save_el ).show(); - } - - jQuery( rtm_file_title_input ).focus(); - - // Set media title and description in file object - $( '#save_' + file.id ).click( function( e ) { - e.preventDefault(); - - rtm_file_label = this; - - rtm_file_title_id = 'text_' + file.id; - rtm_file_title_input = '#' + rtm_file_title_id; - rtm_file_title_wrapper_id = 'rtm_title_wp_' + file.id; - rtm_file_title_wrapper = '#' + rtm_file_title_wrapper_id; - - rtm_file_desc_id = 'rtm_desc_' + file.id; - rtm_file_desc_input = '#' + rtm_file_desc_id; - rtm_file_desc_wrapper_id = 'rtm_desc_wp_' + file.id; - rtm_file_desc_wrapper = '#' + rtm_file_desc_wrapper_id; - - rtm_file_save_id = 'save_' + file.id; - rtm_file_save_el = '#' + rtm_file_save_id; - - var file_title_val = jQuery( rtm_file_title_input ).val(); - var file_desc_val = jQuery( rtm_file_desc_input ).val(); - var file_name_wrapper_el = jQuery( rtm_file_label ).siblings( '.plupload_file_name_wrapper' ); - - if ( '' !== file_title_val.trim() ) { - var extension = file.name.split( '.' )[1]; - file_name_wrapper_el.text( file_title_val + '.' + extension ); - file.title = file_title_val; - } - - if ( file_desc_val != '' ) { - file.description = file_desc_val; - } - - jQuery( rtm_file_title_wrapper ).hide(); - jQuery( rtm_file_desc_wrapper ).hide(); - - file_name_wrapper_el.show(); - jQuery( rtm_file_label ).siblings( '#label_' + file.id ).show(); - jQuery( this ).hide(); - } ); - } ); - } ); - - $.each( upload_remove_array, function( i, rfile ) { - if ( up.getFile( rfile ) ) { - up.removeFile( up.getFile( rfile ) ); - } - } ); - - rtMediaHook.call( 'rtmedia_js_after_files_added', [ up, files ] ); - - if ( typeof rtmedia_direct_upload_enabled != 'undefined' && rtmedia_direct_upload_enabled == '1' ) { - var allow_upload = rtMediaHook.call( 'rtmedia_js_upload_file', { src: 'uploader' } ); - if ( allow_upload == false ) { - return false; - } - uploaderObj.uploadFiles(); - } - - upload_start_btn.focus(); - - } ); - - uploaderObj.uploader.bind( 'Error', function( up, err ) { - - if ( err.code == -600 ) { //File size error // if file size is greater than server's max allowed size - var tmp_array; - var ext = tr = ''; - tmp_array = err.file.name.split( '.' ); - if ( tmp_array.length > 1 ) { - ext = tmp_array[tmp_array.length - 1]; - if ( ! ( typeof ( up.settings.upload_size ) != 'undefined' && typeof ( up.settings.upload_size[ext] ) != 'undefined' && typeof ( up.settings.upload_size[ext]['size'] ) ) ) { - rtmedia_selected_file_list( plupload, err.file, up, err ); - } - } - } else { - - if ( err.code == -601 ) { // File extension error - err.message = rtmedia_file_extension_error_msg; - } - - rtmedia_selected_file_list( plupload, err.file, '', err ); - } - - jQuery( '.plupload_delete' ).on( 'click', function( e ) { - e.preventDefault(); - jQuery( this ).parent().parent( 'li' ).remove(); - } ); - return false; - - } ); - - jQuery( '.start-media-upload' ).on( 'click', function( e ) { - e.preventDefault(); - // Make search box blank while uploading a media. So that newly uploaded media can be shown after upload. - var search_box = jQuery( '#media_search_input' ); - if ( search_box.length > 0 ) { - search_box.val(''); - } - - /** - * To check if any media file is selected or not for uploading - */ - if ( jQuery( '#rtmedia_uploader_filelist' ).children( 'li' ).length > 0 ) { - var allow_upload = rtMediaHook.call( 'rtmedia_js_upload_file', { src: 'uploader' } ); - - if ( allow_upload == false ) { - return false; - } - uploaderObj.uploadFiles(); - } - } ); - - uploaderObj.uploader.bind( 'UploadProgress', function( up, file ) { - //$("#" + file.id + " .plupload_file_status").html(file.percent + "%"); - //$( "#" + file.id + " .plupload_file_status" ).html( rtmedia_uploading_msg + '( ' + file.percent + '% )' ); - // creates a progress bar to display file upload status - var progressBar = jQuery( '
      ', { - 'class': 'plupload_file_progress ui-widget-header', - }); - progressBar.css( 'width', file.percent + '%' ); - $( '#' + file.id + ' .plupload_file_status' ).html( progressBar ); - // filter to customize existing progress bar can be used to display - // '%' of upload completed. - rtMediaHook.call( 'rtm_custom_progress_bar_content', [ file ] ); - $( '#' + file.id ).addClass( 'upload-progress' ); - if ( file.percent == 100 ) { - $( '#' + file.id ).toggleClass( 'upload-success' ); - } - - window.onbeforeunload = function( evt ) { - var message = rtmedia_upload_progress_error_message; - return message; - }; - } ); - - uploaderObj.uploader.bind( 'BeforeUpload', function( up, file ) { - // We send terms conditions data on backend to validate this on server side. - rtMediaHook.call( 'rtmedia_js_before_upload', { uploader: up, file: file, src: 'uploader' } ); - - up.settings.multipart_params.title = file.title.split( '.' )[ 0 ]; - - if ( typeof file.description != 'undefined' ) { - up.settings.multipart_params.description = file.description; - } else { - up.settings.multipart_params.description = ''; - } - - var privacy = $( '#rtm-file_upload-ui select.privacy' ).val(); - if ( privacy !== undefined ) { - up.settings.multipart_params.privacy = $( '#rtm-file_upload-ui select.privacy' ).val(); - } - - var redirection = $( '#rt_upload_hf_redirect' ); - - if ( 0 < redirection.length ) { - up.settings.multipart_params.redirect = up.files.length; - up.settings.multipart_params.redirection = redirection.val(); - } - jQuery( '#rtmedia-uploader-form input[type=hidden]' ).each( function() { - up.settings.multipart_params[$( this ).attr( 'name' )] = $( this ).val(); - } ); - up.settings.multipart_params.activity_id = activity_id; - if ( $( '#rtmedia-uploader-form .rtmedia-user-album-list' ).length > 0 ) { - up.settings.multipart_params.album_id = $( '#rtmedia-uploader-form .rtmedia-user-album-list' ).find( ':selected' ).val(); - } else if ( $( '#rtmedia-uploader-form .rtmedia-current-album' ).length > 0 ) { - up.settings.multipart_params.album_id = $( '#rtmedia-uploader-form .rtmedia-current-album' ).val(); - } - - rtMediaHook.call( 'rtmedia_js_before_file_upload', [up, file] ); - } ); - - uploaderObj.uploader.bind( 'FileUploaded', function( up, file, res ) { - if ( /MSIE (\d+\.\d+);/.test( navigator.userAgent ) ) { //Test for MSIE x.x; - var ieversion = new Number( RegExp.$1 ); // Capture x.x portion and store as a number - - if ( ieversion < 10 ) { - if ( typeof res.response !== 'undefined' ) { - res.status = 200; - } - } - } - - try { - - rtnObj = JSON.parse( res.response ); - uploaderObj.uploader.settings.multipart_params.activity_id = rtnObj.activity_id; - activity_id = rtnObj.activity_id; - if ( rtnObj.permalink != '' ) { - $( "#" + file.id + " .plupload_file_name" ).html( "" + file.title.substring( 0, 40 ).replace( /(<([^>]+)>)/ig, "" ) + "" ); - $( "#" + file.id + " .plupload_media_edit" ).html( " " + rtmedia_edit + "" ); - $( "#" + file.id + " .plupload_delete" ).html( "" ); - } - - } catch ( e ) { - // Console.log('Invalid Activity ID'); - } - if ( res.status == 200 || res.status == 302 ) { - if ( uploaderObj.upload_count == undefined ) { - uploaderObj.upload_count = 1; - } else { - uploaderObj.upload_count++; - } - - rtMediaHook.call( 'rtmedia_js_after_file_upload', [ up, file, res.response ] ); - } else { - $( '#' + file.id + ' .plupload_file_status' ).html( rtmedia_upload_failed_msg ); - } - - files = up.files; - lastfile = files[files.length - 1]; - - } ); - - uploaderObj.uploader.refresh();//Refresh the uploader for opera/IE fix on media page - - $( '#rtMedia-start-upload' ).click( function( e ) { - uploaderObj.uploadFiles( e ); - } ); - $( '#rtMedia-start-upload' ).hide(); - - jQuery( document ).on( 'click', '#rtm_show_upload_ui', function() { - jQuery( '#rtm-media-gallery-uploader' ).slideToggle(); - uploaderObj.uploader.refresh();//Refresh the uploader for opera/IE fix on media page - jQuery( '#rtm_show_upload_ui' ).toggleClass( 'primary' ); - } ); - } else { - jQuery( document ).on( 'click', '#rtm_show_upload_ui', function() { - /* - * 'enabled_ext' will get value of enabled media types if nothing is enabled, - * then an error message will be displayed. - */ - if ( 'object' === typeof rtMedia_plupload_config ) { - var enabled_ext = rtMedia_plupload_config.filters[0].extensions.length; - if ( 0 === enabled_ext ) { - // If no media type is enabled error message will be displayed. - rtmedia_gallery_action_alert_message( rtmedia_media_disabled_error_message, 'warning' ); - } - } - - jQuery( '#rtm-media-gallery-uploader' ).slideToggle(); - jQuery( '#rtm_show_upload_ui' ).toggleClass( 'primary' ); - } ); - } - - jQuery( document ).on( 'click', '.plupload_delete .rtmedia-delete-uploaded-media', function() { - var that = $( this ); - if ( confirm( rtmedia_delete_uploaded_media ) ) { - var nonce = $( '#rtmedia-upload-container #rtmedia_media_delete_nonce' ).val(); - var media_id = $( this ).attr( 'id' ); - var data = { - action: 'delete_uploaded_media', - nonce: nonce, - media_id: media_id - }; - - $.post( ajaxurl, data, function( response ) { - if ( response == '1' ) { - that.closest( 'tr' ).remove(); - $( '#' + media_id ).remove(); - } - } ); - } - } ); - -} ); + var media_search_input = $("#media_search_input"); + if (check_condition("search")) { + if (media_search_input.length > 0 && "" !== media_search_input.val()) { + var search_val = check_url("search"); + href += "?search=" + search_val; -/** Activity Update Js **/ + if (check_condition("search_by")) { + var search_by = check_url("search_by"); + href += "&search_by=" + search_by; + } + } + } -jQuery( document ).ready( function( $ ) { - - - /** - * Uploader improper enter behavior issue(124) fixed - * - * @param e - */ - var submit_function = function (e) { - /** - * Execute code only on enter key - */ - if (e.keyCode === 13) { - /** - * Prevent default behavior and fire custom click - */ - e.preventDefault(); - $(this).trigger('click'); - /** - * stop textarea from disabling - * @type {*|jQuery|HTMLElement} - */ - var textarea = $('#whats-new'); - textarea.removeAttr('disabled'); - /** - * set focus to textarea after buddypress timeout code - */ - setTimeout(function () { - textarea.focus(); - }, 200); - } - }; - /** - * End of issue 124 fix - */ - - /** - * UI changes for buddypress nouveau theme on activity page - */ - if ( bp_template_pack && 'legacy' !== bp_template_pack ) { - - var whats_new_form = jQuery( '#whats-new-form' ); - - jQuery( '#whats-new' ).on( 'focus', function () { - - var rt_uploader_div = whats_new_form.find( '.rtmedia-uploader-div' ); - var rt_uploader_filelist = whats_new_form.find( '#rtmedia_uploader_filelist' ); - var whats_new_option = whats_new_form.find( '#whats-new-options' ); - - rt_uploader_div.show(); - - if ( 0 !== whats_new_option.length ) { - whats_new_option.show(); - - whats_new_option.css( { - 'opacity': '1' - } ); - } - - rt_uploader_div.addClass( 'clearfix' ); - - whats_new_form.find( '#rtmedia-action-update' ).removeClass( 'clearfix' ); - - rt_uploader_filelist.addClass( 'clear-both' ); - rt_uploader_filelist.removeClass( 'clearfix' ); - } ); - - whats_new_form.bind( 'reset', function () { - whats_new_form.find( '.rtmedia-uploader-div' ).hide(); - } ); - - whats_new_form.bind( 'submit', function () { - window.onbeforeunload = null; - setTimeout( function () { - whats_new_form.find( '.rtmedia-uploader-div' ).hide(); - }, 2000 ); - } ); - } - /** - * End of UI changes - */ - - /* - * Fix for file selector does not open in Safari browser in IOS. - * In Safari in IOS, Plupload don't click on it's input(type=file), so file selector dialog won't open. - * In order to fix this, when rtMedia's attach media button is clicked, - * we check if Plupload's input(type=file) is clicked or not, if it's not clicked, then we click it manually - * to open file selector. - */ - - // Initially, select file dialog is close. - var file_dialog_open = false; - - var button = '#rtmedia-upload-container #rtMedia-upload-button'; - - var input_file_el = '#rtmedia-upload-container input[type=file]:first'; - - // Bind callback on Plupload's input element. - jQuery( document.body ).on( 'click', input_file_el, function() { - file_dialog_open = true; - } ); + change_rtBrowserAddressUrl(href, ""); + galleryObj.getNext( + nextpage, + $(this).closest(".rtmedia-container").parent(), + $(this).closest(".rtm-pagination") + ); + }); - // Bind callback on rtMedia's attach media button. - jQuery( document.body ).on( 'click', button, function() { - if ( false === file_dialog_open ) { - jQuery( input_file_el ).click(); - file_dialog_open = false; - } - } ); + $(document).on("submit", "form#media_search_form", function (e) { + e.preventDefault(); + + var $media_search_input = $("#media_search_input").val(); + var $media_search = $("#media_search"); + var $media_fatch_loader = $("#media_fatch_loader"); + var $media_type = $('input[type="hidden"][name="media_type"]'); + + if ("" === $media_search_input) { + return false; + } + + $media_search.css("cursor", "pointer"); + $media_fatch_loader.addClass("load"); + nextpage = 1; + + var href = window.location.href; + // Remove query string. + if (href.indexOf("?") > -1) { + href = window.location.pathname; + } + + href += "?search=" + $media_search_input; + if ($("#search_by").length > 0) { + href += "&search_by=" + $("#search_by").val(); + } + + if ($media_type.length > 0 && "album" === $media_type.val()) { + href += "&media_type=" + $media_type.val(); + } + + href = encodeURI(href); + + change_rtBrowserAddressUrl(href, ""); + galleryObj.getNext( + nextpage, + $(this).closest(".rtmedia-container").parent() + ); + + $("#media_search_remove").show(); + }); + + // media search remove + $(document).on("click", "#media_search_remove", function (e) { + $("#media_search").css("cursor", "not-allowed"); + $("#media_fatch_loader").addClass("load"); + jQuery("#media_search_input").val(""); + nextpage = 1; + var href = window.location.pathname; + if (check_condition("/pg")) { + remove_index = href.indexOf("pg"); + remove_href = href.substring(remove_index); + href = href.replace(remove_href, ""); + } + + change_rtBrowserAddressUrl(href, ""); + galleryObj.getNext( + nextpage, + $(this).parent().parent().parent().parent().parent() + ); + $("#media_search_remove").hide(); + }); + + if (window.location.pathname.indexOf(rtmedia_media_slug) != -1) { + var tempNext = window.location.pathname.substring( + window.location.pathname.lastIndexOf("pg/") + 5, + window.location.pathname.lastIndexOf("/") + ); + if (isNaN(tempNext) === false) { + nextpage = parseInt(tempNext) + 1; + } + } + + window.UploadView = Backbone.View.extend({ + events: { + "click #rtMedia-start-upload": "uploadFiles", + }, + initialize: function (config) { + this.uploader = new plupload.Uploader(config); + /* + * 'ext_enabled' will get value of enabled media types if nothing is enabled, + * then an error message will be displayed. + */ + var ext_enabled = config.filters[0].extensions.length; + if (ext_enabled === 0) { + this.uploader.bind("Browse", function (up) { + rtmedia_gallery_action_alert_message( + rtmedia_media_disabled_error_message, + "warning" + ); + }); + } + }, + render: function () {}, + initUploader: function (a) { + if (typeof a !== "undefined") { + a = false; // If rtmediapro widget calls the function, dont show max size note. + } + this.uploader.init(); + //The plupload HTML5 code gives a negative z-index making add files button unclickable + $(".plupload.html5").css({ + zIndex: 0, + }); + $("#rtMedia-upload-button").css({ + zIndex: 2, + }); + if (a !== false) { + window.file_size_info = + rtmedia_max_file_msg + this.uploader.settings.max_file_size_msg; + if (rtmedia_version_compare(rtm_wp_version, "3.9")) { + // Plupload getting updated in 3.9 + file_extn = this.uploader.settings.filters.mime_types[0].extensions; + } else { + file_extn = this.uploader.settings.filters[0].extensions; + } + window.file_extn_info = + rtmedia_allowed_file_formats + + " : " + + file_extn.split(",").join(", "); + + var info = window.file_size_info + "\n" + window.file_extn_info; + $(".rtm-file-size-limit").attr("title", info); + //$("#rtMedia-upload-button").after("( " + rtmedia_max_file_msg + " "+ this.uploader.settings.max_file_size_msg + ")"); + } + + return this; + }, + uploadFiles: function (e) { + if (e != undefined) { + e.preventDefault(); + } + this.uploader.start(); + return false; + }, + }); + + if ($("#rtMedia-upload-button").length > 0) { + if ( + typeof rtmedia_upload_type_filter == "object" && + rtmedia_upload_type_filter.length > 0 + ) { + rtMedia_plupload_config.filters[0].extensions = + rtmedia_upload_type_filter.join(); + } + uploaderObj = new UploadView(rtMedia_plupload_config); + uploaderObj.initUploader(); + + var rtnObj = ""; + var redirect_request = false; + + jQuery(document).ajaxComplete(function () { + if (redirect_request) { + redirect_request = false; + window.location = rtnObj.redirect_url; + } + }); + + uploaderObj.uploader.bind("UploadComplete", function (up, files) { + activity_id = -1; + var hook_respo = rtMediaHook.call("rtmedia_js_after_files_uploaded"); + if ( + typeof rtmedia_gallery_reload_on_upload != "undefined" && + rtmedia_gallery_reload_on_upload == "1" + ) { + //Reload gallery view when upload completes if enabled( by default enabled) + if (hook_respo != false) { + galleryObj.reloadView(); + } + } + jQuery("#rtmedia_uploader_filelist li.plupload_queue_li").remove(); + jQuery(".start-media-upload").hide(); + apply_rtMagnificPopup( + jQuery( + ".rtmedia-list-media, .rtmedia-activity-container ul.rtmedia-list, #bp-media-list,.widget-item-listing,.bp-media-sc-list, li.media.album_updated ul,ul.bp-media-list-media, li.activity-item div.activity-content div.activity-inner div.bp_media_content" + ) + ); + + var redirection = $("#rt_upload_hf_redirect"); + + if ( + "" !== rtnObj && + "undefined" !== typeof rtnObj.redirect_url && + null !== rtnObj.redirect_url + ) { + if ( + uploaderObj.upload_count === up.files.length && + 0 < redirection.length && + "true" === redirection.val() && + 0 === rtnObj.redirect_url.indexOf("http") + ) { + redirect_request = true; + } + } + + window.onbeforeunload = null; + }); + + uploaderObj.uploader.bind("FilesAdded", function (up, files) { + var upload_size_error = false; + var upload_error = ""; + var upload_error_sep = ""; + var upload_remove_array = []; + + var select_btn = jQuery(".rtmedia-upload-input"); + var upload_start_btn = jQuery(".start-media-upload"); + + $.each(files, function (i, file) { + //Set file title along with file + rtm_file_name_array = file.name.split("."); + file.title = rtm_file_name_array[0]; + + var hook_respo = rtMediaHook.call("rtmedia_js_file_added", [ + up, + file, + "#rtmedia_uploader_filelist", + ]); + + if (hook_respo == false) { + file.status = -1; + upload_remove_array.push(file.id); + return true; + } + + select_btn.attr("value", rtmedia_add_more_files_msg); + if ( + typeof rtmedia_direct_upload_enabled != "undefined" && + rtmedia_direct_upload_enabled == "1" + ) { + upload_start_btn.hide(); + } else { + upload_start_btn.show(); + } + if (uploaderObj.uploader.settings.max_file_size < file.size) { + return true; + } + var tmp_array = file.name.split("."); + if (rtmedia_version_compare(rtm_wp_version, "3.9")) { + // Plupload getting updated in 3.9 + var ext_array = + uploaderObj.uploader.settings.filters.mime_types[0].extensions.split( + "," + ); + } else { + var ext_array = + uploaderObj.uploader.settings.filters[0].extensions.split(","); + } + if (tmp_array.length > 1) { + var ext = tmp_array[tmp_array.length - 1]; + ext = ext.toLowerCase(); + if (jQuery.inArray(ext, ext_array) === -1) { + return true; + } + } else { + return true; + } + + if (rtmedia_version_compare(rtm_wp_version, "3.9")) { + // Plupload getting updated in 3.9 + uploaderObj.uploader.settings.filters.mime_types[0].title; + } else { + uploaderObj.uploader.settings.filters[0].title; + } + + // Creating list of media to preview selected files + rtmedia_selected_file_list(plupload, file, "", ""); + + //Delete Function + $("#" + file.id + " .plupload_delete .remove-from-queue").click( + function (e) { + e.preventDefault(); + uploaderObj.uploader.removeFile(up.getFile(file.id)); + $("#" + file.id).remove(); + rtMediaHook.call("rtmedia_js_file_remove", [up, file]); + return false; + } + ); + + // To change the name of the uploading file + $("#label_" + file.id).click(function (e) { + e.preventDefault(); + + rtm_file_label = this; + + rtm_file_title_id = "text_" + file.id; + rtm_file_title_input = "#" + rtm_file_title_id; + rtm_file_title_wrapper_id = "rtm_title_wp_" + file.id; + rtm_file_title_wrapper = "#" + rtm_file_title_wrapper_id; + + rtm_file_desc_id = "rtm_desc_" + file.id; + rtm_file_desc_input = "#" + rtm_file_desc_id; + rtm_file_desc_wrapper_id = "rtm_desc_wp_" + file.id; + rtm_file_desc_wrapper = "#" + rtm_file_desc_wrapper_id; + + rtm_file_save_id = "save_" + file.id; + rtm_file_save_el = "#" + rtm_file_save_id; + + jQuery(rtm_file_label).hide(); + jQuery(rtm_file_label).siblings(".plupload_file_name_wrapper").hide(); + + // Show/create text box to edit media title + if (jQuery(rtm_file_title_input).length === 0) { + jQuery(rtm_file_label) + .parent(".plupload_file_name") + .prepend( + '
      ' + ); + } else { + jQuery(rtm_file_title_wrapper).show(); + jQuery(rtm_file_desc_wrapper).show(); + jQuery(rtm_file_save_el).show(); + } + + jQuery(rtm_file_title_input).focus(); + + // Set media title and description in file object + $("#save_" + file.id).click(function (e) { + e.preventDefault(); + + rtm_file_label = this; + + rtm_file_title_id = "text_" + file.id; + rtm_file_title_input = "#" + rtm_file_title_id; + rtm_file_title_wrapper_id = "rtm_title_wp_" + file.id; + rtm_file_title_wrapper = "#" + rtm_file_title_wrapper_id; + + rtm_file_desc_id = "rtm_desc_" + file.id; + rtm_file_desc_input = "#" + rtm_file_desc_id; + rtm_file_desc_wrapper_id = "rtm_desc_wp_" + file.id; + rtm_file_desc_wrapper = "#" + rtm_file_desc_wrapper_id; + + rtm_file_save_id = "save_" + file.id; + rtm_file_save_el = "#" + rtm_file_save_id; + + var file_title_val = jQuery(rtm_file_title_input).val(); + var file_desc_val = jQuery(rtm_file_desc_input).val(); + var file_name_wrapper_el = jQuery(rtm_file_label).siblings( + ".plupload_file_name_wrapper" + ); + + if ("" !== file_title_val.trim()) { + var extension = file.name.split(".")[1]; + file_name_wrapper_el.text(file_title_val + "." + extension); + file.title = file_title_val; + } + + if (file_desc_val != "") { + file.description = file_desc_val; + } + + jQuery(rtm_file_title_wrapper).hide(); + jQuery(rtm_file_desc_wrapper).hide(); - // Handling the "post update: button on activity page - /** - * Commented by : Naveen giri - * Reason : Commenting this code because its overriding buddypress functionality - * and introducing issue Duplicate activity generation Issue #108. - */ - /*JQuery( '#aw-whats-new-submit' ).removeAttr( 'disabled' ); + file_name_wrapper_el.show(); + jQuery(rtm_file_label) + .siblings("#label_" + file.id) + .show(); + jQuery(this).hide(); + }); + }); + }); + + $.each(upload_remove_array, function (i, rfile) { + if (up.getFile(rfile)) { + up.removeFile(up.getFile(rfile)); + } + }); + + rtMediaHook.call("rtmedia_js_after_files_added", [up, files]); + + if ( + typeof rtmedia_direct_upload_enabled != "undefined" && + rtmedia_direct_upload_enabled == "1" + ) { + var allow_upload = rtMediaHook.call("rtmedia_js_upload_file", { + src: "uploader", + }); + if (allow_upload == false) { + return false; + } + uploaderObj.uploadFiles(); + } + + upload_start_btn.focus(); + }); + + uploaderObj.uploader.bind("Error", function (up, err) { + if (err.code == -600) { + //File size error // if file size is greater than server's max allowed size + var tmp_array; + var ext = (tr = ""); + tmp_array = err.file.name.split("."); + if (tmp_array.length > 1) { + ext = tmp_array[tmp_array.length - 1]; + if ( + !( + typeof up.settings.upload_size != "undefined" && + typeof up.settings.upload_size[ext] != "undefined" && + typeof up.settings.upload_size[ext]["size"] + ) + ) { + rtmedia_selected_file_list(plupload, err.file, up, err); + } + } + } else { + if (err.code == -601) { + // File extension error + err.message = rtmedia_file_extension_error_msg; + } + + rtmedia_selected_file_list(plupload, err.file, "", err); + } + + jQuery(".plupload_delete").on("click", function (e) { + e.preventDefault(); + jQuery(this).parent().parent("li").remove(); + }); + return false; + }); + + jQuery(".start-media-upload").on("click", function (e) { + e.preventDefault(); + // Make search box blank while uploading a media. So that newly uploaded media can be shown after upload. + var search_box = jQuery("#media_search_input"); + if (search_box.length > 0) { + search_box.val(""); + } + + /** + * To check if any media file is selected or not for uploading + */ + if (jQuery("#rtmedia_uploader_filelist").children("li").length > 0) { + var allow_upload = rtMediaHook.call("rtmedia_js_upload_file", { + src: "uploader", + }); + + if (allow_upload == false) { + return false; + } + uploaderObj.uploadFiles(); + } + }); + + uploaderObj.uploader.bind("UploadProgress", function (up, file) { + //$("#" + file.id + " .plupload_file_status").html(file.percent + "%"); + //$( "#" + file.id + " .plupload_file_status" ).html( rtmedia_uploading_msg + '( ' + file.percent + '% )' ); + // creates a progress bar to display file upload status + var progressBar = jQuery("
      ", { + class: "plupload_file_progress ui-widget-header", + }); + progressBar.css("width", file.percent + "%"); + $("#" + file.id + " .plupload_file_status").html(progressBar); + // filter to customize existing progress bar can be used to display + // '%' of upload completed. + rtMediaHook.call("rtm_custom_progress_bar_content", [file]); + $("#" + file.id).addClass("upload-progress"); + if (file.percent == 100) { + $("#" + file.id).toggleClass("upload-success"); + } + + window.onbeforeunload = function (evt) { + var message = rtmedia_upload_progress_error_message; + return message; + }; + }); + + uploaderObj.uploader.bind("BeforeUpload", function (up, file) { + // We send terms conditions data on backend to validate this on server side. + rtMediaHook.call("rtmedia_js_before_upload", { + uploader: up, + file: file, + src: "uploader", + }); + + up.settings.multipart_params.title = file.title.split(".")[0]; + + if (typeof file.description != "undefined") { + up.settings.multipart_params.description = file.description; + } else { + up.settings.multipart_params.description = ""; + } + + var privacy = $("#rtm-file_upload-ui select.privacy").val(); + if (privacy !== undefined) { + up.settings.multipart_params.privacy = $( + "#rtm-file_upload-ui select.privacy" + ).val(); + } + + var redirection = $("#rt_upload_hf_redirect"); + + if (0 < redirection.length) { + up.settings.multipart_params.redirect = up.files.length; + up.settings.multipart_params.redirection = redirection.val(); + } + jQuery("#rtmedia-uploader-form input[type=hidden]").each(function () { + up.settings.multipart_params[$(this).attr("name")] = $(this).val(); + }); + up.settings.multipart_params.activity_id = activity_id; + if ($("#rtmedia-uploader-form .rtmedia-user-album-list").length > 0) { + up.settings.multipart_params.album_id = $( + "#rtmedia-uploader-form .rtmedia-user-album-list" + ) + .find(":selected") + .val(); + } else if ( + $("#rtmedia-uploader-form .rtmedia-current-album").length > 0 + ) { + up.settings.multipart_params.album_id = $( + "#rtmedia-uploader-form .rtmedia-current-album" + ).val(); + } + + rtMediaHook.call("rtmedia_js_before_file_upload", [up, file]); + }); + + uploaderObj.uploader.bind("FileUploaded", function (up, file, res) { + if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { + //Test for MSIE x.x; + var ieversion = new Number(RegExp.$1); // Capture x.x portion and store as a number + + if (ieversion < 10) { + if (typeof res.response !== "undefined") { + res.status = 200; + } + } + } + + try { + rtnObj = JSON.parse(res.response); + uploaderObj.uploader.settings.multipart_params.activity_id = + rtnObj.activity_id; + activity_id = rtnObj.activity_id; + if (rtnObj.permalink != "") { + $("#" + file.id + " .plupload_file_name").html( + "" + + file.title.substring(0, 40).replace(/(<([^>]+)>)/gi, "") + + "" + ); + $("#" + file.id + " .plupload_media_edit").html( + " " + + rtmedia_edit + + "" + ); + $("#" + file.id + " .plupload_delete").html( + "" + ); + } + } catch (e) { + // Console.log('Invalid Activity ID'); + } + if (res.status == 200 || res.status == 302) { + if (uploaderObj.upload_count == undefined) { + uploaderObj.upload_count = 1; + } else { + uploaderObj.upload_count++; + } + + rtMediaHook.call("rtmedia_js_after_file_upload", [ + up, + file, + res.response, + ]); + } else { + $("#" + file.id + " .plupload_file_status").html( + rtmedia_upload_failed_msg + ); + } + + files = up.files; + lastfile = files[files.length - 1]; + }); + + uploaderObj.uploader.refresh(); //Refresh the uploader for opera/IE fix on media page + + $("#rtMedia-start-upload").click(function (e) { + uploaderObj.uploadFiles(e); + }); + $("#rtMedia-start-upload").hide(); + + jQuery(document).on("click", "#rtm_show_upload_ui", function () { + jQuery("#rtm-media-gallery-uploader").slideToggle(); + uploaderObj.uploader.refresh(); //Refresh the uploader for opera/IE fix on media page + jQuery("#rtm_show_upload_ui").toggleClass("primary"); + }); + } else { + jQuery(document).on("click", "#rtm_show_upload_ui", function () { + /* + * 'enabled_ext' will get value of enabled media types if nothing is enabled, + * then an error message will be displayed. + */ + if ("object" === typeof rtMedia_plupload_config) { + var enabled_ext = rtMedia_plupload_config.filters[0].extensions.length; + if (0 === enabled_ext) { + // If no media type is enabled error message will be displayed. + rtmedia_gallery_action_alert_message( + rtmedia_media_disabled_error_message, + "warning" + ); + } + } + + jQuery("#rtm-media-gallery-uploader").slideToggle(); + jQuery("#rtm_show_upload_ui").toggleClass("primary"); + }); + } + + jQuery(document).on( + "click", + ".plupload_delete .rtmedia-delete-uploaded-media", + function () { + var that = $(this); + if (confirm(rtmedia_delete_uploaded_media)) { + var nonce = $( + "#rtmedia-upload-container #rtmedia_media_delete_nonce" + ).val(); + var media_id = $(this).attr("id"); + var data = { + action: "delete_uploaded_media", + nonce: nonce, + media_id: media_id, + }; + + $.post(ajaxurl, data, function (response) { + if (response == "1") { + that.closest("tr").remove(); + $("#" + media_id).remove(); + } + }); + } + } + ); +}); + +/** Activity Update Js **/ + +jQuery(document).ready(function ($) { + /** + * Uploader improper enter behavior issue(124) fixed + * + * @param e + */ + var submit_function = function (e) { + /** + * Execute code only on enter key + */ + if (e.keyCode === 13) { + /** + * Prevent default behavior and fire custom click + */ + e.preventDefault(); + $(this).trigger("click"); + /** + * stop textarea from disabling + * @type {*|jQuery|HTMLElement} + */ + var textarea = $("#whats-new"); + textarea.removeAttr("disabled"); + /** + * set focus to textarea after buddypress timeout code + */ + setTimeout(function () { + textarea.focus(); + }, 200); + } + }; + /** + * End of issue 124 fix + */ + + /** + * UI changes for buddypress nouveau theme on activity page + */ + if (bp_template_pack && "legacy" !== bp_template_pack) { + var whats_new_form = jQuery("#whats-new-form"); + + jQuery("#whats-new").on("focus", function () { + var rt_uploader_div = whats_new_form.find(".rtmedia-uploader-div"); + var rt_uploader_filelist = whats_new_form.find( + "#rtmedia_uploader_filelist" + ); + var whats_new_option = whats_new_form.find("#whats-new-options"); + + rt_uploader_div.show(); + + if (0 !== whats_new_option.length) { + whats_new_option.show(); + + whats_new_option.css({ + opacity: "1", + }); + } + + rt_uploader_div.addClass("clearfix"); + + whats_new_form.find("#rtmedia-action-update").removeClass("clearfix"); + + rt_uploader_filelist.addClass("clear-both"); + rt_uploader_filelist.removeClass("clearfix"); + }); + + whats_new_form.on("reset", function () { + whats_new_form.find(".rtmedia-uploader-div").hide(); + }); + + whats_new_form.on("submit", function () { + window.onbeforeunload = null; + setTimeout(function () { + whats_new_form.find(".rtmedia-uploader-div").hide(); + }, 2000); + }); + } + /** + * End of UI changes + */ + + /* + * Fix for file selector does not open in Safari browser in IOS. + * In Safari in IOS, Plupload don't click on it's input(type=file), so file selector dialog won't open. + * In order to fix this, when rtMedia's attach media button is clicked, + * we check if Plupload's input(type=file) is clicked or not, if it's not clicked, then we click it manually + * to open file selector. + */ + + // Initially, select file dialog is close. + var file_dialog_open = false; + + var button = "#rtmedia-upload-container #rtMedia-upload-button"; + + var input_file_el = "#rtmedia-upload-container input[type=file]:first"; + + // Bind callback on Plupload's input element. + jQuery(document.body).on("click", input_file_el, function () { + file_dialog_open = true; + }); + + // Bind callback on rtMedia's attach media button. + jQuery(document.body).on("click", button, function () { + if (false === file_dialog_open) { + jQuery(input_file_el).click(); + file_dialog_open = false; + } + }); + + // Handling the "post update: button on activity page + /** + * Commented by : Naveen giri + * Reason : Commenting this code because its overriding buddypress functionality + * and introducing issue Duplicate activity generation Issue #108. + */ + /*JQuery( '#aw-whats-new-submit' ).removeAttr( 'disabled' ); jQuery( document ).on( 'blur', '#whats-new', function() { setTimeout( function() { jQuery( '#aw-whats-new-submit' ).removeAttr( 'disabled' ); @@ -1196,1015 +1460,1233 @@ jQuery( document ).ready( function( $ ) { }, 100 ); } );*/ - // When user changes the value in activity "post in" dropdown, hide the privacy dropdown and show when posting in profile. - jQuery( '#whats-new-post-in' ).on( 'change', function( e ) { - if ( jQuery( this ).val() == '0' ) { - jQuery( '#whats-new-form #rtmedia-action-update .privacy' ).prop( 'disabled', false ).show(); - } else { - jQuery( '#whats-new-form #rtmedia-action-update .privacy' ).prop( 'disabled', true ).hide(); - } - } ); + // When user changes the value in activity "post in" dropdown, hide the privacy dropdown and show when posting in profile. + jQuery("#whats-new-post-in").on("change", function (e) { + if (jQuery(this).val() == "0") { + jQuery("#whats-new-form #rtmedia-action-update .privacy") + .prop("disabled", false) + .show(); + } else { + jQuery("#whats-new-form #rtmedia-action-update .privacy") + .prop("disabled", true) + .hide(); + } + }); - // change color of what's new if content is   - let whatsNew = jQuery( '#whats-new' ); - whatsNew.on( 'keyup', function( e ) { - if ( ' ' === whatsNew.val() ) { - whatsNew.css( 'color', 'transparent' ); - } else { - let replaceNbsp = whatsNew.val().replace( ' ', '' ); - whatsNew.val( replaceNbsp ); - whatsNew.css( 'color', 'inherit' ); - } - } ); + // change color of what's new if content is   + let whatsNew = jQuery("#whats-new"); + whatsNew.on("keyup", function (e) { + if (" " === whatsNew.val()) { + whatsNew.css("color", "transparent"); + } else { + let replaceNbsp = whatsNew.val().replace(" ", ""); + whatsNew.val(replaceNbsp); + whatsNew.css("color", "inherit"); + } + }); + + if (typeof rtMedia_update_plupload_config == "undefined") { + return false; + } + var activity_attachemnt_ids = []; + + if (!rtmedia_add_media_button_post_update) { + rtmedia_add_media_button_post_update = $( + "#rtmedia-add-media-button-post-update" + ); + } + + if (rtmedia_add_media_button_post_update.length > 0) { + objUploadView = new UploadView(rtMedia_update_plupload_config); + objUploadView.initUploader(); + + setTimeout(function () { + if (rtmedia_add_media_button_post_update.length > 0) { + $("#whats-new-options").prepend( + $("#whats-new-form .rtmedia-plupload-container") + ); + if ($("#whats-new-form #rtm-file_upload-ui .privacy").length > 0) { + $("#whats-new-form .rtmedia-plupload-container").append( + $("#whats-new-form #rtm-file_upload-ui .privacy") + ); + } + $("#whats-new-form #rtmedia-whts-new-upload-container > div").css( + "top", + "0" + ); + $("#whats-new-form #rtmedia-whts-new-upload-container > div").css( + "left", + "0" + ); + } + }, 100); + + /** + * Appends rtMedia Uploader option below form content section + */ + if (bp_template_pack && "legacy" !== bp_template_pack) { + var form_ref = jQuery("#whats-new-form"); + var rt_uploader_div = jQuery(".rtmedia-uploader-div"); + + if ( + 0 < jQuery(".activity-update-form").length && + 0 < form_ref.length && + 0 < rt_uploader_div.length + ) { + jQuery(form_ref).append(rt_uploader_div); + rt_uploader_div.hide(); + } + } else { + var new_options = jQuery("#whats-new-options"); + var rt_uploader_div = jQuery("#whats-new-form .rtmedia-uploader-div"); - if ( typeof rtMedia_update_plupload_config == 'undefined' ) { - return false; - } - var activity_attachemnt_ids = [ ]; + if (0 < new_options.length && 0 < rt_uploader_div.length) { + new_options.append(rt_uploader_div); + } + } - if ( ! rtmedia_add_media_button_post_update ) { - rtmedia_add_media_button_post_update = $( '#rtmedia-add-media-button-post-update' ); - } + if (!rtmedia_add_media_button_post_update) { + rtmedia_add_media_button_post_update = $( + "#rtmedia-add-media-button-post-update" + ); + } + $("#whats-new-form").on( + "click", + rtmedia_add_media_button_post_update, + function (e) { + objUploadView.uploader.refresh(); + $("#rtmedia-whts-new-upload-container > div").css("top", "0"); + $("#rtmedia-whts-new-upload-container > div").css("left", "0"); + + /** + * NOTE: Do not change. + * ISSUE: BuddyPress activity upload issue with Microsoft Edge + * GL: 132 [ http://git.rtcamp.com/rtmedia/rtMedia/issues/132 ] + * Reason: Trigger event not working for hidden element in Microsoft Edge browser + * Condition to check current browser. + */ + if (/Edge/.test(navigator.userAgent)) { + jQuery(this) + .closest(".rtm-upload-button-wrapper") + .find("input[type=file]") + .click(); + } - if ( rtmedia_add_media_button_post_update.length > 0 ) { - objUploadView = new UploadView( rtMedia_update_plupload_config ); - objUploadView.initUploader(); + //Enable 'post update' button when media get select + $("#aw-whats-new-submit").prop("disabled", false); + } + ); + //Whats-new-post-in - setTimeout( function() { - if ( rtmedia_add_media_button_post_update.length > 0 ) { - $( '#whats-new-options' ).prepend( $( '#whats-new-form .rtmedia-plupload-container' ) ); - if ( $( '#whats-new-form #rtm-file_upload-ui .privacy' ).length > 0 ) { - $( '#whats-new-form .rtmedia-plupload-container' ).append( $( '#whats-new-form #rtm-file_upload-ui .privacy' ) ); - } - $( '#whats-new-form #rtmedia-whts-new-upload-container > div' ).css( 'top', '0' ); - $( '#whats-new-form #rtmedia-whts-new-upload-container > div' ).css( 'left', '0' ); - } - }, 100 ); + objUploadView.upload_remove_array = []; + + objUploadView.uploader.bind("FilesAdded", function (upl, rfiles) { + //$("#aw-whats-new-submit").attr('disabled', 'disabled'); + + //Remove focusout when media is added in activity post. + jQuery("#whats-new-form").off("focusout"); + + $.each(rfiles, function (i, file) { + //Set file title along with file + file.title = file.name.substring(0, file.name.lastIndexOf(".")); + + rtm_file_name_array = file.name.split("."); + + var hook_respo = rtMediaHook.call("rtmedia_js_file_added", [ + upl, + file, + "#rtmedia_uploader_filelist", + ]); + + if (hook_respo == false) { + file.status = -1; + objUploadView.upload_remove_array.push(file.id); + return true; + } + + if (objUploadView.uploader.settings.max_file_size < file.size) { + return true; + } + + var tmp_array = file.name.split("."); + + if (rtmedia_version_compare(rtm_wp_version, "3.9")) { + // Plupload getting updated in 3.9 + var ext_array = + objUploadView.uploader.settings.filters.mime_types[0].extensions.split( + "," + ); + } else { + var ext_array = + objUploadView.uploader.settings.filters[0].extensions.split(","); + } + if (tmp_array.length > 1) { + var ext = tmp_array[tmp_array.length - 1]; + ext = ext.toLowerCase(); + if (jQuery.inArray(ext, ext_array) === -1) { + return true; + } + } else { + return true; + } + + rtmedia_selected_file_list(plupload, file, "", ""); + + jQuery("#whats-new-content").css("padding-bottom", "0px"); + + $("#" + file.id + " .plupload_delete").click(function (e) { + e.preventDefault(); + objUploadView.uploader.removeFile(upl.getFile(file.id)); + $("#" + file.id).remove(); + return false; + }); + + // To change the name of the uploading file + $("#label_" + file.id).click(function (e) { + e.preventDefault(); + + rtm_file_label = this; + + rtm_file_title_id = "text_" + file.id; + rtm_file_title_input = "#" + rtm_file_title_id; + + rtm_file_title_wrapper_id = "rtm_title_wp_" + file.id; + rtm_file_title_wrapper = "#" + rtm_file_title_wrapper_id; + + rtm_file_desc_id = "rtm_desc_" + file.id; + rtm_file_desc_input = "#" + rtm_file_desc_id; + + rtm_file_desc_wrapper_id = "rtm_desc_wp_" + file.id; + rtm_file_desc_wrapper = "#" + rtm_file_desc_wrapper_id; + + rtm_file_save_id = "save_" + file.id; + rtm_file_save_el = "#" + rtm_file_save_id; + + jQuery(rtm_file_label).hide(); + jQuery(rtm_file_label).siblings(".plupload_file_name_wrapper").hide(); + + // Show/create text box to edit media title + if (jQuery(rtm_file_title_input).length === 0) { + jQuery(rtm_file_label) + .parent(".plupload_file_name") + .prepend( + '
      ' + ); + } else { + jQuery(rtm_file_title_wrapper).show(); + jQuery(rtm_file_desc_wrapper).show(); + jQuery(rtm_file_save_el).show(); + } + + jQuery(rtm_file_title_input).focus(); + }); + + rtm_file_save_id = "save_" + file.id; + rtm_file_save_el = "#" + rtm_file_save_id; + jQuery(document.body).on("click", rtm_file_save_el, function (e) { + e.preventDefault(); + rtm_file_title_id = "text_" + file.id; + rtm_file_title_input = "#" + rtm_file_title_id; + + rtm_file_desc_id = "rtm_desc_" + file.id; + rtm_file_desc_input = "#" + rtm_file_desc_id; + + rtm_file_title_wrapper_id = "rtm_title_wp_" + file.id; + rtm_file_title_wrapper = "#" + rtm_file_title_wrapper_id; + + rtm_file_desc_wrapper_id = "rtm_desc_wp_" + file.id; + rtm_file_desc_wrapper = "#" + rtm_file_desc_wrapper_id; + + var file_title_val = jQuery(rtm_file_title_input).val(); + var file_desc_val = jQuery(rtm_file_desc_input).val(); + + rtm_file_label = "#label_" + file.id; + + var file_name_wrapper_el = jQuery(rtm_file_label).siblings( + ".plupload_file_name_wrapper" + ); + + if ("" !== file_title_val.trim()) { + var extension = file.name.split(".")[1]; + file_name_wrapper_el.text(file_title_val + "." + extension); + file.title = file_title_val; + } + + if (file_desc_val != "") { + file.description = file_desc_val; + } + + jQuery(rtm_file_title_wrapper).hide(); + jQuery(rtm_file_desc_wrapper).hide(); + file_name_wrapper_el.show(); + jQuery(rtm_file_label).siblings(".plupload_file_name_wrapper"); + jQuery(rtm_file_label).show(); + jQuery(this).hide(); + }); + }); + + $.each(objUploadView.upload_remove_array, function (i, rfile) { + if (upl.getFile(rfile)) { + upl.removeFile(upl.getFile(rfile)); + } + }); + + /* + * add rtmedia_activity_text_with_attachment condition to filter + * if user want media and activity_text both require + * By: Yahil + */ + if ("" === jQuery("#whats-new").val().trim()) { + if (rtmedia_activity_text_with_attachment == "disable") { + if ("legacy" === bp_template_pack) { + $("#whats-new").css("color", "transparent"); + $("#whats-new").val(" "); + } + } else { + jQuery("#whats-new-form").prepend( + '

      ' + + rtmedia_empty_activity_msg + + "

      " + ); + jQuery("#whats-new").removeAttr("disabled"); + return false; + } + } + + if ( + typeof rtmedia_direct_upload_enabled != "undefined" && + rtmedia_direct_upload_enabled == "1" + ) { + //Call upload event direct when direct upload is enabled (removed UPLOAD button and its triggered event) + var allow_upload = rtMediaHook.call("rtmedia_js_upload_file", { + src: "activity", + }); + + if (allow_upload == false) { + return false; + } + objUploadView.uploadFiles(); + } + + /** + * Uploader improper enter behavior issue(124) fixed + */ + $("#aw-whats-new-submit").focus(); + $(document).off("keydown", "#aw-whats-new-submit", submit_function); + $(document).on("keydown", "#aw-whats-new-submit", submit_function); + /** + * End issue 124 + */ + }); + + objUploadView.uploader.bind("FileUploaded", function (up, file, res) { + if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { + //Test for MSIE x.x; + var ieversion = new Number(RegExp.$1); // Capture x.x portion and store as a number + + if (ieversion < 10) { + try { + if (typeof JSON.parse(res.response) !== "undefined") { + res.status = 200; + } + } catch (e) {} + } + } + + if (res.status == 200) { + try { + var objIds = JSON.parse(res.response); + $.each(objIds, function (key, val) { + activity_attachemnt_ids.push(val); + if ( + $("#whats-new-form").find("#rtmedia_attached_id_" + val).length < + 1 + ) { + $("#whats-new-form").append( + "" + ); + } + }); + } catch (e) {} + rtMediaHook.call("rtmedia_js_after_file_upload", [ + up, + file, + res.response, + ]); + } + }); + + objUploadView.uploader.bind("Error", function (up, err) { + if (err.code == -600) { + //File size error // if file size is greater than server's max allowed size + var tmp_array; + var ext = (tr = ""); + tmp_array = err.file.name.split("."); + if (tmp_array.length > 1) { + ext = tmp_array[tmp_array.length - 1]; + if ( + !( + typeof up.settings.upload_size != "undefined" && + typeof up.settings.upload_size[ext] != "undefined" && + (up.settings.upload_size[ext]["size"] < 1 || + up.settings.upload_size[ext]["size"] * 1024 * 1024 >= + err.file.size) + ) + ) { + rtmedia_selected_file_list(plupload, err.file, up, err); + } + } + } else { + if (err.code == -601) { + // File extension error + err.message = rtmedia_file_extension_error_msg; + } - /** - * Appends rtMedia Uploader option below form content section - */ - if ( bp_template_pack && 'legacy' !== bp_template_pack ) { - - var form_ref = jQuery( '#whats-new-form' ); - var rt_uploader_div = jQuery( '.rtmedia-uploader-div' ); - - if ( 0 < jQuery( '.activity-update-form' ).length && 0 < form_ref.length && 0 < rt_uploader_div.length ) { - jQuery( form_ref ).append( rt_uploader_div ); - rt_uploader_div.hide(); - } - - } else { - - var new_options = jQuery( '#whats-new-options' ); - var rt_uploader_div = jQuery( '#whats-new-form .rtmedia-uploader-div' ); + rtmedia_selected_file_list(plupload, err.file, "", err); + } - if ( 0 < new_options.length && 0 < rt_uploader_div.length ) { - new_options.append( rt_uploader_div ); - } - } + jQuery(".plupload_delete").on("click", function (e) { + e.preventDefault(); + jQuery(this).parent().parent("li").remove(); + }); - if ( ! rtmedia_add_media_button_post_update ) { - rtmedia_add_media_button_post_update = $( '#rtmedia-add-media-button-post-update' ); - } - $( '#whats-new-form' ).on( 'click', rtmedia_add_media_button_post_update, function( e ) { - objUploadView.uploader.refresh(); - $( '#rtmedia-whts-new-upload-container > div' ).css( 'top', '0' ); - $( '#rtmedia-whts-new-upload-container > div' ).css( 'left', '0' ); - - /** - * NOTE: Do not change. - * ISSUE: BuddyPress activity upload issue with Microsoft Edge - * GL: 132 [ http://git.rtcamp.com/rtmedia/rtMedia/issues/132 ] - * Reason: Trigger event not working for hidden element in Microsoft Edge browser - * Condition to check current browser. - */ - if ( /Edge/.test( navigator.userAgent ) ) { - jQuery( this ).closest( '.rtm-upload-button-wrapper' ).find( 'input[type=file]' ).click(); - } + return false; + }); - //Enable 'post update' button when media get select - $( '#aw-whats-new-submit' ).prop( 'disabled', false ); - } ); - //Whats-new-post-in - - objUploadView.upload_remove_array = [ ]; + objUploadView.uploader.bind("BeforeUpload", function (up, files) { + // We send terms conditions data on backend to validate this on server side. + rtMediaHook.call("rtmedia_js_before_upload", { + uploader: up, + file: files, + src: "activity", + }); - objUploadView.uploader.bind( 'FilesAdded', function( upl, rfiles ) { - //$("#aw-whats-new-submit").attr('disabled', 'disabled'); + $.each(objUploadView.upload_remove_array, function (i, rfile) { + if (up.getFile(rfile)) { + up.removeFile(up.getFile(rfile)); + } + }); - //Remove focusout when media is added in activity post. - jQuery( '#whats-new-form' ).unbind( 'focusout' ); + var object = "profile"; + var item_id = 0; - $.each( rfiles, function( i, file ) { + if ("legacy" === bp_template_pack) { + if (jQuery("#whats-new-post-in").length > 0) { + item_id = jQuery("#whats-new-post-in").val(); + } - //Set file title along with file - file.title = file.name.substring(0,file.name.lastIndexOf(".")); + /* Set object for non-profile posts */ + if (item_id > 0 && jQuery("#whats-new-post-object").length > 0) { + object = jQuery("#whats-new-post-object").val(); + } + } else { + if ("undefined" !== typeof BP_Nouveau?.activity?.params?.object) { + object = BP_Nouveau.activity.params.object; + } - rtm_file_name_array = file.name.split( '.' ); + if ("undefined" !== typeof BP_Nouveau?.activity?.params?.item_id) { + item_id = BP_Nouveau.activity.params.item_id; + } else if ( + ("profile" === object || "user" === object) && + "undefined" !== typeof BP_Nouveau?.activity?.params?.user_id + ) { + item_id = BP_Nouveau.activity.params.user_id; + } + } + + if ("groups" === object) { + object = "group"; + } else if ("user" === object) { + object = "profile"; + } + + up.settings.multipart_params.context = object; + up.settings.multipart_params.context_id = item_id; + up.settings.multipart_params.title = files.title; + + if (typeof files.description != "undefined") { + up.settings.multipart_params.description = files.description; + } else { + up.settings.multipart_params.description = ""; + } + + // If privacy dropdown is not disabled, then get the privacy value of the update + if (jQuery("#whats-new-form select.privacy").prop("disabled") === false) { + up.settings.multipart_params.privacy = jQuery( + "#whats-new-form select.privacy" + ).val(); + } + }); + + objUploadView.uploader.bind("UploadComplete", function (up, files) { + media_uploading = true; + + /** + * Blank error display issue resolved + */ + if (bp_template_pack && "legacy" !== bp_template_pack) { + if ( + "legacy" === bp_template_pack && + "disable" === rtmedia_activity_text_with_attachment && + "" === jQuery.trim(jQuery("#whats-new").val()) + ) { + let textarea = jQuery("#whats-new"); + textarea.css("color", "transparent"); + textarea.val(" "); + } + + jQuery("#whats-new-form").submit(); + } else { + jQuery("#aw-whats-new-submit").click(); + } + + jQuery( + "#whats-new-form #rtmedia_uploader_filelist li.plupload_queue_li" + ).remove(); + window.onbeforeunload = null; + }); + + objUploadView.uploader.bind("UploadProgress", function (up, file) { + //$( "#" + file.id + " .plupload_file_status" ).html( rtmedia_uploading_msg + '( ' + file.percent + '% )' ); + // creates a progress bar to display file upload status + var progressBar = jQuery("
      ", { + class: "plupload_file_progress ui-widget-header", + }); + progressBar.css("width", file.percent + "%"); + $("#" + file.id + " .plupload_file_status").html(progressBar); + // filter to customize existing progress bar can be used to display + // '%' of upload completed. + rtMediaHook.call("rtm_custom_progress_bar_content", [file]); + $("#" + file.id).addClass("upload-progress"); + if (file.percent == 100) { + $("#" + file.id).toggleClass("upload-success"); + } + + window.onbeforeunload = function (evt) { + var message = rtmedia_upload_progress_error_message; + return message; + }; + }); + + $("#rtMedia-start-upload").hide(); + + var change_flag = false; + var media_uploading = false; + + $.ajaxPrefilter(function (options, originalOptions, jqXHR) { + // Modify options, control originalOptions, store jqXHR, etc + try { + if ( + originalOptions.data == null || + typeof originalOptions.data == "undefined" || + typeof originalOptions.data.action == "undefined" + ) { + return true; + } + } catch (e) { + return true; + } + + if ( + originalOptions.data.action == "post_update" || + originalOptions.data.action == "activity_widget_filter" + ) { + var temp = activity_attachemnt_ids; + while (activity_attachemnt_ids.length > 0) { + options.data += + "&rtMedia_attached_files[]=" + activity_attachemnt_ids.pop(); + } - var hook_respo = rtMediaHook.call( 'rtmedia_js_file_added', [ upl, file, '#rtmedia_uploader_filelist' ] ); + var dynamic_privacy = ""; - if ( hook_respo == false ) { - file.status = -1; - objUploadView.upload_remove_array.push( file.id ); - return true; - } + var privacy_select = jQuery("#rtSelectPrivacy"); + var whats_new_form = jQuery("#whats-new-form"); + if (whats_new_form.length > 0 && privacy_select.length > 0) { + dynamic_privacy = privacy_select.val(); + } - if ( objUploadView.uploader.settings.max_file_size < file.size ) { - return true; - } + options.data += "&rtmedia-privacy=" + dynamic_privacy; + activity_attachemnt_ids = temp; + + var orignalSuccess = originalOptions.success; + options.beforeSend = function () { + /** + * This hook is added for rtMedia Upload Terms plugin to check if it is checked or not for activity + */ + var allowActivityPost = rtMediaHook.call( + "rtmedia_js_before_activity_added", + { src: "activity" } + ); + + if (!allowActivityPost) { + $("#whats-new-form #rtmedia-whts-new-upload-container") + .find("input") + .removeAttr("disabled"); + + /** + * Issue fixed: 1056(rtmedia-upload-terms) - Not allowing to upload + */ + var activity_textarea = $("#whats-new"); + activity_textarea.removeAttr("disabled"); + /** + * End of issue 1056 fix + */ + + return false; + } + + if (originalOptions.data.action == "post_update") { + if ( + $.trim($("#whats-new").val()) == "" && + objUploadView.uploader.files.length > 0 + ) { + /* + * Added $nbsp; as activity text to post activity without TEXT + * Disabled TextBox color(transparent) + * ELSE + * Required Activity text with media + * add rtmedia_activity_text_with_attachment condition to filter + * if user want media and activity_text both require + * By: Yahil + */ + + if (rtmedia_activity_text_with_attachment == "disable") { + if ("legacy" === bp_template_pack) { + $("#whats-new").css("color", "transparent"); + $("#whats-new").val(" "); + } + } else { + jQuery("#whats-new-form").prepend( + '

      ' + + rtmedia_empty_activity_msg + + "

      " + ); + jQuery("#whats-new").removeAttr("disabled"); + return false; + } + } + } + if (!media_uploading && objUploadView.uploader.files.length > 0) { + $("#whats-new-post-in").attr("disabled", "disabled"); + if (!rtmedia_add_media_button_post_update) { + rtmedia_add_media_button_post_update = $( + "#rtmedia-add-media-button-post-update" + ); + } + rtmedia_add_media_button_post_update.attr("disabled", "disabled"); - var tmp_array = file.name.split( '.' ); + var terms_condition_cb = $("#rtmedia_upload_terms_conditions"); + if (terms_condition_cb.prop("checked")) { + terms_condition_cb.prop("disabled", true); + } - if ( rtmedia_version_compare( rtm_wp_version, '3.9' ) ) { // Plupload getting updated in 3.9 - var ext_array = objUploadView.uploader.settings.filters.mime_types[0].extensions.split( ',' ); - } else { - var ext_array = objUploadView.uploader.settings.filters[0].extensions.split( ',' ); - } - if ( tmp_array.length > 1 ) { - var ext = tmp_array[tmp_array.length - 1]; - ext = ext.toLowerCase(); - if ( jQuery.inArray( ext, ext_array ) === -1 ) { - return true; - } - } else { - return true; - } - - rtmedia_selected_file_list( plupload, file, '', '' ); - - jQuery( '#whats-new-content' ).css( 'padding-bottom', '0px' ); - - $( '#' + file.id + ' .plupload_delete' ).click( function( e ) { - e.preventDefault(); - objUploadView.uploader.removeFile( upl.getFile( file.id ) ); - $( '#' + file.id ).remove(); - return false; - } ); - - // To change the name of the uploading file - $( '#label_' + file.id ).click( function( e ) { - e.preventDefault(); - - rtm_file_label = this; - - rtm_file_title_id = 'text_' + file.id; - rtm_file_title_input = '#' + rtm_file_title_id; - - rtm_file_title_wrapper_id = 'rtm_title_wp_' + file.id; - rtm_file_title_wrapper = '#' + rtm_file_title_wrapper_id; - - rtm_file_desc_id = 'rtm_desc_' + file.id; - rtm_file_desc_input = '#' + rtm_file_desc_id; - - rtm_file_desc_wrapper_id = 'rtm_desc_wp_' + file.id; - rtm_file_desc_wrapper = '#' + rtm_file_desc_wrapper_id; - - rtm_file_save_id = 'save_' + file.id; - rtm_file_save_el = '#' + rtm_file_save_id; - - jQuery( rtm_file_label ).hide(); - jQuery( rtm_file_label ).siblings( '.plupload_file_name_wrapper' ).hide(); - - // Show/create text box to edit media title - if ( jQuery( rtm_file_title_input ).length === 0 ) { - jQuery( rtm_file_label ).parent( '.plupload_file_name' ).prepend( '
      ' ); - } else { - jQuery( rtm_file_title_wrapper ).show(); - jQuery( rtm_file_desc_wrapper ).show(); - jQuery( rtm_file_save_el ).show(); - } - - jQuery( rtm_file_title_input ).focus(); - - } ); - - rtm_file_save_id = 'save_' + file.id; - rtm_file_save_el = '#' + rtm_file_save_id; - jQuery( document.body ).on('click', rtm_file_save_el , function( e ) { - e.preventDefault(); - rtm_file_title_id = 'text_' + file.id; - rtm_file_title_input = '#' + rtm_file_title_id; - - rtm_file_desc_id = 'rtm_desc_' + file.id; - rtm_file_desc_input = '#' + rtm_file_desc_id; - - rtm_file_title_wrapper_id = 'rtm_title_wp_' + file.id; - rtm_file_title_wrapper = '#' + rtm_file_title_wrapper_id; - - rtm_file_desc_wrapper_id = 'rtm_desc_wp_' + file.id; - rtm_file_desc_wrapper = '#' + rtm_file_desc_wrapper_id; - - var file_title_val = jQuery( rtm_file_title_input ).val(); - var file_desc_val = jQuery( rtm_file_desc_input ).val(); - - rtm_file_label = '#label_' + file.id; - - var file_name_wrapper_el = jQuery( rtm_file_label ).siblings( '.plupload_file_name_wrapper' ); - - if ( '' !== file_title_val.trim() ) { - var extension = file.name.split( '.' )[1]; - file_name_wrapper_el.text( file_title_val + '.' + extension ); - file.title = file_title_val; - } - - if ( file_desc_val != '' ) { - file.description = file_desc_val; - } - - jQuery( rtm_file_title_wrapper ).hide(); - jQuery( rtm_file_desc_wrapper ).hide(); - file_name_wrapper_el.show(); - jQuery( rtm_file_label ).siblings( '.plupload_file_name_wrapper' ); - jQuery( rtm_file_label ).show(); - jQuery( this ).hide(); - } ); - } ); - - $.each( objUploadView.upload_remove_array, function( i, rfile ) { - if ( upl.getFile( rfile ) ) { - upl.removeFile( upl.getFile( rfile ) ); - } - } ); - - /* - * add rtmedia_activity_text_with_attachment condition to filter - * if user want media and activity_text both require - * By: Yahil - */ - if ( '' === jQuery( '#whats-new' ).val().trim() ) { - if ( rtmedia_activity_text_with_attachment == 'disable' ) { - if ( 'legacy' === bp_template_pack ) { - $('#whats-new').css('color', 'transparent'); - $('#whats-new').val(' '); - } - } else { - jQuery('#whats-new-form').prepend('

      ' + rtmedia_empty_activity_msg + '

      ') - jQuery( '#whats-new' ).removeAttr( 'disabled' ); - return false; - } - } - - if ( typeof rtmedia_direct_upload_enabled != 'undefined' && rtmedia_direct_upload_enabled == '1' ) { - //Call upload event direct when direct upload is enabled (removed UPLOAD button and its triggered event) - var allow_upload = rtMediaHook.call( 'rtmedia_js_upload_file', { src: 'activity' } ); - - if ( allow_upload == false ) { - return false; - } - objUploadView.uploadFiles(); - } - - /** - * Uploader improper enter behavior issue(124) fixed - */ - $('#aw-whats-new-submit').focus(); - $(document).off('keydown', '#aw-whats-new-submit', submit_function); - $(document).on('keydown', '#aw-whats-new-submit', submit_function); - /** - * End issue 124 - */ - - } ); - - objUploadView.uploader.bind( 'FileUploaded', function( up, file, res ) { - if ( /MSIE (\d+\.\d+);/.test( navigator.userAgent ) ) { //Test for MSIE x.x; - var ieversion = new Number( RegExp.$1 ); // Capture x.x portion and store as a number - - if ( ieversion < 10 ) { - try { - if ( typeof JSON.parse( res.response ) !== 'undefined' ) { - res.status = 200; - } - } catch ( e ) { - } - } - } - - if ( res.status == 200 ) { - try { - var objIds = JSON.parse( res.response ); - $.each( objIds, function( key, val ) { - activity_attachemnt_ids.push( val ); - if ( $( '#whats-new-form' ).find( '#rtmedia_attached_id_' + val ).length < 1 ) { - $( '#whats-new-form' ).append( '' ); - } - } ); - } catch ( e ) { - - } - rtMediaHook.call( 'rtmedia_js_after_file_upload', [ up, file, res.response ] ); - } - } ); - - objUploadView.uploader.bind( 'Error', function( up, err ) { - - if ( err.code == -600 ) { //File size error // if file size is greater than server's max allowed size - var tmp_array; - var ext = tr = ''; - tmp_array = err.file.name.split( '.' ); - if ( tmp_array.length > 1 ) { - - ext = tmp_array[tmp_array.length - 1]; - if ( ! ( typeof ( up.settings.upload_size ) != 'undefined' && typeof ( up.settings.upload_size[ext] ) != 'undefined' && ( up.settings.upload_size[ext]['size'] < 1 || ( up.settings.upload_size[ext]['size'] * 1024 * 1024 ) >= err.file.size ) ) ) { - rtmedia_selected_file_list( plupload, err.file, up, err ); - } - } - } else { - if ( err.code == -601 ) { // File extension error - err.message = rtmedia_file_extension_error_msg; - } - - rtmedia_selected_file_list( plupload, err.file, '', err ); - } - - jQuery( '.plupload_delete' ).on( 'click', function( e ) { - e.preventDefault(); - jQuery( this ).parent().parent( 'li' ).remove(); - } ); - - return false; - - } ); - - objUploadView.uploader.bind( 'BeforeUpload', function( up, files ) { - // We send terms conditions data on backend to validate this on server side. - rtMediaHook.call( 'rtmedia_js_before_upload', { uploader: up, file: files, src: 'activity' } ); - - $.each( objUploadView.upload_remove_array, function( i, rfile ) { - if ( up.getFile( rfile ) ) { - up.removeFile( up.getFile( rfile ) ); - } - } ); - - var object = 'profile'; - var item_id = 0; - - if ( 'legacy' === bp_template_pack ) { - if ( jQuery( '#whats-new-post-in' ).length > 0 ) { - item_id = jQuery('#whats-new-post-in').val(); - } - - /* Set object for non-profile posts */ - if ( item_id > 0 && jQuery('#whats-new-post-object').length > 0 ) { - object = jQuery('#whats-new-post-object').val(); - } - } else { - if ( 'undefined' !== typeof BP_Nouveau?.activity?.params?.object ) { - object = BP_Nouveau.activity.params.object; - } - - if ( 'undefined' !== typeof BP_Nouveau?.activity?.params?.item_id ) { - item_id = BP_Nouveau.activity.params.item_id; - } else if ( ( 'profile' === object || 'user' === object ) && 'undefined' !== typeof BP_Nouveau?.activity?.params?.user_id ) { - item_id = BP_Nouveau.activity.params.user_id; - } - } - - if ( 'groups' === object ) { - object = 'group'; - } else if ( 'user' === object ) { - object = 'profile'; - } - - up.settings.multipart_params.context = object; - up.settings.multipart_params.context_id = item_id; - up.settings.multipart_params.title = files.title; - - if ( typeof files.description != 'undefined' ) { - up.settings.multipart_params.description = files.description; - } else { - up.settings.multipart_params.description = ''; - } - - // If privacy dropdown is not disabled, then get the privacy value of the update - if ( jQuery( '#whats-new-form select.privacy' ).prop( 'disabled' ) === false ) { - up.settings.multipart_params.privacy = jQuery( '#whats-new-form select.privacy' ).val(); - } - } ); - - objUploadView.uploader.bind( 'UploadComplete', function( up, files ) { - media_uploading = true; - - /** - * Blank error display issue resolved - */ - if ( bp_template_pack && 'legacy' !== bp_template_pack ) { - - if ( 'legacy' === bp_template_pack && 'disable' === rtmedia_activity_text_with_attachment && '' === jQuery.trim( jQuery( '#whats-new' ).val() ) ) { - let textarea = jQuery( '#whats-new' ); - textarea.css( 'color', 'transparent' ); - textarea.val( ' ' ); - } - - jQuery( '#whats-new-form' ).submit(); - } else { - jQuery( '#aw-whats-new-submit' ).click(); - } - - jQuery( '#whats-new-form #rtmedia_uploader_filelist li.plupload_queue_li' ).remove(); - window.onbeforeunload = null; - } ); - - objUploadView.uploader.bind( 'UploadProgress', function( up, file ) { - //$( "#" + file.id + " .plupload_file_status" ).html( rtmedia_uploading_msg + '( ' + file.percent + '% )' ); - // creates a progress bar to display file upload status - var progressBar = jQuery( '
      ', { - 'class': 'plupload_file_progress ui-widget-header', - }); - progressBar.css( 'width', file.percent + '%' ); - $( '#' + file.id + ' .plupload_file_status' ).html( progressBar ); - // filter to customize existing progress bar can be used to display - // '%' of upload completed. - rtMediaHook.call( 'rtm_custom_progress_bar_content', [ file ] ); - $( '#' + file.id ).addClass( 'upload-progress' ); - if ( file.percent == 100 ) { - $( '#' + file.id ).toggleClass( 'upload-success' ); - } - - window.onbeforeunload = function( evt ) { - var message = rtmedia_upload_progress_error_message; - return message; - }; - } ); - - $( '#rtMedia-start-upload' ).hide(); - - var change_flag = false; - var media_uploading = false; - - $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { - // Modify options, control originalOptions, store jqXHR, etc - try { - if ( originalOptions.data == null || typeof ( originalOptions.data ) == 'undefined' || typeof ( originalOptions.data.action ) == 'undefined' ) { - return true; - } - } catch ( e ) { - return true; - } - - if ( originalOptions.data.action == 'post_update' || originalOptions.data.action == 'activity_widget_filter' ) { - var temp = activity_attachemnt_ids; - while ( activity_attachemnt_ids.length > 0 ) { - options.data += '&rtMedia_attached_files[]=' + activity_attachemnt_ids.pop(); - } - - var dynamic_privacy = ''; - - var privacy_select = jQuery( '#rtSelectPrivacy' ); - var whats_new_form = jQuery( '#whats-new-form' ); - if ( whats_new_form.length > 0 && privacy_select.length > 0 ) { - dynamic_privacy = privacy_select.val(); - } - - options.data += '&rtmedia-privacy=' + dynamic_privacy; - activity_attachemnt_ids = temp; - - var orignalSuccess = originalOptions.success; - options.beforeSend = function() { - /** - * This hook is added for rtMedia Upload Terms plugin to check if it is checked or not for activity - */ - var allowActivityPost = rtMediaHook.call( 'rtmedia_js_before_activity_added', { src: 'activity' } ); - - if ( ! allowActivityPost ) { - $( '#whats-new-form #rtmedia-whts-new-upload-container' ).find( 'input' ).removeAttr( 'disabled' ); - - /** - * Issue fixed: 1056(rtmedia-upload-terms) - Not allowing to upload - */ - var activity_textarea = $( '#whats-new' ); - activity_textarea.removeAttr('disabled'); - /** - * End of issue 1056 fix - */ - - return false; - } - - if ( originalOptions.data.action == 'post_update' ) { - if ( $.trim( $( '#whats-new' ).val() ) == '' && objUploadView.uploader.files.length > 0 ) { - /* - * Added $nbsp; as activity text to post activity without TEXT - * Disabled TextBox color(transparent) - * ELSE - * Required Activity text with media - * add rtmedia_activity_text_with_attachment condition to filter - * if user want media and activity_text both require - * By: Yahil - */ - - if ( rtmedia_activity_text_with_attachment == 'disable') { - if ( 'legacy' === bp_template_pack ) { - $( '#whats-new' ).css( 'color', 'transparent' ); - $( '#whats-new' ).val( ' ' ); - } - } else { - jQuery('#whats-new-form').prepend('

      ' + rtmedia_empty_activity_msg + '

      ') - jQuery( '#whats-new' ).removeAttr( 'disabled' ); - return false; - } - } - } - if ( ! media_uploading && objUploadView.uploader.files.length > 0 ) { - $( '#whats-new-post-in' ).attr( 'disabled', 'disabled' ); - if ( ! rtmedia_add_media_button_post_update ) { - rtmedia_add_media_button_post_update = $( '#rtmedia-add-media-button-post-update' ); - } - rtmedia_add_media_button_post_update.attr( 'disabled', 'disabled' ); - - var terms_condition_cb = $( '#rtmedia_upload_terms_conditions' ); - if ( terms_condition_cb.prop( 'checked' ) ) { - terms_condition_cb.prop( 'disabled', true ); - } - - objUploadView.uploadFiles(); - media_uploading = true; - return false; - } else { - media_uploading = false; - return true; - } - - }; - options.success = function( response ) { - // For BuddyPress Nouveau Template. - if ( orignalSuccess && 'function' === typeof orignalSuccess ) { - orignalSuccess( response ); - } - - if ( response[0] + response[1] == '-1' ) { - //Error - - } else { - if ( originalOptions.data.action == 'activity_widget_filter' ) { - $( 'div.activity' ).bind( 'fadeIn', function() { - apply_rtMagnificPopup( jQuery( '.rtmedia-list-media, .rtmedia-activity-container ul.rtmedia-list, #bp-media-list,.widget-item-listing,.bp-media-sc-list, li.media.album_updated ul,ul.bp-media-list-media, li.activity-item div.activity-content div.activity-inner div.bp_media_content' ) ); - rtMediaHook.call( 'rtmedia_js_after_activity_added', [ ] ); - if ( ! rtmedia_add_media_button_post_update ) { - rtmedia_add_media_button_post_update = jQuery( '#rtmedia-add-media-button-post-update' ); - } - - rtmedia_add_media_button_post_update.removeAttr( 'disabled' ); - } ); - $( 'div.activity' ).fadeIn( 100 ); - } - jQuery( 'input[data-mode=rtMedia-update]' ).remove(); - while ( objUploadView.uploader.files.pop() != undefined ) { - } - objUploadView.uploader.refresh(); - $( '#rtmedia-whts-new-upload-container > div' ).css( { 'top': '0', 'left': '0' } ); - $( '#whats-new-form #rtMedia-update-queue-list' ).html( '' ); - - apply_rtMagnificPopup( jQuery( '.rtmedia-list-media, .rtmedia-activity-container ul.rtmedia-list, #bp-media-list,.widget-item-listing,.bp-media-sc-list, li.media.album_updated ul,ul.bp-media-list-media, li.activity-item div.activity-content div.activity-inner div.bp_media_content' ) ); - - // For BuddyPress New Template hacks - jQuery( '.plupload_filelist_content.rtm-plupload-list' ).html(''); - - rtMediaHook.call( 'rtmedia_js_after_activity_added', [ ] ); - if ( ! rtmedia_add_media_button_post_update ) { - rtmedia_add_media_button_post_update = jQuery( '#rtmedia-add-media-button-post-update' ); - } - rtmedia_add_media_button_post_update.removeAttr( 'disabled' ); - } - - // rtmedia_on_activity_add(); - - $( '#whats-new-post-in' ).removeAttr( 'disabled' ); - if ( ! rtmedia_add_media_button_post_update ) { - rtmedia_add_media_button_post_update = $( '#rtmedia-add-media-button-post-update' ); - } - rtmedia_add_media_button_post_update.removeAttr( 'disabled' ); - // Enabled TextBox color back to normal - $( '#whats-new' ).val( '' ); - $( '#whats-new' ).css( 'color', '' ); - - }; - } - } ); - } else { - $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { - // Modify options, control originalOptions, store jqXHR, etc - try { - if ( originalOptions.data == null || typeof ( originalOptions.data ) == 'undefined' || typeof ( originalOptions.data.action ) == 'undefined' ) { - return true; - } - } catch ( e ) { - return true; - } - - if ( originalOptions.data.action == 'post_update' || originalOptions.data.action == 'activity_widget_filter' ) { - var dynamic_privacy = ''; - - if ( jQuery( 'select.privacy' ).not( '.rtm-activity-privacy-opt' ).length > 0 ) { - dynamic_privacy = jQuery( 'select.privacy' ).not( '.rtm-activity-privacy-opt' ).val(); - } else if ( jQuery( 'input[name="privacy"]' ).length > 0 ) { - dynamic_privacy = jQuery( 'input[name="privacy"]' ).val(); - } - - options.data += '&rtmedia-privacy=' + dynamic_privacy; - var orignalSuccess = originalOptions.done; - options.done = function( response ) { - orignalSuccess( response ); - if ( response[0] + response[1] == '-1' ) { - //Error - } else { - if ( originalOptions.data.action == 'activity_widget_filter' ) { - $( 'div.activity' ).fadeIn( 100 ); - } - } - - $( '#whats-new-post-in' ).removeAttr( 'disabled' ); - // Enabled TextBox color back to normal - $( '#whats-new' ).css( 'color', '' ); - - }; - } - } ); - } -} ); + objUploadView.uploadFiles(); + media_uploading = true; + return false; + } else { + media_uploading = false; + return true; + } + }; + options.success = function (response) { + // For BuddyPress Nouveau Template. + if (orignalSuccess && "function" === typeof orignalSuccess) { + orignalSuccess(response); + } + + if (response[0] + response[1] == "-1") { + //Error + } else { + if (originalOptions.data.action == "activity_widget_filter") { + $("div.activity").on("fadeIn", function () { + apply_rtMagnificPopup( + jQuery( + ".rtmedia-list-media, .rtmedia-activity-container ul.rtmedia-list, #bp-media-list,.widget-item-listing,.bp-media-sc-list, li.media.album_updated ul,ul.bp-media-list-media, li.activity-item div.activity-content div.activity-inner div.bp_media_content" + ) + ); + rtMediaHook.call("rtmedia_js_after_activity_added", []); + if (!rtmedia_add_media_button_post_update) { + rtmedia_add_media_button_post_update = jQuery( + "#rtmedia-add-media-button-post-update" + ); + } + rtmedia_add_media_button_post_update.removeAttr("disabled"); + }); + $("div.activity").fadeIn(100); + } + jQuery("input[data-mode=rtMedia-update]").remove(); + while (objUploadView.uploader.files.pop() != undefined) {} + objUploadView.uploader.refresh(); + $("#rtmedia-whts-new-upload-container > div").css({ + top: "0", + left: "0", + }); + $("#whats-new-form #rtMedia-update-queue-list").html(""); + + apply_rtMagnificPopup( + jQuery( + ".rtmedia-list-media, .rtmedia-activity-container ul.rtmedia-list, #bp-media-list,.widget-item-listing,.bp-media-sc-list, li.media.album_updated ul,ul.bp-media-list-media, li.activity-item div.activity-content div.activity-inner div.bp_media_content" + ) + ); + + // For BuddyPress New Template hacks + jQuery(".plupload_filelist_content.rtm-plupload-list").html(""); + + rtMediaHook.call("rtmedia_js_after_activity_added", []); + if (!rtmedia_add_media_button_post_update) { + rtmedia_add_media_button_post_update = jQuery( + "#rtmedia-add-media-button-post-update" + ); + } + rtmedia_add_media_button_post_update.removeAttr("disabled"); + } + + // rtmedia_on_activity_add(); + + $("#whats-new-post-in").removeAttr("disabled"); + if (!rtmedia_add_media_button_post_update) { + rtmedia_add_media_button_post_update = $( + "#rtmedia-add-media-button-post-update" + ); + } + rtmedia_add_media_button_post_update.removeAttr("disabled"); + // Enabled TextBox color back to normal + $("#whats-new").val(""); + $("#whats-new").css("color", ""); + }; + } + }); + } else { + $.ajaxPrefilter(function (options, originalOptions, jqXHR) { + // Modify options, control originalOptions, store jqXHR, etc + try { + if ( + originalOptions.data == null || + typeof originalOptions.data == "undefined" || + typeof originalOptions.data.action == "undefined" + ) { + return true; + } + } catch (e) { + return true; + } + + if ( + originalOptions.data.action == "post_update" || + originalOptions.data.action == "activity_widget_filter" + ) { + var dynamic_privacy = ""; + + if ( + jQuery("select.privacy").not(".rtm-activity-privacy-opt").length > 0 + ) { + dynamic_privacy = jQuery("select.privacy") + .not(".rtm-activity-privacy-opt") + .val(); + } else if (jQuery('input[name="privacy"]').length > 0) { + dynamic_privacy = jQuery('input[name="privacy"]').val(); + } + options.data += "&rtmedia-privacy=" + dynamic_privacy; + var orignalSuccess = originalOptions.done; + options.done = function (response) { + orignalSuccess(response); + if (response[0] + response[1] == "-1") { + //Error + } else { + if (originalOptions.data.action == "activity_widget_filter") { + $("div.activity").fadeIn(100); + } + } + + $("#whats-new-post-in").removeAttr("disabled"); + // Enabled TextBox color back to normal + $("#whats-new").css("color", ""); + }; + } + }); + } +}); /** * RtMedia Comment Js */ -jQuery( document ).ready( function( $ ) { - jQuery( document ).on( 'click', '#rt_media_comment_form #rt_media_comment_submit', function( e ) { - var that = this; - var widget_id = jQuery( this ).attr( 'widget_id' ); - var comment_form_el = jQuery( this ).closest('form'); - var comment_content_el = comment_form_el.find( '#comment_content' ); - - var show_error = false; - var content = jQuery.trim( comment_content_el.val() ); - - comment_attached_id = comment_form_el.find( 'input[name="rtMedia_attached_files[]"]' ).val(); - if ( typeof comment_attached_id == 'undefined' && content == '' ) { - show_error = 1; - }else{ - if( comment_attached_id == '' && content == '' ){ - show_error = 2; - } - } - - if( show_error ){ - - rtmedia_single_media_alert_message( rtmedia_empty_comment_msg, 'warning', true ); - - if ( widget_id ) { - rtmedia_comment_media_input_button( widget_id, false ); - } else { - rtmedia_comment_submit_button_disable( false ); - } - - return false; - } - - - $( this ).attr( 'disabled', 'disabled' ); - //If string has only   then set value as empty. - if ( '' === comment_content_el.val().replace(/\ /g, '' ) ) { - comment_content_el.val( '' ); - } - $.ajax( { - url: comment_form_el.attr( 'action' ), - type: 'post', - data: comment_form_el.serialize() + '&rtajax=true', - success: function( data ) { - $( '#rtmedia-no-comments' ).remove(); - - $( '#rtmedia_comment_ul' ).append( data ); - - - comment_content_el.val( '' ); - - if ( widget_id ) { - rtmedia_comment_media_remove_hidden_media_id( widget_id ); - rtmedia_comment_media_textbox_val( widget_id, false ); - rtmedia_comment_media_input_button( widget_id, false ); - } else { - rtmedia_comment_submit_button_disable( false ); - } - - rtmedia_apply_popup_to_media(); - - rtmedia_reset_video_and_audio_for_popup(); - - rtMediaHook.call( 'rtmedia_js_after_comment_added', [ ] ); - - /** Scroll function called */ - rtMediaScrollComments(); - - /** refreshing fragments */ - if ( false == $( 'body' ).hasClass( 'activity' ) && false == $( 'body' ).hasClass( 'groups' ) ) { - galleryObj.reloadView(); - } - }, - error: function( data ) { - if ( widget_id ) { - rtmedia_comment_media_input_button( widget_id, false ); - rtmedia_comment_media_remove_hidden_media_id( widget_id ); - } else { - rtmedia_comment_submit_button_disable( false ); - } - } - } ); - - return false; - } ); +jQuery(document).ready(function ($) { + jQuery(document).on( + "click", + "#rt_media_comment_form #rt_media_comment_submit", + function (e) { + var that = this; + var widget_id = jQuery(this).attr("widget_id"); + var comment_form_el = jQuery(this).closest("form"); + var comment_content_el = comment_form_el.find("#comment_content"); + + var show_error = false; + var content = jQuery.trim(comment_content_el.val()); + + comment_attached_id = comment_form_el + .find('input[name="rtMedia_attached_files[]"]') + .val(); + if (typeof comment_attached_id == "undefined" && content == "") { + show_error = 1; + } else { + if (comment_attached_id == "" && content == "") { + show_error = 2; + } + } + + if (show_error) { + rtmedia_single_media_alert_message( + rtmedia_empty_comment_msg, + "warning", + true + ); + + if (widget_id) { + rtmedia_comment_media_input_button(widget_id, false); + } else { + rtmedia_comment_submit_button_disable(false); + } - //Delete comment - jQuery( document ).on( 'click', '.rtmedia-delete-comment', function( e ) { - e.preventDefault(); - var ask_confirmation = true; - ask_confirmation = rtMediaHook.call( 'rtmedia_js_delete_comment_confirmation', [ ask_confirmation ] ); - if ( ask_confirmation && ! confirm( rtmedia_media_comment_delete_confirmation ) ) { - return false; - } - var current_comment = jQuery( this ); - var current_comment_parent = current_comment.parent(); - var comment_id = current_comment.data( 'id' ); - current_comment_parent.css( 'opacity', '0.4' ); - if ( comment_id == '' || isNaN( comment_id ) ) { - return false; - } - var action = current_comment.closest( 'ul' ).data( 'action' ); - - jQuery.ajax( { - url: action, - type: 'post', - data: { comment_id: comment_id }, - success: function( res ) { - if ( res != 'undefined' && res == 1 ) { - current_comment.closest( 'li' ).hide( 1000, function() { - current_comment.closest( 'li' ).remove(); - } ); - } else { - current_comment_parent.css( 'opacity', '1' ); - } - rtMediaHook.call( 'rtmedia_js_after_comment_deleted', [ ] ); - } - } ); + return false; + } + + $(this).attr("disabled", "disabled"); + //If string has only   then set value as empty. + if ("" === comment_content_el.val().replace(/\ /g, "")) { + comment_content_el.val(""); + } + $.ajax({ + url: comment_form_el.attr("action"), + type: "post", + data: comment_form_el.serialize() + "&rtajax=true", + success: function (data) { + $("#rtmedia-no-comments").remove(); + + $("#rtmedia_comment_ul").append(data); + + comment_content_el.val(""); + + if (widget_id) { + rtmedia_comment_media_remove_hidden_media_id(widget_id); + rtmedia_comment_media_textbox_val(widget_id, false); + rtmedia_comment_media_input_button(widget_id, false); + } else { + rtmedia_comment_submit_button_disable(false); + } + + rtmedia_apply_popup_to_media(); + + rtmedia_reset_video_and_audio_for_popup(); + + rtMediaHook.call("rtmedia_js_after_comment_added", []); + + /** Scroll function called */ + rtMediaScrollComments(); + + /** refreshing fragments */ + if ( + false == $("body").hasClass("activity") && + false == $("body").hasClass("groups") + ) { + galleryObj.reloadView(); + } + }, + error: function (data) { + if (widget_id) { + rtmedia_comment_media_input_button(widget_id, false); + rtmedia_comment_media_remove_hidden_media_id(widget_id); + } else { + rtmedia_comment_submit_button_disable(false); + } + }, + }); + + return false; + } + ); + + //Delete comment + jQuery(document).on("click", ".rtmedia-delete-comment", function (e) { + e.preventDefault(); + var ask_confirmation = true; + ask_confirmation = rtMediaHook.call( + "rtmedia_js_delete_comment_confirmation", + [ask_confirmation] + ); + if ( + ask_confirmation && + !confirm(rtmedia_media_comment_delete_confirmation) + ) { + return false; + } + var current_comment = jQuery(this); + var current_comment_parent = current_comment.parent(); + var comment_id = current_comment.data("id"); + current_comment_parent.css("opacity", "0.4"); + if (comment_id == "" || isNaN(comment_id)) { + return false; + } + var action = current_comment.closest("ul").data("action"); + + jQuery.ajax({ + url: action, + type: "post", + data: { comment_id: comment_id }, + success: function (res) { + if (res != "undefined" && res == 1) { + current_comment.closest("li").hide(1000, function () { + current_comment.closest("li").remove(); + }); + } else { + current_comment_parent.css("opacity", "1"); + } + rtMediaHook.call("rtmedia_js_after_comment_deleted", []); + }, + }); + }); + + $(document).on("click", ".rtmedia-like", function (e) { + e.preventDefault(); + var that = this; + var like_nonce = $("#rtm_media_like_nonce").val(); + $(this).attr("disabled", "disabled"); + var url = $(this).parent().attr("action"); + $(that).prepend( + "" + ); + $.ajax({ + url: url, + type: "post", + data: { json: true, like_nonce: like_nonce }, + success: function (data) { + try { + data = JSON.parse(data); + } catch (e) {} + + $(".rtmedia-like span").html(data.next); + $(".rtmedia-like").attr("title", data.next); + $(".rtmedia-like-counter-wrap").html(data.person_text); + $(".rtm-like-loading").remove(); + $(that).removeAttr("disabled"); + var comments_container = $(".rtmedia-comments-container").length; + + //Update the like counter + // $( '.rtmedia-like-counter' ).html( data.count ); + if (data.count > 0) { + $(".rtmedia-like-info, .rtm-like-comments-info").removeClass("hide"); + } else { + $(".rtmedia-like-info").addClass("hide"); + + // Add hide class to this element when "comment on media" is not enabled. + if (0 === comments_container) { + $(".rtm-like-comments-info").addClass("hide"); + } + } + }, + }); + }); + $(document).on( + "click", + ".rtmedia-featured, .rtmedia-group-featured", + function (e) { + e.preventDefault(); + var that = this; + $(this).attr("disabled", "disabled"); + var featured_nonce = $(this).siblings("#rtm_media_featured_nonce").val(); + var url = $(this).parent().attr("action"); + $(that).prepend( + "" + ); + $.ajax({ + url: url, + type: "post", + data: { json: true, featured_nonce: featured_nonce }, + success: function (data) { + try { + data = JSON.parse(data); + } catch (e) {} + + if (data.nonce) { + rtmedia_single_media_alert_message( + rtmedia_something_wrong_msg, + "warning" + ); + } else { + if (data.action) { + rtmedia_single_media_alert_message( + rtmedia_set_featured_image_msg, + "success" + ); + } else { + rtmedia_single_media_alert_message( + rtmedia_unset_featured_image_msg, + "success" + ); + } + } + $(that).find("span").html(data.next); + $(".rtm-featured-loading").remove(); + $(that).removeAttr("disabled"); + }, + }); + } + ); + jQuery("#div-attache-rtmedia") + .find("input[type=file]") + .each(function () { + //$(this).attr("capture", "camera"); + // $(this).attr("accept", $(this).attr("accept") + ';capture=camera'); + }); + + // Manually trigger fadein event so that we can bind some function on this event. It is used in activity when content getting load via ajax + var _old_fadein = $.fn.fadeIn; + jQuery.fn.fadeIn = function () { + return _old_fadein.apply(this, arguments).trigger("fadeIn"); + }; +}); - } ); +function rtmedia_selected_file_list( + plupload, + file, + uploader, + error, + comment_media_id +) { + var icon = "", + err_msg = "", + upload_progress = "", + title = ""; + + /** + * Blank error display issue resolved + */ + if (bp_template_pack && "legacy" !== bp_template_pack) { + var new_submit_btn = jQuery("#aw-whats-new-submit"); + if (0 < new_submit_btn.length) { + var new_button = jQuery("", { + type: "button", + class: "button", + name: "aw-whats-new-submit", + id: "aw-whats-new-submit", + value: new_submit_btn.val(), + }); + + new_submit_btn.replaceWith(new_button); + + new_button.on("click", function (e) { + if (!rtmedia_add_media_button_post_update) { + rtmedia_add_media_button_post_update = jQuery( + "#rtmedia-add-media-button-post-update" + ); + } + rtmedia_add_media_button_post_update.prop("disabled", true); + if ( + rtMediaHook.call("rtmedia_js_before_activity_added", { + src: "activity", + }) + ) { + objUploadView.uploadFiles(e); + } + }); + } + } + + rtmedia_uploader_filelist = + typeof comment_media_id === "undefined" + ? "#rtmedia_uploader_filelist" + : "#rtmedia_uploader_filelist-" + comment_media_id; + plupload_delete = + typeof comment_media_id === "undefined" + ? "plupload_delete" + : "plupload_delete-" + comment_media_id; + + if (error == "") { + upload_progress = + '
      '; + upload_progress += "
      "; + icon = + ''; + } else if (error.code == -600) { + alert(rtmedia_max_file_msg + uploader.settings.max_file_size); + err_msg = + uploader != "" + ? rtmedia_max_file_msg + uploader.settings.max_file_size + : window.file_size_info; + title = "title='" + err_msg + "'"; + icon = '"; + } else if (error.code == -601) { + alert(error.message + ". " + window.file_extn_info); + err_msg = error.message + ". " + window.file_extn_info; + title = "title='" + err_msg + "'"; + icon = '"; + } + + var rtmedia_plupload_file = + '
    • "; + rtmedia_plupload_file += + '
      '; + rtmedia_plupload_file += "
      "; + rtmedia_plupload_file += '
      '; + rtmedia_plupload_file += upload_progress; + rtmedia_plupload_file += "
      "; + rtmedia_plupload_file += + '
      '; + rtmedia_plupload_file += ''; + rtmedia_plupload_file += file.name ? file.name : ""; + rtmedia_plupload_file += ""; + rtmedia_plupload_file += icon; + rtmedia_plupload_file += "
      "; + rtmedia_plupload_file += '
      '; + rtmedia_plupload_file += + '
      '; + rtmedia_plupload_file += + ''; + rtmedia_plupload_file += "
      "; + rtmedia_plupload_file += "
      "; + rtmedia_plupload_file += '
      '; + rtmedia_plupload_file += plupload.formatSize(file.size).toUpperCase(); + rtmedia_plupload_file += "
      "; + rtmedia_plupload_file += '
      '; + rtmedia_plupload_file += "
      "; + rtmedia_plupload_file += "
    • "; + + if (error.code !== -601 && error.code !== -600) { + jQuery(rtmedia_plupload_file).appendTo(rtmedia_uploader_filelist); + } + + if (comment_media_id) { + jQuery("#rtmedia-comment-media-upload-" + comment_media_id).focus(); + } else { + jQuery("#whats-new").focus(); + } + + var type = file.type; + var media_title = file.name; + var ext = media_title.substring( + media_title.lastIndexOf(".") + 1, + media_title.length + ); + + if (/image/i.test(type)) { + if (ext === "gif") { + jQuery('').appendTo( + "#file_thumb_" + file.id + ); + } else { + var img = new mOxie.Image(); - $( document ).on( 'click', '.rtmedia-like', function( e ) { - e.preventDefault(); - var that = this; - var like_nonce = $( '#rtm_media_like_nonce' ).val(); - $( this ).attr( 'disabled', 'disabled' ); - var url = $( this ).parent().attr( 'action' ); - $( that ).prepend( '' ); - $.ajax( { - url: url, - type: 'post', - data: { json: true, like_nonce: like_nonce }, - success: function( data ) { - try { - data = JSON.parse( data ); - } catch ( e ) { - - } - - $( '.rtmedia-like span' ).html( data.next ); - $( '.rtmedia-like' ).attr( 'title', data.next ); - $( '.rtmedia-like-counter-wrap' ).html( data.person_text ); - $( '.rtm-like-loading' ).remove(); - $( that ).removeAttr( 'disabled' ); - var comments_container = $( '.rtmedia-comments-container' ).length; - - //Update the like counter - // $( '.rtmedia-like-counter' ).html( data.count ); - if ( data.count > 0 ) { - $( '.rtmedia-like-info, .rtm-like-comments-info' ).removeClass( 'hide' ); - } else { - $( '.rtmedia-like-info' ).addClass( 'hide' ); - - // Add hide class to this element when "comment on media" is not enabled. - if ( 0 === comments_container ) { - $( '.rtm-like-comments-info' ).addClass( 'hide' ); - } - } - } - } ); + img.onload = function () { + this.embed(jQuery("#file_thumb_" + file.id).get(0), { + width: 100, + height: 60, + crop: true, + }); + }; - } ); - $( document ).on( 'click', '.rtmedia-featured, .rtmedia-group-featured', function( e ) { - e.preventDefault(); - var that = this; - $( this ).attr( 'disabled', 'disabled' ); - var featured_nonce = $( this ).siblings( '#rtm_media_featured_nonce' ).val(); - var url = $( this ).parent().attr( 'action' ); - $( that ).prepend( '' ); - $.ajax( { - url: url, - type: 'post', - data: { json:true, featured_nonce:featured_nonce }, - success: function( data ) { - try { - data = JSON.parse( data ); - } catch ( e ) { - - } - - if ( data.nonce ) { - rtmedia_single_media_alert_message( rtmedia_something_wrong_msg, 'warning' ); - } else { - if ( data.action ) { - rtmedia_single_media_alert_message( rtmedia_set_featured_image_msg, 'success' ); - } else { - rtmedia_single_media_alert_message( rtmedia_unset_featured_image_msg, 'success' ); - } - } - $( that ).find( 'span' ).html( data.next ); - $( '.rtm-featured-loading' ).remove(); - $( that ).removeAttr( 'disabled' ); - } - } ); + img.onembedded = function () { + this.destroy(); + }; - } ); - jQuery( '#div-attache-rtmedia' ).find( 'input[type=file]' ).each( function() { - //$(this).attr("capture", "camera"); - // $(this).attr("accept", $(this).attr("accept") + ';capture=camera'); + img.onerror = function () { + this.destroy(); + }; - } ); + img.load(file.getSource()); + } + } else { + jQuery.each(rtmedia_exteansions, function (key, value) { + if (value.indexOf(ext) >= 0) { + var media_thumbnail = ""; + + // Below condition is to show docs and files addon thumbnail. + if (rtmedia_media_thumbs[ext]) { + media_thumbnail = rtmedia_media_thumbs[ext]; + } else { + media_thumbnail = rtmedia_media_thumbs[key]; + } - // Manually trigger fadein event so that we can bind some function on this event. It is used in activity when content getting load via ajax - var _old_fadein = $.fn.fadeIn; - jQuery.fn.fadeIn = function() { - return _old_fadein.apply( this, arguments ).trigger( 'fadeIn' ); - }; -} ); - - -function rtmedia_selected_file_list( plupload, file, uploader, error, comment_media_id ) { - var icon = '', err_msg = '', upload_progress = '', title = ''; - - /** - * Blank error display issue resolved - */ - if ( bp_template_pack && 'legacy' !== bp_template_pack ) { - - var new_submit_btn = jQuery( '#aw-whats-new-submit' ); - if ( 0 < new_submit_btn.length ) { - - var new_button = jQuery( '', { - type : 'button', - class : 'button', - name : 'aw-whats-new-submit', - id : 'aw-whats-new-submit', - value : new_submit_btn.val() - } ); - - new_submit_btn.replaceWith( new_button ); - - new_button.on( 'click', function ( e ) { - - if ( ! rtmedia_add_media_button_post_update ) { - rtmedia_add_media_button_post_update = jQuery( '#rtmedia-add-media-button-post-update' ); - } - rtmedia_add_media_button_post_update.prop( 'disabled', true ); - if ( rtMediaHook.call( 'rtmedia_js_before_activity_added', { src: 'activity' } ) ) { - objUploadView.uploadFiles( e ); - } - } ); - } - } - - rtmedia_uploader_filelist = (typeof comment_media_id === "undefined") ? "#rtmedia_uploader_filelist" : "#rtmedia_uploader_filelist-"+comment_media_id; - plupload_delete = (typeof comment_media_id === "undefined") ? "plupload_delete" : "plupload_delete-"+comment_media_id; - - if ( error == '' ) { - upload_progress = '
      '; - upload_progress += '
      '; - icon = ''; - } else if ( error.code == -600 ) { - alert( rtmedia_max_file_msg + uploader.settings.max_file_size ); - err_msg = ( uploader != '' ) ? rtmedia_max_file_msg + uploader.settings.max_file_size : window.file_size_info; - title = 'title=\'' + err_msg + '\''; - icon = ''; - } else if ( error.code == -601 ) { - alert( error.message + '. ' + window.file_extn_info ); - err_msg = error.message + '. ' + window.file_extn_info; - title = 'title=\'' + err_msg + '\''; - icon = ''; - } - - var rtmedia_plupload_file = '
    • '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += upload_progress; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += ''; - rtmedia_plupload_file += ( file.name ? file.name : '' ); - rtmedia_plupload_file += ''; - rtmedia_plupload_file += icon; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += ''; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += plupload.formatSize( file.size ).toUpperCase(); - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
      '; - rtmedia_plupload_file += '
    • '; - - if ( error.code !== -601 && error.code !== -600 ) { - jQuery( rtmedia_plupload_file ).appendTo( rtmedia_uploader_filelist ); - } - - if ( comment_media_id ) { - jQuery( '#rtmedia-comment-media-upload-' + comment_media_id ).focus(); - } else { - jQuery( '#whats-new' ).focus(); - } - - var type = file.type; - var media_title = file.name; - var ext = media_title.substring( media_title.lastIndexOf( '.' ) + 1, media_title.length ); - - if ( /image/i.test( type ) ) { - if ( ext === 'gif' ) { - jQuery( '' ).appendTo( '#file_thumb_' + file.id ); - } else { - var img = new mOxie.Image(); - - img.onload = function() { - this.embed( jQuery( '#file_thumb_' + file.id ).get( 0 ), { - width: 100, - height: 60, - crop: true - } ); - }; - - img.onembedded = function() { - this.destroy(); - }; - - img.onerror = function() { - this.destroy(); - }; - - img.load( file.getSource() ); - } - } else { - jQuery.each( rtmedia_exteansions, function( key, value ) { - if ( value.indexOf( ext ) >= 0 ) { - - var media_thumbnail = ''; - - // Below condition is to show docs and files addon thumbnail. - if ( rtmedia_media_thumbs[ ext ] ) { - media_thumbnail = rtmedia_media_thumbs[ ext ]; - } else { - media_thumbnail = rtmedia_media_thumbs[ key ]; - } - - jQuery( '', { src: media_thumbnail } ).appendTo( '#file_thumb_' + file.id ); - - return false; - } - } ); - } + jQuery("", { src: media_thumbnail }).appendTo( + "#file_thumb_" + file.id + ); + return false; + } + }); + } } /* Change URLin browser without reloading the page */ -function change_rtBrowserAddressUrl( url, page ) { - if ( typeof ( history.pushState ) != 'undefined' ) { - var obj = { Page: page, Url: url }; - history.pushState( obj, obj.Page, obj.Url ); - } +function change_rtBrowserAddressUrl(url, page) { + if (typeof history.pushState != "undefined") { + var obj = { Page: page, Url: url }; + history.pushState(obj, obj.Page, obj.Url); + } } +// Escape regex special characters in a string so it can be safely used in a RegExp. +// This covers: . * + ? ^ $ { } ( ) | [ ] \ +function escapeForRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} /** * Get query string value * ref: http://stackoverflow.com/questions/9870512/how-to-obtaining-the-querystring-from-the-current-url-with-javascript * return string */ -function getQueryStringValue (key) { - return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); +function getQueryStringValue(key) { + const safeKey = escapeForRegex(encodeURIComponent(key)); + const regex = new RegExp( + "^(?:.*[&\\?]" + safeKey + "(?:=([^&]*))?)?.*$", + "i" + ); + return decodeURIComponent(window.location.search.replace(regex, "$1")); } /** * Check paramater are available or not in url * return bool */ -function check_condition( key ) { - if( window.location.href.indexOf(key) > 0 ) { - return true; - } else { - return false; - } +function check_condition(key) { + if (window.location.href.indexOf(key) > 0) { + return true; + } else { + return false; + } } /** @@ -2212,131 +2694,144 @@ function check_condition( key ) { * Ref: https://www.kevinleary.net/jquery-parse-url * return bool */ -function check_url( query ) { - query = query.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); - var expr = "[\\?&]"+query+"=([^&#]*)"; - var regex = new RegExp( expr ); - var results = regex.exec( window.location.href ); - if( null !== results ) { - return results[1]; - } else { - return false; - } +function escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function check_url(query) { + query = escapeRegExp(query); + var expr = "[\\?&]" + query + "=([^&#]*)"; + var regex = new RegExp(expr); + var results = regex.exec(window.location.href); + if (null !== results) { + return results[1]; + } else { + return false; + } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ -var commentObj = {}; -var plupload_comment_main = {}; -var comment_media_wrapper = 'comment-media-wrapper-'; -var rtmedia_comment_media_submit = 'rtmedia-comment-media-submit-'; -var comment_media_add_button = 'rtmedia-comment-media-upload-'; -var comment_media_uplaod_media = 'rtMedia-start-upload-'; - - -jQuery(document).ready(function($) { - - rtMediaHook.register( 'rtmedia_js_popup_after_content_added', function() { - var popup_upload_comment = jQuery( '.rtmedia-single-container .rtmedia-single-meta .rtm-media-single-comments form' ); - rtmedia_comment_media_upload( popup_upload_comment ); - rtmedia_apply_popup_to_media(); - return true; - } ); - +var commentObj = {}; +var plupload_comment_main = {}; +var comment_media_wrapper = "comment-media-wrapper-"; +var rtmedia_comment_media_submit = "rtmedia-comment-media-submit-"; +var comment_media_add_button = "rtmedia-comment-media-upload-"; +var comment_media_uplaod_media = "rtMedia-start-upload-"; + +jQuery(document).ready(function ($) { + rtMediaHook.register("rtmedia_js_popup_after_content_added", function () { + var popup_upload_comment = jQuery( + ".rtmedia-single-container .rtmedia-single-meta .rtm-media-single-comments form" + ); + rtmedia_comment_media_upload(popup_upload_comment); rtmedia_apply_popup_to_media(); - rtmedia_comment_media_single_page(); - rtmedia_activity_comment_js_add_media_id(); - rtmedia_activity_stream_comment_media(); - rtmedia_buddypress_load_newest_button_click(); + return true; + }); + + rtmedia_apply_popup_to_media(); + rtmedia_comment_media_single_page(); + rtmedia_activity_comment_js_add_media_id(); + rtmedia_activity_stream_comment_media(); + rtmedia_buddypress_load_newest_button_click(); }); - -function rtmedia_reset_video_and_audio(){ - jQuery( 'ul.activity-list li.activity-item div.rtmedia-item-thumbnail > audio.wp-audio-shortcode, ul.activity-list li.activity-item div.rtmedia-item-thumbnail > video.wp-video-shortcode' ).mediaelementplayer( { - // This is required to work with new MediaElement version. - classPrefix: 'mejs-', - // If the