var scrollPos = window.pageYOffset;
var winHeight = (window.innerHeight || document.documentElement.clientHeight);
var winWidth = (window.innerWidth || document.documentElement.clientWidth);
var scrolled = false;

/* LAZY LOAD FUNCTION */
var isInViewport = function (elem, offset) {
    var bounding = elem.getBoundingClientRect();
        scrollPos = window.pageYOffset;
		//console.log('sp', scrollPos);
        winHeight = (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 -= winHeight;
            */

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


    } else {
                    if (elemPos>0)
                            elemPos -= winHeight;
    }
    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)*/
    );
};

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

	
	var menu_interaction=false;
	supports_touch = false;
    $('body').on('touchstart click', '.menu-trigger', { passive: true }, function(event) {
	if (event.type == "touchstart") { 
		supports_touch=true;
	    $(this).toggleClass('open');
	    $('.nav-wrapper').toggleClass('open');
	    $('body').toggleClass('no-scroll');
		console.log('o')
	} else if (event.type == "click" && !supports_touch) {
		console.log('o')
	    $(this).toggleClass('open');
	    $('.nav-wrapper').toggleClass('open');
	    $('body').toggleClass('no-scroll');
	}
    });

	var menu_interaction=false;
        // click touchstart
	$('body').on('click','.main-nav .icon', function() {
        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 .handle').on('click', function() {
            parentBox = jQuery(this).parents('.collapsible');
            if (parentBox.hasClass('expanded')) {
                parentBox.addClass('collapsed').removeClass('expanded');
                parentBox.children('.content').slideUp();
            } else {
                parentBox.addClass('expanded').removeClass('collapsed');
                parentBox.children('.content').slideDown();
            }
    });
	
	// for Firefox lack of ":has()" support
	$(':has(.textbg-white)').addClass('has-white');
	$(':has(.textbg-blue)').addClass('has-blue');
	$(':has(.subheading)').addClass('has-subheading');
	$(':has(.highlight)').addClass('has-highlight');
	$(':has(.line2)').addClass('.has-line2');
	$(':has(svg.wide)').addClass('has-wide');
	$(':has(.odd)').addClass('has-odd');
	$(':has(.wrapper.odd)').addClass('has-wrapper-odd');
	$(':has(.scriptcount-4)').addClass('has-scriptcount-4');
	$(':has(.innerContent)').addClass('has-innerContent');
	$(':has(.checkbox)').addClass('has-checkbox');
	$(':has(.script-writing)').addClass('has-script-writing');
	
/*
	$('body').on('click', '.homefinder .button-wrapper', function() {
	    jQuery.fancybox({
			'padding' : 0,
			'wrapCSS' : 'homefindersignup',
			'type':'ajax',
			'showNavArrows' : false,
			'arrows': false,
			fitToView: true,
			autoSize: true,
			autoDimensions: false,
			href:'/popnewsletter.php',
		    'overlayShow':true,
			beforeShow: function () {
				$.getScript('https://www.google.com/recaptcha/api.js');
			}
	      });
	});
*/

	handwriteHero();
    handwriteSVG();

	parallaxScrolls();
	smoothAnchors();
	
	styleSelectPlaceholders();
	
	function styleSelectPlaceholders() {
		var grayout = document.getElementsByClassName('style-placeholder');

		var grayOutSelect = function() {
		    if ( this.value === "" ) {
		        this.classList.add('placeholder');
		    } else {
		        this.classList.remove('placeholder');
		    }
		};

		for (var i = 0; i < grayout.length; i++) {
		    grayout[i].addEventListener('change', grayOutSelect);
		    if ( grayout[i].value === "" ) {
		        grayout[i].classList.add('placeholder');
		    } else {
		        grayout[i].classList.remove('placeholder');
		    }
		}
	}
//	$('header').clone().addClass('fixed').insertBefore('header');
//	$('header:not(.fixed)').addClass('static');

    $('.contentBlock:first-child h2').each(function() {
		if ($(this).height() > 110) $(this).addClass('multiline');
	});
		  

    assetsLoaded = loadedafterscroll = 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>');
			}
		}
		load_ahead = scrolled ? .5 : 0; // once you start scrolling, load the images 2x down the page so scrolling feels smoother (not waiting on images to load)
		$('.lazy-bg').each(function() {
			if (isInViewport($(this).get(0),load_ahead)) {
				imgsrc=$(this).attr('data-image');
				if (imgsrc) {
//					console.log(imgsrc)
					$(this).css('background-image', 'url('+imgsrc+')').removeClass('lazy-bg');
				}
			}
		});
       	$('.lazy-vid').each(function() {
            if (isInViewport($(this).get(0),0)) {
                postersrc=$(this).attr('data-poster');
				if ($(this).attr('data-autoplay')) {
					$(this).attr('autoplay', true);	
					$(this).get(0).play();
				}
				if ($(this).attr('data-src'))
					$(this).attr('src', $(this).attr('data-src'));
                $(this).attr('poster', postersrc).removeClass('lazy-vid');
            }
        });
        $('.lazy-iframe').each(function() {
			if (isInViewport($(this).get(0),load_ahead)) {
                //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),load_ahead)) {
				imgsrc=$(this).attr('data-lazy-src');
				if (typeof imgsrc === 'undefined')
					imgsrc =  $(this).attr('data-src');


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

		// stars
	    var is_mobile = $(window).width() <= 991 ? true : false;
		
        // 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');
                }
        });
//        $('.in-view-elements > *:not(table)').each(function() {
        $('.in-view-elements > *').each(function() {
                if (isInViewport($(this).get(0),1)) {
                        $(this).removeClass('out-of-view').addClass('in-view');

						if ($(this).hasClass('slide-module') && !$(this).hasClass('cloned')) {
							console.log('slide mod found')
							$(this).addClass('original');
							parentBox = $(this).parent();
							contentBlock = $(this).parents('.contentBlock');
							slidecopy = $(this).clone();
							slidecopy.addClass('cloned').removeClass('original');
							parentBox.replaceWith(slidecopy);
//							$(this).remove();
							
							//$('.slide-module').removeClass('rslides').removeClass('rslides2');
							slidecopy.responsiveSlides({
				                        auto: true,
				                      	pager: false,
				                        nav: true,
				                        speed: 500,
				                        nextText:'<div class="arrows next-arrow next_btn"><img src="/images/arrow-right-slider.svg" alt=""></div>',
				                        prevText:'<div class="arrows prev-arrow previous_btn"><img src="/images/arrow-right-slider.svg" alt=""></div>',
				                        timeout:5000,
										before: function(i) {
											thisone = i+1;
											if (thisone==0) thisone = $('.slide-module > div').length;
											slidenum = pad(thisone, 2);
											//console.log(slidenum)
											$('.midSlide .active-slide-number').html(slidenum);

//											console.log(contentBlock);
											contentBlock.find('.content-slide').removeClass('active');
											contentBlock.find('.slide-'+i).addClass('active');
//											console.log(i)
											// calculate largest content
											maxH = 0;
											contentBlock.find('.content-slide').each(function() {
												thisH = $(this).height();
												if (thisH > maxH)
													maxH = thisH;
											})
											contentBlock.find('.content').css('min-height', maxH +'px');
										},
										after: function(i) {
											   	$('.slide-module .lazy-img').each(function() {
							                        imgsrc =  $(this).attr('data-src');
									                $(this).attr('src', imgsrc).removeClass('lazy-img');
									        });
										}
				            });

						}

                } else if (!$(this).hasClass('in-view')) { // once it's in view, leave it alone
                        $(this).addClass('out-of-view');
                }
        });
		/*
        $('.in-view-elements > table td > *').each(function() {
                if (isInViewport($(this).get(0),1)) {
                        $(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');
                }
        });
*/
        $('.fadein > *:not(.in-view)').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');
                }
        });
        $('.fadeside:not(.in-view)').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;

	                        if (typeof hspixel !== 'undefined') {
        	                        $.getScript('https://js.hs-scripts.com/'+hspixel+'.js');
        	                }

				$.getScript('/js/validation.js');
				$.getScript('https://www.google.com/recaptcha/api.js');
				
                if ($('.hs-form-load').length) {
                    $.getScript('//js.hsforms.net/forms/v2.js', function() {
                        $('.hs-form-load').each(function() {
                            formid=$(this).attr('data-formid');
                            portal=$(this).attr('data-portal');
                            formcontainer=$(this).attr('id');
							hbspt.forms.create({
                                region: "na1",
						        portalId: portal,
						        formId: formid,
						        target:'#'+formcontainer,
                                css: ''
						    });
                        })
					});
				}

				contentBlockHeroParallax();
				responsiveAdjustments();
				
				//$.getScript('https://maps.googleapis.com/maps/api/js?key=AIzaSyAbHebkjazwGkzyBkJDag_iYM6rVohB4K8&libraries=places&callback=initAutocomplete');
				if ($('#directorymap').length)  {
					$('.directorymap .lazy-img').each(function() {
						imgsrc =  $(this).attr('data-src');
						$(this).attr('src', imgsrc).removeClass('lazy-img').removeClass('lazyload');
				        });

					loadCSS('/apps/interactivedirectorymap/styles.css');
					$.getScript('//maps.googleapis.com/maps/api/js?key=AIzaSyAFQ3lAbjgiiQK6r1uQhitFejSz_1DYqpc', function() {
						$.getScript('/apps/interactivedirectorymap/getlistings.js', function() {
							$.getScript('/apps/interactivedirectorymap/preload.js', function() {
								$.getScript('/apps/interactivedirectorymap/jquery.map.js', function() {
									initMap();
								});
							});
						});
						$.getScript('/apps/interactivedirectorymap/infobubble.js');
					});
				}
		        // 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 ($('.contentBlock.t12 .img').length) {
					$.getScript('/js/pinchzoom.js', function() {
						var el = document.querySelector('.contentBlock.t12 .img');
						      new PinchZoom.default(el, {});
					});
				}
*/
				if ($('.scrollable-slides').length) {
			        $(".scrollable-slides .slideshow-wrapper").responsiveSlides({
			          auto: false,
			          pager: true,
			          nav: true,
			                    	prevText:'<svg xmlns="http://www.w3.org/2000/svg" width="31.82" height="55.154" viewBox="0 0 31.82 55.154"><g transform="translate(-1227.243 -72.923)"><rect width="39" height="6" transform="translate(1227.243 100.5) rotate(-45)" fill="CurrentColor"/><rect width="39" height="6" transform="translate(1231.486 96.257) rotate(45)" fill="currentColor"/></g></svg>',
			                        nextText:'<svg xmlns="http://www.w3.org/2000/svg" width="31.82" height="55.154" viewBox="0 0 31.82 55.154"><g transform="translate(1259.063 128.077) rotate(180)"><rect width="39" height="6" transform="translate(1227.243 100.5) rotate(-45)" fill="currentColor"/><rect width="39" height="6" transform="translate(1231.486 96.257) rotate(45)" fill="CurrentColor"/></g></svg>',
			                        manualControls:'.subpagesnav',
			/*                      after:function(i) {
			                                var newurl = $('.subpagesnav .rslides_here').attr('data-href');
			                                window.location.hash = newurl;
			                        }*/
			        });

		           	var identifier = window.location.hash; //gets everything after the hashtag i.e. #home
	                if (identifier) {
	                        $('.subpagesnav > div').each(function() {
	                                if ($(this).attr('data-href') == identifier) {
	                                        $(this).children('a').trigger('click');
	                                }
	                        })
	                }
			
				}
				
	            if ($('.featuredSlider').length) {
	                    loadCSS('https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css');
	                    loadCSS('https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css');
	                    $.getScript('https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js', function() {
	                            loadCarousels();
	                    });
	            }
				
				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');

			    $('.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');
			    });

			}
		}

		if (!assetsLoaded) {
			assetsLoaded = true;

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

    }
        addEventListener('scroll', function() {
			scrolled = true;
            scrollPos = window.pageYOffset;

			lazyLoadScroll();
			$('.parallax-item.not-started').removeClass('not-started'); // only need for preventing jump effect when already scrolled down onto the page
			contentBlockHeroParallax();
			
		}, {passive: true});
	    addEventListener('click', function() {
	            scrolled = true;
	            lazyLoadScroll();
	    }, {passive: true});
	    addEventListener('touchend', function() { // for mobile
	            scrolled = true;
	            lazyLoadScroll();
	    }, {passive: true});
	    addEventListener('resize', function() { // for mobile
			winWidth = (window.innerWidth || document.documentElement.clientWidth);
			winHeight = (window.innerHeight || document.documentElement.clientHeight);
			responsiveAdjustments();
	    }, {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();
						});
					});
            });
		})

    jQuery('body').on('click', '.button.toggledisplay', function() {
        displayelement=jQuery(this).attr('id');
        jQuery('.'+displayelement).show();
    });

		$('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');
			});
		});

        $('.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)
		    $('.plan-listings').on('click', '#homesearch_viewmore', { passive: true }, function() {
		        $('.plan-listings .listings-container').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 });
		    });
		
		
    // 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);
*/
	/* Special Hero-Style Parallax
	Used on Overlapping Photo Content Block
	*/
	/* 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 handwriteSVG() {
    $('.handwritten:not(.inactive) svg').each(function() {
            svg_el = $(this);
            lengthduration=actualduration=0;
            thisdelay=.5;
            defaultlength=1000;
            if (svg_el.length && isInViewport(svg_el.get(0))) {
                    svg_el.find('path:not(defs path)').each(function() {
                            thislength = Math.ceil($(this).get(0).getTotalLength());
                            thisdelay += lengthduration;

                            lengthduration = (thislength)/450;
                            actualduration = defaultlength/450;
                            diffduration = Math.abs(actualduration - lengthduration);
                            dd = actualduration / diffduration;
                             $(this).css('stroke-dasharray', thislength);
                             $(this).css('stroke-dashoffset', thislength);
                             $(this).css('animation-delay', (thisdelay)+'s');
                             $(this).css('animation-name', 'draw-stroke');
                             $(this).css('animation-duration', (lengthduration)+'s');
                             $(this).addClass('started')
                    })
            }
    })
}

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;
}
function parallaxScrolls() {
	$(window).scroll(function() {
	  var scrolled = $(window).scrollTop()
		winHeight = (window.innerHeight || document.documentElement.clientHeight);
		var scrollBottom = scrolled + winHeight;
	  $('.slide .parallax').each(function(index, element) {
	    var initY = $(this).offset().top
	    var height = $(this).height()
	    var endY  = initY + $(this).height()

	    // Check if the element is in the viewport.
	    var visible = parallaxInViewport(this)
	    if(visible) {
	      var diff = scrolled - initY
	      var ratio = Math.round((diff / height) * 100)
			adj = parseInt(+(ratio * 1.5));
			if (adj < 0) adj = 0;
	      $(this).css('background-position','center calc(50% + ' + adj + 'px)')
	    }
	  })
	  $('.contentBlock .parallax .parallax-item:not(.helper),.contentBlock .parallax .parallax-bg').each(function(index, element) {
			parentItem = $(this).closest('.parallax');
			var initY = parentItem.offset().top
			var height = parentItem.height()
			var endY  = initY + parentItem.height()
			var limitToParent = parentItem.hasClass('limit-to-parent');
//			console.log(parentItem)
//			console.log(limitToParent);
			
			visibleitem = this;
			
			pitem = $(this);
			if (pitem.length) {
				visibleitem = pitem[0];
			}
			//console.log(pitem)
			// add helper sibling if not already there
			if (pitem.hasClass('parallax-item') && pitem.next('.parallax-item.helper').length==0) {
				helper = pitem.clone().addClass('helper')
				helper.insertAfter(pitem)
			}
			helper = pitem.next('.parallax-item.helper');
			if (helper.length) {
				visibleitem = helper[0];
				var initY = helper.offset().top
			}
			
//			var limitToParent = $(this).hasClass('limit-to-parent');
//		  console.log($(this));
			if (parentItem.hasClass('grow-in')) {
				childItem = $(this).find('.parallax-item:not(.helper)');
				childY = helper.offset().top
				childDiff = scrollBottom - childY;
				if (childDiff > 0) {
					childHeight = childItem.height();
					spreadout = childDiff / childHeight / 10;
					adjustScale = .8+spreadout;
//					console.log('spread: ' + spreadout)
//					console.log(adjustScale)
					if (adjustScale<.8) adjustScale=.8;
					if (adjustScale>1) adjustScale=1;
					$(this).find('.parallax-item:not(.helper)').css('transform','scale('+(adjustScale) + ')');
				}
			}
			// Check if the element is in the viewport.
		    var visible = parallaxInViewport(visibleitem)
			
			debug = $(this).hasClass('embellish-plant-top');

			if (debug) {
				//console.log('visible: ' + visible);
				
				  var rect = visibleitem.getBoundingClientRect()
	/*
				console.log('height: '+rect.height);
				console.log('width: '+rect.width);
				console.log('bottom: '+rect.bottom);
				console.log('right: '+rect.right);
				console.log('top: '+rect.top);
				console.log('left: '+rect.left);
				console.log('top q: '+rect.top <= (window.innerHeight || document.documentElement.clientHeight));
				console.log('left q: '+rect.left <= (window.innerWidth || document.documentElement.clientWidth));
				console.log('winH: ' + window.innerHeight || document.documentElement.clientHeight)
				console.log('winW: ' + window.innerWidth || document.documentElement.clientWidth)
	*/			
			}

		    if(visible) {
				/*
				if (debug) {
					console.log('scrollBottom: ' + scrollBottom);
					console.log('initY: ' + initY);
					console.log('diff: '+diff)
				}
				*/
				
		      var diff = scrollBottom - initY
	//			console.log('scrolled: '+scrolled)
				speed = $(this).hasClass('slow') ? 10 : 6;
	//			if (limitToParent) speed = 7;
				var ratio = diff / speed * -1;
			
				adjustPX = parseInt((ratio));
	//			console.log('adjustPX: '+adjustPX)
				if (limitToParent) {
					childH = pitem.height();
					max = Math.abs(childH - height)*-1;
//					console.log('max: ' + max)

					if (adjustPX < max)
						adjustPX = max;
				}
			      	//$(this).find('.parallax-item:not(.helper)').css('top',adjustPX + 'px')
				if (pitem.hasClass('parallax-item')) {
					pitem.css('transform','translateY('+adjustPX + 'px)');
					if (pitem.hasClass('not-started')) {
						thisitem = pitem;
						(function(thisitem) {
							setTimeout(function() {
//								console.log(thisitem);
//								console.log('remove c')
								thisitem.removeClass('not-started');
							}, 100);
						})(thisitem);
					}
				}
				
				// BG adjustments for girl with airplane
				scaleFactor = 1.25;
				if (parentItem.hasClass('subtle')) scaleFactor = 1.15;
				scaledH = height*scaleFactor;
				movementLimit = scaledH - height;
	//			console.log('limit: ' + movementLimit);
			
				shiftfactor = movementLimit/winHeight*.7;
	//			console.log('shift factor: ' + shiftfactor);
				adjustbg = shiftfactor*diff;
	//			console.log('scrolled: ' + diff);
	//			console.log('movementLimit: ' + movementLimit);
	//			console.log(adjustbg);
	//			console.log(ratio);
				if (adjustbg>movementLimit) adjustbg = movementLimit;
				if (adjustbg<0) adjustbg=0;
				parentItem.find('.parallax-bg').css('margin-top',(adjustbg*-1) + 'px');

		    }
	  })
	})
}
function smoothAnchors() {
		console.log('smooth')
  // Select all links with hashes
	$('body').on('click', 'a[href*="#"]:not([href="#"]):not([href="#0"])', function(event) {
    // Remove links that don't actually link to anything
	    $('.nav-wrapper').removeClass('open');
	    $('.menu-trigger').removeClass('open');
	    $('body').removeClass('no-scroll');
      // On-page links
      if (
        location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
        && 
        location.hostname == this.hostname
      ) {
        // Figure out element to scroll to
        var target = $(this.hash);
		var hashname = this.hash.slice(1);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        // Does a scroll target exist?
        if (target.length) {
          // Only prevent default if animation is actually gonna happen
          event.preventDefault();
		  console.log('prev def')
          window.history.pushState('', '', '#'+hashname);
		  console.log(target.offset().top)
          $('html, body').animate({
            scrollTop: target.offset().top
          }, 1000, function() {
			  console.log('after')
            // Callback after animation
            // Must change focus!
			  /*
            var $target = $(target);
            $target.focus();
            if ($target.is(":focus")) { // Checking if the target was focused
              return false;
            } else {
              $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
              $target.focus(); // Set focus again
            };
			  */
          });
        }
      }
    });
}
function parallaxInViewport(node) {
  var rect = node.getBoundingClientRect()
	
  return (
    (rect.height > 0 || rect.width > 0) &&
    rect.bottom >= 0 &&
    rect.right >= 0 &&
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.left <= (window.innerWidth || document.documentElement.clientWidth)
  )
}

function handwriteHero() {
	svg_el = $('.slideshow .caption-box .line2 svg');
	lengthduration=actualduration=0;
	thisdelay=.5;
	defaultlength=1000;
	if (svg_el.length) {
		svg_el.find('path').each(function() {
			thislength = Math.ceil($(this).get(0).getTotalLength());
			thisdelay += lengthduration;
			adjustfactor = 450;
			
			if ($(this).hasClass('speed-slower-1p5')) {
				adjustfactor = adjustfactor / 1.5;
			}
			if ($(this).hasClass('speed-slower-2')) {
				adjustfactor = adjustfactor / 2;
			}
			if ($(this).hasClass('speed-faster-1p5')) {
				adjustfactor = adjustfactor * 1.5;
			}
			if ($(this).hasClass('speed-faster-2')) {
				adjustfactor = adjustfactor * 2;
			}
			
			lengthduration = (thislength)/adjustfactor;
			actualduration = defaultlength/adjustfactor;
//			console.log($(this));
//			console.log(thislength);
			
//			lengthduration = (thislength)/675;
//			actualduration = defaultlength/675;
			diffduration = Math.abs(actualduration - lengthduration);
			
			dd = actualduration / diffduration;
			$(this).css('stroke-dasharray', thislength);
			$(this).css('stroke-dashoffset', thislength);
			$(this).css('animation-delay', (thisdelay)+'s');
			$(this).css('animation-name', 'draw-stroke');
			$(this).css('animation-duration', (lengthduration)+'s');

			$(this).addClass('started')
		})

//		console.log($('.slideshow .caption-box .line2 svg path').get(0).getTotalLength());
	}
}
function responsiveAdjustments() {
	$('.contentBlock.t111').each(function() {
		thisH = $(this).outerHeight();
		$(this).css('margin-top', -1*thisH/2+'px')
		
		prevBlock = $(this).prev();
		prevBlock.css('padding-bottom', '');
		original_pb = parseInt(prevBlock.css('padding-bottom'));
		prevBlock.css('padding-bottom', original_pb + thisH/2 + 'px');

		nextBlock = $(this).next();
		nextBlock.css('padding-top', '');
		original_pb = parseInt(nextBlock.css('padding-top'));
		nextBlock.css('padding-top', original_pb + thisH/2 + 'px');

	})
}
function contentBlockHeroParallax(thisBlock) {
	$('.contentBlock.t32.in-view').each(function() {
		thisBlock = $(this);
		var blockSettings = getParallaxSettings(thisBlock);
//		console.log(blockSettings);

		// adjust width of mask
		thisBlock.find('.img-mask').each(function() {
			diff = 10; // from 90vw => 100vw
			startVW = 90;
			//console.log('multiplier: ' + adjustmentMultiplier);
			addW = blockSettings.adjustmentMultiplierMid * diff;
			newVW = (addW + startVW)/100;
//			$(this).css('transform', 'scaleX('+ newVW+')');
			$(this).css('width', (newVW*100)+'%');
//			$(this).find('.img').css('transform', 'scale('+ 1/newVW+')');
//			console.log('translateX('+ newVW+')');
//			$(this).css('width', newVW+'vw');
		});

		// parallax up
		thisBlock.find('.img-wrapper').each(function() {
			diff = 10;
			startVW = 0;
			addW = blockSettings.adjustmentMultiplier * diff;

			if (winWidth > 1000) {
				diff=20;
				addW = blockSettings.adjustmentMultiplierFast * diff *1;
			}
			newVW = (addW + startVW)*-1;
			if (newVW < diff*-1)
				newVW=diff*-1;
			$(this).css('transform', 'translate3d(0px, '+ newVW+'vh, 0px)');
		});
		
		// adjust 3D scale of hero
		thisBlock.find('.img-scale').each(function() {
			diff = .2; // from 1.2 scale => 1
			startVW = 1.2;
			//console.log('multiplier: ' + adjustmentMultiplier);
			addW = blockSettings.adjustmentMultiplierMid * diff;
			newVW = (startVW - addW);
//			console.log('newVW: ' + newVW);
			$(this).css('transform', 'scale3d('+ newVW+', '+ newVW+', 1)');
			//bg image: 3.5 second 1.2 scale=>1 (100 keyframe)
		});
	})

	// Adjust text above the hero block if applicable
	$('.contentBlock.t1.precedes-block-32.in-view .content').each(function() {
		thisBlock = $(this);
		var blockSettings = getParallaxSettings(thisBlock);
//		console.log(blockSettings);

		//console.log('scrollPos: ' + scrollPos);
		
		diff = 5;
		if (blockSettings.blockTop > winHeight) {
			diff = 10;
		}
		startVW = 0;
		
		endingPoint = winHeight;

		// adjust Y
		addW = blockSettings.adjustmentMultiplier * diff;
		newVW = (addW + startVW)*-1;
		
		$(this).css('transform', 'translate3d(0px, '+ newVW+'vh, 0px)');

		// adjust opacity
		startVW = 1;
		diff = 1;
		addW = blockSettings.adjustmentMultiplierVH * diff;
		if (blockSettings.blockTop < winHeight) {
			addW *= 3;
		}
		newVal = (startVW - addW);

		$(this).css('opacity', newVal);

//		scrollPos
//		console.log(thisBlock);
	})

}
function getParallaxSettings(thisBlock) {
	blockSettings = {};

	blockSettings.blockTop = thisBlock.offset().top;
	blockSettings.blockHeight = thisBlock.height();
	
	// calculate starting point of animation.  If the item is within the above-the-fold viewport then set it to 15px from top of browser.  Otherwise set it to 15px + blockTop
	if (blockSettings.blockTop < winHeight)
		blockSettings.startingPoint = 15;
	else
		blockSettings.startingPoint = blockSettings.blockTop - winHeight + 15;

	
	// have ending point be the px where it reaches the top of the page
	blockSettings.endingPoint = blockSettings.blockTop + blockSettings.startingPoint;
	blockSettings.endingPointMid = blockSettings.blockTop + blockSettings.startingPoint + (blockSettings.blockHeight*.25);
	if (blockSettings.blockTop > winHeight) {
		blockSettings.endingPoint = winHeight;
		blockSettings.endingPointMid = blockSettings.blockHeight;
	}

	adjustedStart = scrollPos;
	viewableArea = 0;
	if (blockSettings.blockTop > winHeight) {
		adjustedStart = Math.abs(scrollPos-blockSettings.startingPoint);
		viewableArea = winHeight*.3;
	}
/*	 else {
		adjustedStart =blockSettings.blockTop - scrollPos;
		if (adjustedStart < scrollPos) adjustedStart = scrollPos;
	}
		*/

//	console.log(thisBlock);
//	console.log('scroll: ' + scrollPos);
//	console.log('start: ' + blockSettings.startingPoint);

	adjustmentMultiplier = adjustedStart / blockSettings.endingPoint;
	if (adjustmentMultiplier > 1)
		adjustmentMultiplier = 1;
	if (adjustmentMultiplier < 0)
		adjustmentMultiplier = 0;

	adjustmentMultiplierMid = adjustedStart / (blockSettings.endingPointMid);
	if (adjustmentMultiplierMid > 1)
		adjustmentMultiplierMid = 1;
	if (adjustmentMultiplierMid < 0)
		adjustmentMultiplierMid = 0;

	adjustmentMultiplierFast = adjustedStart / blockSettings.endingPoint * 2;
	if (adjustmentMultiplierFast > 1)
		adjustmentMultiplierFast = 1;
	if (adjustmentMultiplierFast < 0)
		adjustmentMultiplierFast = 0;
	
	adjustmentMultiplierVH = (adjustedStart-viewableArea) / (winHeight);
	if (adjustmentMultiplierVH > 1)
		adjustmentMultiplierVH = 1;
	if (adjustmentMultiplierVH < 0)
		adjustmentMultiplierVH = 0;

	if (scrollPos < (blockSettings.startingPoint+viewableArea)) {
	//	adjustmentMultiplierVH = 0;
	}
	
	if (scrollPos < blockSettings.startingPoint) {
		adjustmentMultiplier = 0;
		adjustmentMultiplierMid = 0;
		adjustmentMultiplierFast = 0;
	//	adjustmentMultiplierVH = 0;
	}
/*
	console.log('viewablearea: ' + viewableArea);
	console.log('scrollpos: '+ scrollPos)
	console.log('multiplier: ' + adjustmentMultiplier);
	console.log('multiplier VH: ' + adjustmentMultiplierVH);
*/	
	blockSettings.adjustmentMultiplier = adjustmentMultiplier;
	blockSettings.adjustmentMultiplierMid = adjustmentMultiplierMid;
	blockSettings.adjustmentMultiplierFast = adjustmentMultiplierFast;
	blockSettings.adjustmentMultiplierVH = adjustmentMultiplierVH;
	return blockSettings;
}

/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
/* Custom Select Style */
/* ----------------------------------------------------------- */
/* ----------------------------------------------------------- */
var x, i, j, l, ll, selElmnt, a, b, c;
/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
l = x.length;
for (i = 0; i < l; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  ll = selElmnt.length;
  /*for each element, create a new DIV that will act as the selected item:*/
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected placeholder");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /*for each element, create a new DIV that will contain the option list:*/
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < ll; j++) {
    /*for each option in the original select element,
    create a new DIV that will act as an option item:*/
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
        /*when an item is clicked, update the original select box,
        and the selected item:*/
        var y, i, k, s, h, sl, yl;
        s = this.parentNode.parentNode.getElementsByTagName("select")[0];
        sl = s.length;
        h = this.parentNode.previousSibling;

		this.parentNode.parentNode.getElementsByClassName('select-selected')[0].classList.remove('placeholder'); // take out placeholder styles once item is selected
//  	  this.classList.remove('placeholder');

        for (i = 0; i < sl; i++) {
          if (s.options[i].innerHTML == this.innerHTML) {
            s.selectedIndex = i;
            h.innerHTML = this.innerHTML;
            y = this.parentNode.getElementsByClassName("same-as-selected");
            yl = y.length;
            for (k = 0; k < yl; k++) {
              y[k].removeAttribute("class");
            }
            this.setAttribute("class", "same-as-selected");
            break;
          }
        }
        h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
      /*when the select box is clicked, close any other select boxes,
      and open/close the current select box:*/
      e.stopPropagation();
      closeAllSelect(this);
      this.nextSibling.classList.toggle("select-hide");
      this.classList.toggle("select-arrow-active");
    });
}
function closeAllSelect(elmnt) {
  /*a function that will close all select boxes in the document,
  except the current select box:*/
  var x, y, i, xl, yl, arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  xl = x.length;
  yl = y.length;
  for (i = 0; i < yl; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i)
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < xl; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}
/*if the user clicks anywhere outside the select box,
then close all select boxes:*/
document.addEventListener("click", closeAllSelect);
/* ----------------------------------------------------------- */
/* END Custom Select Style									*/
/* ----------------------------------------------------------- */
