var t0, t1, t2, t3; // timeouts
function eventHandler(event, params) {
  //alert("event: " + event + "\nparams: " + params);
	var undef;
	if(customEvents[event] != undef) {
		if(customEvents[event] == "customOnly") { customEventHandler(event, params); return }
		else if(customEvents[event] == "customAndStd") customEventHandler(event, params);
	}
  var paramArr = queryStringToArray(params);
  if (event == "TreeNodeSelected") {
    //alert("event: " + event + "\nparams: " + params);
    var nodeType = paramArr["ItemType"];
    var URL = paramArr['URL'];
    var extension = null;
    var include = false;

	if(URL && nodeType != "folder" && nodeType != "device" && nodeType != "bel_mtxthtml" && !clearContentFramesThenLoadingADocument) {

    	if(URL == "undefined") {
    		eventHandler("OpenLink","URL="+escape(getPath('custom/images/noimage.gif'))+"&itemType=document");
    		return;
    	}
		if(URL.indexOf(".jpeg") != -1) extension = ".jpeg";
		else if(URL.indexOf(".jpg") != -1) extension = ".jpg";
		else if(URL.indexOf(".gif") != -1) extension = ".gif";
		else if(URL.indexOf(".bmp") != -1) extension = ".bmp";
		else if(URL.indexOf(".png") != -1) extension = ".png";
		else if(URL.indexOf(".tiff") != -1) extension = ".tiff";
		else if(URL.indexOf(".tif") != -1) extension = ".tif";
		else if(URL.indexOf(".tiff") != -1) extension = ".tiff";
		else if(URL.indexOf(".html") != -1) extension = ".html";
		else if(URL.indexOf(".htm") != -1) extension = ".htm";
		else { // unknow mime type, try to find in "attachedMediaOnTreeButNoImage"-Array - customer special media-files
			for(mt in attachedMediaOnTreeButNoImage) 
				if(URL.indexOf(attachedMediaOnTreeButNoImage[mt]) != -1) {
					extension = attachedMediaOnTreeButNoImage[mt];
					break;
				}
		}
		try { if(attachedMediaOnTreeOpenUpBehavior[extension] == "include") include=true; 
		} catch(e) {/*not found, let default behavior*/}
	} else include = true;			
	var jumpBackToThisPath = null;
	if(!clearContentFramesThenLoadingADocument && !include) jumpBackToThisPath = currentTreePath;
	// clearContentFramesThenLoadingADocument
    if(!belenusHome.printServer && include) {
	    if(getModule("ImageView") != null) sendMessage("Toolbar","HidePrintMode",null);
	    belenusHome.currentTreePath = paramArr["ItemPath"];
	
	    if (belenusHome.HistoryBar != null) {
	      belenusHome.HistoryBar.IPH.add(paramArr["ItemPath"]);
	      belenusHome.HistoryBar.setTreeLabel(paramArr["Label"],paramArr["ItemPath"]);
	    }
	    belenusHome.setXCookie("treepath", paramArr["ItemPath"]);    
    }
    if (!belenusHome.printServer) {
      if (paramArr["ItemPathRemainder"] == null) treepathRemainder = null;
      
      if (nodeType == "device") {
        if(URL) {
          var msgParams = "URL=" + escape(URL);
          if (paramArr["ItemPathRemainder"]) msgParams += "&SelectItemPath=" + escape(paramArr["ItemPathRemainder"]);
          sendMessage("Table", "LoadPartList", msgParams);
          eventHandler("LoadAdditionalDeviceHeader",params);
        } else { //No URL found
          unregisterModule("Detail"); // detail.html hat kein body => kein onunload
          unregisterModule("Table");
          unregisterModule("Toolbar");
          belenusHome.inhalt.location = "about:blank";        
        }
      } else if(nodeType == "folder" || nodeType == "bel_mtxthtml") { // bel_mtxthtml <- 2.8 DataFlow
        if(typeof URL != "undefined" && URL != "undefined") {
          eventHandler("OpenLink","URL="+escape(paramArr['URL'])+"&itemType=folder");
        } else { //No URL found
          unregisterModule("Detail"); // detail.html hat kein body => kein onunload
          unregisterModule("Table");
          unregisterModule("Toolbar");
          belenusHome.inhalt.location = "about:blank";
        }
      } else {
      	if(clearContentFramesThenLoadingADocument) {
	        unregisterModule("Detail"); // detail.html hat kein body => kein onunload, deswegen manuelles "unregistering"
	        unregisterModule("Table");
	        unregisterModule("Toolbar");
	        belenusHome.inhalt.location = "about:blank";
        }
        if(URL)
        	if(jumpBackToThisPath != null && jumpBackToThisPath != "" && jumpBackToThisPath != "/") sendMessage("Tree","SelectNode","ItemPath="+jumpBackToThisPath);
        	if(typeof URL == "undefined" || URL == "undefined") URL = getPath('custom/images/noimage.gif');
        	eventHandler("OpenLink","URL="+escape(URL)+"&itemType=document");
	  }
	}        
	
  } else if (event == "TreeSelectionCleared") {
    // show in the content frame the welcome page
    if(usePartslinkConnector) belenusHome.inhalt.location = getPath("partslink/partslink_welcome.html");
    else if(welcomeI18N) belenusHome.inhalt.location = getPath("lang/"+belenusHome.currentLanguage+"/welcome.html");
	else belenusHome.inhalt.location = getPath("welcome.html");

    unregisterModule("Detail"); // detail.html hat kein body => kein onunload
    unregisterModule("Table");
    unregisterModule("Toolbar");
    
    belenusHome.cookieReset("treepath");
    belenusHome.HistoryBar.setTreeLabel(belenusHome.ld['defaultTitle'],'');
    belenusHome.currentTreePath="/";

  } else if (event == "ImageListChanged") {
    var imageList = new Array();

    if(!paramArr['CurrentlySelected'] && !paramArr['Label0']) {
      sendMessage("ImageView","ClearImageView",null);
      sendMessage("Toolbar","SetChoiceList","Name=ImageList");
      if(belenusHome.showImage == "ifAvailable") {
      sendMessage("Detail", "SetDetailFrameViews", "View=onlyTable");
      }
    } else if(paramArr['Label0']){
      // set images
      sendMessage("Toolbar","SetChoiceList","Name=ImageList&"+params);
    }
    
    for (var imageNo = 0; paramArr["Label" + imageNo] != null; imageNo++)
      imageList[imageNo] = paramArr["Label" + imageNo];

  } else if (event == "HotspotsSelected") {
    var itemPaths = "";
    for (var i = 0; paramArr["HotspotID" + i] != null; i++) {
      if (i > 0) itemPaths += "&";
      itemPaths += getProperty("Global","PartsByField","Field=posno&Value="+paramArr['HotspotID' + i]);
    }
    sendMessage("Table", "SelectParts", itemPaths + "&Exclusive=" + paramArr["Exclusive"]);

  } else if (event == "HotspotsDeselected") {
    var itemPaths = "";
    for (var i = 0; paramArr["HotspotID" + i] != null; i++) {
      if (i > 0) itemPaths += "&";
      itemPaths += getProperty("Global","PartsByField","Field=posno&Value="+paramArr['HotspotID' + i]);
    }
    sendMessage("Table", "DeselectParts", itemPaths);

  } else if (event == "HotspotDblClicked") {
    var itemPaths = getProperty("Global","PartsByField","Field=posno&Value="+paramArr['HotspotID0']);
    var pArr = queryStringToArray(itemPaths);
    for (var i = 0; pArr["ItemPath" + i] != null; i++) {
      sendMessage("Table", "DblClickPart", "ItemPath="+pArr["ItemPath" + i]);
    }

  } else if (event == "SelectionCleared") {
    sendMessage("ImageView", "ClearSelection", params);
	eventHandler("LoadAdditionalFootNote","ClearSelection=true");
  } else if (event == "PartsSelected") {
    // some params in event "PartsSelected" are not needed for message "SelectHotspots",
    // but we send them all as it is easier than stripping off the unneccessary ones...
    //alert(params);
    sendMessage("Toolbar","HidePrintMode",null);
    if (paramArr["ClickedColumnName"] != null) { // is null when selected from ImageView
      var hotspots = "";
      for (var i = 0; paramArr["PosNo" + i] != null; i++)
        hotspots += "&HotspotID" + i + "=" + paramArr["PosNo" + i];
      sendMessage("ImageView", "SelectHotspots", "Exclusive="+paramArr["Exclusive"]+hotspots);
    }
    eventHandler("LoadAdditionalFootNote",null);
  } else if (event == "PartsDeselected") {
    // some params in event "PartSelected" are not needed for message "DeselectHotspot",
    // but we send them all as it is easier than stripping off the unneccessary ones...
    if (paramArr["ClickedColumnName"] != null) { // is null when deselected from ImageView
      var hotspots = "";
      for (var i = 0; paramArr["PosNo" + i] != null; i++) {
        if (i > 0) hotspots += "&";
        hotspots += "HotspotID" + i + "=" + paramArr["PosNo" + i];
      }
      sendMessage("ImageView", "DeselectHotspots", hotspots);
    }
    sendMessage("Toolbar","HidePrintMode",null);
    eventHandler("LoadAdditionalFootNote","ClearSelection=true");    
  } else if (event == "LoadImage") {

    var p2 = "URL=" + escape(paramArr["URL"]) + "&MIMEType=" + 
        escape(paramArr["MIMEType"]);
    if (paramArr["ImageID"]) p2 += "&ImageID=" + escape(paramArr["ImageID"]);
    if (paramArr["Label"]) p2 += "&Label=" + escape(paramArr["Label"]);
    if (paramArr["SelectPosNo"])  p2 += "&SelectHotspotID=" + escape(paramArr["SelectPosNo"]);
    sendMessage("ImageView", event, p2);
    if(paramArr['Label']) sendMessage("Toolbar","SetSelectedChoiceItem","Name=ImageList&CurrentlySelected="+paramArr['Label']);

  } else if(event == "HotspotsLoadingFinished") {
    sendMessage("Table", "HotspotsLoadingFinished", params);
  } else if(event == "Zoomed") {
    var btnStatesQuery = new Array();
    var states = new Array("Enabled","Disabled","Pressed");
    var btns = new Array();
    btns[0] = new Array("ZoomIn",states[0]);
    btns[1] = new Array("ZoomOut",states[0]);
    btns[2] = new Array("FitToWin",states[0]);
    btns[3] = new Array("FitToWidth",states[0]);
    btns[4] = new Array("Lens",states[0]);
    btns[5] = new Array("FreeScale",states[0]);
    btns[6] = new Array("Print",states[0]);
 
    btns[7] = new Array("Rotate3d",states[1]);
    btns[8] = new Array("MoveHand",states[2]);
    btns[9] = new Array("FitToWidthPart",states[1]);
    btns[10] = new Array("HideOnePart",states[1]);
    btns[11] = new Array("ShowAllParts",states[1]);
    btns[12] = new Array("SemiTransparent",states[1]);

    if("false" == paramArr['CanZoomIn']) btns[0][1] = states[1];
    if("false" == paramArr['CanZoomOut']) btns[1][1] = states[1];
    
    if("false" == paramArr['FitToWindowActive']) btns[2][1] = states[0];
    else btns[2][1] = states[1];
    
    if("false" == paramArr['FitToWidthActive']) btns[3][1] = states[0];
    else btns[3][1] = states[1];
    
    if("false" == paramArr['LensAvailable']) {btns[4][1] = states[1];
    } else if("true" == paramArr['LensActive']) { btns[4][1] = states[2]; 
    } else btns[4][1] = states[0];
    
    if("true" == paramArr['FreeScaleActive'] && paramArr['CanZoomIn'] != false) btns[5][1] = states[2];
    else if(paramArr['CanZoomIn'] == "false") btns[5][1] = states[1];
    else btns[5][1] = states[0];
    
    for(b in btns) {
      btnStatesQuery[btnStatesQuery.length] = "Name"+b+"="+btns[b][0] + "&State"+b+"="+btns[b][1];
    }
//    alert(btnStatesQuery.join("&"));
    sendMessage("Toolbar","SetButtonStates", btnStatesQuery.join("&"));
    
  } else if(event == "ButtonClicked") {
    //handle default buttons
    switch(paramArr['Name']) {
      case "ZoomIn":
      sendMessage("ImageView","ZoomIn", null);
      break;
      case "ZoomOut":
      sendMessage("ImageView","ZoomOut", null);
      break;
      case "FitToWidth":
      sendMessage("ImageView","FitToWidth", null);
      break;
      case "FitToWin":
      sendMessage("ImageView","FitToWindow", null);
      break;
      case "Lens":
      sendMessage("ImageView","ToggleLens", null);
      break;
      case "FreeScale":
      sendMessage("ImageView","ToggleFreeScale", null);
      break;
      case "MainImg":
      sendMessage("Table","ChangeImage","Navigate=Main");
      break;
      case "PrevImg":
      sendMessage("Table","ChangeImage","Navigate=Previous");
      break;
      case "NextImg":
      sendMessage("Table","ChangeImage","Navigate=Next");
      break;
      case "MoveHand":
      sendMessage("ImageView","MoveHandActivate",null);
      break;
      case "Rotate3d":
	  sendMessage("ImageView","Rotate3dActivate",null);	      
	  break;
	  case "FitToWidthPart":
	  sendMessage("ImageView","FitToWidthPart",null);	      
	  break;
	  case "HideOnePart":
	  sendMessage("ImageView","HideSelectedPart",null);	      
	  break;
	  case "ShowAllParts":
	  sendMessage("ImageView","ShowAllParts",null);	      
	  break;
	  case "SemiTransparent":
	  sendMessage("ImageView","SemiTransparent",null);	      
      break;
      
      /* print */
      
      case "Print":
      sendMessage("Toolbar","PrintMode",null);
      break;
      
      /* print modes */
      
      case "PrintImage":
      eventHandler("Print","Mode=PrintImage");
      break;
      case "PrintImageAndPartList":
      eventHandler("Print","Mode=PrintImageAndPartList");
      break;
      case "PrintImageAndSelectedParts":
      eventHandler("Print","Mode=PrintImageAndSelectedParts");
      break;
      case "PrintCutout":
      eventHandler("Print","Mode=PrintCutout");
      break;
      case "PrintCutoutAndPartList":
      eventHandler("Print","Mode=PrintCutoutAndPartList");
      break;
      case "PrintCutoutAndSelectedParts":
      eventHandler("Print","Mode=PrintCutoutAndSelectedParts");
      break;
      case "PrintAllImages":
      eventHandler("Print","Mode=PrintAllImages");
      break;
      case "PrintAllImagesAndPartList":
      eventHandler("Print","Mode=PrintAllImagesAndPartList");
      break;
      case "PrintAllImagesAndSelectedParts":
      eventHandler("Print","Mode=PrintAllImagesAndSelectedParts");
      break;
      case "PrintPartList":
      eventHandler("Print","Mode=PrintPartList");
      break;
      case "PrintSel":
      eventHandler("Print","Mode=PrintSel");
      break;
    }
    /*
    else if(paramArr['Print']) {
      paramArr = queryStringToArray(getProperty("ImageView","CurrentState",""));
      belPrintImage(paramArr['URL'], paramArr['X'], paramArr['Y'], paramArr['W'], paramArr['H'], paramArr['Factor'], paramArr['Contrast'], paramArr['CThreshold'], paramArr['Smooth'], paramArr['OrigW'], paramArr['OrigH']);
    }
    */
    //else void(belenusHome.customBtns[belenusHome.getQueryField(params, paramArr['Name'])]); // customBtns
    
  } else if(event == "ChoiceChanged") {
    sendMessage("Table","ChangeImage","Label="+paramArr['Choice']);
  
  } else if(event == "AddSelectionToBasket") {
    var orderable = getProperty("Table", "SelectionOrderable", null);
    if ("true" == orderable) {
	    var selectedParts = getProperty("Table", "SelectedParts", null);
      sendMessage("Basket","Add","AddBy=ItemPaths&" + selectedParts);
    }

  } else if(event == "AddToBasket") {
     if (paramArr["AddBy"] == "HotspotIDs") {
      var itemPaths = "";
      var count = 0;
      for (var i = 0; paramArr["HotspotID" + i] != null; i++) {
        var ip = getProperty("Table","PartsByField","Field=posno&Value="+paramArr["HotspotID" + i]);
        var pArr = queryStringToArray(ip);
        for (var j = 0; pArr["ItemPath" + j] != null; j++)
          itemPaths += "&ItemPath" + count++ + "=" + pArr["ItemPath" + j];
      }
      sendMessage("Basket", "Add", "AddBy=ItemPaths" + itemPaths);
    } else sendMessage("Basket","Add",params);
  
  } else if(event == "ChangedBasketContent") {
    frames['header'].changedBasketContent("Filled="+paramArr['Filled']);

  } else if(event == "ShowBasket") {
    sendMessage("Basket","Show",null);
  
  } else if(event == "OpenLink") {

		if(paramArr['URL']) {
			var URL = paramArr['URL'];
			if(URL.substring(0,11) == "javascript:") {
				eval(URL.substring(11,URL.length));
			} else if(URL.substring(0,6) == "event:") {
				var index = URL.indexOf(",", 6);
				if (index == -1)
					eventHandler(URL.substring(6), null);
				else
					eventHandler(URL.substring(6, index), URL.substring(index + 1));
			} else if(URL.substring(0,8) == "message:") {
				var index = URL.indexOf(",", 8);
				var index2 = URL.indexOf(",", index + 1);
				var msgName = index2 == -1 ? URL.substring(index + 1) : URL.substring(index + 1, index2);
				var msgParams = index2 == -1 ? null : URL.substring(index2 + 1);
				sendMessage(URL.substring(8, index), msgName, msgParams);
			} else if(URL.substring(0,6) == "parts:") {
				sendMessage("Tree","SelectNode","ItemPath="+URL.substring(6,URL.length));
			} else if(URL.substring(0,8) == "partsid:") {
				sendMessage("Tree","SelectNode","IDItemPath="+URL.substring(8,URL.length));
			} else if (paramArr['Target'] == "ExtLink") {
				if(belenusHome.WM.getWindowReference("extlink")!=null)belenusHome.WM.getWindowReference("extlink").close();
				belenusHome.WM.openWindow("extlink", "", true);
				var extlinkWinRef = belenusHome.WM.getWindowReference("extlink");
				var url = unescape(URL);
				with(extlinkWinRef.document) {
					open();
					write('<html><head><title>'+belenusHome.ld['defaultTitle']+'</title></head><body style="padding:0px;margin:0px"><iframe id="extlinkInner" src="about:blank" width="100%" height="100%" border="0" frameborder="0" framespacing="0"></iframe></body></html>');
					close();
				}
				setTimeout('belenusHome.WM.getWindowReference("extlink").document.getElementById("extlinkInner").setAttribute("src","'+url+'");',22);
			} else if(paramArr['itemType'] == "folder" || paramArr['itemType'] == "document") { 
			
				var extension = null;
				var include = false; // by default always excluding media-files
				var includeType = "unknown"; 
				
				// guess mime-type
				if(URL.indexOf(".jpeg") != -1 || URL.indexOf(".jpg") != -1 || URL.indexOf(".gif") != -1 || URL.indexOf(".bmp") != -1 || URL.indexOf(".png") != -1) { // images which could display without plugin in the browser
					includeType="standard";
					if(URL.indexOf(".jpeg") != -1) extension = ".jpeg";
					else if(URL.indexOf(".jpg") != -1) extension = ".jpg";
					else if(URL.indexOf(".gif") != -1) extension = ".gif";
					else if(URL.indexOf(".bmp") != -1) extension = ".bmp";
					else if(URL.indexOf(".png") != -1) extension = ".png";
				} else if(URL.indexOf(".tiff") != -1 || URL.indexOf(".tif") != -1) { // tiff-images needs the interparts.ImageView
					includeType="tiff";
					extension = ".tif";
					if(URL.indexOf(".tiff") != -1) extension = ".tiff";
				} else if(URL.indexOf(".html") != -1 || URL.indexOf(".htm") != -1) { // html pages
					extension = ".html";
					if(URL.indexOf(".htm") != -1) extension = ".htm";
				} else { // unknow mime type, try to find in "attachedMediaOnTreeButNoImage"-Array - customer special media-files
					for(mt in attachedMediaOnTreeButNoImage) 
						if(URL.indexOf(attachedMediaOnTreeButNoImage[mt]) != -1) {
							extension = attachedMediaOnTreeButNoImage[mt];
							break;
						}
				}
				// looking for non default behavior
				try { if(attachedMediaOnTreeOpenUpBehavior[extension] == "include") include=true; } catch(e) {/*not found, let default behavior*/}
				
				// build window.document content
				var standardTypeContent = '<s'+'cript type="text/javascript">var belenusHome = self;function getProperty() {return null };function eventHandler(x,y) {} var currentLoadedURL = "'+URL+'";</s'+'cript>';
				standardTypeContent +='<table width="100%" height="100%" border="0"><tr><td valign="middle" align="center">';
				standardTypeContent +='<img src="'+URL+'"></td></tr></table>';
				
				var tiffTypeContent = '<s'+'cript type="text/javascript">var belenusHome = self;function getProperty() {return null };function eventHandler(x,y) {} var currentLoadedURL = "'+URL+'";</s'+'cript>';
				tiffTypeContent += '<applet archive="core.jar,xml.jar,imageview.jar,tiff.jar" codebase="." mayscript="true" code="com.belenus.interparts.PartsApplet" width="100%" height="100%" hspace="0" vspace="0">';
				tiffTypeContent += '<param name="GUIDef" value="tree_doc_tiff_imageview_guidef.xml">';
				tiffTypeContent += '<param name="DataLocales" value="'+belenusHome.getLanguagesCurrentFirst('DATA')+'">';
				tiffTypeContent += '<param name="LocaleDef" value="'+belenusHome.getPath('lang/'+belenusHome.currentLanguage+'/localedef.txt')+'">';
				tiffTypeContent += '<param name="GUILocale" value="'+belenusHome.currentLanguage+'">';
				tiffTypeContent += '<param name="Message0" value="ImageView,EnableShopping,Enable=false">';
				tiffTypeContent += '<param name="Message1" value="ImageView,LoadImage,URL='+URL+'">';
				tiffTypeContent += '<param name="Message2" value="ImageView,SetGUIParam,Name=SelectedColor&Value=#ffffff">';
				tiffTypeContent += '<param name="Message3" value="ImageView,SetGUIParam,Name=HighlightedColor&Value=null"></applet>';
				
				// decide what to do with the content (popup, or content-frame)
				var internalWinRef = null;
				if(paramArr['itemType'] == "folder" || include) // if itemType is folder we always include the document
					internalWinRef = belenusHome.inhalt;
				else { // set window reference of the popup
					try { //catch "RemoteServerComputer not found" Error
						if(belenusHome.WM.getWindowReference("excludedDocuments")==null || belenusHome.WM.getWindowReference("excludedDocuments").closed == true) { 
							belenusHome.WM.openWindow("excludedDocuments","",false);
							internalWinRef = belenusHome.WM.getWindowReference("excludedDocuments");
						} else internalWinRef = belenusHome.WM.getWindowReference("excludedDocuments");
					} catch(e) {
						belenusHome.WM.openWindow("excludedDocuments","",false);
						internalWinRef = belenusHome.WM.getWindowReference("excludedDocuments");						
					}
				}
				try { // prevent reloading
					var currentLoadedURL = (!include) ? internalWinRef.introvert.currentLoadedURL : internalWinRef.currentLoadedURL;
					if(currentLoadedURL == URL) return; // they were identical
				} catch(e) {}							
				
				if(includeType != "unknown") {
					if(!include) {
						with(internalWinRef.document) {
							open();
							write('<html><head>');
							write('<title>'+belenusHome.ld['defaultTitle']+'</title>');
							write('</head><body style="margin:0px;padding:0px;border:0px;">');
							write('<iframe frameborder="0" width="100%" height="100%" name="introvert" vspace="0" hspace="0" style="margin:0px;padding:0px"></iframe></body></html>');
							close();        
						}
					}

					with((!include) ? internalWinRef.introvert.document : internalWinRef.document) {
						open();
						write('<html><body style="margin:0px;padding:0px;border:0px;">');
						if(includeType == "standard") 
							write(standardTypeContent);
						else // is a tiff 
							write(tiffTypeContent);						
						write('</body></html>');
						close();
					}
					if(!include) internalWinRef.focus();

				} else 
					if(!include && paramArr['itemType'] != "folder") {				
						var preventLosingURL = URL; //IE bug workaround
						with(internalWinRef.document) {
							open();
							write('<html><head>');
							write('<title>'+belenusHome.ld['defaultTitle']+'</title>');
							write('</head><body style="margin:0px;padding:0px;border:0px;">');
							write('<iframe frameborder="0" width="100%" src="'+preventLosingURL+'" height="100%" vspace="0" hspace="0" style="margin:0px;padding:0px"></iframe></body></html>');
							close();     
							internalWinRef.focus();   
						}					
					} else
						internalWinRef.location.href = URL;

			} else {
				try {
					if(document.getElementById("ContentFrame").setAttribute("src") != URL) document.getElementById("ContentFrame").setAttribute("src",URL); // prevent reloading of the same document
				} catch(e) {document.getElementById("ContentFrame").setAttribute("src",URL);}
			}
		} // URL

  } else if(event == "Print") {
    if(paramArr['Mode']) printHandler(paramArr['Mode']);

  } else if(event == "SetDetailFrameViews") {
    setShowImageState(paramArr['View']);
    sendMessage("Detail", "SetDetailFrameViews", "View="+belenusHome.showImageState+"&MIMEType="+escape(getModule("ImageView").currentImageType));
  
  } else if(event == "ErrorLoadingImage") {
    var btnsDisabled = "";
    for(i in belenusHome.shownBtns) btnsDisabled += "Name"+i+"="+belenusHome.shownBtns[i]+"&State"+i+"=Disabled&";
    sendMessage("Toolbar","SetButtonStates",btnsDisabled);
    //sendMessage("Toolbar","SetButtonStates","Name0=ZoomIn&State0=Disabled&Name1=ZoomOut&State1=Disabled&Name2=FitToWin&State2=Disabled&Name3=FitToWidth&State3=Disabled&Name4=Lens&State4=Disabled&Name5=FreeScale&State5=Disabled&Name6=Print&State6=Disabled");
  
  } else if(event == "DataLocaleChanged") {
    if(paramArr['Sender'] == "Table") {
      sendMessage("ImageView", "ChangeDataLocale", "Locale="+paramArr['Locale']);
    }
    
  } else if(event == "DebugOutput") {
  	if(showDebugOutput)
	  	belenusHome.WM.openWindow("debugOutput",params,true);
  } else if(event == "Logout") {
  	if(belenusHome.logoutPath && belenusHome.logoutPath != null && belenusHome.logoutPath != "") {
    	if(paramArr['ShowMessage'] == "true") alert(belenusHome.ld['session_expired']);
	  	void(belenusHome.location.href=belenusHome.logoutPath+"?language="+currentLanguage);
	}
  } else if(event == "SetTreeDataSource") { // URL means the tree.xml within the tree data
//  	IPH.resetHistory();
	sendMessage("Tree","SetDataSource","URL="+escape(paramArr['URL']));
	setTimeout('sendMessage("Tree","SelectNode","ItemPath='+currentTreePath+'");',100);
	
  } else if(event == "SetTreeDataSourceByReloading") { // URL means tree_guidef.xml 
  	IPH.resetHistory();
	sendMessage("Tree","SetDataSourceByReloading","URL="+paramArr['URL']);
	
  } else if(event == "ChangeAppletGUILanguage") {
  	if(paramArr['Language']) { // needs the param "Language=de_de"
		if(getModule("Tree") != null)sendMessage("Tree","SetGUILanguage",params+"&URL="+getPath("lang/"+paramArr['Language']+"/localedef.txt"));
		if(getModule("Table") != null)sendMessage("Table","SetGUILanguage",params+"&URL="+getPath("lang/"+paramArr['Language']+"/localedef.txt"));
		if(getModule("ImageView") != null)sendMessage("ImageView","SetGUILanguage",params+"&URL="+getPath("lang/"+paramArr['Language']+"/localedef.txt"));
	}
	
  } else if(event == "SetGUILanguageSoftly") {
  	if(paramArr['Language']) {
  		eventHandler('ChangeAppletGUILanguage','Language='+paramArr['Language']);
  		belenusHome.setGUILanguage(paramArr['Language']);
  	}
  	
  } else if(event == "SetLanguage") {
  	if(paramArr['GUILanguage'] && paramArr['GUILanguage'] != "" && paramArr['GUILanguage'] != currentLabel) {
  		eventHandler("SetGUILanguageSoftly","Language="+paramArr['GUILanguage']);
  	} 
	if(paramArr['DataLanguage'] && paramArr['DataLanguage'] != "" && paramArr['DataLanguage'] != currentDataLanguage) {
  		if(belenusHome.interpartsVersion == "static") {
  			sendMessage("Tree","ChangeDataLocale","Locale="+paramArr['DataLanguage']);
  			sendMessage("Table","ChangeDataLocale","Locale="+paramArr['DataLanguage']);
  			sendMessage("ImageView","ChangeDataLocale","Locale="+paramArr['DataLanguage']);
  		} else {
  			var ctd = ""+getProperty("Tree","CurrentTreeDef",null);  				
  			setTimeout('sendMessage("Tree","ChangeDataLocale","Locale='+paramArr['DataLanguage']+'");',50); // reduce concurrent using of the live-connection 
  			eventHandler("SetTreeDataSource","URL="+escape(ctd));//+"&dataLanguage="+paramArr['DataLanguage']));
  		}
  		currentDataLanguage = paramArr['DataLanguage'];
  	}   	
  	if(cookieActivate) {
		setXCookie("Language",currentLanguage.concat("|").concat(currentDataLanguage));
	}
  } else if(event == "flipArrangement") {
  	if(belenusHome.detailFrameArrangement == "horizontal") belenusHome.detailFrameArrangement='vertical';
  	else belenusHome.detailFrameArrangement='horizontal'
  	var reselectTreePath = currentTreePath;
  	if(getModule("Detail") == null)return;
  	var selectedPartInSPL = getProperty("Global","SelectedParts",null);
  	if(selectedPartInSPL.length > 0) selectedPartInSPL = getQueryField(selectedPartInSPL,"ItemPath0");
  	unregisterModule("Table");
	eventHandler("OpenLink","URL=parts:"+reselectTreePath+"/"+selectedPartInSPL);
	setTimeout('eventHandler("LoadAdditionalDeviceHeader","ItemPath='+escape(reselectTreePath)+'")',300);
  } else if(event == "LoadAdditionalDeviceHeader") {
  	if(mediaFrameSize > 0) {
  		var contextId = paramArr['ItemPath'];
  		try { if(contextId.length > 1) contextId = contextId.split("/").reverse()[0]; }catch(e){}
  		try {
	  		frames.inhalt.document.getElementById("mediacanvas").setAttribute("src","../custom/deviceheader.jsp?contextid="+contextId);
	  		belenusHome.LoadAdditionalDeviceHeaderFails = 0;
  		} catch(e) {
  			if(belenusHome.LoadAdditionalDeviceHeaderFails < 15) {
  			belenusHome.LoadAdditionalDeviceHeaderFails++;
  			setTimeout('eventHandler("LoadAdditionalDeviceHeader","'+params+'")',300);
  			} else belenusHome.LoadAdditionalDeviceHeaderFails = 0;
  		}
  	}
  } else if(event == "LoadAdditionalFootNote") {
  	if(footnoteFrameSize > 0) {
  		if(paramArr["ClearSelection"] == "true") {
	  		frames.inhalt.document.getElementById("footnote").setAttribute("src","footnote.html");
  		} else {
	  		var selectedPartInSPL = getProperty("Global","SelectedParts",null);
		  	if(selectedPartInSPL.length > 0) selectedPartInSPL = getQueryField(selectedPartInSPL,"ItemPath0");		
		  	var partData = getProperty("Global","ItemData","ItemPath="+selectedPartInSPL);
		  	var ItemContextID = getQueryField(getQueryField(partData,"ItemData"),"ItemContextID");
		  	var DeviceID = getQueryField(getQueryField(partData,"ItemData"),"DeviceID");
		  	frames.inhalt.document.getElementById("footnote").setAttribute("src","../custom/footnote.jsp?itemcontextid="+ItemContextID+"&deviceid="+DeviceID);
	  	}
  	}
  } else if(event == "TableFrameResizeEnd" && belenusHome.useTabManager) {
	getModule("Detail").throwResizeEvent=false;
  	var currentTabFrameSize = belenusHome.document.getElementById("MainFrameSet").getAttribute("rows").split(",");
  	currentTabFrameSize[5] = parseInt(currentTabFrameSize[5]);
  	belenusHome.document.getElementById("MainFrameSet").setAttribute("rows",currentTabFrameSize.join(","));
  	currentTabFrameSize[5] = parseInt(currentTabFrameSize[5]);
  	setTimeout('belenusHome.document.getElementById("MainFrameSet").setAttribute("rows","'+currentTabFrameSize.join(",")+'");setTimeout(\'getModule("Detail").throwResizeEvent=true\',10);',1);
  } else if(event == "SaveDrawing") {
	var imgProp = belenusHome.getProperty("ImageView","CurrentState");
	var url=getQueryField(imgProp,'URL');
	var filename = url.split("/").reverse()[0];
	var contentType = getQueryField(imgProp,'MIMEType');
	belenusHome.frames.mrhidden2.location.href="imagedownload.jsp?url="+url+"&filename="+filename+"&contenttype="+contentType;  
  } else if(event == "HotspotHovered") {
      try {
	     if(paramArr['id'] != null && paramArr['id'] != 'null') {
	  	    hoverHelper(paramArr['id']); // function defined below (for unclutching)
	  	    return;
	  	 } else {
	  	 	clearTimeout(t0);clearTimeout(t1);
	  	 	t0 = setTimeout('sendMessage("Table","ClearSelection",null);',5);
	  		t1 = setTimeout('sendMessage("ImageView","ClearSelection",null);',9);
	  	 }
  	  } catch(e) {}
  } else {
    //alert("Event " + event + " not handled");
  }
	if(customEvents[event] != undef) {
		if(customEvents[event] == "stdAndCustom") customEventHandler(event, params);
	}    
}

function sendMessage(moduleName, message, params) {
	//alert("sendMsg: "+message+ "\nparams: "+params);
  try {
    var module = getModule(moduleName);
    var paramArr = queryStringToArray(params);
    if (module == null) {
      if (moduleName == "Table" || moduleName == "ImageView" || moduleName == "Toolbar") { // => create detail.html
        //alert("location: " + 'detail.html?Message0=' + escape(moduleName + ',' + message + ',' + params));
          belenusHome.inhalt.location = belenusHome.getPath('detail.html')+'?Message0=' + escape(moduleName) + ',' + escape(message) + ',' + escape(params);
      } else if(moduleName == "Basket") {
        try {
          registerModule("Basket", new Basket());
        } catch(e) {
          if(!belenusHome.avoidErrorMsg)alert("Error occurred:\n-Error-nr.: 04\n-Error at handling this module: <"+module+">\n-Fn(moduleName): "+moduleName+"\n-Fn(message): "+message+"\n-Fn(params): "+params+"\n-IPV:"+belenusHome.ipVersionNumber+"\n\nError description:\n"+e.message);
        }
      } else {
        try {
          if(!belenusHome.avoidErrorMsg)alert("Error occurred:\n-Error-nr.: 01\n-Error at handling this module: <"+module+">\n-Fn(moduleName): "+moduleName+"\n-Fn(message): "+message+"\n-Fn(params): "+params+"\n-IPV:"+belenusHome.ipVersionNumber+"\n\nError description:\n"+e.message);
        } catch(e) {
          if(!belenusHome.avoidErrorMsg)alert("Error occurred:\n-Error-nr.: 02\n-Error at handling this module: <unknown>\n Catched error at recovering the module or moduleName.\n-IPV:"+belenusHome.ipVersionNumber+"\n\nError description:\n"+e.message);
        }
      }
    } else{ 
    	try {
	    	module.messageHandler(message, params);
	    } catch(e) { // the page that includes the module is loaded but the object is not completly inited, so retry it once
    		setTimeout('try{module.messageHandler("'+message+'", "'+params+'")}catch(e){};',150);
	    }
    }
  } catch(e) {
    if (!(belenusHome.browserName == "Internet Explorer" && belenusHome.browserVersion == "5.5") && message != "LoadImage") {
      //work-around for bug in ie5.5
      if(!belenusHome.avoidErrorMsg)alert("Error occurred:\n-Error-nr.: 03\n-Error at handling this module: <"+module+">\n-Fn(moduleName): "+moduleName+"\n-Fn(message): "+message+"\n-Fn(params): "+params+"\n-IPV:"+belenusHome.ipVersionNumber+"\n\nError description:\n"+e.message);  
    }
  }
}


function getProperty(moduleName, property, params) {
 params = params+"";
// *** the following if clause contains the global (pseudo) module ***
  if(moduleName == "Global") {
    var paramArr = queryStringToArray(params);
    if(property == "PartsByField") {
      var field = paramArr['Field'];
      if ("HotspotID" == field) field = "posno";
      if(field) return getProperty("Table","PartsByField","Field="+field+"&Value="+paramArr['Value']);
    } else if(property == "AbsoluteItemPath") {
      if(paramArr['RelativeItemPath']) return getProperty("Tree","CurrentTreePath",null)+ "/" + paramArr['RelativeItemPath'];
    } else if(property == "SelectionOrderable") {
      return getProperty("Table", property, null);
    } else if(property == "AllImages") {
      return getProperty("Table", property, null);
    } else if(property == "ImageCount") {
      return getProperty("Table", property, null);      
    } else if(property == "SelectedParts") {
      return getProperty("Table", property, null);
    } else if(property == "HotspotsWithColor") {
  		return getProperty("Table", property, null);
    } else if(property == "PartsURI") {
      return getProperty("Tree","CurrentTreePath",null)+ "/" + paramArr['ItemPath'];
    } else if(property == "PartsOrderable") {
      if (paramArr['ItemPath0'] != null) {
        for (var i = 0; paramArr['ItemPath' + i] != null; i++)
          if ("true" != getProperty("Table","PartOrderable","ItemPath="+ip)) return "false";
        return "true";
      } else if (paramArr['ItemPath'] != null) { // deprecated, for backwards compatibility only
        return getProperty("Table","PartOrderable","ItemPath="+paramArr['ItemPath']);
      } else if (paramArr['Field'] != null)  { // deprecated, for backwards compatibility only
        var field = paramArr["Field"];
        if (field == "HotspotID") field = "posno";
        var parts = getProperty("Table", "PartsByField", "Field="+field+"&Value="+paramArr["Value"]);
        if (parts == null || parts == "") return "false";
        var pArr = queryStringToArray(parts);
        for (var i = 0; pArr["ItemPath" + i] != null; i++) {
          if ("false" == getProperty("Table","PartOrderable","ItemPath="+pArr["ItemPath" + i])) return "false";
        }
      }
      return "false";
    } else if(property == "ItemData") {
      var itemPath = paramArr['ItemPath'];
      var itemType = null;
      var label = null;
      var data = null;
      if (itemPath.charAt(0) == '/') { // abs. path, look in tree
        data = getProperty("Tree", "NodeData", "ItemPath=" + itemPath);
        var treeDataArr = queryStringToArray(data);
        label = treeDataArr["Label"];
        itemType = treeDataArr["NodeType"];
      } else {
        itemType = "Part";
        data = getProperty("Table","PartData","ItemPath="+itemPath);
        var partDataArr= queryStringToArray(data);
        label = partDataArr["description"]; // PER preferences.js konifugrierbar machen
      }
      var ret = "ItemType=" + itemType + "&Label=" + escape(label) + "&ItemData=" + escape(data);
      return ret;
    } return null;
    
  } else {
    var module = getModule(moduleName);
    if (module == null) return null;
    else {
      var ret = module.getProperty(property, params);
      if (ret == null) return null;
      else return "" + ret;
    }
  }
}

function registerModule(moduleName, module) {
  try {
    modules[moduleName] = module;
  } catch(e) {
	//eventHandler("DebugOutput","Sender=Function :registerModule&Message=Error occured: Tried to register module\nmodule name: ["+moduleName+"]");
	//alert("Error occurred\n-Error-nr.: 06\n-Can not register module\n-moduleName: <"+moduleName+">\n\nError description: "+e.toString());
  }
}

function unregisterModule(moduleName) {
	try {
		modules[moduleName] = null;
	} catch(e) {
		alert("error occurred\nunregisterModule: "+moduleName);
	}
}

function getModule(moduleName) {
  var undef;
  try {
	if(typeof modules[moduleName] == "undefined") return null;
  	if(typeof modules[moduleName] == "object" || typeof modules[moduleName] == "function") return modules[moduleName];
	else return null;
  } catch(e) {
  	return null;
  }
}

function calculateSVGImage(url, w, h, transX, transY, scale) {
  var headline = belenusHome.currentLabel;
  var winWidth = 720;//720
  var winHeight = 880;//1080
  var commentFieldHeight = 170;
  var imgMaxWidth = winWidth;
  var imgMaxHeight = winHeight - commentFieldHeight; 
  if (w != imgMaxWidth || h != imgMaxHeight) {
    var factViewport = w/h;
    var factPrint = imgMaxWidth/imgMaxHeight;
    if (factViewport > factPrint) {
      transX = Math.round(transX * imgMaxWidth / w);
      transY = Math.round(transY * imgMaxWidth / w);
      h = Math.round(imgMaxWidth * h / w);
      w = imgMaxWidth;
    } else {
      transX = Math.round(transX * imgMaxHeight / h);
      transY = Math.round(transY * imgMaxHeight / h);
      w = Math.round(imgMaxHeight * w / h);
      h = imgMaxHeight;
    }
  }
  /*
  var output = new Array();
  output['Type'] = "SVG";
  output['X'] = transX;
  output['Y'] = transY;
  output['W'] = w;
  output['H'] = h;
  output['URL'] = url;
  output['Scale'] = scale;
  */
  //alert("X="+transX+"&Y="+transY+"&W="+w+"&H="+h+"&URL="+url+"&Scale="+scale);
  return "X="+transX+"&Y="+transY+"&W="+w+"&H="+h+"&URL="+url+"&Scale="+scale;
  //return output;
}

function calculatePNGImage(url, x, y, w, h, factor, contr, cThres, smoo, origW, origH) {
//alert(url +"\n"+ x+"\n"+ y+"\n"+ w+"\n"+ h+"\n"+factor+"\n"+cThres+"\n"+smoo+"\n"+origW+"\n"+origH);
  var headline = belenusHome.currentLabel;
  var winWidth = 650;//720
  var winHeight = 1080;//1080  
  var commentFieldHeight = 170;
  var imgMaxWidth = winWidth;
  var imgMaxHeight = winHeight - commentFieldHeight; 
  //adjust image sizes
  var tmpFact; 
  if (w < imgMaxWidth || h < imgMaxHeight) {
    var factY = h/imgMaxHeight;
    var factX = w/imgMaxWidth;
    if (factY < factX) {
      tmpFact = factY;
      w = Math.round(w / tmpFact); 
      h = imgMaxHeight;
    } else {
      tmpFact = factX;
      h = Math.round(h / tmpFact);
      w = imgMaxWidth;
    }
    factor = factor / tmpFact;
    y = Math.round(y / tmpFact);
    x = Math.round(x / tmpFact);
  }
  if (h > imgMaxHeight) {
    tmpFact = h/imgMaxHeight;
    w = Math.round(w / tmpFact); 
    h = imgMaxHeight;
    factor = factor / tmpFact;
    y = Math.round(y / tmpFact);
    x = Math.round(x / tmpFact);
  }
  if (w > imgMaxWidth) {
    tmpFact = w/imgMaxWidth;
    h = Math.round(h / tmpFact);
    w = imgMaxWidth;
    factor = factor / tmpFact;
    y = Math.round(y / tmpFact);
    x = Math.round(x / tmpFact);
  }
  /*
  var output = new Array();
  output['X'] = x;
  output['Y'] = y;
  output['W'] = w;
  output['H'] = h;
  output['URL'] = url;
  output['Fact'] = factor;
  output['Smooth'] = smoo;
  output['Contrast'] = contr;
  output['CThreshold'] = cThres;
  output['OrigW'] = origW;
  output['OrigH'] = origH;
  */
  return "X="+x+"&Y="+y+"&W="+w+"&H="+h+"&URL="+url+"&Fact="+factor+"&Smooth="+smoo+"&Contrast="+contr+"&CThreshold="+cThres+"&OrigW="+origW+"&OrigH="+origH;
  //return output;
}


function printHandler(mode) {
  try {
    var imgMode;
    if(mode == "PrintImage" || mode == "PrintImageAndPartList" || mode == "PrintImageAndSelectedParts") imgMode = "single";
    else if(mode == "PrintCutout" || mode == "PrintCutoutAndPartList" || mode == "PrintCutoutAndSelectedParts") imgMode = "cutout";
    else if(mode == "PrintAllImages" || mode == "PrintAllImagesAndPartList" || mode == "PrintAllImagesAndSelectedParts") imgMode = "all";
    else imgMode = null;
    
    belenusHome.WM.openWindow("splPrintPopup");
    belenusHome.WM.getWindowReference("splPrintPopup").document.open();
    belenusHome.WM.getWindowReference("splPrintPopup").document.write('<html><head>');
    belenusHome.includeCSS(belenusHome.WM.getWindowReference("splPrintPopup"),"custom/print_spl.css");
    belenusHome.WM.getWindowReference("splPrintPopup").document.write('<scri'+'pt type="text/javascript">function init(evt, innerWidth, innerHeight, win) { setSVG(document.getElementById(\'SVGView\'));}</'+'script>');
    belenusHome.WM.getWindowReference("splPrintPopup").document.write('<title>'+belenusHome.getPrintLabel(getProperty("Tree","CurrentTreePath",null))+'</title></head>');
    belenusHome.WM.getWindowReference("splPrintPopup").document.write('<body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0" style="cursor:wait" onload="document.getElementsByTagName(\'body\')[0].style.cursor=\'auto\';document.getElementById(\'pleaseWait\').style.display=\'none\';document.getElementById(\'printBtn\').removeAttribute(\'disabled\');">');
    
    // please wait text...
    belenusHome.WM.getWindowReference("splPrintPopup").document.write('<div id="pleaseWait">'+belenusHome.ld['print_pleaseWait']+'</div>');
    // ~~~~~~~~~~
    
    belenusHome.WM.getWindowReference("splPrintPopup").document.write('<b><font size="3" face="Arial Unicode MS,Arial,Sans-Serif">'+belenusHome.getPrintLabel(getProperty("Tree","CurrentTreePath",null))+'</font></b><br>');  
    if(belenusHome.showNoteFieldInPrint) {
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('<textarea id="noteInput" rows="5" cols="80"></textarea><input align="top" type="button" id="printBtn" disabled onclick="document.getElementById(\'noteDisplay\').innerHTML = document.getElementById(\'noteInput\').value.replace(/\\n/g,\'<br>\');print();close();" value="'+belenusHome.ld["printIt"]+'"></input>');
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('<div id="noteDisplay"></div>');
    } else {
	    belenusHome.WM.getWindowReference("splPrintPopup").document.write('<input style="vertical-align:top;float:left;" id="printBtn" type="button" disabled onclick="print();setTimeout(\'close();\',500)" value="'+belenusHome.ld["printIt"]+'"></input>');
    }
  
    var imageList = new Array();
    if(imgMode == "all") {
      var imgList = getProperty("Global","AllImages",null);
      var image = 0;
      while(getQueryField(imgList,"URL"+image)) {
      	var currentMIMEType = getQueryField(imgList,"MIMEType"+image);
        if(currentMIMEType == "image/png" || currentMIMEType == "image/jpeg" || currentMIMEType == "image/jpg" || currentMIMEType == "image/gif") {
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<hr>');
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<img src="'+getQueryField(imgList,"URL"+image++)+'" width="100%"></img>');
        } else if(getQueryField(imgList,"MIMEType"+image) == "image/svg+xml") {
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<hr>');
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<embed id="SVGView" src="'+getQueryField(imgList,"URL"+image++)+'" type="image/svg+xml" pluginspace="http://www.adobe.com/svg/viewer/install/" width="720" height="710"></embed>');
        } else if(getQueryField(imgList,"MIMEType"+image) == "image/tiff") {
  
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<hr>');
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<applet archive="core.jar,imageview.jar,tiff.jar" codebase="." code="com.belenus.interparts.applets.DrawingApplet" width="712" height="440" hspace="0" vspace="0" align="center">');
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="url" value="'+getQueryField(imgList,"URL"+image++)+'">');
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="factor" value="0.0">');
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('</applet>');
       
        } else {
	        belenusHome.WM.getWindowReference("splPrintPopup").document.write('unsupported image');
        }
      }
    } else if(imgMode == "single" || imgMode == "cutout") {
      var paramArr = queryStringToArray(getProperty("ImageView","CurrentState",""));
      if(paramArr['MIMEType'] == "image/svg+xml") {
      
          //////////////////////////////////////////////////
         //SVG SVG SVG SVG SVG SVG SVG SVG //
        ////////////////////////////////////////////////
        svgData = queryStringToArray(calculateSVGImage(paramArr['URL'],paramArr['W'],paramArr['H'],paramArr['TransX'],paramArr['TransY'],paramArr['Scale']));
        if(imgMode == "cutout") {
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('<embed id="SVGView" src="'+paramArr['URL']+'" type="image/svg+xml" pluginspace="http://www.adobe.com/svg/viewer/install/" width="'+svgData['W']+'" height="'+svgData['H']+'"></embed>');
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('<scri'+'pt type="text/javascript">');
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('function setSVG(it) {it.getSVGDocument().rootElement.currentScale='+svgData['Scale']+';it.getSVGDocument().rootElement.currentTranslate.y='+svgData['Y']+'; it.getSVGDocument().rootElement.setAttribute("preserveAspectRatio", "xMidYMid meet"); it.getSVGDocument().rootElement.currentTranslate.x='+svgData['X']+'; it.getSVGDocument().rootElement.setAttribute("zoomAndPan", "disable");}');
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('</'+'script>');
        } else if(imgMode == "single") {
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('<embed id="SVGView" src="'+paramArr['URL']+'" type="image/svg+xml" pluginspace="http://www.adobe.com/svg/viewer/install/" width="'+svgData['W']+'" height="'+svgData['H']+'"></embed>');      
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('<scri'+'pt type="text/javascript">');
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('function setSVG(it) { it.getSVGDocument().rootElement.setAttribute("preserveAspectRatio", "xMidYMid meet"); it.getSVGDocument().rootElement.setAttribute("zoomAndPan", "disable");}');
          belenusHome.WM.getWindowReference("splPrintPopup").document.writeln('</'+'script>');        
        }
        
      } else if(paramArr['MIMEType'] == "application/x-hd3") {
        if(imgMode == "single") {
          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<tr><td><img src="'+paramArr['URL']+'" width="100%"></td></tr>');
        } else if(imgMode == "cutout") {
          var imgInfo = queryStringToArray(calculatePNGImage(paramArr['URL'], paramArr['X'], paramArr['Y'], paramArr['W'], paramArr['H'], paramArr['Factor'], paramArr['Contrast'], paramArr['CThreshold'], paramArr['Smooth'], paramArr['OrigW'], paramArr['OrigH']));
          if(belenusHome.browserName == "Netscape" || belenusHome.browserName == "Mozilla") { // embed applet
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('<applet archive="core.jar,imageview.jar,png.jar" codebase="." code="com.belenus.interparts.applets.DrawingApplet" width="'+parseInt(imgInfo['W'])+'" height="'+parseInt(imgInfo['H'])+'" hspace="0" vspace="0" align="center">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="url" value="'+paramArr['URL']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="x" value="'+parseInt(imgInfo['X'])+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="y" value="'+parseInt(imgInfo['Y'])+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="factor" value="'+parseFloat(imgInfo['Fact'])+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="contrast" value="'+imgInfo['Contrast']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="cThreshold" value="'+imgInfo['CThreshold']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="smooth" value="'+imgInfo['Smooth']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('</applet>');
          } else {
            var x = -parseInt(imgInfo['X']);
            var y = -parseInt(imgInfo['Y']);
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('\n\n<div style="clip:rect(0px '+parseInt(imgInfo['W'])+'px '+parseInt(imgInfo['H'])+'px 0px);left:0px;top:20px;width:'+parseInt(imgInfo['W'])+'px;height:'+parseInt(imgInfo['H'])+'px;overflow:hidden;">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('\n <img src="'+paramArr['URL']+'" border="0" id="picture" name="picture" ');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write(' style="position:absolute;left:'+x+'px;top:'+y+'px;width:'+imgInfo['OrigW']*(parseFloat(imgInfo['Fact'])/1)+'px;height:'+imgInfo['OrigH']*(parseFloat(imgInfo['Fact'])/1)+'px">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('\n</div>\n\n');
          }
        }
      } else if(paramArr['MIMEType'] == "image/tiff") {
          var imgInfo = queryStringToArray(calculatePNGImage(paramArr['URL'], paramArr['X'], paramArr['Y'], paramArr['W'], paramArr['H'], paramArr['Factor'], paramArr['Contrast'], paramArr['CThreshold'], paramArr['Smooth'], paramArr['OrigW'], paramArr['OrigH']));
          if(imgMode == "cutout") {
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('<applet archive="core.jar,imageview.jar,tiff.jar" codebase="." code="com.belenus.interparts.applets.DrawingApplet" width="'+parseInt(imgInfo['W'])+'" height="'+parseInt(imgInfo['H'])+'" hspace="0" vspace="0" align="center">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="url" value="'+paramArr['URL']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="x" value="'+parseInt(imgInfo['X'])+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="y" value="'+parseInt(imgInfo['Y'])+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="factor" value="'+parseFloat(imgInfo['Fact'])+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="contrast" value="'+imgInfo['Contrast']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="cThreshold" value="'+imgInfo['CThreshold']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="smooth" value="'+imgInfo['Smooth']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('</applet>');
          } else if(imgMode == "single") {
			imgInfo = queryStringToArray(calculatePNGImage(paramArr['URL'], paramArr['X'], paramArr['Y'], paramArr['OrigW'], paramArr['OrigH'], 1, paramArr['Contrast'], paramArr['CThreshold'], paramArr['Smooth'], paramArr['OrigW'], paramArr['OrigH']));
			belenusHome.WM.getWindowReference("splPrintPopup").document.write('<applet archive="core.jar,imageview.jar,tiff.jar" codebase="." code="com.belenus.interparts.applets.DrawingApplet" width="'+imgInfo['W']+'" height="'+imgInfo['H']+'" hspace="0" vspace="0" align="center">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="url" value="'+paramArr['URL']+'">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('  <param name="factor" value="0.0">');
            belenusHome.WM.getWindowReference("splPrintPopup").document.write('</applet>');          
          }
      } else {  
		var currentMIMEType = paramArr['MIMEType'];
        if(currentMIMEType == "image/png" || currentMIMEType == "image/jpeg" || currentMIMEType == "image/jpg" || currentMIMEType == "image/gif") {  
        belenusHome.WM.getWindowReference("splPrintPopup").document.writeln(' ');
        belenusHome.WM.getWindowReference("splPrintPopup").document.writeln(' ');
	        if(imgMode == "single") {
	          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<tr><td><img src="'+paramArr['URL']+'" width="100%"></td></tr>');
	        } else if(imgMode == "cutout") {       
                var imgInfo = queryStringToArray(calculatePNGImage(paramArr['URL'], paramArr['X'], paramArr['Y'], paramArr['W'], paramArr['H'], paramArr['Factor'], paramArr['Contrast'], paramArr['CThreshold'], paramArr['Smooth'], paramArr['OrigW'], paramArr['OrigH'])); 
	            var x = -parseInt(imgInfo['X']);
	            var y = -parseInt(imgInfo['Y']);
	            belenusHome.WM.getWindowReference("splPrintPopup").document.write('\n\n<div style="clip:rect(0px '+parseInt(imgInfo['W'])+'px '+parseInt(imgInfo['H'])+'px 0px);left:0px;top:20px;width:'+parseInt(imgInfo['W'])+'px;height:'+parseInt(imgInfo['H'])+'px;overflow:hidden;">');
	            belenusHome.WM.getWindowReference("splPrintPopup").document.write('\n <img src="'+paramArr['URL']+'" border="0" id="picture" name="picture" ');
	            belenusHome.WM.getWindowReference("splPrintPopup").document.write(' style="position:absolute;left:'+x+'px;top:'+y+'px;width:'+imgInfo['OrigW']*(parseFloat(imgInfo['Fact'])/1)+'px;height:'+imgInfo['OrigH']*(parseFloat(imgInfo['Fact'])/1)+'px">');
	            belenusHome.WM.getWindowReference("splPrintPopup").document.write('\n</div>\n\n');        
	        }
	    belenusHome.WM.getWindowReference("splPrintPopup").document.writeln(' ');
	    belenusHome.WM.getWindowReference("splPrintPopup").document.writeln(' ');
        }    
      }
    }
  
    if(imgMode != null)  belenusHome.WM.getWindowReference("splPrintPopup").document.write('<hr>');
  
      ////////////////////////////////////////////////////////////
     //spl part ////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////
    var splMode;
    if(mode == "PrintImageAndPartList" || mode == "PrintCutoutAndPartList" || mode == "PrintAllImagesAndPartList" || mode == "PrintPartList") splMode = "AllParts";
    else if(mode == "PrintImageAndSelectedParts" || mode == "PrintCutoutAndSelectedParts" || mode == "PrintAllImagesAndSelectedParts" || mode == "PrintSel") splMode = "SelectedParts";
    else splMode = null;
    
    if(splMode != null) {
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('<table border="1" class="ip_table" bordercolor="#000000" cellpadding="2" cellspacing="0">');    
    
      var tableEntries = getProperty("Table",splMode);
      var paramArr = queryStringToArray(tableEntries);
      var line = 0;
      tableEntries = new Array();
      while(paramArr['ItemPath'+line]) {
        tableEntries[tableEntries.length] = queryStringToArray(getProperty("Table","PartData","ItemPath="+paramArr['ItemPath'+line++]));
      }
      
      var printableColumns = getProperty("Table","PrintableColumns");
      var visibleColumns = new Array();
      printableColumns = queryStringToArray(printableColumns)

      var tableHeaders = new Array();
      var i = 0;
      while(printableColumns["ColumnName"+i]) {
        tableHeaders[tableHeaders.length] = getProperty("Table","ColumnLabel","ColumnName="+printableColumns["ColumnName"+i]);
        visibleColumns[i] = printableColumns["ColumnName"+i++];
      }
      
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('<thead><tr class="ip_header">');
      for(var th in tableHeaders) {
      	if(printableColumns["HeaderType"+th] == "String")
        belenusHome.WM.getWindowReference("splPrintPopup").document.write('<th>'+tableHeaders[th]+'&nbsp;</th>');
      	else if(printableColumns["HeaderType"+th] == "Icon")
      	belenusHome.WM.getWindowReference("splPrintPopup").document.write('<th><img src="'+tableHeaders[th]+'"></th>');      		
      }
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('</tr></thead>');
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('<tbody>');
      for(tr in tableEntries) {
        var rowClass = (tr % 2) ? 'class="ip_row_0"' :'class="ip_row_1"'
        belenusHome.WM.getWindowReference("splPrintPopup").document.write('<tr '+rowClass+'>');
        for(td in tableHeaders) {
          
          if(tableEntries[tr][visibleColumns[td]] && tableEntries[tr][visibleColumns[td]] != "")
	          belenusHome.WM.getWindowReference("splPrintPopup").document.write('<td>'+tableEntries[tr][visibleColumns[td]].replace(/\n/g,"<br>").replace(/ /g, "&nbsp;")+'&nbsp;</td>');
          else belenusHome.WM.getWindowReference("splPrintPopup").document.write('<td>&nbsp;</td>');
        }
        belenusHome.WM.getWindowReference("splPrintPopup").document.write('</tr>');
      }
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('</tbody>');
      belenusHome.WM.getWindowReference("splPrintPopup").document.write('</table>');
    }
    
    belenusHome.WM.getWindowReference("splPrintPopup").document.write('</body></html>');
    belenusHome.WM.getWindowReference("splPrintPopup").document.close();       
  } catch (e) { alert("\t\tPrintHandler\nError: "+e.message) } 
}

function belSearchForSingleID() {
  if(belenusHome.oci_interface == true) {
    belenusHome.document.getElementById('InvisibleFrame').src='oci/search_for_single_id.html';
  }
}

function belLocateInCatalog(treepath, itemlistURL, itemContextID) {
	//alert("belLocateIn...:\n\ntreepath:\t"+treepath+"\nitemlistURL:\t"+itemlistURL+"\nitemContextID:\t"+itemContextID);
  belenusHome.eventHandler("OpenLink","URL=parts:"+treepath);
  top.status = "belLocateInCatalog() is antiquated";
}

function setShowImageState(value) {
  if(belenusHome.showImage == "never") belenusHome.showImageState = "onlyTable";
  else if(value == "onlyTable") belenusHome.showImageState = "onlyTable";
  else if(value == "imageAndTable") belenusHome.showImageState = "imageAndTable";
  else if(value == "onlyImage") belenusHome.showImageState = "onlyImage";
}

function id(doc,element) {
	return doc.getElementById(element);
}

if(keepServerSessionAlive) {
	if(belenusHome.interpartsVersion == "dynamic") {
		setInterval('document.getElementById("InvisibleFrame").setAttribute("src","stayloggedin.jsp")',240000);
	}
}

function hoverHelper(id) {
   var itemPath = getProperty("Global","PartsByField","Field=posno&Value="+id);
   clearTimeout(t2);clearTimeout(t3);
   if(itemPath != null && itemPath != '' && itemPath != 'null') {
      if(itemPath.indexOf("ItemPath0")!=-1)
	  t2 = setTimeout('sendMessage("Table","SelectParts","'+itemPath+'&Exclusive=true");',5);
	  else if(itemPath.indexOf("DeviceID")!=-1) {
	     var ItemPath0 = getQueryField(itemPath, "DeviceID")+"/"+getQueryField(itemPath, "ItemContextID");
		 t3 = setTimeout('sendMessage("Table","SelectParts","ItemPath0='+ItemPath0+'&Exclusive=true");',9);
	  }
   }
   return;
}