/*
 * xBox - jQuery Plugin
 * Version: 1.0.0 (07/12/2010)
 */
 (function ($) {
     var ie6 = !$.support.opacity && !window.XMLHttpRequest; //判断是否IE6
     var DialogDiv = "xBoxDiv_"; //弹出层前缀名
     var DialogBg = DialogDiv + "Bg_"; //背景层前缀名
     var DialogiFrame = DialogDiv + "iFrame_"; //iFrame前缀名
     var topWin = window.top; //得到主窗口，即最顶端的窗口

     $._Array = []; //弹窗列表
     $.AlertNo = 0; //弹窗计数器
     $.baseZ = 1000; //背景层数

     $.xBox = function (opts) { install(topWin, opts); };
     $.unxBox = function (opts) { remove(topWin, opts); };
     $.alert = function (msg, type, func, w, h) { Alert(msg, type, w, h, func) };
     $.confirm = function (msg, okfunc, cancelfunc, w, h) { Confirm(msg, okfunc, cancelfunc, w, h); };
     $.submitbg = function (o) { SubmitBg(o) };

     //初始化
     $.xBox.defaults = {
         id: "id", //弹出窗口的id
         title: "提示窗口",   //弹出窗口标题
         message: "",   //消息内容
         iframeSrc: "", //框架Src
         width: 400, //初始化宽度
         height: 300, //初始化高度
         Top: 0, //上边位置
         Left: 0, //左边位置
         RightBottom: false, //右下角漂浮
         type: "", //类型
         centerX: true, //横向居中
         centerY: true, //垂直居中
         autoClose: 0, //自动关闭的时间, 0则不会自动关闭
         onOK: null, //确定按钮执行事件
         onClose: null, // 关闭时执行的事件
         showOverlay: true, //是否遮罩
         fadeIn: 200,  //背景渐变载入的时间，毫秒
         fadeOut: 400, //背景渐变消失的时间，毫秒
         ShowTopTitle: true, //是否显示标题
         ShowButtonRow: true //是否显示按钮
     };

     //载入弹窗层
     function install(el, opts) {
         opts = $.extend({}, $.xBox.defaults, opts || {}); //合并参数
         if (opts.id == "id") opts.id = opts.id + "_" + $.AlertNo++; //这里加个判断，可以接受用户传递的id参数，这样同一个弹出窗口只需要创建一次就ok了
         var doc = el.document;
         var view = get_viewport(el);
         //添加背景层
         if (opts.showOverlay) {
             var bgdiv = $("#" + DialogBg + opts.id, doc);
             if (!bgdiv.length > 0) {
                 bgdiv = $("<div class=\"xboxbg\"></div>");
                 bgdiv.attr("id", DialogBg + opts.id);
                 bgdiv.css({ "width": view[4] + "px", "height": view[5] + "px", "z-index": $.baseZ++ });
                 bgdiv.hide();
                 //IE6
                 if (ie6) {
                     var bgiframe = $("<iframe class=\"xframe\"></iframe>");
                     bgiframe.appendTo(bgdiv);
                 }
                 bgdiv.appendTo($(doc.body));
                 bgdiv.animate({ "opacity": "0.6" }).show();
             }
         }
         //添加弹出层
         var div = $("#" + DialogDiv + opts.id, doc);
         if (!div.length > 0) {
             var dh = opts.height + 106;
             div = $("<div></div>");
             div.attr("id", DialogDiv + opts.id).css({ "z-index": $.baseZ++, "margin": "0px", "padding": "0px" }).hide().appendTo($(doc.body));
             var divhtml = "<div class=\"xbox\" style=\"width:" + opts.width + "px;\">";
             if (opts.ShowTopTitle) {
                 //title=\"Esc关闭\"";
                 divhtml = divhtml + "<div class=\"tbg\"><div class=\"title\"><span>" + opts.title + "<a href=\"javascript:void(0);\" onclick=\"$('#ButtonCancel_" + opts.id + "').click();\" ><!-- 关闭 --></a></span></div></div>";
             }
             divhtml = divhtml + "<div class=\"blue_m_cb\">";
             divhtml = divhtml + "<div class=\"blue_m_c\" style=\"height: " + opts.height + "px;\"></div>";
             divhtml = divhtml + "<div class=\"blue_m_b\"";
             if (!opts.ShowButtonRow) {
                 divhtml = divhtml + " style=\"display:none;\"";
             }
             else {
                 dh = dh + 30;
             }
             divhtml = divhtml + "><input id=\"ButtonOK_" + opts.id + "\" type=\"button\" value=\"确 定\" /><input  id=\"ButtonCancel_" + opts.id + "\" type=\"button\" value=\"取 消\" /></div>";
             divhtml = divhtml + "</div>";
             divhtml = divhtml + "</div>";
             var divh = $(divhtml);
             if (opts.type == "alerto") {
                 $(".blue_m_c", divh).addClass("blue_m_o").html(opts.message);
             }
             else if (opts.type == "alertw") {
                 $(".blue_m_c", divh).addClass("blue_m_w").html(opts.message);
             }
             else if (opts.type == "loading") {
                 $(".tbg", divh).hide();
                 $(".blue_m_b", divh).hide();
                 $(".blue_m_c", divh).addClass("blue_m_j").html(opts.message);
                 dh = dh - 26;
             }
             else {
                 if (opts.iframeSrc != "") {
                     dh = dh - 100;
                     $(".blue_m_c", divh).addClass("blue_m_ci").addClass("blue_m_l").html("<iframe src='" + opts.iframeSrc + "' id='" + DialogiFrame + opts.id + "' allowTransparency='true' width='" + (opts.width - 2) + "' height='" + opts.height + "' frameborder='0' style=\"background-color: #transparent; border:none;\">");
                 }
                 else {
                     $(".blue_m_c", divh).addClass("blue_m_i").html(opts.message);
                 }
             }
             if (opts.onOK) $("#ButtonOK_" + opts.id, divh).bind("click", function () { opts.onOK(); });
             $("#ButtonCancel_" + opts.id, divh).bind("click", function () { $.unxBox({ id: "" + opts.id + "" }); });
             if (opts.onClose) $("#ButtonCancel_" + opts.id, divh).bind("click", function () { opts.onClose(); });
             divh.appendTo(div);
             if (opts.RightBottom) {
                 $(".blue_m_b", divh).hide();
                 $(".blue_m_c", divh).hide();
                 var rdiv = $(".blue_m_cb", divh);
                 $("<div class=\"rbdiv\">" + opts.message + "</div>").appendTo(rdiv);
                 var h = ((opts.message.split('<br />').length) * 18) + 68;
                 if (ie6) {
                     div.css({ "position": "absolute" });
                     div.get(0).style.setExpression('top', "((document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop )- " + h + ") + 'px'");
                     div.get(0).style.setExpression('left', "(-" + opts.width + " + (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft )) + 'px'");
                 }
                 else {
                     div.css({ "position": "fixed", "bottom": "0px", "right": "0px" });
                 }
             }
             else {
                 var dw = opts.width / 2;
                 dh = dh / 2;
                 if (ie6) {
                     div.css({ "position": "absolute" });
                     div.get(0).style.setExpression('top', "(-" + dh + " + (document.documentElement.clientHeight ? document.documentElement.clientHeight/2 : document.body.clientHeight/2 ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop )) + 'px'");
                     div.get(0).style.setExpression('left', "(-" + dw + " + (document.documentElement.clientWidth ? document.documentElement.clientWidth/2 : document.body.clientWidth/2 ) + ( ignoreMe = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft )) + 'px'");
                 }
                 else {
                     div.css({ "position": "fixed", "left": "50%", "top": "50%", "margin-left": "-" + dw + "px", "margin-top": "-" + dh + "px" });
                 }
             }
             div.slideDown('slow');
             $._Array.push(opts.id);
             //             if (opts.ShowTopTitle) bindesc(opts.id);
         }
     };

     //对话框
     function Alert(msg, type, w, h, func) {
         var id = "Alert_" + $.AlertNo++; //设置弹出窗口ID
         var wh = w ? w : 400;
         var hh = h ? h : 40;
         var t = "";
         switch (type) {
             case 1:
                 t = "alerto";
                 break;
             case 0:
                 t = "alertw";
                 break;
         }
         var opts = { id: id, width: wh, height: hh, title: '系统提示', type: t, message: msg };
         if (func) opts = $.extend({ onClose: func }, opts); //合并参数
         install(topWin, opts);
         bindSpace(id);
         var alertdiv = $("#" + DialogDiv + id, topWin.document);
         alertdiv.find("input[id^='ButtonOK_']").hide(); //^匹配以ButtonCancel_开始的属
         alertdiv.find("input[id^='ButtonCancel_']").val("确定");
     };

     //确认对话框
     function Confirm(msg, okfunc, cancelfunc, w, h) {
         var id = "Confirm_" + $.AlertNo++; //设置弹出窗口ID
         okf = function () {
             $.unxBox({ id: id });
             if (okfunc) {
                 okfunc();
             }
         }
         var opts = { id: id, width: w ? w : 400, height: h ? h : 40, title: '系统提示', message: msg, onOK: okf };
         if (cancelfunc) opts = $.extend({ onClose: cancelfunc }, opts); //合并参数
         install(topWin, opts);
     };

     //背景框
     function SubmitBg(o) {
         var id = "SubmitBg";
         var opts = { id: id, type: 'loading', height: 40, message: '数据处理中，请稍后...' };
         if (o == 1) {
             install(topWin, opts);
         }
         else {
             remove(topWin, opts);
         }
     };

     //移除弹窗层
     function remove(el, opts) {
         opts = $.extend({}, $.xBox.defaults, opts || {}); //合并参数
         var doc = el.document.body;
         var div = $("#" + DialogDiv + opts.id, doc);
         div.remove();
         $("#" + DialogBg + opts.id, doc).fadeOut("fast", function () { $(this).remove(); });
         ArrayRemove(opts.id);
         if ($._Array.length == 0) {
             //复位参数
             $._Array = [];
             $.AlertNo = 0;
             $.baseZ = 1000;
         }
     };

     //删除数组中的元素
     function ArrayRemove(s) {
         for (var i = 0; i < $._Array.length; i++) {
             if (s == $._Array[i]) {
                 $._Array.splice(i, 1);
             }
         }
     };

     //绑定ESC
     function bindesc(id) {
         var events = 'keydown.fb';
         var doc = $("body", topWin.document);

         //当绑定事件前，先释放，避免多重绑定！
         doc.unbind(events, handler).bind(events, handler);
         try {
             var iFrame = $("#" + DialogiFrame + id, topWin.document.body).contents();
             iFrame.bind(events, handler);
         }
         catch (err) { }
         doc.focus();
     };
     function handler(e) {
         if (e.keyCode && e.keyCode == 27) {
             e.preventDefault();
             if (topWin.$._Array.length > 0) {
                 remove(topWin, { id: topWin.$._Array[topWin.$._Array.length - 1] });
             }
         }
     };
     //绑定空格
     function bindSpace(id) {
         var events = 'keydown.fb';
         var doc = $("body", topWin.document);

         //当绑定事件前，先释放，避免多重绑定！
         doc.unbind(events, handlerSpace).bind(events, handlerSpace);
         try {
             var iFrame = $("#" + DialogiFrame + id, topWin.document.body).contents();
             iFrame.bind(events, handlerSpace);
         }
         catch (err) { }
         doc.focus();
     };

     function handlerSpace(e) {
         if (e.keyCode) {
             if (e.keyCode == 32 || e.keyCode == 13) {
                 e.preventDefault();
                 var alertdiv = $("#" + DialogDiv + topWin.$._Array[topWin.$._Array.length - 1], topWin.document);
                 if (alertdiv.length > 0) {
                     alertdiv.find("input[id^='ButtonCancel_']").click();
                 }
                 $("body", topWin.document).unbind('keydown.fb', handlerSpace);
             }
         }
     }

     //获取页面规格
     get_viewport = function (el) {
         //计算窗口的高宽和滚动条的位置,确保显示在屏幕正中间
         var cw = el.document.compatMode == "BackCompat" ? el.document.body.clientWidth : el.document.documentElement.clientWidth;
         var ch = el.document.compatMode == "BackCompat" ? el.document.body.clientHeight : el.document.documentElement.clientHeight;
         var st = Math.max(el.document.documentElement.scrollTop, el.document.body.scrollTop); //考虑滚动的情况
         var sl = Math.max(el.document.documentElement.scrollLeft, el.document.body.scrollLeft);
         var sw = Math.max(el.document.documentElement.scrollWidth, el.document.body.scrollWidth);
         var sh = Math.max(el.document.documentElement.scrollHeight, el.document.body.scrollHeight);
         sw = Math.max(sw, cw);
         sh = Math.max(sh, ch);
         return [cw, ch, st, sl, sw, sh];
     };
 })(jQuery);
