// ============================================================================================================
// IDS Webhelp scripting
// KdG Eluxis.com
// ============================================================================================================

/* *************************************** */
/* Global variables */
/* *************************************** */
var historie = new Array();
var historiecurrent = 0;
var currenthref="";

// ============================================================================================================
// Determine display mode: mobile or full desktop. Used to load large (wh_data.js) or small (wh_data_mobile.js) Priva search data 
// ============================================================================================================
/*
var mobile=true; //default is mobile
if (window.location.href.search(/device=full/) != -1) {//URL contains "device=full"
	mobile=false;
}
else { 
	if (window.location.href.search(/device=mobile/) == -1) {//URL does not contain "device=mobile"
		if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
			mobile=true;
		}else{
			mobile=false;
		}
	}
}
*/
// ============================================================================================================
function init(cover) {
	//Set current href to contentframe default
	if (cover) {
		currenthref = cover
		document.getElementById("contentframe").src = cover;
	}
	else {
		currenthref = document.getElementById("contentframe").src;
	}
	//Get navwrapper css style left to see if it is mobile or full
	var el = document.getElementById("navwrapper");
	if (getStyle(el, "bottom",true)==0) {
		toggleNav(true);  //Full: default show navwrapper with TOC 
	} else {
		toggleNav(false); //Mobile: default hide navwrapper with TOC 
	}

	//Set initial displays
	var el;
	el = document.getElementById("toccontainer");       if (el) toggleClass(el,'hidden','shown');
	el = document.getElementById("tocshowbar");         if (el) toggleClass(el,'shown','hidden');
	el = document.getElementById("a_toc");              if (el) addClass(el,'focus');
	el = document.getElementById("resultcontainer");    if (el) toggleClass(el,'shown','hidden'); 
}

// ============================================================================================================
function showmenu(show) {
	var el = document.getElementById("menuContainer");
	var classshow = !(hasClass(el,'shown'));
	if (show==true || show==false) {//show!=null
		if (show!=classshow) return; //quit because show already good
	}
	else {show = classshow;}
	if(show==true) {
		addClass(el,'shown');
	}
	else {
		removeClass(el,'shown');
	}
}

function printcontent() {
	//HTML page containing an iframe that contains content that spans more pages, all browsers only print the first page.
	//Solution is to print the iframe it self (styling is done with CSS @media print). 
	//It seems important to have the iframe tag closed with a </iframe> instead of an empty tag (is a known browser bug)
	//See https://graciesdad.wordpress.com/2007/04/19/all-in-one-printing-from-multiple-iframes/
	//Alternative for Chrome: window.frames[0].print() does not work in chrome (iframes are regarded as cross-domain in Chrome)
	showmenu(false);//Hide the expanded menu
	var isChrome = window.chrome;
	if (isChrome!= null && isChrome!=undefined && /Chrome/.test(navigator.userAgent) && window.navigator.vendor=="Google Inc.") {
		var node = getElementsByClassName(SelectedClass)
		var topicUrl = node[0].getElementsByTagName("a")[0]
		//Open topic in new tab to print it from there
		if (topicUrl) {
			var newWin = window.open(topicUrl,'_blank'); //Or open as popup	//var newWin = open(topicUrl,'_blank','height=300,width=600');
			newWin.focus();
		}
		else {alert('"Empty" Container topics cannot be printed')}
	}
	else {
		//All other browsers
		window.frames[0].focus();
		window.frames[0].print();
	}
}


// ============================================================================================================
// Slide Navigation panel
// ============================================================================================================
function toggleNav(show) {
	var el = document.getElementById("navwrapper");
	var doshow = true;
	var currentlyshown = false //default: if hidden or undefined -> show it
//console.log("|>>>>> "+hasClass(el,'navshown')+"|"+hasClass(el,'navhidden')+" | "+getStyle(el, "left"))
	if (hasClass(el,'navshown')) currentlyshown=true;
	if (hasClass(el,'navhidden')) currentlyshown=false;
	if (show==true || show==false) {//not null
//console.log("RETURN: "+currentlyshown+"-"+show+" -> "+doshow+" ,"+el.className)
		doshow=show;
	} else {
//console.log("3: "+currentlyshown+"-"+show+" -> "+doshow+" ,"+el.className)
		doshow= !(currentlyshown) //toggle view
	}

	if(doshow==false) {
//console.log("DOHIDE: "+currentlyshown+"-"+show+" -> "+doshow+" ,"+el.className)
		//Set contentwrapper
		el = document.getElementById("contentwrapper");
		toggleClass(el,'navshown','navhidden');
		//Hide navwrapper
		el = document.getElementById("navwrapper");
		toggleClass(el,'navshown','navhidden');
		//Hide navclickunderlay
		el = document.getElementById("navclickunderlay");
		toggleClass(el,'navshown','navhidden');
		//Show tocshowbar
		el = document.getElementById("tocshowbar");
		toggleClass(el,'hidden','shown');		
		//swith off highlight selected icon
		el = document.getElementById("a_toc");   if (el) removeClass(el,'focus');
		el = document.getElementById("a_search");if (el) removeClass(el,'focus');
	}
	else {
//console.log("DOSHOW: "+currentlyshown+"-"+show+" -> "+doshow+" ,"+el.className)
		//Set contentwrapper
		el = document.getElementById("contentwrapper");
		toggleClass(el,'navhidden','navshown');
		//Show navwrapper
		el = document.getElementById("navwrapper");
		toggleClass(el,'navhidden','navshown');
		//Show navclickunderlay
		el = document.getElementById("navclickunderlay");
		toggleClass(el,'navhidden','navshown');
		//Show tocshowbar
		el = document.getElementById("tocshowbar");
		toggleClass(el,'shown','hidden');
	}
	showmenu(false);//Hide the expanded menu
}

// ============================================================================================================
// WebHelp Display functions
// IDS webhelp for mobile and desctop show screen handling
// ============================================================================================================
function showToc() {
	//Select the currently displayed content topic in the Toc
	var tocroot = document.getElementById("toccontainer");
	var target;
	try {
		//Dit werkt voor Chrome alleen in een server configuratie (niet op een locale schijf)
		//Voor FF, IE en Edge werkt dit op server en lokaal
		target = window.parent.mainframe.location.href
		target = target.split('#')[0] //url without hash		
	}
	catch(e) {
		//Fall back for Chrome on local drive. Dit is de intern bewaarde laatste locatie. 
		//(Klikken op referenties binnen het iframe kan hierin niet meegenomen worden.)
		var target = currenthref.split('#')[0] //url without hash
	}
	if (target && tocroot) {expandToItemURL(target,tocroot);}
	//Display the TOC, hide the rest
	var el;
	el = document.getElementById("a_toc");    if (el) addClass(el,'focus');
	el = document.getElementById("toccontainer"); if (el) toggleClass(el,'hidden','shown');
	el = document.getElementById("tocshowbar"); if (el) toggleClass(el,'shown','hidden');
	el = document.getElementById("resultcontainer"); 
	if (el) {
		var resultcontainershown = !(hasClass(el,'shown'));
		toggleClass(el,'shown','hidden');	
	}

	//highlight selected icon
	el = document.getElementById("a_toc");    if (el) addClass(el,'focus');
	el = document.getElementById("a_search"); if (el) removeClass(el,'focus');

	//Toggle the navwrapper
	el = document.getElementById("navwrapper");
	var navhidden = !(hasClass(el,'navshown'));
	if (resultcontainershown==true || navhidden) toggleNav();

	showmenu(false);//Hide the expanded menu
}

function showSearchResult() {
	//Display the search result, hide the rest
	var el;
	el = document.getElementById("toccontainer"); if (el) toggleClass(el,'shown','hidden');
	el = document.getElementById("tocshowbar");	if (el) toggleClass(el,'hidden','shown');
	el = document.getElementById("resultcontainer");	if (el) toggleClass(el,'hidden','shown');

	//highlight selected icon
	el = document.getElementById("a_toc");    if (el) removeClass(el,'focus');
	el = document.getElementById("a_search"); if (el) addClass(el,'focus');

	toggleNav(true);//Show the navwrapper
	showmenu(false);//Hide the expanded menu
}

function showContent(node) {
	//Add to history
	//get selected url (note: this because in Chrome iframes (regarded cross-domain) following does not work: currenthref = window.mainframe.location.href;
	if (node.nodeName=='A' || node.nodeName=='a')
		//a href clicked (in search result)
		currenthref=node.href;
	else {	
		//div clicked in TOC
		currenthref = node.getElementsByTagName("a")[0].href
	}

	if (currenthref != historie[historiecurrent]) {
		//add the current
		historie.push(currenthref)
		if (historie.length > 20) {historie = historie.slice(historie.length-20)}
		historiecurrent = historie.length-1;
	}
	//set view to top of page
	document.body.scrollTop = 0;document.documentElement.scrollTop = 0;
	showmenu(false);//Hide the expanded menu
}

function showInfo() {
	//Display the metadata info of this WebHelp
	var el;
	el = document.getElementById("toccontainer"); if (el) toggleClass(el,'shown','hidden');
	el = document.getElementById("tocshowbar");	if (el) toggleClass(el,'hidden','shown');
	el = document.getElementById("resultcontainer");
	var inftxt = info;
	if (el) {
		toggleClass(el,'hidden','shown');
		if (searchhelp!="") {
			inftxt += "<div class='searchhelp'>" + searchhelp + "</div>"
		}
		el.innerHTML = '<div class="metainfo">'+inftxt+'</div>';
	}
	//swith off highlight selected icon
	el = document.getElementById("a_toc");   if (el) removeClass(el,'focus');
	el = document.getElementById("a_search"); if (el) removeClass(el,'focus');

	toggleNav(true);//Show the navwrapper
	showmenu(false);//Hide the expanded menu
}

function dohistory(dir) {
	//Select current in the history to one back or forward 
	if (historiecurrent == historie.length-1) {
		if (window.mainframe.location.href != historie[historiecurrent]) {
			//add the current
			historie.push(window.mainframe.location.href)
			if (historie.length > 20) {historie = historie.slice(historie.length-20)}
			historiecurrent = historie.length-1;
		}
	}
	if (dir==1) {
		if (historiecurrent < historie.length-1) {
			historiecurrent ++
			window.mainframe.location.href = historie[historiecurrent]
			showContent(true); 
			var tocroot = document.getElementById("toccontainer");
			if(tocroot == null){alert("Error: elementId toccontainer not found");return false}
			else {expandToItemURL(historie[historiecurrent],tocroot);}
		}
	}
	else {
		if (historiecurrent > 0) { 
			historiecurrent --
			window.mainframe.location.href = historie[historiecurrent]
			showContent(true); 
			var tocroot = document.getElementById("toccontainer");
			if(tocroot == null){alert("Error: elementId toccontainer not found");return false}
			else {expandToItemURL(historie[historiecurrent],tocroot);}
		}
	}
//Show historie
//var msg = historie.length+" items\n\n"
//for (i=0; i<historie.length; i++) {hlp = historie[i].split("/"); msg+= i+"  "+hlp[hlp.length - 1]+"\n"}
//alert(msg+"\n------------\nCurrent:"+historiecurrent+":\n"+historie[historiecurrent])
}

// ============================================================================================================
// DHTML expandable tree
// KdG Eluxis.com
// Tested on IE8,9,10,11 FF16, Chrome, Safari
// Tree structure is a normal unordered html list.
// The output is controlled by the CSS classes.
// ============================================================================================================
var OpenClass= "liOpen";
var ClosedClass="liClosed";
var SelectedClass = "selected"

/* **************************************** */
/* Show clicked topic or expand/collapse    */
/* **************************************** */
function toggleView(node) {
	localStorage.setItem('searchstring', '');//Clear search terms in local storage (no searchterm highlighting when a topic is clicked from the TOC)

	var tocroot = document.getElementById("toccontainer");
	if(tocroot == null){alert("Error: elementId toccontainer not found");return false}
	var item = node.parentNode
	if (hasClass(item,"liBullet")) {
		//Display the content
		resetSelected(tocroot);
		addClass(node,SelectedClass);
		showContent(node); 
		//Get navwrapper css style left to see if it is mobile or full
		var el = document.getElementById("navwrapper");
		if (getStyle(el, "bottom",true)!=0) {
			toggleNav(false); //Mobile: default hide navwrapper with TOC 
		}
	}
	else {//Expand or collapse
		var togglecontainer = $(item).children("ul:first")
		if (hasClass(item,OpenClass)) {
			var ahref = node.getElementsByTagName("a")[0]
			if (ahref) {
				showContent(node); 
			}
			togglecontainer.slideUp(function() {toggleClass(item,OpenClass,ClosedClass);})
		}
		else {
			togglecontainer.slideDown(function(){if (hasClass(item,ClosedClass)){toggleClass(item,ClosedClass,OpenClass)};})
			//Reset collapse All as default
			el = document.getElementById("TOCexpandcollapseAll"); if (el) {el.className = 'TOCcollapseAll'; el.title='Collapse All';}
		}
		resetSelected(tocroot);
		addClass(node,SelectedClass);
	}
	return true;
}

function resetSelected(tocroot) {
	if(tocroot == null){alert("Error: elementId tocroot not found2");return false}
	var els = tocroot.getElementsByTagName("*");
	var node;
	var re = new RegExp('(\\s|^)'+SelectedClass+'(\\s|$)')
	for(var i=0; i<els.length; i++) {
		node=els[i]
		if (node.className.match(re)) {
			removeClass(els[i],SelectedClass);
		}
	}
}

function Initial_expand_check() {
/* **************************************** */
/*Find target topic that is the default first page
  Expand the tree with the topic found in the main frame
  This is relevant for when the file is opened (e.g. through asp) with another than the first topic in the main frame*/
/* **************************************** */
	var target = ""
	var found = false;
	var tocroot = document.getElementById("toccontainer");
	if(tocroot == null){alert("Error: elementId toccontainer not found");return false}

	try {
		//Check URL for ?target=
		var url = window.location; 
		var str = url.toString(); 
		str = str.replace(/#top/,"");//remove #top hash
		var p1 = str.indexOf("?target="); 
		if (p1!=-1) {
			p2 =str.indexOf("&",p1+1); 
			if (p2==-1) {target=str.substring(p1+8)} else {target=str.substring(p1+8,p2)}
			if (target.indexOf(".htm")==-1) {target=target+".htm"}
			found = expandToItemURL(target,tocroot)
		}	
		if (found==false) {//Check for notoc entries
			var notocs=document.getElementsByTagName("var")
			for (i=0; i<notocs.length; i++) {
				if (target.search(notocs.item(i).title)!=-1) {
					target=notocs.item(i).title
					found=true;
					break;
				}
			}
		}
		if (found==false) {//Take first entry in toc
			var ahrefs = tocroot.getElementsByTagName("a")
			target = ahrefs[0].href;
			found = expandToItemURL(target,tocroot)
		}
		if (found==false) {//Check for default main href (set in index.htm
			target = window.parent.mainframe.location.href;
			if (target.indexOf(".htm")==-1) {target += ".htm";}
			found = expandToItemURL(target,tocroot)
		}
	}
	catch(e) {//if target file does not exist, or somethong else goes wrong (404)
	}
	if (found) {
		document.getElementById("contentframe").src= target;
		document.getElementById("contentframe").location=target; //refresh page
	}
}


/* **************************************** */
/* Expand/collapse All                      */
/* **************************************** */
function expandcollapseAll() {
	var tocroot = document.getElementById("toccontainer");
	var uls = tocroot.getElementsByTagName("ul")
	var lis = tocroot.getElementsByTagName("li")
	el = document.getElementById("TOCexpandcollapseAll");
	var collapseAll = false; //Start with default 
	if (el.className=='TOCcollapseAll'){
		collapseAll = true; 
	}
	var i
	if (collapseAll==false) {
		for(i=1;i<uls.length;i++){uls.item(i).style.display="block";}
		for(i=0;i<lis.length;i++){toggleClass(lis.item(i),ClosedClass,OpenClass);}
		collapseAll = true
		el = document.getElementById("TOCexpandcollapseAll"); if (el) {el.className = 'TOCcollapseAll'; el.title='Collapse All';}
	}
	else {
		for(i=1;i<uls.length;i++){uls.item(i).style.display="none";}
		for(i=0;i<lis.length;i++){toggleClass(lis.item(i),OpenClass,ClosedClass);}
		collapseAll = false
		el = document.getElementById("TOCexpandcollapseAll"); if (el) {el.className = 'TOCexpandAll'; el.title='Expand All';};
	}
}

/* **************************************** */
/* Expand TOC to the displayed target topic */
/* **************************************** */
function expandToItemURL(findURL,tocroot){
	if (findURL=="") return;
	//Remove the tailing slash / that is automatically added to the end of a URL by some browsers (not IE)
	findURL = findURL.replace(/\/$/,"");
	var a = document.createElement('a');
	a.href = findURL;
	findURL = a.href;
//alert("expandToItemURL\n"+	findURL +"\n"+ a.href);
	resetSelected(tocroot);
	var ahrefs = tocroot.getElementsByTagName("a")
	var item,itemURL
	var found=false;
	for(var i=0;i<ahrefs.length;i++){//find all occurences
		item = ahrefs.item(i);
		itemURL = item.href
		itemURL = itemURL.replace(/\/$/,"");//Remove tailing slash /
		if (findURL.toLowerCase() == itemURL.toLowerCase()) {
			found=true;
//			if (i==0) break; //if it is the first topic then quit;
			//expand Parents
			var p = item.parentNode;
			addClass(p,SelectedClass);
			while (p && p!=tocroot) {
				if (p.tagName) {
					if (hasClass(p,ClosedClass)) {
						toggleClass(p,ClosedClass,OpenClass);
					}
					if (p.style.display=="none") p.style.display="block"
				}
				p = p.parentNode;
			}
			//set focus to next item,if possible), to move somewhat further
			//Note: does not work for IE which in overflow frame webHelp column width. IE shifts lines to left (icons dissapear)
			if (navigator.userAgent.search(/MSIE[ ]/i)==-1 && navigator.userAgent.search(/EIE10/i)==-1) {	
				if (i+1 < ahrefs.length) {ahrefs.item(i+1).focus()}
				item.focus();//then move focus back to founditem
			}
		}
	}
	return found;
}


// ============================================================================================================
// Class Helper functions
// ============================================================================================================
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function toggleClass(ele,fromClas, toClas) {
	removeClass(ele,fromClas)
	addClass(ele,toClas)
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
 
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls);
		var c = ele.className
		c = c.replace(reg,'');
		c=c.replace(/(^\s+)|\s+$/g,"");//strip spaces
		ele.className=c;
	}
}

function getElementsByClassName(classname, node) {
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
		if(re.test(els[i].className))a.push(els[i]);
	return a;
}

function getStyle(ele, cssStr, omitunit){
	var computedStyle = "";
	if(ele.currentStyle){//IE
		//cssStr = cssStr.replace(/\-(\w)/g, function (strMatch, p1){return p1.toUpperCase();});
		computedStyle = ele.currentStyle[cssStr];
	}
	else {//Other browsers
		computedStyle = document.defaultView.getComputedStyle(ele, "").getPropertyValue(cssStr);
	}
	if (omitunit) computedStyle = computedStyle.replace(/[A-Za-z]/g,'');
	return computedStyle;;
}
