var ConnectionMapController = new Class({
	_currentPopup: '',
	_currentId: '',

	initialize: function(windowsContainer, contentsContainer, mapContainer) {
        var windows = $(windowsContainer).getChildren();
        var contents = $(contentsContainer).getChildren();
        var areas = $(mapContainer).getChildren();
        contents.each(function(item, index) {
            var popupId = item.get('id');
            areas[index].addEvent('mouseover', this.mouseover.bindWithEvent(this, popupId));
            areas[index].addEvent('mouseout', this.mouseout.bindWithEvent(this, popupId));
            areas[index].set('id', 'area-'+popupId);
        }.bind(this));
        areas.each(function(item) {
            item.addEvent('click', function (event) {
                event.stop();
            });
        });
        windows.each(function(item) {
            item.addEvent('mouseout', this._mouseoutPopup.bindWithEvent(this));
            item.set('tween', {transition: Fx.Transitions.linear, duration: 300});
        }.bind(this));
	},
	
	mouseover: function(event, popupId) {
	    if (this._currentId && popupId == this._currentId) {
	        return;
	    }
	    if (this._currentId && popupId != this._currentId) {
	        this._hidePopup();
	    }
	    this._currentId = popupId;
	    this._showPopup();
	},
	
	mouseout: function(event, popupId) {
	    if (this._currentId && popupId != this._currentId) {
	        return;
	    }
	    if (this._isMouseOut(event, popupId)) {
    	    this._hidePopup();
    	    this._currentId = null;
	    }
	},
	
	_mouseoutPopup: function(event) {
	    this.mouseout(event, this._currentId);
	},
	
	_showPopup: function() {
        var popupContent = $(this._currentId);
        var popupAttribs = popupContent.get('popup_attribs').split(':');
	    this._currentPopup = $('popup-window-'+popupAttribs[0]);
        this._currentPopup.getElement('.popup-content').adopt(popupContent.getChildren());
        this._currentPopup.setStyles({
            display: 'block',
            top: popupAttribs[1]+"px",
            left: popupAttribs[2]+"px"
        });
        this._currentPopup.fade('show');
	},
	
	_hidePopup: function() {
	    this._currentPopup.fade('hide');
	    this._currentPopup.setStyle('display', 'none');
        $(this._currentId).adopt(this._currentPopup.getElement('.popup-content').getChildren());
        this._currentPopup = null;
	},
	
	_isMouseOut: function(event, popupId) {
	    var target = $(event.relatedTarget);
	    var result = true;
	    var popupId = this._currentPopup ? this._currentPopup.get('id') : false;
        var areaId = 'area-'+this._currentId;
	    while(target) {
	        var targetId = target.get('id');
	        if (targetId == 'component-area') {
	            break;
	        } else if ((popupId && targetId == popupId) || targetId == areaId) {
	            result = false;
	            break;
	        }
	        target = target.getParent();
	    }
	    return result;
	}
});
