/**
*** Theme functions file.
**/

( function( $ ) {

	$( document ).ready( function() {

		$(document).router({

		    common: function() {
          /*
			    |--------------------------------------------------------------------------
			    | Anchor Link
			    |--------------------------------------------------------------------------
			    */
          $('a.anchor').on('click', function (e) {
            e.preventDefault();

            var target = $($(this).attr('href'));
            
            $('html, body').animate({
              scrollTop: $(target).offset().top - 150
            }, 250);
          });


          /*
			    |--------------------------------------------------------------------------
			    | Notification Bar
			    |--------------------------------------------------------------------------
			    */
          $('.notification-bar .close').click(function(){
            $('body').removeClass('with-notification-bar');
            $('.notification-bar').hide();
          });


				  /*
			    |--------------------------------------------------------------------------
			    | Fixed Header
			    |--------------------------------------------------------------------------
			    */

			    var fixHeader = function(){
			        if ($(window).scrollTop() > 300) {
			            if (!$('header').hasClass('condensed')){
				            $('header').addClass('condensed');
				            window.setTimeout(function(){$('header').addClass('active');}, 250);
				        }
			        }
			        else{
			        	if ($('header').hasClass('condensed')){
				            $('header').removeClass('condensed active');
				        }	
			        }
			    };

			    // On load fix the header
			    $(window).on('load', function(){
			        fixHeader(true);
			    });

			    // On scroll fix the header
			    $(window).scroll(function(){
			        fixHeader();
			    });

			    /*
			    |--------------------------------------------------------------------------
			    | Site Search
			    |--------------------------------------------------------------------------
			    */

			    $('.utility-nav .icon-link.search').click(function(e){
			    	e.preventDefault();
			    	ToggleSearch();
			    	if($('.mobile-nav').hasClass('open')){
			    		ToggleMobileMenu();
			    	}
			    })

			    function ToggleSearch(){
			    	$searchBtn = $('.utility-nav .icon-link.search');
			    	$search = $('header .search')
			    	if(!$searchBtn.hasClass('active')){
			    		//this adds active to both the search div and the search link
			    		//in the utility nav, because they have the same .search class
			    		$search.addClass('active');
			    		$search.find('.form-control').focus();
			    	}
			    	else{
			    		$search.removeClass('active');	
			    	}
			    }

			    //close the search if you click anywhere else
			    $(document).click(function(event) { 
				    if(!$(event.target).closest('.search').length) {
				        if($('header .search').hasClass('active')) {
				            ToggleSearch();
				        }
				    }        
				})

				/*
			    |--------------------------------------------------------------------------
			    | Mobile Menu
			    |--------------------------------------------------------------------------
			    */

			    $('.mobile-nav-link a').click(function(e){
			    	e.preventDefault();
			    	ToggleMobileMenu();
			    });

			    function ToggleMobileMenu(){
			    	$mobileNavButton = $('.mobile-nav-link a');
			    	$mobileNav = $('.mobile-nav');
			    	if($mobileNav.hasClass('open')){
			    		$mobileNavButton.removeClass('open');
			    		$mobileNavButton.html('<i class="material-icons">menu</i>');
			    		$mobileNav.removeClass('open');
			    		$('body').removeClass('no-scroll');
			    	}else{
			    		$mobileNavButton.addClass('open');
			    		$mobileNavButton.html('<i class="material-icons">close</i>');
			    		$mobileNav.addClass('open');
			    		$('body').addClass('no-scroll');
			    	}
			    }

				$('.mobile-nav .collapse-arrow').click(function(){
					$(this).toggleClass('collapsed');
					$(this).parent('li').toggleClass('expanded');
					$(this).next('.collapse').toggleClass('in');
				});

				$('.side-nav .collapse-arrow').click(function(){
					$(this).toggleClass('collapsed');
					$(this).parent('li').toggleClass('expanded');
				});

				/*
			    |--------------------------------------------------------------------------
			    | Fancybox
			    |--------------------------------------------------------------------------
			    */

			    $('.fancybox').fancybox();

			    $('.fancybox[href^="http"]').fancybox({
			    	'type': 'iframe',
			    	'width': 600,
			    	'height': 600
			    });

			    /*
			    |--------------------------------------------------------------------------
			    | Panorama embeds
			    |--------------------------------------------------------------------------
			    */


			    initializePanoramas();

			    /*
			    |--------------------------------------------------------------------------
			    | Interactive Map
			    |--------------------------------------------------------------------------
			    */

			    var $panzoom = $('.panzoom');
				$zoomInButton = $(".zoom-in");
				$zoomOutButton = $(".zoom-out");
				var minScale = 0.75;

				if($(document).width() > 1600){
					var minScale = 1.0;
				}

				$panzoom.panzoom({
				  contain: 'invert',
				  minScale: minScale,
					maxScale: 1.75,
				  increment: 0.25,
				  startTransform: 'scale('+minScale+')',
				  $zoomIn: $zoomInButton,
				  $zoomOut: $zoomOutButton
				});

			    $tooltip = $('.tooltip');

			    $('.map-menu-list a').click(function(e){
			    	e.preventDefault();
			    	$target = $($(this).attr('href'));
			    	if($target){
			    		MoveToHotspot($target);
			    		SetTooltipText($(this).html());
			    		ActivateHotspot($target);
			    		//deactivate 2 seconds later
			    		setTimeout(function(){
							DeactivateHotspot($target)
						}, 2000);
			    	}
			    });

			    //mobile map-menu-list, close dropdown on click of menu item
			    //close the dropdown when you apply filters
				$(document).on('click', '.dropdown.map-menu-list li a', function (e) {
					$('#dropdownMenuButton').dropdown('toggle');
				});
				
				//handle differently on mobile
				$('.hotspot').on('touchstart', function(e){
					e.stopImmediatePropagation();
					var $this = $(this);

					if($this.attr('class') == 'hotspot'){
						//MoveToHotspot($(this));
			    		//find map menu item that corresponds to this hotspot
						var id = $this.attr('id');
						$menuItem = $('a[href$="'+id+'"]');
						//insert innerhtml into tooltip
						SetTooltipText($menuItem.html());
						ActivateHotspot($this);
			    		//deactivate 2 seconds later
			    		setTimeout(function(){
							DeactivateHotspot($this)
						}, 2000);
			    	}
			    	else{
			    		// open location
						if($(this).data('slideout') == true){
							// open location
							locationOpen( $(this).attr('id') );
						}
			    	}
				});
			    
			    $('.hotspot').click(function(e){
			    	MoveToHotspot($(this));
			    });			

				$('.hotspot').mouseover(function(){
					//find map menu item that corresponds to this hotspot
					var id = $(this).attr('id');
					$menuItem = $('a[href$="'+id+'"]');
					//insert innerhtml into tooltip
					SetTooltipText($menuItem.html());
					ActivateHotspot($(this));
				});

				$('.hotspot').mouseleave(function(){
					DeactivateHotspot($(this));
				});

				$(window).scroll(function(){
					FixTooltip();
				});

				$panzoom.on("panzoompan", function(){
					FixTooltip();
				});

				function MoveToHotspot(hotspot){
					var $parent = $('.panzoom-parent');
			    	var parentCenterX = $parent.offset().left + $parent.width() * 0.5;
					var center = GetCenterOfHotspot(hotspot);
					panX = (center.x - parentCenterX) * -1;

					var centerY = ($parent.offset().top - $(window).scrollTop()) - center.y;
					panY = (centerY*-1) - $parent.height() * 0.5;
					$panzoom.panzoom('pan', panX, -panY, {relative: true});
				}

				function ActivateHotspot(hotspot){
					//addclass doesn't work for some reason
					hotspot.attr('class', 'hotspot active');
					var center = GetCenterOfHotspot(hotspot);

					//position tooltip
					$tooltip.css({
						//compensate for tooltip dimensions
						left : center.x - $tooltip.width()*0.5 - 10,
						top : center.y - $tooltip.height()*0.75 - 45
					});
					$tooltip.addClass('visible');
				}

				function DeactivateHotspot(hotspot){
					//remove hovered class
					hotspot.attr('class', 'hotspot');
					$tooltip.removeClass('visible');
				}

				function GetCenterOfHotspot(hotspot){
					//get the bounding box of this polygon
					var boundingBox = hotspot[0].getBoundingClientRect();
					//center from left
					var centerX = boundingBox.left + boundingBox.width * 0.5;
					//center from top
					var centerY = boundingBox.top + boundingBox.height * 0.5;

					return {x:centerX, y:centerY};
				}

				function SetTooltipText(text){
					$tooltip.html(text);
				}

				function FixTooltip(){
					//check if a hotspot is currently hovered
					$hoveredHotspot = $('.hotspot.active');
					if($hoveredHotspot.length){
						var center = GetCenterOfHotspot($hoveredHotspot);						
						//position tooltip
						$tooltip.css({
							//compensate for tooltip dimensions
							left : center.x - $tooltip.width()*0.75,
							top : center.y - $tooltip.height()*0.75 - 30
						});
					}
				}

		    },

		    home: function() {
			    //var fixDiscoverCarousel = $('.discover-carousel').height($('.news-events .tab-content').height());
		    },

		    events_list: function() {
			    $('.events-search').submit(function(e){
			    	e.preventDefault();

			    	keyword = $(this).find('[name=keyword]').val();

			    	$('#tribe-bar-search').val(keyword);
			    	$('#tribe-bar-form').submit();
			    });

			    $(document).on('click', '.tribe-mini-calendar-day-link', function(e){
			    	e.preventDefault();

			    	day = $(this).data('day');

			    	$('#tribe-bar-date').val(day);
			    	$('#tribe-bar-form').submit();
			    });

			    $('.btn-full-calendar').click(function(e){
			    	e.preventDefault();

			    	$('[name=tribe_eventcategory]').val('');
			    	$('#tribe_events_filters_form').submit();
			    });

			    $('.btn-undergrad-admissions-calendar').click(function(e){
			    	e.preventDefault();

			    	$('[name=tribe_eventcategory]').val(5);
			    	$('#tribe_events_filters_form').submit();
			    });

			    $('.btn-grad-admissions-calendar').click(function(e){
			    	e.preventDefault();

			    	$('[name=tribe_eventcategory]').val(54);
			    	$('#tribe_events_filters_form').submit();
			    });
			    
			     $('.btn-catalyst-calendar').click(function(e){
			    	e.preventDefault();

			    	$('[name=tribe_eventcategory]').val(105);
			    	$('#tribe_events_filters_form').submit();
			    });
		    }
		    
		});
			/*
	    |--------------------------------------------------------------------------
	    | Mega Menu ie10
	    |--------------------------------------------------------------------------
	    */
	    //add useragent to html for reference
	    var doc = document.documentElement;
			doc.setAttribute('data-useragent', navigator.userAgent);

			/*
	    |--------------------------------------------------------------------------
	    | Table classes
	    |--------------------------------------------------------------------------
	    */

	    $('.content table').each(function(){
	    	//add styles to make tables players
	    	$(this).addClass('table table-striped table-bordered');

	    	//wrap in responsive class
	    	$(this).wrap( "<div class='table-responsive'></div>" );
	    });

	    /*
	    |--------------------------------------------------------------------------
	    | Detail Pages
	    |--------------------------------------------------------------------------
	    */

	    //$('.detail-2-col .sidebar ul.side-nav > li.has_children').

	    $(document).on('click', '.additional-nav .dropdown-menu', function (e) {
			  e.stopPropagation();
			});

	    /*
	    |--------------------------------------------------------------------------
	    | Isotope
	    |--------------------------------------------------------------------------
	    */

	    /* dict Page */

	    var $dictGrid = $('.dict-grid');

	    $(window).resize(function(){
	    	$dictGrid.isotope('layout');
	    });

		$dictGrid.isotope({
		  itemSelector: '.dict-grid-item',
		  percentPosition: true,
		  masonry: {
		    columnWidth: '.dict-grid-sizer',
		    gutter: '.dict-gutter-sizer'
		  }
		});

		$('.dict-grid-item:not(.big)').click(function(){
			$this = $(this);
			$dictGrid.find('.big').removeClass('big');
			$this.addClass('big');
			$dictGrid.isotope('layout');
			setTimeout(function(){
				if($this.hasClass('big')){
					$('html, body').animate({
				        scrollTop: $this.offset().top - $('header').height() - 15
				    }, 250);
				}
			}, 100);
		});

		$('.dict-nav-prev').click(function(){
			$parentGridItem = $(this).parents('.dict-grid-item');
			$prevGridItem = $parentGridItem.prev('.dict-grid-item');
			if($prevGridItem.length){
				setTimeout(function(){
					$parentGridItem.removeClass('big');
					$prevGridItem.addClass('big');
					$dictGrid.isotope('layout');
					setTimeout(function(){
						$('html, body').animate({
					        scrollTop: $prevGridItem.offset().top - $('header').height() - 15
					    }, 250);
					}, 100);
				}, 100);
			}
		});

		$('.dict-nav-next').click(function(){
			$parentGridItem = $(this).parents('.dict-grid-item');
			$nextGridItem = $parentGridItem.next('.dict-grid-item');
			if($nextGridItem.length){
				setTimeout(function(){
					$parentGridItem.removeClass('big');
					$nextGridItem.addClass('big');
					$dictGrid.isotope('layout');
					setTimeout(function(){
						$('html, body').animate({
					        scrollTop: $nextGridItem.offset().top - $('header').height() - 15
					    }, 250);
					}, 100);
				}, 100);
			}
		});
		

		$('.dict-nav-close').click(function(){
			$parentGridItem = $(this).parents('.dict-grid-item');
			setTimeout(function(){
				$parentGridItem.removeClass('big');
				$dictGrid.isotope('layout');
			}, 100);
		});

		/* Majors & Programs */

		var $programGrid = $('.program-grid').isotope({
		  itemSelector: '.program-grid-item',
		  percentPosition: true,
		  sortBy: 'lastname',
		  getSortData: {
		    lastname: '.lastname', // text from querySelector
		    weight: function( itemElem ) { // function
		      var weight = $( itemElem ).find('.weight').text();
		      return parseFloat( weight.replace( /[\(\)]/g, '') );
		    }
		  },
		  masonry: {
		    columnWidth: '.program-grid-sizer',
		    gutter: '.program-gutter-sizer'
		  }
		});

		/* filter handling */

		// disable letters
		function toggleAlpha() {
			$('.alpha-filters a').each(function() {
				alpha = $(this).data('alpha')

				if ($('.program-grid-item[data-alpha="' + alpha + '"]:visible').length) {
					$(this).removeAttr('disabled');
				} else {
					$(this).attr('disabled', 'disabled');
				}
			})
		}

		toggleAlpha();

		$programGrid.isotope('on', 'layoutComplete', function () {
			toggleAlpha();
		});

		// scroll to letter
		$('.alpha-filters a').click(function (e) {
			e.preventDefault();

			alpha = $(this).data('alpha');
			
			$('html, body').animate({
				scrollTop: $('.program-grid-item[data-alpha="' + alpha + '"]:visible:first').offset().top - 95
			});
		})


		//stop clicks closing the filters dropdown
		$(document).on('click', '.dropdown.filters .dropdown-menu', function (e) {
			e.stopPropagation();
		});

		//close the dropdown when you apply filters
		$(document).on('click', '.dropdown.filters .apply-filters', function (e) {
			$('#filterDropdown').dropdown('toggle');
		});

		//degree of study filters

		var degreeOfStudyFilter = '';
		$degreeOfStudyFilterOptions = $('.program-filters .filter-option-group.degree-of-study .filter-option');

		//degree of study filter group buttons
		$('.program-filters .filter-option-group.degree-of-study .filter-option').click(function(e){
			e.preventDefault();
			//var $this = $(this);
			ToggleDegreeOfStudyFilter($(this).attr('data-filter'));
		});

		function ToggleDegreeOfStudyFilter(filterString){
			$degreeOfStudyFilterOptions.each(function(){
				$this = $(this);
				if($this.attr('data-filter') == filterString){
					if($this.hasClass('is-checked')){
						degreeOfStudyFilter = '';
						$this.removeClass('is-checked');
					}
					else{
						$('.program-filters .filter-option-group.degree-of-study .filter-option.is-checked').removeClass('is-checked');
						$this.addClass('is-checked');
						degreeOfStudyFilter = $this.attr('data-filter');
					}
				}
			});
		}

		//school filters

		var schoolFilter = '';
		$schoolFilterOptions = $('.program-filters .filter-option-group.school .filter-option');

		//school filter group buttons
		$('.program-filters .filter-option-group.school .filter-option').click(function(e){
			e.preventDefault();
			//var $this = $(this);
			ToggleSchoolFilter($(this).attr('data-filter'));
		});

		function ToggleSchoolFilter(filterString){
			$schoolFilterOptions.each(function(){
				$this = $(this);
				if($this.attr('data-filter') == filterString){
					if($this.hasClass('is-checked')){
						schoolFilter = '';
						$this.removeClass('is-checked');
					}
					else{
						$('.program-filters .filter-option-group.school .filter-option.is-checked').removeClass('is-checked');
						$this.addClass('is-checked');
						schoolFilter = $this.attr('data-filter');
					}
				}
			});
		}

		//program type filters

		var programTypeFilter = '';
		$programTypeFilterOptions = $('.program-filters .filter-option-group.program-type .filter-option');

		//school filter group buttons
		$('.program-filters .filter-option-group.program-type .filter-option').click(function(e){
			e.preventDefault();
			//var $this = $(this);
			ToggleProgramTypeFilter($(this).attr('data-filter'));
		});

		function ToggleProgramTypeFilter(filterString){
			$programTypeFilterOptions.each(function(){
				$this = $(this);
				if($this.attr('data-filter') == filterString){
					if($this.hasClass('is-checked')){
						programTypeFilter = '';
						$this.removeClass('is-checked');
					}
					else{
						$('.program-filters .filter-option-group.program-type .filter-option.is-checked').removeClass('is-checked');
						$this.addClass('is-checked');
						programTypeFilter = $this.attr('data-filter');
					}
				}
			});
		}

		/**
		 * mynpu cookies
		 */

		$('.mynpu-links a').on('click', function(e) {
			var cookieVal = $(this).data('cookie');

			Cookies.set('mynpu-saved', cookieVal, { expires: Infinity });
		});

		/* search filter */

		var searchFilter = '';

		$( "#grid-search" ).submit(function(e){
			e.preventDefault();
			searchFilter = $('#search-term').val();
			Cookies.set('search-filter', searchFilter, { expires: 0.1 });
			SetSearchFilter();
		});

		//pre-filter if cookie is set and we're on the faculty & staff page
		if(Cookies.get('search-filter') && $('body').hasClass('page-template-page-faculty-and-staff')){
			searchFilter = Cookies.get('search-filter');
			$('#search-term').val(searchFilter);
			SetSearchFilter();
		}

		function SetSearchFilter(){
			if(searchFilter != ''){
				//update status message of current search
				$('#search-status .search-term').html(searchFilter);
				$('#search-status').show();
				//if we're on the faculty grid, unhide hidden staff members without photos
				//during a search
				if($('body').hasClass('page-template-page-faculty-and-staff')){
					$('.program-grid-item').removeClass('hidden-xs-up');
				}
				setTimeout(function(){
					ApplyFilters()
				}, 100);
			}
		}

		//clear search filter if status contains html
		$('#search-status a').click(function(e){
			e.preventDefault();
			//hide status
			$('#search-status').hide();
			//empty search input
			$('#search-term').val('');
			//empty search filter var
			searchFilter = '';
			Cookies.remove('search-filter');
			setTimeout(function(){
				ApplyFilters()
			}, 100);
		});

		/* faculty department select filter */

		var deptFilter = '';

		$('#dept-filter').change(function(){
			deptFilter = $(this).find('option:selected').val();
			//if we're on the faculty grid, unhide hidden staff members without photos
			//during a search
			if($('body').hasClass('page-template-page-faculty-and-staff')){
				$('.program-grid-item').removeClass('hidden-xs-up');
			}
			//set cookie
			Cookies.set('dept-filter', deptFilter, { expires: 0.1 });
			ApplyFilters();
		});

		// pre-filter if cookie is set and we're on the faculty and staff page
		if(Cookies.get('dept-filter') && $('body').hasClass('page-template-page-faculty-and-staff')){
			deptFilter = Cookies.get('dept-filter');
			$('#dept-filter').val(deptFilter).change();
			//unhide staff without images
			if($('body').hasClass('page-template-page-faculty-and-staff')){
				$('.program-grid-item').removeClass('hidden-xs-up');
			}
			setTimeout(function(){
				ApplyFilters()
			}, 100);
		}

		var filterFunction = function(){

		  var filterToApply = '';
			if(degreeOfStudyFilter != ''){
				filterToApply += degreeOfStudyFilter;
			}
			if(schoolFilter != ''){
				filterToApply += schoolFilter;
			}
			if(programTypeFilter != ''){
				filterToApply += programTypeFilter;
			}
			if(deptFilter != ''){
				filterToApply += deptFilter;
			}

			//no filters set, show all
			if(filterToApply == '' && searchFilter == ''){
				return true;
			}
			else{
				//apply search filter if one exists
				if(searchFilter != ''){
            //check if title (h4) contains search term
            var name = $(this).find('h4').text();
				    var match = (name.toLowerCase().indexOf(searchFilter.toLowerCase()) != -1) ? true : false;
				    if(filterToApply != ''){
				    	//if additional filters are set, return true only if
				    	//element has filter classes AND matches search term
				    	return ($(this).is(filterToApply) && match);
				    }
				    else{
				    	//no additional filters set, return true only for elements that match search term
					    return match;
					}
				}
				else{
					//no search filter set, return true on for elements that have the applied filter classes
        
          // compound department created of art, music and theatre departments.
          // otherwise use the exact filter option
          if (filterToApply == '.school-of-music-art-theatre'){
            var results = $(this).is('.school-of-music-art-theatre') || $(this).is('.music') || $(this).is('.art') || $(this).is('.theatre');

            return results;
          } else {
            return $(this).is(filterToApply);
          }
					
				}
			}

		};

		//apply filters

		function ApplyFilters(){
			$programGrid = $('.program-grid').isotope({
				itemSelector: '.program-grid-item',
				percentPosition: true,
				filter: filterFunction,
				animationEngine: 'jquery',
				masonry: {
				columnWidth: '.program-grid-sizer',
					gutter: '.program-gutter-sizer'
				}
			});			
		}


		/*
		$('.alpha-filters a').click(function(e){
			var letter = $(this).
		});

			//$gridItems = $('.program-grid .program-grid-item:visible');
			$startsWithA = $('.program-grid .program-grid-item:visible[data-title^="B"]');
			console.log($startsWithA.first());
		}, 2000);
		*/

		$programGrid.on( 'arrangeComplete', function( event, filteredItems ) {
		  console.log( filteredItems.length );
		});

		//Apply Filters
		$('.program-filters .apply-filters').click(function(e){
			e.preventDefault();
			ApplyFilters();
		});

    // Prefilter URL
    // example: https://www.northpark.edu/academics/all-majors-programs/#filter/undergraduate/all/minor
		if(window.location.hash){
			// if hash contains 'team'
			if (window.location.hash.indexOf('filter') == 1){
				//process url
				url = window.location.hash;
				urlParts = url.replace(/\/\s*$/,'').split('/');
				
				//append periods for classes
				degreeOfStudyUrlPart = '.' + urlParts[1];
				schoolUrlPart = '.' + urlParts[2];
				programTypeUrlPart = '.' + urlParts[3];

				//toggle degree of study filter if its not default value 'all'
				if(degreeOfStudyUrlPart != 'all'){
					ToggleDegreeOfStudyFilter(degreeOfStudyUrlPart);
				}

				//toggle school filter if its not default value 'all'
				if(schoolUrlPart != 'all'){
					ToggleSchoolFilter(schoolUrlPart);
				}

				//toggle program type filter if its not default value 'all'
				if(programTypeUrlPart != 'all'){
					ToggleProgramTypeFilter(programTypeUrlPart);
				}

				ApplyFilters();

			}
		}

	    /*---------------------------------------
		| SLIDEOUTS
		---------------------------------------*/

			var url;
			var url_parts;
			var overlayIsOpen = false;

			function overlayOpen(data){
				$('.overlay').html( data );
				$('.overlay').addClass('active');
				$('body').addClass('no-scroll');
				initializePanoramas();
			}

			function overlayClose(){
				$('.overlay').removeClass('active');
				$('body').removeClass('no-scroll');
				overlayIsOpen = false;
			}

			// Map location

			function locationOpen(locID){
				if( overlayIsOpen ) {
					$('.slide-out').removeClass('active');
				}

				// open overlay
				$('.overlay').addClass('active');

				// set overlay as open
				overlayIsOpen = true;

				args = { 'location_id': locID };

				$.post('/wp-content/themes/northpark/template-parts/location-detail.php', args, function(data){
					// data is not empty
					if(data.trim() == ""){
						// reload page without hash
						//window.location = window.location.href.split('#')[0];

						// set overlay as closed
						overlayIsOpen = false;
					} else {
						// scroll to top
						$('.overlay').animate({
							scrollTop: 0
						},0);

						// open overlay
						overlayOpen( data );

						// read css property hack to prevent instant css transition
						$('.slide-out').css('right');

						// add active class to trigger css transition
						$('.slide-out').addClass('active');
					}
				});
			}

			// Major

			function majorOpen(major){
				if( overlayIsOpen ) {
					$('.slide-out').removeClass('active');
				}

				url = major;
				url_parts = url.replace(/\/\s*$/,'').split('/');

				// open overlay
				$('.overlay').addClass('active');

				// set overlay as open
				overlayIsOpen = true;

				if (typeof other_majors === 'undefined') {
					args = { 'post_name': url_parts[1] };
				} else {
					args = { 'post_name': url_parts[1], 'other_majors': other_majors }
				}

				args.post_id = url_parts[2];

				$.post('/wp-content/themes/northpark/template-parts/major-detail.php', args, function(data){
					// data is not empty
					if(data.trim() == ""){
						// reload page without hash
						window.location = window.location.href.split('#')[0];

						// set overlay as closed
						overlayIsOpen = false;
					} else {
						// scroll to top
						$('.overlay').animate({
							scrollTop: 0
						},0);

						// open overlay
						overlayOpen( data );

						// read css property hack to prevent instant css transition
						$('.slide-out').css('right');

						// add active class to trigger css transition
						$('.slide-out').addClass('active');
					}
				});
			}

			// Staff

			function staffOpen(staff){
				if( overlayIsOpen ) {
					$('.slide-out').removeClass('active');
				}

				url = staff;
				url_parts = url.replace(/\/\s*$/,'').split('/');

				// open overlay
				$('.overlay').addClass('active');

				// set overlay as open
				overlayIsOpen = true;

				if (typeof other_majors === 'undefined') {
					args = { 'post_name': url_parts[1] };
				} else {
					args = { 'post_name': url_parts[1], 'other_staffs': other_majors }
				}

				$.post('/wp-content/themes/northpark/template-parts/staff-detail.php', args, function(data){
					// data is not empty
					if(data.trim() == ""){
						// reload page without hash
						window.location = window.location.href.split('#')[0];

						// set overlay as closed
						overlayIsOpen = false;
					} else {
						// scroll to top
						$('.overlay').animate({
							scrollTop: 0
						},0);

						// open overlay
						overlayOpen( data );

						// read css property hack to prevent instant css transition
						$('.slide-out').css('right');

						// add active class to trigger css transition
						$('.slide-out').addClass('active');
					}
				});
			}

			function locationClose(){

				// close slide-out
				$('.slide-out').removeClass('active');

				setTimeout(function(){
					// empty overlay
					$('.overlay').empty();
					// close overlay
					overlayClose();
				}, 250);

				// $('.overlay').removeClass('active');
				// reset hash and prevent scroll to top
				window.location.hash = '/';
			}

			function majorClose(){
				// close slide-out
				$('.slide-out').removeClass('active');

				setTimeout(function(){
					// empty overlay
					$('.overlay').empty();
					// close overlay
					overlayClose();
				}, 250);

				// $('.overlay').removeClass('active');
				// reset hash and prevent scroll to top
				window.location.hash = '/';
			}

			function staffClose(){
				// close slide-out
				$('.slide-out').removeClass('active');

				setTimeout(function(){
					// empty overlay
					$('.overlay').empty();
					// close overlay
					overlayClose();
				}, 250);

				// $('.overlay').removeClass('active');
				// reset hash and prevent scroll to top
				window.location.hash = '/';
			}

			$('.hotspot[data-slideout="true"]').click(function(){
				if($(document).width() > 992){
					// open location
					locationOpen( $(this).attr('id') );
				}
			});

			$('body').on('click', '.major-card-link', function(e){
				// open major
				majorOpen( $(this).attr('href') );
			});

			$('body').on('click', '.staff-card-link', function(e){
				// open major
				staffOpen( $(this).attr('href') );
			});

			if(window.location.hash){
				// if hash contains 'major'
				if (window.location.hash.indexOf('major') == 1){
					// open major
					majorOpen( window.location.hash );
				}

				// if hash contains 'staff'
				if (window.location.hash.indexOf('staff') == 1){
					// open staff
					staffOpen( window.location.hash );
				}
			}

			$(document).keyup(function(e) {
				// on press escape
				if (e.keyCode == 27) {
					// close slideouts
					majorClose();
					staffClose();
					locationClose();
				}
			});

			$('body').on('click','.close-btn',function(e){
				e.preventDefault();

				// close slideouts
				majorClose();
				staffClose();
				locationClose();
			});

			$('body').on('click','.bg-slide-out',function(){
				// close slideouts
				majorClose();
				staffClose();
				locationClose();
			});


		function initializePanoramas(){
		    $panoramas = $('.panzoom-pano');
		    $panoramas.each(function( index ) {
				$(this).panzoom({
					contain: 'invert',
					minScale: 0.5,
					maxScale: 1.5,
					increment: 0.25,
					startTransform: 'scale(0.75)',
					$zoomIn: $(this).parent().find('.zoom-in'),
					$zoomOut: $(this).parent().find('.zoom-out')
				});
			});
		}
		
		/*---------------------------------------
		| STORIES FILTER
		---------------------------------------*/
		(function($) {
        var firsttimestory = true; // param to check 
		   	// Filter Ajax Load More
		   	var alm_is_animating = false;
		   	
		   	// Hide empty posts message
		   	$('.empty-posts').hide();

		   	$('#alm-year-select').change(function(){
	   			var filter = $(this),
	   				selectedOption = $('#alm-year-select option').filter(':selected');

	   			if( filter.val !== selectedOption.text() && !alm_is_animating ) {
	   				alm_is_animating = true;  

	   				var data = selectedOption.data(), // Get data values from selected menu item
	             		transition = 'fade', // 'slide' | 'fade' | null
	             		speed = '300'; //in milliseconds
	         		$.fn.almFilter(transition, speed, data); // reset Ajax Load More (transition, speed, data)      
	   			}
		   	});

		   	$('#alm-category-select').change(function(){
	   			var filter = $(this),
	   				selectedOption = $('#alm-category-select option').filter(':selected');

	   			if( filter.val !== selectedOption.text() && !alm_is_animating ) {
	   				alm_is_animating = true;  

	   				var data = selectedOption.data(), // Get data values from selected menu item
	             		transition = 'fade', // 'slide' | 'fade' | null
	             		speed = '300'; //in milliseconds
	             
	         		$.fn.almFilter(transition, speed, data); // reset Ajax Load More (transition, speed, data)      
	   			}
         });
		   
		   	$.fn.almFilterComplete = function(){      
		   		$('.empty-posts').hide();
            alm_is_animating = false; // clear alm_is_animating flag
		   	};

		   	$.fn.almComplete = function(alm){
		   		$('.empty-posts').hide();
          alm_is_animating = false;
          // console.log('ALM complete');
          // console.log('firsttimestory: ', firsttimestory);

          if (firsttimestory) {
            // get query parameter and list of existing categories
            const queryString = window.location.search;
            const urlParams = new URLSearchParams(queryString);
            const cat_query = urlParams.get('category');
            const categories = $('#alm-category-select option').map(function() { return $(this).val(); }).get();
            // console.log(categories);

            // if exists, filter by category
            if (categories.includes(cat_query)){
              $('#alm-category-select')
              .val(cat_query)
              .trigger('change');
            }
            
            firsttimestory = false;
          }
			};

		   	$.fn.almEmpty = function(alm){
			    $('.empty-posts').show();
			    alm_is_animating = false;
      };
      
      // add message if no results found
      window.almEmpty = function(alm){
        var el = alm.listing;
        var msg = 'No results found.';
        
        var item = document.createElement('div');
        item.innerHTML = msg;
        item.classList.add("alert", "alert-info");
        item.style.marginLeft = "15px";
        item.style.marginRight = "15px";
        el.appendChild(item); // Append to ALM
        
        // console.log("Nothing found in this Ajax Load More query :(");
      };

		})(jQuery);
	

		/*
    |--------------------------------------------------------------------------
    | News Page
    |--------------------------------------------------------------------------
    */

    $('.carousel.tabbed-carousel').flickity({
	  	// options
	  	cellAlign: 'left',
	  	prevNextButtons: false,
			pageDots: false,
			autoPlay: false,
			draggable: false,
			freeScroll: false
		});

		// select cell on button click
		$('.tabbed-carousel-nav a').on( 'click', function(e) {
			e.preventDefault();

		  var index = $(this).index();
		  $('.carousel.tabbed-carousel').flickity( 'select', index );

		  //move active class
		  $('.tabbed-carousel-nav a').removeClass('active');
		  $('.tabbed-carousel-nav a').eq(index).addClass('active');
		});

		/*
    |--------------------------------------------------------------------------
    | Arrow position
    |--------------------------------------------------------------------------
    */

    //adjust so arrow point in centered to shield
    function getArrowOffset(){
    	var windowWidth = $( window ).width();

    	if (windowWidth < 544) {
    		offset = 0;
    	}else if(windowWidth <= 768){
    		offset = 3;
   		}else if(windowWidth <= 992){
    		offset = 8;
    	}else if(windowWidth <= 1200){
    		offset = 0;
    	}else if(windowWidth <= 1600){
    		offset = 4;
    	}else{
    		offset = 6;
    	}

    	return offset - 0; //subtract so registers as number
    }

    //get logo position and set it to as the left of arrow bg max width
    var offset = getArrowOffset();
    $logo = $('.footer-logo');
    if($logo.length){

    	var logo_pos = $logo.offset().left + offset;
    	$('.arrow-left').css('max-width', logo_pos);

    	$(window).resize(function(e){
	    	//get logo position and set it to as the left of arrow bg max width
	    	offset = getArrowOffset();
	    	logo_pos = $logo.offset().left + offset;
	    	$('.arrow-left').css('max-width', logo_pos);
	    });

    }
    
    /*
    |--------------------------------------------------------------------------
    | Events Calendar View 2 button functionality
    | Works with Select2 implementation
    |--------------------------------------------------------------------------
    */
    $('.btn-full-calendar').click(function(e){
      // if tribe_eventcategory doesn't exist (aka views V1), return
      if ($('[name="tribe_eventcategory[]"]').length === 0) {
        // Redirect if V2 but form isn't available
        if ($('.tribe-events-c-view-selector__list').length !== 0 ){
          window.location.replace('/events/');
        }
        return;
      }

      e.preventDefault();

      var target = $('[name="tribe_eventcategory[]"]');
      $(target).val('').trigger("change");
    });

    $('.btn-undergrad-admissions-calendar').click(function(e){
      // if tribe_eventcategory doesn't exist (aka views V1), return
      if ($('[name="tribe_eventcategory[]"]').length === 0) {

        // Redirect if V2 but form isn't available
        if ($('.tribe-events-c-view-selector__list').length !== 0 ){
          window.location.replace('/events/photo/?tribe_eventcategory%5B0%5D=5');
        }
        return;
      }

      e.preventDefault();

      var target = $('[name="tribe_eventcategory[]"]');
      $(target).val(5).trigger("change");
    });

    $('.btn-grad-admissions-calendar').click(function(e){
      // if tribe_eventcategory doesn't exist (aka views V1), return
      if ($('[name="tribe_eventcategory[]"]').length === 0) {
        // Redirect if V2 but form isn't available
        if ($('.tribe-events-c-view-selector__list').length !== 0 ){
          window.location.replace('/events/photo/?tribe_eventcategory%5B0%5D=54');
        }
        return;
      }

      e.preventDefault();

      var target = $('[name="tribe_eventcategory[]"]');
      $(target).val(54).trigger("change");
    });
    
     $('.btn-catalyst-calendar').click(function(e){
      // if tribe_eventcategory doesn't exist (aka views V1), return
      if ($('[name="tribe_eventcategory[]"]').length === 0) {
        // Redirect if V2 but form isn't available
        if ($('.tribe-events-c-view-selector__list').length !== 0 ){
          window.location.replace('/events/photo/?tribe_eventcategory%5B0%5D=105');
        }
        return;
      }

      e.preventDefault();

      var target = $('[name="tribe_eventcategory[]"]');
      $(target).val(105).trigger("change");
    });

	} );

} )( jQuery );
