// source --> https://www.lebens-retter.org/wp-content/themes/hello-theme-child/assets/js/typewriter.js?ver=1.0 
/*
 * every jQuery plugin for "typewriter" effect totally sucked
   so I hacked something together.
   
   Then I got a lot of interview questions about when a good time
   to use javascript closures is, and I kept coming back to this
   example; so I generalized it into a proper jQuery plugin.

   Feedback appreciated.
*/

(function ( $ ) {
    $.fn.typewrite = function ( options ) {
        var settings = {
            'selector': this,
            'extra_char': '',
            'delay':    100,
            'trim':     false,
            'callback': null
        };
        if (options) $.extend(settings, options);

        /* This extra closure makes it so each element
         * matched by the selector runs sequentially, instead
         * of all at the same time. */
        function type_next_element(index) {
            var current_element = $(settings.selector[index]);
            var final_text = current_element.text();
            if (settings.trim) final_text = $.trim(final_text);
            current_element.html("").show();

            function type_next_character(element, i) {
                element.html( final_text.substr(0, i)+settings.extra_char );
                if (final_text.length >= i) {
                    setTimeout(function() {
                        type_next_character(element, i+1);
                    }, settings.delay);
                }
                else {
                    if (++index < settings.selector.length) {
                        type_next_element(index);
                    }
                    else if (settings.callback) settings.callback();
                }
            }
            type_next_character(current_element, 0);
        }
        type_next_element(0);

        return this;
    };
})(jQuery);

// example: $('.someclass').typewrite();
// source --> https://www.lebens-retter.org/wp-content/themes/hello-theme-child/assets/js/swiped-events.min.js?ver=1.2.0 
/*!
 * swiped-events.js - v1.2.0
 * Pure JavaScript swipe events
 * https://github.com/john-doherty/swiped-events
 * @inspiration https://stackoverflow.com/questions/16348031/disable-scrolling-when-touch-moving-certain-element
 * @author John Doherty <www.johndoherty.info>
 * @license MIT
 */
!function(t,e){"use strict";"function"!=typeof t.CustomEvent&&(t.CustomEvent=function(t,n){n=n||{bubbles:!1,cancelable:!1,detail:void 0};var a=e.createEvent("CustomEvent");return a.initCustomEvent(t,n.bubbles,n.cancelable,n.detail),a},t.CustomEvent.prototype=t.Event.prototype),e.addEventListener("touchstart",function(t){if("true"===t.target.getAttribute("data-swipe-ignore"))return;l=t.target,r=Date.now(),n=t.touches[0].clientX,a=t.touches[0].clientY,u=0,i=0,o=t.touches.length},!1),e.addEventListener("touchmove",function(t){if(!n||!a)return;var e=t.touches[0].clientX,r=t.touches[0].clientY;u=n-e,i=a-r},!1),e.addEventListener("touchend",function(t){if(l!==t.target)return;var c=parseInt(s(l,"data-swipe-threshold","20"),10),d=s(l,"data-swipe-unit","px"),p=parseInt(s(l,"data-swipe-timeout","500"),10),h=Date.now()-r,v="",b=t.changedTouches||t.touches||[];"vh"===d&&(c=Math.round(c/100*e.documentElement.clientHeight));"vw"===d&&(c=Math.round(c/100*e.documentElement.clientWidth));Math.abs(u)>Math.abs(i)?Math.abs(u)>c&&h<p&&(v=u>0?"swiped-left":"swiped-right"):Math.abs(i)>c&&h<p&&(v=i>0?"swiped-up":"swiped-down");if(""!==v){var E={dir:v.replace(/swiped-/,""),touchType:(b[0]||{}).touchType||"direct",fingers:o,xStart:parseInt(n,10),xEnd:parseInt((b[0]||{}).clientX||-1,10),yStart:parseInt(a,10),yEnd:parseInt((b[0]||{}).clientY||-1,10)};l.dispatchEvent(new CustomEvent("swiped",{bubbles:!0,cancelable:!0,detail:E})),l.dispatchEvent(new CustomEvent(v,{bubbles:!0,cancelable:!0,detail:E}))}n=null,a=null,r=null},!1);var n=null,a=null,u=null,i=null,r=null,l=null,o=0;function s(t,n,a){for(;t&&t!==e.documentElement;){var u=t.getAttribute(n);if(u)return u;t=t.parentNode}return a}}(window,document);
// source --> https://www.lebens-retter.org/wp-content/themes/hello-theme-child/script.js?ver=20260128145617 
function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}


jQuery(document).ready(function($) {


const animate_elements = document.querySelectorAll(".animate-text-line");
const options = {
  root: null,
	rootMargin: "-300px"
};

const animate_elements_observer = new IntersectionObserver (function (entries, observer) {
	entries.forEach(function(entry) {
		if (entry.isIntersecting) {
			entry.target.classList.add("active");
		} else {
			// entry.target.classList.remove("active");
		}
	});
}, options);

animate_elements.forEach(function(el) {
	animate_elements_observer.observe(el);
});


setTimeout(function() {
$('.elementor-tab-title').removeClass('elementor-active');
$('.elementor-tab-content').css('display', 'none'); 
}, 600);


if ($('.typewriter').length > 0) {
const intersectionObserver = new IntersectionObserver((entries) => {
  if (entries[0].intersectionRatio <= 0) return;
  $('.typewriter').typewrite();
});
// start observing
intersectionObserver.observe(document.querySelector(".typewriter"));
}


function playPauseVideo() {
  let videos = document.querySelectorAll("video.wp-block-cover__video-background");
  
  videos.forEach((video) => {
      // We can only control playback without insteraction if video is mute
      video.muted = true;
              let observer = new IntersectionObserver(
                  (entries) => {
                      entries.forEach((entry) => {
                        if (!entry.isIntersecting) {
                          video.pause(); // Pause the TARGET video
                        } else {
                          video.play(); // Play the TARGET video
                        }
                      });
                  },
                  { threshold: 0.2 }
              );
              observer.observe(video);
  });
}

if ($('video.wp-block-cover__video-background').length > 0) {
playPauseVideo();
}

$('.lr-read-more').on('click', function(e) {
e.preventDefault()
var el = $(this).prev();
el.toggleClass('show');
$(this).toggleClass('active');
});


$('#stickyheader .e-n-menu-toggle').on('click', function(e) {
  e.preventDefault()
  $('body').toggleClass('mobile-nav-open');

  if (!$('body').hasClass('mobile-nav-open')) {
    $('#stickyheader .e-n-menu-wrapper > ul > li.e-n-menu-item').removeClass('mobile-active');
  }
  

  });
  
// nth-child muss raus, dafür mit IDs arbeiten, da sonst keine Neupositionierung in der Navi möglich ist
  $('#stickyheader .e-n-menu-wrapper > ul > li.e-n-menu-item:not(:nth-child(7),:nth-child(8)) > .e-n-menu-title').on('click', function(e) {
    e.preventDefault()
    $('#stickyheader .e-n-menu-wrapper > ul > li.e-n-menu-item').removeClass('mobile-active');
    $(this).parent().addClass('mobile-active');
    });
    

    $('#stickyheader .mobile-nav-back').on('click', function(e) {
      e.preventDefault()
      $('#stickyheader .e-n-menu-wrapper > ul > li.e-n-menu-item').removeClass('mobile-active');
      });

      
    function is_touch_enabled() {
      return ( 'ontouchstart' in window ) || 
            ( navigator.maxTouchPoints > 0 ) || 
            ( navigator.msMaxTouchPoints > 0 );
    }


      $('.e-n-menu ul.e-n-menu-heading > li a.e-n-menu-title-container').on('click', function() {
        let hasubNav = $(this).parent().find('button').length > 0 && !$('body').hasClass('mobile-nav-open');
        if (hasubNav) {

          if (is_touch_enabled()) {
            let hasClicked = $(this).hasClass('touched');
            if (hasClicked) {
              let href = $(this).attr('href');
              window.location.href = href;
            } else {
              $(this).addClass('touched');
            }

          } else {
            let href = $(this).attr('href');
            window.location.href = href;
          }
        }
        });
  


      $("#stickyheader .e-n-menu-content").on( "swiped-right", function(event) {
        $('#stickyheader .e-n-menu-wrapper > ul > li.e-n-menu-item').removeClass('mobile-active');
      });

      

$('#ub-expand-source .ub-expand-toggle-button').on('click', function(e) {
e.preventDefault();
$(this).parent().parent().toggleClass('show');
});

$('.post-rating-inline img').on('click', function(event) {    
    event.preventDefault();
    var score = $(this).data("rate");
    var postID = $(this).parent().data("post-id");
   
    if ($('span#post-ratings-'+postID+' img#rating_'+postID+'_'+score).length) {
      var el = $('span#post-ratings-'+postID).find('img#rating_'+postID+'_'+score);
      el.trigger('onmouseover');
      el.click();
      $('.post-rating-inline').remove();
    }
});

$('.post-rating-inline img').hover(
  function() {
    $(this).attr("src","/wp-content/plugins/wp-postratings/images/stars/rating_over.gif");
  }, function() {
    $(this).attr("src","/wp-content/plugins/wp-postratings/images/stars/rating_on.gif");
  }
);

if ( !$('body.has-ratings').length && $('.post-ratings').length > 0) {
  $('.post-ratings img').attr('src','/wp-content/plugins/wp-postratings/images/stars/rating_on.gif')
}

if ( $(window).width() <= 1210) {

var prevScrollPos = 300;
var headerElement = document.getElementById('stickyheader');
var headerHeight = 130; // Adjust this value to the height of your header
window.onscroll = function() {
var currentScrollPos = Math.max(window.scrollY, 0);
if (prevScrollPos >= currentScrollPos) {
headerElement.style.transform = 'translateY(0)';
} else {
headerElement.style.transform = `translateY(-${headerHeight}px)`;
}
prevScrollPos = currentScrollPos;
};

}


$('.openCookieBox a').on('click', function(event) {
  event.preventDefault();
  if (window.BorlabsCookie) {
  window.BorlabsCookie.showCookieBox();
  }
});

/*
$('a.lr-seo-box--more').on('click', function(event) {
  event.preventDefault();

  if ($('.lr-seo-box--keywords li.hide').length > 0) {
  $('.lr-seo-box--keywords li.hide').addClass('showed').removeClass('hide');
  } else {
  $('.lr-seo-box--keywords li.showed').addClass('hide').removeClass('showed');
  $('html, body').animate({
    scrollTop: $("#lr-seo-box").offset().top - 130
}, 500);
  }
});
*/

$('#lr-seo-box-close a').on('click', function(event) {
  event.preventDefault();
  $('#lr-seo-box').hide();
  $('#lr-seo-box-sticky').show();
});

$('#lr-seo-box-sticky a').on('click', function(event) {
  event.preventDefault();
  $('#lr-seo-box').show();
  $('#lr-seo-box-sticky').hide();
});

$('a[href*="#next-tab"]').on('click', function(event) {
  event.preventDefault();
  let parent = $(this).parents().find('.wp-block-ub-tabbed-content');
  let next = parent.find('.wp-block-ub-tabbed-content-tab-title-wrap.active').next();
  if (next.length > 0) {
  next.trigger("focus");
  } else {
    let first = parent.find('.wp-block-ub-tabbed-content-tab-title-wrap').eq(0);
    first.trigger("focus");
  }
});

$('a[href*="#prev-tab"]').on('click', function(event) {
  event.preventDefault();
  let parent = $(this).parents().find('.wp-block-ub-tabbed-content');
  let prev = parent.find('.wp-block-ub-tabbed-content-tab-title-wrap.active').prev();
  if (prev.length > 0) {
    prev.trigger( "focus" );
  } else {
    let first = parent.find('.wp-block-ub-tabbed-content-tab-title-wrap').eq(0);
    first.trigger("focus");
  }
  
});

$('a[href*="#"]').on('click', function(event) {
    
    if (this.hash !== "") {
      var hash = this.hash;
      
      if ($(hash).length > 0) {

      event.preventDefault();
      var offset = $('header .elementor-container').outerHeight();
      $('html, body').animate({
        scrollTop: $(hash).offset().top-(offset+30)
      }, 800);

    }
    }
  });

if ( $('.single-recipe').length ) {

    if ( $('.dr-entry-content .wp-block-video').length ) {
        $( 'a.dr-video-jump-gutenberg' ).addClass('show').on('click', function(e){
            e.preventDefault();
            $("html, body").animate({ scrollTop: $('.dr-entry-content .wp-block-video').eq(0).offset().top - 200}, 1000);
        });
    }

}

if ( $('.form-app-start').length ) {
    var text = $( 'textarea#form-field-message' ).val();
    if (!text) {
        $( 'textarea#form-field-message' ).val('Ich habe Interesse an der Lebens-Retter Ernährung. Meldet euch bei mir.');
    }
    
}
/*
$('a[href*="/jetzt-starten"]').on('click', function(event) {

  event.preventDefault();

  if (elementorFrontend) {
    elementorFrontend.documentsManager.documents[45771].showModal();

  // const url = window.location.href;
  // history.pushState({ page: 1 }, document.title, url);
  
  }
});
*/

$('a[href*="/popup-zugang"]').on('click', function(event) {

  event.preventDefault();

  if (elementorFrontend) {
    elementorFrontend.documentsManager.documents[45891].showModal();
  }
});


var lastScrollTop = 0;
var docHeight = $(document).height();
var windowHeight = $(window).height();

$(window).scroll(function() {
        
var currentScroll = $(this).scrollTop();


if ((currentScroll + windowHeight) > (docHeight - 2000)){ 
  $('body').addClass('bottom-reached');
}

if (currentScroll > 0){  
  $('body').addClass('nav-fixed');
  } else {
  $('body').removeClass('nav-fixed');
}

if (currentScroll < lastScrollTop && currentScroll != 0){  
$('body').addClass('scroll-mode');
} else {
$('body').removeClass('scroll-mode');
}

lastScrollTop = currentScroll;   

});


if ( $('.trigger-popup-stick').length > 0) {

  var popupTriggerBox = $('.trigger-popup-stick');
  var posTop = popupTriggerBox.offset().top;
  var divHeight = popupTriggerBox.outerHeight();
  var setTop = 0;
  var slideEffect = 0;
  var popUpTeaserHeight = 0;
  var placeHolderHeight = 0;

  /*
  $(document).on('elementor/popup/show', function() {
    placeHolderHeight = $('.dialog-message .elementor-location-popup').outerHeight();
    popupTriggerBox.css('padding-bottom',placeHolderHeight+'px');
  });
  $(window).on( "resize", function() {
    placeHolderHeight = $('.dialog-message .elementor-location-popup').outerHeight();
    popupTriggerBox.css('padding-bottom',placeHolderHeight+'px');
  });

*/

  $(window).scroll(function() {
        
    var currentScroll = $(this).scrollTop();
        
    if (currentScroll >= (popupTriggerBox.offset().top + popUpTeaserHeight - windowHeight + divHeight)) { 
      $('body').addClass('trigger-reached');
    
    // setTop = posTop - currentScroll + 10 + divHeight;
    // setTop = posTop + divHeight - currentScroll - 80;
    // slideEffect = (currentScroll / (docHeight - windowHeight)) * 200;
   /* 
    $('.dialog-widget-content').css({
      'top': setTop + 'px'
    });
 
    $('.dialog-widget-content').css({
      'transform' : 'translate3d(0,'+setTop+'px,0)'
    });
  */ 
    } else {
      $('body').removeClass('trigger-reached');
    }
    
    
    });


    $(window).trigger( "resize" );

}



});