﻿(function($) {
    $.fn.AlertBubble = function(opts) {
        return this.each(function() {
            var conf = $.extend({}, opts);
            if (conf !== false) {
                new alertBubble().init(this, conf);
            }
        });
    };
    function alertBubble() {
        return {
            settings: {
                fadeTime: 150,
                text: false,
                showEvent: [],
                hideEvent: [],
                onBeforeShowCallback: null,
                onBeforeHideCallback: null,
                onAfterShowCallback: null,
                onAfterHideCallback: null,
                showOnStart: true,
				hideTimer: false
            },
            container: null,
            init: function(elem, opts) {
                this.container = $(elem);
                if (this.container.size == 0) { alert("Invalid container node!"); return }
                this.settings = $.extend({}, this.settings, opts);

                if (!this.settings.text) {
                    this.settings.text = this.container.html();
                }
                else {
                    this.container.html(this.settings.text);
                }
                this.container.hide();
                this.container.addClass("alert-bubble");

				this._bindEvents(this.settings.showEvent, this.showBubble);
				this._bindEvents(this.settings.hideEvent, this.hideBubble);

                if (this.settings.showOnStart) this.showBubble();

                //store the api for this object
                this.container.data("AlertBubble", this);
            },
            showBubble: function() {
                if (this.settings.onBeforeShowCallback == null || (this.settings.onBeforeShowCallback != null && this.settings.onBeforeShowCallback.apply(this, []))) {
                    var _this = this;
					this.container.fadeIn(this.fadeTime, function() {
						if (_this.settings.hideTimer) setTimeout(function() {_this.hideBubble()}, _this.settings.hideTimer);
					});
                    if (this.settings.onAfterShowCallback != null) this.settings.onAfterShowCallback.apply(this, []);
                }
            },
            hideBubble: function() {
                if (this.settings.onBeforeHideCallback == null || (this.settings.onBeforeHideCallback != null && this.settings.onBeforeHideCallback.apply(this, []))) {
                    this.container.fadeOut(this.fadeTime);
                    if (this.settings.onAfterHideCallback != null) this.settings.onAfterHideCallback.apply(this, []);
                }
            },
			_bindEvents: function(sl, b) {
				for (var e in sl) {
                    var ev = sl[e];
					var _this = this;
					ev.selector.bind(ev.event, function(event) {
						b.apply(_this, []);
					});
                }
			}
        };
    };
})(jQuery);
