var MODALPANEL = {};
window.addEvent("domready", function() {
    MODALPANEL = (function() {
        var el = $("MODALPANEL");
        var opt = {
            position: "absolute",
            background: "#333333",
            width: window.getSize().size.x,
            height: window.getSize().size.y,
            top: 0,
            left: 0,
            zIndex: 65500,
            opacity: 0.2
        };
        el.setStyles(opt);
        el.addEvent("onshow",
        function(e) {
            e.setStyles({
                width: window.getSize().size.x,
                height: window.getSize().size.y
            })
        });
        return el
    })();
});

(function() {
    var str, strFrm;
    var gContent = function(frm) {
        if (!frm) {
            if (undefined != str) {
                return str
            }
            str = $("dialogProtoType").innerHTML;
            $("dialogProtoType").remove();
            return str
        }
        if (undefined != strFrm) {
            return strFrm
        }
        strFrm = $("frameDialogProtoType").innerHTML;
        $("frameDialogProtoType").remove();
        return strFrm
    };
    Dialog = new Class({
        Implements: [Options, Events],
        options: {
            onShow: $empty,
            onHide: $empty,
            onClose: $empty,
            onLoad: $empty,
            callback: false,
            frameable: false,
            width: 750,
            height: 400,
            dialogBoxWidth: 10,
            title: "",
            html:"",
            dragable: true,
            resizeable: true,
            ajaksable: true,
            singlon: true,
            modal: false,
            ajaxoptions: {
                update: false,
                evalScripts: true,
                method: "get",
                autoCancel: true
            }
        },
        initialize: function(url, param) {
            var div = this.currentRegionDialogs = $$(".dialog");
			//检测是否已经实例化，已实例化则直接跳出
            if (div.some(function(v, i) {
					if (v.retrieve("serial") == url.toString().trim() && v.style.display != "none") {
						v.inject(document.body);
						return true
					}
				})) {
                return
            }
            this.setOptions(param);
            param = this.options;
            this.UID = (Native.UID)++;
			//静态ajax框架内容
            var txt = gContent(this.options.frameable);
            this.dialog = new Element("div", {
                id: "dialog_" + this.UID,
                "class": "dialog",
                styles: {
                    zoom: 1,
                    opacity: 0,
                    position: "absolute",
                    top: (window.getSize().y-this.options.height)/2,
                    left: (window.getSize().x-this.options.width)/2,
                    zIndex: 65534
                }
            }).setHTML(txt).inject(document.body).store("serial", url.toString().trim());
            //如果定义了callback，则将值存储在本对话框中以便其它模块调用。类似：this.getParent('.dialog').retrieve
            if (this.options.callback) {
                this.dialog.store("callback", this.options.callback)
            }
			//对于多个dialog，则利用click来使其top
            this.dialog_head = $E(".dialog-head", this.dialog).addEvent("click",
            function(e) {
                if ($$(".dialog").length > 1) {
                    this.inject(document.body)
                }
            }.bind(this.dialog));
            this.dialog_body = $E(".dialog-content-body", this.dialog);
            //设置标题
            $E(".dialog-title", this.dialog_head).setText(param.title || "Dialog");
            //为关闭按钮绑定事件
            $E(".dialog-btn-close", this.dialog_head).addEvents({
                click: function(e) {
                    if (e) {
                        e = new Event(e).stop()
                    }
                    this.close()
                }.bind(this),
                mousedown: function(e) {
                    new Event(e).stop()
                }
            });
            if (param.dragable) {
                this.dragDialog()
            }
            if (param.resizeable) {
				//使body部分可拖动，注意setDialogWidth方法
                this.dialog_body.makeResizable({
                    handle: $E(".dialog-btn-resize", this.dialog),
                    limit: {
                        x: [200, window.getSize().x * 0.9],
                        y: [100, Math.max(window.getSize().y, window.getScrollSize().y)]
                    },
                    onDrag: function() {
                        this.setDialogWidth()
                    }.bind(this)
                })
            } else {
                $E(".dialog-btn-resize", this.dialog).hide()
            }
            //刷新体分为三部分，content-head、body、foot。
            //其中head部分是根据返回的字符串正则截取而来(main-head，如果有)，而body部分则是真正更新的部分，foot未处理。
            $extend(param.ajaxoptions, {
                update: this.dialog_body,
                elMap: {
                    ".mainHead": $E(".dialog-content-head", this.dialog),
                    ".mainFoot": $E(".dialog-content-foot", this.dialog)
                },
                onRequest: function() {
                    this.setDialog_bodySize()
                }.bind(this),
                onFailure: function() {
                    this.close();
                    alert("加载弹出内容失败!")
                }.bind(this),
                onComplete: function(h) {
                    if ("onComplete" in param) {
                        param.onComplete(h)
                    }
                    this.onLoad.call(this, h)
                }.bind(this)
            });
            this.popup(url, param)
        },
        onLoad: function(e) {
            var closeBtn = $E("*[isCloseDialogBtn]", this.dialog);
            if (closeBtn) {
                closeBtn.addEvent("click", this.close.bind(this))
            }
            this.dialog.store("instance", this);
            this.show()
        },
        initContent: function(url, param, arg) {
            param = param || this.options;
            var obj = this;
            /* unuseful,i don't know their's thinking
            if (!h) {
                var fuc = arguments.callee;
                this.reload = function() {
                    fuc(url, param, true)
                }
            }
            */
            if (param.frameable) {
                this.dialog_body.set("src", url).addEvent("load",
                function() {
                    obj.onLoad.call(obj, this)
                });
                return
            }
            if ($type(url) == "string") {
                if (param.ajaksable) {
                    W.page(url, param.ajaxoptions)
                } else {
                    new Ajax(url, param.ajaxoptions).request()
                }
            } else {
                try {
                    if($type(param.html) == "string")
                        this.dialog_body.empty().setHTML(param.html)
                } catch(i) {
                    this.dialog_body.setHTML("内容加载失败.!")
                }
                this.onLoad.call(this)
            }
        },
        popup: function(url, param) {
            if (param.modal || param.singlon) {
                MODALPANEL.show()
            }
            $("loadMask").amongTo(window).show();
            this.fireEvent("onShow", this);
            this.initContent(url, param)
        },
        show: function() {
            this.setDialog_bodySize();
            $("loadMask").hide();
            var ds = this.currentRegionDialogs;
            var ln = ds ? ds.length: 0;
            if (ln && ln > 0) {
                //对于多个窗口，show时对位置进行偏移，2639行mootools自带的兼容性方法setPosition
                this.dialog.position( $H(ds[ln - 1].getPosition()).map(function(v) {return v += 20}) ).setOpacity(1)
            } else {
                this.dialog.amongTo(window)
            }
            this.fireEvent("onLoad", this)
        },
        close: function() {
            try {
                this.fireEvent("onClose", this.dialog)
            } catch(e) {}
            this.dialog.style.display = "none";
            if (window.ie) {
                $ES("iframe", this.dialog_body).remove()
            }
            this.dialog.empty().remove();
            $("dialogdragghost_" + this.UID) ? $("dialogdragghost_" + this.UID).remove() : "";
            if (this.currentRegionDialogs.length > 0) {
                return false
            }
            MODALPANEL.hide();
            return "nodialog"
        },
        hide: function() {
            this.fireEvent("onHide");
            this.close.call(this)
        },
        setDialog_bodySize: function() {
            this.dialog_body.setStyles({
                //根据options选项设置dialog正文体的高度
                //这里暂时屏蔽高度选项设置，因为在现有操作模式下，很多页面本身高度很小。
                //但是在初始化时又必须将dialog设置为visibility:hidden，否则body部分的实际宽度就是0。从而导致出现滚动条而出现跳跃感。
                height: this.options.height - this.dialog_head.getSize().size.y - this.options.dialogBoxWidth * 2,
                //设置正文体宽度
                width: this.options.width - this.options.dialogBoxWidth * 2
            });
            this.setDialogWidth()
        },
        setDialogWidth: function() {
            //设置dialog宽度
            this.dialog.setStyle("width", this.dialog_body.getSize().size.x + this.options.dialogBoxWidth * 2)
        },
        dragDialog: function() {
            var o = this.dialog;
            var mDiv = new Element("div", {
                id: "dialogdragghost_" + this.UID
            });
            mDiv.setStyles({
                position: "absolute",
                border: "2px #555599 dashed",
                cursor: "move",
                background: "#E7EFF8",
                display: "none",
                opacity: 0.3,
                zIndex: 65535
            }).inject(document.body);
            
            //注意options选项添加了一个load事件，但是却是在这里初始化的
            this.addEvent("load",
            function(f) {
                mDiv.setStyles(o.getCis())
            });
            new Drag(mDiv, {
                handle: this.dialog_head,
                limit: {
                    x: [0, window.getSize().x],
                    y: [0, window.getSize().y]
                },
                onStart: function() {
                    mDiv.setStyles(o.getCis());
                    mDiv.show()
                },
                onComplete: function() {
                    var p = mDiv.getPosition();
                    o.setStyles({
                        top: p.y,
                        left: p.x
                    });
                    mDiv.hide()
                }
            })
        }
    })
})();