document.addEventListener('DOMContentLoaded', addCollapsibleOnClick(), false);
document.addEventListener('DOMContentLoaded', applyExpandSettings(), false);

function addCollapsibleOnClick() {
	var coll = document.getElementsByClassName("collapsible");
	var i;
	for (i = 0; i < coll.length; i++) {
		var collapsibleLink = coll[i].querySelector('.collapsibleLink'); 
		if (collapsibleLink === null){
			collapseNextElementOnClick(coll[i]);	
		} else {
			expandableNextOuterElementOnClick(collapsibleLink);	
		}
		
	}
}

function expandableNextOuterElementOnClick(element){
	element.addEventListener("click", function() {
		this.parentElement.classList.toggle("expanded");
		this.parentElement.classList.toggle("collapsed");
		var content = this.parentElement.nextElementSibling;
		if (content.style.display === "block") {
			content.style.display = "none";
		} else {
			content.style.display = "block";
		}
	});
}

function collapseNextElementOnClick(element){
	element.addEventListener("click", function() {
		this.classList.toggle("active");
		var content = this.nextElementSibling;
		if (content.style.display === "block") {
			content.style.display = "none";
		} else {
			content.style.display = "block";
		}
	});
}

function applyExpandSettings() {
	if (localStorage.getItem('switchExpand') === true || localStorage.getItem('switchExpand') === 'true') {
		var expandSwitchCB = document.getElementById("expandCB");
		if ( expandSwitchCB != null ){
			expandSwitchCB.checked = true;	
		}
		var expandSwitchSettingsCB = document.getElementById("expandSettingsCB");
		if ( expandSwitchSettingsCB != null ){
			expandSwitchSettingsCB.checked = true;	
		}
		$('.autoExpand').show();
		showDocumentCollapseButton();
	} else {
		$('.autoExpand').hide();
		showDocumentExpandButton();
	}
}

function switchExpand() {
	var checkBox = document.getElementById("expandCB");
	if (checkBox.checked == true) {
		$('.autoExpand').show();
		showDocumentCollapseButton();
	} else {
		$('.autoExpand').hide();
		showDocumentExpandButton();
	}
}
function showDocumentCollapseButton(){
	var collapseTextControl = document.querySelector('#collapseTextControl');
	collapseTextControl.style.display = "inline";
	var expandTextControl = document.querySelector('#expandTextControl');
	expandTextControl.style.display = "none";
}

function showDocumentExpandButton(){
	var collapseTextControl = document.querySelector('#collapseTextControl');
	collapseTextControl.style.display = "none";
	var expandTextControl = document.querySelector('#expandTextControl');
	expandTextControl.style.display = "inline";
}

function switchExpandSettings() {
	var checkBox = document.getElementById("expandSettingsCB");
	if (checkBox.checked == true) {
		localStorage.setItem('switchExpand', true);
	} else {
		localStorage.setItem('switchExpand', false);
	}
}
