window.addEvent('domready', function() {
	if ($('locations')) {
		new map($('locations'), $('body').getElement('.container'));
	}
	
//	$('locations').inject($('header').getElement('.container')).setStyles({'float':'left', marginTop:195, marginLeft: 210});
});

var map = new Class({
	initialize: function(ddata, loc) {
		this.loc = loc;
		this.ddata = ddata;


		this.mapcontainer = new Element('div').setStyles({backgroundColor:'#ccc', width:'100%', height:450}).inject(this.loc, 'before');
		this.map = new Element('div', {'class':'map'}).setStyles({width:'100%', height:'100%'}).inject(this.mapcontainer);
		
		this.resize();

		this.spinner = new Spinner(this.mapcontainer).show();

		window.addEvent('resize', this.resize.bind(this));
		this.resize();
		
		google.load("maps", "3", {'callback' : this.mapsLoaded.bind(this), 'other_params': "sensor=true"});

		this.loc.addEvent('onMapsLoaded', function(){
			this.loadMap();
			this.loaded = true;
		}.bind(this));
		
	},
	resize: function() {
		window_dim = Window.getSize();		

		width = ((e = $('header').getSize().x) > 980) ? e : 980;
		this.mapcontainer.setStyles({'width': width});
		this.map.setStyles({'width': width});		
	},
	mapsLoaded: function() {
		this.loadLibraries([
		//	'/js/libs/google/maps/infobubble.js'
		//	'js/libs/google/maps/markermanager.js'
		]);
	},
	loadLibraries: function(libs) {
		var count = libs.length;		
		if (count > 0) {		
			libs.each(function(lib){
				alert('load: '+ lib);
				new Asset.javascript(lib, {
				    events: {
				        load: function(){
							alert('go loaded');
				            this.libsLoaded(count);
				        }.bind(this)
				    }
				}, this);
			}.bind(this));
		}
		else {
			this.loc.fireEvent('onMapsLoaded');
		}
	},
	libsLoaded: function(count) {		
		if (typeof this.loadedlibs != "undefined") {
			this.loadedlibs++;
		}
		else {
			this.loadedlibs = 1;
		}		
		if (this.loadedlibs == count) this.loc.fireEvent('onMapsLoaded');
	},
	loadMap: function() {
		var self = this;
		
		var latlng = new google.maps.LatLng(51.23071548460618, 4.44185320095403);
		var myOptions = {
			zoom: 13,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl: false,
			scrollwheel: false,
			streetViewControl: false
		};
		self.mapObj = new google.maps.Map(this.map, myOptions);
		
		self.markers = [];
		self.markers['countries'] = [];
		self.markers['bounds'] = new google.maps.LatLngBounds();

		self.infoBubble = new InfoBubble({
			map: this.mapObj,
			shadowStyle: 1,
			padding: 0,
			backgroundColor: 'rgb(57,57,57)',
			borderRadius: 4,
			arrowSize: 10,
			borderWidth: 1,
			borderColor: '#2c2c2c',
			disableAutoPan: true,
			hideCloseButton: true,
			arrowPosition: 20,
			backgroundClassName: 'phoney',
			arrowStyle: 2
		});
		
		google.maps.event.addListener(this.mapObj, "tilesloaded", function(e) {
			self.spinner.hide();
		});
		

		/*
		new Element('a', {'href':'#', 'html':'map'}).addEvents({
			mouseup: function(e) {
				e.stop();
				self.mapObj.fitBounds(self.markers.bounds);
				if (self.mapObj.getZoom() > 12) self.mapObj.setZoom(12);
			}
		}).inject(this.loc.getElement('h1').setStyles({marginRight:'.35em'}), 'after');
		*/
		
		this.ddata.getElements('li.country').each(function(country){
			self.markers.countries[country.get('data-id')] = [];
			self.markers.countries[country.get('data-id')]['bounds'] = new google.maps.LatLngBounds();
			self.markers.countries[country.get('data-id')]['markers'] = [];
			/*
			new Element('a', {'href':'#', 'html':'map'}).addEvents({
				mouseup: function(e) {
					e.stop();
					eval("self.mapObj.fitBounds(self.markers.countries."+country.get('data-id')+".bounds)");
					if (self.mapObj.getZoom() > 12) self.mapObj.setZoom(12);
					
				}
			}).inject(country.getElement('.name').setStyles({marginRight:'.55em'}), 'after');
			*/
			this.icon = function(country) {
				switch (country) {
					case 'belgium':
						img = 'images/marker_blue.png';
					break;
					case 'netherlands':
						img = 'images/marker_yellow.png';
					break;
					case 'germany':
						img = 'images/marker_green.png';
					break;
					case 'denmark':
						img = 'images/marker_red.png';
					break;
					case 'luxembourg':
						img = 'images/marker_red.png';
					break;
					default:
						img = 'images/marker_red.png';
					break;
				}
				
				icon = new google.maps.MarkerImage(img,
			    	// This marker is 20 pixels wide by 32 pixels tall.
					new google.maps.Size(20, 34),
					// The origin for this image is 0,0.
					new google.maps.Point(0,0),
					// The anchor for this image is the base of the flagpole at 0,32.
					new google.maps.Point(10, 34)
				);
			
				return icon;
			};
			
			this.shadow = new google.maps.MarkerImage('images/marker_red.png',
				new google.maps.Size(37, 34),
				new google.maps.Point(20,0),
				new google.maps.Point(10, 34)
			);
			
			country.getElements('li.venue').each(function(venue){
				link = venue.getElement('a');
				marker = new google.maps.Marker({
					map: this.mapObj, 
					position: new google.maps.LatLng(link.get('data-lat'), link.get('data-lng')),
					uri: venue.getElement('a'),
					shadow: this.shadow,
					icon: this.icon(country.get('data-id'))
				});
				
				pos = marker.getPosition();
				
				self.markers.bounds.extend(pos)
								
				eval("self.markers.countries."+country.get('data-id')+".bounds.extend(pos)");
				eval("self.markers.countries."+country.get('data-id')+".markers.append([marker])");

				google.maps.event.addListener(marker, "click", function(e) {
					self.infoBubble.close();
					self.infoBubble.setPosition(this.getPosition());
					self.infoBubble.setContent(
						new Element('div', {html:"<h1>{location}</h1><p>{country}</p>".substitute({location:this.uri.get('html'), country:venue.getParent('.country').get('data-linktxt')}), 'class':'bubblecontent'}).setStyles({cursor:'pointer'}).addEvents({
						mouseup: function(){
							window.location = this.uri.get('href');
						}.bind(this)
					}));
					self.infoBubble.open();			
//					self.loc.fireEvent('onUpdateMap');
				});
				
//				new Element('a').set({html:'map'}).inject(venue, 'after');
			}.bind(this));
		}.bind(this));
		
		this.mapObj.fitBounds(self.markers.bounds);
		
		google.maps.event.addListener(this.mapObj, "click", function(e) {
			self.infoBubble.close();
		});		
	}
});
