var msgEditionInProgress='Vous devez sortir du mode edition pour effectuer cette operation.';
var doAllVar=false;
var show=false;
var newStyle=null;
var scaleValShow=0;
var scaleValHide=1;
var timerIdShow;
var timerIdHide;    
var deleted=false;
var ellipseNum=0;
var rectangleNum=0;
var decalage=0;
var polygonNum=0;
var pointNum=0;
var ligneNum=0;
var drawBoard;
var drawBoardTmp;
var style;
var styleTmp;
var origX=0;
var origY=0;
var lastX=0;
var lastY=0;
var origTransX;
var origTransY;
var btnState="Up";
var polyPath="";
var tolerance=2;
var xTransOld;
var yTransOld;
var curObj;
var canSelect=1;
var status ="";
var actionText;
var curNode;
var aimant ="off";
var aideTemp="";
var aideTemp2="";
var aideTemp3="";
var aideTemp4=""; 
var aideCourante="";
var aideCourante2="";
var aideCourante3="";
var aideCourante4="";
var toolType="";
var toolTypeCourant="";
var imgDir ="../iconToolBar/";
var origineX = 0;
var origineY = 0;
var offset=0;
var xmincarto1;
var ymincarto1;	 
var xmaxcarto1;
var ymaxcarto1;
var appui=false,x0=0.0,y0=0.0,x1,y1;
var currentID="";
var MAX_QUERY_SIZE=1600;
var addedToSend;
var editedToSend;
var deletedToSend;	
var cartoNS = "http://www.carto.net/attrib";
var geomNS= "http://www.carto.net/attrib";
var ellipseCenterDefined=false;
var bufdeltax;
var bufdeltay;
var usedDeltaX;
var usedDeltaY;
var curId;


 function ShowToolBar()
 {
			scaleValShow=0;
			timerIdShow = setInterval('showToolBar()',25);
 }
        
 function showToolBar() 
 {
         scaleValShow += 0.1;
        if (scaleValShow > 1)
                clearInterval(timerIdShow);
        else 
               SVGDoc.getElementById("toolBar").setAttribute("transform", "scale(" + scaleValShow +")");
		
	
  } 
  
  function cancelCurrentShape()
  {
		if(curNode!=null)
		{
		
		isDrawing = 0;
		if (shapeType=="polygon" || shapeType=="ligne")
		{
			deleted=false;
			polyPath="";
			
		}
			
		  status ="done";
		  btnState="up";
		 var shapeId = curNode.getAttribute('id');
		 
		 shapePosition = getIdPosition(shapeId);
		 
		 if(shapePosition !=-1)
		 {
		 id=supForArray(shapePosition,id);
		 shapes=supForArray(shapePosition,shapes);
		 //id.splice(shapePosition,1);
			//shapes.splice(shapePosition,1);
		 }
		 
		 shapePosition = getIndexPosition(shapeId);
		 
		 if(shapePosition !=-1)
		 {		 
			indexAddedShapes=supForArray(shapePosition,indexAddedShapes);
			//indexAddedShapes.splice(shapePosition,1);
			//addedShapes.splice(shapePosition,1);
			addedShapes=supForArray(shapePosition,addedShapes);
			
		 }
		
		 //curNode.parent.removeChild(curNode);
		 drawBoardTmp.removeChild(curNode);
		 curNode=null;
		 
	
		}
  }
  
 function exitEditMode()
 {
 reloading=false;
	cancelCurrentShape();
	
	if(confirmation())
	{
	    showFlashTb = true;
		editSvg=false;
	    resizeSvgMode(false);
		hideObject("divEditLayer");
		showObject("divRight");
		emptyEditLayerDiv();
		RAZActions();
		return true;
	}
	
	return false;
 }
 
function reinitToolBar()
{
	unSelectAll('no');
	shapeType="";
}

function RAZActions()
{
	editedShapes=new Array();
	addedShapes=new Array();
	deletedShapes=new Array();
}

 function confirmation()
 {
	if( editedShapes.length + addedShapes.length +deletedShapes.length>0 )
	{	
		var msg="Soumettre les modifications sur la couche "+ currentEditedLayer+" ?\n";
		
		if(editedShapes.length>0)
		msg+="- " +editedShapes.length+" Edition(s) \n";
		
		if(addedShapes.length>0)
		msg+="- "+addedShapes.length+" Ajout(s) \n";
		
		if(deletedShapes.length>0)
		msg+="- "+deletedShapes.length+" Suppression(s) \n";
		
		if( confirm(msg))
		{
			 getEditionShapesCoordinates(true);
			 return true;
		}
		else
		{
			if(confirm("Quitter le mode edition ?"))
				return true
				
			return false;
		}

			
	}
	
	return true;
 }
 function haveTosend()
 {
	if( editedShapes!=null && addedShapes!=null && deletedShapes!=null && (editedShapes.length + addedShapes.length +deletedShapes.length>0) )
	{
		alert("Les modifications doivent etre envoyee avant d'effectuer l'operation");
		return false;
	}
	
	return true;
 }
 
 function confirmationChargementCouche(couche)
 {

	if( editedShapes!=null && addedShapes!=null && deletedShapes!=null && ((editedShapes.length + addedShapes.length +deletedShapes.length)>0) )
	{	
		var msg="Soumettre les modifications sur la couche "+ currentEditedLayer+" ?\n";
		
		if(editedShapes.length>0)
		msg+="- " +editedShapes.length+" Edition(s) \n";
		
		if(addedShapes.length>0)
		msg+="- "+addedShapes.length+" Ajout(s) \n";
		
		if(deletedShapes.length>0)
		msg+="- "+deletedShapes.length+" Suppression(s) \n";
		
		if( confirm(msg))
		{
			 getEditionShapesCoordinates(true);
			 return true;
		}
		else
		{
			if(confirm("Charger la couche "+couche+" en edition ?"))
				return true
				
			return false;
		}
	}
	
	return true;
 }
 
 function initHideToolBar()
 {
        scaleValHide=1;
        timerIdHide = setInterval('hideToolBar()',25);
 }
 
 function hideToolBar() 
 {
         scaleValHide -= 0.1;
        if (scaleValHide < 0)
                clearInterval(timerIdHide);
        else 
               SVGDoc.getElementById("toolBar").setAttribute("transform", "scale(" + scaleValHide +")");
  } 

function Point(x,y){this.x=x;this.y=y;}

function initialisation(evt) 
{ 		
	var directTarget = evt.target;
	SVGDoc = directTarget.ownerDocument;
	
			usedDeltaX=0;
			usedDeltaY=0;
			bufdeltax=0;
			bufdeltay=0;
		
	
		
	
		
		drawBoard = SVGDoc.getElementById('drawBoard');
		drawBoardTmp = SVGDoc.getElementById('drawBoardTmp');
		
	setMapObjObject();
	
		var viewbox = new String(mapObj.getAttribute("viewBox"));
		viewBoxDepart=viewbox;
		
		var viewboxes = viewbox.split(' ');
	
		var widthMapSys = parseFloat(viewboxes[2]);
		var heightMapSys = parseFloat(viewboxes[3]);
				
		widthMap = parseFloat(mapObj.getAttribute("width"));
		heightMap = parseFloat(mapObj.getAttribute("height"));
		
		// position de la toolbar
		
		var toolbar = SVGDoc.getElementById('dessin');
		toolbar.setAttribute("x",widthMap);
		toolbar.setAttribute("y",0);
		
			// position de l'aide
		
		var aiderect = SVGDoc.getElementById('aide');
		aiderect.setAttribute("y",heightMap);

			// position de l'action
		
		var actionrect = SVGDoc.getElementById('actionSVG');
		actionrect.setAttribute("y",heightMap-30);
		
		
		
		scaleValue=new Point(0,0);
			if((heightMapSys)/heightMap<(widthMapSys)/widthMap)
			scaleValue.x = scaleValue.y=(widthMapSys)/widthMap;
			else
			scaleValue.y = scaleValue.x=(heightMapSys)/heightMap;
		


		
		
		var geom = mapObj.getAttributeNS(geomNS,"geometrie");
		
		if(geom.indexOf("0")>=0)
			 canUsePoint=true;

		if(geom.indexOf("1")>=0)
			canUsePoly = true;

		if(geom.indexOf("2")>=0)
			canUseLine=true;
		
		var geom = mapObj.getAttributeNS(cartoNS,"geometrie");
		
		if(geom.indexOf("0")>=0)
		canUsePoint=true;
		if(geom.indexOf("1")>=0)
		canUsePoly = true;
		if(geom.indexOf("2")>=0)
		canUseLine=true;

		
		var empriseCarto = mapObj.getAttributeNS(cartoNS,"EmpriseCarto");
		var xymin = empriseCarto.split(' ');
		
		xmincarto1 = parseFloat(xymin[0]);
		ymincarto1 = parseFloat(xymin[1]);
		xmaxcarto1 = xmincarto1+widthMapSys;
		ymaxcarto1 = ymincarto1+heightMapSys;
		

		curZoom = widthMap/widthMapSys;
		
		
		var ZoomY = heightMap/heightMapSys;
		if(ZoomY<curZoom)
				curZoom = ZoomY;
				
		zoomForScale=curZoom;		
		originalZoom=curZoom;
		
		if(parent.editedShapes==null)
			initEditionArrays();
		//else
			//reloadExistingShapes();
			
			
			RAZActions();
}

function initEditionArrays()
{

		parent.editedShapes = new Array();
		parent.addedShapes = new Array();
		parent.deletedShapes = new Array();
		parent.indexEditedShapes = new Array();
		parent.indexDeletedShapes = new Array();
		parent.indexAddedShapes = new Array();
		parent.indexLocalIdShapes=new Array();


}

function freeArrays()
{
		parent.editedShapes = null;
		parent.addedShapes = null;
		parent.deletedShapes = null;
		parent.indexEditedShapes = null;
		parent.indexDeletedShapes = null;
		parent.indexAddedShapes = null;
		parent.indexLocalIdShapes=null;
}

function init() 
{
	
        SVGDoc = evt.target.ownerDocument();
        drawBoard = SVGDoc.getElementById('drawBoard');
		drawBoardTmp = SVGDoc.getElementById('drawBoardTmp');
}

function initCaptureEvents(evt)
{
	if(!sendingInProgress)
	{
        if((evt.button==2)||(evt.button==3)||(evt.button==4))
		{
			
			//clique bouton droit
			cancelCurrentShape();
		}
		else if(shapeType!="")
		{
			var mousePos = getMousePosition(evt);
			lastX=origX;
			lastY=origY;
			
			if(currentClick.x != -1 && currentClick.y!=-1  && aimant=='on')
			{
					origX = currentClick.x;
					origY = currentClick.y;
			}
			else
			{
						 
					origX = mousePos.x;
					origY= mousePos.y;
			}
			
			appui = true;
			if(shapeType!="polygon"&& shapeType != "ligne")
				btnState="Down";
		}
	}
	else
		alert("L envoie de requetes est en cours. Veuillez patienter");
}

/*function deleteAll(delRecordedSelection)
{
	
    if(confirmSUP())
	{
        var childs = drawBoard.getChildNodes();
        while(childs.getLength()>1)
        {
                drawBoard.removeChild(childs.item(childs.getLength()-1));
        }
		
		     
		
        
        ellipseNum=0;
        rectangleNum=0;
        polygonNum=0;
        pointNum=0;
        ligneNum=0;
        
        if (delRecordedSelection == true)
                sendClear();
		
		addedShapes = new Array();
		indexAddedShapes= new Array();
	}
        
        
}*/
function confirmMAJ()
{
	var msg="Soumettre les modifications sur la couche "+ currentEditedLayer+" ?\n";
	
	if(editedShapes.length>0)
	msg+="- " +editedShapes.length+" Edition(s) \n";
	
	if(addedShapes.length>0)
	msg+="- "+addedShapes.length+" Ajout(s) \n";
	
	if(deletedShapes.length>0)
	msg+="- "+deletedShapes.length+" Suppression(s) \n";
	
	return confirm(msg);
}

function confirmSUP()
{
	return confirm("Supprimer tout les elements de la couche "+currentEditedLayer+" ?");
}

function getShapesCoordinates()
{
       if( ellipseNum == 0 && rectangleNum == 0 && polygonNum == 0 && pointNum == 0 && ligneNum == 0)
               alert("Aucune selection n'a ete effectuee");
       else
       {
	  
       var child = drawBoard.getChildNodes();
       var shapesInfo = new Array();
       var rectangleArr = new Array();
       var ellipseArr=  new Array();
       var polygonArr = new Array();
       var pointArr = new Array();
       var ligneArr = new Array();
       
       for(var i=1; i<child.getLength();i++)
       {
               var shapeChild = child.item(i).getChildNodes();
               var attributes = shapeChild.item(1).getAttributes();
               var id = shapeChild.item(1).getAttribute('id');
               var transX =0.0;
               var transY= 0.0;
               if(id.indexOf("rectangle")>=0)
               {
                       var x;
                       var y;
                       var width;
                       var height;
                       var str="";
                       var tmpTrans="";

                       
                      for(var j=0;j<attributes.getLength();j++)
                      {              
                                      if(attributes.item(j).getNodeName() == "x")
                                              x=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "y")
                                              y=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "width")
                                              width=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "height")
                                              height=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "transform")
                                      {
                                              tmpTrans=attributes.item(j).getNodeValue();
                                              if(tmpTrans!="translate(0,0)")
                                              {
                                                transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
                                                transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
                                              }
                                             
                                      }
                       }
                       x+=transX;
                       y+=transY;
                       var pt = new Point();
                       pt=ConvertViewToSysSVGEdit(x,y);
                       x=pt.x;
                       y=pt.y;
                       width=ConvertViewToSysDistanceSVG(width);
                       height=ConvertViewToSysDistanceSVG(height);
                       str+="x="+x+"@y="+y+"@width="+width+"@height="+height;
                       rectangleArr.push(str);
               }
                else if(id.indexOf("point")>=0)
               {
                       var cx;
                       var cy;
                       var str="";
                      for(var j=0;j<attributes.getLength();j++)
                      {              
                                      if(attributes.item(j).getNodeName() == "cx")
                                              cx=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "cy")
                                              cy=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "transform")
                                      {
                                              tmpTrans=attributes.item(j).getNodeValue();
                                              if(tmpTrans!="translate(0,0)")
                                              {
                                                transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
                                                transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
                                              }
                                      }
                                    
                       }
                       //on applique l'赥ntuel translation
                       cx+=transX;
                       cy+=transY;
                       var pt =  new Point();
                       pt=ConvertViewToSysSVGEdit(cx,cy);
                       cx=pt.x;
                       cy=pt.y;
                       
                       str +="cx="+cx+"@cy="+cy;
                       pointArr.push(str);
               }                
               else if(id.indexOf("ellipse")>=0)
               {
                       var cx;
                       var cy;
                       var rx;
                       var ry;
                       var str="";
                      for(var j=0;j<attributes.getLength();j++)
                      {              
                                      if(attributes.item(j).getNodeName() == "cx")
                                              cx=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "cy")
                                              cy=parseInt(attributes.item(j).getNodeValue());
                                      if(attributes.item(j).getNodeName() == "rx")
                                              rx=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "ry")
                                              ry=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "transform")
                                      {
                                              tmpTrans=attributes.item(j).getNodeValue();
                                              if(tmpTrans!="translate(0,0)")
                                              {
                                                transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
                                                transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
                                              }
                                      }
                                    
                       }
                       //on applique l'赥ntuel translation
                       cx+=transX;
                       cy+=transY;
                       var pt =  new Point();
                       pt=ConvertViewToSysSVGEdit(cx,cy);
                       cx=pt.x;
                       cy=pt.y;
                       rx=ConvertViewToSysDistanceSVG(rx);
                       ry=ConvertViewToSysDistanceSVG(ry);
                       
                       str +="cx="+cx+"@cy="+cy+"@rx="+rx+"@ry="+ry;
                       ellipseArr.push(str);
               }            
               else if(id.indexOf("polygon")>=0)
               {
                       var str="";
                      for(var j=0;j<attributes.getLength();j++)
                      {         
                                      if(attributes.item(j).getNodeName() == "d")
                                      {
                                              str+=attributes.item(j).getNodeValue();
                                      }
                                      else if(attributes.item(j).getNodeName() == "transform")
                                      {
                                              tmpTrans=attributes.item(j).getNodeValue();
                                              if(tmpTrans!="translate(0,0)")
                                              {
                                                transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
                                                transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
                                              }
                                      }                                              
                       }
                       
                       //pour passer en coordonn褳 r褬les on d袯upe la chaine
                       
                       // on r袵pere que les valeus du path
                       var tmp = str.split('M')[1];
                       str="";
                       //on d袯upe par rapport � "
                       var tab = tmp.split(" ");
                       
                       //on parcours les points en ne prenant pas le dernier (doubl硠 cause du double click);
                       var pt = new Point();
                       for(var cpt=0; cpt<tab.length-1;cpt++)
                       {
                               //on r袵p籥 les coord议n褳 des points 
                               pt = ConvertViewToSysSVGEdit(parseFloat(tab[cpt].split(',')[0])+transX,parseFloat(tab[cpt].split(',')[1])+transY);
                               
                               str+=pt.x+","+pt.y+" ";
                       }
                       
                       polygonArr.push(str);
               }
                else if(id.indexOf("ligne")>=0)
               {
                       var str="";
                      for(var j=0;j<attributes.getLength();j++)
                      {         
                                      if(attributes.item(j).getNodeName() == "d")
                                      {
                                              str+=attributes.item(j).getNodeValue();
                                      }
                                      else if(attributes.item(j).getNodeName() == "transform")
                                      {
                                              tmpTrans=attributes.item(j).getNodeValue();
                                              if(tmpTrans!="translate(0,0)")
                                              {
                                                transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
                                                transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
                                              }
                                      }                                              
                       }
                       
                       //pour passer en coordonn褳 r褬les on d袯upe la chaine
                       
                       // on r袵pere que les valeus du path
                       var tmp = str.split('M')[1];
                       str="";
                       //on d袯upe par rapport � "
                       var tab = tmp.split(" ");
                       
                       //on parcours les points en ne prenant pas le dernier (doubl硠 cause du double click);
                       var pt = new Point();
                       for(var cpt=0; cpt<tab.length-1;cpt++)
                       {
                               //on r袵p籥 les coord议n褳 des points 
                               pt = ConvertViewToSysSVGEdit(parseFloat(tab[cpt].split(',')[0])+transX,parseFloat(tab[cpt].split(',')[1])+transY);
                               
                               str+=pt.x+","+pt.y+" ";
                       }
                       
                       ligneArr.push(str);
               }
       }
       
       shapesInfo.push(rectangleArr,ellipseArr,polygonArr,pointArr,ligneArr);
       var shapestr = "RECTANGLES:";
       for(var k=0;k<shapesInfo[0].length;k++)
              shapestr += shapesInfo[0][k]+":";
              
                      shapestr+="ELLIPSES:";

       for(var k=0;k<shapesInfo[1].length;k++)
               shapestr += shapesInfo[1][k]+":";
               
                      shapestr+="POLYGONES:";

       for(var k=0;k<shapesInfo[2].length;k++)
               shapestr += shapesInfo[2][k]+":";    
               
                      shapestr+="POINTS:";

       for(var k=0;k<shapesInfo[3].length;k++)
               shapestr += shapesInfo[3][k]+":";         
                       shapestr+="LIGNES:";

       for(var k=0;k<shapesInfo[4].length;k++)
               shapestr += shapesInfo[4][k]+":"; 
               
       //deleteAll(false);
	  
       sendSvgRequest(shapestr);
       }//fin du else
}


function formatMAJRequest(shapeList,isEdition)
{
  var shapesInfo = new Array();
	   
   var rectangleArr = new Array();
   var ellipseArr=  new Array();
   var polygonArr = new Array();
   var pointArr = new Array();
   var ligneArr = new Array();
   
   var strShapes="";

   for(var i=0; i<shapeList.length;i++)
   {
  
	   var shapeChild = shapeList[i];
	   var id = shapeChild.getAttribute('id');
	   var attributes = shapeChild.getAttributes();
	  
	   var transX =0.0;
	   var transY= 0.0;
		 		   

	
		    //forme ajout褳 --> RECTANGLES
                   if(shapeChild.localName == "rect")
                   {
				
                           var x;
                           var y;
                       var width;
                       var height;
					   var str="";
					   if (isEdition)
						str="NOSHAPE@"+id+"@";
							//str="ID@"+id+"@";
                       var tmpTrans="";

                       
                      for(var j=0;j<attributes.getLength();j++)
                      {              
                                      if(attributes.item(j).getNodeName() == "x")
                                              x=parseFloat(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "y")
                                              y=parseFloat(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "width")
                                              width=parseFloat(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "height")
                                              height=parseFloat(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "transform")
                                      {
                                              tmpTrans=attributes.item(j).getNodeValue();
                                              if(tmpTrans!="translate(0,0)")
                                              {
											  
                                                transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
                                                transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
                                              }
                                             
                                      }
                       }
					   
                       x+=transX;
                       y+=transY;
                       var pt = new Point();
					   pt=ConvertViewToSysSVGEdit(x,y);
                       x=pt.x;
                       y=pt.y;

                       str+="x="+x+"@y="+y+"@width="+width+"@height="+height;
											 
                       rectangleArr.push(str);
               }
                else if(shapeChild.localName == "ellipse")
               {

				if(id.indexOf("ellipse")>=0)
               {
			   

                       var cx;
                       var cy;
                       var rx;
                       var ry;
                       var str="";
					    if (isEdition)
							str="NOSHAPE@"+id+"@";
							//str="ID@"+id+"@";
							
                      for(var j=0;j<attributes.getLength();j++)
                      {              
                                      if(attributes.item(j).getNodeName() == "cx")
                                              cx=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "cy")
                                              cy=parseInt(attributes.item(j).getNodeValue());
                                      if(attributes.item(j).getNodeName() == "rx")
                                              rx=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "ry")
                                              ry=parseInt(attributes.item(j).getNodeValue());
                                      else if(attributes.item(j).getNodeName() == "transform")
                                      {
                                              tmpTrans=attributes.item(j).getNodeValue();
                                              if(tmpTrans!="translate(0,0)")
                                              {
                                                transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
                                                transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
                                              }
                                      }
                                    
                       }
                       //on applique l'赥ntuel translation
                       cx+=transX;
                       cy+=transY;
                       var pt =  new Point();
			//CHANGEMENT
                       pt=ConvertViewToSysSVGEdit(cx,cy);
					   //pt=ConvertViewToSys(cx,cy);
					   
                       cx=pt.x;
                       cy=pt.y;
                       //rx=ConvertViewToSysDistanceSVG(rx);
                       //ry=ConvertViewToSysDistanceSVG(ry);
                       
                       str +="cx="+cx+"@cy="+cy+"@rx="+rx+"@ry="+ry;
					 
                       ellipseArr.push(str);
               }
               }                
               else if(shapeChild.localName == "circle")
			   {
			   				
                       var cx;
                       var cy;
                       var str="";
					   
					   if (isEdition)
						str="NOSHAPE@"+id+"@";
							//str="ID@"+id+"@";
                      for(var j=0;j<attributes.getLength();j++)
                      {              
						  if(attributes.item(j).getNodeName() == "cx")
								  cx=parseInt(attributes.item(j).getNodeValue());
						  else if(attributes.item(j).getNodeName() == "cy")
								  cy=parseInt(attributes.item(j).getNodeValue());
						  else if(attributes.item(j).getNodeName() == "transform")
						  {
								  tmpTrans=attributes.item(j).getNodeValue();
								  if(tmpTrans!="translate(0,0)")
								  {
									transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
									transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
								  }
						  }
                       }
                       //on applique l'赥ntuel translation
                       cx+=transX;
                       cy+=transY;
                       var pt =  new Point();
						//CHANGEMENT
                       pt=ConvertViewToSysSVGEdit(cx,cy);
					   //pt=ConvertViewToSys(cx,cy);
					   
                       cx=pt.x;
                       cy=pt.y;
                       
                       str +="cx="+cx+"@cy="+cy;
					 
                       pointArr.push(str);
					
			   
			   }
			   else if(shapeChild.localName == "path")
               {
			   var str="";
				
					
			   str+=shapeChild.getAttributeNS(null,"d");
			   
			   tmpTrans=shapeChild.getAttributeNS(null,"transform");
			   transX=0;
			   transY=0;
			   
			   
			   
			  if(tmpTrans!="translate(0,0)"  && tmpTrans!="")
			  {
				transX = parseFloat(tmpTrans.split('(')[1].split(',')[0]);
				transY = parseFloat(tmpTrans.split('(')[1].split(',')[1].split(')')[0]); 
			  }
			  
			 
				
               if(id.indexOf("polygon")>=0 || str.indexOf("z")>=0)
               {
			   
                       //pour passer en coordonn褳 r褬les on d袯upe la chaine
                     
                       // on r袵pere que les valeurs du path
                       var tmp = str.split('M')[1];
					   
					   
                        if (isEdition)
							str="NOSHAPE@"+id+"@";
							//str="ID@"+id+"@";
						else
							str="";
							
					
					   //trim
					   tmp =trimString(tmp);
					   tmp=tmp.substr(0, tmp.length-1);
                       //on d袯upe par rapport � "
					   
					   var tab;
					 
					   if(tmp.indexOf("l")>=0)
							tab=splitL(tmp,"l");
						else if(tmp.indexOf("L")>=0)
							tab=splitL(tmp,"L");
					   else
                        tab = tmp.split(" ");
                
                       var pt = new Point();
                       for(var cpt=0; cpt<tab.length;cpt=cpt+2)
                       {
                               //on r袵p籥 les coordonn褳 des points 
							  
                               pt = ConvertViewToSysSVGEdit(parseFloat(tab[cpt])+transX,parseFloat(tab[cpt+1])+transY);
                               str+=pt.x+","+pt.y+" ";
                       }
                       
                       polygonArr.push(str);
               }
                else
				// if(id.indexOf("ligne")>=0) ou il ny a pas de "z"
               {
                       //pour passer en coordonn褳 r褬les on d袯upe la chaine
                        
                       // on r袵pere que les valeurs du path
                       var tmp = str.split('M')[1];
					   
                        if (isEdition)
							str="NOSHAPE@"+id+"@";
							//str="ID@"+id+"@";
						else
							str="";
					   //trim
					   tmp =trimString(tmp);
                       //on d袯upe par rapport � "
					   
                       var tab;
					
					   if(tmp.indexOf("l")>=0)
							tab=splitL(tmp,"l");
						else if(tmp.indexOf("L")>=0)
							tab=splitL(tmp,"L");
					   else
                        tab = tmp.split(" ");
                    
                     
                       var pt = new Point();
					
                       for(var cpt=0; cpt<tab.length;cpt+=2)
                       {
                               //on r袵p籥 les coord议n褳 des points 
								
	                            pt = ConvertViewToSysSVGEdit(parseFloat(tab[cpt])+transX,parseFloat(tab[cpt+1])+transY);
                              				   
                               str+=pt.x+","+pt.y+" ";
                       }
						
                       ligneArr.push(str);
               }
			   }
       
	   
       
       shapesInfo.push(rectangleArr,ellipseArr,polygonArr,pointArr,ligneArr);
       strShapes = "|RECTANGLES:";
       for(var k=0;k<shapesInfo[0].length;k++)
              strShapes += shapesInfo[0][k]+":";
              
                      strShapes+="|ELLIPSES:";

       for(var k=0;k<shapesInfo[1].length;k++)
               strShapes += shapesInfo[1][k]+":";
           
                      strShapes+="|POLYGONES:";

       for(var k=0;k<shapesInfo[2].length;k++)
               strShapes += shapesInfo[2][k]+":";    
               
                      strShapes+="|POINTS:";

       for(var k=0;k<shapesInfo[3].length;k++)
               strShapes += shapesInfo[3][k]+":";         
                       strShapes+="|LIGNES:";

       for(var k=0;k<shapesInfo[4].length;k++)
               strShapes += shapesInfo[4][k]+":"; 
	}	   
	

	return strShapes;
}


function getEditionShapesCoordinates(forceSubmit)
{
	reloading = true;
	if(forceSubmit || ( (editedShapes.length>0 || addedShapes.length>0 || deletedShapes.length>0) && confirmMAJ()))
	{
	   var editedShapesQuery  = "";
	   var addedShapesQuery   = ""; 
	   var deletedShapesQuery = ""; 
	   var globalQuery=new Array();
	   var tmp="";
	   
	   getShapeToSendList();
	   
		if(editedShapes.length > 0)
		{
			
			editedShapesQuery = "!EDITED="+formatMAJRequest(editedToSend,true);
								
			tmp+=editedShapesQuery;
			globalQuery.push(editedShapesQuery);
			
		}
		if(addedShapes.length > 0)			
		{
			addedShapesQuery=  "!ADDED="+formatMAJRequest(addedToSend,false);
			
			tmp+=addedShapesQuery;
			globalQuery.push(addedShapesQuery);
		}
		if(deletedShapes.length > 0)	
		{
			deletedShapesQuery = "!DELETED="+arrayToString(deletedToSend);
			tmp+=deletedShapesQuery;
			globalQuery.push(deletedShapesQuery);
		}
		
		var splittedQuery = new Array();
		var i=0;
		
		
		if(	(tmp.length) >0	)
		{
			
			if((tmp.length)<MAX_QUERY_SIZE)
				splittedQuery.push(tmp);
			else
			{
			
				if(globalQuery.length==1)
				{
					var tmpp=cutQuery(tmp);
					splittedQuery = splittedQuery.concat(tmpp);
					
					
				}
				else if(globalQuery.length==2)
				{
					if(globalQuery[0].length<MAX_QUERY_SIZE)
						splittedQuery.push(globalQuery[0]);
					else
						splittedQuery = splittedQuery.concat(cutQuery(globalQuery[0]));
					
					if(globalQuery[1].length<MAX_QUERY_SIZE)
						splittedQuery.push(globalQuery[1]);
					else
						splittedQuery = splittedQuery.concat(cutQuery(globalQuery[1]));
				}
				else if(globalQuery.length==3)
				{
					if(globalQuery[0].length+globalQuery[1].length<MAX_QUERY_SIZE)
					{
						splittedQuery.push(globalQuery[0]+globalQuery[1]);
						
						if(globalQuery[2].length<MAX_QUERY_SIZE)
							splittedQuery.push(globalQuery[2]);
						else
							splittedQuery = splittedQuery.concat(cutQuery(globalQuery[2]));
					}
					else if(globalQuery[0].length+globalQuery[2].length<MAX_QUERY_SIZE)
					{
						splittedQuery.push(globalQuery[0]+globalQuery[2]);
						
						if(globalQuery[1].length<MAX_QUERY_SIZE)
							splittedQuery.push(globalQuery[1]);
						else
							splittedQuery = splittedQuery.concat(cutQuery(globalQuery[1]));					
					}
					else if(globalQuery[1].length+globalQuery[2].length<MAX_QUERY_SIZE)
					{
						splittedQuery.push(globalQuery[1]+globalQuery[2]);
						
						if(globalQuery[0].length<MAX_QUERY_SIZE)
							splittedQuery.push(globalQuery[0]);
						else
							splittedQuery = splittedQuery.concat(cutQuery(globalQuery[0]));				
					}
				}
			}
		
			razShapesArrays();
			pile = splittedQuery;
			sendingInProgress= true;
			
			sendNextRequest();
		
		}
		else
		{
			return false;
		}
       
	}
	else if( editedShapes.length==0 && addedShapes.length==0 && deletedShapes.length==0)
			alert("Aucune modification n'a ete effectuee.");
	else
			alert("Les modifications n'ont pas ete soumisent.");
	
	//fin if confirmMAJ()
}

function arrayToString(arr)
{
	var strRet="";
	for(k=0;k<deletedToSend.length-1;k++)
           strRet+=deletedToSend[k]+",";
		   
	strRet+=deletedToSend[deletedToSend.length-1];
	
	return strRet;
	
}
function razShapesArrays()
{
	editedShapes = new Array();
	addedShapes = new Array();
	deletedShapes = new Array();
	indexEditedShapes = new Array();
}
function cutQuery(query)
{

	var prefixe = "";
	var returnedArray = new Array();
	
	if(query.indexOf("!ADDED")>=0)
	{
		prefixe="!ADDED";
		query=query.split("!ADDED=")[1];
	}
	else if(query.indexOf("!EDITED")>=0)
	{
		prefixe="!EDITED";
		query=query.split("!EDITED=")[1];
	}
	else if(query.indexOf("!DELETED")>=0)
	{
		prefixe="!DELETED";
		query=query.split("!DELETED=")[1];
	}
	
	
	var tmp = query.split("|RECTANGLES:")[1]
	var rect = tmp.split("|ELLIPSES:")[0];
	tmp =tmp.split("|ELLIPSES:")[1];
	var ellipse = tmp.split("|POLYGONES:")[0];
	tmp =tmp.split("|POLYGONES:")[1];
	var poly = tmp.split("|POINTS:")[0];
	tmp =tmp.split("|POINTS:")[1];
	var points = tmp.split("|LIGNES:")[0];
	var lignes =tmp.split("|LIGNES:")[1];
	
	var arrTmp,cptArr;
	//on s'occuppe des formes 'courtes'
	if(rect.length+points.length+ellipse.length >0)
	{
		if(rect.length+points.length+ellipse.length < MAX_QUERY_SIZE)
		{
			returnedArray.push(prefixe+"="+"|ELLIPSES:"+ellipse+"|POINTS:"+points+"|RECTANGLES:"+rect);
		}
		else
		{
			//Ellipse
			if(ellipse.length>0 && ellipse.length<MAX_QUERY_SIZE)
				returnedArray.push(prefixe+"="+"|ELLIPSES:"+ellipse);
			else if(ellipse.length>0)
			{
				arrTmp = cutShape(ellipse,true);
				
				cptArr=0;
				
				for(cptArr=0;cptArr<arrTmp.length;cptArr++)
					returnedArray.push(prefixe+"="+"|ELLIPSES:"+arrTmp[cptArr]);
			}
				
			//points
			if(points.length>0 && points.length<MAX_QUERY_SIZE)	
				returnedArray.push(prefixe+"="+"|POINTS:"+points);
			else if(points.length>0)
			{
				arrTmp = cutShape(points,true);
				cptArr=0;
				
				for(cptArr=0;cptArr<arrTmp.length;cptArr++)
					returnedArray.push(prefixe+"="+"|POINTS:"+arrTmp[cptArr]);
			}
			
			//rectangles
			if(rect.length>0 && rect.length<MAX_QUERY_SIZE)
				returnedArray.push(prefixe+"="+"|RECTANGLES:"+rect);
			else if(rect.length>0)
			{
				arrTmp = cutShape(rect,true);
				cptArr=0;
				
				for(cptArr=0;cptArr<arrTmp.length;cptArr++)
					returnedArray.push(prefixe+"="+"|RECTANGLES:"+arrTmp[cptArr]);
			}
				
		}
	}
	
	if(poly.length <  MAX_QUERY_SIZE && lignes.length <  MAX_QUERY_SIZE)
	{
		if(poly.length +lignes.length < MAX_QUERY_SIZE)
		{
			returnedArray.push(prefixe+"="+"|POLYGONES:"+poly+"|LIGNES:"+lignes);
		}
		else
		{
			returnedArray.push(prefixe+"="+"|POLYGONES:"+poly);
			returnedArray.push(prefixe+"="+"|LIGNES:"+lignes);
		}
	}
	else
	{
		
		if(poly.length <  MAX_QUERY_SIZE && poly.length>0)
		{
			returnedArray.push(prefixe+"="+"|POLYGONES:"+poly);
		}
		else if(poly.length>0)
		{
			
			arrTmp = cutShape(poly,false);
			cptArr=0;
			
			for(cptArr=0;cptArr<arrTmp.length;cptArr++)
				returnedArray.push(prefixe+"="+"|POLYGONES:"+arrTmp[cptArr]);
		}
		
		if(lignes.length <  MAX_QUERY_SIZE && lignes.length>0)
		{
			
			returnedArray.push(prefixe+"="+"|LIGNES:"+lignes);
		}
		else if(lignes.length>0)
		{
			
			arrTmp = cutShape(lignes,false);
			cptArr=0;
				
			for(cptArr=0;cptArr<arrTmp.length;cptArr++)
				returnedArray.push(prefixe+"="+"|LIGNES:"+arrTmp[cptArr]);
			
		}
		
	}
	
	/*for(cptArr=0;cptArr<returnedArray.length;cptArr++)
	{
	returnedArray[cptArr]+=":";
	}*/
	
	return returnedArray;
}

function cutShape(shapePoints, isShort)
{
	var tmpShapePoints;
	var tmp="",tmp2="";
	var returnedArray = new Array();
	var cpt=0,cpt2=0;
	var tmpShape,tmpShape2;
	
	if(isShort)
	{
		//on traite soit un rectangle soit un cercle soit un point
		tmpShape = 	shapePoints.split(':');
		
		for (cpt=0;cpt<shapePoints.length;cpt++)
		{
			
			if((tmp.length+tmpShape[cpt].length)< MAX_QUERY_SIZE)
				tmp+=tmpShape[cpt]+":";
			else
			{
				returnedArray.push(tmp);
				tmp=tmpShape[cpt]+":";
			}
		}
		
		returnedArray.push(tmp);
	}
	else
	{
		//cas d'une ligne ou dun polygone
		tmpShape = 	shapePoints.split(':');
		
		for (cpt=0;cpt<tmpShape.length;cpt++)
		{
			if(tmpShape[cpt].length< MAX_QUERY_SIZE && tmpShape[cpt]!="")
			{
				if((tmp.length+tmpShape[cpt].length)< MAX_QUERY_SIZE)
					tmp+=tmpShape[cpt]+":";
				else
				{
					returnedArray.push(tmp);
					tmp=tmpShape[cpt]+":";
				}
			}
			else if(tmpShape[cpt]!="")
			{
				var nbMsg = Math.ceil(tmpShape[cpt].length/MAX_QUERY_SIZE); 
				var d=new Date();
				var noShape = d.getTime();
			
				
				if(tmpShape[cpt].indexOf("NOSHAPE@")>=0)
				{
					var tabSplit = tmpShape[cpt].split("@");
					noShape=tabSplit[1];
					tmpShape[cpt]=tabSplit[2];
					
					
					/*var strSplit=""
					var ind= 2;
					while(ind<tabSplit.length)
					{
						strSplit+=tabSplit[ind];
						ind++;
					}
					
					
					tmpShape[cpt]=strSplit;*/
				}
					
				tmpShape2 = tmpShape[cpt].split(" ");
				var curNoseq=1;
				for (cpt2=0;cpt2<tmpShape2.length;cpt2++)
				{
					
					if((tmp2.length+tmpShape2[cpt2].length)< MAX_QUERY_SIZE)
						tmp2+=tmpShape2[cpt2]+" ";
					else
					{
						
						returnedArray.push("NOSHAPE@"+noShape+"@NOSEQ:"+curNoseq+"@"+nbMsg+":"+tmp2);
						curNoseq++;
						tmp2=tmpShape2[cpt2]+" ";
					}
	
				}
				
				returnedArray.push("NOSHAPE@"+noShape+"@NOSEQ:"+curNoseq+"@"+nbMsg+":"+tmp2);
				
			}
		}
		
		if(tmp !="")
			returnedArray.push(tmp);
	
	}
	
	return returnedArray;
}
function getMousePosition(mouseEvt)
{

        var pt = new Point(0,0);
		if(editSvg)
		{
			
		
			pt.x=mouseEvt.getClientX()*scaleValue.x+origineX;//-usedDeltaX;
			pt.y=mouseEvt.getClientY()*scaleValue.y+origineY;//-usedDeltaY; 
		}
		else
		{
			 if(isMinNS4)
			{
					pt.x=mouseEvt.pageX;
					pt.y=mouseEvt.pageY;
			}
			else
			{
					pt.x=event.x+idBody.scrollLeft;
					pt.y=event.y+idBody.scrollTop;
			}
		}
		
        return(pt);
}

function mouseUp(evt)
{       
        if(status == "drawing")
        {
                status ="done";
                if(shapeType=="rectangle")
                {  
                        curNode.setAttribute('onmousemove', 'checkNear(evt)');
                        curNode.setAttribute('style', style);
                        addShape(curNode,"rectangle_"+rectangleNum);
                       
					   addedShapes.push(curNode);
					   indexAddedShapes.push("rectangle_"+rectangleNum);
                        rectangleNum++;
						
						curNode=null;
                       
                }
                else if(shapeType=="cercle")
                {
                        curNode.setAttribute('onmousemove', 'checkNear(evt)');
                        curNode.setAttribute('style', style);
                        addShape(curNode,"ellipse_"+ellipseNum);
                       
						addedShapes.push(curNode);
						indexAddedShapes.push("ellipse_"+ellipseNum);
						 ellipseNum++;
						curNode=null;
						ellipseCenterDefined=false;
                }
        }
                
       if(shapeType!="polygon" && shapeType!="ligne")
                btnState="Up";
       
       canSelect=1;
}
function drawShape(evt)
{		
        if(shapeType=="rectangle"){drawRect(evt);}
        else if(shapeType =="cercle"){drawEllipse(evt);}
        else if(shapeType =="polygon"){drawPolygon(evt);}
        else if(shapeType == "ligne"){drawLigne(evt);}
}

function reDrawSelection()
{
        sendReDraw();
}

function drawRect(evt) 
{
        if(btnState=="Down")
        {
                status =  "drawing";
                var mousePos = getMousePosition(evt);
                var finalX,finalY;
                
                if(currentClick.x !=-1 && currentClick.y != -1  && aimant=='on')
                {
                        finalX = currentClick.x;
                        finalY = currentClick.y;
                        currentClick.x=-1;
                        currentClick.y=-1;
                }
                else
                {
                        finalX = mousePos.x;
                        finalY = mousePos.y;
                }
                
                var elemID = "rectangle_" + rectangleNum;
                var oldCheck = SVGDoc.getElementById(elemID);
                var rectWidth = Math.abs(origX-finalX);
                var rectHeight= Math.abs(origY-finalY);
               
              
                if (oldCheck!=null) 
                {
						var oldElem = oldCheck;
                        oldElem.setAttribute('height', rectHeight);
                        oldElem.setAttribute('width', rectWidth);
                        if (origX>finalX) {newElem.setAttribute('x', finalX);}
                        else newElem.setAttribute('x', origX);
                        if (origY>finalY) newElem.setAttribute('y', finalY);
                        else newElem.setAttribute('y', origY);
                        
                        newElem.setAttribute('id', elemID);
						
						curNode=newElem;
						
                } 
                else 
                {
                        newNode = nodeClone(SVGDoc.getElementById("protoRectangle"));
                        newNode.setAttribute('id', elemID);
                        newNode.setAttributeNS("http://www.kevlindev.com/gui","edit","editable");
                        newNode.setAttribute('onmousemove', 'checkNear(evt)');
                        newElem=newNode;
                        curNode = newNode;
						 
                        if (origX>finalX) {newElem.setAttribute('x', finalX);}
                        else newElem.setAttribute('x', origX);
                        if (origY>finalY) newElem.setAttribute('y', finalY);
                        else newElem.setAttribute('y', origY);
                        newElem.setAttribute('height', rectHeight);
                        newElem.setAttribute('width', rectWidth);
                        newElem.setAttribute('style', styleTmp);
                        drawBoard.appendChild(newNode);
                }
        }
}

function drawEllipse() 
{
        if(btnState=="Down")
        {
        
        status =  "drawing";
        
        var elemID = "ellipse_" + ellipseNum;
        var oldCheck = SVGDoc.getElementById(elemID);
        
        var mousePos = getMousePosition(evt);
        
       
                curX = mousePos.x;
                curY = mousePos.y;
        
        var oldCheck = SVGDoc.getElementById(elemID);
        var radiusX =2;
        var radiusY =2;
        
                if (Math.abs(curX - origX) > 5) radiusX = (Math.abs(curX - origX))/2;
                if (Math.abs(curY - origY) > 5) radiusY = (Math.abs(curY - origY))/2;
                
                var centerX = origX + radiusX;
                if(origX>curX) centerX = curX + radiusX;      
                                
                var centerY = origY + radiusY;
                if(origY>curY) centerY = curY + radiusY;      
        
       
        
        
        if (oldCheck) 
        {
		oldElem = oldCheck;
                oldElem.setAttribute('cx', centerX);
                oldElem.setAttribute('cy', centerY);
                oldElem.setAttribute('rx', radiusX);
                oldElem.setAttribute('ry', radiusY);
                newElem.setAttribute('id', elemID);
        }
        else 
        { 
                newNode = nodeClone(SVGDoc.getElementById("protoEllipse"));
		newNode.setAttributeNS("http://www.kevlindev.com/gui","edit","editable");
                newNode.setAttribute('id', elemID);
		
	        newElem = newNode;
                curNode = newNode;
				if(currentClick.x!=-1 && currentClick !=-1)
				{
				
				centerX=currentClick.x;
				centerY=currentClick.y;
				ellipseCenterDefined =true;
				}
				
                newElem.setAttribute('cx', centerX);
                newElem.setAttribute('cy', centerY);
                newElem.setAttribute('rx', radiusX);
                newElem.setAttribute('ry', radiusY);
                newElem.setAttribute('style', styleTmp);
                newElem.setAttribute('id', elemID);
                drawBoard.appendChild(newNode);
        }
        }
}


function drawPoint() 
{
      
        var elemID = "point_" + pointNum;
        
        var mousePos = getMousePosition(evt);
        var curX,curY;
        
        if(currentClick.x!=-1 && currentClick.y != -1  && aimant=='on')
        {
                curX = currentClick.x;
                curY = currentClick.y;
        }
        else
        {
                curX = mousePos.x;
                curY = mousePos.y;
                
        }
		newNode = nodeClone(SVGDoc.getElementById("protoPoint"));
		newNode.setAttributeNS("http://www.kevlindev.com/gui","edit","editable");
		newNode.setAttribute('id', elemID);
		newNode.setAttribute('cx', curX);
		newNode.setAttribute('cy', curY);
		var rayon = 4*scaleValue.x;
		newNode.setAttribute('r', rayon);
		//newNode.setAttribute('ry', rayon);
		newNode.setAttribute('id', elemID);
        newNode.setAttribute('onmousemove', 'checkNear(evt)');
		drawBoard.appendChild(newNode);
        pointNum++;       
        addShape(newNode,elemID);
		
		addedShapes.push(newNode);
		indexAddedShapes.push(elemID);
		
		
        
}


function drawPolygon() 
{
        
        if(shapeType=="polygon")
        {
		
        if(btnState=="UpClicked" || btnState =="end" ||btnState =="waitForClick")
        {
        var elemID = "polygon_" + polygonNum;
        var oldCheck = SVGDoc.getElementById(elemID);
        
        var mousePos = getMousePosition(evt);
	//	mousePos.x-=pan.x*scaleValue.x;
		//mousePos.y-=pan.y*scaleValue.x;
        var ployPathPoints;
        var path="";
        var lastPoint;
        if (oldCheck) 
        {
                var oldElem = oldCheck;
               if( btnState =="end")
               {
                       oldElem.setAttribute('d', polyPath);
                       btnState="Up";
                       polyPath="";
                       polygonNum++;
                       curNode.setAttribute('style', style);
                       curNode.setAttribute('onmousemove', 'checkNear(evt)');
                       addShape(curNode,elemID);
					   addedShapes.push(curNode);
					   indexAddedShapes.push(elemID);
					   
					   curNode=null;
               }
               else if(deleted)
			   {
					deleted=false;
					drawBoard.removeChild(oldElem);
			   }
			   else
               {
			   
                 if(currentLine.pt1.x !=-1 && currentLine.pt1.y !=-1 
                         && currentLine.pt2.x !=-1 && currentLine.pt2.y !=-1  && aimant=='on')
                {
                     ployPathPoints = polyPath.split(' ');
                     lastPoint = new Point(ployPathPoints[ployPathPoints.length-2],ployPathPoints[ployPathPoints.length-1]);
                     
                     if((currentLine.pt1.x == lastPoint.x && currentLine.pt1.y == lastPoint.y))
                        oldElem.setAttribute('d', polyPath+" "+currentLine.pt2.x+" "+currentLine.pt2.y);
                        
                     else if((currentLine.pt2.x == lastPoint.x && currentLine.pt2.y == lastPoint.y) ) 
                        oldElem.setAttribute('d', polyPath+" "+currentLine.pt1.x+" "+currentLine.pt1.y);
                        
                     else
                     {
                        
                        if( getCloser(getMousePosition(evt),currentLine.pt1,currentLine.pt2)<0)      
                            oldElem.setAttribute('d', polyPath+" "+currentLine.pt1.x+" "+currentLine.pt1.y+" "+currentLine.pt2.x+" "+currentLine.pt2.y);
                        else
                            oldElem.setAttribute('d', polyPath+" "+currentLine.pt2.x+" "+currentLine.pt2.y+" "+currentLine.pt1.x+" "+currentLine.pt1.y);
                     }
                
                }
                else if(currentClick.x !=-1 && currentClick.y != -1  && aimant=='on')
                {
                        oldElem.setAttribute('d', polyPath+" "+currentClick.x+" "+currentClick.y);
                }
                else
                {
                    if( aimant=='on')
					{	ployPathPoints = polyPath.split(' ');
						lastPoint = new Point(ployPathPoints[ployPathPoints.length-2],ployPathPoints[ployPathPoints.length-1]);
						var positionMontree;
						
						if(ployPathPoints.length>0)
							positionMontree = setPositionMontree(lastPoint,mousePos);
						else
							positionMontree=new Point(mousePos.x+decalage*scaleValue.x,mousePos.y+decalage*scaleValue.y);
						
						oldElem.setAttribute('d', polyPath+" "+positionMontree.x+" "+positionMontree.y);
                    }
                    else
                        oldElem.setAttribute('d', polyPath+" "+mousePos.x+" "+mousePos.y);
                }
				
                curNode = oldElem;
                btnState="waitForClick";
               }
               
               
        }
        else 
        {      
		btnState="waitForClick";
		
                if(currentLine.pt1.x !=-1 && currentLine.pt1.y !=-1 
                         && currentLine.pt2.x !=-1 && currentLine.pt2.y !=-1  && aimant=='on')
                {
                       
                        if( getCloser(getMousePosition(evt),currentLine.pt1,currentLine.pt2)>0)      
                        {
                                 polyPath+="M "+currentLine.pt2.x+" "+currentLine.pt2.y+" "+currentLine.pt1.x+" "+currentLine.pt1.y;
                                 path+="M "+currentLine.pt2.x+" "+currentLine.pt2.y+" "+currentLine.pt1.x+" "+currentLine.pt1.y;       
                                 lastClick=currentLine.pt1;
                        }
                        else
                        {
                                 polyPath+="M "+currentLine.pt1.x+" "+currentLine.pt1.y+" "+currentLine.pt2.x+" "+currentLine.pt2.y;
                                 path+="M "+currentLine.pt1.x+" "+currentLine.pt1.y+" "+currentLine.pt2.x+" "+currentLine.pt2.y;
                                 lastClick=currentLine.pt2;
                        }
                }
                else if(currentClick.x !=-1 && currentClick.y != -1  && aimant=='on')
                {
				
                         polyPath="M "+currentClick.x+" "+currentClick.y;
                         path="M "+currentClick.x+"  "+currentClick.y+" L"+mousePos.x+" "+mousePos.y;
                         lastClick=currentClick;
                }
                else
                {
				
                        polyPath="M "+origX+" "+origY;
                        path="M "+origX+"  "+origY+" L"+mousePos.x+" "+mousePos.y;
                        lastClick.x=origX;
                        lastClick.y=origY;
                }
                isDrawing = 1;
                newNode = nodeClone(newNode = nodeClone(SVGDoc.getElementById("protoPolygon")));
                newNode.setAttributeNS("http://www.kevlindev.com/gui","edit","editable");
                newNode.setAttribute('id', elemID);
                curNode = newNode;
                newElem = newNode;
                newElem.setAttribute('d', path);
                newElem.setAttribute('style', styleTmp);
                //drawBoard.appendChild(newNode);
				drawBoardTmp.appendChild(newNode);
                btnState="waitForClick";
				
        }
        }
        }
}


function drawLigne() 
{
        
        if(shapeType=="ligne")
        {
               
        if(btnState=="UpClicked" || btnState =="end" ||btnState =="waitForClick")
        {
        var elemID = "ligne_" +ligneNum;
        var oldCheck = SVGDoc.getElementById(elemID);
        var mousePos = getMousePosition(evt);
        var path="";
        if (oldCheck!=null) 
        {
                var oldElem = oldCheck;
               if( btnState =="end")
               {
                       oldElem.setAttribute('d', polyPath);
                       btnState="Up";
                       polyPath="";
                       ligneNum++;
                       curNode.setAttribute('onmousemove', 'checkNear(evt)');
                       curNode.setAttribute('style', style);
					   
                       addShape(curNode,elemID);
					   
					   addedShapes.push(curNode);
					   indexAddedShapes.push(elemID);
					   drawBoard.appendChild(curNode);
					   curNode=null;
					   
               }
			   else if(deleted)
			   {
					deleted=false;
					drawBoard.removeChild(SVGDoc.getElementById(elemID));
					
			   }
               else
               {
                       
                       if(currentLine.pt1.x !=-1 && currentLine.pt1.y !=-1 
                         && currentLine.pt2.x !=-1 && currentLine.pt2.y !=-1  && aimant=='on')
                {
                     ployPathPoints = polyPath.split(' ');
                     lastPoint = new Point(ployPathPoints[ployPathPoints.length-2],ployPathPoints[ployPathPoints.length-1]);
                     
                     if((currentLine.pt1.x == lastPoint.x && currentLine.pt1.y == lastPoint.y))
                        oldElem.setAttribute('d', polyPath+" "+currentLine.pt2.x+" "+currentLine.pt2.y);
                        
                     else if((currentLine.pt2.x == lastPoint.x && currentLine.pt2.y == lastPoint.y) ) 
                        oldElem.setAttribute('d', polyPath+" "+currentLine.pt1.x+" "+currentLine.pt1.y);
                        
                     else
                     {
                     
                        var distPoint1 = Math.sqrt((mousePos.x-currentLine.pt1.x)*(mousePos.x-currentLine.pt1.x)+
                                                    (mousePos.y-currentLine.pt1.y)*(mousePos.y-currentLine.pt1.y)
                                                        );
                         var distPoint2 = Math.sqrt((mousePos.x-currentLine.pt2.x)*(mousePos.x-currentLine.pt2.x)+
                                                    (mousePos.y-currentLine.pt2.y)*(mousePos.y-currentLine.pt2.y)
                                                        );
                         if(distPoint1>distPoint2)
						 {
                                 oldElem.setAttribute('d', polyPath+" "+currentLine.pt1.x+" "+currentLine.pt1.y+" "+currentLine.pt2.x+" "+currentLine.pt2.y);
                         }
						 else
						 {
                                 oldElem.setAttribute('d', polyPath+" "+currentLine.pt2.x+" "+currentLine.pt2.y+" "+currentLine.pt1.x+" "+currentLine.pt1.y);
						 }
						 distPoint1=null;
						 distPoint2=null;
                     
                     }
                        
                }
                else if(currentClick.x !=-1 && currentClick.y != -1  && aimant=='on')
                {
				
                        oldElem.setAttribute('d', polyPath+" "+currentClick.x+" "+currentClick.y);
                }
                else
                {   
                        if(aimant=='on')
                        {
						
								ployPathPoints = polyPath.split(' ');
								lastPoint = new Point(ployPathPoints[ployPathPoints.length-2],ployPathPoints[ployPathPoints.length-1]);
								var positionMontree;
								
								if(ployPathPoints.length>0)
									positionMontree = setPositionMontree(lastPoint,mousePos);
								else
									positionMontree=new Point(mousePos.x+decalage*scaleValue.x,mousePos.y+decalage*scaleValue.y);
								
								oldElem.setAtt
						
                                oldElem.setAttribute('d', polyPath+" "+positionMontree.x+" "+positionMontree.y);
                        }
                        else
                                oldElem.setAttribute('d', polyPath+" "+mousePos.x+" "+mousePos.y);
                }
                        
                btnState="waitForClick";
               }
               
               newElem.setAttribute('id', elemID);
               
        }
        else 
        {
                 if(currentLine.pt1.x !=-1 && currentLine.pt1.y !=-1 
                         && currentLine.pt2.x !=-1 && currentLine.pt2.y !=-1  && aimant=='on')
                {
                        
                        var distPoint1 = Math.sqrt((mousePos.x-currentLine.pt1.x)*(mousePos.x-currentLine.pt1.x)+
                                                    (mousePos.y-currentLine.pt1.y)*(mousePos.y-currentLine.pt1.y)
                                                        );
                         var distPoint2 = Math.sqrt((mousePos.x-currentLine.pt2.x)*(mousePos.x-currentLine.pt2.x)+
                                                    (mousePos.y-currentLine.pt2.y)*(mousePos.y-currentLine.pt2.y)
                                                        );
                         if(distPoint1>distPoint2)
                         {
                                 polyPath+="M "+currentLine.pt1.x+" "+currentLine.pt1.y+" "+currentLine.pt2.x+" "+currentLine.pt2.y;
                                 path+="M "+currentLine.pt1.x+" "+currentLine.pt1.y+" "+currentLine.pt2.x+" "+currentLine.pt2.y;
                                 
                         }
                         else
                         {
                                 polyPath+="M "+currentLine.pt2.x+" "+currentLine.pt2.y+" "+currentLine.pt1.x+" "+currentLine.pt1.y;
                                 path+="M "+currentLine.pt2.x+" "+currentLine.pt2.y+" "+currentLine.pt1.x+" "+currentLine.pt1.y;
                         }
                }
                else
                {
                        polyPath="M "+origX+" "+origY;
                        path="M "+origX+"  "+origY+" L"+mousePos.x+" "+mousePos.y;
                }
              
             isDrawing = 1;
                newNode = nodeClone(newNode = nodeClone(SVGDoc.getElementById("protoLigne")));
                newNode.setAttributeNS("http://www.kevlindev.com/gui","edit","editable");
                newNode.setAttribute('id', elemID);
                newElem = newNode;
                curNode=newNode;
                newElem.setAttribute('d', path);
                newElem.setAttribute('style', styleTmp);
                drawBoardTmp.appendChild(newNode);
                btnState="waitForClick";
        }
        }
        }
}

function mouseClick()
{      if((evt.button!=2)&&(evt.button!=3)&&(evt.button!=4))
		{
			if(shapeType=="polygon" || shapeType == "ligne")
			{
					if(wasDblClick())
					{
							
							onDoubleClick();
							
					}
					else
					{
						   
							if(btnState=="waitForClick")
							{
									if(currentLine.pt1.x !=-1 && currentLine.pt1.y !=-1 
									&& currentLine.pt2.x !=-1 && currentLine.pt2.y !=-1  && aimant=='on')
									{
											var mousePos = getMousePosition(evt);
										  
											
										 ployPathPoints = polyPath.split(' ');
										 lastPoint = new Point(ployPathPoints[ployPathPoints.length-2],ployPathPoints[ployPathPoints.length-1]);
										 
										 if((currentLine.pt1.x == lastPoint.x && currentLine.pt1.y == lastPoint.y))
										 {
										
										   lastClick = currentLine.pt2;
										   polyPath+=" "+currentLine.pt2.x+" "+currentLine.pt2.y;
										 }
										 else if((currentLine.pt2.x == lastPoint.x && currentLine.pt2.y == lastPoint.y) ) 
										 {
										
											lastClick = currentLine.pt1;
											polyPath+=" "+currentLine.pt1.x+" "+currentLine.pt1.y;
										 }
										 else
										 {
											var distPoint1 = Math.sqrt((mousePos.x-currentLine.pt1.x)*(mousePos.x-currentLine.pt1.x)+
																		(mousePos.y-currentLine.pt1.y)*(mousePos.y-currentLine.pt1.y)
																			);
											 var distPoint2 = Math.sqrt((mousePos.x-currentLine.pt2.x)*(mousePos.x-currentLine.pt2.x)+
																		(mousePos.y-currentLine.pt2.y)*(mousePos.y-currentLine.pt2.y)
																			);
															
										
											 if(distPoint1>distPoint2)
											 {
											 
													 lastClick = currentLine.pt2;
													 polyPath+=" "+currentLine.pt1.x+" "+currentLine.pt1.y+" "+currentLine.pt2.x+" "+currentLine.pt2.y;
											 }
											 else
											 {
									
													 lastClick = currentLine.pt1;
													 polyPath+=" "+currentLine.pt2.x+" "+currentLine.pt2.y+" "+currentLine.pt1.x+" "+currentLine.pt1.y;
											 }
															
										 }
											
									}
									else
									{
											lastClick.x = origX;
											lastClick.y = origY;
											polyPath+= " "+origX+" "+origY;
									}
							}
							btnState="UpClicked";
					}
			}
			else if(shapeType=="point"){drawPoint(evt);}
		}
}
function wasDblClick()
{
        return (lastX <= origX+tolerance*scaleValue.x) && (lastX>=origX-tolerance*scaleValue.x) && (lastY <= origY+tolerance*scaleValue.x) && (lastY>=origY-tolerance*scaleValue.x);
}
function onDoubleClick()
{
		isDrawing = 0;
        if(shapeType == "polygon")
		{
			
               polyPath+="z"; 
			   drawBoard.appendChild(curNode);
			   
		}
	
         lastClick=new Point(-1,-1);
       btnState="end";
}
function itemSelected(evt)
{
       if(shapeType=="delete")
       {        
				
				var shapeId = evt.target.getAttribute('id');
				var shapeId2;
				if(shapeId.indexOf("REBORD_")>=0)
					shapeId2= shapeId.split("REBORD_")[1];
				else
				{
					shapeId2=shapeId;
					shapeId="REBORD_"+shapeId;
				}
		
				//addNodeToDeletedList(shapeId);
				
			
				addNodeToDeletedList(shapeId2);
                 shapePosition = getIdPosition(shapeId2);
				 id = supForArray(shapePosition,id);
                 //id.splice(shapePosition,1);
                 //shapes.splice(shapePosition,1);
				 shapes = supForArray(shapePosition,shapes);
				if(SVGDoc.getElementById(shapeId)!=null)
                 drawBoard.removeChild(SVGDoc.getElementById(shapeId));
				 
				 if(SVGDoc.getElementById(shapeId2)!=null)
					drawBoard.removeChild(SVGDoc.getElementById(shapeId2));
       }
	  /* else if(shapeType=="move")
	   {
				var shapeId = evt.target.getAttribute('id');
				var shapeId2;
				if(shapeId.indexOf("REBORD_")>=0)
					shapeId2= shapeIdsplit("REBORD_")[1];
				else
				{
					shapeId2=shapeId;
					shapeId="REBORD_"+shapeId;
				}
				
				
			//	alert(shapeId2);

				curId = shapeId2;
				var nodeTmp = SVGDoc.getElementById(shapeId2);
				var shpTmp = null;
				switch ( nodeTmp.localName ) 
				{
					case "circle":  shpTmp = new Circle(nodeTmp);    break;
					case "ellipse": shpTmp = new Ellipse(nodeTmp);   break;
					case "line":    shpTmp = new Line(nodeTmp);      break;
					case "path":    shpTmp = new Path(nodeTmp);      break;
					case "polygon": shpTmp = new Polygon(nodeTmp);   break;
					case "rect":    shpTmp = new Rectangle(nodeTmp); break;
				}
				
				shpTmp.mousedown(evt);

	   }*/
	   
}

function doAll(evt)
{
	doAllVar=true;
	moveCursor(evt);loadCurrentNode(evt);checkNear(evt);
}
function nodeClone(thisNode) 
{
        var newCopy = nodeCloneShallow(thisNode);
        var children = thisNode.getChildNodes();
        
        var childNum = children.getLength();
        var c;
         
        for (c=0; c < childNum; c++)
        {
                var childNode = children.item(c);
                var nodeType = childNode.getNodeType() -0;
                var newChild = nodeClone(childNode);
                newCopy.appendChild(newChild);
        }
        
        return newCopy;
}


function nodeCloneShallow(thisNode) 
{
        var i;
        var nodeType = thisNode.getNodeType() -0;
        var newNode, attrs, attrsLen;
        switch (nodeType) 
        {
                case 1:
                newNode = SVGDoc.createElement(thisNode.getTagName());
                attrs = thisNode.getAttributes();
                attrsLen = attrs.getLength();
               
                
                for (i = 0; i < attrsLen; i++) 
                {
                         
                        attrNode = attrs.item(i);
						
                        newNode.setAttribute(attrNode.getNodeName(),attrNode.getNodeValue());
                }
                
                break;
                
                case 2:
                newNode = SVGDoc.createAttributeNode(thisNode.getNodeName(), thisNode.getNodeValue());
                break;
                
                case 3:
                newNode = SVGDoc.createTextNode(thisNode.getData());
                break;
                
                case 8:
                newNode = SVGDoc.createCommentNode(thisNode.getData());
                break;
        }
        return newNode;
}

function changeImg(id,src)
{
        document.getElementById(id).setAttribute("xlink:href",imgDir+src);
}

function testVar(v)
{
	if(typeof(v)=="undefined") return false;
	if(v==null) return false;
	return true;
}
function unSelectAll(keepLastHelp,evt)
{      
        //la fonction est appell裠�haque clique sur un 譩ment du menu
        if(keepLastHelp=="yes")
        {
		
				if(testVar(aideTemp)==true)
                aideCourante = aideTemp;
				
				if(testVar(aideTemp2)==true)
                aideCourante2 = aideTemp2;
				
				if(testVar(aideTemp3)==true)
                aideCourante3 = aideTemp3;
				
				if(testVar(aideTemp4)==true)
                aideCourante4 = aideTemp4;
				
                toolTypeCourant = toolType;
				
				cancelCurrentShape();
        }

			
        if(shapeType!='point' && canUsePoint==true)
                SVGDoc.getElementById("rectTool0").setAttribute("xlink:href",imgDir+"point.jpg");
        if(shapeType!='rectangle' && canUsePoly ==true)
                SVGDoc.getElementById("rectTool1").setAttribute("xlink:href",imgDir+"rect.jpg");
        if(shapeType!='cercle' && canUsePoly ==true)
                SVGDoc.getElementById("rectTool2").setAttribute("xlink:href",imgDir+"cercle.jpg");
        if(shapeType!='polygon' && canUsePoly ==true)
                SVGDoc.getElementById("rectTool3").setAttribute("xlink:href",imgDir+"poly.jpg");
        if(shapeType!='ligne' && canUseLine ==true )
                SVGDoc.getElementById("rectTool4").setAttribute("xlink:href",imgDir+"path.jpg");
        if(shapeType!='move')
                SVGDoc.getElementById("rectTool5").setAttribute("xlink:href",imgDir+"fleche.jpg");
        if(shapeType!='delete')
                SVGDoc.getElementById("rectTool6").setAttribute("xlink:href",imgDir+"croix1.jpg");
        
}

function setPositionMontree(lastPoint,mousePos)
{
	var positionMontree;
	
	if(lastPoint.x<mousePos.x)
	{//vers la droite
		if(lastPoint.y<mousePos.y)
		{//vers le bas
			positionMontree=new Point(mousePos.x-decalage*scaleValue.x,mousePos.y-decalage*scaleValue.y);
		}
		else
		{//vers le haut
			positionMontree=new Point(mousePos.x-decalage*scaleValue.x,mousePos.y+decalage*scaleValue.y);
		}
	}
	else
	{//vers la gauche
		if(lastPoint.y<mousePos.y)
		{//vers le bas
			positionMontree=new Point(mousePos.x+decalage*scaleValue.x,mousePos.y-decalage*scaleValue.y);
		}
		else
		{//vers le haut
			positionMontree=new Point(mousePos.x+decalage*scaleValue.x,mousePos.y+decalage*scaleValue.y);
		}
	}
	
	return positionMontree;
}
function trimString(sInString) 
{
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

function splitL(str,sep)
{
	
	if(sep=="l")
	{
		var arr = str.split(sep);
	
		var cptTmp = 0 ;
		var deptX,deptY;
		deptX=deptY=null;
		var strRet=" ";
		var tmpValueX,tmpValueY;
		
		
			deptX=parseFloat(arr[0].split(",")[0]);
			deptY=parseFloat(arr[0].split(",")[1]);
			
			strRet = deptX+" "+deptY;
	
			for(cptTmp=1;cptTmp<arr.length;cptTmp++)
			{
		
					tmpValueX=parseFloat(arr[cptTmp].split(",")[0])+deptX;
					tmpValueY=parseFloat(arr[cptTmp].split(",")[1])+deptY;
									
					deptX = tmpValueX;
					deptY = tmpValueY;
					
					strRet+=" "+tmpValueX+" "+tmpValueY;
				
			}
		strRet=trimString(strRet);
		
		return strRet.split(" ");
	}
	else
	{
		var arr = str.split(sep);
		
		var strRet="";
		var i=0;
		var arrRet =new Array();
		for(i=0;i<arr.length;i++)
		{
			var tmpArr = arr[i].split(",");
			var j=0;
			
			for(j=0;j<tmpArr.length;j++)
			{
				if(tmpArr[j].indexOf(" ") >=0)
				{
					var a = tmpArr[j].split(" ");
					
					for(k=0;k<a.length;k++)
						if(!(isNaN(parseFloat(a[k]))))
							arrRet.push(a[k]);
				}
				else
					if(!(isNaN(parseFloat(tmpArr[j]))))
						arrRet.push(tmpArr[j]);
			}
		}
			
		return arrRet;
	}
}


//ZOOM

function convertViewToSys2(evt)
{
  mapCurrentX = ( evt.clientX) * scaleValue.x + origineX;
  mapCurrentY = ( evt.clientY) * scaleValue.y + origineY;	
}

function bouger(evt)
{

	convertViewToSys2(evt);
	
	if((appui==true)&&(curTool==209))
	{
		  var zoomrect= 'ZoomRectSVG'; 
		  var svgobj = svgDoc.getElementById (zoomrect); 
		  var svgstyle = svgobj.getStyle(); 
		
		 x1 = mapCurrentX;
		 y1 = mapCurrentY;
	
		svgobj.setAttribute('width',x1-x0);
		svgobj.setAttribute('height',y1-y0);
		
	}
	else if((appui==true)&&(curTool==213))
	{
		emptyDivMap();   
		x1 = mapCurrentX;
		y1 = mapCurrentY;
		var deltax = x1-x0;
		var deltay = y1-y0;
		
		if((deltax!=0)||(deltay!=0))
		{
			bufdeltax+=deltax;
			bufdeltay+=deltay;
			
			panMap(-deltay,-deltax);
			panCadres(-deltay,-deltax);
		
			
			x0 = x1;
			y0 = y1;
		}
		
		 	
	}
}

function cliquer(evt)
{
	
	
 if(curTool==209 && shapeType=="")
 {
	var zoomrect= 'ZoomRectSVG'; 
	var svgobj = svgDoc.getElementById (zoomrect); 
	var svgstyle = svgobj.getStyle(); 
	convertViewToSys2(evt);
	x0 = mapCurrentX;
	y0 = mapCurrentY;
	x1 = mapCurrentX;
	y1 = mapCurrentY;
	
	svgobj.setAttribute ('x', x0); 
	svgobj.setAttribute ('y', y0); 
	svgobj.setAttribute('width',0);
	svgobj.setAttribute('height',0);
	svgstyle.setProperty ('visibility', 'visible'); 
	appui=true;
 }
 
 if(curTool==213 && shapeType=="")
 {
	convertViewToSys2(evt);
	x0 = mapCurrentX;
	y0 = mapCurrentY;
	x1 = mapCurrentX;
	y1 = mapCurrentY;
	bufdeltax=0;
	bufdeltay=0;
	appui=true;
	
 }
	
}
	
	
	
function startZoom(factor)
{
    interval = window.setInterval("zoomPlus("+ factor + ")",100);
} 

function stopZoom()
{
    window.clearInterval (interval);
    interval="";
	var curech = GetEchelleMap();
	checkEmprise(curech);
}

function fitAll()
{
    mapObj.setAttribute("viewBox",originalviewbox);
	var viewboxes = originalviewbox.split(' ');
	widthMap = parseFloat(viewboxes[2]);
	heightMap = parseFloat(viewboxes[3]);
    maptop=ymincarto+heightMap;
	mapbottom=ymincarto;
	mapleft=xmincarto;
	mapright=xmincarto+widthMap;
	xmaxcarto = xmincarto+widthMap;
	ymaxcarto = ymincarto+heightMap;
	
	topMap=0;
	leftMap=0;
		
	RescaleSVG2(1/curZoom);
	
	curZoom = 1;
	zoomForScale=curZoom;
	curTool = 0;
	mapWidth=null;
	mapHeight=null;
 }  
    
 function rescaleDrawingObjects(diffscale)
 {
	
	node=SVGDoc.getElementById("cursor");
	//var newVal= node.getAttribute("r")/diffscale;
	var newVal2= node.getAttribute("stroke-width")/diffscale;
	//node.setAttribute("r", newVal);
	node.setAttribute("stroke-width", newVal2);
	
	/*node=SVGDoc.getElementById("accroch");
	node.setAttribute("r", newVal);
	
	node=SVGDoc.getElementById("accroch1");
	node.setAttribute("r", newVal);
	
	node=SVGDoc.getElementById("accroch2");
	node.setAttribute("r", newVal);
	*/

	handleWidth=handleWidth/diffscale;
	handleHeight=handleHeight/diffscale;

	handleStrokeWidth=handleStrokeWidth/diffscale;
	
	styleTmp='fill:none;stroke:red;stroke-width:'+scaleValue.x/diffscale+';fill-opacity:0;stroke-opacity:1;';
	

}


function RescaleSVG2(diffscale)
{
rescaleDrawingObjects(diffscale);
rescaleBorder(diffscale);
var i=0;
var node;
var layer;
var nombre;
var k=1;
var objet;
var cur_transform;
var indexscale;
var subscale;
var indexscale2;
var curscale;
var cureppaisseur


 
  node=drawBoard;
	if(node!=null)
	{
  layer=node.childNodes;
  nombre=layer.length;
	var k=0;
	// mise a jour des epaisseur sur le style du groupe

	if(node.nodeType==1)
	{
	
	var svgstyle = node.getStyle(); 
	var laststroke = svgstyle.getPropertyValue('stroke-width');
  
	var newstroke = parseFloat(laststroke);
	
	newstroke = newstroke/diffscale;
	svgstyle.setProperty('stroke-width',newstroke);
	
	
	
	}
	
	while (k<nombre)
	{
	
  	objet=layer.item(k);
  	if(objet.nodeType==1)
  	{
  	
  	 cur_transform = objet.getAttribute ("transform");
  	 indexscale = cur_transform.indexOf("scale(");
		 if(indexscale>=0)
		 {
  	 subscale = cur_transform.substr(indexscale,cur_transform.length-indexscale);
  	 indexscale2 = subscale.indexOf(")");
  	 curscale = parseFloat(subscale.substr(6,indexscale2-6));
  	 curscale = curscale/diffscale;
  	 subscale = cur_transform.substr(0,indexscale);
  	 cur_transform = subscale + "scale("+ curscale +")";
  	 objet.setAttribute("transform",cur_transform);
		 }
		 
	if(objet.getTagName()=="circle")
	{
		var r=objet.getAttribute('r');
			
		var newrayon = parseFloat(r);
		newrayon=newrayon/diffscale;
		objet.setAttribute('r',newrayon);
	}
		 
  	}
  	k=k+1;
	}

 }
 
}

function rescaleBorder(diffscale)
{
	var node=drawBoard;
	var layer=node.childNodes;
	var nombre=layer.length;
	
	k=0;
	
	while (k<nombre)
	{
		objet=layer.item(k);
		if(objet.nodeType==1)
		{
		var id = objet.getAttribute('id');
		if(id.indexOf("REBORD_")>=0)
		{
			if(newStyle==null)
			{
				var style=objet.getAttribute('style');
				var valTmp = style.split("stroke-width:");
				var val = valTmp[1].split(";fill-opacity:");
				var strokeWidth= val[0]/diffscale;
				
				newStyle= "stroke:white;fill:none;stroke-opacity:0.0001;stroke-width:"+strokeWidth+";fill-opacity:0;\" " ;
			
			}
			
			objet.setAttribute('style',newStyle);
		}
		}
		k++;
		
	}
	
	newStyle=null;
}

 
 
 
function zoomPlus(facteur)
{
 		var oldzoom = 	curZoom;		
		var viewbox = new String(mapObj.getAttribute("viewBox"));
		var viewboxes = viewbox.split(' ');
	
		
		var curwidthMap = parseFloat(viewboxes[2]);
		var curheightMap = parseFloat(viewboxes[3]);
	
		mapCurrentY = parseFloat(viewboxes[1])+curheightMap/2.0;
		mapCurrentX = parseFloat(viewboxes[0])+curwidthMap/2.0;
		var newtop;
		var newleft;
		var newwidth;
		var newheight;
		
		newwidth = curwidthMap*facteur;
		newheight = curheightMap*facteur;
		newbottom = mapCurrentY - newheight/2.0;
		newleft = mapCurrentX - newwidth/2.0;
	
		var viewbox = "" + newleft + " " + newbottom + " " + newwidth + " " + newheight;
		x0 = newleft;
		y0 = newbottom;
		
		curZoom = widthMap/(newwidth);
		ZoomY = heightMap/(newheight);
		if(ZoomY<curZoom)
			curZoom = ZoomY;
		
		zoomForScale=curZoom;
		var centerX = x0+newwidth/2.0;
		var centerY = y0+newheight/2.0;
	
	
		topMap = centerY-heightMap/(2.0*curZoom);
		leftMap = centerX-widthMap/(2.0*curZoom);
	
		mapObj.setAttribute("viewBox",viewbox);
		
		maptop = ymaxcarto - topMap;
		mapbottom = maptop - heightMap/(curZoom);
		mapleft = leftMap+xmincarto;
		mapright =leftMap+xmincarto+widthMap/(curZoom);
		
		RescaleSVG2(curZoom/oldzoom);
		oldzoom = curZoom;
}
function ConvertViewToSysSVGEdit(x,y)
{
		var pt = new Point();
		 		
		var viewbox = new String(mapObj.getAttribute("viewBox"));
		var viewboxes = viewbox.split(' ');
	
		
		var curwidthMap = parseFloat(viewboxes[2]);
		var curheightMap = parseFloat(viewboxes[3]);
	
				
		var curZoom = widthMap/(curwidthMap);
		var ZoomY = heightMap/(curheightMap);
		
		if(ZoomY<curZoom)
			curZoom = ZoomY;
			
	zoomForScale=curZoom;
		pt.x = x + xmincarto1;
		pt.y = ymaxcarto1-y ;

        return pt;
}
function setMapObjObject()
{
		var mainMap= 'MainMap'; 
	    mapObj = SVGDoc.getElementById (mainMap); 
}
function ConvertSVG2sys(x,y)
{
		mapCurrentX = x + xmincarto1;
		mapCurrentY = ymaxcarto1 - y;
}

function lacher(evt)
{




//alert("X:"+SVGDoc.getElementById("cadre").getAttribute("x")+"Y:"+SVGDoc.getElementById("cadre").getAttribute("y"));
		
  usedDeltaX = bufdeltax;
  usedDeltaY = bufdeltay;
  
	if(appui=true && shapeType =="")
	{
		appui=false;
	
	
	
	if((curTool==209)&&((x1-x0)!=0))
	{
		curTool = 0;
		mapZoom=true;
		var zoomrect= 'ZoomRectSVG';     
		var svgobj = svgDoc.getElementById (zoomrect); 
		var svgstyle = svgobj.getStyle(); 
		svgstyle.setProperty ('visibility', 'hidden'); 
		var oldzoom = 	curZoom;					
		var viewbox = "" + x0 + " " + y0 + " " + (x1-x0) + " " + (y1-y0);
			
		// zoom par click and drag
			
		curZoom = widthMap/(x1-x0);
		var ZoomY = heightMap/(y1-y0);
		if(ZoomY<curZoom)
				curZoom = ZoomY;
		
		zoomForScale=curZoom;
		var centerX = (x1+x0)/2.0;
		var centerY = (y1+y0)/2.0;
		
		
		topMap = centerY-heightMap/(2.0*curZoom);
		leftMap = centerX-widthMap/(2.0*curZoom);
		
		mapObj.setAttribute("viewBox",viewbox);
	
		var viewbox1 = new String(mapObj.getAttribute("viewBox"));
		
		
		
		maptop = ymaxcarto1 - topMap;
		mapbottom = maptop - heightMap/(curZoom);
		mapleft = leftMap+xmincarto1;
		mapright =leftMap+xmincarto1+widthMap/(curZoom);
		
		origineX = leftMap;
		origineY = topMap;
		
		RescaleSVG2(curZoom/oldzoom);
	
		
		if((y1-y0)/heightMap<(x1-x0)/widthMap)
			scaleValue.x = scaleValue.y=(x1-x0)/widthMap;
		else
			scaleValue.y = scaleValue.x=(y1-y0)/heightMap;
			
		//on envoie la requete de zoom pour la carte de fond
		
		
		
		var viewboxesValues = viewbox.split(' ');
		
		mapWidth=mapright-mapleft;
		mapHeight=maptop-mapbottom;
		


lastLeftSend=mapleft;
lastBottomSend=mapbottom;
lastWidthSend=mapWidth;
lastHeightSend=mapHeight;
		
		var loc = location.href;
		var chaine = szHttpServeur +
                    "&ACTION=BuildMap!EMPRISE=" + mapleft  + "@" + mapbottom + "@" + 
												  mapWidth	  + "@" +  mapHeight + 
									"!OUTPUTSIZE=" + widthMap + "@" + heightMap +
									"!LOCATION=" + loc ;
        		
				
		emptyDivMap();                                      
                updateBufferMap(chaine);
		
		curTool=209;
		
			
	}

	else if((curTool==210)||((curTool==209)&&((x1-x0)==0)))
	{
mapZoom=true;
	  var oldzoom = curZoom;		
	  convertViewToSys2(evt);
	  
	  var viewbox = new String(mapObj.getAttribute("viewBox"));
	  var viewboxes = viewbox.split(' ');
	
	  var curwidthMap = parseFloat(viewboxes[2]);
	  var curheightMap = parseFloat(viewboxes[3]);

	
	  var newtop;
	  var newleft;
		var newwidth;
		var newheight;
		var facteur = 2.0;
		if (curTool==209)
		{
		 facteur = 0.5;
		}
		newwidth = curwidthMap*facteur;
	    newheight = curheightMap*facteur;
		newbottom = mapCurrentY - newheight/2.0;
		newleft = mapCurrentX - newwidth/2.0;
	
		var viewbox = "" + newleft + " " + newbottom + " " + newwidth + " " + newheight;
		
		setCadreSVG(newleft,newbottom,newwidth,newheight);
	    x0 = newleft;
		y0 = newbottom;
		
		curZoom = widthMap/(newwidth);
	 ZoomY = heightMap/(newheight);
	if(ZoomY<curZoom)
			curZoom = ZoomY;
	
	zoomForScale=curZoom;
	 var centerX = x0+newwidth/2.0;
	 var centerY = y0+newheight/2.0;
	
	
	topMap = centerY-heightMap/(2.0*curZoom);
	leftMap = centerX-widthMap/(2.0*curZoom);
	
	mapObj.setAttribute("viewBox",viewbox);
		
		maptop = ymaxcarto - topMap;
		mapbottom = maptop - heightMap/(curZoom);
		mapleft = leftMap+xmincarto;
		mapright =leftMap+xmincarto+widthMap/(curZoom);
		
		
		RescaleSVG2(curZoom/oldzoom);
		oldzoom = curZoom;
		
	if((newheight)/heightMap<(newwidth)/widthMap)
		scaleValue.x = scaleValue.y=(newwidth)/widthMap;
	else
		scaleValue.y = scaleValue.x=(newheight)/heightMap;
		
	
		origineX = leftMap;
		origineY = topMap;
		
		var viewboxesValues = viewbox.split(' ');
		
		maptop = ymaxcarto1 - topMap;
		mapbottom = maptop - heightMap/(curZoom);
		mapleft = leftMap+xmincarto1;
		mapright =leftMap+xmincarto1+widthMap/(curZoom);
		
		mapWidth=mapright-mapleft;
		mapHeight=maptop-mapbottom;
			
		lastLeftSend=mapleft;
lastBottomSend=mapbottom;
lastWidthSend=mapWidth;
lastHeightSend=mapHeight;
		var loc = location.href;
		var chaine = szHttpServeur +
                    "&ACTION=BuildMap!EMPRISE=" + mapleft  + "@" + mapbottom + "@" + 
												  mapWidth	  + "@" +  mapHeight + 
									"!OUTPUTSIZE=" + widthMap + "@" + heightMap +
									"!LOCATION=" + loc ;
        		
				
		emptyDivMap();                                      
                updateBufferMap(chaine);
		
		
	
	}
	else if(curTool==213)
	{
	
		mapZoom=true;
		mapWidth=mapright-mapleft;
		mapHeight=maptop-mapbottom;
		
		lastLeftSend=mapleft;
		lastBottomSend=mapbottom;
		lastWidthSend=mapWidth;
		lastHeightSend=mapHeight;
		
		var loc = location.href;
		var chaine = szHttpServeur +
                    "&ACTION=BuildMap!EMPRISE=" + mapleft  + "@" + mapbottom + "@" + 
												  mapWidth	  + "@" +  mapHeight + 
									"!OUTPUTSIZE=" + widthMap + "@" + heightMap +
									"!LOCATION=" + loc ;
									
        updateBufferMap(chaine);
		
		origineX-= bufdeltax;
		origineY-= bufdeltay;

				
	}
	}
}



function translateEditedLayer(dxpercent,dypercent)
{
		emptyDivMap();      
		
 		var viewbox = new String(mapObj.getAttribute("viewBox"));
		var viewboxes = viewbox.split(' ');
		var curwidthMap = parseFloat(viewboxes[2]);
		var curheightMap = parseFloat(viewboxes[3]);
		panMap(curheightMap*dypercent,curwidthMap*dxpercent);
		
		
		var curech = GetEchelleMap();
	
		checkEmprise(curech);
		
	
}

function panCadres(dy,dx)
 {
		var viewbox = new String(mapObj.getAttribute("viewBox"));
		
		var viewboxes = viewbox.split(' ');
		
		var curwidthMap = parseFloat(viewboxes[2]);
		var curheightMap = parseFloat(viewboxes[3]);
		
		var newbottom = parseFloat(viewboxes[1])+dy;
		var newleft = parseFloat(viewboxes[0])+dx;
		
		
		var mmap = SVGDoc.getElementById("MainMap").getAttribute("viewBox");
		var v = mmap.split(' ');
		//alert(parseFloat(v[1]));
		//setCadreSVG(newleft,newbottom,curwidthMap,curheightMap);
		
		setCadreSVG(parseFloat(v[0])+dx,parseFloat(v[1])+dy,curwidthMap,curheightMap);
 }
 
 function setCadreSVG(x,y,width,height)
 {
		x+=SVGDoc.getElementById("cadre").getAttribute("x");
		y+=SVGDoc.getElementById("cadre").getAttribute("y");
		
		SVGDoc.getElementById("cadre").setAttribute("x",x);
		SVGDoc.getElementById("cadre").setAttribute("y",y);
		//SVGDoc.getElementById("cadre").setAttribute("width",width);
		//SVGDoc.getElementById("cadre").setAttribute("height",height);
		
		SVGDoc.getElementById("background").setAttribute("x",x);
		SVGDoc.getElementById("background").setAttribute("y",y);
		//SVGDoc.getElementById("background").setAttribute("width",width);
		//SVGDoc.getElementById("background").setAttribute("height",height);
 
 }
function addNodeToDeletedList(id)
{
	
	if(
		getDeletedIdPosition(id)==-1 &&
		getIndexPosition(id)==-1   &&
		id !="" && 
		id !="handle"
		){
		
			deletedShapes.push(id);
		}
	else if(
	
			getIndexPosition(id)  !=-1     &&
			id != "" && 
			id != "handle"
			
			)
	{
		var i = getIndexPosition(id);
			
		
		 indexAddedShapes=supForArray(i,indexAddedShapes);
		 addedShapes=supForArray(i,addedShapes);
	}
}

function supForArray(indice, arr)
{
	var arrTmp = new Array()
	
	var i=0;
	for(i=0;i<arr.length;i++)
	{
		if(i!=indice)
			arrTmp.push(arr[i]);
	}
	
	return arrTmp;
}

function addCurrentNodeToEditionList()
{
	if(currentID.indexOf("REBORD_")>=0)
					currentID= currentID.split("REBORD_")[1];
	if(currentID!="")
	{
	
		if(getEditedIdPosition(currentID)==-1 && getIndexPosition(currentID)==-1)
		{
		
			editedShapes.push(SVGDoc.getElementById(currentID));
			indexEditedShapes.push(currentID);
		}
		
	}
}

function currentNodeIsPoint()
{
	if(currentID!="")
	{
		
		var name = SVGDoc.getElementById(currentID).getTagName();
		
		if(name=="circle")
			return true;
	}
	

	return false;
}
function deployBar()
{
	//if(reloading==true)
		//initShowToolBar();
}

 function initShowToolBar()
 {
			scaleValShow=0;
			timerIdShow = setInterval('showToolBar()',25);
 }
        
 function showToolBar() 
 {
         scaleValShow += 0.1;
        if (scaleValShow > 1)
                clearInterval(timerIdShow);
        else 
               SVGDoc.getElementById("toolBar").setAttribute("transform", "scale(" + scaleValShow +")");
		
	
  } 
	
	
function getShapeToSendList()
{
	var ind=0;
		addedToSend=new Array();
 editedToSend=new Array();
	deletedToSend=new Array();	
	
	
	for(ind=0;ind<shapes.length;ind++)
	{
	
		var nodeSVG = shapes[ind].svgNode;
		
        var id = nodeSVG.getAttribute('id');
		
	
		if(getIndexPosition(id) != -1)
		{
			addedToSend.push(nodeSVG);
		}
		else if(getEditedIdPosition(id) != -1)
		{
			editedToSend.push(nodeSVG);
		}

		
			

	}

	deletedToSend= deletedShapes;
	
	
}

function getIndexPosition(shapeId)
{
	
         if(shapeId != null && shapeId!="")
                for(k=0;k<indexAddedShapes.length;k++)
                        if(indexAddedShapes[k] == shapeId) return k;
                        
         return -1;
}

function getIdSysFromLocal(shapeId)
{
         if(shapeId != null && shapeId!="")
                for(k=0;k<indexLocalIdShapes.length;k++)
                        if(indexLocalIdShapes[k] == shapeId) return k;
                        
         return -1;
}		
		


function getEditedIdPosition(shapeId)
{
         if(shapeId != null && shapeId!="")
                for(k=0;k<indexEditedShapes.length;k++)
                        if(indexEditedShapes[k] == shapeId) return k;
                        
         return -1;
}

function getDeletedIdPosition(shapeId)
{
         if(shapeId != null && shapeId!="")
                for(k=0;k<deletedShapes.length;k++)
                        if(deletedShapes[k] == shapeId) return k;
                        
         return -1;
}

//FIN des fonctions de zoom