/*************************************************************************[info]
  JS DOCUMENT:        GoogleMap.js
  DATA:               29/10/2008
  COMPANY:            Onlime S.n.c.
 
  LAST EDIT:          24/11/08

  PURPOSE:            GoogleMap object
  
  CHANGES:
  --------
  -
    
  TODO LIST:
  ----------  
  - (! verificare come mai i marker sforano di poco)  
  - centramento punti forse risolto size di GMap2... (da verificare)
  - ie6 to check se non appare il marker
*******************************************************************************/
(function(){
/*******************************************************************************
  [GOOGLEMAP OBJECT]  
*******************************************************************************/
GoogleMap = function( obj, default_area, small_controls )
{
  var obj_GoogleMap = this;         // Closure
  
  var listener      = new JEvent(); // event.listener
  this.map          = null;         // GMap2
  this.typeControl  = null;
  this.MapControl   = null;
  this.geocoder     = null;         // GClientGeocoder
  this.markers      = [];           // Array GMarker
  
  this.tabAccuracy  = new Array(2,4,6,10,12,13,16,16,17);
  
  this.GoogleMap = function( obj, default_area, small_controls )
  {
    // (sembra che risolvi i problemi di centramento punti..)
    var opts = {
      size:new GSize(
        parseInt($(obj).fn.css('width')),
        parseInt($(obj).fn.css('height'))
      )
    };
     
    if ( !obj ) return null
    this.map = new GMap2( obj,opts );
    
    if ( !this.map ) return null;
    
    /* Attach eventi window.onload e window.unload */
    //addListener(window, "load", showMap);
    listener.add( window, "unload", GUnload );
    
    small_controls = (small_controls === true || small_controls === undefined ) ?  (true) : (false);
    
    /* mappa - satellite - ibrida */
    this.typeControl = new GMapTypeControl();
    this.map.addControl( this.typeControl );
    
    if ( small_controls )
    {
      /* controller small */
      this.mapControl = new GSmallMapControl();
      this.map.addControl( this.mapControl );
    }
    else
    {
      /* controller con barra vert */
      this.mapControl = new GLargeMapControl();
      this.map.addControl( this.mapControl );
      
      /* zoom box, in basso a dx */
      this.map.addControl(new GOverviewMapControl(),new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(9, 9)));
    }
    
    this.geocoder = new GClientGeocoder();
    
    if ( default_area )
    {
      this.geocoder.getLatLng( 
        default_area[0],   
        function(point) 
        {
          if (!point) 
          {
            //alert(default_area['luogo'] + " not found");
          } 
          else
          {                 
             var zoom = default_area[1] || 3;
             obj_GoogleMap.map.setCenter( point , zoom );
          }
         }   
      );  
    }
    else
    {
      // Milano ...
      //this.map.setCenter(new GLatLng(45.470364,9.19487), 7);
    }  
  };
  
  /* */
  this.removeMapControl = function()
  { 
    if ( this.mapControl )
    {
      this.map.removeControl( this.mapControl );
    }
  };
  
  /* */
  this.createMarkers = function( arr_markers_detail )
  {
    if ( arr_markers_detail )
    {
      for(i=0;i<arr_markers_detail.length;i++)
      {
        this.createMarker( i,arr_markers_detail[i] );
        //this.createMarker( (obj_GoogleMap.markers.length + 1),arr_markers_detail[i] );
      }
    }
  };
  
  this.centerMap = function ( area )
  {
    this.geocoder.getLatLng( 
      area[0],   
      function(point) 
      {
        if (!point) 
        {
          return false;
        } 
        else
        {
           var zoom = area[1] || 3;
           obj_GoogleMap.map.setCenter( point , zoom );
           return true;
        }
       }   
    );
  };
  
  this.centerMapWithAccuracy = function( strLocation ) 
  {
    if (this.geocoder) 
    {
      this.geocoder.getLocations( 
        strLocation,
        function(response) 
        {
          if(response.Status.code!=200)
          {
            // alert('"' + address + '" not found');
          } 
          else 
          {
            place = response.Placemark[0];
            accuracy = place.AddressDetails.Accuracy;
            obj_GoogleMap.map.setCenter(
              new GLatLng(place.Point.coordinates[1],
              place.Point.coordinates[0]), obj_GoogleMap.tabAccuracy[accuracy]
            );
          }
        }
      );
    }
  };  
      
  function fitMap( map, points ) 
  {
    var bounds = new GLatLngBounds();
    for (var i=0; i< points.length; i++) {
    bounds.extend(points[i]);
    }
    map.setZoom( map.getBoundsZoomLevel(bounds) );
    map.setCenter( bounds.getCenter() );
  };

  /* ESEMPIO COSTRUZIONE ARRAY ASSOCIATIVO MARKER */
  // var arr_marker = new Array();
  
  /* Cotrutto equivalente a quello sottoindicato
  arr_marker[0] = new Array();
  arr_marker[0]["address"]      = "25, Cliff Street New Rochelle 10801 New York";
  arr_marker[0]["icon"]         = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
  arr_marker[0]["description"]  = "...";
  arr_marker[0]["setcenter"]    = false;
  arr_marker[0]["panTo"]        = false;
  */
  
  /*    
  arr_marker[0] = new Array();
  arr_marker[0] = {
  	"address"     : "via melchiorre gioia 69 Milano italia",
  	"icon"        : "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png",
  	"description" : "....",
  	"setcenter"   : false,
  	"panTo"       : false
  };
  */
  this.createMarker = function ( indice, marker_detail ) 
  {
    if (this.geocoder) 
    {
      this.geocoder.getLatLng( 
        marker_detail["address"],
        function(point) 
        {
          // ie6 to check se non appare il marker
          if (!point) 
          {
            //alert(marker_detail["address"] + " not found");
            return null;
          } 
          else 
          { 
            /* Creazione icona marker & setting proprietá */
            var colorIcon = new GIcon(G_DEFAULT_ICON);
            colorIcon.image = marker_detail["icon"];
            colorIcon.iconSize = new GSize(32, 32);
            
            //var offset = new GSize(iwAnchor.x-iconAnchor.x,iwAnchor.y-iconAnchor.y);

            colorIcon.shadow = null;
            //colorIcon.iconAnchor = new GPoint(20, 30);
            
            /* AL MOMENTO NN UTILIZZATI
            // baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            // baseIcon.shadowSize = new GSize(37, 34);
            // baseIcon.iconAnchor = new GPoint(9, 34);
            // baseIcon.infoWindowAnchor = new GPoint(9, 2);
            // baseIcon.infoShadowAnchor = new GPoint(18, 25);
            */
                            
            /* Set up Oggetto GMarkerOptions */
            markerOptions = { icon:colorIcon };
            if ( marker_detail["title"] ) markerOptions["title"] = marker_detail["title"];
            
            var marker = new GMarker(point,markerOptions);
            obj_GoogleMap.map.addOverlay(marker);
            
            if ( marker_detail["hide"] == 0 ) marker.hide();
            
            /* Centramento su punto e zoom se viene richiesto il centramento */
            if ( marker_detail["setcenter"] ) 
            {
              obj_GoogleMap.map.setCenter( point,14 );
            }
            
            /* panTo se viene richiesto l'effetto */
            if ( marker_detail["panTo"] ) 
            {
              obj_GoogleMap.map.panTo( point );
            }
            
            /* Attach evento onclick su marker se vi è descrizione */
            if ( marker_detail["description"] )
            {
              var fn = function()
              {
                //var opts = {pixelOffset:new GSize(32,5), maxWidth:250};
                var opts = null;
                marker.openInfoWindowHtml(marker_detail["description"],opts); 
              }
              GEvent.addListener( marker, "click", fn );  
            }
            
            // In caso di richiesta di callbackFn la attacco al click
            if ( marker_detail["cbFn"] )
            {
              if ( typeof( marker_detail["cbFn"] ) =='string' )
              {
                //...
              }  
              GEvent.addListener( marker, "click", marker_detail["cbFn"] );
            }
             
            obj_GoogleMap.markers[indice] = marker;  
          }
        }
      );
    }
  };
  
  // Richiamo il costruttore GoogleMap
  this.GoogleMap( obj, default_area, small_controls );
}
/*******************************************************************************
  [END GOOGLEMAP OBJECT]  
*******************************************************************************/
})();
