/* 
 * PMMI map
 *
 * @author Zsolt Mészárovics
 */

/*extern jQuery, pmmi*/
Object.setToDotRef("pmmi.Map", function ($) {
    var inited = false,
        defaultCfg,
        rCoords = /([0-9]+) *, *([0-9]+)/;

    function Map(config) {
        this.c = $.extend({}, defaultCfg, config);
        this.attachEvents();
        this.outDelay = null;
        this.overlay = new pmmi.Overlay(this.c.overlay);
        this.overlay.addReceiver("hide", this.onOverlayHide, this);
        this.nextCity = null;
    }

    Map.prototype = {
        onMapOver: function () {
            if (this.outDelay) {
                clearTimeout(this.outDelay);
                this.outDelay = null;
            } else {
                this.c.$img.addClass("over");
            }
        },

        onMapOut: function () {
            var self = this;

            this.outDelay = setTimeout(function () {
                self.onMapOutDealyElapsed();
            }, this.c.outDelay);
        },

        onMapOutDealyElapsed: function () {
            this.outDelay = null;
            this.c.$img.removeClass("over");
        },

        onCityOver: function (evt) {
            var coords = rCoords.exec(evt.target.coords), x, y, id;
            if (coords) {
                x = parseInt(coords[1], 10);
                y = parseInt(coords[2], 10);
                id = parseInt(evt.target.id.substring(10));
                if (!this.overlay.isVisible()) {
                    this.overlay.show(x, y, id);
                } else {
                    this.nextCity = [x, y, id];
                }
            }
        },

        onCityOut: function () {
            this.nextCity = null;
        },

        onOverlayHide: function () {
            var nextCity = this.nextCity;
            if (nextCity) {
                this.overlay.show.apply(this.overlay, nextCity);
            }
        },

        attachEvents: function () {
            var self = this;
            this.c.$img.bind("mouseover", function () {
                self.onMapOver();
            }).bind("mouseout", function () {
                self.onMapOut();
            });

            $("> area", this.c.$map).bind("mouseover", function (evt) {
                self.onCityOver(evt);
            }).bind("mouseout", function (evt) {
                self.onCityOut(evt);
            }).bind("click", function (evt) {
                evt.preventDefault();
            });
        }
    };

    Map.getInstance = function (config) {
        if (!inited) {
            defaultCfg = {
                $img: $("#pmmap"),
                $map: $("#pmmap_map"),
                outDelay: 500,
                overlay: {
                    xOffset: 5,
                    yOffset: 2,
                    cities: {}
                }
            };
            inited = true;
        }

        return new Map(config);
    }

    return Map;
}(jQuery));
