/***************************************
*                                      *
* Author: Antoine Quint                *
* Article: Doing that drag thang       *
* Date: 24/02/2002                     *
*                                      *
*                                      *
* 13/03/2008: Peter Weller
* 	Heavily edit combining with mapapp *
*                                      *
***************************************/

// pointer to the root of the document
var root;

// pointers to SVG elements we will access
var target;
var frame;
var bmousedown=0;
var translate = "translate(0,0)";
var scale = "scale(1)";
var scaleNumeric = 1;
var svgdoc;

var myMapApp;
var timer;
var timerMs;
var curTimer;
var outsizeWidth;
var outsizeHeight;
var origStyle;

// SVGPoint to keep track of the offset of the dragging session
var offset;

function init_nav()
{

	svgdoc = document.embeds[0].getSVGDocument();
	root = svgdoc.documentElement;
	
	root.setAttributeNS(null, "onmousedown", "onMouseDown(evt)");
	root.setAttributeNS(null, "onclick", "DoOnClick(evt)");
	root.setAttributeNS(null, "onmouseup", "onMouseUp(evt)");
//	root.setAttributeNS(null, "onmouseout", "onMouseUp(evt)");
	
	myMapApp = new mapApp();

	outsizeWidth = document.embeds[0].width;
	outsizeHeight = document.embeds[0].height;
	
	var newgroup = svgdoc.createElementNS("http://www.w3.org/2000/svg", "g");
	newgroup.setAttributeNS(null, "id", "navtarget"); 
	newgroup.setAttributeNS(null, 'viewBox', root.getAttribute('viewBox'));
	svgdoc.documentElement.appendChild(newgroup);
	
	target = root.getElementById("navtarget");
	var childNodes = root.childNodes;
	var number = childNodes.length;
	var index = 0;
	while (index<number) {
		if (childNodes.item(index).id == "navtarget")
			index = index + 1;
		else {
			var clone = childNodes.item(index).cloneNode(true);
			target.appendChild(clone);
			oldChild = childNodes.item(index);
			oldChild.parentNode.removeChild(oldChild);
			childNodes = root.childNodes;
			number = childNodes.length;
			index = 0;
			}
	}
	
	target = root.getElementById("navtarget");

	offset = root.createSVGPoint();
	

	var navrect = svgdoc.createElementNS("http://www.w3.org/2000/svg", "rect");
	navrect.setAttributeNS(null, "id", "canvas"); 
	navrect.setAttributeNS(null, "x", 0);
	navrect.setAttributeNS(null, "y", 0);
	navrect.setAttributeNS(null, "width", "100%");
	navrect.setAttributeNS(null, "height", "100%");
	navrect.setAttributeNS(null, 'viewBox', root.getAttribute('viewBox'));
	navrect.setAttributeNS(null, "opacity", "0");
	navrect.setAttributeNS(null, "fill", "green");
	navrect.setAttributeNS(null, "pointer-events", "visible");
	navrect.setAttributeNS(null, "cursor", "wait");	
	navrect.setAttributeNS(null, "onmousedown", "onMouseDown(evt)");
	navrect.setAttributeNS(null, "onmousemove", "onMouseMove(evt)");
	navrect.setAttributeNS(null, "onmouseup", "onMouseUp(evt)");
	navrect.setAttributeNS(null, "onmouseout", "onMouseUp(evt)");
	navrect.setAttributeNS(null, "onclick", "DoOnClick(evt)");
	
	
	svgdoc.documentElement.insertBefore(navrect, svgdoc.documentElement.firstChild);

	target.setAttributeNS(null, 'transform', translate + ' ' + scale);
// setting of cursor not implented in ADOBE SVG 3.0	
//	target.setAttributeNS(null, "cursor", "move");

	timer = new Timer(this); //a Timer instance for calling the functionToCall
	timerMs = 200; //a constant of this object that is used in conjunction with the timer - functionToCall is called after 200 ms	
}

// called on starting the drag
function onMouseDown(evt){
  // track the origin
  var matrix = target.getCTM();
  // get the relative position
  var mouse = getMouse(evt);
  
  var transWidth = getViewBox('navtarget','width');
  pixWidth = parseFloat(outsizeWidth); //holds width of the map in pixel coordinates
  pixHeight = parseFloat(outsizeHeight); //holds height of the map in pixel coordinates
  pixSize = transWidth / pixWidth; //size of a screen pixel in map units
	
  offset.x = matrix.e - mouse.x * pixSize;
  offset.y = matrix.f - mouse.y * pixSize;

  bmousedown=1;
	var timerEvt = {x:evt.clientX,y:evt.clientY,type:evt.type,detail:evt.detail,timeStamp:evt.timeStamp};
	curTimer = timer.setTimeout("fireFunction",timerMs,timerEvt);

}

// called on dragging
function onMouseMove(evt){


   if(bmousedown == 2){
	

	var transWidth = getViewBox('navtarget','width');
	pixWidth = parseFloat(outsizeWidth); //holds width of the map in pixel coordinates
	pixHeight = parseFloat(outsizeHeight); //holds height of the map in pixel coordinates
	pixSize = transWidth / pixWidth; //size of a screen pixel in map units
	
	// gets the pointer position
	var mouse = getMouse(evt);
	var x = Math.round(mouse.x * pixSize + offset.x);
	var y = Math.round(mouse.y * pixSize + offset.y);
	

	// updating the matrix
	translate = 'translate(' + x + ',' + y + ')';
	target.setAttributeNS(null, 'transform', translate + ' ' + scale);
	}
	
}

// called on finishing the drag and exit area
function onMouseUp(evt){

	timer.clearTimeout(curTimer);
	bmousedown=0;
	zSwap(false);
//	root.setAttributeNS(null,"cursor","move");
	
}

function pan2(k1,k2){
    svgdoc=document.embeds[0].getSVGDocument();
    root=svgdoc.documentElement();
    var old_taille=root.currentScale;
	
	var x = parseInt(getTranslate('navtarget','x'));
	var y = parseInt(getTranslate('navtarget','y'));
	var transWidth = getViewBox('navtarget','width');
	pixWidth = parseFloat(outsizeWidth); //holds width of the map in pixel coordinates
	pixHeight = parseFloat(outsizeHeight); //holds height of the map in pixel coordinates
	pixSize = transWidth / pixWidth; //size of a screen pixel in map units
	
    if (k1!=0)
        {old_x=getTranslate('navtarget','x');
        x=Math.round(parseInt((old_x)) + (k1*20 * pixSize));
    }
    else
        {old_y=parseInt(getTranslate('navtarget','y'));
        y=Math.round((old_y) +(k2*20 * pixSize));
    }

	translate = 'translate(' + x + ',' + y + ')';
	target.setAttributeNS(null, 'transform', translate + ' ' + scale);
}

function adjustView(k){
	svgdoc=document.embeds[0].getSVGDocument();
    root=svgdoc.documentElement();
    var old_taille=root.currentScale;
	
	var x = parseInt(getTranslate('navtarget','x'));
	var y = parseInt(getTranslate('navtarget','y'));
	var transWidth = getViewBox('navtarget','width');
	pixWidth = parseFloat(outsizeWidth); //holds width of the map in pixel coordinates
	pixHeight = parseFloat(outsizeHeight); //holds height of the map in pixel coordinates
	pixSize = transWidth / pixWidth; //size of a screen pixel in map units
		
//	k = k * 2;
	var NewWidth = pixWidth * (1 + k); //scaleNumeric;
	var NewHeight = pixHeight * (1 + k); //scaleNumeric;
	
	x=Math.round(x-((NewWidth - pixWidth) / 2)* pixSize);
	y=Math.round(y-((NewHeight - pixHeight) / 2)* pixSize);

	translate = 'translate(' + x + ',' + y + ')';
	target.setAttributeNS(null, 'transform', translate + ' ' + scale);
}

function zoomDoc(k){
	svgdoc=document.embeds[0].getSVGDocument();
    root=svgdoc.documentElement();
    var old_taille=root.currentScale;
	
	var x = parseInt(getTranslate('navtarget','x'));
	var y = parseInt(getTranslate('navtarget','y'));
	var transWidth = getViewBox('navtarget','width');
	pixWidth = parseFloat(outsizeWidth); //holds width of the map in pixel coordinates
	pixHeight = parseFloat(outsizeHeight); //holds height of the map in pixel coordinates
	pixSize = transWidth / pixWidth; //size of a screen pixel in map units
	
	scaleNumeric = scaleNumeric + k;
	scale = 'scale(' + (scaleNumeric) + ')';
//	translate = 'translate(' + x + ',' + y + ')';
	target.setAttributeNS(null, 'transform', translate + ' ' + scale);
}
function resetNav(){

	translate = "translate(0,0)";
	scale = "scale(1)";
	scaleNumeric = 1;
	target.setAttributeNS(null, 'transform', translate + ' ' + scale);
}

function DoOnClick(evt){

	if (evt.getDetail() ==2)
	{
	  //get current zoom and pan values
	var transx = getTranslate('navtarget','x');
	var transy = getTranslate('navtarget','y');
	var transHeight = getViewBox('navtarget','height');
	var transWidth = getViewBox('navtarget','width');
	
	// gets the pointer position
	var coords = myMapApp.calcCoord(evt, root.getElementById("canvas"));
	var x = coords.x.toFixed(1);
	var y = coords.y.toFixed(1);	

	var hisWidth = root.getAttribute('width');
	
	pixWidth = parseFloat(outsizeWidth); //holds width of the map in pixel coordinates
	pixHeight = parseFloat(outsizeHeight); //holds height of the map in pixel coordinates
	pixSize = transWidth / pixWidth; //size of a screen pixel in map units
	
	x = x * pixSize;
	x = Math.round((transWidth / 2) - x) + parseInt(transx);

	y = y * pixSize
	y = Math.round((transHeight / 2) - y) + parseInt(transy);

//	translate = 'translate(' + x + ',' + y + ')';
	
	target.setAttributeNS(null, 'transform', translate + ' ' + scale);
	//<animate id=“anim“ attributeName=“viewBox“ begin=“undefined“ dur=“2s“ 
     //    values=“0 0 400 400; 100 100 200 200“ fill=“freeze“/>
 
	}
}

// returns the mouse coordinates as an SVGPoint
function getMouse (evt) {
  var position = root.createSVGPoint();
  position.x = evt.clientX;
  position.y = evt.clientY;
  return position;
}	

function getViewBox(myElement,item) {
  //get reference to element
  element = root.getElementById(myElement);
  
  var curTransform = new String(element.getAttribute('viewBox'));
  curTransforms = curTransform.split(' ');
  

  if (item == "x") {
	return parseInt( curTransforms[0]);//.substring(0 , curTransforms[0].length ));
  }
  if (item == "y") {
	return parseInt( curTransforms[1]);//.substring( 0, curTransforms[1].length - 1 ));
  }
  
  if (item == "width") {
	return parseInt( curTransforms[2]);//.substring( 0, curTransforms[2].length - 1 ));
  }
  
  if (item == "height") {
	return parseInt( curTransforms[3]);//.substring( 0, curTransforms[3].length - 1 ));
  }
}


function passBackSVG(){ 
	var embedSVG = root.getElementById("diagram"); 

	if(embedSVG.window.passState){
		embedSVG.window.passState(embedSVG);
	} 
} 

function getTranslate(myElement,xOrY) {
  //get reference to element
  element = root.getElementById(myElement);
  
  //first get transform value of coordinate box
  var curTransform = element.getAttribute("transform");
  curTransform = new String(curTransform); 
  //no fear from Regular expressions, just copy it, I copied it either ...
  var translateRegExp=/translate\(([-+]?\d+)(\s*[\s,]\s*)([-+]?\d+)\)\s*/;
  //This part extracts the translation-part from the transform-string
  if (curTransform.length != 0){
    var result = curTransform.match(translateRegExp);
    if (result == null || result.index == -1){
       var oldTranslateX = 0;
       var oldTranslateY = 0;
	     
    }
    else{
       var oldTranslateX = result[1];
       var oldTranslateY = result[3];
    }
  }
  if (xOrY == "x") {
    return oldTranslateX;
  }
  if (xOrY == "y") {
    return oldTranslateY;
  }      
}

function fireFunction(evt){
	if ((bmousedown == 1)||bmousedown == 5){
		zSwap(true);
		bmousedown = 2;
		//root.setAttributeNS(null,"cursor","crosshair");
	}
}

function zSwap(onTop)
{
	var navrect = root.getElementById("canvas");
	svgdoc.documentElement.removeChild(navrect);
	
	navrect = svgdoc.createElementNS("http://www.w3.org/2000/svg", "rect");
	navrect.setAttributeNS(null, "id", "canvas"); 
	navrect.setAttributeNS(null, "x", 0);
	navrect.setAttributeNS(null, "y", 0);
	navrect.setAttributeNS(null, "width", "100%");
	navrect.setAttributeNS(null, "height", "100%");
	navrect.setAttributeNS(null, 'viewBox', root.getAttribute('viewBox'));
	navrect.setAttributeNS(null, "opacity", "0");
	navrect.setAttributeNS(null, "fill", "green");
	navrect.setAttributeNS(null, "pointer-events", "visible");
	navrect.setAttributeNS(null, "onmousedown", "onMouseDown(evt)");
	navrect.setAttributeNS(null, "onmousemove", "onMouseMove(evt)");
	navrect.setAttributeNS(null, "onmouseup", "onMouseUp(evt)");
	navrect.setAttributeNS(null, "onmouseout", "onMouseUp(evt)");
	navrect.setAttributeNS(null, "onclick", "DoOnClick(evt)");
	
	if (onTop)
	{
		svgdoc.documentElement.appendChild(navrect);
	}
	else
	{
		svgdoc.documentElement.insertBefore(navrect, svgdoc.documentElement.firstChild);
	}
   
}
