


(function($) {

    $.alerts = {

        verticalOffset: 0,
        horizontalOffset: 0,
        repositionOnResize: true,
        overlayOpacity: 0.2,
        overlayColor: '#000',
        draggable: true,
        okButton: '&nbsp;确定&nbsp;',
        cancelButton: '&nbsp;取消&nbsp;',
        dialogClass: null,
        defaultWidth: 340,
        visible: false,
        flashObj: null,
        popup: 0,
        zIndex: 9999,
        title: "",
        isIE6: $.browser.msie && parseInt($.browser.version) <= 6,



        alert: function(message, title, callback) {
            if (title == null) title = 'Alert';
            this.visible = false; this.title = "alert";
            $.alerts._show(title, message, null, 'alert', function(result) {
                if (callback) callback(result);
            });
        },

        confirm: function(message, title, callback) {
            if (title == null) title = 'Confirm';
            this.visible = false; this.title = "confirm";
            $.alerts._show(title, message, null, 'confirm', callback);
        },

        prompt: function(message, value, title, callback) {
            if (title == null) title = 'Prompt';
            this.visible = false; this.title = "prompt";
            $.alerts._show(title, message, value, 'prompt', function(result) {
                if (callback) callback(result);
            });
        },
        html: function(html, title, obj, callback) {
            if (title == null) title == "Html";
            this.title = "html";
            if (!obj || obj != "") { this.visible = false; }
            $.alerts._show(title, html, null, "html")
            if (typeof obj == "string") {
                this.flashObj = $("#" + obj)
            }
            else this.flashObj = obj
            if (obj) {
                $.alerts._flash(this.flashObj, callback)
            }
        },
        clear: function() {
            $("div.popup_bg").remove();
            $("div.popup_container").remove();
            $("div.popup_overlay").remove()
            $("div.uccontain").remove()
        },

        close_flash: function(flashBox) {
            $.alerts._close_flash(flashBox)
        },


        reposition: function() {
            $.alerts._reposition();
        },


        _show: function(title, msg, value, type, callback) {
            this.popup++
            this.zIndex += 10

            //$.alerts._hide();
            $.alerts._overlay('show');

            $("body").append(
             '<div id="popup_bg_' + this.popup + '" class="popup_bg"></div>',
			  '<div id="popup_container_' + this.popup + '" class="popup_container" style="display:none">' +
			    '<div id="popup_title_' + this.popup + '" class="popup_title"></div><div id="btnClose_' + this.popup + '"  title="关闭" class="btnClose" ></div>' +
			    '<div id="popup_content_' + this.popup + '" class="popup_content">' +
			      '<div id="popup_message_' + this.popup + '" class="popup_message"></div>' +
				'</div>' +
			  '</div>');
            if ($.alerts.dialogClass) $("#popup_container_" + this.popup).addClass($.alerts.dialogClass);

            // IE6 Fix
            var pos = ($.browser.msie && parseInt($.browser.version) <= 6) ? 'absolute' : 'fixed';
            $("#popup_container_" + this.popup).css({
                position: pos,
                zIndex: this.zIndex + 6,
                padding: 0,
                margin: 0,
                display: this.visible ? "block" : "none"
            });
            $("#popup_bg_" + this.popup).css({
                position: pos,
                zIndex: this.zIndex + 3,
                padding: 0,
                margin: 0,
                display: this.visible ? "block" : "none"
            });
            $("#popup_content_" + this.popup).addClass(type);
            var contenObj = $("#popup_message_" + this.popup).html(msg.replace(/\n/g, '<br />'));
            switch (type) {
                case 'alert':
                    $("#popup_message_" + this.popup).after('<div class="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok_' + this.popup + '" /></div>');
                    $("#popup_ok_" + this.popup).click(function() {
                        $.alerts._hide();
                        callback(true);
                    }).focus().keypress(function(e) {
                        if (e.keyCode == 13 || e.keyCode == 27) $(this).trigger('click');
                    });
                    break;
                case 'confirm':
                    $("#popup_message_" + this.popup).after('<div class="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok_' + this.popup + '" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel_' + this.popup + '" /></div>');
                    $("#popup_ok_" + this.popup).click(function() {
                        $.alerts._hide();
                        if (callback) callback(true, contenObj);
                    });
                    $("#popup_cancel_" + this.popup).click(function() {
                        $.alerts._hide();
                        if (callback) callback(false, 2);
                    });
                    $("#popup_ok_" + this.popup).focus();
                    $('#popup_ok_' + this.popup + ', #popup_cancel_' + this.popup).keypress(function(e) {
                        if (e.keyCode == 13) $(this).trigger('click');
                        if (e.keyCode == 27) $(this).trigger('click');
                    });
                    break;
                case 'prompt':
                    $("#popup_message_" + this.popup).append('<br /><input type="text" size="30" id="popup_prompt_' + this.popup + '" />').after('<div class="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok_' + this.popup + '" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel_' + this.popup + '" /></div>');
                    $("#popup_prompt_" + this.popup).width($("#popup_message_" + this.popup).width());
                    $("#popup_ok_" + this.popup).click(function() {
                        var val = $("#popup_prompt_" + this.popup).val();
                        $.alerts._hide();
                        if (callback) callback(val);
                    });
                    $("#popup_cancel_" + this.popup).click(function() {
                        $.alerts._hide();
                        if (callback) callback(null);
                    });
                    $('#popup_prompt_' + this.popup + ', #popup_ok_' + this.popup + ', #popup_cancel_' + this.popup).keypress(function(e) {
                        if (e.keyCode == 13) $("#popup_ok_" + this.popup).trigger('click');
                        if (e.keyCode == 27) $("#popup_cancel_" + this.popup).trigger('click');
                    });
                    if (value) $("#popup_prompt_" + this.popup).val(value);
                    $("#popup_prompt_" + this.popup).focus().select();
                    break;
                case "html": $("#popup_content_" + this.popup).html(msg);
                    break;
            };
            // Make draggable
            if (type != "html") {
                $("#btnClose_" + this.popup).click(function() {
                    $.alerts._hide();
                    callback(false);
                })
            }
            // Make draggable
            var popup_container = $("#popup_container_" + this.popup);
            if (!this.isIE6) {
                this.defaultWidth = popup_container.outerWidth();
            }
            $("#popup_title_" + this.popup).html(title).css("width", this.defaultWidth);
            if ($.alerts.draggable) {
                try {
                    $.alerts._drag("#popup_container_" + this.popup, "#popup_bg_" + this.popup, "#popup_title_" + this.popup, false)
                    $("#popup_title_" + this.popup).css({ cursor: 'move' });
                } catch (e) { }
            }

            $.alerts._reposition();
            $.alerts._maintainPosition(true)
        },
        _drag: function dragmove(moveEl, moveBg, handleEl, isOpa) {
            var _move = false
            var _x, _y; //鼠标离控件左上角的相对位置
            var handleEl = $(handleEl)
            var moveEl = $(moveEl)
            var moveBg = $(moveBg)
            var bgOffset = 4 //透明背景层相对内容层的偏移量
            var transparency = 0.3
            var layout
            var mouseup = function() {
                _move = false
                $(this).unbind("mousemove", mousemove)
                $(this).unbind("mouseup", mouseup)
                moveEl.fadeTo("fast", 1); //点击后开始拖动并透明显示
                moveBg.fadeTo("fast", 0.3)
                _x = moveBg.offset().left
                _y = moveBg.offset().top

                layout.animate({ left: _x, top: _y }, 200, "linear", function() {
                    $(this).remove()
                })
            }
            var mousemove = function(e) {
                if (_move) {
                    var x = e.pageX - _x; //移动时根据鼠标位置计算控件左上角的绝对位置
                    var y = e.pageY - _y;
                    moveEl.css({ top: y, left: x }); //控件新位置\
                    moveBg.css({ top: y - bgOffset, left: x - bgOffset }); //控件新位置
                }
            }
            var event = function(e) {
                _move = true
                _x = e.pageX - parseInt(moveEl.css("left"));
                _y = e.pageY - parseInt(moveEl.css("top"));
                var w = moveEl.outerWidth() + bgOffset
                var h = moveEl.outerHeight() + bgOffset
                var m = 0
                if (isOpa) {
                    m = 300
                }
                moveEl.fadeTo(m, transparency); //点击后开始拖动并透明显示
                moveBg.fadeTo(m, transparency); //点击后开始拖动并透明显示

                $("body").append('<div id="layout" class="layout"></div>')
                layout = $("#layout")
                layout.css({ left: moveEl.offset().left - bgOffset, top: moveEl.offset().top - bgOffset, width: w, height: h, zIndex: moveEl.css("z-index") - 10 })
                $(document).mousemove(mousemove).mouseup(mouseup)
            }
            handleEl.mousedown(event)

        },

        _flash: function(flashObj, callback) {
            var popup_bg = $("#popup_bg_" + $.alerts.popup)
            var popup_overlay = $("#popup_overlay_" + $.alerts.popup)
            var popup_container = $("#popup_container_" + $.alerts.popup)
            var w = popup_bg.outerWidth();
            var h = popup_bg.outerHeight();
            var top = (($(window).height() / 2) - (h / 2)) + $.alerts.verticalOffset + $(document).scrollTop()
            var left = (($(window).width() / 2) - (w / 2)) + $.alerts.horizontalOffset;
            if (top < 0) top = 0;
            if (left < 0) left = 0;
            var flashBox
            $("body").append('<div id="flash_' + $.alerts.popup + '" class="flash"></div>');

            flashBox = $("#flash_" + $.alerts.popup)
            var fw = flashObj.outerWidth()
            var fh = flashObj.outerHeight()
            var fl = flashObj.offset().left
            var ft = flashObj.offset().top
            flashBox.html(popup_container.html())
            flashBox.css("z-index", $.alerts.zIndex + 9);
            flashBox.css({ left: fl, top: ft, width: fw, height: fh }).animate({ left: left, top: top, width: w, height: h }, 300, "swing", function() {
                $("#btnClose_" + $.alerts.popup).click(function() {
                    $.alerts._flash_return(flashObj, popup_container);
                })
                flashBox.remove()

                popup_overlay.css("display", "block")
                popup_container.show()
                popup_bg.show()
                if (callback) callback();
            })

        },
        _flash_return: function(flashObj, popup_container) {
            $("body").append('<div id="flash_' + $.alerts.popup + '" class="flash"></div>');
            var flashBox = $("#flash_" + $.alerts.popup)
            flashBox.css("z-index", $.alerts.zIndex + 9);
            var popup_bg = $("#popup_bg_" + $.alerts.popup)
            $.alerts._hide();
            var w = popup_bg.outerWidth()
            var h = popup_bg.outerHeight()
            var l = popup_bg.css("left")
            var t = parseFloat(popup_bg.css("top").replace("px", "")) + $(document).scrollTop()
            var fw = flashObj.outerWidth()
            var fh = flashObj.outerHeight()
            var fl = flashObj.offset().left
            var ft = flashObj.offset().top
            flashBox.html(popup_container.html())
            flashBox.css({ left: l, top: t, height: h, width: w }).show().animate({ left: fl, top: ft, width: fw, height: fh }, 250, "swing", function() {
                $(this).remove()
            })
        },
        _close_flash: function(flashObj) {
            var popup_container = $("#popup_container_" + $.alerts.popup)
            $.alerts._flash_return(flashObj, popup_container)
        },

        _hide: function() {
            $("#popup_container_" + this.popup).remove();
            $("#popup_bg_" + this.popup).remove()
            $.alerts._overlay('hide');
            $.alerts._maintainPosition(false);
            this.popup--
            this.zIndex -= 10
        },
        _overlay: function(status) {
            switch (status) {
                case 'show':
                    $.alerts._overlay('hide');
                    $("BODY").append('<div id="popup_overlay_' + this.popup + '" class=\"popup_overlay\"><iframe style=\"position:absolute;z-index:10010;width:100%;height:100%;_filter:alpha(opacity=0);opacity=0;border-style:none;background:Transparent!important;\"></iframe></div>');
                    $("#popup_overlay_" + this.popup).css({
                        position: 'absolute',
                        zIndex: this.zIndex,
                        top: '0px',
                        left: '0px',
                        width: '100%',
                        height: $(window).height(),
                        background: $.alerts.overlayColor,
                        opacity: $.alerts.overlayOpacity,
                        display: this.visible || $.alerts.title != "html" ? "block" : "none"
                    });
                    break;
                case 'hide':
                    $("#popup_overlay_" + this.popup).remove();
                    break;
            }
        },

        _reposition: function() {
            var popup_container = $("#popup_container_" + $.alerts.popup);
            var w = popup_container.outerWidth();
            var h = popup_container.outerHeight()
            var top = (($(window).height() / 2) - (h / 2)) + $.alerts.verticalOffset;
            var left = (($(window).width() / 2) - (w / 2)) + $.alerts.horizontalOffset;
            if (top < 0) top = 0;
            if (left < 0) left = 0;
            // IE6 fix
            if (this.isIE6) top = top + $(window).scrollTop();
            popup_container.css({
                top: top + 'px',
                left: left + 'px'
            });
            $("#popup_bg_" + $.alerts.popup).css({
                top: (top - 4) + 'px',
                left: (left - 4) + 'px',
                width: (w + 8) + 'px',
                height: (h + 8) + 'px'
            });
            if (!this.visible && this.title != "html") { $("#popup_bg_" + this.popup).show(); $("#popup_container_" + this.popup).show(); }
            $("#popup_overlay_" + $.alerts.popup).height($(document).height());
        },

        _maintainPosition: function(status) {
            if ($.alerts.repositionOnResize) {
                switch (status) {
                    case true:
                        $(window).bind('resize', $.alerts._reposition);
                        break;
                    case false:
                        $(window).unbind('resize', $.alerts._reposition);
                        break;
                }
            }
        }

    }

    jAlert = function(message, title, callback) {
        $.alerts.alert(message, title, callback);
    }

    jConfirm = function(message, title, callback) {
        $.alerts.confirm(message, title, callback);
    };

    jPrompt = function(message, value, title, callback) {
        $.alerts.prompt(message, value, title, obj, callback);
    };
    jHtml = function(html, title, obj, callback) {
        $.alerts.html(html, title, obj, callback)
    }
    jClear = function() {
        $.alerts.clear()
    }
    jClose_flash = function(flashBox) {
        $.alerts.close_flash(flashBox)
    }

    jResize = function() {
        $.alerts.reposition()
    }
})(jQuery);

