google.load("maps", "2");
if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj){
        return i;
      }
    }
    return -1;
  }
}

var GoogleMap = function() {};
GoogleMap.prototype = {
  initialize: function(options) {
    this.setOptions(options);
    this.setIconObjects(options.icons);
    this.mapframe = $('#google_map');
    this.resize();
    this.map = new google.maps.Map2(document.getElementById('google_map'));

    this.map.setCenter(new google.maps.LatLng(this.options.latitude, this.options.longitude), this.options.zoom);


    G_PHYSICAL_MAP.getMaximumResolution = function () { return 8 };
    G_NORMAL_MAP.getMaximumResolution = function () { return 8 };
    G_SATELLITE_MAP.getMaximumResolution = function () { return 8 };
    G_HYBRID_MAP.getMaximumResolution = function () { return 8 };

    G_PHYSICAL_MAP.getMinimumResolution = function () { return 5 };
    G_NORMAL_MAP.getMinimumResolution = function () { return 5 };
    G_SATELLITE_MAP.getMinimumResolution = function () { return 5 };
    G_HYBRID_MAP.getMinimumResolution = function () { return 5 };

    this.map.enableScrollWheelZoom();
    this.map.setUIToDefault();
    this.geocoder = new google.maps.ClientGeocoder();
    this.setupMarker(options);
    this.trail = new GGeoXml("http://www.elcaminorealdelostejas.org/javascripts/thetrail2.kmz");
    this.mapControl = new google.maps.LargeMapControl3D();
    this.map.addControl(this.mapControl);
    this.loadFilters();
    $('#loading').hide();
  },

  setOptions: function(options) {
    this.options = options;
  },

  setIconObjects: function(icons) {
    for (var i in icons) {
      var pointIcon = new GIcon(G_DEFAULT_ICON);
      pointIcon.image = icons[i][1];
      pointIcon.iconSize = new GSize(26,37);
      this.iconObjects[this.iconObjects.length] = [icons[i][0], pointIcon];
    }
  },

  resize: function() {
    options = this.options;
    if(options == undefined) {
      this.mapframe.css({width: '880px', height: '600px'});
    } else {
      if(options.width) {
        this.mapframe.css({width: options.width});
      } else {
        this.mapframe.css({width: '880px'});
      }
      if(options.height) {
        this.mapframe.css({height: options.height});
      } else {
        this.mapframe.css({height: '600px'});
      }
    }
  },

  mark: function(id, lat, lng, text, icon_type) {
    for (var i in this.iconObjects) {
      if (this.iconObjects[i][0] == icon_type) {
	var pointIcon = this.iconObjects[i][1];
      }
    }
    var point = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker(point, {icon: pointIcon});

    this.map.addOverlay(marker);
    var self = this;
    var listen = new google.maps.Event.addListener(marker, 'click', function() {
      //self.map.panTo(this.getLatLng());
      marker.openInfoWindowHtml(text,{maxWidth: self.options.bubble_max_width});
    });
    this.markers[this.markers.length] = {'marker': marker, 'text': text, 'id':id, 'type': icon_type};
  },

/*  line: function(id,lat1,lng1,lat2,lng2) {
    var point1 = new google.maps.LatLng(lat1,lng1);
    var point2 = new google.maps.LatLng(lat2,lng2);
    var polyline = new google.maps.Polyline([point1,point2],this.options.line_color,this.options.line_width);
    this.map.addOverlay(polyline);
    this.lines[this.lines.length] = {'id': id, 'line':polyline, 'pointA': point1, 'pointB': point2};
  },

  showLines: function() {
    // IE breaks when we attempt to use indexOf...
    for (var i=0; i<this.lines.length; i++) {
      this.lines[i].line.show();
    }
  },
  hideLines: function() {
    // IE breaks when we attempt to use indexOf...
    for (var i=0; i<this.lines.length; i++) {
      this.lines[i].line.hide();
    }
  },*/

  addTrail: function() {
    if (GBrowserIsCompatible()) {
      this.map.addOverlay(this.trail);
    }
  },
  removeTrail: function() {
    if(GBrowserIsCompatible()) {
      this.map.removeOverlay(this.trail);
    }
  },
  hideMarkerByType: function(type) {
    for (var i in this.markers) {
      if (this.markers[i].type == type) {
	this.markers[i].marker.hide();
      }
    }
  },

  showMarkerByType: function(type) {
    for (var i in this.markers) {
      if (this.markers[i].type == type) {
	this.markers[i].marker.show();
      }
    }
  },

  closeOverlay: function() {
    if (this.currentMarker) {
      this.map.removeOverlay(this.currentMarker.overlay);
    }
  },
  setupMarker: function(options) {
    this.baseIcon = new GIcon(G_DEFAULT_ICON);
    //this.baseIcon.image = icon;
    this.baseIcon.iconSize = new GSize(32,32);
    //this.baseIcon.shadow = "/images/g_icon_shadow.png"
    //this.baseIcon.shadowSize = new GSize(31, 20);
  },

  openMarkerById: function(id) {
    for(x in this.markers) {
      if(this.markers[x].id == id) {
        this.closeOverlay();
        this.currentMarker = this.markers[x].marker;
        this.map.panTo(this.markers[x].marker.getLatLng());
        //this.markers[x].marker.openInfoWindowHtml(this.markers[x].text);
        this.map.addOverlay(this.markers[x].marker.overlay);
        break;
      }
    }
  },

  centerMarker: function(index) {
    for(x in this.markers) {
      if(this.markers[x].id == id) {
        this.map.setCenter(this.markers[x].marker.getLatLng());
        break;
      }
    }
  },

  loadFilters: function() {
    var map = this;
    this.filters = $('#filters .filter_change select');
    this.filters.each(function(index){
      $(this).change(function() {
        map.filter(this.options[this.selectedIndex].value);
      });
    });
  },

  filter: function(filter_option_id) {
    var self = this;
    $.getJSON('/communities.js', this.filters, function(json) {
      var community_ids = [];
      $.each(json.communities, function(i, comm) {
        community_ids[community_ids.length] = comm.community.id;
      });
      // now we have ids, need to dim and brighten
      $.each(self.markers, function(i, marker) {
        if (community_ids.indexOf(marker.id) > -1) {
          marker.marker.setImage('/images/icons/g_logo.png');
          $('#community_'+marker.id).removeClass('inactive');
        } else {
          marker.marker.setImage('/images/icons/g_logo_inactive.png');
          $('#community_'+marker.id).addClass('inactive');
        }
      });
    });
  },

  // Look up an address, create a mark, then save it over Ajax
  geocode: function(address, text) {
    var self = this;
    this.geocoder.getLatLng(
      address,
      function(point) {
        if (point) {
          var marker = new google.maps.Marker(point, {icon:this.baseIcon});
          self.map.addOverlay(marker);
          self.markers[self.markers.length] = {'marker': marker, 'text': text};
        }
      }
    );
  },
  //default settings
  map: null,
  mapControl: null,
  geocoder: null,
  filters: [],
  markers: [],
  trail: null,
  options: {},
  baseIcon: null,
  currentMarker: null,
  mapframe: 'google_map',
  contentframe: 'map_content',
  iconObjects: []
};

