//
//	Support for dynamic components
//
//	Copyright (c) 2016-2024 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA
//

right_toc_elts = null;

$(document).ready(function() {
	
	// Check to see if the window is top if not then display button
	$(window).scroll(function(){
		if ($(this).scrollTop() > 100) {
			$('.scrollToTop').fadeIn();
		} else {
			$('.scrollToTop').fadeOut();
		}
	});

	function scrollToTop() {
		$('html, body').animate({ scrollTop: 0 }, 600);
		return false;
	}
	
	// Click event to scroll to top
	$('.scrollToTop').click(scrollToTop);

	// PHDCC TOC and Index
	var tocVisible = window.innerWidth > 900 ? false : true;
	var indexVisible = window.innerWidth > 900 ? false : true;

	function toggleTOC(scroll) {
	    if (typeof scroll !== 'boolean') { scroll = true; }
	    if (tocVisible) {
	        $('.tocindex').hide();
	        $('.tocindex').removeClass('col-sm-3');
	        $('.nottocindex').removeClass('col-sm-9');
	        $('.nottocindex').addClass('col-sm-12');
	        $('.breadcrumb-sag').removeClass('breadcrumb-sag-toc');
	        tocVisible = false;
	        indexVisible = false;
	    } else {
	        $('.tocindex').show();
	        $('.tocindex').addClass('col-sm-3');
	        $('.nottocindex').addClass('col-sm-9');
	        $('.nottocindex').removeClass('col-sm-12');
	        $('.breadcrumb-sag').addClass('breadcrumb-sag-toc');
	        // $(".sidebar-index").hide();
	        $(".sidebar-nav").show();
	        tocVisible = true;
	        indexVisible = false;
	        if (scroll) {
	            scrollToTop();
	        }
	    }
	    // try {
	    //     if (localStorage) {
	    //         localStorage.tocVisible = tocVisible ? "1" : "0";
	    //         localStorage.indexVisible = indexVisible ? "1" : "0";
				
	    //     }
	    // } catch (ex) { }
	    return false;
	}
	function toggleIndex(scroll) {
	    if (typeof scroll === 'undefined') { scroll = true; }
		if (indexVisible) {
			// $('.tocindex').hide();
			// $('.tocindex').removeClass('col-sm-3');
			// $('.nottocindex').removeClass('col-sm-9');
			// $('.nottocindex').addClass('col-sm-12');
			// $('.breadcrumb-sag').removeClass('breadcrumb-sag-toc');
			tocVisible = false;
			indexVisible = false;
		} else {
			$('.tocindex').show();
			$('.tocindex').addClass('col-sm-3');
			$('.nottocindex').addClass('col-sm-9');
			$('.nottocindex').removeClass('col-sm-12');
			$('.breadcrumb-sag').addClass('breadcrumb-sag-toc');
			// $(".sidebar-index").show();
			$(".sidebar-nav").hide();
			tocVisible = false;
			indexVisible = true;
			if (scroll) {
			    scrollToTop();
			}
		}
	//   try {
	//     if (localStorage) {
	//       localStorage.tocVisible = tocVisible ? "1" : "0";
	//       localStorage.indexVisible = indexVisible ? "1" : "0";
	//     }
	//   } catch (ex) { }
		return false;
	}

	$('#toc').click(toggleTOC);

	$('#toc').click(() => { $('body').toggleClass('toc-collapsed') });

	$('#atoz').click(toggleIndex);

	if(window.innerWidth < 900){
		$('body').addClass('toc-collapsed');
	}
	toggleTOC(false);

	// var divIndex = "<div class='sidebar-index'><input type='text' id='index-filter' placeholder='search index' /><br /><select id='index-list'></select></div>";
	var divTOC = "<div class='sidebar-nav'><div id='toc-top'></div><div class='navbar navbar-default navbar-toc' role='navigation'><div class='navbar-header'>";
	divTOC += "<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.sidebar-navbar-collapse'>";
	divTOC += "<span class='sr-only'>Toggle navigation</span><span class='icon-bar'></span><span class='icon-bar'></span><span class='icon-bar'></span></button>";
	divTOC += "<span class='visible-xs navbar-brand'>Contents menu</span></div>";
	divTOC += "<div class='navbar-collapse collapse sidebar-navbar-collapse'><ul class='nav xnavbar-nav navbar-toc-tree' id='fishiTree'></ul></div></div></div>";
	$('.tocindex').html(divTOC);

	var fishiLogging = true;
	fishi.config.baseurl = docroot+"navig/";
	fishi_page.config.idTree = "#fishiTree";
	fishi_page.config.idIndexList = "#index-list";
	fishi_page.config.idIndexFilter = "#index-filter";

	$('#helpindex-version').text(fishi.version);
	$('#helpindex-date').text(fishi.versionDate.toLocaleDateString());

	// PHDCC Search
	var fisLogging = true;
	//var fisFreezeDb = true;

	findinsite.config.rules = findinsite_rules_english;
	findinsite.config.baseurl = docroot + "fts/";
	findinsite_page.config.idSearch = "search";
	findinsite_page.config.idResults = "results";
	findinsite_page.config.idSearchForm = "search-subsets";
	findinsite_page.config.highlight = "?hi=";
	findinsite_page.config.startSearch = function () {
		$('#searchModal').modal();
	};
	findinsite_page.config.target = "_blank";

	$('#findinsite-version').text(findinsite.version);
	$('#findinsite-date').text(findinsite.versionDate.toLocaleDateString());

	// Do querystring search once DOM is loaded so we can store the results
	function loadPageVar(sVar) {
		return window.location.search.replace(new RegExp("^(?:.*[&\\?]" +
		encodeURIComponent(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1");
	};

	var querySearch = loadPageVar('search');
	if (querySearch && (querySearch.trim().length > 0)) {
		querySearch = decodeURIComponent(querySearch.replace(/\+/g, ' '));
		findinsite_page.search(querySearch);
	}

	// Do search word highlighting
	var hi = loadPageVar('hi');
	if (hi) {
		$("body").mark(hi.split('+'), {
		  accuracy: {
		    "value": "exactly",
		    "limiters": [",", ".","_"]
		  }
		});
	}

	// toggleTOC(false);
  // See if TOC or Index needs to be open
	//   try {
	//       if (localStorage) {
	//           if (localStorage.tocVisible === "1") {
	//               toggleTOC(false);
	//           } else if (localStorage.tocVisible !== "0") {
	//               toggleTOC(false);
	//           }
	//           if (localStorage.indexVisible === "1") {
	//               toggleIndex(false);
	//           }
	//       }
	//   } catch (ex) {
	//     //console.log("localStorage failed");
	//   }
	setTimeout(() => {
		$('.fishi-dd a b').each((pos,elt) => {
			elt.addEventListener('click',(event) => {
				const arrowElt = $(event.target);
				const parent = arrowElt.closest('.fishi-dd');
				if(parent.length){
					parent[0].classList.toggle('expanded');
				}
			});
		});

		const activeElt = $('.fishi-active');
		if(activeElt){
			activeElt.parents('.fishi-dd').each((pos,elt) => {
				elt.classList.add('expanded');
			})
		    activeElt[0].scrollIntoView({
			behavior: 'auto',
			block: 'start',
			inline: 'nearest'
		    });
		}
	},50);

	// function to change hashchange
	function updateTocHandler(){
		const currentHash = window.location.hash;
		const tocEltSelector = `div.right-tocindex a[href="${currentHash}"]`;
		const tocElt = $(tocEltSelector);

		if(tocElt.length){
			$('.right-tocindex li.active').each((pos,elt) => {
				elt.classList.remove('active')
			});

			$(tocElt[0]).parent('li').addClass('active');
		}
	}

	// function to update the hash on scroll
	function updateHash_scrollHandler(){
		let activeTocHash = null;

		if(right_toc_elts == null){
			right_toc_elts = $('.right-tocindex a');
		}

		right_toc_elts.each((pos,elt) => {
			const hash = elt.getAttribute('href');
			const hashName = hash.split('#')[1];
			const headerSelector = `[name="${hashName}"]`;
			const headerElt = document.querySelector(headerSelector);
			
			if(headerElt){
				const topVal = headerElt.getBoundingClientRect().top;
				const ACTIVE_TOC_THRESHOLD = 200;

				if(topVal <= ACTIVE_TOC_THRESHOLD){
					activeTocHash = hash;
				}
			}
		});

		if(activeTocHash){
			history.replaceState(null,null,activeTocHash);
			updateTocHandler();
		}
	}

	function righttocToggleHandler(){
		const bodyElt = document.querySelector('body');
		if(bodyElt){
			bodyElt.classList.toggle('righttoc-collapse');
		}
	}

	window.addEventListener('hashchange',updateTocHandler);
	document.querySelector('div.nottocindex').addEventListener("scroll",updateHash_scrollHandler);
	document.getElementById('right-tocindex-toggle').addEventListener("click",righttocToggleHandler)
});

function rotate_arrow(){
	console.log('rotate_arrow called');
}

function nav_search() {
	var search = $('#search').val();
	$('#search2').val(search);
	return findinsite_page.search();
}

function nav_search_keypress(event) {
	if (event.which === 13 || event.keyCode === 13) {

		let results = $('.modal-content');
		if(results){
			results[0].scrollTo({top: 0});
		}
		
		return nav_search();
	}
	return true;
}

function nav_search_modal() {
	var search = $('#search2').val();
	$('#search').val(search);
	return findinsite_page.search();
}

function nav_search_modal_keypress(event) {
	if (event.which === 13 || event.keyCode === 13) {
		var search = $('#search2').val();
		$('#search').val(search);

		let results = $('.modal-content');
		if(results){
			results[0].scrollTo({top: 0});
		}
		
		return findinsite_page.search();
	}
	return true;
}
