var map = null;
//var slDrawing = new VEShapeLayer();
var myGeomType = null;
var myCurrentShape = null;
var myPoints = new Array();
var myDistance = 0;
var tempShape = null;
var tempPoints = null;
var tempDistance = 0;
var myCirclePoints = null;
var tempCircle = null;
var i = 1;

//agg.
var tipoObj = "";
var coordObj = "";

function Draw(geomType) {
    myGeomType = geomType;
    map.AttachEvent("onkeypress", DrawPolyMouseClick);
    map.AttachEvent("onmousemove", MouseMove);
    prendiElementoDaId("myMap").style.cursor='crosshair';
    
}

function MouseMove(e) {
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    var LL = map.PixelToLatLong(pixel);
    //prendiElementoDaId("txtLat").value = LL.Latitude;
    //prendiElementoDaId("txtLon").value = LL.Longitude;
}

function DrawPolyMouseClick(e) {
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    var LL = map.PixelToLatLong(pixel);    
    
       
    if (myPoints && myPoints.length == 0 && myGeomType != "point") 
    {
        map.DetachEvent("onmousemove", MouseMove);
        map.AttachEvent("onmousemove", DrawPolyMouseMove);
        prendiElementoDaId("divDistance").style.visibility = "visible";
    }
    
    if (myPoints && myGeomType == "circle" && myPoints.length == 2)
    {
        myPoints[1] = LL;
        myDistance = tempDistance;
    }
    else if (myPoints)
    {
	  	    
		myPoints.push(LL);
		//Aggiunte
		var ii = 0;
		var coord = "";
		while (ii < myPoints.length){
			coord += myPoints[ii] + " ";   
			ii++; 
		}    
		//fine agg.
		myDistance = myDistance + tempDistance;
	    
    }
    
    if (e.keyCode == 13)  {
        try
        {
            map.DetachEvent("onmousemove", DrawPolyMouseMove);
            map.DetachEvent("onclick", DrawPolyMouseClick);
            prendiElementoDaId("divDistance").style.visibility = "hidden";
            slDrawing.DeleteShape(tempShape);
            slDrawing.DeleteShape(tempCircle);
        }
        catch (err)
        {
        }
        
		//Aggiunte
		var ii = 0;
		var coord = "";
		while (myPoints && ii < myPoints.length){
			coord += myPoints[ii] + " ";   
			ii++; 
		}
		var tipo = ""; 
		//fine agg.
	    
	    
        myCurrentShape = "shape" + i;
        myDistance = Math.round(myDistance * 1000) / 1000;
        switch (myGeomType) 
        {
            case "polygon":
                myCurrentShape = new VEShape(VEShapeType.Polygon, myPoints);
				var coordstxt = new String(myPoints.toString());
//                prendiElementoDaId("txtShapeDetails").value = coordstxt.replace(new RegExp(/,/g), " ");
                
                tipo = "3";
                
                break;
            case "polyline":
                myCurrentShape = new VEShape(VEShapeType.Polyline, myPoints);
//                prendiElementoDaId("txtShapeDetails").value = "Distance: " + myDistance + " km";
                
                tipo = "2";
                
                break;
            case "circle":
                myCurrentShape = new VEShape(VEShapeType.Polygon, myCirclePoints);
//                prendiElementoDaId("txtShapeDetails").value = "Radius: " + myDistance + " km";
                break;
            case "point":
                myCurrentShape = new VEShape(VEShapeType.Pushpin, LL);
                
                tipo = "1";
                
                break;
        }
        
        
        slDrawing.AddShape(myCurrentShape);
        prendiElementoDaId("txtShapeID").value = "shape" + i;
        i = i + 1;
        var dummy = prendiElementoDaId("divShapeInfo");
        
//        dummy.style.left = e.clientX + "px";
        dummy.style.left = 780 + "px";
//        dummy.style.top = e.clientY + "px";
        dummy.style.top = 220 + "px";
        dummy.style.visibility = "visible";
        prendiElementoDaId("myMap").style.cursor = 'http://maps.live.com/cursors/grab.cur';
		
        //salvo i dati a DB	
		coordObj = coord;
		tipoObj = tipo;
		myPoints = null
		
		   
	} else {
       prendiElementoDaId("myMap").style.cursor='crosshair';
        
    }
}

function DrawPolyMouseMove(e) {
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    var LL = map.PixelToLatLong(pixel);
    //prendiElementoDaId("txtLat").value = LL.Latitude;
    //prendiElementoDaId("txtLon").value = LL.Longitude;    
    
    tempPoints = myPoints.slice(0, myPoints.length);
    
    
    if (tempPoints && myGeomType == "circle" && tempPoints.length == 2)
    {
        tempPoints[1] = LL;
        tempDistance = getDistance(tempPoints[0], LL);
    }
    else if (tempPoints)
    {
        tempPoints.push(LL);
        tempDistance = getDistance(tempPoints[myPoints.length-1], LL);
    }    var dummy = prendiElementoDaId("divDistance");
    dummy.style.left = e.clientX + "px";
    dummy.style.top = e.clientY + "px";
    dummy.innerHTML = Math.round((myDistance + tempDistance) * 1000) / 1000;    try
    {
        slDrawing.DeleteShape(tempShape);
        slDrawing.DeleteShape(tempCircle);
    }
    catch (err)
    {
    }
    
    if (tempPoints && tempPoints.length == 2)
    {
        tempShape = new VEShape(VEShapeType.Polyline, tempPoints);
        tempShape.HideIcon();
        slDrawing.AddShape(tempShape);
        if (myGeomType == "circle")
        {
            GetCircle();
            tempCircle = new VEShape(VEShapeType.Polygon, myCirclePoints);
            tempCircle.HideIcon();
            slDrawing.AddShape(tempCircle);
        }
    }
    
    if (tempPoints && tempPoints.length > 2)
    {
        switch (myGeomType) 
        {
            case "polygon":
                tempShape = new VEShape(VEShapeType.Polygon, tempPoints);
                break;
            case "polyline":
                tempShape = new VEShape(VEShapeType.Polyline, tempPoints);
                break;
        }
        tempShape.HideIcon();
        slDrawing.AddShape(tempShape);
    }
}//calculate distance

function getDistance(p1, p2) {
    p1Lat = latLonToRadians(p1.Latitude);
	p1Lon = latLonToRadians(p1.Longitude);
	
	p2Lat = latLonToRadians(p2.Latitude);
	p2Lon = latLonToRadians(p2.Longitude);	
	
	var R = 6371; // earth's mean radius in km
	var dLat  = p2Lat - p1Lat;
	var dLong = p2Lon - p1Lon;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1Lat) * Math.cos(p2Lat) * Math.sin(dLong/2) * Math.sin(dLong/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var disKm = R * c;
	//var disMiles = disKm * 0.6214;	
	return (disKm);
}//convert lat/long in degrees to radians

function latLonToRadians(point) {
	return point * Math.PI / 180;	
}//Draw Circle

function GetCircle() {
    var R = 6371; // earth's mean radius in km
    var lat = (myPoints[0].Latitude * Math.PI) / 180; //rad
    var lon = (myPoints[0].Longitude * Math.PI) / 180; //rad
    var d = parseFloat(tempDistance) / R;  // d = angular distance covered on earth's surface
    myCirclePoints = new Array();
    for (x = 0; x <= 360; x++) 
    { 
        var p2 = new VELatLong(0,0)            
        brng = x * Math.PI / 180; //rad
        p2.Latitude = Math.asin(Math.sin(lat)*Math.cos(d) + Math.cos(lat)*Math.sin(d)*Math.cos(brng));
        p2.Longitude = ((lon + Math.atan2(Math.sin(brng)*Math.sin(d)*Math.cos(lat), Math.cos(d)-Math.sin(lat)*Math.sin(p2.Latitude))) * 180) / Math.PI;
        p2.Latitude = (p2.Latitude * 180) / Math.PI;
    	//Aggiunte
        var ii = 0;
        var coord = "";
        while (ii < myCirclePoints.length){
	    	coord += myCirclePoints[ii] + " ";   
	    	ii++; 
	    }    
    	//Fine Agg.
   
        myCirclePoints.push(p2);
    }
    return myCirclePoints;
}

function SetInfo() {
    myCurrentShape.SetTitle(prendiElementoDaId("txtShapeTitle").value);
//    myCurrentShape.SetDescription(prendiElementoDaId("txtShapeDetails").value + "<br><a href='javascript:DelShape(\"" + myCurrentShape.GetID() + "\")'>Elimina</a>");    
	myPoints = new Array();
    tempPoints = null;
    myDistance = 0;
    tempDistance = 0;

    if (prendiElementoDaId("txtShapeTitle").value != ""){
	    //Salvo i dati a db    
		  newObj(prendiElementoDaId("txtShapeTitle").value,prendiElementoDaId("txtShapeDetails").value,tipoObj,coordObj);    
	    var dummy = prendiElementoDaId("divShapeInfo").style.visibility = "hidden";
	    prendiElementoDaId("txtShapeTitle").value = "";
	    prendiElementoDaId("txtShapeDetails").value = "";
		} else {
			alert('Inserire un titolo!');
		}   
	  
}


function SetInfo2(id) {
//    myCurrentShape.SetTitle(prendiElementoDaId("txtShapeTitle").value);
    myCurrentShape.SetDescription(prendiElementoDaId("txtShapeDetails").value + "<br><a href='javascript:DelShape(\"" + id + "\",\"" + myCurrentShape.GetID() + "\")'>Elimina2</a>");    
/*
	myPoints = new Array();
    tempPoints = null;
    myDistance = 0;
    tempDistance = 0;

    var dummy = prendiElementoDaId("divShapeInfo").style.visibility = "hidden";
    prendiElementoDaId("txtShapeTitle").value = "";
    prendiElementoDaId("txtShapeDetails").value = "";
*/
    
}


function DelShape(id,shape) {
	//elimino l'elemento appena creato
    var delShape = slDrawing.GetShapeByID(shape);
    slDrawing.DeleteShape(delShape);
    //Elimino i dati a db    
	delObj(id);    
    
}

