(function ($) {
	'use strict';
	//var origW;
	var lastS = 0;
	var $document = $(document);
	var $window = $(window);
	//var $main = $('main');
	var $body = $('body');
	//var $section = $('section');	
	//var $mobile = ($window.width() < 769) ? true : false;	
	
    var vimeoPlayers = []; 
    
	function debounce(func, wait) {
		var lastCallTime;
		return function() {
			var now = Date.now();
			if (lastCallTime && now < lastCallTime + wait) {
				return;
			}
			lastCallTime = now;
			return func.apply(this, arguments);
		};
	}
	
	$document.ready(function () {
		initMenu();		
		//initFAQ();
		scrollDirection();
		bodyBG();		
        vimeoLoad();
	});

	$window.on('load', function () {
		touchTest();
		$body.addClass('loaded');
		orientationWarning();		
		initSlider();
		initAccordion();
		//calcVars();
		onLoad();
		checkForExternalLinks();
		
	});
	
	var onResize = debounce(function() {
		orientationWarning();
		appendSisterSlideImgs('.landlord');
		//onReadyResize();
	}, 250);
	
	var onScroll = debounce(function() {
		bodyBG();
		scrollDirection();
	}, 50);
	
	var onResizeScroll = debounce(function() {
		//revealElements();
	}, 100);
	
	$window.on('resize', onResize);
	$window.on('scroll', onScroll);
	$window.on('resize scroll', onResizeScroll);
	
	document.addEventListener("DOMContentLoaded", function() {
		var image1 = document.querySelector("[id='our-story-hero'] .column-1 img");
		var image2 = document.querySelector("[id='our-story-hero'] .column-2 img");
		
		function swapImages() {
			// Check if window width is less than 768px
			if (window.innerWidth < 768) {
				// Swap the src of the images
                if( typeof(image1)!=='undefined' && image1 !== null && typeof(image2) && image2 !== null ){
                    var tempSrc = image1.src;
                    image1.src = image2.src;
                    image2.src = tempSrc;
                }
			}
		}
		
		// Run when the page is loaded
		swapImages();
		
		// Run when the window is resized
		window.addEventListener('resize', swapImages);
	});
	
	function onLoad() {      
      //$body.addClass('video-open');
      var $chronoformsi = $('div.chronoforms.index *');
      
      var $heroReveal = $('.hero-block .revealme');
      $heroReveal.each(function () {
        var $this = $(this);
        if ($this.isInViewport()) {
          $this.parent().addClass('revealed');
        }
      });
      
      var $mTags = jQuery('p:not(.ignore-nbsp, .ignore-nbsp *),span:not(.ignore-nbsp, .ignore-nbsp *),h1:not(.ignore-nbsp, .ignore-nbsp *),h2:not(.ignore-nbsp, .ignore-nbsp *),h3:not(.ignore-nbsp, .ignore-nbsp *),h4:not(.ignore-nbsp, .ignore-nbsp *),h5:not(.ignore-nbsp, .ignore-nbsp *),h6:not(.ignore-nbsp, .ignore-nbsp *)');
      
      for (var mTag of $mTags) {
        // Skip elements with the 'ignore-class' class
        if(jQuery(mTag).hasClass('ignore-nbsp')) {
          continue;
        }
        var innerHTML = jQuery(mTag).html();
        var lastSpaceIndex = innerHTML.lastIndexOf(' ');
        
        if (lastSpaceIndex !== -1) {
          var firstPart = innerHTML.slice(0, lastSpaceIndex);
          var secondPart = innerHTML.slice(lastSpaceIndex + 1);
          var updatedFirstPart = firstPart.replace(/([^\s]+)\s(?=[^<>]*<\/)/g, '$1&nbsp;');
          mTag.innerHTML = updatedFirstPart + '&nbsp;' + secondPart;
        }
      }
    }
  
	function initAccordion() {
		//var $aheader = $('.a-header');
		$document.on('click', '.a-header', function () {
			var $parent = $(this).parent('.a-item');
			var id = $parent.attr('id');
			
			console.log(id);
			var $accordion = $('#accordion');
			$accordion.find('.a-item').each(function(){
				var $this = $(this);
				console.log($this.attr('id'));
				if($this.attr('id') != id) {
					$this.removeClass('a-open');
				} else {
					console.log('match')
				}
			});
			if(screen.width <= 768){
				window.location.href = '#'+id;
			}
			$parent.toggleClass('a-open');
			
			if($parent.attr('id') == 'a-landlord'){
				appendSisterSlideImgs('.landlord');
			}
		});
	}
	
	function touchTest() {
		var touchDevice = false;
		var testExp = new RegExp('Android|webOS|iPhone|iPad|'
			+ 'BlackBerry|Windows Phone|'
			+ 'Opera Mini|IEMobile|Mobile',
			'i');
		if (!testExp.test(navigator.userAgent)) {
			touchDevice = false;
			$body.addClass('non-touch');
		} else {
			touchDevice = true;
			$body.addClass('touch-me');
		}
	}	

	function orientationWarning() {
		var landscape = ($window.innerHeight > $window.innerWidth) ? false : true;
		var small = ($window.innerHeight > 500) ? false : true;
		if (landscape) {
			$body.addClass('landscape').removeClass('portrait');
		} else {
			$body.addClass('portrait').removeClass('landscape');
		}
		if (small) {
			$body.addClass('small');
		} else {
			$body.removeClass('small');
		}
	}

	function initMenu() {
		var $body = $('body');
		var $parent = $('header .parent a');
		//toggleClass & $bopdy variable intermittently not working.
		//need to do it this way
		$parent.on('click', function (e) {
			e.preventDefault();
			e.stopPropagation();
			if (!$body.hasClass('mega-open')){
				$body.addClass('mega-open');
			} else {
				$body.removeClass('mega-open');
			}
		});
		
		$('#hamburger-menu').click(function(){
			if (!$body.hasClass('mega-open')){
				$body.addClass('mega-open');
			} else {
				$body.removeClass('mega-open');
			}
		});
		
		$body.on('click', function (event) {
			var $target = $(event.target);
			if ($body.hasClass('mega-open') && !$target.closest('.mega-menu').length && !$target.closest('header').length && !$target.hasClass('mega-open')) {
				$body.removeClass('mega-open');
			}			
		});
	}
		
	function checkForExternalLinks() {
		var $htmlBody = $('html, body');
		var $bodyahref = $('body a[href]');
		$bodyahref.on('click', function (e) {
			var a_href = $(this).attr('href');
			a_href = (a_href.indexOf(location.hostname) !== -1) ? a_href.split(location.hostname)[1] : a_href;
			var l_href = (window.location.href.indexOf(location.hostname) !== -1) ? window.location.href.split(location.hostname)[1] : window.location.href;
			l_href = (l_href.indexOf('#') !== -1) ? l_href.split('#')[0] : l_href;
			if (a_href.indexOf('#') !== -1 && (a_href.split('#')[0] === l_href || a_href.split('#')[0] === '')) {
				e.preventDefault();
				$htmlBody.animate({
					scrollTop: $('#' + a_href.split('#')[1]).offset().top
				}, 500);
			}
			if ($body.hasClass('menu-open')) {
				var $headerParent = $('header .parent a');
				$headerParent.click(); //Close menu
			}
		});
	}

	$.fn.sectionPos = function () {
		var $this = $(this);
		var elementTop = $this.offset().top;
		var viewportTop = $window.scrollTop();
		var inView = $window.height() / 2.5;
		return elementTop < viewportTop + inView;
	}

	$.fn.isInViewport = function () {
		var $this = $(this);
		var elementHeight = ( $this.outerHeight() > $window.height() ) ? $window.height() : $this.outerHeight();
		var elementTop = $this.offset().top;
		var elementBottom = elementTop + elementHeight / 2;
		var viewportTop = $window.scrollTop();
		var viewportBottom = viewportTop + $window.height();
		var $mobile = ($window.width() < 769) ? true : false;
		if (!$mobile) {
			return elementBottom <= viewportBottom - 1;
		} else {
			return elementBottom - ($window.height() / 3) <= viewportBottom;
		}
	};	
	
	function bodyBG() {
		if ($window.width() > 768) {
			const $sections = $('section');
			var $body = $('body');
			setTimeout(function () {
				const observer = new IntersectionObserver(
					(entries) => {
						entries.forEach((entry) => {
							if (entry.isIntersecting) {
								$body.attr("data-background", entry.target.getAttribute("data-background"));
							}
						});
					},
					{
						threshold: 0.5,
					}
				);
				$sections.each(function () {
					observer.observe(this);
				});
			}, 1000);
		}
	}
	
	function scrollDirection() {
		var $body = $('body');
		var scrollPos = $window.scrollTop();
		setTimeout(function () {
			if (scrollPos > lastS) {
				$body.addClass('scroll-down').removeClass('scroll-up');
				lastS = scrollPos - 1;
			} else {
				$body.addClass('scroll-up').removeClass('scroll-down');
				lastS = scrollPos + 1;
			}
		}, 250);
		if (!$window.scrollTop()) {
			$body.addClass('very-top').removeClass('scroll-up').removeClass('scroll-down');
		} else {
			$body.removeClass('very-top');
		}
		if ($window.scrollTop() > 600) {
			$body.removeClass('page-top');
		}
	}
	
	var element = '';
	function getArrowElement(element) {
		var $element = $(element);
		if ($window.width() < 769) {
			return $element.siblings().children('.mob-slider-arrows');
		} else {
			return $element;
		}
	}
	$document.ready(function () {
		if ($window.width() < 769) {
			var $hs = $('.half-slider');
			$hs.slick('slickRemove', 0);
			getArrowElement(element);
		}
	});

	$window.on('resize', function () {
		getArrowElement(element);
	});
		
	function initSlider() {	
		var $vw = $('.fw-slider');
		$vw.each(function(index, element) {
			var $element = $(element);
			$element.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: true,
				infinite: ($element.find('div[data-video]').length) ? false : true,
				autoplay: false,
				arrows: true,
				appendDots: $element.siblings('.slider-dots'),
			});
		});
		
		var $hero = $('.hero-slider .slider');
		$hero.each(function(index, element) {
			var $element = $(element);
			$element.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: true,
				infinite: true,
				autoplay: true,
				arrows: true,
				appendDots: $element.siblings('.slider-dots'),
				speed:700,
				pauseOnHover:false,
				pauseOnFocus:false
			});
		});

		
		var $sister = $('.sister-slider-text');
		$sister.each(function(index, element) {
			var $element = $(element);
			$element.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: false,
				infinite: true,
				autoplay: false,
				arrows: true,
				fade: true,
				cssEase: 'ease',
				respondTo: 'slider',
				asNavFor:'.sister-slider-img',
				//appendArrows: getArrowElement(element),
				responsive: [{
					breakpoint: 769,
					settings: {						
						slidesToShow: 1,
						asNavFor:'.sister-slider-img',
						dots: true,
						appendDots: $element.next('.slider-dots'),
					}
				}]
			});
		});
		
		var $sister2 = $('.sister-slider-img');
		$sister2.each(function(index, element) {
			var $element = $(element);
			$element.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: false,
				infinite: true,
				autoplay: false,
				arrows: false,
				respondTo: 'slider',
				asNavFor:'.sister-slider-text',
				//appendArrows: getArrowElement(element),
				responsive: [{
					breakpoint: 769,
					settings: {						
						slidesToShow: 1,
						asNavFor:'.sister-slider-text',
						dots: false,
					}
				}]
			});
		});
		
		if(screen.width <= 768){
			appendSisterSlideImgs('.landlord');
			appendSisterSlideImgs('#sister-sites-our-story');
		}
		
		var $tms = $('.testimonials-slider');
		$tms.each(function (index, element) {
			var $element = $(element);
			$element.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: false,
				appendDots: $element.siblings('.slider-dots'),
				infinite: true,
				autoplay: false,
				arrows: true,
				centerMode: false,
				respondTo: 'slider',
				fade:true,
				cssEase: 'linear',
				
				responsive: [{
					breakpoint: 769,
					settings: {						
						dots: true,
						appendDots: $element.next('.slider-dots')
					}
				}]
			});
		});
		
		var $ss = $('.small-slider');
		$ss.each(function (index, element) {
			var $element = $(element);
			$element.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: false,
				infinite: true,
				autoplay: false,
				arrows: true,
				centerMode: false,
				respondTo: 'slider',
				fade:true,
				cssEase: 'linear',
				responsive: [{
					breakpoint: 769,
					settings: {						
						dots: true,
						appendDots: $element.next('.slider-dots')
					}
				}]		
			});
		});
		
		var $mms = $('.media-slider');
		$mms.each(function (index, element) {
			var $element = $(element);
			$element.slick({
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: false,
				infinite: true,
				autoplay: false,
				arrows: true,
				centerMode: false,
				respondTo: 'slider',
				fade:true,
				cssEase: 'linear'
			});
		});
		
		$('.slide-link').click(function(){
			$mms.slick('slickNext');
		});
		
		
		if($mms.length > 0){
			var $media = $('.media-slider');
			checkCurrentSlide($media.slick('slickCurrentSlide'));
			$media.on('afterChange', function(event, slick, direction){
				checkCurrentSlide($mms.slick('slickCurrentSlide'));
			});
		}
	}
	function checkCurrentSlide(currentSlick){
		var $body = $('body');
		// your acction for current slick
		if(currentSlick == 1){
			$body.addClass('slide-hero-orange');
		} else {
			$body.removeClass('slide-hero-orange');
		}			
		if(currentSlick == 3 || currentSlick == 5 || currentSlick == 2){
			$body.addClass('slide-hero-dark');
		} else {
			$body.removeClass('slide-hero-dark');
		}
		console.log('Current Slick:', currentSlick);
	}
	
	function appendSisterSlideImgs(section){
			var textSlides = $(section+' .sister-slider-text .slide-image-append');
			textSlides.each(function(){
				var $this = $(this);
				if($this.find('img').length == 0){
					var id = $this.data('img');
					console.log(id);
					var $img = $(section+' .sister-slider-img img[data-img="'+id+'"]');
					$($img[0]).clone().appendTo(this);
				}
				
			});
			$(section+' .sister-slider-img').slick('refresh');
	}
    
    
    function vimeoLoad(){
        var vCnt = 0;
        $('[data-video]:not(.done)').each(function(){
            $(this).addClass('done');
            var vimeoId = $(this).attr('data-video');
            if( $(this).hasClass('slide-wrap') ){
                $(this).find('img').first().addClass('hidden');
                $(this).append('<iframe src="https://player.vimeo.com/video/'+vimeoId+'?autoplay=0&mute=1&control=1&loop=0" style="max-width:100vw;" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');
            }else{
                $(this).attr('id','vimeo'+vimeoId).addClass('paused');
                $(this).attr('data-count',vCnt);
                $(this).append('<iframe id="vframe'+vimeoId+'" src="https://player.vimeo.com/video/'+vimeoId+'?autoplay=0&mute=1&control=1&loop=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe><div class="illustration" style="'+$(this).attr('style')+'"></div>');
                $(this).attr('style','');
                var vFrame = document.getElementById('vframe'+vimeoId);
                vimeoPlayers[vCnt] = new Vimeo.Player(vFrame);
                vimeoPlayers[vCnt].on('play', function(data) {
                    this.getVideoId().then(function(theid){ document.getElementById('vimeo' + theid).classList.add('playing'); document.getElementById('vimeo' + theid).classList.remove('paused'); })
                });
                vimeoPlayers[vCnt].on('pause', function(data) {
                    this.getVideoId().then(function(theid){ document.getElementById('vimeo' + theid).classList.add('paused'); document.getElementById('vimeo' + theid).classList.remove('playing'); })
                });
            }
        });
    }
    
})(jQuery);


