var $ = jQuery.noConflict();

$(window).bind("pageshow", function(event) { //fix safari bug backward/forwards cache  needed for page transitions
    if (event.originalEvent.persisted) {
        window.location.reload();
		console.log('reload page after back button navigation')
    }
})


gsap.registerPlugin(ScrollTrigger);

const showAnim = gsap.from('header.site-header', { 
  yPercent: -100,
  paused: true,
  duration: 0.2
}).progress(1);

ScrollTrigger.create({
  start: "top top",
  end: 99999,
  onUpdate: (self) => {
    self.direction === -1 ? showAnim.play() : showAnim.reverse()
  }
});


function disableScrolltrigger() {
	showAnim.play();
}

if ($('.horizontal-scroll-container').length) {
	//var width = -window.innerWidth/1.1;
	var width = -document.querySelector('#hero').scrollWidth;
	gsap.set('#homeIllustrationCar', { x: '0%' })
	gsap.to('#homeIllustrationCar', {
	  //x: '-100%',
	  x: () => width,
	  ease: "none",
	  scrollTrigger: {
		trigger: "#hero",
		start: "top 0%",
		end: "bottom 1%",
		  invalidateOnRefresh: true,
		scrub: true
	  }
	})
}

if ($('.parallax').length) {
	gsap.set('.parallax', {  y: -60   })
	var parallax = gsap.utils.toArray('.parallax');
	parallax.forEach((section) => {

	  gsap.to(section, { yPercent: 60,
		scrollTrigger: {
			trigger: section,
			//start: 'top 90%',
			scrub: true,
			//end: 'bottom 90%',
			//markers: true
		  },
		  //ease: "power3.inOut"
		});

	})
}

if ($('.parallax-slow').length) {
	gsap.set('.parallax-slow', {  y: 50   })
	var parallaxSlow = gsap.utils.toArray('.parallax-slow');
	parallaxSlow.forEach((section) => {

	  gsap.to(section, { yPercent: -10,
		scrollTrigger: {
			trigger: section,
			start: 'top 90%',
			scrub: true,
			end: 'bottom 90%',
		   // markers: true
		  },
		  //ease: "power3.inOut"
		});

	})
}

if ($('.parallax-up').length) {
	gsap.set('.parallax-up', {  y: 60   })
	gsap.to(".parallax-up", {
	  yPercent: -40,
	  ease: "none",
	  scrollTrigger: {
		trigger: ".parallax-up-container",
		// start: "top bottom", // the default values
		// end: "bottom top",
		scrub: true
	  }, 
	});
}

if ($('.fade-in').length) {
	gsap.set('.fade-in', {  opacity: 0   })
	var fadeIns = gsap.utils.toArray('.fade-in');
	fadeIns.forEach((section) => {
	  gsap.to(section, { alpha: 1,
		scrollTrigger: {
			trigger: section,
			start: 'top 95%',
			scrub: true,
			end: 'top 65%',
		  toggleActions: "play none none reverse",
		  invalidateOnRefresh: true,
			//markers: true
		  },
		  ease: "power2.inOut"
		});
	})
}

if ($('.fade-in-up').length) {
	gsap.set('.fade-in-up', {  opacity: 0, y: 20  })
	var fadeInUps = gsap.utils.toArray('.fade-in-up');
	fadeInUps.forEach((section) => {
	  gsap.to(section, { alpha: 1, y: 0,
		scrollTrigger: {
			trigger: section,
			start: 'top 95%',
			scrub: true,
			end: 'top 65%',
		  toggleActions: "play none none reverse",
		  invalidateOnRefresh: true,
			//markers: true
		  },
		  ease: "power2.inOut"
		});
	})
}

if ($('.fade-in-footer').length) {
	// gsap.set('.fade-in-footer', {  opacity: 0   })  // using css tranforms for opacity now
	var fadeInFooters = gsap.utils.toArray('.fade-in-footer');
	fadeInFooters.forEach((section) => {
	  gsap.to(section, { alpha: 1,
		scrollTrigger: {
			trigger: section,
			start: '80% 95%',
			scrub: true,
			end: '80% 89%',
		  onEnter: () => $(this).addClass('revealed'),
      onLeave: () => $(this).removeClass('revealed'),
      onEnterBack: () => $(this).addClass('revealed'),
      onLeaveBack: () => $(this).removeClass('revealed'),  //expecting to see class 'revaled' on these .fade-in-footer elements but no luck?! 
			markers: false
		  },
		  ease: "power2.inOut"
		});
	})
}

gsap.defaults({ease: "power3"});
if ($('.fade-in-staggered').length) {
	gsap.set(".fade-in-staggered", {opacity: "0"});

	ScrollTrigger.batch(".fade-in-staggered", {
	  start: "top bottom-=10px",
	  onEnter: batch => gsap.to(batch, {opacity: 1, duration: 1.5, stagger: 0.25}),
	  onLeaveBack:batch => gsap.to(batch, {opacity: 0, duration: 1.5, stagger: 0.25})
	});

	ScrollTrigger.addEventListener("refreshInit", () => gsap.set(".fade-in-staggered", {opacity: 0 }));
}
  


jQuery(document).ready(function($) {
	
	
	$('a:not(.external):not([target="_blank"])').on('click', function(e) {
		
		if ($(this).hasClass('external')) { return true; }
		e.preventDefault();
		if ($(this).data('href')) { $href = $(this).data('href'); } 
			else { $href=$(this).attr('href'); }

		if ($href!='#') { 
			$('#primary, footer').animate({ 'opacity':'0'}, function() {
				$('#nav-icon').removeClass('open');
				$('#site-navigation').removeClass('toggled');
				window.location.href=$href;
			});
		} 
	})
	
	
	$('.button, .events-form-submit-button').on('mouseover', function() {
	  $('.button-arrow-right', this).animate({'margin-left': '12px'},{
		duration: 300,
		iterations: 1
	  });
	}).on('mouseout', function() {
	  $('.button-arrow-right', this).animate({'margin-left': '6px'},{
		duration: 230,
		iterations: 1
	  });
	})
	
	
	$('.events-form-submit-button').append('<svg id="Layer_1" class="button-arrow-right" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98.81 58" style="margin-left: 6px;"><defs><style>.arrow-right{fill:#6c6662;}</style></defs><polygon class="arrow-right" points="65.7 55.85 67.67 58 98.81 29 67.67 0 65.7 2.15 93.09 27.57 0 27.57 0 30.43 93.09 30.43 65.7 55.85"></polygon></svg>');

	
	
	$(".credits-trigger").on("click",function(t) {
		t.preventDefault();
		$("#credits").slideToggle();
		$("html, body").animate({scrollTop:$(document).height()},"slow")
	})
	
	
	 $('form#mc-embedded-subscribe-form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
	    	travelclickSignup( $('form#mc-embedded-subscribe-form'), $('#mce-error-response') ); 
        });
	
	$('.musicPlayer').on('click', function(e) {
		e.preventDefault();
		  window.open('/spotify-player.html', 'player', "height=480,width=376");
	})
	
	if ( $('#roomsMap').length && $(window).width() < 767) {
		$('#roomsMap').zoom({url: 'https://www.grandview-gardens.com/instance/front/media/wp-content/themes/sparrowslodge/images/SparrowsLodge_FloorPlan_bw.svg'});
	}
	
	$('body.page-template-page-press .wp-block-column').hover( function() {
		$( '.read-more', this ).animate({ 'opacity':'1' });
	  }, function() {
		$( '.read-more', this ).animate({ 'opacity':'0' });
	  }
	)
	
	
	
	if ( $('body.page-template-page-the-barn-kitchen #tabs-bar').length) { 
		$('.tab-content').hide();
		$('#tabs-bar li a').removeClass('current');
		
		$('#tab-1').addClass('current');
		$('#th-tab-1').fadeIn('slow');

		$('.tab').on('click', function(e) {
			e.preventDefault();
			$('.tab-content').hide();
			$('#tabs-bar li a').removeClass('current');
			$(this).addClass('current');
			$( $(this).attr('href') ).show()
			onResize();
			ScrollTrigger.refresh();
		})
		

	};

	
	if ($('body.page-template-page-gallery').length) {
		$('.magnificPopup').magnificPopup({ delegate: 'img', type: 'image', closeBtnInside: false, gallery:{enabled:true},
			 callbacks: {
				  elementParse: function(item) { item.src = item.el.attr('src'); }
			 }
		});
	}
	
	if ($('.appointments').length) {
		$('.magnific').magnificPopup({ items: {
                src: '#appointment', closeBtnInside: false
            },
			type: 'inline' })
	}
	
	if ($('#scroller').length ) {

		//see https://codepen.io/mikeK/pen/RwGLOmm  and https://greensock.com/forums/topic/26626-customscrollbar-scrolltrigger-draggable/

		// = custom scrollbar ============
		const scrollBar = document.querySelector(".bar");
		const handler = document.querySelector("#handler");
		const scroller = document.querySelector("#scroller");
		var trigger, draggable;  // originally let trigger, draggable; but that caused errors that broke the slideshow on Menus Page template

		trigger = ScrollTrigger.create({
			scroller: scroller,
			start:0,
			end:'max',
			onRefresh: onResize,
			onUpdate: updateHandler
		});

		draggable = Draggable.create(handler, {
			type: "y",
			bounds: ".bar",
			onDrag: function() {
				trigger.scroll(this.y / barLength * maxScroll); 
				console.log(barLength);
			}
		})[0];

		function onResize() {
			if (trigger) {
				trigger.scroll(0); 
				maxScroll = ScrollTrigger.maxScroll(scroller); 
				barLength = scrollBar.offsetHeight - handler.offsetHeight; 
				updateHandler();
			}
		}

		function updateHandler() {
			gsap.set(handler, {y: barLength * trigger.scroll() / maxScroll});
		}

		// ===========

		const gbs = gsap.utils.toArray('span');

		gbs.forEach(gb => {
			gsap.timeline({
				scrollTrigger: {
					scroller:scroller,
					trigger: gb,
					start:'top 200px',

					toggleActions: "play none none reverse",

				}
			})
		});

	}
	
	
}) // document.ready




$(window).on('load', function() {

	$('main#primary').css({ 'margin-top': $('header.site-header').outerHeight() })
	
	//jQuery('#loader').fadeOut();
	$('#primary, footer, .main-navigation ul').animate({'opacity': '1'}, function() {
		if(window.location.hash) { 
			jQuery("html, body").animate({ scrollTop: jQuery(window.location.hash).offset().top - 20 });
			ScrollTrigger.refresh()
			}
		}
	)
	
	
	
	if ($('.custom-scrollbar').length) $(".custom-scrollbar").mCustomScrollbar({
    	theme:"rounded-dark",
		mouseWheel:{ enable: true, preventDefault: false }
	});
	
	
	
	
}) // window.load


function travelclickSignup($form, $responseContainer) {
	var email = $form.find('[name=email]').val();
	var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  	if (!regex.test(email)) {
		$responseContainer.html('The email is invalid').fadeIn();
		return;
	}
	jQuery.ajax('https://www.grandview-gardens.com/instance/front/media/wp-content/slcl/v1/newsletter?email=' + email).done(function(data) {
		if (data == 'Success\r\n') {
			$responseContainer.html('Thank&nbsp;you for your interest.');
			jQuery('.newsletterLabel').fadeOut('2000');
			jQuery('input#mce-EMAIL').val('').prop("disabled",true).fadeOut('1000');
			jQuery('.mc-field-group').fadeOut('1000');
			jQuery('input#mc-embedded-subscribe').val('Thank you!').prop("disabled",true).fadeOut('2500');
		} else {
			//$responseContainer.html(data);
			$responseContainer.html('An error occurred. Please try again.');
		}
	});
}

	
	


/* lottie animation standalone using bodymovin ( see https://airbnb.io/lottie/#/web )  */

function animateJSON(whichID, whichPath, whichDelay, whichLoop) {
	var animation = bodymovin.loadAnimation({
	  container: document.getElementById(whichID),
	  renderer: 'svg',
	  loop: whichLoop,
	  autoplay: false,
	  path: whichPath
	})//animation.play();
	setTimeout(function(){ animation.play(); }, whichDelay);
}

if ( $('body.home').length ) {
	animateJSON('homeIllustrationCar', 'https://www.grandview-gardens.com/JSON/car.json', 0, false)
	//animateJSON('decorPalm', 'https://www.grandview-gardens.com/JSON/palmtree.json', 1000, false)
	animateJSON('home-decor-cactus','https://www.grandview-gardens.com/JSON/cactus.json', 2000, true);
	animateJSON('home-decor-coffee','https://www.grandview-gardens.com/JSON/coffee.json', 3000, true);
	animateJSON('decor-animation-1','https://www.grandview-gardens.com/JSON/wine.json', 3000, true);
}

if ( $('body.page-template-page-contact').length ) {
	animateJSON('contact-decor-bicycle','https://www.grandview-gardens.com/JSON/bike.json', 2000, false);
}

if ( $('body.category-rooms').length ) {
	animateJSON('rooms-decor-umbrella','https://www.grandview-gardens.com/JSON/umbrella1.json', 1000, false);
	animateJSON('rooms-decor-chair','https://www.grandview-gardens.com/JSON/chair.json', 2000, false);
	//animateJSON('rooms-decor-flower2','https://www.grandview-gardens.com/JSON/flower2.json', 1000, false);
}

if ( $('body.page-template-page-history').length ) {
	animateJSON('history-decor-1','https://www.grandview-gardens.com/JSON/palmtree.json', 0, false);
	animateJSON('history-decor-2','https://www.grandview-gardens.com/JSON/cactus.json', 1000, false);
}

if ( $('body.page-template-page-events').length ) {
	animateJSON('events-decor-1','https://www.grandview-gardens.com/JSON/flower1.json', 1000, false);
	//animateJSON('events-decor-2','https://www.grandview-gardens.com/JSON/cheers.json', 1000, false);
}

if ( $('body.page-template-page-the-massage-tent').length ) {
	animateJSON('massageTent-decor-leaf','https://www.grandview-gardens.com/JSON/sparrows_massageTent_leaf1.json', 1000, false);
	/* animateJSON('massageTent-decor-bush','https://www.grandview-gardens.com/JSON/sparrows_massageTent_bush1.json', 1000, false); */
}


if ( $('body.page-template-page-the-barn-kitchen').length ) {
	animateJSON('barnKitchen-decor-flower','https://www.grandview-gardens.com/JSON/sparrows_barnKitchen_flower1.json', 1000, false);
}

/* lottie animation via scrollTrigger: */	

function LottieScrollTrigger(vars) {
	let playhead = {frame: 0},
		target = gsap.utils.toArray(vars.target)[0],
		speeds = {slow: "+=3000", medium: "+=1000", fast: "+=500"},
		st = {trigger: target, pin: false, start: "top 60%", end: speeds[vars.speed] || "+=9000",  markers: false},
		animation = lottie.loadAnimation({
			container: target,
			renderer: vars.renderer || "svg",
			loop: false,
			autoplay: false,
			path: vars.path
		});
	for (let p in vars) { // let users override the ScrollTrigger defaults
		st[p] = vars[p];
	}
	animation.addEventListener("DOMLoaded", function() {
		gsap.to(playhead, {
			frame: animation.totalFrames - 1,
			ease: "none",
			onUpdate: () => animation.goToAndStop(playhead.frame, true),
			scrollTrigger: st
		});
    // in case there are any other ScrollTriggers on the page and the loading of this Lottie asset caused layout changes
    ScrollTrigger.sort();
    ScrollTrigger.refresh(); 
	});
  return animation;
}
	

LottieScrollTrigger({
 target: "#decorPalm",
 path: "https://www.grandview-gardens.com/JSON/palmtree.json",
	toggleActions: "play none none reverse", end: "+=200", scrub: 3
});



LottieScrollTrigger({
 target: "#footerLogoAnimated",
 path: "https://www.grandview-gardens.com/JSON/mountains.json",
 start: "top 96%",
    toggleActions: "play none none reverse", end: "+=200", scrub: 3
});
	
	
LottieScrollTrigger({
 target: "#home-decor-snake",
 path: "https://www.grandview-gardens.com/JSON/snake.json",
 start: "top 86%",
    toggleActions: "play none none reverse", end: "+=200", scrub: 3
});


LottieScrollTrigger({
 target: "#rooms-decor-flower2",
 path: "https://www.grandview-gardens.com/JSON/sparrows_rooms_flower3.json",
 start: "top 86%",
    toggleActions: "play none none reverse", end: "+=200", scrub: 3
});
	
LottieScrollTrigger({
 target: "#rooms-decor-cactus2",
 path: "https://www.grandview-gardens.com/JSON/cactus2.json",
 start: "top 86%",
    toggleActions: "play none none reverse", end: "+=200", scrub: 3
});
	
LottieScrollTrigger({
 target: "#massageTent-decor-bush",
 path: "https://www.grandview-gardens.com/JSON/sparrows_massageTent_bush1.json",
 start: "top 86%",
    toggleActions: "play none none reverse", end: "+=200", scrub: 3
});
	
LottieScrollTrigger({
 target: "#events-decor-2",
 path: "https://www.grandview-gardens.com/JSON/cheers.json",
 start: "top 86%",
    toggleActions: "play none none reverse", end: "+=200", scrub: 3
});
	

if ( $('.main-carousel').length ) {
	var $carousel = $('.main-carousel').flickity({
	  cellAlign: "center", 
		wrapAround : true, 
		contain: true, 
		pageDots: true, 
		prevNextButtons: false, 
		arrowShape: "M 10,50 L 60,100 L 65,95 L 20,50  L 65,5 L 60,0 Z"
	});

	$carousel.on( 'staticClick.flickity', function( event, pointer, cellElement, cellIndex ) {
		$this = $(this);
		var flkty = $this.data('flickity');

	  // dismiss if cell was not clicked
	  if ( !cellElement ) {
		return;
	  }
	  // go to next if current cell selected
	  if ( cellIndex == flkty.selectedIndex ) {
		$this.flickity('next');
	  } else {
		$this.flickity( 'select', cellIndex );
	  }
	});
}