jQuery(document).ready(function () {
    // Mobile menu open/close

	supports_touch = false;
    $('body').on('touchstart click', '.mobile-menu-button', { passive: true }, function(event) {
	if (event.type == "touchstart") { 
		supports_touch=true;
	    $(this).toggleClass('open');
	    $('.nav-wrapper').toggleClass('open');
	    $('body').toggleClass('no-scroll');
		// older iOS non-support of vh
		if ($('.nav-wrapper').hasClass('open')) {
			navH = $('.nav-wrapper').outerHeight();
			winH = Math.round(window.innerHeight*.9);
			if (navH<(winH-80)) {
				$('.nav-wrapper').height(winH);
			}
		}
	} else if (event.type == "click" && !supports_touch) {
	    $(this).toggleClass('open');
	    $('.nav-wrapper').toggleClass('open');
	    $('body').toggleClass('no-scroll');
	}
    });

	var menu_interaction=false;
	// click touchstart
    $('.main-nav .has-children').on('touchstart click', '.icon', { passive: true }, function(event) {
		if  (!menu_interaction) {
			menu_interaction=true;
			event.preventDefault();
	        $(this).parents('.has-children').toggleClass('open');
	        //$(this).parents('.has-children').children('ul').toggle();
			menu_interaction=false;
		}
    });

	jQuery('.collapsible').on('click', '.handle', function() {
            parentBox = $(this).parents('.collapsible');
            parentBox.toggleClass('expanded').toggleClass('collapsed');
    })

    /* LAZY LOAD FUNCTION */
    var isInViewport = function (elem, offset) {
        var bounding = elem.getBoundingClientRect();
            var scrollPos = window.pageYOffset;
            botPos = (window.innerHeight || document.documentElement.clientHeight);

        if (bounding.top==0) {
                bounding.top = $(elem).offset().top;
//				console.log($(elem));
//				console.log($(elem).is(':visible'));
        }
                elemPos = bounding.top;
/*
                if (bounding.top>0)
                                elemPos -= botPos;
                */

        if (offset=='double') {
                        adjust = botPos/2;
                        elemPos -= adjust;//bounding.height*offset;
        }
        else if (offset) {
                        adjust = botPos/offset;
                        elemPos -= adjust;//bounding.height*offset;


        } else {
                        if (elemPos>0)
                                elemPos -= botPos;
        }
        return (
                        (elemPos <= 0 && $(elem).is(':visible'))
                        // || (offset!=0 && scrollPos >= elemPos)
                        /*&&
            scrollPos >= elemPos
            bounding.left >= 0 &&
            bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            bounding.right <= (window.innerWidth || document.documentElement.clientWidth)*/
        );
    };

    assetsLoaded = loadedafterscroll = false;
	var scrolled = false;
    function lazyLoadScroll() {

		if (scrolled) {
			if ($('.fb-page').length && !$('#fb-root').length) {
				$('body').prepend('<div id="fb-root"></div><script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v5.0"></script>');
			}
		}
		$('.lazy-bg').each(function() {
			if (isInViewport($(this).get(0),0)) {
				imgsrc=$(this).attr('data-image');
				if (imgsrc)
					$(this).css('background-image', 'url('+imgsrc+')').removeClass('lazy-bg');
			}
		});
        $('.lazy-iframe').each(function() {
        	if (isInViewport($(this).get(0),0)) {
                //console.log($(this));
                framesrc=$(this).attr('data-lazy-src');
                $(this).attr('src', framesrc).removeClass('lazy-iframe');
  
//				console.log('loaded');
//				console.log(framesrc)
      		}
        });
		$('.lazy-img,img.lazyload').each(function() {
			if (isInViewport($(this).get(0),0)) {
				imgsrc=$(this).attr('data-lazy-src');
				if (typeof imgsrc === 'undefined')
					imgsrc =  $(this).attr('data-src');


				$(this).attr('src', imgsrc).removeClass('lazy-img').removeClass('lazyload');
			}
        });

        // content blocks
        $('.contentBlock').each(function() {
                if (isInViewport($(this).get(0),1.2)) {
                        $(this).removeClass('out-of-view').addClass('in-view');
                } else if (!$(this).hasClass('in-view')) { // once it's in view, leave it alone
                        $(this).addClass('out-of-view');
                }
        });

		if (scrolled) {

			if (!loadedafterscroll) {
				loadedafterscroll = true;

				$.getScript('/js/validation.js');
				$.getScript('https://www.google.com/recaptcha/api.js');

				loadCSS('/fancybox2/jquery.fancybox.css');

		        // top slideshow
		        $('.main-header-image > .slideshow .lazy-bg').each(function() {
		           imgsrc=$(this).attr('data-image');
		           $(this).css('background-image', 'url('+imgsrc+')').removeClass('lazy-bg');
		        });

				$.getScript('/js/jquery-ui-1.12.1.min.js', function() {
				    $(".datepicker").datepicker();
				});
				
				$.getScript('/js/jquery.ui.touch-punch.min.js');
				loadCSS('https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css');
				if ($('.share-container').length) {
					$.getScript('//s7.addthis.com/js/300/addthis_widget.js#pubid='+pubid+'&domready=1', function() {
			            addthis.toolbox(
			                        $(".addthis_toolbox").get()
			                    );
					});
/* Moved to GTM 12/5/19
*/
				}
				$("html").addClass("wf-shelby-n7-active").addClass('wf-shelby-n4-active');

/*
				$.getScript('/fancybox2/jquery.fancybox.pack.js', function() {
					$.getScript('/js/fancybox.js?v=2.5');
				});
*/
			    $('.latest-news-wrapper .lazy-bg').each(function() {
//					console.log($(this));
			        imgsrc=$(this).attr('data-image');
					if (imgsrc)
						$(this).css('background-image', 'url("'+imgsrc+'")').removeClass('lazy-bg');
			    });

				loadCSS('/styles/flickity.min.css');
				$.getScript('/js/flickity.min.js', function() {
					$.getScript('/js/dualslides.js');
					$('.latest-news .main-carousel').flickity({
						// options
						cellAlign: 'left',
						imagesLoaded: true,
						wrapAround: true,
						draggable: true,
						prevNextButtons: false
					});
				});
			}
		}

		if (!assetsLoaded) {
			assetsLoaded = true;
			$.getScript('/fancybox2/jquery.fancybox.pack.js', function() {
				$.getScript('/js/fancybox.js');
			});

		    if (typeof FBPixelLoadHomes === 'function') {
		            FBPixelLoadHomes();
		    }

			// couple second delay to load non-critical assets to help with page speed
	        setTimeout(function () {
				scrolled=true;
				lazyLoadScroll();
			}, 4000);
		}

    }
        addEventListener('scroll', function() {
			scrolled = true;
			lazyLoadScroll();
		}, {passive: true});
	    addEventListener('click', function() {
	            scrolled = true;
	            lazyLoadScroll();
	    }, {passive: true});
	    addEventListener('touchend', function() { // for mobile
	            scrolled = true;
	            lazyLoadScroll();
	    }, {passive: true});
    	var y = window.scrollY;
    	if  (y>0) // if already scrolled down on page load
			scrolled=true;

        lazyLoadScroll();
		
		$('.navigation-container').on('click', '.showMapView', { passive: true }, function() {
            $.getScript( "//maps.googleapis.com/maps/api/js?key="+MAPKEY, function( data) {
					loadCSS('/apps/maps/mapstyles.css?v=1.6')
					$.getScript('/apps/maps/infobubble.js');
					$.getScript('/apps/maps/getlistings.js', function() {
						$.getScript('/apps/maps/jquery.map.js?v=1.2', function() {
		                    initMap();
						});
					});
            });
		})

		$('body').on('click', '.load-more', { passive: true }, function() {
			$('.filterable .previewmode').removeClass('previewmode');
		    $('.filterable .lazy-bg').each(function() {
		        imgsrc=$(this).attr('data-image');
		        $(this).css('background-image', 'url('+imgsrc+')').removeClass('lazy-bg');
		    });
			$('.load-more').hide();
		})

        $('.filters').on('click', '.filter', { passive: true }, function() {
			$('.filterable .previewmode').removeClass('previewmode');
		    $('.filterable .lazy-bg').each(function() {
		        imgsrc=$(this).attr('data-image');
		        $(this).css('background-image', 'url('+imgsrc+')').removeClass('lazy-bg');
		    });

			$('.load-more').hide();
                fclass = $(this).attr('data-filter');
                tagname = $(this).attr('data-tag');
                if (fclass=='' || ($(this).hasClass('on') && !$(this).parents('.filters').hasClass('singleView'))) {
                        $('.item').show(); // re-activate all
						$('.item > a').attr('data-fancybox-group', 'all');
                        $('.filters .filter').removeClass('on');
                        $('.filters .filter.all').addClass('on');
                                        window.history.pushState('', '', '?');
                } else {
                        $('.filters .filter').removeClass('on');
                        // activate current
                        $(this).addClass('on');

                        $('.filterable .item').each(function() {
                                if ($(this).hasClass(fclass)) {
									console.log($(this).children('a').attr('data-cat'))
									$(this).children('a').attr('data-fancybox-group', $(this).children('a').attr('data-cat'));
                                    $(this).show();
                                }
                                else {
									$(this).children('a').removeAttr('data-fancybox-group');
                                    $(this).hide();
                                }
                        })
                        if (typeof tagname != 'undefined')
                                window.history.pushState('', '', '?tag='+tagname);
                }
        });

		// Content Block 19, BG Swapping
		$('.contentBlock').on('click', '.swap-bg', function() {
			activate =  $(this).attr('data-activate');
			
			$(this).parents('.contentBlock').find('.img-wrapper .img').each(function() {
				if ($(this).hasClass(activate))
					$(this).addClass('active');
				else
					$(this).removeClass('active');
			});
		});

        $('.grid-item').on('click', '.view-photos', function() {
                console.log('c')
                $(this).parents('.grid-item').find('.fancybox:first-child').trigger('click')
        })
        $('.showMapView').click(function() {
                $('.mapContainer').show();
                $('.showMapView').addClass('active');
                $('.showListView').removeClass('active');
                redrawMap();
        })
        $('.showListView').click(function() {
                $('.mapContainer').hide();
                $(this).addClass('active');
                $('.showMapView').removeClass('active');
        })
		    // Home search preview (for Google GTM tracking)
		    $('body').on('click', '#homes_viewmore', { passive: true }, function() {
				console.log('c')
		        $('.result-list').removeClass('preview');
		// no longer changing the url per Nate request 7/17/17
		//      window.history.pushState(null, pagetitle, "/home-search-results");
		        $(this).hide();
		    });
		        // Sort feature
		    $('#sortresults').change(function () {
		                var direction = 'asc'; // default
		        var selection = this.value;
		        if (selection.search('-desc') > 0) {
		                direction = 'desc';
		                selection = selection.replace('-desc', '')
		        }
		        featureList.sort(selection, { order: direction });
		    });
		
    // Set Top Nav to fixed bar when window scrolls down
    activearea = '';
    $(window).scroll(function (event) {
        var scroll = $(window).scrollTop();

        // navigation bar -- fixed once it reaches the bottom of the header
        if ($('.find-home .floating-filter-box').length) {
                subTriggers = new Array;
                fixedSubTrigger = $('.filter-box-location').offset().top;
                if ($('.floating-filter-box').hasClass('fixed')) fixedSubTrigger -= 20; // adjust for change once sub turns fixed

                if (scroll  > (fixedSubTrigger))
                                        $('.floating-filter-box').addClass('fixed');
                else
                    $('.floating-filter-box').removeClass('fixed')

        }
    });

		
    // Mobile thumbnails click

    if ($(window).width() <= 768) {
        $('.thumbnails-section li').one('click', function(event) {
            event.preventDefault();
            $(this).children('.layer').css('opacity', '1');
        });

        $('.boxes li').one('click', function(event) {
            event.preventDefault();
            $(this).children('.layer').css('opacity', '1');
        });

		// mobile menu set to fixed on scroll up, hide on scroll down
		// Hide Header on on scroll down
		var didScroll;
		var lastScrollTop = 0;
		var delta = 5;
		var navbarHeight = $('header').outerHeight();

		$(window).scroll(function(event){
		    didScroll = true;
		});

		setInterval(function() {
		    if (didScroll) {
		        hasScrolled();
		        didScroll = false;
		    }
		}, 250);

		function hasScrolled() {
			//console.log(navbarHeight)
		    var st = $(this).scrollTop();

		    // Make sure they scroll more than delta
		    if(Math.abs(lastScrollTop - st) <= delta)
		        return;

		    // If they scrolled down and are past the navbar, add class .nav-up.
		    // This is necessary so you never see what is "behind" the navbar.
		    if (st > lastScrollTop && st > navbarHeight){
		        // Scroll Down
		        $('header').removeClass('nav-down').addClass('nav-up');
		    } else {
		        // Scroll Up
		        if(st + $(window).height() < $(document).height()) {
		            $('header').removeClass('nav-up').addClass('nav-down');
		        }
		    }

		    lastScrollTop = st;
		}
    }
    $('.mobile-contant-open').click(function () {
       $('.mobile-contact').toggleClass('open');
    });


	$('.navigate-wrapper').on('click', '.navigate-button', { passive: true }, function() {
		parentBox = $(this).parents('.navigate-wrapper');
		navigateTo =  parentBox.find('select').val();
		parent.location.href=navigateTo;
	});

	jQuery('body').on('click', '.autoClose', { passive: true }, function() {
	    jQuery(this).parent().hide();
	});

    /* ===============================================================================================================
 	===============================================================================================================*/                                      

	// embedded map workaround for scrolling
	$('.contentBlock.t18')
	.click(function(){
			$(this).find('iframe').addClass('clicked')})
	.mouseleave(function(){
			$(this).find('iframe').removeClass('clicked')});
			
$('a[id]:empty').addClass('adjustAnchor');

/* adjust #anchor links to make up for fixed header
// The function actually applying the offset
function offsetAnchor() {
console.log('a');
  if (location.hash.length !== 0) {
console.log(window.pageYOffset);
//    window.scrollTo(window.scrollX, window.scrollY - 250);
    window.scrollTo(window.pageXOffset, window.pageYOffset - 250);
  }
}

// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
  // Click events are captured before hashchanges. Timeout
  // causes offsetAnchor to be called after the page jump.
  window.setTimeout(function() {
    offsetAnchor();
  }, 0);
});

// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
*/

	/* Video */
	    if (typeof objectFitVideos !== 'undefined') {
	        objectFitVideos();
	    }

	/* start video after it's fully loaded */
	videojQuery.on('canplaythrough', startPlaylist);

	    /*
	// If the video is in the cache of the browser,
	// the 'canplaythrough' event might have been triggered
	// before we registered the event handler.
	    */
	if (videoPlayer && videoPlayer.readyState > 3) {
	    startPlaylist();
	}

});
var video_count=0;
var mobile_video_count=0;
var videojQuery = jQuery('.bgvideo#bgvid_0');
var videoPlayer = videojQuery.get()[0];
var preloadedVideos = false;

function startPlaylist() {
        /* preload the rest of the videos */
        if (!preloadedVideos) {
            var winWidth = $(window).width();
            var mobile = winWidth < 735;

                if (mobile) {
                        document.getElementById('vsource_0').src = mp4s[0];
                        videoPlayer.load();
                    videoPlayer.play();
                }

                videoWrapper = videojQuery.parent('.videoWrapper');
                videoWrapper.show();
                videojQuery.show();

                $('.playvid').hide();
                videoPlayer.muted= true;
            videoPlayer.volume = 0.0;
            videoPlayer.play();

                setTimeout(function() {
                        videojQuery.attr('poster', '');
                        $('.slideshow .photo').css('background-image', 'none');
                }, 2000);

                for(pi=0;pi<mp4s.length;pi++) {
                        doScaledTimeout(pi);
                }
        }
	preloadedVideos = true;
        /*

	*/
}
function doScaledTimeout(i) {
        setTimeout(function() {
                thisvid = mp4s[i];
                preloadVid(thisvid, i);
        }, i * 2000);
}
function preloadVid(thisvid, vc) {
        req = new XMLHttpRequest();
        req.open('GET', thisvid, true);
        req.responseType = 'blob';

        req.onload = function() {
           /* Onload is triggered even on 404
           // so we need to check the status code
        */
           if (this.status === 200) {
              var videoBlob = this.response;
              var vid = URL.createObjectURL(videoBlob); // IE10+
                        mp4s[vc] = vid;
                        /*
              // Video is now downloaded
              // and we can set it as source on the video element
                */
                        if (vc > 0) {
                        document.getElementById('vsource_'+vc).src = vid;
                        }
           }
        }
	req.onerror = function() {
           /*
        // Error
                //alert(i)
                */
        }

        req.send();
}
function run(){
    var winWidth = $(window).width();
    var mobile = winWidth < 735;


        if (mobile) {
            firstVideojQuery = $('.bgvideo#bgvid_0');
            firstVideoPlayer = firstVideojQuery.get()[0];
                mobile_video_count++;
            if (mobile_video_count == mp4s.length) mobile_video_count = 0;
                document.getElementById('vsource_0').src = mp4s[mobile_video_count];
                firstVideoPlayer.load();
            firstVideoPlayer.play();
	} else {
            lastPlayer = videoPlayer;
            lastPlayerjQ = videojQuery;
            video_count++;
            if (video_count == mp4s.length) video_count = 0;

            videojQuery = $('.bgvideo#bgvid_'+video_count);
            videoPlayer = videojQuery.get()[0];

            videoPlayer.muted= true;
            videoPlayer.volume = 0.0;

            videoPlayer.play();


            videojQuery.parent('.videoWrapper').fadeIn();

            lastPlayerjQ.parent('.videoWrapper').hide();

            lastPlayer.currentTime = 0;
        }
};

function getAttributeValue(attribute, source)
{
    var regex = RegExp("<script?\\w+(?:\\s+(?:" + attribute + "=\"([^\"]*)\")|[^\\s>]+|\\s+)*>","gi");
    var matches;
    while ( matches = regex.exec(source) )
    {
        return matches[1]; 
    }
}

function toggleExtraValue(thisForm, templateid) {
	if (templateid.value==2) {
		jQuery('.extravalue').show();
	}
	else
		jQuery('.extravalue').hide();
}
	
function loadCSS(csspath) {
	var linkElem = document.createElement('link');
	document.getElementsByTagName('head')[0].appendChild(linkElem);
	linkElem.rel = 'stylesheet';
	linkElem.type = 'text/css';
	linkElem.href = csspath;
}

function GetReCaptchaID(containerID) {
	var retval = -1;
	$(".g-recaptcha").each(function(index) {
		if(this.id == containerID) {
			retval = index;
			return;
		}
	});

	return retval;
}
