/**
 * Hotspot tester
 */
/*extern jQuery, pmmi*/
Object.setToDotRef("pmmi.Hotspot", function ($) {

    function pInPoly(x, y, v) {
        var i, n = v.length - 1, vt, cv, nv, cn = 0;

        for (i = 0; i < n; i++) {
            cv = v[i]; nv = v[i + 1];
            if (((cv.y <= y) && (nv.y > y)) ||
                ((cv.y > y) && (nv.y <= y))) {
                vt = (y - cv.y) / (nv.y - cv.y);
                if (x < cv.x + vt * (nv.x - cv.x)) {
                    cn++;
                }
            }
        }

        return (cn % 2) === 1;
    }

    var Hotspot = Object.extendClass(pmmi.Emitter, {
        constructor: function () {
            Hotspot.superclass.constructor.call(this);
            this.addEvents("enter", "leave");
            this.mouseMoveEvtName = "mousemove.hotspot";
            this.hotspotPoly = null;
            this.bound = false;
            this.over = false;
        },

        onMouseMove: function (evt) {
            var over = pInPoly(evt.pageX, evt.pageY, this.hotspotPoly);
            if (!over && this.over) {
                //console.log("hotspot: %s", "leave");
                this.emitEvent("leave");
            } else if (over && !this.over) {
                //console.log("hotspot: %s", "enter");
                this.emitEvent("enter");
            }
            this.over = over;
        },

        start: function (hotspotPoly, mousePos) {
            var self = this;

            this.stop();
            this.bound = true;
            this.over = mousePos ? pInPoly(mousePos.x, mousePos.y, hotspotPoly) : true;
            this.hotspotPoly = hotspotPoly;

            $(document).bind(this.mouseMoveEvtName, function (evt) {
                self.onMouseMove(evt);
            });
        },

        stop: function () {
            if (this.bound) {
                this.hotspotPoly = null;
                $(document).unbind(this.mouseMoveEvtName);
                this.bound = false;
            }
        }
    });

    return Hotspot;
}(jQuery));
