Map = new Class({
	'options': {
		'width': 939,
		'height': 620,
		'detailsWidth': 400,
		'detailsHeight': 250,
		'zoom': 2,
		'backgroundColor': '#E7E7E7',
		'lat': 25,
		'lng': 0,
		'markersZoom': 12,
		'filter': 'hours=336',
		'error': gettext('Server overloaded, too many people are making love right now')
	},
	'initialize': function(){
		if (!GBrowserIsCompatible()){
	        alert(gettext('Your browser is not compatible'),'error');
	        return false;
	    }
	    window.addEvent('domready', function(){
			var holder = $('ijmlMap');
			if (!holder) return false;
			this.notifications = holder.getPrevious('.notifications');
			this.map = new GMap2(holder,{
				'size': new GSize(marker?this.options.detailsWidth:this.options.width,marker?this.options.detailsHeight:this.options.height),
				'backgroundColor': this.options.backgroundColor,
				'googleBarOptions':{
					'showOnLoad':true,
					'style': 'new',
					'listingTypes': G_GOOGLEBAR_TYPE_LOCALONLY_RESULTS,
					'adsOptions':{
						'client': this.options.adsClient
					}
				}
			});
			this.map.setCenter(new GLatLng(this.options.lat,this.options.lng),this.options.zoom);
			!marker?this.map.enableGoogleBar():null;
			this.map.setMapType(G_PHYSICAL_MAP);
			this.map.setUI({
				'maptypes': {
					'normal':false,
					'satellite':false,
					'hybrid': false,
					'physical':false
				},
				'zoom': {
					'scrollwheel': false,
					'doubleclick': true,
					'keyboard': false
				},
				'controls': {
					'smallzoomcontrol3d': true,
					'maptypecontrol': true,
					'menumaptypecontrol':false,
					'scalecontrol': false
				}
			});
			this.refresh = $$('.refreshMap');
		    this.marker = new GIcon(G_DEFAULT_ICON);
		    this.marker.iconSize = new GSize(16, 25);
		    this.marker.iconAnchor = new GPoint(8,25);
		    this.marker.shadow = '';
		    this.cluster = new GIcon(G_DEFAULT_ICON);
		    this.cluster.image = MEDIA_URL+'img/icons/cluster.png';
		    this.cluster.shadow = '';
		    if (marker) {
		    	marker = this.createMarker(marker);
		    	this.map.setCenter(new GLatLng(marker.getLatLng().lat(),marker.getLatLng().lng()),13);
		    	this.map.addOverlay(marker);
			} else {
			    GEvent.bind(this.map, 'singlerightclick', this, function(point,src,overlay){
					var point = this.map.fromContainerPixelToLatLng(point);
		            if (overlay) return false;
					new Request.JSON({
						'url':ROOT_URL+'map/form/',
						'method':'POST',
						'data':['lat='+point.lat().toFixed(6),'lng='+point.lng().toFixed(6)].join('&'),
						'onRequest': function(){
							this.notify(gettext('creating new marker'));
						}.bind(this),
						'onComplete': function(json){
							if (!json) {
								this.notify(this.options.error,'error');
								return false;
							} else if (!json.status){
								this.notify(json.response,'error');
								return false;
							}
							this.marker.image = MEDIA_URL+'img/icons/orientation_1.png';
							var marker = new GMarker(point,{'icon':this.marker,'clickable':false});
				            GEvent.bind(marker, 'infowindowclose', this, function(){
								this.map.removeOverlay(marker);
				            });
				            this.map.addOverlay(marker);
				            var html = new Element('div',{'html':json.response});
				            if (Browser.Engine.trident){
				            	html.addEvent('click',events);
							}
				            marker.openInfoWindowHtml(html);
				            this.notifications.empty();
						}.bind(this),
						'onFailure': function(xhr){
							this.notify(this.options.error,'error');
						}.bind(this)
					}).send();
			    });

		    	GEvent.bind(this.map, 'zoomend', this, function(){
			        this.map.clearOverlays();
			        this.refresh.removeClass('hidden');
			    });
			    GEvent.bind(this.map, 'dragend', this, function(){
					this.refresh.removeClass('hidden');
			    });
		    	this.getMarkers();
			}
		}.bind(this));
	},
	'getMarkers': function(){
		if (this.request) this.request.cancel();
		var bounds = this.map.getBounds();
		this.request = new Request.JSON({
        	'url':ROOT_URL+'map/markers/',
        	'method':'POST',
        	'link':'cancel',
        	'data':[
        		'decimal='+(this.map.getZoom()>this.options.zoom?1:0),
        		'markers='+(this.map.getZoom()>=this.options.markersZoom?1:0),
        		this.options.filter,
        		'north='+bounds.getNorthEast().lat(),
        		'east='+bounds.getNorthEast().lng(),
        		'south='+bounds.getSouthWest().lat(),
        		'west='+bounds.getSouthWest().lng()
        	].join('&'),
        	'onRequest': function(){
            	this.map.clearOverlays();
            	this.refresh.addClass('hidden');
            	this.notify(gettext('loading'));
        	}.bind(this),
			'onComplete': function(json){
			    if (!json || !json.status) {
					this.notify(this.options.error,'error');
			        return false;
			    }
			    json.response.each(function(element){
	            	if (element.pk){
						this.map.addOverlay(this.createMarker(element,true));
					} else{
						this.map.addOverlay(this.createCluster(element));
					}
			    }.bind(this));
			    var total_holder = $('total_holder');
				if (total_holder.hasClass('hidden')) total_holder.removeClass('hidden');
				if (total_holder) total_holder.getElements('strong')[0].set('html', json.total);		
			    this.notifications.empty();
			}.bind(this)
		});
		this.request.send();
	},
	'createMarker': function(element,click){
		this.marker.image = element.icon;
		var marker = new GMarker(new GLatLng(element.lat,element.lng),{'icon':this.marker,'clickable':true});
		if (click){
			GEvent.bind(marker, 'click', this, function(point){
				new Request.JSON({
        			'url':ROOT_URL+'map/marker/',
        			'method': 'POST',
        			'data':['pk='+element.pk].join('&'),
					'onComplete': function(json){
						if (!json || !json.status) {
							this.notify(this.options.error,'error');
							return false;
						}
						var html = new Element('div',{'html':json.response});
					    if (Browser.Engine.trident){
					        html.addEvent('click',events);
						}
						marker.openInfoWindowHtml(html);
					}.bind(this)
				}).send();
			});
		}
		return marker;
	},
	'createCluster': function(element){
		this.cluster.iconSize = new GSize(element.size,element.size);
		this.cluster.iconAnchor = new GPoint(element.size/2,element.size/2);
		this.cluster.imageMap = [0,0,element.size,0,element.size,element.size,0,element.size];
		var cluster = new GMarker(new GLatLng(element.lat,element.lng),{'icon':this.cluster,'clickable':true});
		GEvent.bind(cluster, 'click', this, function(point){
			this.map.setCenter(point);
			this.map.zoomIn();
			this.getMarkers();
		});
		GEvent.bind(cluster, 'mouseover', this, function(){
			cluster.isOver = true;
			setTimeout(function(){
				if (cluster.isOver){
					cluster.openInfoWindowHtml('<p>'+gettext('Love count in this area')+': <strong>'+element.count.toString()+'</strong><br/><br/><i>'+gettext('zoom in for more info')+'.</i></p>');
				}
			}.bind(this),400);
		});
		GEvent.bind(cluster, 'mouseout', this, function(){
			cluster.closeInfoWindow();
			cluster.isOver = false;
		});
		return cluster;
	},
	'notify': function(message,type){
		this.notifications.set('html','<li class="'+(type?type:'info')+'"><span>'+message+'</span></li>');
	}
});
var map = new Map();
