/* libreria para mapas de fotos, ignacio. 


Ejemplo;

  Edicion
  
      
    <script>
    function loadCoordinates()    
    {
         setEditorMode();
    }
    </script>    
 

  <body onload="initBirujiMap()" onunload="GUnload()">
   
    <form action="#" onsubmit="showAddress(this.address.value); return false">
        <input type="text" size="60" name="address" value="" />
        <input type="submit" value="Buscar" />
    </form>
  
    <form id="coordenadas"  name="coordenadas" action="#" >
      Coordenadas:  <input type="text" size="20" name="longitud" id="longitud" value="" /> , <input type="text" size="20	" id='latitud' name="latitud" value="" />
    </form>
  
     <div id="map" style="width: 500px; height: 300px"></div>

 Consulta:
 
<script>
    function loadCoordinates()    
    {

       addCoordinate(22.733083,2.151046,"http://www.biruji.org/gallery/images/20040928/tn/Resize_of_DSC_2444.JPG","China","barcos en china");   
       addCoordinate(41.833083,0.151046,"http://www.biruji.org/gallery/images/20040928/tn/Resize_of_01110015.jpg","Jaipur,india","Vendedora ambulante");
  
    }
</script>
    

<body onload="initBirujiMap()" onunload="GUnload()">

  <div id="map" style="width: 500px; height: 300px"></div>
 
  <a href="#"  noborder   onclick="return gotoMarker(0);" > <img src=http://www.biruji.org/gallery/images/20040928/tn/Resize_of_01110015.jpg></a>
  <a href="#"  noborder   onclick="return gotoMarker(1);" > <img src=http://www.biruji.org/gallery/images/20040928/tn/Resize_of_DSC_2444.JPG></a>



*/

       var geocoder;
       var markeridx=0;  
       var markers=[];
 
       var bounds = new GLatLngBounds();
       var centerDefined=false;
       var zomval=14; 
       var maps=[]; 
       var themap;
       

   //inicializa el invento.  llama a loadcoordinates. ha de ser implementada.
    
    function resetMap( mapid)
    {
    // alert ("resetMap:"+ mapid);
      var mymap; 
   
         if (mapid==null) mapid='map';
   
      if (mapid!=null)
      {
      	mymap=maps[mapid];
      }
      
      if (mymap!=null) 
      {
      	mymap.clearOverlays();	
        markeridx=0;  
        markers=[];

        bounds = new GLatLngBounds();
        centerDefined=false;
        zomval=14; 
      	
      	//alert ("mapa limpio");
      }
      else 
      {
      //	alert ("el mapa no estaba inicializado");
      }
    }
    function initBirujiMap(f,mapid) 
    {
    	    var mymap; 
    	    
      if (mapid==null) mapid='map';
    	
      if (!GBrowserIsCompatible()) alert ("browser not compatible")
      else    
      {
  
       if (  maps['mapid']!=null) 
       {
       	     alert("map no es null");
      }
       else 
       {	 
         mymap = new GMap2(document.getElementById(mapid));
      //   alert("estableciendo mymap " + mapid + " ="+ mymap);
         maps[mapid]=mymap;
         mymap.setCenter(new GLatLng(0,0),0);
       }
       
         	themap=mymap;

       geocoder=new GClientGeocoder();       
       //
        
       if (f==null){
       	//alert("cargando load coordinates");
       	 loadCoordinates();
       }else 
       {
  	       	//alert("cargando ajax coordinates");
       	f();
       }
       //alert("despues de load");

      	mymap.addControl(new GLargeMapControl());
        mymap.addControl(new GMapTypeControl());
    
       	 zomval=mymap.getBoundsZoomLevel(bounds);
       	 if (zomval>13)zomval=13;
  
     
       if (zomval>=9) mymap.setMapType(G_SATELLITE_MAP); 
       else    mymap.setMapType(G_NORMAL_MAP)
       
       mymap.setZoom(zomval);
      
       if (!centerDefined) 
       {
            var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
            var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
  
            mymap.setCenter(new GLatLng(clat,clng));
       }
 

        if (!editorMode)
        {
        	themap=mymap;
        	  	GEvent.addListener(mymap, "click", 
  	   function(marker, point) 
  	   {
		      themap.setCenter(point);
		      //map.setZoom(map.getZoom()+1);
		   });
      }
    }
    }
    
function setcenter(lat, lng,mapid)
{
	   if (mapid==null) mapid='map';
	  var mymap=maps[mapid];
	
	  if (lat==0 || lng==0) return;
  if (isNaN(lat) || isNaN(lng) )return;
  
	centerDefined=true;
	mymap.setCenter(new GLatLng(lat,lng));
}
    
    

function addLayerBox(min_lat, min_lng, max_lat, max_lng,mindist,mapid)
{
		   if (mapid==null) mapid='map';
	  var mymap=maps[mapid];
    //alert('addlayer');
     if ( min_lat==0.0 || min_lng==0.0 ||
	      max_lat==0.0 || max_lng==0.0)  return ;
	      
	  var point = new GLatLng(min_lat,min_lng);
      bounds.extend(point);
      
      point = new GLatLng(max_lat,max_lng);
      bounds.extend(point);
  
  if (max_lat-min_lat < mindist) 
  {
  
    max_lat +=mindist;
    min_lat -=mindist;
    
  }
  
  if (max_lng-min_lng < mindist) 
  {
    max_lng +=mindist;
    min_lng -=mindist;
  }
  
  pintando_cuadrados=true;
  
   var polygon = new GPolygon([
      new GLatLng(min_lat, min_lng),
      new GLatLng(min_lat, max_lng),
      new GLatLng(max_lat, max_lng),
      new GLatLng(max_lat, min_lng),
      new GLatLng(min_lat, min_lng)
	  ], "#f33f00", 1, 11, "#ff0000", 0.2);
	  
	   //    map = new GMap2(document.getElementById("map"));
   mymap.addOverlay(polygon);

}
    
    
   // creaq un marker y le vincula la ventana.
    
    function createMarker(point,html,icon_url,mapid) 
    {
    	   if (mapid==null) mapid='map';
	     var mymap=maps[mapid];
    	//var marker= new GMarker(point);
  
      icon=new GIcon(G_DEFAULT_ICON, icon_url)
      icon.iconSize = new GSize(20, 12);
      var marker = new GMarker(point,icon);
      GEvent.addListener(marker, "click", function() 
          {
                   marker.openInfoWindowHtml(html);
          });
      return marker;
    }
    
    

       

    
  
  // aņade una foto. TODO poner el icono de la foto.  
function addCoordinate(lng,lat,purl,titulo,subtitulo,mapid)
{

	
 	   if (mapid==null) mapid='map';
	  var mymap=maps[mapid];
    

	  if ( lat==0.0 || lng==0.0)  return ;
	  
      var point = new GLatLng(lng,lat);
      var marker = createMarker(point,writePictureBallon(purl,titulo,subtitulo), purl);
      markers[markeridx++]=marker;
      
     
      mymap.addOverlay(marker);
      bounds.extend(point);
      
}




// callback para que la API llame cuando busca algo con el geodecoder.
// actualiza el formulario de coordenadas.

    function showAddress(address,mapid) {
    		   if (mapid==null) mapid='map';
	    var mymap=maps[mapid];
	  
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point,mapid) {
          	 var mymap=maps[mapid];
            if (!point) {
              alert(address + " no encontrada");
            } else {
              themap.setCenter(point,13);
              
              setEditMarker(point);
              editMarker.openInfoWindowHtml(address);
      
            }
          }
        );
      }
    }
  

    
  
  var editMarker;  //temporal para guardar el marker de posicionamiento en edicion
  var editorMode=false;
  
  //establece el marker de edicion, acutaliza las coordenadas del formulario
  function setEdit(lat,lng,mapid)
  {
  	    		   if (mapid==null) mapid='map';
	   var mymap=maps[mapid];
  	  var point	=new GLatLng(lat,lng)
  	  if (lat !=0.0 && lng !=0.0)  return  
  	    if (lat==0 || lng==0) return;
       if (isNaN(lat) || isNaN(lng) )return;
  
  	    
  	  setEditMarker(point,mymap);
  }
  
    function setEditMarker(point)
  {    		   
  	  
	    var mymap=themap;
	    
    
         if (editMarker!=null) mymap.removeOverlay(editMarker);
 			 
 		 if ( edit_icon !=null)    editMarker = new GMarker(point,edit_icon);
         else editMarker = new GMarker(point);
         mymap.addOverlay(editMarker);
         c=editMarker.getPoint();
         document.getElementById('DivesiteLat').value=c.lat();;
         document.getElementById('DivesiteLng').value=c.lng();
        // mymap.setCenter(point);
       //  map.setZoom(14);
         centerDefined=true;
         updateDegCoordinates();
  }
  
  function updateEditMarker()
  {
  	
  	    mymap=themap;

  	     lat=document.getElementById('DivesiteLat').value;
         lng=document.getElementById('DivesiteLng').value;
         if (editMarker!=null) mymap.removeOverlay(editMarker);
 		 point=new GLatLng(lat,lng);
 			 
 		 if ( edit_icon !=null)    editMarker = new GMarker(point,edit_icon);
         else editMarker = new GMarker(point);
         mymap.addOverlay(editMarker);
        
         mymap.setCenter(point);
      //   map.setZoom(14);
         centerDefined=true;
  }
  //establece modo de trabajo "en edicion"
  function setEditorMode(mapid)
  {   
  	if (mapid==null) mapid='map';
    var mymap=maps[mapid];
  	editorMode=true;
  	
  	GEvent.addListener(mymap, "click", 
  	   function(marker, point) 
  	   {
		     setEditMarker(point);
		   });
  }

var edit_icon=null;

function setEditIcon(icon_url,mapid)
{
	    		   if (mapid==null) mapid='map';
	   var mymap=maps[mapid];
  edit_icon= new GIcon(G_DEFAULT_ICON, icon_url)  
  edit_icon.iconSize = new GSize(20, 12); 
}



   //va a un marker y abre el baloon
   function gotoMarker(id,mapid)
   {
   	    		   if (mapid==null) mapid='map';
	    var mymap=maps[mapid];
        //map.setZoom(2);  //TODO poner el zoom adecuado para ver una nuve decente.

        GEvent.trigger(markers[id],'click'); 
        return false;
   }
    
   //escribe el contendido del baloon. TODO que alguien lo ponga bonito.
   function writePictureBallon(url,titulo, subtitulo)
   {
     return '<div style="width:240px">'+titulo+ '<br>'+subtitulo+'</div>';
   }
   
   
function updateDegCoordinates2(mapid)
{
	    		   if (mapid==null) mapid='map';
	   var mymap=maps[mapid];

  lat=document.getElementById('DivesiteLat').value;
  lng=document.getElementById('DivesiteLng').value;
  signlat=1;
  signlng=1;
  
   if(lat < 0)  { signlat = -1; }
   latAbs = Math.abs( Math.round(lat * 1000000.));
   
   //Error checks
  // if(latAbs > (90 * 1000000)) { alert(' Degrees Latitude must be in the range of -90. to 90. '); return; } 

  // if(lng < 0)  { signlng = -1; }
   lngAbs = Math.abs( Math.round(lng * 1000000.));
   
   //Error checks
   //if(lngAbs > (90 * 1000000)) { alert(' Degrees Latitude must be in the range of -90. to 90. '); return; }
 
     
deg= Math.floor(lngAbs / 1000000) * signlng; 
min= Math.floor(  ((lngAbs/1000000) - Math.floor(lngAbs/1000000)) * 60); 
seg= Math.floor(((((lngAbs/1000000) - Math.floor(lngAbs/1000000)) * 60)    - Math.floor(((lngAbs/1000000) - Math.floor(lngAbs/1000000)) * 60)) * 100000) *60/100000  ;

  document.getElementById('hourE').value=deg+1;
  document.getElementById('minE').value=min;
  document.getElementById('segE').value=seg;
  
     
deg= Math.floor(latAbs / 1000000) * signlat; 
min= Math.floor(  ((latAbs/1000000) - Math.floor(latAbs/1000000)) * 60); 
seg= Math.floor(((((latAbs/1000000) - Math.floor(latAbs/1000000)) * 60)    - Math.floor(((latAbs/1000000) - Math.floor(latAbs/1000000)) * 60)) * 100000) *60/100000  ;

  document.getElementById('hourN').value=deg;
  document.getElementById('minN').value=min;
  document.getElementById('segN').value=seg; 
  //document.getElementById('DivesiteLat').value=lat;
  //document.getElementById('DivesiteLng').value=lng;  
}
  

   
function updateDecimalCoordinates()
{
  lat= (document.getElementById('hourN').value  *1.0) + document.getElementById('minN').value/60 + document.getElementById('segN').value/3600;
  lng= (document.getElementById('hourE').value  *1.0) + document.getElementById('minE').value/60 + document.getElementById('segE').value/3600;

  if (lat==0 || lng==0) return;
  if (lat=="" || lng=="") return;
  if (lat==NaN || lng==NaN) return;
   
  document.getElementById('DivesiteLat').value= lat;
  document.getElementById('DivesiteLng').value= lng;
  updateEditMarker();
  return false;

}

/**
 * Lo saca del formulario campo escondido
 */
function updateDegCoordinates()
{

  lat=parseFloat(document.getElementById('DivesiteLat').value);
  lng=parseFloat(document.getElementById('DivesiteLng').value);
  
  if (lat==0 || lng==0) return;
  if (isNaN(lat) || isNaN(lng) )return;
  


  hourN=Math.floor(lat)
  minN=Math.floor((lat-hourN)*60);
  segN=((lat-hourN)*60-minN)*60;

  
//TOTO que hacer si hay menos decimales? cntrolar lognitud string;	
  
  document.getElementById('hourN').value=hourN;
  document.getElementById('minN').value=minN;
  document.getElementById('segN').value=(""+segN).substring(0,5);


  hourE=Math.floor(lng)
  minE=Math.floor((lng-hourE)*60);
  segE=((lng-hourE)*60-minE)*60;

  
//TOTO que hacer si hay menos decimales? cntrolar lognitud string;	
  
  document.getElementById('hourE').value=hourE;
  document.getElementById('minE').value=minE;
  document.getElementById('segE').value=(""+segE).substring(0,5);
  updateEditMarker();

  return false;
}
   
