var MapBoxes = {
    init: function () {
        $('#cyp-map .icon').hover(
            function () { MapBoxes.show($(this).next())},
            MapBoxes.hideSoon
        );
        $('#cyp-map .popup').hover(
            MapBoxes.cancelHide,
            MapBoxes.hideSoon
        );
        $('#cyp-map').children().last().attr('alt', '');
    },

    show: function (bubble) {
        MapBoxes.cancelHide();
        $('#cyp-map .popup').not(bubble).hide();
        MapBoxes.bubble_show(bubble);
    },

    hide: function () {
        $('#cyp-map .popup').hide();
        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 (bubble) {
        var icon = bubble.prev();
        bubble.show();

        var bw = bubble.width();

        if (!bubble.has('.tail').length) {
            $('<img class="tail" src="/assets/images/map-bubble-tail.png" />').css({position: 'absolute', bottom: '-32px', left: (bw/2 - 8) + 'px'}).appendTo(bubble);
        }

        var pos = icon.position();

        var left = pos.left - (bw - icon.width())/2;
        var top = pos.top - bubble.outerHeight() - 32 + icon.height()/2;

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

        bubble.css({
            left: left + 'px',
            top: top + 'px'
        });
    },
};

$(MapBoxes.init);

