var MapBoxes = {
	init: function () {
		var map = $('cyp-map')

		if (!map) return;

		map.childElements().last().alt = '';

		map.select('.icon').each(function (a) {
			a.bubble = a.next('.popup');
			a.bubble.show = MapBoxes.bubble_show;
			a.bubble.hide = MapBoxes.bubble_hide;
			Event.observe(a, 'mouseover', MapBoxes.show.bindAsEventListener(a));
			Event.observe(a, 'mouseout', MapBoxes.hideSoon);
		});
	},

	show: function () {
		MapBoxes.cancelHide();
		if (MapBoxes.showing == this)
			return;
		else if (MapBoxes.showing)
			MapBoxes.showing.bubble.hide();

		MapBoxes.showing = this;
		this.bubble.show();
		Event.observe(this.bubble, 'mouseout', MapBoxes.hideSoon);
		Event.observe(this.bubble, 'mouseover', MapBoxes.cancelHide);
	},

	hide: function () {
		if (MapBoxes.showing)
		{
			MapBoxes.showing.bubble.hide();
			MapBoxes.showing = null;
		}
		MapBoxes.hideTimer = null;
	},

	hideSoon: function () {
		if (MapBoxes.hideTimer)
			clearTimeout(MapBoxes.hideTimer);
		MapBoxes.hideTimer = setTimeout(MapBoxes.hide, 800);
	},

	cancelHide: function () {
		if (!MapBoxes.hideTimer) return;

		clearTimeout(MapBoxes.hideTimer);
		MapBoxes.hideTimer = null;
	},

	bubble_show: function () {
		this.setStyle({display: 'block'});

		var icon = this.previous('.icon');

		var dims = this.getDimensions()

		var left = (icon.offsetLeft - dims.width/2 + icon.offsetWidth/2);
		var top = (icon.offsetTop - dims.height - 32 + icon.offsetHeight/2);

		if (/MSIE [3-7]/.match(navigator.appVersion) && !window.opera)
			left -= 20;	//IE places these bubbles mysteriously 20px to the right

		this.setStyle({
			left: left + 'px',
			top: top + 'px'
		});
		if (!this.tail) {
			this.tail = new Element('img', {src: 'images/map-bubble-tail.png'}).setStyle({position: 'absolute', bottom: '-32px', left: (dims.width/2 - 8) + 'px'});
			this.appendChild(this.tail);
		}
	},

	bubble_hide: function () {
		this.setStyle({display: 'none'});
	}
};

Event.observe(document, 'dom:loaded', MapBoxes.init);
