var map = null;
var pinPoint = null;
var pinPixel = null;
     
var lat = 34.118875035799;
var lon = -118.3003306388855;
var l = new VEShapeLayer(); 
          
//per disegnare
var slDrawing = new VEShapeLayer();

function GetMap(idP)
{
	map = new VEMap('myMap');
	map.LoadMap();
	//per disegnare
	map.AddShapeLayer(slDrawing);
	map.SetZoomLevel(14);
	map.SetMapStyle('h');
	map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
	try {
		if (idP==""){
			var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, "../maph/georss.php", l);           
		} else {
			var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, "../maph/georss.php?" + idP, l);           
		}	
//	alert("../maph/georss.php?" + idP);
		//			var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, "test.xml", l);           
		map.ImportShapeLayerData(veLayerSpec, onFeedLoad);        
		
		map.SetCenterAndZoom (new VELatLong(45.700,12.626),9);
		map.ShowMiniMap(13, 250);
    // The onclick event to call the callPopUp function
    //map.AttachEvent("onzoomchanged", map.SetZoomLevel(17));
		
	} catch (Err) {
		alert (Err);		
	}	
	
}
         
//=========Icone per i 3 tipi di Primitive ============
function setIcona(tipo) {
	if (tipo != null) {
//			return "<span style='font-family:Arial; font-size:x-small; color:Black; background-color:White'><img src='./img/linea.jpg' width='50px' />linea</span>";	
		if (tipo == 1) {//punto
			return "<img src='../maph/img/punto.gif' />";	
		} else if (tipo == 2){//linea
			return "<img src='../maph/img/clear.gif' height='30px' width='30px' />";	
		} else if (tipo == 3){//poligono
			return "<img src='../maph/img/clear.gif' height='30px' width='30px' />";	
		}
	}
	return "../img/clear.gif";	
	
		
}
//====================         
         
//=== elimino la key ==
function delKey(titolo){
	var splitted = titolo.split("|");
	if (splitted[1] != null) {
		return splitted[1];
	} else {
		return titolo;
	}
	
}

//=== nascondo la key ==
function hideKey(titolo){
	var splitted = titolo.split("|");
	if (splitted[1] != null) {
		return "<!--" + splitted[0] + "-->" + splitted[1];
	} else {
		return titolo;
	}
	
}

//=== ricavo la key ==
function getIDObj(titolo){
	var splitted = titolo.split("|");
	if (splitted[0] != null) {
		return splitted[0];
	} else {
		return "";
	}
	
}

       
//======= Aggiunta di eventi =====         

function onFeedLoad(layer) {
	var numShapes = layer.GetShapeCount();
//		alert ("oggetti caricati: " + numShapes.toString());
	for(var i=0; i < numShapes; ++i) {
		var shape = layer.GetShapeByIndex(i);
		shape.SetCustomIcon("../maph/img/bandiera.png");
		// giovanni 20071112
//		shape.SetFillColor(new VEColor(0,150,100, Math.random()));
		//andrea 20070822
		var GeomType = shape.GetType();
        switch (GeomType) 
        {
            case "Point":
//Andrea 20070926 togliere commento				shape.SetCustomIcon(setIcona(1));  
								
                break;
            case "Polyline":
				shape.SetCustomIcon(setIcona(2));  
				shape.SetLineWidth(6);		
				shape.SetLineColor(new VEColor(254,220,0,0.7));

                break;
            case "Polygon":
				shape.SetCustomIcon(setIcona(3));
				shape.SetLineWidth(6);		
				shape.SetLineColor(new VEColor(254,220,0,0.7));
				shape.SetFillColor(new VEColor(200,255,0,0.4));
                break;
        }
		if (shape.GetTitle().indexOf("| Comune di") > 0) {
            shape.SetCustomIcon("../maph/img/comune.png");
        };
		// giovanni 20071112

//			alert (s.GetDescription());

//			document.getElementById('label').innerHTML = "<p>Hover over the polygon for info about this shape!</p>"
        
        // The onclick event to call the callPopUp function
				//progress bar
//				map.AttachEvent("onchangeview", prendiElementoDaId3("progress").src='../maph/img/clear.gif');
//				map.AttachEvent("onchangeview", alert(prendiElementoDaId3("progress").src='../maph/img/clear.gif');


        // The onmouseover event which calls the shapeInfo function
        map.AttachEvent("onmouseover", shapeInfo);
    
        // The onmouseout event that calls the shapeInfo function to clear the info element
        //da lasciare nel F.E. map.AttachEvent("onmouseout", hideshapesInfo);
	      map.AttachEvent("onmouseout", shapeInfo);

	      
//	alert('passo2');
	      	      
	      //Change Zoom
	      if (map.GetZoomLevel() >= 17) {
		      map.SetZoomLevel(17);
	    	}  


	}
}

// funzione per prendere un elemento con id univoco
function prendiElementoDaId3(id_elemento) {
	var elemento;
	if(document.getElementById)
		elemento = document.getElementById(id_elemento);
	else
		elemento = document.all[id_elemento];
	return elemento;
}

/*		//creo un poligono e gli aggiungo degli eventi
		function drawPolygon()
        {
            map.DeleteAllShapes();
            
            try
            {
				// Custom HTML for pushpin popup (This is NEW in V5!)

				// titolo dell'oggetto
				var title = "<div id='customTitle'><h3>Titolo dell'oggetto</h3></div>";		        
								
				// descrizione dell'oggetto
		        var description = "<div>"
		        +"descrizione dell'oggetto ..."
		        +"<br>descrizione ..."
		        +"</div>";
	            
		        
		        //Elementi aggiuntivi: Elimina
		        var btnElimina = "<div>"
		        +"<input type='button' name='Elimina' value='Elimina'>"
		        +"</div>";
		        
		        var xc = lon;
		        var yc = lat;
		        var y1 = 0.0015;
		        var x1 = 0.0025;
				var points=[new VELatLong(yc,xc-0.0010),
		            new VELatLong(yc+y1,xc-x1),
		            new VELatLong(yc+y1,xc+x1),
		            new VELatLong(yc,xc+0.0015),
		            new VELatLong(yc-y1,xc+x1),
		            new VELatLong(yc-y1,xc-x1)];	            
	            
                var shape = new VEShape(VEShapeType.Polygon,points);
                
                //Andrea: icona personalizzata
				shape.SetCustomIcon(setIcona(3));  
                
                shape.SetLineWidth(2);
                shape.SetTitle(title);
                shape.SetDescription(description + btnElimina);
                shape.SetPoints(points);
                shape.ShowIcon();
                map.AddShape(shape);
                document.getElementById('label').innerHTML = 
                "<p>Hover over the polygon for info about this shape!</p>"
            
                // The onmouseover event which calls the shapeInfo function
                map.AttachEvent("onmouseover", shapeInfo);
            
                // The onmouseout event that calls the shapeInfo function to clear the info element
                map.AttachEvent("onmouseout", shapeInfo);
            
                // The onclick event to call the callPopUp function
                map.AttachEvent("onclick", callPopUp);
            }
            
            // This example features handling exceptions with the VEException object
            catch(VEException)            
            {
                document.getElementById('label').innerText=VEException.message+
                " : "+VEException.name+" : "+VEException.source
            }
        }
*/        
		//creo un altro poligono e gli aggiungo degli eventi
/*		function drawPolygon2()
        {
//            map.DeleteAllShapes();
            
            try
            {
				// Custom HTML for pushpin popup (This is NEW in V5!)

				// titolo dell'oggetto
				var title = "<div id='customTitle'><h3>Titolo dell'oggetto2</h3></div>";		        
								
				// descrizione dell'oggetto
		        var description = "<div>"
		        +"descrizione dell'oggetto2 ..."
		        +"<br>descrizione2 ..."
		        +"</div>";
	            
		        
		        //Elementi aggiuntivi: Elimina
		        var btnElimina = "<div>"
		        +"<input type='button' name='Elimina' value='Elimina'>"
		        +"</div>";
		        
		        var xc = lon - 0.010;
		        var yc = lat - 0.010;
		        var y1 = 0.0005;
		        var x1 = 0.005;
				var points=[new VELatLong(yc,xc-0.0010),
		            new VELatLong(yc+y1,xc-x1),
		            new VELatLong(yc+y1,xc+x1),
		            new VELatLong(yc,xc+0.0015),
		            new VELatLong(yc-y1,xc+x1),
		            new VELatLong(yc-y1,xc-x1)];	            
	            
                var shape = new VEShape(VEShapeType.Polygon,points);
                
                //Andrea: icona personalizzata
				shape.SetCustomIcon(setIcona(3));  
                
                shape.SetLineWidth(2);
                shape.SetTitle(title);
                shape.SetDescription(description + btnElimina);
                shape.SetPoints(points);
                shape.ShowIcon();
                map.AddShape(shape);
                document.getElementById('label').innerHTML = 
                "<p>Hover over the polygon for info about this shape!</p>"
            
                // The onmouseover event which calls the shapeInfo function
                map.AttachEvent("onmouseover", shapeInfo);
            
                // The onmouseout event that calls the shapeInfo function to clear the info element
                map.AttachEvent("onmouseout", shapeInfo);
            
                // The onclick event to call the callPopUp function
                map.AttachEvent("onclick", callPopUp);
//            map.AttachEvent("onclick", PixelClick);                
            }
            
            // This example features handling exceptions with the VEException object
            catch(VEException)            
            {
                document.getElementById('label').innerText=VEException.message+
                " : "+VEException.name+" : "+VEException.source
            }
        }        
*/        

/*        
		//disegno un punto  e gli aggiungo degli eventi
		function drawPoint2()
        {
//            map.DeleteAllShapes();
            
            try
            {
				// Custom HTML for pushpin popup (This is NEW in V5!)

				// titolo dell'oggetto
				var title = "<div id='customTitle'><h3>Titolo dell'oggetto puntuale</h3></div>";		        
								
				// descrizione dell'oggetto
		        var description = "<div>"
		        +"descrizione dell'oggetto punto ..."
		        +"<br>descrizione di un punto ..."
		        +"</div>";
	            
		        
		        //Elementi aggiuntivi: Elimina
		        var btnElimina = "<div>"
		        +"<input type='button' name='Elimina' value='Elimina'>"
		        +"</div>";
		        
		        var xc = lon - 0.0005;
		        var yc = lat - 0.010;
		        var y1 = 0.0005;
		        var x1 = 0.005;
		        
				var latLong = new VELatLong(yc, xc);        
	            
                var shape = new VEShape(VEShapeType.Pushpin,latLong);
                //Andrea: icona personalizzata
				shape.SetCustomIcon(setIcona(1));  
                
                shape.SetTitle(title);
                shape.SetDescription(description + btnElimina);
                shape.ShowIcon();
                map.AddShape(shape);
                document.getElementById('label').innerHTML = 
                "<p>Hover over the polygon for info about this shape!</p>"
            
                // The onmouseover event which calls the shapeInfo function
               map.AttachEvent("onmouseover", shapeInfo);
            
                // The onmouseout event that calls the shapeInfo function to clear the info element
                map.AttachEvent("onmouseout", shapeInfo);
            
                // The onclick event to call the callPopUp function
                map.AttachEvent("onclick", callPopUp);
//            map.AttachEvent("onclick", PixelClick);                
            }
            
            // This example features handling exceptions with the VEException object
            catch(VEException)            
            {
                document.getElementById('label').innerText=VEException.message+
                " : "+VEException.name+" : "+VEException.source
            }
        }        
*/        

        
        function detach()
        {
            // Detach all events
            map.DetachEvent("onmouseover", shapeInfo);
            map.DetachEvent("onmouseout", shapeInfo);
            map.DetachEvent("onclick", callPopUp);
        }
        
	function callPopUp(e)
	        {
		        
	            if(e.elementID != null){
		            var shape = map.GetShapeByID(e.elementID);
		            var titolo = shape.GetTitle();
		            var idobj = getIDObj(titolo);

		            //alert("You can now call other functions via events \n" + "This event was " + e.eventName);
		            
		            //elenco dei progetti associati all'oggetto
		            elencoProgettiAssociati(idobj);
	            
            	} else {
		            return false;
	        	}    
	        	
	        }

//cambiamento in auto dello zoom dopo il caricamento 	        	        
/*
function ChangeZoom(){
	map.SetZoomLevel(10);		
}
*/	        
//cliccando sull'oggetto mi restituisce le coordinate	        
function PixelClick(e)
{
            var x = e.mapX;
            var y = e.mapY;
            pixel = new VEPixel(x, y);
            var LL = map.PixelToLatLong(pixel);
 //           alert ("Pixel X: " + x + " | Pixel Y: " + y + "<br /> LatLong: " + LL);
}
	        
 function shapeInfo(e)
        {
            if(e.elementID != null)
            {
							var shape = map.GetShapeByID(e.elementID);
							var titolo = shape.GetTitle();
							titolo = hideKey (titolo);	            
	            shape.SetTitle(titolo);
	            
							var x = e.mapX;
							var y = e.mapY;
							pixel = new VEPixel(x, y);
							var LL = map.PixelToLatLong(pixel);
							var shape = map.GetShapeByID(e.elementID);
	            
							//SOLO per i poligoni e linee:
							var GeomType = shape.GetType();
			        switch (GeomType) 
			        {
			            case "Point":
		                break;
			            case "Polyline":
										//	            shape.SetLineColor(new VEColor(254,0,0,1.0));
										map.ShowInfoBox(shape, LL);
										//			    shape.SetLineColor(new VEColor(254,254,0,1.0));
		                break;
			            case "Polygon":
										//	            shape.SetLineColor(new VEColor(254,0,0,1.0));
								    map.ShowInfoBox(shape, LL);
										//			    shape.SetLineColor(new VEColor(254,254,0,1.0));
		                break;
			        }								            
								            

            }
            else
                document.getElementById("label").innerText = "";
        }

        
 function hideshapesInfo(e)
        {
            if(e.elementID != null)
            {
	            
	            
				var s = map.GetShapeByID(e.elementID);
				var layer =s.GetShapeLayer();
				var numShapes = layer.GetShapeCount();
				for(var i=0; i < numShapes; ++i) {
					var s = layer.GetShapeByIndex(i);
				    s.SetLineColor(new VEColor(0,0,254,0.5));
				    //s.SetCustomIcon("images/pp.gif");
				    setTimeout(function(){map.HideInfoBox(s);}, 3500);
					//map.HideInfoBox(s);
				}	

            }
            else
                document.getElementById("label").innerText = "";
        }        
//========= Fine Aggiunta di eventi =====      
         

//======Elenco dei progetti associati ============
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function elencoProgettiAssociati(id){
	if (id!=null && id != "" && !isNaN(id)){
		//apro una popup
		MM_openBrWindow('progettiAssociati.php?IDObjMap='+ id +'','new', 'width=800,height=400,toolbar=0,location=0,directories=0,status=0,menuBar=0,scrollBars=1,resizable=1');
	}	
}

//======Fine elenco dei progetti associati =======

/*
		//aggiunge un poligono  
		//non è usata!!       
		function AddPolygon()
         {   
			var points=[new VELatLong(lat,lon-0.15),
	            new VELatLong(lat+0.1,lon-0.05),
	            new VELatLong(lat+0.1,lon+0.05),
	            new VELatLong(lat,lon+0.15),
	            new VELatLong(lat-0.1,lon+0.05),
	            new VELatLong(lat-0.1,lon-0.05)];

           map.AddPolygon(points);
           map.SetMapView(points); 
         }   
*/         
function getInfo()
{
	if (map.IsBirdseyeAvailable())
	{
	    var be = map.GetBirdseyeScene();
	    var info = "ID: " + be.GetID() + "\n";
	    info += "thumbnail: " + be.GetThumbnailFilename()+ "\n";
	    info += "orientation: " + be.GetOrientation()+ "\n";
	    info += "height: " + be.GetHeight() + "\n";
	    info += "width: " + be.GetWidth() + "\n";
	    var pixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());
	    info += "LatLongToPixel: " + pixel.x + ", " + pixel.y + "\n";
	
	    // Check to see if the current birdseye view contains the pushpin pixel point.
	    info += "contains pixel " + pinPixel.x + ", " + pinPixel.y + ": " + be.ContainsPixel(pinPixel.x, pinPixel.y, map.GetZoomLevel()) + "\n";
	    
	    // Check to see if the current view contains the pushpin LatLong.
	    info += "contains latlong " + pinPoint + ": " + be.ContainsLatLong(pinPoint) + "\n";
	    
	    // This method may return null, depending on the selected view and map style.
	    info += "latlong: " + map.PixelToLatLong(pixel);
	    alert(info);
	}
	else
	{
	    alert("Bird's eye images are not available at this location and zoom level.");
	}
}

//Aggiunge un'icona tipo puntina
function AddPin()
{
// Add a new pushpin to the center of the map.
pinPoint = map.GetCenter();
pinPixel = map.LatLongToPixel(pinPoint);
var pin = map.AddPushpin(pinPoint);
pin.SetTitle('This is the title text');
pin.SetDescription('This is the description text.');

}

