var hubspotloaded=false;
jQuery(document).ready(function () {
	$('a[href*=".mp3"]').on('click', function(e) {
        e.preventDefault();
		audio = new Audio($(this).attr('href'));
		
		audio.play();
	});
	$('a[href*=".mp3"]').css('pointer-events', 'auto');
	
	var fancyboxloaded=false;
	// popup on page load
	const params = new URLSearchParams(window.location.search);
	if (params.has('gtd')) {
//	if (location.hash.length !== 0) {
		//var anchor = $('a[href="'+location.hash+'"]');
		//if (anchor.hasClass('popup')) {
//		if (location.hash == '#aegis-sef--swap-execution-facility') {
			fancyboxloaded=true;
			loadCSS('/fancybox2/jquery.fancybox.css');
			$.getScript('//js.hsforms.net/forms/v2.js');
			$.getScript('/fancybox2/jquery.fancybox.pack.js?v=2.7', function() {
				$.getScript('/js/fancybox.js?v=2.7', function() {
					setTimeout(function(){ 						
						//anchor.click()

						$.fancybox({
						    'padding' : 0,
						    'type':'ajax',
						    'showNavArrows' : false,
						    'arrows': false,
						    'scrolling' : 'auto',
							'closeBtn': false,
							helpers     : { 
						        // prevents closing when clicking OUTSIDE fancybox
						        overlay : {closeClick: false} 
						    },
							keys : {
						        // prevents closing when press ESC button
						        close  : null
						    },
							fitToView:true,
							minHeight:'80%',
							minWidth:'60%',
//							autoSize:
						    'overlayShow':true,
							beforeLoad: function () {
						        var url = location.hash;
								var url = '#aegis-sef--swap-execution-facility';
								if (typeof url !== 'undefined') {
									if (url.search('#')==0) {
										url = url.replace('#', '');
										this.href = '/popups.php?p='+url
									}
								}
						    }
						});
					}, 100);
				});
			});
//		}
	}

	var fancyboxloaded=false;
	// popup on page load
	if (params.has('htk')) {
		fancyboxloaded=true;
		loadCSS('/fancybox2/jquery.fancybox.css');
		$.getScript('/fancybox2/jquery.fancybox.pack.js', function() {
			$.getScript('/js/fancybox.js?v=2.7', function() {
				setTimeout(function(){ 						
					$.fancybox({
					    'padding' : 0,
					    'type':'ajax',
					    'showNavArrows' : false,
					    'arrows': false,
					    'scrolling' : 'auto',
						'closeBtn': false,
						helpers     : { 
					        // prevents closing when clicking OUTSIDE fancybox
					        overlay : {closeClick: false} 
					    },
						keys : {
					        // prevents closing when press ESC button
					        close  : null
					    },
						fitToView:true,
//						minHeight:'80%',
//						minWidth:'60%',
//							autoSize:
					    'overlayShow':true,
						beforeLoad: function () {
					        var url = location.hash;
							var url = '#aegis-hedging-expands-technology-capabilities-with-acquisition-of-instanext';
							if (typeof url !== 'undefined') {
								if (url.search('#')==0) {
									url = url.replace('#', '');
									this.href = '/popups.php?p='+url
								}
							}
					    }
					});
				}, 100);
			});
		});
	}

    if (typeof triggerQuiz === 'function') {
            triggerQuiz();
    }
    if (typeof initStateMap === 'function') {
            initStateMap();
    }

//    $('header:not(.placeholder)').clone().addClass('placeholder').insertBefore('header');

/*
*/
    // Mobile menu open/close
    $('body').on('click', '.menu-button', function() {
		parent = $('.nav-wrapper');
        parent.toggleClass('open');
        $(this).toggleClass('open');
        $(this).toggleClass('closed');
        $('body').toggleClass('no-scroll');
    });
   	$('body').on('click', '.main-nav__menu a', function() {
        $('.nav-wrapper').removeClass('open');
	});

   	$('body').on('click', '.has-sub .toggleSub', function() {
		parentBox = $(this).parents('.has-sub');
            parentBox.toggleClass('open')

            if (!parentBox.hasClass('open')) {
                    parentBox.addClass('closed');
            } else {
                    parentBox.removeClass('closed');
            }
    })
	// for iPads
    $('body').on('touchstart', '.has-sub > a', { passive: true }, function() {
        if ($(this).parents('li').hasClass('hover')) {
                action='close';
        }  else{
                action='open';
        }
        // close any others
        $('.has-sub').removeClass('hover');

        if (action=='close') {
                $(this).parents('li.has-sub').removeClass('hover').addClass('closed');
        } else {
                $(this).parents('li.has-sub').addClass('hover').removeClass('closed');
        }
    })

	$('body').on('click', '.slide-down-arrow', { passive: true }, function() {
		$([document.documentElement, document.body]).animate({
		        scrollTop: $(".main-container.top").offset().top - 100
		    }, 2000);
	});
	$('body').on('click', '.back-to-top', { passive: true }, function() {
		console.log('hi')
		$([document.documentElement, document.body]).animate({
			scrollTop: $("body").offset().top
	    }, 2000);
	});
	
	$('body').on('click', '.go-back', { passive: true }, function() {
		console.log('go');
		history.go(-1);
	});

    jQuery('.collapsible .handle').on('click', function() {
            parentBox = jQuery(this).parents('.collapsible');
            if (parentBox.hasClass('expanded')) {
                parentBox.addClass('collapsed').removeClass('expanded');
            } else {
                parentBox.addClass('expanded').removeClass('collapsed');
            }
    });

	// Tagged Button Filters
	$('.keyword-buttons').on('click', '.item a', function() {
		keyword = $(this).attr('data-tagged-keyword');

		// reset all buttons and highlight the one clicked
		$('.keyword-buttons .item a').addClass('outline');
		$(this).removeClass('outline');

		// loop through blocks and show/hide relevant ones
//		console.log(keyword)
		if (keyword=='all') {
			$('.ContentBlockWrapper .contentBlock').show();
		} else {
			$('.ContentBlockWrapper .contentBlock.t60').each(function() {
				blocktags = $(this).attr('data-tags');
				if (typeof blocktags !== 'undefined') {
					tagarray = blocktags.split(',').map(function(item) {
						return item.trim();
					});
					console.log(tagarray);
					
					if (tagarray.includes(keyword)) {
						$(this).show();
					} else {
						$(this).hide();
					}
				}
			});
		}
	});
	
	// horizontally scrollable tables
	$('.contentBlock.t111 .content table tbody').each(function() {
		if (!$(this).find('.scroll').length) {
			$(this).prepend('<div class="scroll-wrapper left"><div class="scroll left"><div class="background-area"><span>&lsaquo;</span></div></div></div>')
			$(this).append('<div class="scroll-wrapper right"><div class="scroll right"><div class="background-area"><span>&rsaquo;</span></div></div></div>')
		}
	})
	$('.contentBlock.t111 .content').on('click', '.scroll', function() {
		var vwidth = $(window).width();
		oldpos = $(this).parents('tbody').scrollLeft();
		if ($(this).hasClass('right'))
			newpos = oldpos + vwidth;
		else
			newpos = oldpos - vwidth;

//		console.log(newpos)
		$(this).parents('tbody').scrollLeft(newpos);

			//console.log($(this).parents('tbody').scrollLeft())
/*
		$(this).parents('tbody').animate({
		    scrollLeft: newpos
		  }, "slow");
		*/
	})
	
	if (typeof FontFaceObserver === 'undefined') {} else {
		var font = new FontFaceObserver('Saira');

		font.load().then(function () {
			$('html').removeClass('wf-loading');
//		  console.log('Font is available');
		}, function () {
		});
	}
    /* LAZY LOAD FUNCTION */
    var isInViewport = function (elem, offset) {
        var bounding = elem.getBoundingClientRect();
        var scrollPos = window.pageYOffset;
        botPos = (window.innerHeight || document.documentElement.clientHeight);

		//is_hidden = $(elem).css('opacity')=='0';
			
        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'))
			//&& !is_hidden
                        // || (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');
//				   console.log('loading '+imgsrc)
				
				if (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');
                $(this).attr('poster', postersrc).removeClass('lazy-vid');
			}
		});
        $('.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');
			}
        });

		hubspot_abovethefold = false;
		$('.hs-form-load').each(function() {
			if (isInViewport($(this).get(0),0)) {
				hubspot_abovethefold=true;
			}
        });
		if (hubspot_abovethefold) {
			console.log('hs atf')
			loadHubspot();
		}
		
		$('.lazy-border').each(function() {
			if (isInViewport($(this).get(0),0)) {
				imgsrc=$(this).attr('data-border-image');
				if (imgsrc)
					$(this).css('border-image-source', 'url('+imgsrc+')').removeClass('lazy-border');
			}
		});

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

		if (scrolled) {

			if (!loadedafterscroll) {
				loadedafterscroll = true;

			    if ($('.hs-form-load').length) {
					console.log('hs delayed')
					loadHubspot();
			     }

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

				$.getScript('/js/main.js');
				if (!fancyboxloaded) {
					//console.log('fbl')
					$.getScript('/fancybox2/jquery.fancybox.pack.js', function() {
						$.getScript('/js/fancybox.js?v=2.7', function() {
		                    if (typeof takeoverPop !== 'undefined')
		                             takeoverPop();
						});
					});
					loadCSS('/fancybox2/jquery.fancybox.css');
				} else {
                    if (typeof takeoverPop !== 'undefined')
                             takeoverPop();
				}
				
				$.getScript('https://snapwidget.com/js/snapwidget.js');

				if ($('.featuredSliderContainer').length) {
					console.log('load ss')
					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() {
					    $('.episode-slider').slick({
					      centerMode: false,
					      variableWidth: false,
					      slidesToShow: 4,
					      slidesToScroll: 1,
					      autoplay: true,
					      autoplaySpeed: 4000,
					      infinite: true,
					      dots: false,
					      arrows: true,
			                prevArrow: '<img src="/images/icon-arrow-right-white.svg" width="25" class="arrow prev" alt="Previous" />',
			                nextArrow: '<img src="/images/icon-arrow-right-white.svg" width="25" class="arrow next" alt="Next" />',
					      responsive: [
					        {
					          breakpoint: 1024,
					          settings: {
					            arrows: true,
					            centerMode: false,
					          slidesToScroll: 1,
					            slidesToShow: 2
					          }
						},
						{
					          breakpoint: 550,
					          settings: {
					            arrows: true,
					            centerMode: false,
					          slidesToScroll: 1,
					            slidesToShow: 2
					          }
						}
					      ]
					    });
					});
				}

		        // top slideshow
		        $('.slideshow .lazy-bg').each(function() {
		           imgsrc=$(this).attr('data-image');
//				   console.log('loaading '+imgsrc)
		           $(this).css('background-image', 'url('+imgsrc+')').removeClass('lazy-bg');
		        });
			   	$('.homePhotos .lazy-img').each(function() {
                    imgsrc =  $(this).attr('data-src');
	                $(this).attr('src', imgsrc).removeClass('lazy-img');
				});
			   	$('.sliderPhotos .lazy-img').each(function() {
                    imgsrc =  $(this).attr('data-src');
	                $(this).attr('src', imgsrc).removeClass('lazy-img');
				});
			   	$('.fpPhotos .lazy-img').each(function() {
                    imgsrc =  $(this).attr('data-src');
	                $(this).attr('src', imgsrc).removeClass('lazy-img');
				});


				$.getScript('/js/jquery.ui.touch-punch.min.js');
				if (typeof jqui_loaded === 'undefined' || !jqui_loaded) {
					$.getScript('/js/jquery-ui-1.12.1.min.js', function() {
					    $(".datepicker").datepicker();
					});
					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
*/
				}

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

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

    }
	adjustSlideshowPosition();

        addEventListener('scroll', function() {
			scrolled = true;
			lazyLoadScroll();
			
	        var scrollPos = window.pageYOffset;
			if (scrollPos > 100)
				$('body').addClass('scrolled100')
			else
				$('body').removeClass('scrolled100')
		});
	    addEventListener('click', function() {
	            scrolled = true;
	            lazyLoadScroll();
	    });
	    addEventListener('touchend', function() { // for mobile
	            scrolled = true;
	            lazyLoadScroll();
	    });
    	var y = window.scrollY;
    	if  (y>0) // if already scrolled down on page load
			scrolled=true;

        lazyLoadScroll();

        addEventListener('resize', function() {
			adjustSlideshowPosition();
		});
		
		function adjustSlideshowPosition() {
			is_mobile = $(window).width() <= 800;
			console.log('adjust')
			headerheight = $('header').height();
			console.log(headerheight)
			vh = is_mobile ? '95vh' : '100vh'; // account for bottom search bar on mobile
			if ($('.p_index .main-header-image .slideshow').hasClass('short') && $('.p_index .main-header-image .slideshow').attr('data-height')) {
				new_vh = $('.p_index .main-header-image .slideshow').attr('data-height');
				if (is_mobile) new_vh -= 5;
				vh = new_vh + 'vh';
				$('.p_index .main-header-image .slideshow').css('height', 'calc('+vh+' - '+headerheight+'px)');
			}
			else
				$('.p_index .main-header-image .slideshow').css('height', 'calc('+vh+' - '+headerheight+'px)');
			
			
			// also check for any horizontal scroller and remove the arrows if not overflowing
			$('.contentBlock.t111 .content table tbody').each(function() {
				element = $(this).get(0);
				//console.log(element.offsetWidth)
				//console.log(element.scrollWidth)
				if ((element.offsetWidth+50) < element.scrollWidth) {
					$(this).find('.scroll-wrapper').removeClass('hidden');
					console.log('overflow')
				} else {
					console.log('hide arrows')
					$(this).find('.scroll-wrapper').addClass('hidden');
				}
			});
		}
        // start slideshow
		if (typeof responsiveSlides === 'function') {
	        $(".main-header-image .slide_group").responsiveSlides({
	              auto: true,
	              pager: true,
	//                        nav: true,
	//                      navContainer: '#sliderNav #nav',
	                nextText:'<div class="next_btn"><img src="/images/icon-arrow-right.svg" alt=""></div>',
	                prevText:'<div class="previous_btn"><img src="/images/icon-arrow-left.svg" alt=""></div>',
	                speed: 500,
	                timeout:5000
	        });
		}

		
		$('.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() {
			$(this).parents('.previewmode').removeClass('previewmode');
		    $('.filterable .lazy-bg').each(function() {
		        imgsrc=$(this).attr('data-image');
		        $(this).css('background-image', 'url('+imgsrc+')').removeClass('lazy-bg');
		    });
			$(this).hide();
		})
		
		$('.remove-filters').on('click', function() {
			$('.filterable .remove-filters').hide();
			$('.filterable .featured-container').show();
			$('.item-wrapper').show(); // re-activate all
            $('.item').show(); // re-activate all
			$('.item > a').attr('data-fancybox-group', 'all');
            $('.filters .filter').removeClass('on');
            $('.filters .filter.all').addClass('on');
		});

        $('.filters').on('click', '.filter', { passive: true }, function() {
			$('.filterable .featured-container').hide();
			$('.filterable .remove-filters').show();

			$('.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-wrapper').show(); // re-activate all
                        $('.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');

                        hasWrapper = $('.filterable .item-wrapper').length;
						itemClass = hasWrapper ? '.item-wrapper' : '.item';
                        $('.filterable ' + itemClass).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 });
		    });

	is_mobile = $(window).width() <= 1000;

	if (is_mobile) {
		$('.table-of-contents').addClass('fixed').addClass('collapsed');
		$('.table-of-contents').appendTo('body');
		
		$('body').on('click', '.table-of-contents a', function() {
			$('.table-of-contents').addClass('collapsed');
			console.log('c')
		})
	}

    // Set Top Nav to fixed bar when window scrolls down
    activearea = '';
    $(window).scroll(function (event) {
        var scroll = $(window).scrollTop();

        // community navigation bar -- fixed once it reaches the bottom of the header
        if ($('.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')

        }

		// Set table of contents when window scrolls down
		if (!is_mobile) {
			if ($('.table-of-contents:not(.fixed)').length) {
	            fixedToCTrigger = $('.table-of-contents:not(.fixed)').offset().top;
	            if (scroll  > (fixedToCTrigger)) { 
					cloned = $('.table-of-contents:not(.fixed):not(.cloned)').clone()
					$('.table-of-contents:not(.fixed)').addClass('cloned');
					cloned.addClass('fixed').insertAfter('.table-of-contents:not(.fixed)');
				}
	            else if (!is_mobile) {
	                $('.table-of-contents.fixed').remove();
	                $('.table-of-contents').removeClass('cloned')
//	                $('.table-of-contents').removeClass('fixed')
	            }
	        }
			
		}
    });

	$('body').on('click', '.table-of-contents.fixed tr:first-child p:first-child', function() {
		$('.table-of-contents').toggleClass('collapsed')
	});
	$('body').on('click', '.table-of-contents.fixed.collapsed tbody', function() {
		$('.table-of-contents').toggleClass('collapsed')
	});

	// SEF Report
	$('.sef').on('change', 'select', function() {
		console.log('c');
		day = $('.sef-day').val();
		month = $('.sef-month').val();
		year = $('.sef-year').val();
		if (day && month && year) {
			reportdate = year + '-' + month + '-' + day;
			
			$('.sef-report').load('/common/sefreport.php?d='+reportdate);
		}
		
	});
			
    // 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');
    });

	if ($('.typewriter').length) {
		var typing = false;
		var wordcount=0;

		//console.log('type')
		//console.log(animatedtext)
		
		words = animatedtext.length;
		//console.log(words);
		
  		var txt = animatedtext[wordcount]; /* The text */
  		var lettercnt = 0;
		var speed = 80; /* The speed/duration of the effect in milliseconds */
		typeWriter();
	}
	
	function typeWriter() {
		if (lettercnt==0) {
			document.getElementById("typewriter").innerHTML = '';
		}
		if (lettercnt < txt.length) {
			document.getElementById("typewriter").innerHTML += txt.charAt(lettercnt);
			lettercnt++;
			if (lettercnt==txt.length){
				wordcount++;
				//console.log(wordcount)
				//console.log(words);
				if (wordcount>=words) {
					wordcount=0;	
				}
				//console.log(wordcount)

				lettercnt = 0;
				txt = animatedtext[wordcount]; /* The text */

				setTimeout(typeWriter, 2000); /* time before next word */
			} else {
				setTimeout(typeWriter, speed);
			}
		}
	}

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

    /* ===============================================================================================================
 	===============================================================================================================*/                                      
			
	$('a[id]:empty').addClass('adjustAnchor');

	$('.contentBlock').on('click', '.table-flow-chart a', function(event) {
        event.preventDefault();
		is_infowindow = $(this).parents('.table-flow-chart-moreinfo').length;
		if (is_infowindow) {
			MoreInfoBox = $(this).closest('table').closest('td').find('.table-flow-chart-moreinfo');
			openerContainer = MoreInfoBox.closest('tr');
			openerContainer.height('')
		}
		else {
			MoreInfoBox = $(this).closest('td').find('.table-flow-chart-moreinfo');
			openerContainer = $(this).closest('tr');
			newH = parseInt(MoreInfoBox.height())-48;
			openerContainer.height(newH)
		}
		MoreInfoBox.toggleClass('active');
	})
	function checkCounter() {
		$('.counter:not(.activated)').each(function() {
			parentContainer = $(this).parent();
			divContainer = $(this).parents('div');
			if (isInViewport(divContainer.get(0))) {
			  var $this = $(this),
				thisText=$this.text(),
			    countTo = parseInt(thisText);
				appendPlus = thisText.search(/\+/) > -1 ? true : false;
//				console.log(countTo);
			    parentContainer.show();
				$this.addClass('activated');
//	console.log($this.text());

			  $({
	//		    countNum: $this.text()
				  countNum: 0
			  }).animate({
			      countNum: countTo
			    },

			    {
			      duration: 3000,
			      easing: 'linear',
			      step: function() {
			        $this.text(commaSeparateNumber(Math.floor(this.countNum)) + (appendPlus ? '+' : ''));
			      },
			      complete: function() {
			        $this.text(commaSeparateNumber(this.countNum) + (appendPlus ? '+' : ''));
			        //alert('finished');
			      }
			    }
			  );
			}
		});
	}
	/*
	counterdiv = document.getElementById('counter-container');
	startval = parseFloat(counterdiv.innerHTML.replace(/,/g, ''));
	val = startval-200;
	val =val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
	counterdiv.innerHTML = val;
	*/

	addEventListener('scroll', function() {
		checkCounter();
		checkBackToTop();
	});

	function checkBackToTop() {
        var scrollPos = window.pageYOffset;

		if (scrollPos>400)
			$('.back-to-top').css('bottom', '17px');
		else
			$('.back-to-top').css('bottom', '-30px');
		
	}

/* 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 updatePlayStatus(thisVideo) {
	if (thisVideo.paused) {
		$(thisVideo).parents('.img-wrapper').removeClass('playing')
	} else {
		$(thisVideo).parents('.img-wrapper').addClass('playing')
	}
}
function triggerVideo(thisChild) {
	thisVideo = $(thisChild).parents('.wrapper').find('video');
	thisVideo.get(0).play();
	updatePlayStatus(thisVideo);
}
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 loadHubspot() {
	if (!hubspotloaded) {
		hubspotloaded=true;
		console.log('loading hs')
	    $.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: ''
	            });
	        })
	    });
	}
}
function fancyVideoAutoPlay() {
	setTimeout(function () {
//		$('.fancybox-iframe').attr('autoplay', true).attr('allow', 'autoplay');
    }, 2000);
}
function commaSeparateNumber(val) {
  while (/(\d+)(\d{3})/.test(val.toString())) {
    val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
  }
  return val;
}

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;
}
