//  Copyright 2016 Quantum Corporation. All rights reserved.
//
//  This script manages the versioning of help topics.
//  When a help version is chosen on any topic page, that choice is saved to local storage
//  When another topic is loaded, it ensures that the previously selected version is displayed

// Called when version selector control is changed.
// Holds the selected version.
// Changing it on any page updates the sessionStorage, which is checked on every other page load 
function setSelectedVersion() {

	// get version selector control
	var versionSelector = document.getElementById('version-select');
	sessionStorage.selectedVersion = versionSelector.selectedIndex;
 
	showHideVersion();
               
}

// Search all page elements and return those with a particular attribute
//     e.g. elements that are have different help versions
function getElementsWithAttribute(attr) {

	var elementsWithAttribute = [];
	var elements = document.body.getElementsByTagName('*');
	for (var i = 0; i < elements.length; i++)
	{
		if (elements[i].getAttribute(attr))
		{
			elementsWithAttribute.push(elements[i]);
		}
	}


	return elementsWithAttribute;

}

// Add ALL version conditional help to the current topic page
function addCustomOriginalDisplayAttribute () {

	var elements = document.body.getElementsByTagName('*');
	for (var i = 0; i < elements.length; i++)
	{
		elements[i].setAttribute('data-original-display-attribute-value', elements[i].style.display);
	}
 
}

// Update topic page for selected version
//    updates version selector control  
//    displays correct version of help
function showHideVersion() {
	// get version selector control		
	var versionSelector = document.getElementById('version-select');
               
	// initialize storage if necessary
	if (typeof sessionStorage.selectedVersion == 'undefined') {
		sessionStorage.selectedVersion = versionSelector.selectedIndex;
	}
               
	// set version selector control
	versionSelector.selectedIndex = sessionStorage.selectedVersion;
               
	// Show the correct help version
	var selectedVersion = versionSelector.options[sessionStorage.selectedVersion].value;
	var elements = getElementsWithAttribute('data-mc-conditions');
	for (var i = 0; i < elements.length; i++) {
		if (elements[i].getAttribute('data-mc-conditions').indexOf(selectedVersion) > -1 ) {
			if (elements[i].getAttribute('data-original-display-attribute-value') != '') {
				elements[i].style.display = elements[i].getAttribute('data-original-display-attribute-value')
			}
			else{
				elements[i].style.display = 'block';
			}
		}
		else {
			elements[i].style.display = 'none';
		}

	}
}

// When user displays a page, add custom help and display the correct version
window.onload = addCustomOriginalDisplayAttribute();
window.onload = showHideVersion();
