/************************Cache Memory Management*********************************/

function cacheAndLoadImageWithID(imageId, imagePath) {
            const imageElement = document.getElementById(imageId);
            if (!imageElement) {
                console.error(`Element with id ${imageId} not found`);
                return;
            }
            // Check if the image is in localStorage
            if (localStorage.getItem(imagePath)) {
                // Use the cached image
                imageElement.src = localStorage.getItem(imagePath);
            } else {
                // Load the image and cache it
                fetch(imagePath)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onloadend = () => {
                            const base64data = reader.result;
                            localStorage.setItem(imagePath, base64data);
                            imageElement.src = base64data;
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => {
                        console.error('Error loading image:', error);
      });
   }
}


/*This function just put the new image into the local storage of the browser*/

/*
function cacheImage(imagePath) {
    // Check if the image is already in localStorage
    if (localStorage.getItem(imagePath)) {
        return;
    }

    // Load the image and cache it
    fetch(imagePath)
        .then(response => response.blob())
        .then(blob => {
            const reader = new FileReader();
            reader.onloadend = () => {
                const base64data = reader.result;
                localStorage.setItem(imagePath, base64data);
                console.log(`Image cached: ${imagePath}`);
            };
            reader.readAsDataURL(blob);
        })
        .catch(error => {
            console.error('Error loading image:', error);
        });
}
*/



function getKeyByValue(searchValue) {
    const keys = [
        "submenubutton.gif",
        "submenubutton_hl.gif",
        "buttonreload.gif",
        "buttonreload_hl.gif",
        "buttonactivate.gif",
        "buttonactivate_hl.gif",
        "submenuback.gif",
        "submenuback_hl.gif"
    ];

    for (let key of keys) {
        let value = localStorage.getItem(key);
        if (value === searchValue) {
            return key;
        }
    }

    return null; // If the value is not found
}


function cacheAndLoadImageWithElement(imageElement, imagePath) {

            if (!imageElement) {
                console.error(`Element with id ${imageId} not found`);
                return;
            }
            // Check if the image is in localStorage
            if (localStorage.getItem(imagePath)) {
                // Use the cached image
                imageElement.src = localStorage.getItem(imagePath);
            } else {
                // Load the image and cache it
                fetch(imagePath)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onloadend = () => {
                            const base64data = reader.result;
                            localStorage.setItem(imagePath, base64data);
                            imageElement.src = base64data;
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => {
                        console.error('Error loading image:', error);
      });
   }
}


/********************************************************************************/

var ClickedButton = "";

var MenuButton = new Image();
//MenuButton.src = "menubutton.gif";
var MenuButton_hl = new Image();
//MenuButton_hl.src = "menubutton_hl.gif";

var SubMenuButton = new Image();
//SubMenuButton.src = "submenubutton.gif";
var SubMenuButton_hl = new Image();
//SubMenuButton_hl.src = "submenubutton_hl.gif";

var SubMenuBack = new Image();
//SubMenuBack.src = "submenuback.gif";
var SubMenuBack_hl = new Image();
//SubMenuBack_hl.src = "submenuback_hl.gif";

var ButtonReload = new Image();
//ButtonReload.src = "buttonreload.gif";
var ButtonReload_hl = new Image();
//ButtonReload_hl.src = "buttonreload_hl.gif";

var ButtonActivate = new Image();
//ButtonActivate.src = "buttonactivate.gif";
var ButtonActivate_hl = new Image();
//ButtonActivate_hl.src = "buttonactivate_hl.gif";

var Job_Run = new Image();
//Job_Run.src =  "labels_anim.gif";

var Job_Stop = new Image();
//Job_Stop.src = "labels.gif");


cacheAndLoadImageWithElement(MenuButton,"menubutton.gif");
cacheAndLoadImageWithElement(MenuButton_hl,"menubutton_hl.gif");
cacheAndLoadImageWithElement(Job_Run, "labels_anim.gif");
cacheAndLoadImageWithElement(Job_Stop, "labels.gif");

cacheAndLoadImageWithElement(SubMenuButton,"submenubutton.gif");
cacheAndLoadImageWithElement(SubMenuButton_hl,"submenubutton_hl.gif");
cacheAndLoadImageWithElement(ButtonReload,"buttonreload.gif");
cacheAndLoadImageWithElement(ButtonReload_hl,"buttonreload_hl.gif");
cacheAndLoadImageWithElement(ButtonActivate,"buttonactivate.gif");
cacheAndLoadImageWithElement(ButtonActivate_hl,"buttonactivate_hl.gif");
cacheAndLoadImageWithElement(SubMenuBack,"submenuback.gif");
cacheAndLoadImageWithElement(SubMenuBack_hl,"submenuback_hl.gif");



function TeaseButton(ButtonNr, ButtonObj) {

var imageElement = window.document.images[ButtonNr];

let key = getKeyByValue(ButtonObj.src);

if (key !== null) {
   imageElement.src = localStorage.getItem(key);
} else {
   cacheAndLoadImageWithElement(imageElement, ButtonObj.src);
}

//window.document.images[ButtonNr].src = ButtonObj.src;
	//ParValue=ButtonNr;
}

function ChangeTwoFrames(URL1, URL2) {
	parent.Menu.location.href = URL1;
	parent.Main.location.href = URL2;
}

function SendForm(MenuItemID, MenuItemName, MenuName) {
	var Menu = this.SubMenuList[MenuName.length > 0 ? MenuName : "Main Menu"];
	var i;

	if (typeof Menu !== "undefined") {
		for (i = 0; i < Menu.length; i++) {
			Menu[i].setActMenuItem(MenuItemName);
		}
	}

	document.Formular.MenuName.value = MenuItemName;
	document.Formular.MenuID.value = MenuItemID;
	document.Formular.submit();
}

function ChangeFrameAndSend(MenuItemID, MenuItemName, MenuName, URL1) {
	var SubPages = this.SubMenuList[MenuItemName];
	var SubPage;

	// console.log("MenuItemName = " + MenuItemName + " (menu item to be selected)\nURL1 = " + URL1 + " (html menu page to be shown)");

	// Backbutton gedrückt?
	if (MenuName === null) {
		// eine Menüebene höher gehen
		SubPages = this.SubMenuList[SubPages[0].Parent];
	}

	// Menueinträge gefunden?
	if (typeof SubPages !== "undefined") {
		// den aktuellen Menüeintrag vom erstbesten holen
		// SubPage = SubPages[0].ActMenuItem;

		// Obiges Verhalten ist smart aber verwirrend bei der Bedienung, denn es führt
		// dazu, daß beim Betreten eines Untermenüs zunächst das zuletzt in diesem Menü
		// angezeigte Item/Untermenü angezeigt wird und nicht die Inhalte des aktuell
		// angeklickten Untermenüs selbst. Diese erscheinen erst, wenn man mittels des
		// Backbuttons das Menü wieder verlässt. So, wie es jetzt ist, wird immer zuerst
		// der Inhalt des angeklickten Knotens angezeigt. Will man darunterliegende Knoten
		// öffnen/anzeigen, dann muß man diese explizit anklicken. Am Verhalten des
		// Backbuttons ändert sich nichts.
		SubPage = MenuItemName;
		// console.log("SubPage = " + SubPage + " (after having scanned all sub pages)");
	} else {
		SubPage = MenuItemName;
		// console.log("SubPage = " + SubPage + " (using MenuItemName since no sub pages are defined)");
	}

	// Nicht Backbutton gedrückt?
	if (MenuName) {
		var Menu = this.SubMenuList[MenuName.length > 0 ? MenuName : "Main Menu"];

		if (typeof Menu !== "undefined") {
			var i;
			for (i = 0; i < Menu.length; i++) {
				Menu[i].setActMenuItem(MenuItemName);
			}
		}
	}

	document.Formular.MenuName.value = SubPage;
	document.Formular.MenuID.value = MenuItemID;
	parent.Menu.location.assign(URL1);
	document.Formular.submit();
}

function ToggleNode(MenuName, NodeIndex) {
	var Menu = this.SubMenuList[MenuName];
	var Node = Menu[NodeIndex];
	var SubPage;
	var i;

	// console.log("Menu = " + MenuName + " (menu to be selected)\nNodeIndex = " + NodeIndex + " (index of menu item to be selected)");

	if (typeof Node !== "undefined") {
		// console.log("ToggleNode: toggling node " + Node.MenuName + ", old status = " + Node.isExpanded());
		Node.toggle();
		// console.log("ToggleNode: new status = " + Node.isExpanded());
		// window.location.reload();
	}

	SubPage = Node.MenuItemName;

	for (i = 0; i < Menu.length; i++) {
		Menu[i].setActMenuItem(SubPage);
	}

	// console.log("Selected menu item = " + SubPage);
	document.Formular.MenuName.value = SubPage;
	document.Formular.submit();
	window.location.reload();
}

function StoreAndSend(Name, Value) {
	document.Formular.ParID.value = Name;
	document.Formular.ParValue.value = Value;
	document.Formular.submit();
}

function StoreAndSendButton(Value) {
	document.Formular.ParID.value = Value;
	document.Formular.ParValue.value = "Button";
	document.Formular.submit();
}

function ParMenu(MenuName, MenuItemName, MenuID, NoChilds, Parent, ActMenuItem, MenuItemNameT) {
	this.expanded = false;
	this.MenuName = MenuName;
	this.MenuItemName = MenuItemName;
	this.MenuID = MenuID;
	this.NoChilds = NoChilds;
	this.Parent = Parent;
	this.ActMenuItem = ActMenuItem;
	
	if (MenuItemNameT === "(null)") {
		this.MenuItemNameT = MenuItemName;
	}
	else {
		this.MenuItemNameT = MenuItemNameT;
	}

	if (typeof this.SubMenuVisible === "undefined") {
		var tmpExpanded = this.expanded;
		var tmpActMenuItem = this.ActMenuItem;
		// console.log("INIT: " + this.MenuItemName + "Expanded is not defined - trying to retrieve value from persistent storage");
		if (window.sessionStorage) {
			var dummy;
			// Member expanded
			if (dummy) {
				tmpExpanded = (dummy === "false") ? false : true;
			}
			// Member ActMenuItem
			dummy = window.sessionStorage.getItem(this.MenuItemName + "ActMenuItem");
			if (dummy) {
				tmpActMenuItem = dummy;
			}
		} else {
			// no persistent storage available -> use defaults
			tmpExpanded = true;
		}
		this.SubMenuVisible = tmpExpanded;
		this.expanded = tmpExpanded;
		this.ActMenuItem = tmpActMenuItem;
		// console.log("INIT: " + this.MenuItemName + "Expanded = " + this.expanded);
	}

	this.collapse = function () {
		if (this.expanded) {
			this.expanded = false;
			// console.log("collapse: new value for " + this.MenuItemName + "Expanded = " + this.expanded);
			if (window.sessionStorage) {
				window.sessionStorage.setItem(this.MenuItemName + "Expanded", this.expanded);
			}
			window.location.reload();
		}
	};

	this.expand = function () {
		if (!this.expanded) {
			this.expanded = true;
			// console.log("expand: new value for " + this.MenuItemName + "Expanded = " + this.expanded);
			if (window.sessionStorage) {
				window.sessionStorage.setItem(this.MenuItemName + "Expanded", this.expanded);
			}
			window.location.reload();
		}
	};

	this.toggle = function () {
		this.expanded = !this.expanded;
		// console.log("toggle: new value for " + this.MenuItemName + "Expanded = " + this.expanded);
		if (window.sessionStorage) {
			window.sessionStorage.setItem(this.MenuItemName + "Expanded", this.expanded);
		}
	};

	this.getHTMLFileName = function () {
		return this.MenuItemName.replace(/[ :\/\\]/g, "_");
	};

	this.getHTMLParentFileName = function () {
		return this.Parent.replace(/[ :\/\\]/g, "_");
	};

	this.setActMenuItem = function (item) {
		this.ActMenuItem = item;
		// console.log("setActMenuItem: new value for " + this.MenuItemName + "ActMenuItem = " + this.ActMenuItem);
		if (window.sessionStorage) {
			window.sessionStorage.setItem(this.MenuItemName + "ActMenuItem", this.ActMenuItem);
		}
	};

	this.isExpanded = function () {
		return this.expanded;
	};

	this.isCollapsed = function () {
		return !this.expanded;
	};

	this.isLeaf = function () {
		return this.NoChilds === 0;
	};

	this.hasChilds = function () {
		return this.NoChilds > 0;
	};

	this.getNoChilds = function () {
		return this.NoChilds;
	};
}

function Param(SubID, Parname, ParID, Parvalue, Parmin, Parmax, Parlist, ParDim, Size, Access, ParnameT, ParlistT,Pardefault,PcParID,FavMenu) {
	this.SubID = SubID;
	this.Parname = Parname;
	this.ParID = ParID;
	this.Parvalue = Parvalue;
	this.Parmin = Parmin;
	this.Parmax = Parmax;
	this.Parlist = Parlist;
	this.ParDim = ParDim;
	this.Size = Size;
	this.Access = Access;
    this.ParnameT = ParnameT;
    this.ParlistT = ParlistT;
	this.Pardefault = Pardefault;
	this.PcParID = PcParID;
	this.FavMenu = FavMenu;
}

function HTMLFileName(MenuItemName) {
	return MenuItemName.replace(/[ :\/\\]/g, "_");
}

function NodeIsExpanded(MenuItemName, NodeIndex) {
	var Node = this.SubMenuList[MenuItemName][NodeIndex];
	var Ret = false;

	if (Node) {
		if (typeof Node !== "undefined") {
			Ret = Node.isExpanded();
		}
	}

	return Ret;
}

function NodeIsCollapsed(MenuItemName, NodeIndex) {
	var Node = this.SubMenuList[MenuItemName][NodeIndex];
	var Ret = true;

	if (Node) {
		if (typeof Node !== "undefined") {
			Ret = Node.isCollapsed();
		}
	}

	return Ret;
}

function NodeIsLeaf(MenuItemName, NodeIndex) {
	var Node = this.SubMenuList[MenuItemName][NodeIndex];
	var Ret = true;

	if (Node) {
		if (typeof Node !== "undefined") {
			Ret = Node.isLeaf();
		}
	}

	return Ret;
}

function NodeHasChilds(MenuItemName, NodeIndex) {
	var Node = this.SubMenuList[MenuItemName][NodeIndex];
	var Ret = false;

	if (Node) {
		if (typeof Node !== "undefined") {
			Ret = Node.getNoChilds() > 0;
		}
	}

	return Ret;
}

function NodeGetNoChilds(MenuItemName, NodeIndex) {
	var Node = this.SubMenuList[MenuItemName][NodeIndex];
	var Ret = 0;

	if (Node) {
		if (typeof Node !== "undefined") {
			Ret = Node.getNoChilds();
		}
	}

	return Ret;
}

function DoesBrowserSupport(Feature) {
	var Ret = true; // true, um grundsätzlich alle Features hinsichtlich des Supports zu checken
	var UserAgent = this.navigator["userAgent"]; // Browserversion abfragen.
	var Delim = new Array(";", " ");
	var i;

	switch (Feature) {
	case "MenuTree":

		Ret = false; // true, um grundsätzlich die Darstellung des Menüs als Baum zu unterstützen

		for (i = 0; (i < Delim.length) && Ret; i++) {
			var Tokens = UserAgent.split(Delim[i]);
			var State = 0;
			var j;

			for (j = 0; (j < Tokens.length) && Ret; j++) {
				var Token = Tokens[j];

				switch (State) {
				case 0:
					// ist es der Internet Explorer?
					if (Token === "MSIE") {
						State = 1;
					}
					break;

				case 1: {
						var NumTokens = Token.split(".");

						// IE Version 9 oder älter?
						if (parseInt(NumTokens[0], 10) <= 9) {
							// Baumdarstellung nicht möglich!
							Ret = false;
						}
					}
					break;

				default:
					break;
				}
			}
		}
		break;

	case "NavigateByLocationChange":

		Ret = true; // true, um grundsätzlich die Navigation mittels "change location" zu unterstützen

		// ist es Chrome oder Safari?
		if (UserAgent.indexOf("Chrome") > 0 ||
			UserAgent.indexOf("Safari") > 0) {
			Ret = false;
		}
		break;

	default:
		Ret = false; // unbekanntes Feature - wird nicht unterstützt
		break;
	}

	return Ret;
}

function ShowMenu(MenuItemName, Level, UseMenuTree, NavigateByLocationChange) {
	var idx = 0;
	var Menu = this.SubMenuList[MenuItemName];

	if (typeof Menu !== "undefined") {
		if (UseMenuTree) {
			document.writeln("<table width=\"100%\">");
		}

		for (idx = 0; idx < Menu.length; idx++) {
			var Node = Menu[idx];
			var ObjName = MenuItemName + Node.MenuItemName;
			var ButtonClass = "SubMenu";
//			var ButtonImage = "submenubutton.gif";
			var ButtonOnMouseOver = "SubMenuButton_hl";
			var ButtonOnMouseOut = "SubMenuButton";
			var Indentation = 10;
			var OutString = "";

			if (UseMenuTree) {
				OutString = "<tr><td width=\"" + Indentation + "px\">" + /* idx + */
					"</td><td>";
				document.writeln(OutString);
			}

			OutString = "<img class=\"" + ButtonClass + "\" src=\"" + SubMenuButton.src + "\" name=\"" + ObjName + "\">";
			document.writeln(OutString);

			if (Node.hasChilds()) {
				if (UseMenuTree) {
					OutString = "<a id=\"MenuLink\" href=\"javascript:ToggleNode('" + MenuItemName + "', " + idx + ")\"";                    
				} else {
					if (NavigateByLocationChange) {
						OutString = "<a id=\"MenuLink\" href=\"javascript:ChangeFrameAndSend(" + Node.MenuID + ", '" + Node.MenuItemName + "', '" + Node.MenuName + "', 'menu" + Node.getHTMLFileName() + ".htm')\"";
					} else {
						OutString = "<a id=\"MenuLink\" href=\"menu" + HTMLFileName(Node.MenuItemName) + ".htm\" ";
					}
				}
			} else {
				OutString = "<a id='MenuLink' href=\"javascript:SendForm(" + Node.MenuID + ", '" + Node.MenuItemName + "', '" + Node.MenuName + "')\" ";
			}
			document.writeln(OutString);

			OutString = "onmouseover=\"TeaseButton('" + ObjName + "', " + ButtonOnMouseOver + ")\"";
			document.writeln(OutString);

			OutString = "onmouseout=\"TeaseButton('" + ObjName + "', " + ButtonOnMouseOut + ")\">";
			document.writeln(OutString);

			OutString = "<div align=\"left\" class=\"" + ButtonClass + "\">";
			document.writeln(OutString);

			OutString = Node.MenuItemNameT + "</div>";
			document.writeln(OutString);

			OutString = "</a>";
			document.writeln(OutString);

			if (UseMenuTree) {
				OutString = "</td></tr>";
				document.writeln(OutString);

				if (Node.isExpanded()) {
					if (Node.hasChilds()) {
						OutString = "<tr><td width=\"" + Indentation + "px\">.</td><td>";
						document.writeln(OutString);

						ShowMenu(Node.MenuItemName, Level + 1, UseMenuTree, NavigateByLocationChange);

						OutString = "</td></tr>";
						document.writeln(OutString);
					} else {
						Node.expanded = false;
					}
				}
			}
		}

		if (UseMenuTree) {
			document.writeln("\n</table>");
		}
	}
}
