var svgNS = "http://www.w3.org/2000/svg";
var txt;
var root = document.rootElement;
var pt1 = root.createSVGPoint();
var pt2 = root.createSVGPoint();
var pt3 = root.createSVGPoint();
var pt4 = root.createSVGPoint();
var rect = document.createElementNS(svgNS, "path");
rect.setAttribute("fill", "#444");
root.setAttribute("onmouseover","highlight(evt)");
root.setAttribute("onmouseout","unhighlight(evt)");

var isAdobe = false;
try {
  var vStr = getSVGViewerVersion();
  var idx = vStr.indexOf("; ");
  if (idx != -1) {
    var ver = parseFloat(vStr.substring(idx+2));
    if (ver <= 3)
      isAdobe = true;
  }
} catch (x) { }

function screenCTM(elem) {
  if (!isAdobe) 
    return elem.getScreenCTM();
  if (elem == root) {
    var scale = root.currentScale;
    var trans = root.currentTranslate;
    var ret = root.createSVGMatrix();
    ret.scale(scale);
    ret.translate(trans.x, trans.y);
    return ret;
  }

  var pMat = screenCTM(elem.parentNode);
    
  var eMat = elem.getCTM();
  if (eMat == null) return pMat;
  eMat = eMat.multiply(pMat);
  return eMat;
}

function transformToElement(from, to) {
  if (!isAdobe) 
    return from.getTransformToElement(to);
  var m1 = screenCTM(from);
  var m2 = screenCTM(to);
  return m1.multiply(m2.inverse());
}


function highlight(evt) {
  var tgt  = evt.target;
  if ((!tgt) || (tgt == rect) || (tgt == txt)) return;
  while (tgt.localName == "tspan") {
    tgt = tgt.parentNode;
    if (!tgt) return;
  }
  if (tgt.localName != "text") return;

  txt = tgt;
  if (!txt.getAttribute("class").match("highlight")) return;
  var bbox = txt.getBBox();
  var mat = transformToElement(txt, txt.parentNode);
  rect.setAttribute("visibility", "visible");
  pt1.x = bbox.x-5;             pt1.y = bbox.y-5;
  pt2.x = bbox.x+bbox.width+10; pt2.y = bbox.y-5;
  pt3.x = bbox.x+bbox.width+10; pt3.y = bbox.y+bbox.height+10;
  pt4.x = bbox.x-5;             pt4.y = bbox.y+bbox.height+10;
  pt1 = pt1.matrixTransform(mat);
  pt2 = pt2.matrixTransform(mat);
  pt3 = pt3.matrixTransform(mat);
  pt4 = pt4.matrixTransform(mat);
  rect.setAttribute("d", 
                    "M" + pt1.x + "," + pt1.y + 
                    "L" + pt2.x + "," + pt2.y + 
                    "L" + pt3.x + "," + pt3.y + 
                    "L" + pt4.x + "," + pt4.y + "z");
  txt.parentNode.insertBefore(rect, txt);
  txt.setAttribute("style", "fill:yellow");
}

function unhighlight(evt) {
  if (evt.relatedTarget == rect) return;
  rect.setAttribute("visibility", "hidden");
  if (txt) {
    txt.setAttribute("style","");
    txt=null;
  }
}
