/*
  GoogleMaps Class
  Dominus Mappae V3 !!
  06-09-2011
*/

var gmap;

function GoogleMaps()
{
    var edit = false;
    var map = null;
    var geocoder = null;
    var addresses = null;
    var ids = null;
    var n = 0;
    var bounds = null;
    var center_map = null;
    var overlays = [];

    this.init = function(admin)                                                 // V3
    {
      if(admin == true)
      {
        edit = true
      }
      else
      {
        edit = false
      }

      var latlng = new google.maps.LatLng(0, 0);

      var mapOptions = {
        scrollwheel: false,
        zoom: 16,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
      geocoder = new google.maps.Geocoder();
      bounds = new google.maps.LatLngBounds();
      n = 0;
    };

    function addAddressToMapGC(response, status)                                // V3
    {
      clearOverlays();

      if(status == google.maps.GeocoderStatus.OK)
      {
        //this.map.setCenter(results[0].geometry.location);

        var marker = new google.maps.Marker({
            map: map,
            position: response[0].geometry.location
        });

        addMarker(marker);
      }
    };

    function addAddressToMap(address)
    {
      clearOverlays();

      var marker = new google.maps.Marker({
          map: map,
          position: new google.maps.LatLng(address[0], address[1])
      });

      addMarker(marker);
    }

    function addMarker(marker)
    {
      var infoWindow = new google.maps.InfoWindow();

      if(edit)
      {
        marker.setDraggable(true);

        google.maps.event.addDomListener(marker, 'dragstart', function()
        {
          infoWindow.close()
        });

        google.maps.event.addDomListener(marker, 'dragend', function()
        {
          reqPath = '/web_module/add_lat_lng_to_info_data/' + marker.id

          infoWindow.setContent('<strong>Latitudine:</strong> ' + this.position.lat() + '<br />' +
                    '<strong>Longitudine:</strong> ' + this.position.lng() + '<br /><br />' +
                    '<form action="/" method="post" ' +
                    'onsubmit="new Ajax.Request(\'' + reqPath + '\', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">' +
                    '<input type="hidden" name="lat" value="' + this.position.lat() + '" />' +
                    '<input type="hidden" name="lng" value="' + this.position.lng() + '" />' +
                    '<div id="add_lat_lng_response" align="center"><input name="commit" type="submit" value="Salva la posizione" class="mybutton" /></div>' +
                    '</form>');
          infoWindow.open(map, marker);
        });
      }

      marker.id = ids[n];                                                       //
      marker.setMap(map);                                                       //
      map.setCenter(marker.position);                                           //

      //google.maps.event.addDomListener(marker, 'click', getMapMarker);

      overlays.push(marker);
    }

    function clearOverlays()
    {
      for(var n = 0, overlay; overlay = overlays[n]; n++)
      {
        overlay.setMap(null);
      }
      overlays = [];
    }


    /* aggiunge più indirizzi alla mappa con geocode */
    this.addAddressesToMapGC = function(response)
    {
        if(!response || response.Status.code != G_GEO_SUCCESS)
        {
        //alert('Impossibile trovare questo indirizzo');
        }
        else
        {
            place = response.Placemark[0];
            point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

            addMarkers(point)
        }
    };

    /* aggiunge più indirizzi alla mappa con lat e lng */
    function addAddressesToMap(address)
    {
        point = new GLatLng(address[0], address[1]);

        addMarkers(point);
    }

    function addMarkers(point)
    {
        marks = new GMarker(point);
        marks.id = ids[n];
        map.addOverlay(marks);

        GEvent.addListener(marks, 'click', getMapMarker);

        bounds.extend(point);

        if(n == (addresses.length - 1))
        {
            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        }

        n++;
    }

    this.showLocation = function(address, id)
    {
        ids = id;
        addresses = address;

        if(is_array(address) && address.length > 1)
        {
            for(i = 0; i < address.length; i++)
            {
                if(is_array(address[i]))
                {
                    addAddressesToMap(address[i]);
                }
                else
                {
                    geocoder.getLocations(address[i], this.addAddressesToMapGC);
                }
            }
        }
        else
        {
          if(is_array(address[0]))
          {
            addAddressToMap(address[0]);
          }
          else
          {
            geocoder.geocode({address: address[0]}, addAddressToMapGC);
          }
        }
    };

    this.description = function(i)
    {
        return descriptions[i]
    };

    this.address = function(i)
    {
        return addresses[i]
    };

    this.refresh = function()
    {
        map.checkResize();

        if(center_map != null)
        {
            map.setCenter(center_map);
        }
        else
        {
            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        }
    }


/* inizializzazione della classe */
function getMapMarker()
{
    mark = this;

    splitPath = window.location.pathname.split('/');
    //reqPath = '/' + splitPath[1] + '/resources/json_resource/' + this.id;
    reqPath = '/web_module/json_apartment/' + this.id;

    new Ajax.Request(reqPath, {
        asynchronous:true,
        evalScripts:true,
        onSuccess:function(resp)
        {
            resource = JSON.parse(resp.responseText);

            image = (resource['image'] != null) ? '<td width="60"><img src="' + resource['image'] + '" width="50" height="50" /></td>' : '';

            html = '<table width="210"><tr>' + image + '<td valign="top">' +
            '<b>' + resource['title_it'] + '</b><br />' +
            resource['address'] + '<br />' + resource['town'] + ', ' + resource['district'] +
            '</td></tr></table>';

            mark.openInfoWindowHtml(html);
        },
        onFailure:function()
        {
        //
        }
    });
}
}

function is_array(input)
{
  return typeof(input)=='object'&&(input instanceof Array);
}

