if (!SL.ext) {
	SL.ext = {};
}

(function() {

	SL.ext.GoogleMaps = Class.create(SL.Component, {

		init : function() {

			// this.config.setDefault('zoom', 12);
			this.config.setDefault('type', google.maps.MapTypeId.ROADMAP);
			this.config.setDefault('map_type_control', false);
			this.config.setDefault('navigation_control', false);
			this.config.setDefault('street_view_control', false);

			var myOptions = {
				zoom : this.config.get('zoom'),
				mapTypeId : this.config.get('type'),
				mapTypeControl : this.config.get('map_type_control'),
				navigationControl : this.config.get('navigation_control'),
				streetViewControl : this.config.get('street_view_control')
			};

			this.map = new google.maps.Map(this.e, myOptions);

			this.geocoder = new google.maps.Geocoder();

			this.latlng = [];

			var markers = this.config.get('markers');
			this.multi = markers.length > 1;

			$A(markers).each(function(m) {
				if (m.latlng) {
					var marker = new google.maps.Marker({
						map : this.map,
						position : m.latlng,
						title : m.title
					});

					if (!this.multi) {
						this.map.setCenter(m.latlng);
					}

					this.latlng.push(m.latlng);

					if (m.tooltip) {
						var infowindow = new google.maps.InfoWindow({
							content : m.tooltip
						});
						google.maps.event.addListener(marker, 'click', function(c) {
							if (c.win) {
								c.win.close();
							}
							infowindow.open(this.map, marker);
							c.win = infowindow;
						}.curry(this));
					}

				} else {
					this.geocoder.geocode({
						'address' : m.address
					}, this.onGeoResult.bind(this, m));
				}
			}.bind(this));

			if (this.multi || !this.config.get('zoom')) {
				this.updateMap();
			}
		},

		onGeoResult : function(m, results, status) {
			if (status == google.maps.GeocoderStatus.OK) {

				if (!this.multi) {
					this.map.setCenter(results[0].geometry.location);
				}

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

				this.latlng.push(results[0].geometry.location);

				if (m.tooltip) {
					var infowindow = new google.maps.InfoWindow({
						content : m.tooltip
					});
					google.maps.event.addListener(marker, 'click', function(c) {
						if (c.win) {
							c.win.close();
						}
						infowindow.open(this.map, marker);
						c.win = infowindow;
					}.curry(this));
				}

				if (this.multi || !this.config.get('zoom')) {
					this.updateMap();
				} else {
					this.map.setCenter(results[0].geometry.location);
				}

			} else {
				console.log("No location for address", m.address + status);
			}
		},

		updateMap : function() {
			var bounds = new google.maps.LatLngBounds();
			for ( var i = 0; i < this.latlng.length; i++) {
				bounds.extend(this.latlng[i]);
			}
			this.map.fitBounds(bounds);
			this.map.setCenter(bounds.getCenter());
		}
	});

})();
