var Map = {
	
	map: null,
	
	map_zoom_level: 3,
	markerOptions: null,
	
	points: [],
	points_cache: [],
	
	show_started: false,
	current_position: 0,
	delay: 5, // seconds
	timeout: null,
	overlay: null,
	per_page: 20,
	
	language: null,
		
	init: function() {
		var self = this;
		
		var map_holder = $('#map-holder');
		map_holder.empty();
		
		this.map = new GMap2(map_holder[0]);
		centre = new GLatLng(22.997429561826504, 14.998891688883305);
		this.map.setCenter(centre, this.map_zoom_level);
		
		// when this is enabled, clicking on an open InfoWindow closes it!
		//this.map.disableDragging();
		
		this.map.setMapType(G_PHYSICAL_MAP);
		
		GEvent.addListener(this.map, "click", function() {
			return false;
		});

		icon = new GIcon();
		icon.image = '/assets/images/markers/image.png';
		icon.iconSize = new GSize(12,12);
		icon.shadowSize = new GSize(18,12);
		icon.iconAnchor = new GPoint(6,12);
		icon.infoWindowAnchor = new GPoint(6,0);
		icon.printImage = '/assets/images/markers/printImage.gif';
		icon.mozPrintImage = '/assets/images/markers/mozPrintImage.gif';
		icon.printShadow = '/assets/images/markers/printShadow.gif';
		icon.transparent = '/assets/images/markers/transparent.png';
		icon.imageMap = [7,1,9,2,10,3,10,4,10,5,10,6,10,7,10,8,9,9,8,10,6,11,5,11,3,10,2,9,1,8,1,7,1,6,1,5,1,4,1,3,2,2,4,1];		
		this.markerOptions = {icon:icon, draggable: false};
		
		// load the initial batch straight into the points array
		this.loadPoints(false);
		
		$('#map label.answers-own-language').click(function() {
			self.resetLanguage($('input', this).is(':checked'));
		});
	},
	
	loadPoints: function(cache_only) {
		var self = this;
		$.getJSON('/en/gmap-markers/' + ((this.language == null) ? '' : '?language=' + this.language), function(data) {
			var quoteCount = data.quotes.length;
			for (var i=0; i < quoteCount; i++) {				
				if (cache_only == true) {
					self.points_cache.push(data.quotes[i]);
				} else {
					self.points.push(data.quotes[i]);
				}				
			}			
			if (self.show_started == false) self.showNextPoint();			
		});
	},
	
	resetLanguage: function(filter) {
		if (filter == true) {
			this.language = $('body')[0].className.split(' ')[0];
		} else {
			this.language = null;
		}
		
		clearTimeout(this.timeout);
		this.timeout = null;
		
		this.current_position = 0;
		this.points = [];
		this.points_cache = [];
		
		this.show_started = false;
		this.loadPoints(false);
	},
	
	showNextPoint: function() {
		var self = this;
		
		// let the show commence!
		this.show_started = true;
		
		// clear the previous timeout
		clearTimeout(this.timeout);
		this.timeout = null;
		
		// the next point in line
		var point = this.points[this.current_position];
		
		// we are at the end of the points array so restart with the next batch
		if (point == undefined) {	
			// start from the beginning
			this.current_position = 0;
			this.points = [];
			this.points = this.points_cache;
			
			if (this.points.length) this.showNextPoint();
			
		} else {
			
			this.showOverlay();
			this.current_position++;
			
		}
		
		if (this.points.length > 1 && this.current_position == Math.ceil(this.points.length / 2)) {
			this.points_cache = [];
			this.loadPoints(true);
		}
		
	},
	
	showOverlay: function() {
		var self = this;
		
		var point = this.points[this.current_position];
		var gLatLng = new GLatLng(point.lat, point.lng);
		var marker = new GMarker(gLatLng, this.markerOptions);
		
		if (this.overlay != null) {
			this.map.removeOverlay(this.overlay);
		}
		
		this.map.closeInfoWindow();
		this.map.addOverlay(marker);
		
		marker.openExtInfoWindow(
			self.map,
			'infowindow',
			'<p dir="' + point.direction + '">' + point.quote + '<cite>' + point.user + ', ' + point.country + '<a href="#' + point.id + '">'+ Lang.FREEFORM_REPORT_COMMENT + '</a></cite></p>',
			{ beakOffset: 1 }
		);
		
		$('#infowindow a').bind('click', function(e) {
			e.preventDefault();
		});
		
		$('#infowindow a').one('click', function(e) {			
			var self = $(this);
			var id = self.attr('href').match(/[0-9]+/);
			
			self.addClass('spinner');		
			
			$.ajax({
				type: 'POST',
				url: '/en/gmap-markers/report/',
				data: 'fields[status]=Alerted&id=' + id + '&action[report-freeform-answer]=submit',
				success: function(data) {
					self.remove();
				}
			});
		});
		
		this.overlay = marker;
		
		this.timeout = setTimeout(
			function() {
				self.showNextPoint();
			},
			(this.delay * 1000)
		);
	}	
}

$(function() {
	if (GBrowserIsCompatible()) {
		$('head').append('<link rel="stylesheet" type="text/css" href="/assets/css/infowindow.css" media="screen, projection" />')
		$.ajax({
			type: "GET",
			url: '/assets/javascript/google.extinfowindow.js',
			cache: true,
			dataType: "script",
			success: function () {
				Map.init();
			}
		});
	}
});

$(document.body).unload(function() {
	if (GBrowserIsCompatible()) GUnload();
});