var Map = new Class({
  initialize: function(div, opts) {
    if (!opts) opts = {}
    this.div = $(div)
    this.div.manager = this
    this.map = new GMap2(this.div)

    if (opts.large) this.map.addControl(new GLargeMapControl())
    if (opts.overview) this.map.addControl(new GOverviewMapControl(false, false))
    this.map.enableDoubleClickZoom()
    this.map.enableScrollWheelZoom()
    this.map.addControl(new GLargeMapControl())
    this.map.addControl(new GMapTypeControl())

    this.center = new GLatLng(opts.latitude || opts.lat || 45, opts.longitude || opts.lng || 0)
    this.map.setCenter(this.center, opts.zoom || 9)
    this.mgr = new GMarkerManager(this.map)
    if (opts.mark_center) {
      this.center_marker = new GMarker(this.center, G_DEFAULT_ICON)
      this.map.addOverlay(this.center_marker)
      // this.mgr.addMarker(this.center_marker)
      // this.mgr.refresh()
    }
    if (opts.source) {
      this.hash = {}
      this.source = opts.source
      this.cancel_events = false
      this.matrix = new Array(360)
      for (var i=0; i < 360; i++) this.matrix[i] = new Array(180)
      if (opts.init) opts.init(this.map)
      GEvent.addListener(this.map, 'moveend', this.viewport_changed.bind(this))
      GEvent.addListener(this.map, 'zoomend', this.viewport_changed.bind(this))
      GEvent.addListener(this.map, 'click', this.open_bubble.bind(this))
      this.viewport_changed()
    } else if (opts.init) opts.init(this.map)
  },

  viewport_changed: function() {
    // TODO
  },
  open_bubble: function() {
    // TODO
  }
})

window.addEvent('domready', function() {
  $$('div.google-map').each(function (div) {
    new Map(div, {
      source: $try(function() { return document.getElement('link#'+div.get('id')+'[rel=map-source]').href }),
      lat: $try(function() { return parseFloat(div.getElement('.latitude').get('text')) }),
      lng: $try(function() { return parseFloat(div.getElement('.longitude').get('text')) }),
      zoom: $try(function() { return parseInt(div.getElement('.zoom').get('text')) }),
      mark_center: div.hasClass('mark-center')
    })
  })
})
