// source --> https://www.ormsprintroom.co.za/wp-content/plugins/easy-facebook-likebox/facebook/frontend/assets/js/public.js?ver=6.7.2 
jQuery(document).ready(function($) {

  jQuery('.efbl-popup-carousel-container img').removeAttr('srcset');

  /*
  *	Check if the like box has loaded. If yes then remove loader and add animation class!
  */

  if ($('.efbl_feed_wraper .efbl_custom_likebox')[0] ||
      $('.widget_easy_facebook_page_plugin .efbl-like-box')[0]) {

    if (typeof FB === 'undefined' || FB === null) {

      setTimeout(function() { $('.efbl-loader').remove(); }, 3000);

    }
    else {

      FB.Event.subscribe('xfbml.render', function(response) {

        var animclasses = $('.efbl-like-box .fb-page').data('animclass');

        $('.efbl-loader').remove();

        $('.efbl-like-box iframe').addClass('animated ' + animclasses);

      });

    }
  }

  // Sanitize content to prevent XSS attacks
  function sanitizeContent(content) {
    if (!content) return '';
    
    // Create a temporary div to safely parse and sanitize HTML
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = content;
    
    // Remove script tags and event handlers
    var scripts = tempDiv.querySelectorAll('script');
    for (var i = 0; i < scripts.length; i++) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }
    
    // Remove event handlers from all elements
    var allElements = tempDiv.querySelectorAll('*');
    for (var i = 0; i < allElements.length; i++) {
      var element = allElements[i];
      var attributes = element.attributes;
      for (var j = attributes.length - 1; j >= 0; j--) {
        var attr = attributes[j];
        if (attr.name.toLowerCase().startsWith('on') || 
            attr.name.toLowerCase() === 'javascript:' ||
            attr.value.toLowerCase().includes('javascript:')) {
          element.removeAttribute(attr.name);
        }
      }
    }
    
    return tempDiv.innerHTML;
  }

  // Magic function that will prepare and render markup.
  function efbl_render_poup_markup(object) {

    var $story_link = object.data('storylink'),
        $story_link_text = object.data('linktext'),
        $caption = object.data('caption'),
        $image_url = object.data('imagelink'),
        $iframe_vid_url = object.data('videolink'),
        $video_url = object.data('video'),
        $itemnumber = object.data('itemnumber'),
        $windowWidth = window.innerWidth,
        $windowHeight = window.innerHeight - 200;

    // Detect GDPR mode and consent for this feed container.
    var $feedContainer = object.closest('.efbl_feed_wraper');
    var flagsAttr = $feedContainer.length ? ($feedContainer.attr('data-esf-flags') || '') : '';
    var flags = flagsAttr ? flagsAttr.split(',') : [];
    var hasGdpr = flags.indexOf('gdpr') > -1;
    var mode = 'none';

    if (flags.indexOf('gdpr_yes') > -1) {
      mode = 'yes';
    } else if (flags.indexOf('gdpr_auto') > -1) {
      mode = 'auto';
    }

    var consentGiven = false;
    if (window.ESFGDPR && typeof window.ESFGDPR.checkConsent === 'function' && $feedContainer.length) {
      consentGiven = window.ESFGDPR.checkConsent($feedContainer);
    }

    // Media is allowed only when:
    // - GDPR is not enabled, OR
    // - mode is "auto" and consent has been given.
    var mediaAllowed = true;
    if (hasGdpr) {
      if (mode === 'yes') {
        mediaAllowed = false;
      } else if (mode === 'auto' && !consentGiven) {
        mediaAllowed = false;
      }
    }

    $('.white-popup .efbl_popup_left_container').css({
      'width': 'auto',
      'height': 'auto',
    });

    $('.efbl_popup_image').css('height', 'auto');

    // Helper to get a placeholder image URL from the clicked element, if available.
    function getPlaceholderFromElement(el) {
      var bg = el.css('background-image') || '';
      if (!bg || bg === 'none') {
        return '';
      }
      // Expect format: url("...") or url('...') or url(...)
      bg = bg.replace(/^url\((['"]?)/, '').replace(/(['"]?)\)$/, '');
      return bg;
    }

    // IMAGES
    if ($image_url) {
      if (mediaAllowed) {
        $('#efblcf_holder .efbl_popup_image').attr('src', $image_url);
        $('#efblcf_holder .efbl_popup_image').css('display', 'block');
      } else {
        var placeholderImg = getPlaceholderFromElement(object);
        if (placeholderImg) {
          $('#efblcf_holder .efbl_popup_image').attr('src', placeholderImg);
          $('#efblcf_holder .efbl_popup_image').css('display', 'block');
        } else {
          // No safe placeholder, hide image completely.
          $('#efblcf_holder .efbl_popup_image').attr('src', '');
          $('#efblcf_holder .efbl_popup_image').css('display', 'none');
        }
      }
    }

    // IFRAME VIDEO
    if ($iframe_vid_url) {
      if (mediaAllowed) {
        $('#efblcf_holder .efbl_popup_if_video').attr('src', $iframe_vid_url);
        $('#efblcf_holder .efbl_popup_if_video').css({
          'display': 'block',
          'width': '720px',
          'height': '400px',
        });
      } else {
        $('#efblcf_holder .efbl_popup_if_video').attr('src', '');
        $('#efblcf_holder .efbl_popup_if_video').css('display', 'none');
      }

    }

    // HTML5 VIDEO
    if ($video_url) {
      if (mediaAllowed) {
        $('#efblcf_holder .efbl_popup_video').attr('src', $video_url);
        $('#efblcf_holder .efbl_popup_video').css('display', 'block');
        setTimeout(function() {
          $('#efblcf_holder .efbl_popup_video')[0].play();
        }, 500);
      } else {
        $('#efblcf_holder .efbl_popup_video').attr('src', '');
        $('#efblcf_holder .efbl_popup_video').css('display', 'none');
      }

    }

    //$('.efbl-popup-next').attr('data-itemnumber', $itemnumber+1);
    //$('.efbl-popup-prev').attr('data-itemnumber', $itemnumber-1);

    $('.efbl_feed_wraper #item_number').val($itemnumber);

    if ($caption) {
      // Sanitize caption and link text to prevent XSS
      var sanitizedCaption = sanitizeContent($caption);
      var sanitizedLinkText = sanitizeContent($story_link_text);
      
      $('#efblcf_holder .efbl_popupp_footer').
          html(
              '<p>' + sanitizedCaption + ' <br> <a class="efbl_popup_readmore" href="' +
              $story_link + '" target="_blank">' + sanitizedLinkText +
              '</a></p>');
      $('#efblcf_holder .efbl_popupp_footer').css('display', 'block');
    }

  }

  function reset_popup_holder() {
    //Clear the container for new instance
    $('#efblcf_holder .efbl_popup_image').attr('src', '');
    $('#efblcf_holder .efbl_popup_image').css('display', 'none');

    $('#efblcf_holder .efbl_popup_if_video').attr('src', '');
    $('#efblcf_holder .efbl_popup_if_video').css('display', 'none');

    $('#efblcf_holder .efbl_popup_video').attr('src', '');
    $('#efblcf_holder .efbl_popup_video').css('display', 'none');

    $('#efblcf_holder .efbl_popupp_footer').html('');
    $('#efblcf_holder .efbl_popupp_footer').css('display', 'none');
  }

  $('.efbl_feed_popup').esfFreePopup({
    type: 'ajax',
    tLoading: 'Loading...',
    preloader: false,
    mainClass: 'esfp-fade',

    callbacks: {

      ajaxContentAdded: function() {
        // Ajax content is loaded and appended to DOM

        efbl_render_poup_markup(this.st.el);

        // GDPR: if consent is already given and popup content contains
        // placeholder images (esf-no-consent), swap them to real URLs.
        if (window.ESFGDPR && typeof window.ESFGDPR.checkConsent === 'function') {
          try {
            // Use the first feed wrapper on the page to evaluate consent state.
            var $feedContainer = jQuery('.efbl_feed_wraper').first();
            if ($feedContainer.length && window.ESFGDPR.checkConsent($feedContainer)) {
              // Target the most recently added popup.
              var $popup = jQuery('.efbl-popup').last();
              if ($popup.length) {
                $popup.find('.esf-no-consent').each(function() {
                  var $element = jQuery(this);
                  var realImageUrl = $element.attr('data-image-url');

                  if (realImageUrl) {
                    // Update <img> tag if present.
                    var $img = $element.is('img') ? $element : $element.find('img');
                    if ($img.length) {
                      $img.attr('src', realImageUrl);
                    }

                    // Also update background-image if used.
                    $element.css('background-image', 'url(' + realImageUrl + ')');

                    $element.removeClass('esf-no-consent');
                    $element.removeAttr('data-image-url');
                  }
                });
              }
            }
          } catch (e) {
            // Fail silently; do not break popup if something goes wrong.
          }
        }
      },

      beforeOpen: function() {
        // console.log(this.st.el);

        // efbl_render_poup_markup(this.st.el);

      },

      beforeClose: function() {

        reset_popup_holder();

      },
    },

  });

  $('.efbl_share_links').click(function() {
    $(this).next('.efbl_links_container').slideToggle('slow');
  });

  $('.efbl_info').click(function() {
    $(this).siblings('.efbl_comments_wraper').slideToggle('slow');
  });

  jQuery(document).
      on('click', 'div[data-class=\'efbl_redirect_home\']', function(event) {

        window.open(
            'https://easysocialfeed.com/?utm_campaign=powered-by&utm_medium=link&utm_source=plugin',
            '_blank');
      });

  $('.esf-share').click(function(e) {
    e.preventDefault();
    $(this).next().slideToggle();
  });

});
// source --> https://www.ormsprintroom.co.za/wp-content/plugins/grid-kit-premium/js/gkit-winready.js?ver=6.9.4 
(function(funcName, baseObj) {
    // The public function name defaults to window.docReady
    // but you can pass in your own object and own function name and those will be used
    // if you want to put them in a different namespace
    funcName = funcName || "docReady";
    baseObj = baseObj || window;
    var readyList = [];
    var readyFired = false;
    var readyEventHandlersInstalled = false;

    // call this when the document is ready
    // this function protects itself against being called more than once
    function ready() {
        if (!readyFired) {
            // this must be set to true before we start calling callbacks
            readyFired = true;
            for (var i = 0; i < readyList.length; i++) {
                // if a callback here happens to add new ready handlers,
                // the docReady() function will see that it already fired
                // and will schedule the callback to run right after
                // this event loop finishes so all handlers will still execute
                // in order and no new ones will be added to the readyList
                // while we are processing the list
                readyList[i].fn.call(window, readyList[i].ctx);
            }
            // allow any closures held by these functions to free
            readyList = [];
        }
    }

    function readyStateChange() {
        if ( document.readyState === "complete" ) {
            ready();
        }
    }

    // This is the one public interface
    // docReady(fn, context);
    // the context argument is optional - if present, it will be passed
    // as an argument to the callback
    baseObj[funcName] = function(callback, context) {
        if (typeof callback !== "function") {
            throw new TypeError("callback for docReady(fn) must be a function");
        }
        // if ready has already fired, then just schedule the callback
        // to fire asynchronously, but right away
        if (readyFired) {
            setTimeout(function() {callback(context);}, 1);
            return;
        } else {
            // add the function and context to the list
            readyList.push({fn: callback, ctx: context});
        }
        // if document already ready to go, schedule the ready function to run
        if (document.readyState === "complete") {
            setTimeout(ready, 1);
        } else if (!readyEventHandlersInstalled) {
            // otherwise if we don't have event handlers installed, install them
            if (document.addEventListener) {
                // first choice is DOMContentLoaded event
                document.addEventListener("DOMContentLoaded", ready, false);
                // backup is window load event
                window.addEventListener("load", ready, false);
            } else {
                // must be IE
                document.attachEvent("onreadystatechange", readyStateChange);
                window.attachEvent("onload", ready);
            }
            readyEventHandlersInstalled = true;
        }
    }
})("gkitWinReady", window);
// source --> https://www.ormsprintroom.co.za/wp-content/plugins/grid-kit-premium/js/gkit-pkg.js?ver=6.9.4 

var GKIT_PKG_TYPE_FREE = "free";
var GKIT_PKG_TYPE_PREMIUM = "premium";
var GKIT_PKG_TYPE = GKIT_PKG_TYPE_PREMIUM;
// source --> https://www.ormsprintroom.co.za/wp-content/plugins/grid-kit-premium/js/crp-helper.js?ver=6.9.4 
var _CRP_LAST_GENERATED_ID = 100000;
function crp_generateId(){
    return "tmpid_" + (++_CRP_LAST_GENERATED_ID).toString();
}

var crpUids = [];
function crp_generateUniqueId() {
    var uid = new Date().valueOf() + Math.floor(Math.random() * 11);
    if (jQuery.inArray(uid, crpUids) != -1) {
        return crp_generateUniqueId();
    }
    crpUids.push(uid);
    return uid;
}


function crp_showSpinner(message="Loading...") {
  jQuery("#crp-spinner").css('display', 'block');
  jQuery("#crp-spinner-message").css('display', 'block');
  jQuery("#crp-spinner-message").html(message);
  jQuery("#crp-spinner-background").css('display', 'block');
}

function crp_hideSpinner() {
    setTimeout(function(){
        jQuery("#crp-spinner").css('display', 'none');
        jQuery("#crp-spinner-message").css('display', 'none');
        jQuery("#crp-spinner-background").css('display', 'none');
    }, 1000);
}

function crp_openMediaUploader( callback, multipleSelection, notSelectedCallback, type ) {
	'use strict';

    multipleSelection = typeof multipleSelection !== 'undefined' ? multipleSelection : false;
    var uploader, imgData, json;

	if ( undefined !== uploader ) {
		uploader.open();
		return;
	}

	var params = {
        frame:    'post',
        state:    'insert',
        multiple: multipleSelection
    };
	if (typeof type == 'undefined') {
       type = 'image';
    }
    params.library = {
        type: [ type ]
    };
	uploader = wp.media.frames.file_frame = wp.media(params);

    if (typeof notSelectedCallback != 'undefined') {
        uploader.on('close', function () {
            var selection = uploader.state('insert').get('selection');
            if (!selection.length) {
                notSelectedCallback();
            }
        });
    }

	uploader.on( 'insert', function() {
        var selections = uploader.state().get( 'selection').toJSON();
        var picInfos = [];

        for(var sIdx = 0; sIdx < selections.length; sIdx++){
            var json = selections[sIdx];
            if ( 0 > jQuery.trim( json.url.length ) ) {
                continue;
            }

            var picInfo = {};
            picInfo.id = json.id;
            if (json.type == 'image') {
                picInfo.src = json.sizes.full.url;

                if (json.sizes.medium) {
                    picInfo.src = json.sizes.medium.url;
                }
            } else if(json.type == 'video') {
                picInfo.src = json.url;
                picInfo.thumb = crpPluginUrl + '/images/general/video_default.jpg';
                // if (json.thumb.src) {
                //     picInfo.thumb = json.thumb.src;
                // } else {
                //     picInfo.thumb = json.icon;
                // }
            }
            picInfos.push(picInfo);
        }

        if(multipleSelection){
            callback(picInfos);
        }else{
            callback(picInfos.length > 0 ? picInfos[0] : null);
        }
	});
	uploader.open();
}

function crp_isJSArray(obj){
    return (Object.prototype.toString.call( obj ) === '[object Array]')
}

function crp_truncateIfNeeded(text, maxLength){
    if(text){
        if(text.length > 3 && text.length > maxLength - 3){
            text = text.substring(0,maxLength - 3);
            text += "..."
        }
    }
    return text;
}

function crp_loadHref(href, blank){
    if(!blank){
        window.location.href = href;
    }else{
        window.open(href, '_blank');
    }
}

function crp_mgfCloseButtonMarkup(){

    var html = "";
    html += "<button class='mfp-close'>";
    html +=     "x"; //"<img class='mfp-close-img'/>";
    html += "</button>"

    return html;
}


var CrpBase64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    if(!input) return output;
    input = CrpBase64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    if(!input) return output;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = this._keyStr.indexOf(input.charAt(i++));
        enc2 = this._keyStr.indexOf(input.charAt(i++));
        enc3 = this._keyStr.indexOf(input.charAt(i++));
        enc4 = this._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = CrpBase64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

}
function crp_insertParam(url, key, value)
{
    key = encodeURI(key);
    value = encodeURI(value);
    var kvp = url.substr(1).split('&');
    var i = kvp.length;
    var x;
    while(i--) {
        x = kvp[i].split('=');

        if (x[0]==key) {
            x[1] = value;
            kvp[i] = x.join('=');
            break;
        }
    }

    if (i<0) {
        kvp[kvp.length] = [key,value].join('=');
    }

    return kvp.join('&');
}

function crp_tagEscape(tag) {
    return tag.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}

function gkitConsoleLog(msg) {
  console.log("GRID KIT ( " + (GKIT_PKG_TYPE == GKIT_PKG_TYPE_PREMIUM ? "PREMIUM" : "FREE") + " ) : " + msg);
};