if (Object.isUndefined(Prototype.Browser.IE6)) {
    Prototype.Browser.IE6 = (navigator.appName.indexOf("Microsoft Internet Explorer") != -1 && navigator.appVersion.indexOf("MSIE 6.0") != -1 && !window.XMLHttpRequest);
}
if (!window.Modalbox) var Modalbox = {};
Modalbox.Methods = {
    overrideAlert: false,
    focusableElements: [],
    currFocused: 0,
    initialized: false,
    active: true,
    options: {
        title: "ModalBox Window",
        overlayClose: true,
        displayTag: true,
        width: 500,
        height: 90,
        overlayOpacity: 0.65,
        overlayDuration: 0.25,
        slideDownDuration: 0.5,
        slideUpDuration: 0.5,
        resizeDuration: 0.25,
        inactiveFade: true,
        transitions: true,
        loadingString: "Please wait. Loading...",
        closeString: "Close window",
        closeValue: "&times;",
        params: {},
        method: "get",
        autoFocusing: true,
        aspnet: false
    },
    _options: {},
    setOptions: function (options) {
        Object.extend(this.options, options || {});
    },
    _init: function (options) {
        Object.extend(this._options, this.options);
        this.setOptions(options);
        this.MBoverlay = new Element("div", {
            id: "MB_overlay",
            style: "opacity: 0"
        });
        this.MBwindow = new Element("div", {
            id: "MB_window",
            style: "display: none"
        }).update(this.MBframe = new Element("div", {
            id: "MB_frame"
        }).update(this.MBheader = new Element("div", {
            id: "MB_header"
        }).update(this.MBcaption = new Element("div", {
            id: "MB_caption"
        }))));
        this.MBclose = new Element("a", {
            id: "MB_close",
            title: this.options.closeString,
            href: "#"
        }).update("<span>" + this.options.closeValue + "</span>");
        this.MBheader.insert({
            'bottom': this.MBclose
        });
        this.MBcontent = new Element("div", {
            id: "MB_content"
        }).update(this.MBloading = new Element("div", {
            id: "MB_loading"
        }).update(this.options.loadingString));
        this.MBframe.insert({
            'bottom': this.MBcontent
        });
        if (this.options.displayTag !== false) {
            this.MBtag = new Element("div", {
                id: "MB_tag"
            }).update("<div class=\"poweredBy\">Powered by <a href=\"http://www.worldaddresses.com\" target=\"_blank\"><img src=\"images/worldaddresses_logo.png\" alt=\"World Addresses\" title=\"World Addresses\" /></a> &reg;</div>");
            this.MBwindow.insert({
                'bottom': this.MBtag
            });
        }
        var injectToEl = this.options.aspnet ? $(document.body).down('form') : $(document.body);
        injectToEl.insert({
            'top': this.MBwindow
        });
        injectToEl.insert({
            'top': this.MBoverlay
        });
        this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
        this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        this.hideObserver = this._hide.bindAsEventListener(this);
        this.kbdObserver = this._kbdHandler.bindAsEventListener(this);
        this.resizeObserver = this._setWidthAndPosition.bindAsEventListener(this);
        this._initObservers();
        this.initialized = true;
    },
    show: function (content, options) {
        if (!this.initialized) this._init(options);
        this.content = content;
        this.setOptions(options);
        if (this.options.title) {
            this.MBcaption.update(this.options.title);
        } else {
            this.MBheader.hide();
            this.MBcaption.hide();
        }
        if (this.MBwindow.style.display == "none") {
            this._appear();
            this.event("onShow");
        } else {
            this._update();
            this.event("onUpdate");
        }
    },
    hide: function (options) {
        if (this.initialized) {
            if (options && !Object.isFunction(options.element)) Object.extend(this.options, options);
            this.event("beforeHide");
            if (this.options.transitions) {
                Effect.SlideUp(this.MBwindow, {
                    duration: this.options.slideUpDuration,
                    transition: Effect.Transitions.sinoidal,
                    afterFinish: this._deinit.bind(this)
                });
            } else {
                this.MBwindow.hide();
                this._deinit();
            }
        } else {
            throw ("Modalbox is not initialized.");
        }
    },
    _hide: function (event) {
        event.stop();
        if (event.element().id == 'MB_overlay' && !this.options.overlayClose) return false;
        this.hide();
    },
    alert: function (message) {
        var html = '<div class="MB_alert"><p>' + message + '</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';
        Modalbox.show(html, {
            title: 'Alert: ' + document.title,
            width: 300
        });
    },
    _appear: function () {
        if (Prototype.Browser.IE6) {
            window.scrollTo(0, 0);
            this._prepareIEHtml("100%", "hidden");
            this._prepareIESelects("hidden");
        }
        this._setSize();
        this._setPosition();
        if (this.options.transitions) {
            this.MBoverlay.setOpacity(0);
            new Effect.Fade(this.MBoverlay, {
                from: 0,
                to: this.options.overlayOpacity,
                duration: this.options.overlayDuration,
                afterFinish: (function () {
                    new Effect.SlideDown(this.MBwindow, {
                        duration: this.options.slideDownDuration,
                        transition: Effect.Transitions.sinoidal,
                        afterFinish: (function () {
                            this._setPosition();
                            this.loadContent();
                        }).bind(this)
                    });
                }).bind(this)
            });
        } else {
            this.MBoverlay.setOpacity(this.options.overlayOpacity);
            this.MBwindow.show();
            this._setPosition();
            this.loadContent();
        }
        Event.observe(window, "resize", this.resizeObserver);
    },
    _update: function () {
        this.MBcontent.update($(this.MBloading).update(this.options.loadingString));
        this.loadContent();
    },
    resizeTo: function (newWidth, newHeight, options) {
        var o = this.MBoverlay.getDimensions();
        var newStyle = {
            width: newWidth + "px",
            height: newHeight + "px",
            left: (o.width - newWidth) / 2 + "px"
        };
        this.options.width = newWidth;
        if (options) this.setOptions(options);
        if (this.options.transitions) {
            new Effect.Morph(this.MBwindow, {
                style: newStyle,
                duration: this.options.resizeDuration,
                beforeStart: function (fx) {
                    fx.element.setStyle({
                        overflow: "hidden"
                    });
                },
                afterFinish: (function (fx) {
                    fx.element.setStyle({
                        overflow: "visible"
                    });
                    this.event("_afterResize");
                    this.event("afterResize");
                }).bind(this)
            });
        } else {
            this.MBwindow.setStyle(newStyle);
            (function () {
                this.event("_afterResize");
                this.event("afterResize");
            }).bind(this).defer();
        }
    },
    resize: function (byWidth, byHeight, options) {
        var w = this.MBwindow.getDimensions(),
            hHeight = this.MBheader.getHeight(),
            cHeight = this.MBcontent.getHeight();
        this.resizeTo((w.width + byWidth), Math.max(hHeight + cHeight, w.height + byHeight), options);
    },
    resizeToContent: function (options) {
        var byHeight = this.options.height - this.MBwindow.getHeight();
        if (byHeight != 0) {
            this.resize(0, byHeight, options);
        }
    },
    resizeToInclude: function (element, options) {
        element = $(element);
        var styles = ['margin-top', 'margin-bottom', 'border-top-width', 'border-bottom-width'];
        var elHeight = styles.inject(element.getHeight(), function (acc, n) {
            var x = parseInt(element.getStyle(n), 10);
            acc += (isNaN(x) ? 0 : x);
            return acc;
        });
        if (elHeight > 0) {
            Modalbox.resize(0, elHeight, options);
        }
    },
    loadContent: function () {
        if (this.event("beforeLoad")) {
            if (typeof this.content == 'string') {
                var htmlRegExp = new RegExp(/<\/?[^>]+>/gi),
                    evalScript = function (script) {
                        return eval(script.replace("<!--", "").replace("// -->", ""));
                    };
                if (htmlRegExp.test(this.content)) {
                    this._insertContent(this.content.stripScripts(), (function () {
                        this.content.extractScripts().map(evalScript, window);
                    }).bind(this));
                } else {
                    new Ajax.Request(this.content, {
                        method: this.options.method.toLowerCase(),
                        parameters: this.options.params,
                        onSuccess: (function (transport) {
                            var response = new String(transport.responseText);
                            this._insertContent(transport.responseText.stripScripts(), function () {
                                response.extractScripts().map(evalScript, window);
                            });
                        }).bind(this),
                        onException: function (instance, exception) {
                            Modalbox.hide();
                            throw ('Modalbox Loading Error: ' + exception);
                        }
                    });
                }
            } else if (typeof this.content == 'object') {
                this._insertContent(this.content);
            } else {
                this.hide();
                throw ('Modalbox Parameters Error: Please specify correct URL or HTML element (plain HTML or object)');
            }
        }
    },
    _insertContent: function (content, callback) {
        this.MBcontent.hide().update();
        if (typeof content == 'string') {
            this.MBcontent.insert(new Element("div", {
                style: "display: none"
            }).update(content)).down().show();
        } else if (typeof content == 'object') {
            var _htmlObj = content.cloneNode(true);
            if (content.id) content.id = "MB_" + content.id;
            $(content).select('*[id]').each(function (el) {
                el.id = "MB_" + el.id;
            });
            this.MBcontent.insert(_htmlObj).down().show();
            if (Prototype.Browser.IE6) {
                this._prepareIESelects("", "#MB_content ");
            }
        }
        if (this.options.height == this._options.height) {
            this.resizeTo(this.options.width, this.MBheader.getHeight() + this.MBcontent.getHeight(), {
                afterResize: (function () {
                    this._putContent.bind(this, callback).defer();
                }).bind(this)
            });
        } else {
            this._setSize();
            this.MBcontent.setStyle({
                overflow: 'auto',
                height: this.options.height - this.MBheader.getHeight() - 1 + 'px'
            });
            this._putContent.bind(this, callback).defer();
        }
    },
    _putContent: function (callback) {
        this.MBcontent.show();
        this._findFocusableElements();
        this._setFocus();
        if (Object.isFunction(callback)) callback();
        this.event("afterLoad");
    },
    activate: function (options) {
        this.setOptions(options);
        this.active = true;
        if (this.options.overlayClose) this.MBoverlay.observe("click", this.hideObserver);
        this.MBclose.observe("click", this.hideObserver).show();
        if (this.options.transitions && this.options.inactiveFade) new Effect.Appear(this.MBwindow, {
            duration: this.options.slideUpDuration
        });
    },
    deactivate: function (options) {
        this.setOptions(options);
        this.active = false;
        if (this.options.overlayClose) this.MBoverlay.stopObserving("click", this.hideObserver);
        this.MBclose.stopObserving("click", this.hideObserver).hide();
        if (this.options.transitions && this.options.inactiveFade) new Effect.Fade(this.MBwindow, {
            duration: this.options.slideUpDuration,
            to: 0.75
        });
    },
    _initObservers: function () {
        this.MBclose.observe("click", this.hideObserver);
        if (this.options.overlayClose) this.MBoverlay.observe("click", this.hideObserver);
        var kbdEvent = (Prototype.Browser.Gecko || Prototype.Browser.Opera) ? "keypress" : "keydown";
        Event.observe(document, kbdEvent, this.kbdObserver);
    },
    _removeObservers: function () {
        this.MBclose.stopObserving("click", this.hideObserver);
        if (this.options.overlayClose) this.MBoverlay.stopObserving("click", this.hideObserver);
        var kbdEvent = (Prototype.Browser.Gecko || Prototype.Browser.Opera) ? "keypress" : "keydown";
        Event.stopObserving(document, kbdEvent, this.kbdObserver);
    },
    _setFocus: function () {
        if (this.options.autoFocusing === true && this.focusableElements.length > 0) {
            var firstEl = this.focusableElements.find(function (el) {
                return el.tabIndex == 1;
            }) || this.focusableElements.first();
            this.currFocused = this.focusableElements.toArray().indexOf(firstEl);
            firstEl.focus();
        } else if (this.MBclose.visible()) {
            this.MBclose.focus();
        }
    },
    _findFocusableElements: function () {
        if (this.options.autoFocusing === true) {
            this.MBcontent.select('input:not([type~=hidden]):enabled, select, textarea, button, a[href]').invoke('addClassName', 'MB_focusable');
            this.focusableElements = this.MBcontent.select('.MB_focusable');
        }
    },
    _kbdHandler: function (event) {
        var node = event.element();
        switch (event.keyCode) {
        case Event.KEY_TAB:
            event.stop();
            if (node != this.focusableElements[this.currFocused]) this.currFocused = this.focusableElements.indexOf(node);
            if (!event.shiftKey) {
                if (this.currFocused >= this.focusableElements.length - 1) {
                    this.currFocused = 0;
                } else {
                    this.currFocused++;
                }
            } else {
                if (this.currFocused <= 0) {
                    this.currFocused = this.focusableElements.length - 1;
                } else {
                    this.currFocused--;
                }
            }
            this.focusableElements[this.currFocused].focus();
            break;
        case Event.KEY_ESC:
            if (this.active) this._hide(event);
            break;
        case 32:
            this._preventScroll(event);
            break;
        case 0:
            if (event.which == 32) this._preventScroll(event);
            break;
        case Event.KEY_UP:
        case Event.KEY_DOWN:
        case Event.KEY_PAGEDOWN:
        case Event.KEY_PAGEUP:
        case Event.KEY_HOME:
        case Event.KEY_END:
            if (Prototype.Browser.WebKit && !["textarea", "select"].include(node.tagName.toLowerCase())) event.stop();
            else if ((node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a")) event.stop();
            break;
        }
    },
    _preventScroll: function (event) {
        if (!["input", "textarea", "select", "button"].include(event.element().tagName.toLowerCase())) event.stop();
    },
    _deinit: function () {
        this._removeObservers();
        Event.stopObserving(window, "resize", this.resizeObserver);
        if (this.options.transitions) {
            Effect.toggle(this.MBoverlay, 'appear', {
                duration: this.options.overlayDuration,
                afterFinish: this._removeElements.bind(this)
            });
        } else {
            this.MBoverlay.hide();
            this._removeElements();
        }
        this.MBcontent.setStyle({
            overflow: '',
            height: ''
        });
    },
    _removeElements: function () {
        if (Prototype.Browser.Opera) {
            window.scrollBy(0, 0);
        }
        this.MBoverlay.remove();
        this.MBwindow.remove();
        if (Prototype.Browser.IE6) {
            this._prepareIEHtml("", "");
            this._prepareIESelects("");
            window.scrollTo(this.initScrollX, this.initScrollY);
        }
        if (typeof this.content == 'object') {
            if (this.content.id && this.content.id.match(/MB_/)) {
                this.content.id = this.content.id.replace(/MB_/, "");
            }
            this.content.select('*[id]').each(function (el) {
                el.id = el.id.replace(/MB_/, "");
            });
        }
        this.initialized = false;
        this.event("afterHide");
        this.setOptions(this._options);
    },
    _setSize: function () {
        this.MBwindow.setStyle({
            width: this.options.width + "px",
            height: this.options.height + "px"
        });
    },
    _setPosition: function () {
        this.MBwindow.setStyle({
            left: ((this.MBoverlay.getWidth() - this.MBwindow.getWidth()) / 2) + "px"
        });
    },
    _setWidthAndPosition: function () {
        this.MBwindow.setStyle({
            width: this.options.width + "px",
            left: ((this.MBoverlay.getWidth() - this.options.width) / 2) + "px"
        });
    },
    _prepareIEHtml: function (height, overflow) {
        $$('html, body').invoke('setStyle', {
            width: height,
            height: height,
            overflow: overflow
        });
    },
    _prepareIESelects: function (overflow, prefix) {
        $$((prefix || "") + "select").invoke('setStyle', {
            'visibility': overflow
        });
    },
    event: function (eventName) {
        var r = true;
        if (this.options[eventName]) {
            var returnValue = this.options[eventName]();
            this.options[eventName] = null;
            if (!Object.isUndefined(returnValue)) r = returnValue;
        }
        Event.fire(document, 'Modalbox:' + eventName);
        return r;
    }
};
Object.extend(Modalbox, Modalbox.Methods);
if (Modalbox.overrideAlert) window.alert = Modalbox.alert;
