var idPrefix = null;
var zoomScalar = 1.25;
var strokeWidth = 2; // recalculated in function r(...)

/** holds the currently selected hotspot ids */
var allHotspots = new Array();
var selectedHotspots = new Array();
var svgDocument = null;
var de = null;

var origX = 0.0;
var origY = 0.0;
var origW = 0.0;
var origH = 0.0;
var origAspectR = 0.0;

var innerW = -1;
var innerH = -1;
var innerAspectR = 0.0;

var svgToClientFac = 0.0;

var svgLoaded=false;

function resetSVG() {
  svgLoaded=false;
  allHotspots = new Array();
  selectedHotspots = new Array();
  origX = 0.0;
  origY = 0.0;
  origW = 0.0;
  origH = 0.0;
  origAspectR = 0.0;
  innerW = -1;
  innerH = -1;
  innerAspectR = 0.0;
  svgToClientFac = 0.0;
}
function domIdToBelId(domId) {
  if (idPrefix != null && idPrefix.length > 0) {
    return domId.substring(idPrefix.length);
  } else return domId;
}

function belIdToDomId(belId) {
	if (idPrefix != null && idPrefix.length > 0) {
		return idPrefix + belId;
	} else return belId;
}

function getSVGProperty() {
  var properties = new Array();
  properties['url'] = document.getElementById("SVGView").getSrc();
  properties['w'] = innerW;
  properties['h'] = innerH;
  properties['transX'] = (de) ? de.currentTranslate.x : origX;
  properties['transY'] = (de) ? de.currentTranslate.y : origY;
  properties['scale'] = (de) ? de.currentScale : origAspectR;
  
  return "URL="+properties['url']+"&W="+properties['w']+"&H="+properties['h']+"&TransX="+properties['transX']+"&TransY="+properties['transY']+"&Scale="+properties['scale'];
}

/*
function stopAnimations() {
	for (i = selectedHotspots.length - 1; i >= 0; i--) {
    var curElem = svgDocument.getElementById(belIdToDomId(selectedHotspots[i]));
    if (curElem != null) {
	    curElem.getLastChild().endElement();
    }
	}
}
function startAnimations() {
	for (i = selectedHotspots.length - 1; i >= 0; i--) {
    var curElem = svgDocument.getElementById(belIdToDomId(selectedHotspots[i]));
    if (curElem != null) {
	    curElem.getLastChild().beginElement();
    }
	}
}
*/
function sz(y, z) {
  if(z<1)z=1;
	var delay = 500;
	de.currentTranslate.y = y;
  if (de.currentScale != z) {
	  if (de.currentTranslate.y != y) setTimeout("de.currentScale = " + z, delay);
	  else de.currentScale = z;
  }
}

function setNewXYZ(x, y, z) {

//alert("x:"+x+"\ny:"+y+"\nz:"+z);
if(z<1){z=1;x=0;y=0;};
	var delay = 500;
	if (de.currentTranslate.x != x) de.currentTranslate.x = x;
	if (de.currentTranslate.y != y) {
	  if (de.currentTranslate.x != x) {
		  setTimeout("sz(" + y + "," + z + ")", delay);
		  return;
	  } else de.currentTranslate.y = y;
  }
  if (de.currentScale != z) {
	  if (de.currentTranslate.x != x || de.currentTranslate.y != y) {
		  setTimeout("de.currentScale = " + z, delay);
		  return;
	  } else {
      de.currentScale = z;
      return; /*de.currentScale = z;*/ 
    }
  }
}
/*
function setNewXYZ(x, y, z) {
	var delay = 500;
	if (de.currentScale != z) de.currentScale = z;
	if (de.currentTranslate.y != y) {
	  if (de.currentScale != z) setTimeout("de.currentTranslate.y = " + y, delay);
	  else de.currentTranslate.y = y;
  }
  if (de.currentTranslate.x != x) {
	  if (de.currentScale != z || de.currentTranslate.y != y) setTimeout("de.currentTranslate.x = " + x, delay);
	  else de.currentTranslate.x = x;
  }
}

*/

function deselectHotspot(querystring) {
  var id = belenusHome.getQueryField(querystring, "HotspotID");
  var curElem = svgDocument.getElementById(belIdToDomId(id));
  var curAnim = svgDocument.getElementById(belIdToDomId(id + "_anim"));
  if (curElem != null && curElem.hasChildNodes()) curElem.removeChild(curAnim);
  for (var i = 0; i < selectedHotspots.length; i++)
    if (id == selectedHotspots[i]) {
      if (i == 0) selectedHotspots.shift();
      else if (i == selectedHotspots.length - 1) selectedHotspots.pop();
      else selectedHotspots = selectedHotspots.slice(0, i).concat(selectedHotspots.slice(i + 1, selectedHotspots.length));
      break;
    }
}
 

/**
 * is called from Table (Itemlist)
 * Table => Drawing
 */
function selectedHotspot(querystring) {
	if(!svgLoaded) {
		setTimeout("selectedHotspot('"+querystring+"');",371);
		return;
	}
//     alert("select: " + querystring);
	var id = belenusHome.getQueryField(querystring, "HotspotID");
  var exclusive = belenusHome.getQueryField(querystring, "Exclusive") == "true";
  // UNSELECT SELECTED HOTSPOT(S)
  if(exclusive) {
    for (i = selectedHotspots.length - 1; i >= 0; i--) {
      var deselID = selectedHotspots[i];
      var curElem = svgDocument.getElementById(belIdToDomId(deselID));
      var curAnim = svgDocument.getElementById(belIdToDomId(deselID + "_anim"));
      if (curElem != null && curElem.hasChildNodes()) curElem.removeChild(curAnim);
    }
    selectedHotspots = new Array();
  }

  
  trys = 0;
  try {
  var newSel = svgDocument.getElementById(id);
    if(newSel == null) {
      setTimeout('selectedHotspot("'+querystring+'")',333);
    }
  } catch (e) {
    setTimeout('selectedHotspot("'+querystring+'")',300);
    //top.status = "TRYS:"+ ++trys;
    return;
  } 
  //if (newSel == null) return;
  
  
  var rectGroup = newSel;


  var animNode = svgDocument.createElement('animate');
  animNode.setAttribute('id', id + "_anim");
  //animNode.setAttribute('attributeName', "opacity");
  animNode.setAttribute('attributeName', "fill");
  //animNode.setAttribute('attributeType', "CSS");
  animNode.setAttribute('attributeType', "XML");
  //animNode.setAttribute('values', "1;.75;.5;.25;0;.25;.5;.75;1");
  animNode.setAttribute('values', "#ff0000;#ff0000;#ff0000;#ff0000;#ff3f3f;#ff7e7e;#ffbdbd;#ffffff;#ffbdbd;#ff7e7e;#ff3f3f");
  //animNode.setAttribute('from', "#ff0000");
  //animNode.setAttribute('to', "#ffffff");
  
  animNode.setAttribute('dur',"1s");
  animNode.setAttribute('repeatCount',"indefinite");

  if(newSel == null) { return; }
  else newSel.appendChild(animNode);

  selectedHotspots[selectedHotspots.length] = id;

  var bb = rectGroup.getBBox();
  var bbX = bb.x;
  var bbY = bb.y;
  var bbW = bb.width;
  var bbH = bb.height;
  var bbMX = bbX + bbW;
  var bbMY = bbY + bbH;
  try {
  for (i = selectedHotspots.length - 1; i >= 0; i--) {
    var curElem = svgDocument.getElementById(belIdToDomId(selectedHotspots[i]));
    var curBB = curElem.getBBox();
    var curBBX = curBB.x - strokeWidth;
    var curBBY = curBB.y - strokeWidth;
    var curBBMX = curBBX + curBB.width + strokeWidth + strokeWidth;
    var curBBMY = curBBY + curBB.height + strokeWidth + strokeWidth;
    if (curBBX < bbX) {
      bbX = curBBX;
      bbW = bbMX - bbX;
    }
    if (curBBY < bbY) {
      bbY = curBBY;
      bbH = bbMY - bbY;
    }
    if (curBBMX > bbMX) {
      bbW = curBBMX - bbX;
      bbMX = curBBMX;
    }
    if (curBBMY > bbMY) {
      bbH = curBBMY - bbY;
      bbMY = curBBMY;
    }
  }
  } catch(e) {
  }
  bb.x = bbX;
  bb.y = bbY;
  bb.width = bbW;
  bb.height = bbH;

  var selPixelBBoxX = (bb.x - origX) * de.currentScale / svgToClientFac;
  var selPixelBBoxW = bb.width * de.currentScale / svgToClientFac;
  var selPixelBBoxY = (bb.y - origY) * de.currentScale / svgToClientFac;
  var selPixelBBoxH = bb.height * de.currentScale / svgToClientFac;
  
  var curPixelTransX = de.currentTranslate.x;
  var xCenterPixelOffset = (innerW - origW / svgToClientFac) * de.currentScale / 2;
  if (innerAspectR > origAspectR) curPixelTransX += xCenterPixelOffset; // because xMidYMid centers the image horizontally
  
  var curPixelTransY = de.currentTranslate.y;
  var yCenterPixelOffset = (innerH - origH / svgToClientFac) * de.currentScale / 2;
  if (innerAspectR < origAspectR) curPixelTransY += yCenterPixelOffset; // because xMidYMid centers the image vertically
  
  var xx = de.currentTranslate.x;
  var yy = de.currentTranslate.y;
  var zz = de.currentScale;

  if (selPixelBBoxW > innerW) {
	  zz *= innerW / selPixelBBoxW;
  }
  if (selPixelBBoxH > innerH) {
	  var tmp = zz * innerH / selPixelBBoxH;
	  if (tmp < zz) zz = tmp;
  }
  var oldNewFac = de.currentScale / zz;

  if (zz < de.currentScale) { // we must shrink the image => recalculate vars
    selPixelBBoxX = (bb.x - origX) * zz / svgToClientFac;
    selPixelBBoxW = bb.width * zz / svgToClientFac;
    selPixelBBoxY = (bb.y - origY) * zz / svgToClientFac;
    selPixelBBoxH = bb.height * zz / svgToClientFac;
  
    curPixelTransX = de.currentTranslate.x;
    xCenterPixelOffset = (innerW - origW / svgToClientFac) * zz / 2;
    if (innerAspectR > origAspectR) curPixelTransX += xCenterPixelOffset; // because xMidYMid centers the image horizontally
  
    curPixelTransY = de.currentTranslate.y;
    yCenterPixelOffset = (innerH - origH / svgToClientFac) * zz / 2;
    if (innerAspectR < origAspectR) curPixelTransY += yCenterPixelOffset; // because xMidYMid centers the image vertically
  }
//  alert(selPixelBBoxX + " " + de.currentTranslate.x + " " + curPixelTransX + " | " + zz + " " + de.currentScale); 
  if (selPixelBBoxX < -curPixelTransX / oldNewFac) { // bounding box exceeds left border?
	  xx = -selPixelBBoxX;
	  if (innerAspectR > origAspectR) xx -= xCenterPixelOffset;
  } else if (selPixelBBoxX + selPixelBBoxW > innerW - curPixelTransX / oldNewFac) { // bounding box exceeds right border?
	  xx = innerW - (selPixelBBoxW + selPixelBBoxX);
	  if (innerAspectR > origAspectR) xx -= xCenterPixelOffset;
  }

  if (selPixelBBoxY < -curPixelTransY / oldNewFac) { // bounding box exceeds top border?
	  yy = -selPixelBBoxY;
	  if (innerAspectR < origAspectR) yy -= yCenterPixelOffset;
  } else if (selPixelBBoxY + selPixelBBoxH > innerH - curPixelTransY / oldNewFac) { // bounding box exceeds bottom border?
	  yy = innerH - (selPixelBBoxH + selPixelBBoxY);
	  if (innerAspectR < origAspectR) yy -= yCenterPixelOffset;
  }
  setNewXYZ(xx, yy, zz);
}
function zoomIn() {
	var nz = de.currentScale * zoomScalar;
	if (nz > 16.0) nz = 16.0;
	var nx = (de.currentTranslate.x - (innerW / 2)) * zoomScalar + (innerW / 2);
	var ny = (de.currentTranslate.y - (innerH / 2)) * zoomScalar + (innerH / 2);
	setNewXYZ(nx, ny, nz);
}
function zoomOut() {
	var nz = de.currentScale / zoomScalar;
	var nx = (de.currentTranslate.x - (innerW / 2)) / zoomScalar + (innerW / 2);
	var ny = (de.currentTranslate.y - (innerH / 2)) / zoomScalar + (innerH / 2);
	setNewXYZ(nx, ny, nz);
}
function zoomOrig() {
	setNewXYZ(0,0,1);
	belenusHome.sendMessage("Toolbar","SetButtonStates","Name0=FitToWin&State0=Disabled&Name1=ZoomOut&State1=Disabled");
}
function z(evt) {
	if (de.currentScale != 1.0 || de.currentTranslate.x != 0 || de.currentTranslate.y != 0) {
    belenusHome.sendMessage("Toolbar","SetButtonStates","Name0=FitToWin&State0=Enabled&Name1=ZoomOut&State1=Enabled");
    if(de.currentScale < 4.0) belenusHome.sendMessage("Toolbar","SetButtonStates","Name0=ZoomIn&State0=Enabled");
    else belenusHome.sendMessage("Toolbar","SetButtonStates","Name0=ZoomIn&State0=Disabled");
	} else {
		belenusHome.sendMessage("Toolbar","SetButtonStates","Name0=ZoomIn&State0=Enabled&Name1=FitToWin&State1=Disabled");
  }
}
function s(evt) {
  if(de.currentTranslate.x != 0 || de.currentTranslate.y != 0)
    belenusHome.sendMessage("Toolbar","SetButtonStates","Name0=FitToWin&State0=Enabled");
  else
    belenusHome.sendMessage("Toolbar","SetButtonStates","Name0=FitToWin&State0=Disabled");
}

function r(evt, innerWidth, innerHeight) {
	innerW = innerWidth;
	innerH = innerHeight;
	innerAspectR = innerW / innerH;
	svgToClientFac = (origAspectR > innerAspectR) ? origW / innerW : origH / innerH;
  svgToClientFac = svgToClientFac.toPrecision(4);
	strokeWidth = svgToClientFac;
}

function init(evt, innerWidth, innerHeight) {
	svgLoaded=true;
  svgDocument = document.getElementById("SVGView").getSVGDocument();
   de = svgDocument.rootElement;
   de.setAttribute("preserveAspectRatio", "xMidYMid meet");
		var vb = de.getAttribute("viewBox");
  if (vb != "") {
	  var vbArr = vb.split(/\s*,\s*|\s+/);
	  origX = parseFloat(vbArr[0]);
	  origY = parseFloat(vbArr[1]);
	  origW = parseFloat(vbArr[2]);
	  origH = parseFloat(vbArr[3]);
	  origAspectR = origW / origH;
  }
	var posnos = de.getElementById("Positionsnummern");
  if(posnos) {
    	var arr = posnos.getElementsByTagName("g");
  
      var hsStr = "";
      var hsStrCount = 0;
    	for (var i = 0; i < arr.length; i++) {
    	  var id = arr.item(i).getAttribute("id");
	  if (id != null) {
          allHotspots[allHotspots.length] = domIdToBelId(id);
          if (hsStrCount > 0) hsStr += "&";
          hsStr += "Hotspot" + hsStrCount++ + "=" + escape(domIdToBelId(id));
        }
    	}
  belenusHome.eventHandler("HotspotsLoadingFinished", "Sender=ImageView&ImageID=" +
	escape(currentImageID) + "&Hotspots=" + escape(hsStr));
  }
  r(evt, innerWidth, innerHeight); // SET VARIABLES
}

// click
function c(evt) {
  var dblClick = evt.getDetail() == 2 ? true : false;
  var hotspot = evt.getTarget().parentNode;
  var id = domIdToBelId(hotspot.getAttribute('id'));
  selectedHotspot("Exclusive=true&HotspotID=" + escape(id));
  belenusHome.eventHandler(dblClick==true ? "HotspotDblClicked" : "HotspotsSelected", "Exclusive=true&HotspotID0=" + escape(id));
}

// mouse over
function mov(evt) {
  return;
  var children = evt.getTarget().parentNode.parentNode.childNodes;
  for (var i = 0; i < children.length; i++) {
	  if (children.item(i).nodeType == 1 /*Node.ELEMENT_NODE*/ && children.item(i).getAttribute('id') == 'id-') {
		  if (children.item(i).getAttribute("class") == "fil0") children.item(i).setAttribute("class", "mover");
		  break;
	  }
  }
}

// mouse out
function mou(evt) {
  return;
  var children = evt.getTarget().parentNode.parentNode.childNodes;
  for (var i = 0; i < children.length; i++) {
	  if (children.item(i).nodeType == 1 /*Node.ELEMENT_NODE*/ && children.item(i).getAttribute('id') == 'id-') {
		  if (children.item(i).getAttribute("class") == "mover") children.item(i).setAttribute("class", "fil0");
		  break;
	  }
  }
}
