﻿
(function ($) {
    var ie6 = $.browser.msie && parseInt($.browser.version) === 6 && typeof window['XMLHttpRequest'] !== 'object',
		ie7 = $.browser.msie && parseInt($.browser.version) === 7,
        w={};

    $.fn.customBox = function (options) {
        $.customBox.impl.init(this, options);
    };

    $.customBox = function (data, options) {
        $.customBox.impl.init(data, options);
    };

    $.customBox.dispose = function () {
		$.customBox.impl.dispose();
	};

    $.customBox.defaults = {
        appendTo: "body",
        modal: true,
        hasTitle: true,//是否显示为模式窗口
        hasCloseIcon: true,
        hasOkBtn: true,
        hasCancleBtn: true,
        opacity: 50,
        zIndex:10000,
        position: null,
        closeHTML:"<div>&nbsp;</div>",
        title: "",
        content: "提示内容",
        okTxt: "确定",
        cancelTxt: "取消",
        overlayCss: { background:'#000'},
        containerCss:{},
        overlayId: "customBox_overlay",
        overlayClass: "customBox_overlay",
        containerId: "customBox",
        containerClass: "customBox",
        titleClass: "customBox_title",
        titleBarClass:"customBox_titleBar",
        closeIconClass: "customBox_close",
        bodyClass: "customBox_body",
        contentClass: "customBox_content",
        btnsClass: "customBox_btns",
        okClass: "customBox_btn_ok",
        cancelClass: "customBox_btn_cancel",
        persist:true,//使用原内容，修改后替换，并不克隆，仅用于已存在内容
        onShow: null,
        onClose: null,
        onOk: null,//定义确定事件
        onCancel: null//定义取消事件
    };

    $.customBox.impl = {
        //保存节点元素
        d: {},
        //初始化
        init: function (data, options) {
            var s = this;
           
            var o2={};
            if(typeof options!='undefined' && options.type)
            {
                switch(options.type)
                {
                    case 'alert':
                        o2={hasTitle:true,hasCloseIcon:true,hasOkBtn:true,hasCancleBtn:false};
                        break;
                    case 'confirm':
                        o2={hasTitle:true,hasCloseIcon:true,hasOkBtn:true,hasCancleBtn:true};
                        break;
                    case 'alert-timeOut':
                        o2={hasTitle:false,hasCloseIcon:false,hasOkBtn:false,hasCancleBtn:false,onShow:function(args){setTimeout(function(){$.customBox.dispose();},500);}};
                        break;
                    case 'alert-close':
                        o2={hasTitle:false,hasCloseIcon:true,hasOkBtn:false,hasCancleBtn:false};
                        break;
                }
            }
            s.o = $.extend({}, $.customBox.defaults,o2, options);

            if (typeof data === 'object') {
                data = data instanceof jQuery ? data : $(data);
                s.d.placeholder = false;
				if (data.parent().parent().size() > 0) {
					data.before($('<span></span>').attr('id', 'customBox-placeholder').css({display: 'none'}));
					s.d.placeholder = true;
					s.display = data.css('display');

					//persist为false则克隆
					if (!s.o.persist) {
						s.d.orig = data.clone(true);
					}
				}
            }
            else if (typeof data === 'string' || typeof data === 'number') {
                data = $('<div></div>').html(data);
            }
            else {
                alert('错误：数据类型不正确- ' + typeof data);
                return s;
            }
            s.create(data);
            s.show();
            return s;
        },
        //创建
        create: function (data) {
            var s = this;
            w = s.getDimensions();

            //覆盖层
            if(s.o.modal)
            {
                s.d.overlay = $('<div>&nbsp;</div>').attr('id', s.o.overlayId).addClass(s.o.overlayClass)
				    .css($.extend(s.o.overlayCss, {
					    display: 'none',
                        opacity: s.o.opacity / 100,
					    height: s.o.modal ? w.height : 0,
					    width: s.o.modal ? w.width : 0,
					    position: ie6?'absolute':'fixed',
					    left: 0,
					    top: 0,
                        zIndex:s.o.zIndex+1
				    }))
				    .appendTo(s.o.appendTo);
            }

            //外框
            s.d.container= $("<div/>").attr("id", s.o.containerId).addClass(s.o.containerClass)
            .css($.extend(s.o.containerCss,{ 
                display: 'none',
                zIndex:s.o.zIndex+2,
                position: ie6?'absolute':'fixed'//IE6使用绝对定位，其它浏览器使用相对浏览器定位
            }));

            //标题
            if(s.o.hasTitle)
            {
                s.d.titleBar = $("<div/>").addClass(s.o.titleBarClass);
            }

            //关闭按钮
            if (s.o.hasCloseIcon) {
                s.d.closeIcon = $(s.o.closeHTML).addClass(s.o.closeIconClass);
                s.d.closeIcon.click(function () {
                    s.close();
                });
            }

            if(s.o.hasTitle)
            {
                s.d.title=$("<span/>").addClass(s.o.titleClass).append(s.o.title);
                s.d.titleBar.append(s.d.title);
                if (s.o.hasCloseIcon)s.d.titleBar.append(s.d.closeIcon);
                s.d.container.append(s.d.titleBar);
            }else if (s.o.hasCloseIcon)
            {
                s.d.container.append(s.d.closeIcon);
            }

            //主体
            s.d.body = $("<div/>").addClass(s.o.bodyClass);

            //内容
            s.d.data=data;
            s.d.content = $("<div/>").addClass(s.o.contentClass).append(s.d.data);
            s.d.body.append(s.d.content);

            //按钮
            if (s.o.hasOkBtn || s.o.hasCancleBtn) {
                s.d.btns = $("<div/>").addClass(s.o.btnsClass);
                if (s.o.hasOkBtn) {
                    s.d.okBtn = $("<input type=\"button\"/>").addClass(s.o.okClass).val(s.o.okTxt);
                    s.d.okBtn.click(function () {
                        s.ok();
                    });
                    s.d.btns.append(s.d.okBtn);
                }

                if (s.o.hasCancleBtn) {
                    s.d.cancelBtn = $("<input type=\"button\"/>").addClass(s.o.cancelClass).val(s.o.cancelTxt);
                    s.d.cancelBtn.click(function () {
                        s.cancel();
                    });
                    s.d.btns.append("&nbsp;&nbsp;&nbsp;&nbsp;").append(s.d.cancelBtn);
                }

                s.d.body.append(s.d.btns);
            }
            s.d.container.append(s.d.body);
            $(s.o.appendTo).append(s.d.container);
        },
        show:function(){
           var s = this;
           if($.isFunction(s.o.onShow))
           {
                s.o.onShow.apply(s, [s.d]);
           }
           if(s.o.modal)s.d.overlay.show();
		   s.d.data.show();
	       s.d.container.show();
           s.setPosition();

           if (ie6) {
                //这个一定要放到scroll的外面，否则出BUG
                var w_t = $(window).scrollTop();
                //IE6中offset().top包括scrollTop
                var o_t = s.d.container.offset().top-w_t;     

                $(window).bind("scroll",function () {
                    if(typeof s.d.container!='undefined' && s.d.container!=null)
                    {
                        w_t = $(window).scrollTop();
                        var top = o_t + w_t + "px";
                        s.d.container.css({ top: top, bottom: "auto" });
                    }
                });
            }
        },
        close:function(){
           var s = this;
           if($.isFunction(s.o.onClose))
           {
                s.o.onClose.apply(s, [s.d]);
           }
           s.dispose();
        },
        ok:function(){
            var s = this;
            if($.isFunction(s.o.onOk))
            {
                //加上次判断，可在点击确定时跳出
                if(!s.o.onOk.apply(s, [s.d]))
                {
                    return false;
                }
            }
            s.dispose();
            return true;
        },
        cancel:function(){
            var s = this;
            if($.isFunction(s.o.onCancel))
            {
                s.o.onCancel.apply(s, [s.d]);
            }
           s.dispose();
           return false;
        },
        dispose:function(){
           var s = this;
           if (s.d.placeholder) {
				var ph = $('#customBox-placeholder');
				if (s.o.persist) {
					//还原内容区域
					ph.replaceWith(s.d.data.css('display', s.display));
				}
				else {
					//删除克隆内容区域
					s.d.data.hide().remove();
					ph.replaceWith(s.d.orig);
				}
			}
			else {
				s.d.data.hide().remove();
			}

           if(s.o.modal)s.d.overlay.hide().remove();
	       s.d.container.hide().remove();
           s.d={};  
        },
        //获取页面文档整体大小
        getDimensions:function () {
			    var el = $(window);

			    // fix a jQuery/Opera bug with determining the window height
			    var h = $.browser.opera && $.browser.version > '9.5' && $.fn.jquery < '1.3'
						    || $.browser.opera && $.browser.version < '9.5' && $.fn.jquery > '1.2.6'
				    ? el[0].innerHeight : $(document).height();

			    return {height:h,width:el.width()};
	    },
        //设置坐标为居中显示
        setPosition:function(){
            var s = this, top, left,
                d=$(document),
                dw=$(window),
                x1=d.scrollLeft(),
                y1=d.scrollTop();
                            
            if(s.o.position==null)
            {
                var w1=dw.width(),
                h1=dw.height(),
                w=s.d.container.outerWidth(),
                h=s.d.container.outerHeight();
				top = ((h1-h)/2)+(ie6?y1:0),//IE6使用绝对定位须要加上scrollTop
				left = ((w1-w)/2)+(ie6?x1:0);
            }else
            {
               top=s.o.position.top+(ie6?y1:0);
               left=s.o.position.left+(ie6?x1:0);    
            }
            s.d.container.css({left: left, top: top}); 
       }
    };
})(jQuery);
