//TODO move alot of this DOM manipulation into on('headerChange')
function checkScroll(){
	$body = $("body");
	if( $(window).scrollTop() > $(".alertBox").outerHeight() ){
		if(!$body.hasClass("pageScrolled")){
			$(".alertBox").removeClass("showAlert");
			$body.addClass("pageScrolled");
			/*
			//close the menu
			$("header").removeClass("show-nav").find("#menu-header-menu > li")
				.removeClass("activeMenu").siblings().removeClass("activeMenu");
			$("#menu-header-menu").attr('aria-hidden', true);
			*/
		}
	}else{
		$body.removeClass("pageScrolled");

		//close the menu
		/*
		$("header").removeClass("show-nav").find("#menu-header-menu > li")
			.removeClass("activeMenu").siblings().removeClass("activeMenu");

		$("#menu-header-menu").attr('aria-hidden', true);
		*/

		//reset the browser anchor history
//		history.replaceState("", document.title, window.location.pathname + window.location.search);
	}
}

function adjust_h1() {
	//adjust H1 ids
	var window_width = $(window).width();
	if (window_width <= 768) {
		$(".header-image-mobile h1").attr("id", "skip");
		$(".header-image-desktop h1").attr("id", "");
	}
	else {
		$(".header-image-mobile h1").attr("id", "");
		$(".header-image-desktop h1").attr("id", "skip");
	}
}

$(function() { // event rigging

	$(".mobileMenu").on("click", function(event){
		$("header").toggleClass("show-nav");
		$("#menu-header-menu").attr('aria-hidden', !$("header").hasClass("show-nav"));
	});

	adjust_h1();
	checkScroll();
	
	var resizeTimer;
	$(window).on('resize', function(e) {
		clearTimeout(resizeTimer);
		resizeTimer = setTimeout(function() {
		//debounced resize event
		
		//resizing has "stopped", cleanup menu
		$("header").removeClass("show-nav");
		$("#menu-header-menu").attr('aria-hidden', true);
		$("header li.activeMenu").removeClass("activeMenu");
		
		adjust_h1();
	    checkScroll();
		waypoint.refreshAll();
	  }, 1);
	});
	var scrollTimer;
	$(window).on('scroll',  function(e) {
		//debounced scroll event
		checkScroll();
	});

	$(document).click(function(e) {
		if ($(e.target).closest('header').length === 0) {
			//close menu, cleanup
			$("header").removeClass("show-nav");
			$("#menu-header-menu").attr('aria-hidden', true);
			$("header li.activeMenu").removeClass("activeMenu");
		}
		if ($(e.target).closest('.alertBox').length === 0) {
			//close alert
			$(".alertBox").removeClass("showAlert");
		}
	});
	
	/* level-2 menu toggle */
	$(document).on('click', "header.show-nav ul#menu-header-menu>li>a", function(e){

		e.preventDefault();
	    e.stopPropagation();

		var rect = e.target.getBoundingClientRect();
		var xpos = e.pageX - rect.left;
		
		if (xpos > ($(this).outerWidth() - 62)) { //62 pixels on right for icon click
	        $(this).parent().toggleClass("activeMenu").siblings().removeClass("activeMenu");
	    }else{

			if($(this).parent().hasClass("activeMenu")){
				document.location=$(this).attr("href");
			}else{
	        	$(this).parent().addClass("activeMenu").siblings().removeClass("activeMenu");
			}
		}

	    return false;
	});

	$("header a.homeLink").on("focus", function(e){
		$(".alertBox").removeClass("showAlert");
	});
	$(".alertBox a").on("focus", function(e){
		$(".alertBox").addClass("showAlert");
	});
	$(".alertBox").on("keydown", function(event){
		if (a11yClick(event) === true) {
			if (event.target.tagName === 'A') return; // allow clicking links in alerts
			event.preventDefault();
			event.stopPropagation();
		}
	});
	$(".alertBox").on("click keyup", function(event){
		if (a11yClick(event) === true) {
			if (event.target.tagName === 'A') return; // allow clicking links in alerts
			event.preventDefault();
			event.stopPropagation();
			$(this).toggleClass("showAlert");
		}
	});
	
	//waypoint sticky headers
	var stickys = new Array();
	var theHistories = new Array();

	var stickyHandler = function(direction){

		var previousWaypoint = this.waypoint.previous();
		var nextWaypoint = this.waypoint.next();

		$(".sticky-wrapper").removeClass('wp-current wp-next').addClass("wp-previous");
		
		$(this.element).parent(".sticky-wrapper").removeClass('wp-previous').addClass('wp-current');
		
		if(direction=="up"){

			if(previousWaypoint){
				$(previousWaypoint.element).removeClass('wp-previous')
			}
		}else{
			if (nextWaypoint) {
			  $(nextWaypoint.element).removeClass('wp-current').addClass('wp-next');
			}
		}
	}
	var historyHandler = function(direction){

		var histElement = this.element; //the element we consult for history
		
		//history # of location
		var theId =  $(histElement).attr("id");
		if(direction==="up" && !this.previous()){
			theId = null;
		}else if(direction==="up"){
			theId = $(this.previous().element).attr("id");
		}
		if(theId){
			var theTitle = histElement.text();
			history.replaceState(theId, theTitle, "#"+theId);
		}else{
			history.replaceState("", document.title, window.location.pathname + window.location.search);
		}
	}
/*
	var theHero = new Waypoint.Sticky({
		element: $("#hero"),
		offset: 93
	})
	
	$('.destroy-sticky').on('click', function() {
		theHero.destroy();
	});
	$('.refresh-sticky').on('click', function() {
		Waypoint.refreshAll();
	});
	$('.resize-sticky').on('click', function() {
		var heroHeight = $("#hero").outerHeight();
		$(".hero__section > .sticky-wrapper").height(heroHeight);
	});
*/
	var theHeader = $("header").each(function(){
		stickys.push(new Waypoint.Sticky({
			element: $(this),
			handler: stickyHandler
		}))
	});
	/*
	var theHero = $(".hero__sticky").each(function(){
		stickys.push(new Waypoint.Sticky({
			element: $(this),
			offset: 93,
			handler: stickyHandler
		}))
	});
	*/
	var theModules = $(".isSticky").each(function(){
		stickys.push(new Waypoint.Sticky({
			element: $(this),
			offset: ($("header").outerHeight()),
			group: "isStickys",
			handler: stickyHandler
		}))
	});

	//history updates when crossing anchors
	$(".module a.anchor").each(function(){
		theHistories.push(new Waypoint({
			element: $(this),
			group: "histories",
			handler: historyHandler
		}));
	});
	
	$('.popper').each(function() {
		$(this).data("top", $(this).offset().top);
	});
	
	$(".popper-bar").on("keydown", function(event){
		if (a11yClick(event) === true) {
			event.preventDefault();
			event.stopPropagation();
		}
	});
	$(".popper-bar").on("click keyup", function(event){
		if (a11yClick(event) === true) {
			event.stopPropagation();
			event.preventDefault();
			var this_popper = $(this).closest(".popper");
			if (this_popper.hasClass("open")) {
				this_popper.attr("aria-expanded", "false");
				$(".popper").removeClass("open");
			}
			else {
				this_popper.attr("aria-expanded", "true");
				$(".popper").removeClass("open");
				this_popper.addClass("open");
				
				$('html, body').animate({
					scrollTop: this_popper.data().top - 62
				}, 'slow');
			}
		}
    });

	//-- module functionality
	
	$(".faq").click(function(e) {
		$(this).toggleClass("open").siblings().removeClass("open");
		if ($(this).hasClass("open")) {
			$(this).children(".question").attr("aria-expanded", "true");
		}
		else {
			$(this).children(".question").attr("aria-expanded", "false");
		}
	});
	
	$('.pricing-carousel .owl-carousel').owlCarousel({
		loop: true,
		responsiveClass: true,
		nav: true,
		items: 1,
		center: true,
		navText: [
			"",
			""
		],
	});
	
	$('.carousel .owl-carousel').owlCarousel({
		loop: true,
		responsiveClass: true,
		nav: true,
		navText: [
			"",
			""
		],
		responsive: {
			0: {
				items: 1,
				center: true
			},
			600:{
				items: 2,
				center: false,
				margin: 20
			},
			850:{
				items: 2,
				center: false,
				margin: 50
			},
			1200:{
				items: 2,
				center: false,
				margin: 90
			}
		}
	});
	
	//-- end event rigging
	
	var is_events_page = $("#is_events_page").val();
	if (is_events_page == "1") {
		$("#menu-item-142").addClass("active");
	}
	
	/*************************************
    Responsive Video
    *************************************/
 
    $(".inner iframe:not(.instagram-media)").wrap("<div class='embed-container'></div>");
	
	$(".skip-main").click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
			if (target.length == 1) {
				
				var offset_adjuster = 72;
				var window_width = $(window).width();
				if (window_width <= 768) {
					offset_adjuster = 100;
				}
								
				$('html,body').animate({
					scrollTop: target.offset().top - offset_adjuster //offsets for fixed header
				}, 500);
				//return false;
			}
		}
	});
});


/*************************************
Checks for click of Enter or Space
*************************************/

function a11yClick(event) {
	if (event.type === 'click') {
		//console.log('click');
		return true;
	}
	else if (event.type === 'keyup' || event.type === 'keydown') {
		var code = event.charCode || event.keyCode;
		if ((code === 32) || (code === 13)) {
			//console.log('Space pressed');
			return true;
		}
		else {
			//console.log('not space');
			return false;
		}
	}
	else{
		//console.log('nope');
		return false;
	}
}