var svgns  = "http://www.w3.org/2000/svg";
var azap; 
var mouser;
var points; 
var shapes;
var id;
var circle;
var circleNode;
var type="point";
var currentClick = new Point(-1,-1);
var currentLine;
var lastClick;
var svgDoc;


var currentNode;

var isMinNS4=(navigator.appName.indexOf("Netscape")>=0&&parseFloat(navigator.appVersion)>=4)?1:0;
function Point(x,y){this.x=x;this.y=y;}
function Ligne(pt1,pt2){this.pt1=pt1;this.pt2=pt2;}
var ligneIntersectee=null;
var background;
function changeType(str)
{type=str;}

/*****
*
*   init
*
*****/
function init(evt) 
{
	
	handleWidth=4*scaleValue.x;
	handleHeight=4*scaleValue.y;
	handleStrokeWidth=scaleValue.x;
	
	styleTmp='fill:none;stroke:red;stroke-width:'+scaleValue.x+';fill-opacity:0;stroke-opacity:1;';
	style="";
	
	if(evt.target != null)	
	{
		var tmp =evt.target;
		svgDoc = tmp.ownerDocument;
	}

	azap   = new AntiZoomAndPan();
	mouser = new Mouser();
	points = new Array();
	shapes = new Array();
	id = new Array();
	 
	currentLine= new Ligne( new Point(-1,-1),new Point(-1,-1));
	lastClick=new Point(-1,-1);
	 
    background = svgDoc.getElementById("background");
    
    azap.appendNode(mouser.svgNode);
    azap.appendNode(background);
    
    circleNode = svgDoc.getElementById("cursor"); //cercle d'accrochage
    circleAccroch = svgDoc.getElementById("accroch");
    circleAccrochLine1 = svgDoc.getElementById("accroch1");
    circleAccrochLine2 = svgDoc.getElementById("accroch2");
	
    circle = new Circle(circleNode); //cercle d'accrochage
	
	reinitAccroch();
}
/**
*Ajoute la forme correspondant aunoeud passé en paramètre
* a la liste des formes
**/
function addShape(child,curid)
{		
        var shapeToAdd;
        
        switch ( child.localName ) 
        {
            case "circle":  shapeToAdd = new Circle(child);    break;
            case "ellipse": shapeToAdd = new Ellipse(child);   break;
            case "line":    shapeToAdd = new Line(child);      break;
            case "path":    shapeToAdd = new Path(child);      break;
            case "polygon": shapeToAdd = new Polygon(child);   break;
            case "rect":    shapeToAdd = new Rectangle(child); break;
        }

        if ( shapeToAdd != null ) 
        {
                id.push(curid);
                shapeToAdd.realize();
                shapes.push(shapeToAdd);
        }

}

/**
*S'il n'est pas charger, chargele noeud survollé par la souris en tant que forme intersecable
**/
function loadCurrentNode(evt)
{
		var curid = evt.target.getAttribute('id');
		
		if(curid != "cursor" && curid != "")
		{
	
		if(curid!="handle")
			currentID = curid;
			
		currentNode=null;
		
		if(curid.indexOf("REBORD_")>=0)
		{
			
			curid= curid.split("REBORD_")[1];
			
			
		}
		
		//on ne charge pas la forme que l'on est en train de dessiner ni les poingnées ni les rebords
		if( curid != ("ellipse_"+ellipseNum) &&
			curid != ("rectangle_"+rectangleNum) &&
			curid != ("point_"+pointNum) &&
			curid != ("polygon_"+polygonNum) &&
			curid != ("ligne_"+ligneNum) &&
			curid!="" && 
			curid!="handle"
		
			
			)
		{
				

			//var child = evt.target;
			
		
			var child = SVGDoc.getElementById(curid);
			var cptTmp = getIdPosition(curid);
			
			if(cptTmp == -1)
			{
			
				var shapeToAdd;
				//alert(child.localName);
				switch ( child.localName ) 
				{
				
					case "circle":  shapeToAdd = new Circle(child);    break;
					case "ellipse": shapeToAdd = new Ellipse(child);   break;
					case "line":    shapeToAdd = new Line(child);      break;
					case "path":    shapeToAdd = new Path(child);      break;
					case "polygon": shapeToAdd = new Polygon(child);   break;
					case "rect":    shapeToAdd = new Rectangle(child); break;
				}
		
				if ( shapeToAdd != null ) 
				{
						id.push(curid);
						shapeToAdd.realize();
						shapes.push(shapeToAdd);
						currentNode=shapeToAdd;
						
				}
			}
			else
				currentNode=shapes[cptTmp];
		}
		}
		
	
}

/**
*Démarre la détéction d'intersection
**/
function checkNear (evt)
{ 		
	if( shapeType !="move" &&
		shapeType != "delete" &&
		aimant=='on' 
		&& currentNode!=null
	  )
	{
		if(testVar( evt.target)==false)
			alert("undef");
			
		
		shapeId = evt.target.getAttribute('id'); 
		
		if(shapeId != "cursor")
		{
			//alert(shapeId);	
			if(shapeId.indexOf("REBORD_")>=0)
			{
				
				shapeId= shapeId.split("REBORD_")[1];
				
			}
			
			var pt = getMousePosition(evt);
			if(testVar(circleNode)==false)alert("undef");
			circle = new Circle(circleNode);
			if(testVar(circle)==false)alert("undef");
			circle.realize();
			circle.callback = showIntersections;
			showIntersections(evt,shapeId);
		}
	}

}

/**
*Déplacement du cercled'intersection
**/
function moveCursor(evt)
{       
	var mousePos = getMousePosition(evt);
	circleNode.setAttributeNS(null, "cx", mousePos.x);
	circleNode.setAttributeNS(null, "cy", mousePos.y);
}

/**
*Réinitialisationdes cercles d'accrochage
**/
function reinitAccroch()
{
	circleAccrochLine2.setAttribute ('visibility', 'hidden'); 
	circleAccrochLine1.setAttribute ('visibility', 'hidden'); 
	circleAccroch.setAttribute ('visibility', 'hidden'); 
	
	currentClick.x = -1;
	currentClick.y= -1;
   
	currentLine= new Ligne( new Point(-1,-1),new Point(-1,-1));
}

/*****
*
*   showIntersections
*       Zone de traitement des intersections
*
*****/
function showIntersections(evt,shapeId) 
{
//alert(shapeId);
	if(ellipseCenterDefined==false)
	{
    if( shapeType!="delete"  && shapeType!="move" )
    {
	
    var cptTmp = getIdPosition(shapeId);
    
    reinitAccroch(); //on réinitialise les pointeurs d'accroche
   	  
        var inter = Intersection.intersectShapes( circle,shapes[cptTmp]  );
		
         if(inter.points.length > 0)
         {
				var intersectedShapeName = shapes[cptTmp].getIntersectionParams().name;
				
                 if( evt.altKey && shapeType!="rectangle" && shapeType!="ellipse" && shapeType !="point")
                 {
                       if( intersectedShapeName == "Circle" || intersectedShapeName == "Ellipse" )
						{
						
							parameters = new String(shapes[cptTmp].getIntersectionParams().params);
							setSimpleAccroch(false,(parameters.split(","))[0],(parameters.split(","))[1])
						}
						else
						{
							if(intersectedShapeName == "Line")
							{
							    ligneIntersectee =new Ligne();
							   
								ligneIntersectee.pt1.x=shapes[cptTmp].getIntersectionParams().params.split(",")[0];
								ligneIntersectee.pt1.y=shapes[cptTmp].getIntersectionParams().params.split(",")[1];
								ligneIntersectee.pt2.x=shapes[cptTmp].getIntersectionParams().params.split(",")[2];
								ligneIntersectee.pt2.y=shapes[cptTmp].getIntersectionParams().params.split(",")[3];
							}
							
							setAccrochLine();
						}
                                
                 }
                else
                {
                       if( intersectedShapeName == "Circle" || intersectedShapeName == "Ellipse" )
                       {
                                   parameters = new String(shapes[cptTmp].getIntersectionParams().params);
								   
                                   setSimpleAccroch(false,parameters.split(",")[0],parameters.split(",")[1]);
                       }
                       else
                       {
                               if(evt.ctrlKey)
                               {
									if(intersectedShapeName == "Path" || intersectedShapeName == "Rectangle")
										setSimpleAccroch(true);
                               }   
                               else
                               {
							   
									if(inter.points.length==1)
											setSimpleAccroch(false,inter.points[0].x,inter.points[0].y);
									else
									{
										if (inter.nbSegment >1)
										{
											if(intersectedShapeName == "Path" || intersectedShapeName == "Rectangle")
												setSimpleAccroch(true);
											 /*if( getCloser(getMousePosition(evt),inter.points[0],inter.points[1])>0)      
													setSimpleAccroch(false,inter.points[0].x,inter.points[0].y);
											  else
													setSimpleAccroch(false,inter.points[1].x,inter.points[1].y);*/
										}
										else
										{
											var ptAccroch =getCenterIntersection(inter.points[0],inter.points[1]);
											setSimpleAccroch(false,ptAccroch.x,ptAccroch.y);
										}
									}
									
										
												
                               }
                       }
                 }
       }
    }
	}
}

function getCenterIntersection(pt1,pt2)
{
	var ptCenter = new Point();
	ptCenter.x = (pt1.x+pt2.x)/2.0;
	ptCenter.y = (pt1.y+pt2.y)/2.0;
	
	return ptCenter;
}


/**
*Retourne l'indiced'uneforme dans le tableau shapes par rapportà son id
* retourne -1 si elle ny est pas
**/
function getIdPosition(shapeId)
{
         if(shapeId != null && shapeId!="")
                for(k=0;k<id.length;k++)
                        if(id[k] == shapeId) return k;
                        
         return -1;
}

/**
*Retourne la distance séparant deux points
**/
function getDistance(point1, point2)
{
  return Math.sqrt
            (
                (point1.x-point2.x)*(point1.x-point2.x)+
                (point1.y-point2.y)*(point1.y-point2.y)
            );
                                                   
}

/**
*Function getCloser 
*retourne 1 si point1 est le plus pres de origine
*         -1 si point2 est le plus pres de origine
*         0 si les deux point son equidistant de l'origine
*/
function getCloser(origine, point1, point2)
{
        var distance1= getDistance(origine, point1);
        var distance2= getDistance(origine, point2);
        
        if(distance1<distance2) return 1;
        if(distance1>distance2) return -1;
        return 0;
}

/**
*Function setAccrochLine
*utilisé lors de l'accrochage par ligne
*Utilise la variable globale ligneIntersectee pour positionner les poitns d'accrochage
*remet la variable à null
**/
function setAccrochLine()
{	
	circleAccrochLine1.setAttributeNS(null,"cx",ligneIntersectee.pt1.x);
	circleAccrochLine1.setAttributeNS(null,"cy",ligneIntersectee.pt1.y);
	
	circleAccrochLine2.setAttributeNS(null,"cx",ligneIntersectee.pt2.x);
	circleAccrochLine2.setAttributeNS(null,"cy",ligneIntersectee.pt2.y);
	
	circleAccrochLine1.setAttribute ('visibility', 'visible'); 
	circleAccrochLine2.setAttribute ('visibility', 'visible'); 
	
	currentLine = ligneIntersectee;
	ligneIntersectee=null;
}

/**
*Function setSimpleAccroch
*utilisée lors de l'accrochage simple ou sur l'extrémité du segment courant
*Dans ledeuxieme cas, on utilise la variable globale ligneIntersectee pour positionner le point d'accrochage
*remet la variable à null
**/
function setSimpleAccroch(useLigneIntersectee,x,y)
{
	if(useLigneIntersectee)
	{
		//on s'accroche sur l'éxtrémité d'un segment
		
		var posX,posY;
		
		if(  getCloser(getMousePosition(evt),ligneIntersectee.pt1,ligneIntersectee.pt2)>0 )
		{
			posX = ligneIntersectee.pt1.x;
			posY = ligneIntersectee.pt1.y;
		}
		else
		{
			 posX = ligneIntersectee.pt2.x;
			 posY = ligneIntersectee.pt2.y;
		}
		
		circleAccroch.setAttributeNS(null,"cx",posX);
		circleAccroch.setAttributeNS(null,"cy",posY);
		
		currentClick.x=posX;
		currentClick.y=posY;
	}
	else
	{
	
		var posX,posY;
		var ptTmp = new Point(x,y);
		if(ligneIntersectee != null && ligneIntersectee.pt1 !=null && ligneIntersectee.pt2 !=null)
		{
		if(  getCloser(ptTmp,ligneIntersectee.pt1,ligneIntersectee.pt2)>0 )
		{
			posX = ligneIntersectee.pt1.x;
			posY = ligneIntersectee.pt1.y;
		}
		else
		{
			 posX = ligneIntersectee.pt2.x;
			 posY = ligneIntersectee.pt2.y;
		}
		
		var distance = Math.sqrt((ptTmp.x-posX)*(ptTmp.x-posX)+(ptTmp.y-posY)*(ptTmp.y-posY));
		
		//alert("DIST : "+distance+" val : "+scaleValue.x+" DIV : "+distance/scaleValue.x);
		if(distance/scaleValue.x <7)
		{
			currentClick.x=posX;
			currentClick.y=posY;
		}
		else
		{
		//accrochage simple, on remplace lesvaleur de circleAccroch
		currentClick.x=x;
		currentClick.y=y;
		}
		}
		else
		{
			currentClick.x=x;
		currentClick.y=y;
		}
		
		
		circleAccroch.setAttributeNS(null,"cx",currentClick.x);
		circleAccroch.setAttributeNS(null,"cy",currentClick.y);
		
	}
		
		circleAccroch.setAttribute ('visibility', 'visible'); 
	
	ligneIntersectee=null;
}
  