/home/moonrcjl/template.moontelict.com/freegen/assets/js/main.js
/***************************************************
==================== JS INDEX ======================
****************************************************
01. PreLoader Js
02. mobile menu Js
03. Sticky Header Js
04. Sidebar Js
05. overlay not working js
06. Close Handlers js
07. Common Js
08. Masonary Js
09. magnificPopup img view
10. Nice Select Js
11. Counter Js
12. backToTop
13. mtblog__item Active Item 
14. Smooth Scroll Js
15. scroll-scale-up-img
16. Text Invert With Scroll 
17. webgl images hover animation
18. fade-class-active
19. rotate-text-anim
20. scroll-scale-up-img
21. button hover animation
22. Button Move Animation
23. mt-text-perspective
24. Counter Animation
25. hover reveal start
26. hover image-wrapper
27. carachter Animation
28. portfolio animation start


****************************************************/

(function ($) {
	"use strict";

	var windowOn = $(window);

	// Get Device width
	let device_width = window.innerWidth;

	////////////////////////////////////////////////////
	// 01. PreLoader Js
	windowOn.on('load', function () {
		var body = $('body');
		body.addClass('loaded');
		setTimeout(function () {
			body.removeClass('loaded');
		}, 1500);
	});

	document.addEventListener("DOMContentLoaded", () => {
		const svg = document.getElementById("svg");
		if (!svg) return;

		const tls = gsap.timeline();
		const curve = "M0 502S175 272 500 272s500 230 500 230V0H0Z";
		const flat = "M0 2S175 1 500 1s500 1 500 1V0H0Z";

		// Loader heading text
		if (document.querySelector(".loader-wrap-heading")) {
			tls.to(".loader-wrap-heading .load-text , .loader-wrap-heading .cont", {
				delay: 0.5,
				y: -100,
				opacity: 0,
			});
		}

		// SVG animation
		tls.to(svg, {
			duration: 0.5,
			attr: { d: curve },
			ease: "power2.in",
		}).to(svg, {
			duration: 0.5,
			attr: { d: flat },
			ease: "power2.out",
		});

		// Loader wrap
		if (document.querySelector(".loader-wrap")) {
			tls.to(".loader-wrap", { y: -1500 })
				.to(".loader-wrap", { zIndex: -1, display: "none" });
		}

		// Pre-header animation (safe check)
		const preHeader = document.querySelector(".pre-header");
		if (preHeader) {
			tls.from(preHeader, { y: 200 }, "-=1.5");

			const preHeaderCont = preHeader.querySelector(".containers");
			if (preHeaderCont) {
				tls.from(preHeaderCont, {
					y: 40,
					opacity: 0,
					delay: 0.1,
				}, "-=1.5");
			}
		}
	});

	////////////////////////////////////////////////////
	// 02. mobile menu Js
	var tpMenuWrap = $('.mt-mobile-menu-active > ul').clone();
	var tpSideMenu = $('.mt-offcanvas-menu nav');
	tpSideMenu.append(tpMenuWrap);
	if ($(tpSideMenu).find('.mt-submenu, .mega-menu').length != 0) {
		$(tpSideMenu).find('.mt-submenu, .mega-menu').parent().append('<button class="mt-menu-close"><i class="far fa-chevron-right"></i></button>');
	}
	var sideMenuList = $('.mt-offcanvas-menu nav > ul > li button.mt-menu-close, .mt-offcanvas-menu nav > ul li.has-dropdown > a, .mt-offcanvas-menu nav > ul li.has-dropdown > ul > li.menu-item-has-children > a');
	$(sideMenuList).on('click', function (e) {
		e.preventDefault();
		if (!($(this).parent().hasClass('active'))) {
			$(this).parent().addClass('active');
			$(this).siblings('.mt-submenu, .mega-menu').slideDown();
		} else {
			$(this).siblings('.mt-submenu, .mega-menu').slideUp();
			$(this).parent().removeClass('active');
		}
	});

	///////////////////////////////////////////////////
	// 03. Sticky Header Js
	$(window).on('scroll', function () {
		let scroll = $(window).scrollTop();
		if (scroll < 20) {
			$("#header-sticky").removeClass("header-sticky");
		} else {
			$("#header-sticky").addClass("header-sticky");
		}
	});

	////////////////////////////////////////////////////
	// 04. Sidebar Js
	$(".mt-offcanvas-open-btn").on("click", function () {
		$(".mtoffcanvas__area, .body-overlay").addClass("opened");
	});

	////////////////////////////////////////////////////
	// 05. overlay not working js //
	$('.mt-offcanvas-open-btn').on('click', function () {
		const hasOffcanvas2 = $('.mtoffcanvas__area').length;
		$('.body-overlay').toggleClass('opened', !hasOffcanvas2);
	});
	////////////////////////////////////////////////////
	// 06. Close Handlers //
	$(".mtheader__bar").on("click", function () {
		$(".mtoffcanvas").addClass("opened");
		$(".body-overlay").addClass("apply");
	});
	$(".close-btn").on("click", function () {
		$(".mtoffcanvas").removeClass("opened");
		$(".body-overlay").removeClass("apply");
	});
	$(".body-overlay").on("click", function () {
		$(".mtoffcanvas").removeClass("opened");
		$(".body-overlay").removeClass("apply");
	});
	$(".body-overlay, .mtoffcanvas__close-btn").on("click", function () {
		$(".mtoffcanvas__area").removeClass("opened");
		$(".body-overlay").removeClass("opened");
	});

	$('.mtoffcanvas__area .mt-offcanvas-menu > nav > ul > li').on("mouseenter", function () {
		$(this).addClass('is-active').siblings().removeClass('is-active');
	}).on("mouseleave", function () {
		$(this).siblings().addClass('is-active');
	});

	////////////////////////////////////////////////////
	// 07. Common Js
	// data background
	$("[data-background]").each(function () {
		$(this).css("background-image", "url(" + $(this).attr("data-background") + ")")
	})
	//   data width
	$("[data-width]").each(function () {
		$(this).css("width", $(this).attr("data-width"));
	});
	// data bg color
	$("[data-bg-color]").each(function () {
		$(this).css("background-color", $(this).attr("data-bg-color"))
	})
	// data color
	$("[data-color]").each(function () {
		$(this).css("color", $(this).attr("data-color"))
	})

	////////////////////////////////////////////////////
	// 08. Masonary Js
	$('.grid').imagesLoaded(function () {
		// init Isotope
		var $grid = $('.grid').isotope({
			itemSelector: '.grid-item',
			percentPosition: true,
			masonry: {
				// use outer width of grid-sizer for columnWidth
				columnWidth: '.grid-item',
			}
		});


		// filter items on button click
		$('.masonary-menu').on('click', 'button', function () {
			var filterValue = $(this).attr('data-filter');
			$grid.isotope({ filter: filterValue });
		});

		//for menu active class
		$('.masonary-menu button').on('click', function (event) {
			$(this).siblings('.active').removeClass('active');
			$(this).addClass('active');
			event.preventDefault();
		});

	});

	////////////////////////////////////////////////////
	// 09. magnificPopup img view
	$('.popup-image').magnificPopup({
		type: 'image',
		gallery: {
			enabled: true
		}
	});

	$(".popup-video").magnificPopup({
		type: "iframe",
	});

	////////////////////////////////////////////////////
	// 10. Nice Select Js
	$('.mt-select').niceSelect();


	////////////////////////////////////////////////////
	// 11. Counter Js
	new PureCounter();
	new PureCounter({
		filesizing: true,
		selector: ".filesizecount",
		pulse: 2,
	});

	/////////////////////////////////////////////////////
	// 12. backToTop
	let windowHeight = 0;
	let documentHeight = 0;
	function updateDimensions() {
		windowHeight = window.innerHeight;
		documentHeight = document.documentElement.scrollHeight - windowHeight;
	}
	updateDimensions();
	$(window).on('resize', updateDimensions);

	let $box = $(".scrollToTop");
	if ($box.length) {
		let $water = $box.find(".water");

		$(window).on('scroll', function () {
			let scrollPosition = $(window).scrollTop();
			let percent = Math.min(
				Math.floor((scrollPosition / documentHeight) * 100),
				100
			);

			$water.css("transform", "translate(0," + (100 - percent) + "%)");

			if (scrollPosition >= 200) {
				$box.fadeIn();
			} else {
				$box.fadeOut();
			}
		});

		// Scroll to top
		$box.on('click', function () {
			$('html, body').animate({ scrollTop: 0 }, 'smooth');
		});
	}

	/////////////////////////////////////////////////////
	// 13. mtblog__item Active Item
	$('.mtblog__2 .mtblog__item').on('mouseenter', function () {
		$('.mtblog__item').removeClass('active');
		$(this).addClass('active');
	});

	////////////////////////////////////////////////////
	// 14. Smooth Scroll Js
	gsap.registerPlugin(ScrollTrigger, ScrollSmoother, ScrollToPlugin);
	if ($('#smooth-wrapper').length && $('#smooth-content').length) {
		ScrollSmoother.create({
			smooth: 1.35,
			effects: true,
			smoothTouch: .1,
			ignoreMobileResize: false
		})
	}

	///////////////////////////////////////////////////
	// 15. scroll-scale-up-img
	document.querySelectorAll(".scale-up-img").forEach((section) => {
		let tl = gsap.timeline({
			scrollTrigger: {
				trigger: section,
				start: "top bottom",
				end: "bottom center",
				scrub: 1,
				markers: false,
			},
		});

		tl.to(section.querySelector(".scale-up"), {
			scale: 1.15,
			duration: 1,
		});
	});

	/////////////////////////////////////////////////////
	// 16. Text Invert With Scroll 
	function mt_text_invert() {
		const split = new SplitText(".mt_text_invert", { type: "lines" });
		split.lines.forEach((target) => {
			gsap.to(target, {
				backgroundPositionX: 0,
				ease: "none",
				scrollTrigger: {
					trigger: target,
					scrub: 1,
					start: 'top 85%',
					end: "bottom center"
				}
			});
		});
	}
	$(function () {
		mt_text_invert();
	});


	////////////////////////////////////////////////////
	// 17. webgl images hover animation
	if ($('.mt--hover-item').length) {
		let hoverAnimation__do = function (t, n) {
			let a = new hoverEffect({
				parent: t.get(0),
				intensity: t.data("intensity") || void 0,
				speedIn: t.data("speedin") || void 0,
				speedOut: t.data("speedout") || void 0,
				easing: t.data("easing") || void 0,
				hover: t.data("hover") || void 0,
				image1: n.eq(0).attr("src"),
				image2: n.eq(0).attr("src"),
				displacementImage: t.data("displacement"),
				imagesRatio: n[0].height / n[0].width,
				hover: !1
			});
			t.closest(".mt--hover-item").on("mouseenter", function () {
				a.next()
			}).on("mouseleave", function () {
				a.previous()
			})
		}
		let hoverAnimation = function () {
			$(".mt--hover-img").each(function () {
				let n = $(this);
				let e = n.find("img");
				let i = e.eq(0);
				i[0].complete ? hoverAnimation__do(n, e) : i.on("load", function () {
					hoverAnimation__do(n, e)
				})
			})
		}
		hoverAnimation();
	}

	///////////////////////////////////////////////////
	// 18. fade-class-active
	if ($(".mt_fade_anim").length > 0) {
		gsap.utils.toArray(".mt_fade_anim").forEach((item) => {
			let tp_fade_offset = item.getAttribute("data-fade-offset") || 40,
				tp_duration_value = item.getAttribute("data-duration") || 0.75,
				tp_fade_direction = item.getAttribute("data-fade-from") || "bottom",
				tp_onscroll_value = item.getAttribute("data-on-scroll") || 1,
				tp_delay_value = item.getAttribute("data-delay") || 0.15,
				tp_ease_value = item.getAttribute("data-ease") || "power2.out",
				tp_anim_setting = {
					opacity: 0,
					ease: tp_ease_value,
					duration: tp_duration_value,
					delay: tp_delay_value,
					x: (tp_fade_direction == "left" ? -tp_fade_offset : (tp_fade_direction == "right" ? tp_fade_offset : 0)),
					y: (tp_fade_direction == "top" ? -tp_fade_offset : (tp_fade_direction == "bottom" ? tp_fade_offset : 0)),
				};
			if (tp_onscroll_value == 1) {
				tp_anim_setting.scrollTrigger = {
					trigger: item,
					start: 'top 85%',
				};
			}
			gsap.from(item, tp_anim_setting);
		});
	}

	/////////////////////////////////////////////////////
	// 19. rotate-text-anim
	const rotateText = document.querySelector(".rotate-text-anim");

	if (rotateText) {
		// SplitText apply only if element exists
		let headingTitle = new SplitText(rotateText, { type: "chars" });
		let headingChars = headingTitle.chars;

		let tHero = gsap.timeline({
			scrollTrigger: {
				trigger: rotateText,
				start: "top 80%",
				toggleActions: "play none none none",
			}
		});

		tHero.from(headingChars, {
			rotate: 20,
			ease: "back.out",
			opacity: 0,
			duration: 1,
			stagger: 0.1
		});
	}

	///////////////////////////////////////////////////
	// 20. scroll-scale-up-img
	document.querySelectorAll(".scale-up-img").forEach((section) => {
		let tl = gsap.timeline({
			scrollTrigger: {
				trigger: section,
				start: "top bottom",
				end: "bottom center",
				scrub: 1,
				markers: false,
			},
		});

		tl.to(section.querySelector(".scale-up"), {
			scale: 1.15,
			duration: 1,
		});
	});

	////////////////////////////////////////////////////
	// 21. button hover animation
	$('.mt-btn-rounded').on('mouseenter', function (e) {
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;

		$(this).find('.mt-btn-circle-dot').css({
			top: y,
			left: x
		});
	});

	/////////////////////////////////////////////////////
	// 22. Button Move Animation
	const all_btn = gsap.utils.toArray(".mtbtn__wrap, #btn_wrapper");
	const all_btn_circle = gsap.utils.toArray(".btn-item");

	if (all_btn.length && all_btn_circle.length) {
		all_btn.forEach((btn, i) => {
			const circle = all_btn_circle[i];

			// Mouse move = parallax effect
			$(btn).on("mousemove", function (e) {
				const $this = $(this);
				const relX = e.pageX - $this.offset().left;
				const relY = e.pageY - $this.offset().top;
				gsap.to(circle, {
					duration: 0.5,
					x: ((relX - $this.width() / 2) / $this.width()) * 80,
					y: ((relY - $this.height() / 2) / $this.height()) * 80,
					ease: "power2.out",
				});
			});

			// Mouse leave = reset effect
			$(btn).on("mouseleave", function () {
				gsap.to(circle, {
					duration: 0.5,
					x: 0,
					y: 0,
					ease: "power2.out",
				});
			});
		});
	}

	///////////////////////////////////////////////////
	// 23. mt-text-perspective
	gsap.utils.toArray(".mt-text-perspective").forEach(splitTextLine => {
		const delay_value = parseFloat(splitTextLine.getAttribute("data-delay") || 0.5);
		const tl = gsap.timeline({
			scrollTrigger: {
				trigger: splitTextLine,
				start: 'top 85%',
				duration: 1.5,
				scrub: false,
				markers: false,
				toggleActions: 'play none none none'
			}
		});
		const itemSplitted = new SplitText(splitTextLine, { type: "lines" });
		gsap.set(splitTextLine, { perspective: 400 });
		itemSplitted.split({ type: "lines" });

		tl.from(itemSplitted.lines, {
			duration: 1,
			delay: delay_value,
			opacity: 0,
			rotationX: -80,
			force3D: true,
			transformOrigin: "top center -50",
			stagger: 0.1
		});
	});

	/////////////////////////////////////////////////////
	// 24. Counter Animation
	const bounceItems = gsap.utils.toArray(".bounce_animation .bounce__anim");

	if (bounceItems.length > 0) {
		// Initial state
		gsap.set(bounceItems, { y: -100, opacity: 0 });

		if (device_width < 1023) {
			// Mobile / Tablet
			bounceItems.forEach((item) => {
				let counterTl = gsap.timeline({
					scrollTrigger: {
						trigger: item,
						start: "top center+=200",
					}
				});

				counterTl.to(item, {
					y: 0,
					opacity: 1,
					ease: "bounce",
					duration: 1.5,
				});
			});
		} else {
			// Desktop
			gsap.to(bounceItems, {
				scrollTrigger: {
					trigger: ".bounce_animation",
					start: "top center+=300",
				},
				y: 0,
				opacity: 1,
				ease: "bounce",
				duration: 1.5,
				stagger: {
					each: 0.3,
				}
			});
		}
	}

	const headings_bottom = document.querySelectorAll('.text-scale-anim-bottom');

	headings_bottom.forEach(heading => {
		const textNodes = [];

		heading.childNodes.forEach(node => {
			if (node.nodeType === Node.TEXT_NODE) {
				node.textContent.split(' ').forEach((word, index, array) => {
					const wordSpan = document.createElement('span');
					wordSpan.classList.add('mt-word-span');
					word.split('').forEach(letter => {
						const letterSpan = document.createElement('span');
						letterSpan.classList.add('mt-letter-span');
						letterSpan.textContent = letter;
						wordSpan.appendChild(letterSpan);
					});
					textNodes.push(wordSpan);
					if (index < array.length - 1) {
						textNodes.push(document.createTextNode(' '));
					}
				});
			} else if (node.nodeType === Node.ELEMENT_NODE) {
				textNodes.push(node.cloneNode(true));
			}
		});

		heading.innerHTML = '';
		textNodes.forEach(node => heading.appendChild(node));

		const letters = heading.querySelectorAll('.mt-letter-span');
		letters.forEach(letter => {
			$(letter).on('mouseenter', () => {
				gsap.to(letter, {
					scaleY: 1.3,
					y: '14%',
					duration: 0.2,
					ease: 'sine'
				});
			});

			$(letter).on('mouseleave', () => {
				gsap.to(letter, {
					scaleY: 1,
					y: '0%',
					duration: 0.2,
					ease: 'sine'
				});
			});
		});
	});

	////////////////////////////////////////////////////
	// 25. hover reveal start
	const hoverItem = document.querySelectorAll(".mt-reveal-item");
	function moveImage(e, hoverItem, index) {
		const item = hoverItem.getBoundingClientRect();
		const x = e.clientX - item.x;
		const y = e.clientY - item.y;
		if (hoverItem.children[index]) {
			hoverItem.children[index].style.transform = `translate(${x}px, ${y}px)`;
		}
	}
	hoverItem.forEach((item, i) => {
		$(item).on("mousemove", (e) => {
			setInterval(moveImage(e, item, 1), 50);
		});
	});

	////////////////////////////////////////////////////
	// 26. hover image-wrapper
	const imageWrapper = document.querySelector(".image-wrapper");
	const imageSlider = document.querySelector(".image-slider");
	const projects = gsap.utils.toArray(".projects");

	if (imageWrapper && imageSlider && projects.length > 0) {

		$('[data-index-number]').each((index, el) => {
			$(el).on("mouseenter", () => {
				gsap.to(imageWrapper, {
					opacity: 1,
					duration: 0.5,
				});
			});

			$(el).on("mouseleave", () => {
				gsap.to(imageWrapper, {
					opacity: 0,
					duration: 0.5,
				});
			});

			const projectCount = imageSlider.children.length;
			const movePercent = 100 / projectCount;
			$(el).on("mousemove", function () {
				const indexNumber = $(this).data('index-number');
				gsap.to(imageSlider, {
					y: -(movePercent * indexNumber) + '%',
					duration: 0.6,
					ease: "power2.out"
				});
			});
		})

		$(document).on("mousemove", ".mt-service-wd", function (event) {
			const parentOffset = $(this).offset();
			const relativeX = event.pageX - parentOffset.left;
			const relativeY = event.pageY - parentOffset.top;

			const offsetX = -200;
			const offsetY = 0;

			gsap.to(imageWrapper, {
				x: relativeX - offsetX,
				y: relativeY - offsetY,
				duration: 0.5,
				ease: "power2.out"
			});
		});
	}
	////////////////////////////////////////////////////
	// 27. carachter Animation
	if ($('.mt-char-animation').length > 0) {
		let char_come = gsap.utils.toArray(".mt-char-animation");
		setTimeout(function () {


			char_come.forEach(splitTextLine => {
				const tl = gsap.timeline({
					scrollTrigger: {
						trigger: splitTextLine,
						start: 'top 90%',
						end: 'bottom 60%',
						scrub: false,
						markers: false,
						toggleActions: 'play none none none'
					}
				});
				const itemSplitted = new SplitText(splitTextLine, { type: "chars, words" });
				gsap.set(splitTextLine, { perspective: 300 });
				itemSplitted.split({ type: "chars, words" })
				tl.from(itemSplitted.chars,
					{
						duration: 1,
						delay: 0.5,
						x: 100,
						autoAlpha: 0,
						stagger: 0.05
					});
			});
		}, 200);
	}

	////////////////////////////////////////////////////
	// 28. portfolio animation start
	if ($('.mt-item-anime').length > 0) {
		gsap.set('.mt-item-anime.marque', {
			x: '25%'
		});
		gsap.timeline({
			scrollTrigger: {
				trigger: '.mt-item-anime-area ',
				start: '-1000 10%',
				end: 'bottom 20%',
				scrub: true,
				invalidateOnRefresh: true
			}
		})
			.to('.mt-item-anime.marque ', {
				x: '-100%'
			});
	}

	if ($('.mt-item-anime-md').length > 0) {
		gsap.set('.mt-item-anime-md.marque', {
			x: '2%'
		});
		gsap.timeline({
			scrollTrigger: {
				trigger: '.mt-item-anime-area-md ',
				start: '-100 20%',
				end: 'bottom 20%',
				scrub: true,
				invalidateOnRefresh: true
			}
		})
			.to('.mt-item-anime-md.marque ', {
				x: '-10%'
			});
	}



})(jQuery);