var map = null;
var content = null;
var close = null;
var cluster = null;
var markers = [];
var loaded = false;
var show_on_load = false;
var moving_marker = false;
var current_marker = null;
var user_pos = null;

Event.observe(window, 'load', function() {
	site.jslinks();
	
	close = $('close');
	close.hide();
	close.observe('click', site.close);
	
	if(GBrowserIsCompatible()) {
		var content_area = $('content');
		var mapbox = $('mapbox');
		var center_set = false;
		
		content_area.insert(mapbox);
		
		map = new GMap2(mapbox);
		map.setCenter(new GLatLng(39.23225314171489, -101.77734375), 3);
		map.addControl(new GSmallZoomControl3D());
		map.addControl(new GHierarchicalMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.enableScrollWheelZoom();
		
		var icon = new GIcon({
			'image': '/images/icon.png',
			'size': new GSize(30, 33),
			'iconAnchor': new GPoint(17, 33),
			'infoWindowAnchor': new GPoint(17, 33)
		});
		
		var icon_hide = new GIcon({
			'image': '/images/icon_hide.png',
			'size': new GSize(30, 33),
			'iconAnchor': new GPoint(17, 33),
			'infoWindowAnchor': new GPoint(17, 33)
		});

		new Ajax.Request('/map.php?words='+words+'&test='+test_markers, {
			method: 'get',
			onSuccess: function(transport){
				if(transport.responseText.substr(0, 1) == '[') {
					var points = transport.responseText.evalJSON(true);
					
					points.each(function(p, i) {
						if(typeof view_marker != 'undefined' && view_marker > 0 && view_marker == p.user_id) {
							map.setCenter(new GLatLng(p.lat, p.lon), 15);
							center_set = true;
						}
						
						if(user_id > 0 && user_id == p.user_id) {
							user_pos = new GLatLng(p.lat, p.lon);
							if(! center_set) map.setCenter(user_pos, 15);
						}
						
						if(typeof p.hide != 'undefined' && p.hide == 1) markers[i] = new GMarker(new GLatLng(p.lat, p.lon), {icon: icon_hide, draggable: true});
						else markers[i] = new GMarker(new GLatLng(p.lat, p.lon), {icon: icon, draggable: true});
				
						markers[i].data = {id: p.id, user_id: p.user_id, lat: p.lat, lon: p.lon};
						GEvent.addListener(markers[i], 'click', marker_events.clicked);
						GEvent.addListener(markers[i], 'dragend', marker_events.moved);
						markers[i].disableDragging();
					});

					cluster = new MarkerClusterer(map, markers, {gridSize: 40, styles: [
						{width: 30, height: 33, url: '/images/icon.png', opt_anchor: [19, 13], opt_textColor : 'white'},
						{width: 30, height: 33, url: '/images/icon.png', opt_anchor: [19, 9], opt_textColor : 'white'},
						{width: 30, height: 33, url: '/images/icon.png', opt_anchor: [19, 7], opt_textColor : 'white'},
						{width: 30, height: 33, url: '/images/icon.png', opt_anchor: [19, 2], opt_textColor : 'white'}
					]});
				} else alert(transport.responseText);
			}
		});
		
		content = $('content_body').hide();
	}
	
	loaded = true;
	if(show_on_load) site.display();
});

var marker_events = {
	clicked: function(i) {
		if(! moving_marker) {
			new Ajax.Request('/bubble.php?id='+this.data.user_id, {
				method: 'get',
				onSuccess: (function(transport){
					current_marker = this;
					this.openInfoWindowHtml(transport.responseText);
				}).bind(this)
			});
		}
	},
	moved: function() {
		
	}
}

var marker_func = {
	start_move: function() {
		if(current_marker) {
			moving_marker = true;
			current_marker.closeInfoWindow();
			current_marker.enableDragging();
			$('move_message').show();
		} else alert('Can\'t find marker');
	},
	save_move: function() {
		var latlng = current_marker.getLatLng();
		current_marker.disableDragging();
		moving_marker = false;
		$('move_message').hide();
		
		new Ajax.Request('/action.php', {
			method: 'post',
			parameters: {
				'action': 'move_marker',
				'id': current_marker.data.id,
				'lat': latlng.lat(),
				'lon': latlng.lng()
			},
			onSuccess: function(transport){
				if(transport.responseText == 1) {
					current_marker.data.lat = latlng.lat();
					current_marker.data.lon = latlng.lng();
				} else alert('Could not move the marker.');
			}
		});
	},
	cancel_move: function() {
		current_marker.disableDragging();
		current_marker.setLatLng(new GLatLng(current_marker.data.lat, current_marker.data.lon));
		moving_marker = false;
		$('move_message').hide();
	},
	show: function() {
		current_marker.closeInfoWindow();
		current_marker.setImage('/images/icon.png');
		
		new Ajax.Request('/action.php', {
			method: 'post',
			parameters: {
				'action': 'show_marker',
				'id': current_marker.data.id
			},
			onSuccess: function(transport){if(transport.responseText != 1) alert('Error setting visibility status.');}
		});
	},
	hide: function() {
		current_marker.closeInfoWindow();
		current_marker.setImage('/images/icon_hide.png');
		
		new Ajax.Request('/action.php', {
			method: 'post',
			parameters: {
				'action': 'hide_marker',
				'id': current_marker.data.id
			},
			onSuccess: function(transport){if(transport.responseText != 1) alert('Error setting visibility status.');}
		});
	}
};

var site = {
	my_marker: function() {
		if(user_pos) {
			map.setCenter(user_pos, 15);
			(function() {
				site.open(null, '/profile.php?id='+user_id);
			}).delay(0.2);
		} else {
			site.open(null, '/edit_account.php?id='+user_id);
		}
	},
	jslinks: function(obj) {
		if(typeof obj != 'undefined' && obj) {
			obj.select('a.jsopen').each(function(e) {e.observe('click', site.open); e.removeClassName('jsopen')});
			obj.select('a.jsblank').each(function(e) {e.target='_blank'; e.removeClassName('jsblank')});
		} else {
			$$('a.jsopen').each(function(e) {e.observe('click', site.open); e.removeClassName('jsopen')});
			$$('a.jsblank').each(function(e) {e.target='_blank'; e.removeClassName('jsblank')});
		}
	},
	open: function(event, url) {
		if(! url) var url = this.href;
		if(url.indexOf('?') < 0) url += '?ajax=1';
		else url += '&ajax=1';
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport){
				content.update(transport.responseText);
				site.jslinks(content);
			}
		});
		
		if(event) Event.stop(event);
	},
	display: function() {
		if(loaded) {
			content.show();
			close.show();
			var inputs = content.select('input[type="text"]');
			if(inputs.length > 0) inputs[0].focus();
		} else show_on_load = true;
	},
	close: function(event) {
		close.hide();
		content.hide();
		content.update();
		Event.stop(event);
	},
	country_control: function() {
		var country = $('country');
		var csel = function() {
			if(this.options[this.selectedIndex].value == 'US') {
				$('province_row').hide();
				$('state_row').show();
			} else {
				$('state_row').hide();
				$('province_row').show();
			}
		};
		
		country.observe('change', csel);
		var csel_now = csel.bind(country);
		csel_now();
	}
};