/*
* jBox 1.1 - a webpage UI dialog widget written in javascript on top of the jQuery library
* By Daniel Lin(http://www.aspstat.com)
* Copyright (c) 2007 Daniel Lin Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
* Last modify:2007-11-20
http://www.aspstat.com/jbox/demo.htm
*/
//Usage:jBox.open( boxID , contentType , content , title , windowStyles , ajaxOptions)
var jBox = {
    imgs: ['min.gif', 'close.gif', 'restore.gif', 'resize.gif', 'title.gif', 'jbox_button.gif', 'jbox_button_hover.gif'], //在css中设置
    minClass: 'jbtnMin',
    closeClass: 'jbtnClose',
    restoreClass: 'jbtnRestore',
    resizeClass: 'jbtnResize',
    boxes: [], minimizeorder: 0,
    defaultWidth: 320,
    defaultHeight: 160,
    findBoxIndex: function(id) {
        for (var i = 0; i < jBox.boxes.length; i++) {
            if (jBox.boxes[i].jBoxID == id) {
                return i;
            }
        }
        return null;
    },
    findBox: function(id) {
        for (var i = 0; i < jBox.boxes.length; i++) {
            if (jBox.boxes[i].jBoxID == id) {
                return jBox.boxes[i];
            }
        }
        return null;
    },
    _maxZIndex: 99999,
    ie: document.all && !window.opera,
    domBody: (document.compatMode == "CSS1Compat") ? document.documentElement : document.body,
    //scroll offset
    pageXYOffset: function() {
        return [(jBox.ie) ? jBox.domBody.scrollLeft : window.pageXOffset,
	        (jBox.ie) ? jBox.domBody.scrollTop : window.pageYOffset];
    },
    //visiable zone
    pageInnerSize: function() {
        if (!jBox.domBody) jBox.domBody = (document.compatMode == "CSS1Compat") ? document.documentElement : document.body;
        var domclientWidth = jBox.domBody && parseInt(jBox.domBody.clientWidth) || 100000;
        return [(jBox.ie) ? jBox.domBody.clientWidth : (/Safari/i.test(navigator.userAgent)) ? window.innerWidth : Math.min(domclientWidth, window.innerWidth - 16),
           (jBox.ie) ? jBox.domBody.clientHeight : window.innerHeight];
    },
    //max scroll width or max scrol offset+visiable zone
    pageSize: function() {
        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;
        if (self.innerHeight) {	// all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = windowWidth;
        } else {
            pageWidth = xScroll;
        }

        return new Array(pageWidth, pageHeight, windowWidth, windowHeight);
    },
    init: function(id) {
        var holder = $('#jBoxHolder');
        if (holder.length == 0) { holder = $('<div id="jBoxHolder"></div>'); $(document.body).append(holder); }
        var box = $('<div class="jBox" id="' + id + '"></div>').appendTo(holder);
        box.append('<div class="jBoxHandler">jBox<div class="jBoxControls"><span class="' + jBox.minClass + '" title="Minimize"></span><span class="' + jBox.closeClass + '" title="Close"></span></div></div>')
           .append('<div class="jBoxContent"></div>')
		   .append('<div class="jBoxButtons"></div>')
		   .append('<div class="jBoxStatus"><div class="' + jBox.resizeClass + '">&nbsp;</div></div>');
        box.css('zIndex', $('div.jBox').length + 99);
        //bind custom property with DOM
        box.handler = box.find('div.jBoxHandler'); box.controls = box.find('div.jBoxControls');
        box.content = box.find('div.jBoxContent'); box.status = box.find('div.jBoxStatus');
        box.buttons = box.find('div.jBoxButtons'); box.resize = box.find('div.' + jBox.resizeClass);
        box.buttonList = {};
        /*buttonList:  json 数据:	{ { text:"上一步",fn:"test",data:{} } ,{ text:"下一步",fn:"test",data:{} }  }
        fn (Function): 绑定到每个匹配元素的事件上面的处理函数 
        data (Object): (可选) 作为event.data属性值传递给事件对象的额外数据对象 
        */
        //bind custom method & event with DOM			
        box.open = function(type, source, title) { jBox.open(this, type, source, title); };
        box.load = function(type, source, title) { jBox.load(this, type, source, title); };
        box.close = function() { if (undefined != this.onClosed) { this.onClosed(); } return true; };
        box.show = function() { jBox.show(this); };
        box.hide = function() { jBox.hide(this); };
        box.isResize = function(bol) { jBox._isResize(this, bol); };
        box.hasScroll = function(bol) { jBox._hasScroll(this, bol); };
        box.setButtons = function() { jBox._setButtons(this); }
        box.setSize = function(w, h) { jBox.setSize(this, w, h); };
        box.moveTo = function(x, y) { jBox.moveTo(this, x, y); };
        box.jBoxID = id;
        jBox._maxZIndex++;
        if (box.jBoxID == "jBoxAlert" || box.jBoxID == "jBoxConfirm") {

            box.css('z-index', jBox._maxZIndex * 100); //始终保持在上
        }
        else {
            box.css('z-index', jBox._maxZIndex);
        }

        box.bringUp = function() {
            if (box.css('z-index') < jBox._maxZIndex) {
                jBox._maxZIndex++;
                box.css('z-index', jBox._maxZIndex);
            }
        };

        box.click(function() { var thisBox = jBox.findBox(this.id); if (thisBox) thisBox.bringUp(); });
        jBox.boxes[jBox.boxes.length] = box;
        return box;
    },
    open: function(id, type, source, title, attr, buttons, closeCallback) {
        function getValue(Name) {
            var config = new RegExp(Name + "=([^,]+)", "i");
            var val = "0";
            if (Name == "closeable" && !config.test(attr)) return 1; //若参数中没有,默认为显示
            try {
                if (config.test(attr)) {
                    if (RegExp.$1 && RegExp.$1.indexOf("%") != -1) //witdh=33%有%时出错
                        val = RegExp.$1;
                    else
                        val = eval('(' + RegExp.$1 + ')');
                }
            }
            catch (e) { val = RegExp.$1; }
            return val;
        }
        var box = jBox.findBox(id);
        //Find a jbox element has been created else create new element		
        if (null == box) {
            box = this.init(id);

            box.css("visibility", "visible"); box.css("display", "block"); box.content.css("display", "block");
            box.hasScroll(getValue("scrolling"));

            box.boxType = type; //自定义属性
            box.boxAttr = attr; //初始宽度		
            box.buttonList = buttons; // init buttons		
            box.setButtons();

            box.isModel = getValue("model");
            if (box.isModel) jBox.showModel();

            box.minimizable = getValue("minimizable");
            box.closeable = getValue("closeable");
            if (!box.minimizable) { box.controls.find('span[@title=Minimize]').remove() };
            if (!box.closeable) { box.controls.find('span[@title=Close]').hide(); }; //remove()};			
            if (getValue("draggable")) { box.handler.mousedown(function(e) { jBox.etarget = this; jBox.setupDrag(e); }); }
            box.isResize(getValue("resize"));
            if (box.resizeBool) { box.resize.mousedown(function(e) { jBox.etarget = this; jBox.setupDrag(e); }); }
            box.controls.click(function(e) { jBox.setupControls(e); });
            //box.controls.click( function(box){jBox.setupControls(box);} ); 
            var btnClose = box.controls.find('span[@title=Close]');
            if (typeof closeCallback == "function") { btnClose.bind("click", closeCallback); } //绑定关闭时回调函数
            btnClose.bind("click", function() { jBox._close(box); }); //绑定关闭时回调函数

            box.controls.find('span[@title=Minimize]').hover(function() { $(this).addClass("jbtnMinOver"); },
			    function() { $(this).removeClass("jbtnMinOver"); })
            box.controls.find('span[@title=Close]').hover(function() { $(this).addClass("jbtnCloseOver"); },
			    function() { $(this).removeClass("jbtnCloseOver"); })

            box.load(type, source, title);
            box.setSize(getValue(("width")), (getValue("height")));
            var xpos = getValue("center") ? "middle" : getValue("left");
            var ypos = getValue("center") ? "middle" : getValue("top");
            box.moveTo(xpos, ypos);
        }
        else {
            if (box.state == 'minimized') jBox.restore(box.controls.find('span[@title=Restore]').get(0), box);
            box.bringUp();
        }
        return box;
    },
    setContentHeight: function(box, type) {//当为inline或div类型时,根据box的尺寸来设置内容区的尺寸

    },
    load: function(box, type, source, title) {
        var type = type.toLowerCase();
        if (typeof title != 'undefined') box.handler.get(0).firstChild.nodeValue = title;
        if (title == '') {
            box.handler.css('backgroundColor', '#fff'); box.handler.css('padding', '0px'); /*box.content.css('padding','0px 10px');*/
        }
        if (type == "inline") {
            box.content.html(source);
            //box.content.height();
        }
        else if (type == "div") {
            var copy = $('#' + source).clone(); copy.attr('id', box.jBoxID + copy.attr('id')); //box.jBoxID
            copy.appendTo(box.content);
            copy.css('display', 'block');
        } else if (type == "iframe") {
            box.content.css('overflow', 'hidden');
            var ifrName = 'jb_iframe-' + box.jBoxID;
            if (box.content.children().length < 1 || box.content.children().get(0).tagName != "IFRAME") {
                box.content.iframe = $('<iframe src="" style="margin:0; padding:0; width:100%; height: 100%" frameborder="no" name="' + ifrName + '" class="jBoxIframe"></iframe>');
                box.content.html(box.content.iframe); ; //box.content.html('<iframe src="" style="margin:0; padding:0; width:100%; height: 100%" frameborder="no" name="'+ifrName+'" class="jBoxIframe"></iframe>');
            }

            //将数据以post方式提交给iframe
            if (typeof source == "string") {//url,get方式
                window.frames[ifrName].location.replace(source);
            }
            else if (typeof source == "object") {//json data: { url:"text.aspx",method:"post",data:{} },get或post方式

                var url = source["url"];
                var method = source["method"];
                //-----source是json对象----2008-05-12
                if (!url) {
                    jBox.alert("缺少参数!");
                    return;
                }
                if (!method) method = "get";
                if (method.toLowerCase() == "get") {//get
                    var query = "";
                    for (var key in source) {
                        if (key != "url" && key != "method") {
                            query += key + "=" + source[key] + "&";
                        }
                    }
                    if (query && query.length > 0) {
                        if (query.lastIndexOf("?") == -1)
                            query = "?" + query;
                        else
                            query = "&" + query;
                    }
                    window.frames[ifrName].location.replace(url + query);

                }
                else {//post方式
                    if ($("#jBoxFormPost").length == 0) {//把存放选择记录id列表的input移动到form内,以供post方式提交
                        $('body').eq(0).prepend('<form id="jBoxFormPost" name="jBoxFormPost" action="" method="post"></form>');
                    }
                    var jBoxFormPost = $("#jBoxFormPost").empty();
                    for (var key in source) {
                        if (key != "url" && key != "method") {
                            jBoxFormPost.append('<input  type="hidden" name="' + key + '" value="' + escape(source[key]) + '" />');
                        }
                    }
                    jBoxFormPost.attr("target", ifrName);
                    jBoxFormPost.attr("action", url);
                    jBoxFormPost.attr("method", "post");
                    jBoxFormPost.attr("target", ifrName);
                    jBoxFormPost.submit();
                    jBoxFormPost.focus();
                } //if(method.toLowerCase()=="get")
            } //if(typeof source == "string")					    
        } else if (type == "ajax") {
            box.content.html('loading...');
            $.ajax({ type: "GET", url: source,
                success: function(data) {
                    box.content.html(data);
                },
                error: function(r) {
                    box.content.html(r.responseText);
                }
            });
        }
        box.content.datatype = type;
    },

    _close: function(box) {
        //---box为object,即box对象
        //jBox.purge(box);//用这个会更慢
        box.empty();
        if ($.browser.msie) {
            CollectGarbage();
        }
        try { var closewinbol = box.close(); }
        catch (err) { var closewinbol = true; }
        finally {
            if (typeof closewinbol == "undefined") {
                alert("An error has occured somwhere inside your \"onclose\" event handler")
                var closewinbol = true
            }
        }
        if (closewinbol) {
            var index = jBox.findBoxIndex(box.jBoxID);
            delete jBox.boxes[index];
            for (var i = index; i < jBox.boxes.length; i++) {
                if ((i + 1) < jBox.boxes.length) {
                    jBox.boxes[i] = jBox.boxes[i + 1];
                }
            }
            if (jBox.boxes.length > 0) jBox.boxes.length--;
            box.remove(); //当jBox为iframe类型时,此句在jquery1.2.1.js中引起父页面无法获得焦点,文本框无法输入.而jquery1.2.6.js则需要过几秒才能获得焦点
            if (box.isModel) jBox.hideModel();
            //if(box.content.iframe)box.content.iframe=null;
            delete box.handler; delete box.content; delete box.buttons; delete box.buttonlist;
            delete box.resize; delete box.controls; delete box.status;
            if (box.state == 'minimized') {
                jBox.minimizeorder--;
                for (var i = 0; i < jBox.boxes.length; i++) {
                    if (jBox.boxes[i].state == 'minimized') {
                        if (jBox.boxes[i].minimizeorder > box.minimizeorder) {
                            jBox.boxes[i].minimizeorder--;
                            jBox._minimizeRedraw(jBox.boxes[i]);
                        }
                    }
                }
            }
            box = null;
            //try{CollectGarbage();}catch(e){}//有时报:没有权限
            // box[0].removeNode(true);
            //var p=box.parent()[0];
            //p.removechild(box[0]);
            //   box[0]=null;
            //delete box;
            //CollectGarbage();
        } //if (closewinbol)
        return closewinbol;
    },
    close: function(box, e) {/*????当iframe里面文档对象比较多时,关闭后,父窗口会不能即时获得焦点*/
        var paramType = typeof box;
        if (paramType == "string") {//---如果参数为string,则示为jbox的ID
            var boxID = box;
            switch (boxID.toLowerCase()) {
                case "confirm":
                case "jboxconfirm":
                    boxID = "jBoxConfirm";
                    break;
                case "alert":
                case "jboxalert":
                    boxID = "jBoxAlert";
                    break;
                case "progress":
                case "jboxprogress":
                    boxID = "jBoxProgress";
                    break;
            }
            var cunjBox = jBox.findBox(boxID);
            jBox.close(cunjBox);
            return;
        }
        else if (paramType == "undefined") {//---参数为空时,默认为关闭当前实例窗口,用于iframe中的关闭按钮调用jBox.close()关闭自己.
            //关闭iframe类型的窗口	
            if (window.frameElement && window.frameElement.parentNode && window.frameElement.parentNode.parentNode) {//从ifame中关闭上
                //$(window.frameElement).unbind();
                var cunjBox = window.parent.jBox.findBox(window.frameElement.parentNode.parentNode.id);
                if (cunjBox != null) window.parent.jBox.close(cunjBox);
                cunjBox = null;
                return;
            }
            else {//从jbox所在层上关闭上
                var e = window.event || arguments.callee.caller.arguments[0]; //获取event对象 ie || firefox
                var src = e.srcElement || e.target;
                var cunjBox = jBox.findBox(src.parentNode.parentNode.id);
                if (cunjBox != null) jBox.close(cunjBox);
                cunjBox = null;
                return;
            }
            return; //没有找到
        } else if (!box) {
            return;
        }
        else {//执行关闭按钮的单击事件
            box.controls.find('span[@title=Close]').click();
        }
    },

    show: function(box) {
        box.css('display', 'block');
        if (box.isModel) jBox.showModel();
    },
    hide: function(box) {
        box.css('display', 'none');
        if (box.isModel) jBox.hideModel();
    },
    purge: function(obj) {
        //清除元素及其子元素的所有事件句柄,obj可以是jquery对象或html对象
        if (!obj) return;
        if (obj.jquery) obj = obj[0];
        for (var name in obj.attributes) {
            if (typeof obj[name] == "function") obj[name] = null; //仅能释放在html绑定的事件.如: onclik="test1();"
        }
        $(obj).unbind(); //仅能释放jquery绑定的事件,如: $(obj).click(function(){ alert(1); });

        for (var i = 0; obj.childNodes && i < obj.childNodes.length; i++) {
            cur = obj.childNodes[i];
            if (cur.tagName && cur.tagName.toLowerCase() == "iframe") {
                var doc = cur.document.frames[cur.uniqueID].document;
                cur = (doc.compatMode == "CSS1Compat") ? doc.documentElement : doc.body;
            }
            if (cur.childNodes && cur.childNodes.length == 0)
                cur = null;
            else
                jBox.purge(cur);
        } //for
        if ($.browser.msie) {
            CollectGarbage();
        }
    },
    _hasScroll: function(box, bol) { box.content.css("overflow", (bol) ? "auto" : "hidden"); },
    _isResize: function(box, bol) { box.status.css("display", (bol) ? "block" : "none"); box.resizeBool = (bol) ? 1 : 0 },
    _setButtons: function(box) {
        var n = 0;
        box.buttons.empty(); //设置之前删除
        if (box.buttonList && box.buttonList.length > 0) {//新增自定义buttons------star---2008-05-07---------
            n = box.buttonList.length;
            for (var idx in box.buttonList) {
                var item = box.buttonList[idx];
                if (item["text"] && item["fn"]) {
                    var btn = $('<input value="button" type="button" class="buttonOut"  />');
                    btn.hover(hoverFunction(btn, 'add'), hoverFunction(btn, 'remove')); //修改jBox鼠标焦点位置--------ljm----2009-3-17----------

                    btn.val(item["text"]);

                    if (typeof item["fn"] == "string") {//单击按钮时执行的脚本块					
                        btn.bind("click", item["data"], eval(item["fn"]));
                    }
                    else if (typeof item["fn"] == "function") {//单击按钮时执行的函数					
                        btn.bind("click", item["data"], item["fn"]);
                    }
                    btn.appendTo(box.buttons);
                }
            } // for...in...		
        }
        box.buttons.css("display", (n > 0) ? "block" : "none");
        box.buttonsBool = n > 0 ? 1 : 0;
    },
    setSize: function(box, w, h) {
        //---box超过父窗口时，重设尺寸---
        var docW = $(document.body).attr("clientWidth"); //当box.boxType=="inline" || box.boxType=="div"
        var docH = $(document.body).attr("clientHeight");
        if (box.boxType == "iframe") {
            docW = $(window.parent.document.body).attr("clientWidth");
            docH = $(window.parent.document.body).attr("clientHeight");
        }
        if (w.toString().indexOf("%") == -1)
            boxW = w;
        else
            boxW = Math.floor((parseInt(w) * docW) * 0.01); //按百分比计算

        if (h.toString().indexOf("%") == -1)
            boxH = h;
        else
            boxH = Math.floor((parseInt(h) * docH) * 0.01); //按百分比计算
        //---小于默认值时,重设尺寸---

        if (boxW < jBox.defaultWidth) {
            if (box.jBoxID.toLowerCase().indexOf("tip") == -1) boxW = jBox.defaultWidth;
        }
        if (boxH < jBox.defaultHeight) {
            if (box.jBoxID.toLowerCase().indexOf("tip") == -1) boxH = jBox.defaultHeight;
        }
        box.width(boxW);
        box.height(boxH);
        //---设置内容区域尺寸---		
        var handlerH = box.find('div.jBoxHandler').get(0).offsetHeight;
        var buttonsH = box.find('div.jBoxButtons').get(0).offsetHeight;
        var statusH = box.find('div.jBoxStatus').get(0).offsetHeight; //当display:none时offsetHeight为undefined
        //if(!handlerH)handlerH=0;
        //if(!buttonsH)buttonsH=0;
        //if(!statusH)statusH=0;
        var contentW = boxW - 10;
        var contentH = boxH - (handlerH + buttonsH + statusH + 10);
        box.content.width(contentW);
        box.content.height(contentH);

    },
    moveTo: function(box, x, y) {
        var pageInnerSize = jBox.pageInnerSize();
        var pageOffset = jBox.pageXYOffset();
        //var boxpos = [(x=="middle")? pageOffset[0]+(pageInnerSize[0]-box.get(0).offsetWidth)/2 : pageOffset[0]+parseInt(x),
        //   (y=="middle")? pageOffset[1]+(pageInnerSize[1]-box.get(0).offsetHeight)/2: pageOffset[1]+parseInt(y)];
        //box.css("left",boxpos[0]+"px");box.css("top", boxpos[1]+"px");

        var left = (x == "middle") ? pageOffset[0] + (pageInnerSize[0] - box.get(0).offsetWidth) / 2 : pageOffset[0] + parseInt(x);
        var top = (y == "middle") ? pageOffset[1] + (pageInnerSize[1] - box.get(0).offsetHeight) / 2 : pageOffset[1] + parseInt(y);

        box.css("left", left + "px"); box.css("top", top + "px");
    },
    minimize: function(btn, box) {
        jBox.saveViewState(box); box.state = 'minimized';
        $(btn).removeClass().addClass(jBox.restoreClass).attr('title', 'Restore');
        box.content.css('display', 'none'); box.buttons.css('display', 'none'); box.status.css('display', 'none');
        if (typeof box.minimizeorder == 'undefined') {
            jBox.minimizeorder++; box.minimizeorder = jBox.minimizeorder;
        }
        jBox._minimizeRedraw(box);
    },
    _minimizeRedraw: function(box) {
        //最小化时,至下而上排列
        //box.css('left','10px');
        //box.css('width','200px');
        // box.css('height',box.handler.get(0).offsetHeight);
        //var margin = box.minimizeorder*10;
        //var a = jBox.pageXYOffset();var b = jBox.pageInnerSize();
        // box.css('top',a[1]+b[1]-(box.handler.get(0).offsetHeight*box.minimizeorder)-margin+'px');

        //最小化时,至左向右排列	  
        var a = jBox.pageXYOffset(); var b = jBox.pageInnerSize();
        var minH = box.handler.get(0).offsetHeight;
        box.css('width', '200px');
        box.css('height', minH);
        box.css('top', (b[1] - minH - 5) + 'px');
        var margin = box.minimizeorder * 5;
        box.css('left', a[0] + (box.handler.get(0).offsetWidth * (box.minimizeorder - 1)) + margin + 'px');
    },
    restore: function(btn, box) {
        if (box.state == 'minimized') {
            jBox.minimizeorder--;
            for (var i = 0; i < jBox.boxes.length; i++) {
                if (jBox.boxes[i].state == 'minimized') {
                    if (jBox.boxes[i].minimizeorder > box.minimizeorder) {
                        jBox.boxes[i].minimizeorder--;
                        jBox._minimizeRedraw(jBox.boxes[i]);
                    }
                }
            }
            box.minimizeorder = undefined;
        };
        var pageOffset = jBox.pageXYOffset();
        box.state = 'restore';
        $(btn).removeClass().addClass(jBox.minClass).attr('title', 'Minimize');
        box.content.css('display', 'block');
        if (box.buttonsBool) box.buttons.css('display', 'block');
        if (box.resizeBool) box.status.css('display', 'block');
        box.css('left', parseInt(box.lastPos[0]) + pageOffset[0] + 'px');
        box.css('top', parseInt(box.lastPos[1]) + pageOffset[1] + 'px');
        box.css('width', box.lastSize[0]);
        box.css('height', box.lastSize[1]);
    },
    showModel: function() {
        var model = $('#jBox_hideIframe');
        if (model.length == 0) {
            model = $('<iframe id="jBox_hideIframe" scrolling="no" frameborder="0" style="z-index:9999; position:absolute; top:0px; left:0px;-moz-opacity:0.2; opacity:0.2;filter:alpha(opacity=20);display:none;" ></iframe>');
            model.css("background", "#000");
            model.appendTo(document.body);
            //debug IE下iframe里面的空body背景色默认为白色
            model.get(0).contentWindow.document.bgColor = "#000000";
            $(window).bind('resize', function() { jBox.showModel(); })
        }
        var ps = jBox.pageSize();
        model.css('width', ps[0] + 'px');
        model.css('height', ps[1] + 'px');
        //延长背景显示的的时间，避免在加载后背景由白变黑中间出现的闪烁
        window.setTimeout(function() {
            $("#jBox_hideIframe").show();
        }, 50);

    },
    hideModel: function() {

        $(window).unbind('resize')
        var model = $('#jBox_hideIframe');
        if (model.length > 0)
            model.remove();
    },
    setupControls: function(e) {
        var sourceobj = window.event ? window.event.srcElement : e.target;
        var box = jBox._retBox(sourceobj);
        if (/Minimize/i.test(sourceobj.getAttribute("title")))
            jBox.minimize(sourceobj, box);
        else if (/Restore/i.test(sourceobj.getAttribute("title")))
            jBox.restore(sourceobj, box);
        else if (/Close/i.test(sourceobj.getAttribute("title")))
            jBox.close(box);

        return false;
    },
    reDraw: function(box, e) {
        var w = Math.max(jBox.width + jBox.distancex, 150); //最小宽度150
        var h = Math.max(jBox.contentheight + jBox.distancey + 80, 100); //最小高度100 //加80,以免点击时缩减80
        box.setSize(w, h);
    },
    setupDrag: function(e) {
        var boxE = jBox.etarget;
        var box = jBox._retBox(boxE);
        if (!box) return false;
        var e = window.event || e;
        jBox.initmousex = e.clientX;
        jBox.initmousey = e.clientY;
        jBox.initx = parseInt(box.get(0).offsetLeft);
        jBox.inity = parseInt(box.get(0).offsetTop);
        jBox.width = parseInt(box.get(0).offsetWidth);
        jBox.contentheight = parseInt(box.content.get(0).offsetHeight);
        if (box.content.datatype == "iframe") {
            box.css('backgroundColor', '#F8F8F8');
            box.content.css('visibility', 'hidden'); //不隐藏会耗尽内存
        }
        document.onmousemove = jBox.getDistance;
        document.onmouseup = function() {
            if (box.attr("offsetTop") < 0) box.css("top", 0);
            if (box.content.datatype == "iframe") {
                box.content.css('visibility', 'visible');
            }
            jBox.stopDrag();
        }
        return false;
    },
    getDistance: function(e) {
        var etarget = jBox.etarget;
        var e = window.event || e;
        jBox.distancex = e.clientX - jBox.initmousex;
        jBox.distancey = e.clientY - jBox.initmousey;
        var box = jBox._retBox(etarget);
        if (etarget.className == 'jBoxHandler') {
            box.css('left', jBox.distancex + jBox.initx + 'px')
            box.css('top', jBox.distancey + jBox.inity + 'px');
        }
        else if (etarget.className == jBox.resizeClass)
            jBox.reDraw(box, e);
        return false;
    },
    stopDrag: function() {
        jBox.etarget = null;
        document.onmousemove = null;
        document.onmouseup = null;
    },
    saveViewState: function(box) {
        var pageOffset = jBox.pageXYOffset();
        box.lastPos = [parseInt((box.css('left') || box.get(0).offsetLeft)) - pageOffset[0],
			parseInt((box.css('top') || box.get(0).offsetTop)) - pageOffset[1]];
        box.lastSize = [box.css('width'), box.css('height')];
    },
    _retBox: function(dom) {
        return jBox.findBox($(dom).parents('div.jBox').get(0).id);
    }
}//var jBox

    jBox.alert = function(msg, w, h, okFn) {
        if (!w) w = jBox.defaultWidth; if (!h) h = jBox.defaultHeight;
        var buttons = [{ text: "确认", fn: (okFn) ? okFn : function() { jBox.close('jBoxAlert'); } }];
        return jBox.open('jBoxAlert', 'inline', msg, "提示", 'center=1,scrolling=1,draggable=0,model=1,closeable=0,minimizable=0,width=' + w + ',height=' + h, buttons, null);
    }


    jBox.confirm = function(msg, w, h, okFn, cancelFn) {
        if (!w) w = jBox.defaultWidth; if (!h) h = jBox.defaultHeight;
        var buttons = [{ text: "确认", fn: (okFn) ? okFn : function() { jBox.close('jBoxConfirm'); } },
					{ text: "取消", fn: (cancelFn) ? cancelFn : function() { jBox.close('jBoxConfirm'); } }]; //关闭jBox窗口
        return jBox.open('jBoxConfirm', 'inline', msg, "提示", 'center=1,scrolling=1,draggable=0,model=1,closeable=0,minimizable=0,width=' + w + ',height=' + h, buttons, null);
    }

    jBox.newConfirm = function(msg, w, h, buttons) {
        if (!w) w = jBox.defaultWidth; if (!h) h = jBox.defaultHeight;
        if (!buttons) {
            buttons = [{ text: "确认", fn: (okFn) ? okFn : function() { jBox.close('jBoxConfirm'); } },
					{ text: "取消", fn: (cancelFn) ? cancelFn : function() { jBox.close('jBoxConfirm'); } }]; //关闭jBox窗口
        }
        return jBox.open('jBoxConfirm', 'inline', msg, "提示", 'center=1,scrolling=1,draggable=0,model=1,closeable=0,minimizable=0,width=' + w + ',height=' + h, buttons, null);
    }

    jBox.newKeep = function(msg, w, h) {
        /*keepFn:
        */
        if (!w) w = jBox.defaultWidth; if (!h) h = jBox.defaultHeight;

        return jBox.open('jBoxKeep', 'inline', msg, "提示", 'center=1,scrolling=1,jBoxKeep=0,model=1,closeable=0,minimizable=0,width=' + w + ',height=' + h, [], null);
    }

    jBox.keep = function(msg, w, h, keepFn, completeFn) {
        /*keepFn:
        */
        if (!w) w = jBox.defaultWidth; if (!h) h = jBox.defaultHeight;
        var buttons = [{ text: ContinueText, fn: (keepFn) ? keepFn : function() { jBox.close('jBoxKeep'); } },
					{ text: "完成", fn: (completeFn) ? completeFn : function() { jBox.close('jBoxKeep'); } }]; //关闭当前jBox窗口和父jBox窗品
        return jBox.open('jBoxKeep', 'inline', msg, "提示", 'center=1,scrolling=1,jBoxKeep=0,model=1,closeable=0,minimizable=0,width=' + w + ',height=' + h, buttons, null);
    }

    jBox._tipTimeout = function(timeOut, completeFn) {
        var box = jBox.findBox('jBoxTip');
        if (null != box) {
            if (undefined == box.isMouseOver || null == box.isMouseOver || !box.isMouseOver) {
                jBox.close(box);
                //执行回调事件
                if (completeFn) {
                    completeFn();
                }
            }
            else {
                var funcRef = function() { jBox._tipTimeout(timeOut, completeFn) };
                setTimeout(funcRef, timeOut);
            }
        }
    }
    jBox.tip = function(msg, w, h) { //n( e ,msg , w , h )
        var box = jBox.findBox('jBoxTip');
        if (null == box) {
            //var e = e||window.event;
            var e = window.event;
            if (!w) w = 150; if (!h) h = 20;
            var pageInner = jBox.pageInnerSize();
            var pageOffset = jBox.pageXYOffset();
            var mousePos = [50, 50];
            if (e) mousePos = [e.clientX, e.clientY];
            box = jBox.open('jBoxTip', 'inline', msg, '', 'top=' + mousePos[1] + ',left=' + mousePos[0] + ',scrolling=1,minimizable=0,closeable=0,width=' + w + ',height=' + h, null);
            box.content.mouseover(function() {
                var box = jBox.findBox('jBoxTip');
                box.isMouseOver = true;
            });
            box.content.mouseout(function() {
                var box = jBox.findBox('jBoxTip');
                box.isMouseOver = false;
            });
            setTimeout(jBox._tipTimeout, 3000);
        }
        return box;
    }

    //timeOut单位毫秒
    jBox.tip = function(msg, w, h, timeOut, completeFn) {
        var box = jBox.findBox('jBoxTip');
        if (null == box) {
            //var e = e||window.event;
            var e = window.event;
            if (!w) w = 150; if (!h) h = 20;
            var pageInner = jBox.pageInnerSize();
            var pageOffset = jBox.pageXYOffset();
            var mousePos = [50, 50];
            if (e) mousePos = [e.clientX, e.clientY];
            box = jBox.open('jBoxTip', 'inline', msg, '', 'top=' + mousePos[1] + ',left=' + mousePos[0] + ',scrolling=1,minimizable=0,closeable=0,width=' + w + ',height=' + h, null);
            box.content.mouseover(function() {
                var box = jBox.findBox('jBoxTip');
                box.isMouseOver = true;
            });
            box.content.mouseout(function() {
                var box = jBox.findBox('jBoxTip');
                box.isMouseOver = false;
            });

            var funcRef = function() { jBox._tipTimeout(timeOut, completeFn) };

            //等待timeOut指定时间后，如果用户鼠标放到了上面，就继续显示这么长时间，否则消失
            setTimeout(funcRef, timeOut);
        }
        return box;
    }

    //新增
    jBox.bindTip = function(source, eventName, msg, w, h) {
        $(source).bind(eventName, function() {
            var box = jBox.findBox('jBoxTip');
            if (null == box) {
                var e = window.event;
                if (undefined == w) w = 150; if (undefined == h) h = 20;
                var pageInner = jBox.pageInnerSize();
                var pageOffset = jBox.pageXYOffset();
                var mousePos = [50, 50];
                if (e) mousePos = [e.clientX, e.clientY];
                box = jBox.open('jBoxTip', 'inline', msg, '', 'top=' + mousePos[1] + ',left=' + mousePos[0] + ',scrolling=1,minimizable=0,closeable=0,width=' + w + ',height=' + h, null);
                box.content.mouseover(function() {
                    var box = jBox.findBox('jBoxTip');
                    box.isMouseOver = true;
                });
                box.content.mouseout(function() {
                    var box = jBox.findBox('jBoxTip');
                    box.isMouseOver = false;
                });
                setTimeout(jBox._tipTimeout, 3000);
            }
            return box;
        });
    }

    //进度报告
    jBox.showProgress = function(progressID, nowVal, maxVal, tip, title, attr, buttons, showButtonsOnlyComplete) {/*
progressID: 可选,不同进度条用不同id,可支持一个页面显示多个进度条,互不影响.若不指定或id相同,则为同一进度条.
nowVal:     必选,当前进度值
maxVal:     必选,最大进度值
tip:        必选,当前提示信息.默认为成功消息.失败消息以|分隔,开头为下列之一: fail|,failure|,0|,异常|,失败,或indexof("失败")!=-1,;
title:      必选,进度主题
attr:       可选,为空则默认为:"center=1,scrolling=1,draggable=1,model=0,minimizable=1,closeable=0,width=350,height=160"
buttons:    可选,为空则默认为:进度时无按钮,完成100%时显示 确定 按钮
showButtonsOnlyComplete: 可选,是否仅在完成时才显示按钮(为空则默认为在完成100%时才显示按钮).false:一直显示,true:完成时显示
*/
        if (!progressID) progressID = "jBoxProgress";
        var box = jBox.findBox(progressID);
        if (!box) {
            if (!attr) attr = "center=1,scrolling=1,draggable=1,model=0,minimizable=1,closeable=0,width=350,height=160";
            box = jBox.open(progressID, "inline", "", title, attr);
            //当前消息
            box.progressNow = $("<div class='progressNow'></div>");
            box.content.append(box.progressNow);
            //进度展示区
            box.progressBar = $("<div class='progressBar'> \
	                            <div class='progressText'></div> \
                                <div class='progressColor'><span class='progressText'></span></div> \
                            </div>");
            box.progressText = box.progressBar.find(".progressText"); //div.progressText(黑色)和span.progressText(白色)
            box.progressColor = box.progressBar.find(".progressColor");
            box.content.append(box.progressBar);
            box.progressBar.find("span.progressText").width(box.progressBar.attr("clientWidth"));

            //历史消息
            box.progressTip = $("<div class='progressTip'></div>");
            box.content.append(box.progressTip);
            var hTip = box.content.attr("clientHeight") - box.progressBar.attr("clientHeight") - box.progressNow.attr("clientHeight") - 20;
            box.progressTip.css("height", hTip);

            box.progressFailVal = 0;
            box.progressSuccessVal = 0;
            box.progressStartTime = new Date();
        }
        var width = Math.ceil(nowVal / maxVal * 100);
        var time = new Date();
        var msg = nowVal + ".[" + time.toLocaleTimeString() + "]";
        if (tip.indexOf("fail|") == 0 || tip.indexOf("0|") == 0 || tip.indexOf("failure|") == 0 || tip.indexOf("异常|") == 0 || tip.indexOf("失败") != -1) {
            tip = tip.replace("fail|", "").replace("0|", "").replace("failure|", "").replace("异常|", "").replace("失败|", "");
            msg = $("<div class='resultMsg failMsg'>" + msg + tip + "</div>");
            box.progressFailVal++;
        }
        else {
            tip = tip.replace("success|", "").replace("1|", "").replace("succ|", "").replace("成功|", "");
            msg = $("<div class='resultMsg successMsg'>" + msg + tip + "</div>");
            if (nowVal > 0) box.progressSuccessVal++;
        }
        var elapse = Math.ceil((time.getTime() - box.progressStartTime.getTime()) / 1000);
        var h = Math.floor(elapse / 3600);
        var m = Math.floor((elapse - h * 3600) / 60);
        var s = Math.floor(elapse - h * 3600 - m * 60);
        var spend = (h < 9 ? "0" + h : h) + ":" + (m < 9 ? "0" + m : m) + ":" + (s < 9 ? "0" + s : s);
        time = null;

        box.progressNow.html("[" + nowVal + "/" + maxVal + "," + spend + "]" + tip);
        if (width < 1 || nowVal == 0) return;
        box.progressText.html(width + " %"); //百分比指示     
        box.progressColor.css("width", width + "%"); //颜色指示     
        box.progressTip.append(msg);
        box.buttonList = null;
        if (nowVal == maxVal) {
            var stat = nowVal + "/" + maxVal + "," + "成功" + box.progressSuccessVal + "," + "失败" + box.progressFailVal + "," + ConsumingText + spend;
            box.progressNow.html(stat); //完成时显示统计
            if (!buttons)
                box.buttonList = [{ text: "确认", fn: "close"}]; //默认按钮
            else
                box.buttonList = buttons;
            box.progressFailVal = null;
            box.progressFailVal = null;
            box.progressStartTime = null;
            if ($.browser.msie) {
                CollectGarbage();
            }
        }
        else {
            if (buttons && showButtonsOnlyComplete != undefined && !showButtonsOnlyComplete) box.buttonList = buttons; //缺少showButtonsOnlyComplete时,则进度过程不显示
        }
        box.setButtons();
    } //jBox.showProgress


    /* 网页载入进度
    <link   rel="stylesheet"   href="../css/bmys_style.css">   
    <SCRIPT>   
    var   i;   
    function   longtime()   
    {   
    i=0;   
    b1.style.cursor="wait";   
    b1.disabled=true;     
    timedIterations();     
    }   
    
    function   timedIterations()   
    {   
    if   (i<=140)   
    {   
    d1.innerText="正在装载........."+Math.round(i/1.4)+"%";     
    d2.style.width=i;   
    //   following   statements   represents   a   calculation   that   takes   some   time   
    var   j=0;   
    while   (j<=10000)   
    j++;       
    setTimeout("timedIterations();",   1);   
    i++;         
    }   
    else   
    {   
    b1.style.cursor="";   
    b1.disabled=false;     
    }   
    }   
    </SCRIPT>   
    <BODY   id=b1   onload="longtime();"   leftmargin=250   topmargin=200>   
    <DIV   id="d1">正在装载.....</DIV>   
    <DIV   id="d2"     style="background-color:#1b3679"></DIV>   
    </BODY>   


*/

    /*

//载入进度
    //$(window.frames[ifrName].document).bind("readystatechange",function()
    window.frames[ifrName].document.onreadystatechange=function()
    {
    //window.frames[ifrName].document;
    var ifrDoc=window.frames[ifrName].document;
    //
    var processBar=box.content.find(".processBar");
    alert(ifrDoc.body);
    switch(ifrDoc.readyState)
    {//loading,loaded,interactive,complete
    case "complete":
    alert(ifrDoc.readyState);
    processBar.remove();
    break;
    default:
    if(processBar.length==0)
    {			 
    processBar=box.content.prepend("<div class='processBar'>loading...</div>");                   
    }
    alert(ifrDoc.body);
    processBar.text(ifrDoc.readyState);
    break;
    }			
    };
    */

    //jBox鼠标焦点位置改变函数 ljm 2009-3-17 11:09:22添加
    function hoverFunction(btn, fn) {
        return function() {
            if (fn == 'add') {
                btn.addClass('buttonOver');
            }
            else if (fn == 'remove') {
                btn.removeClass('buttonOver');
            }
        }
    }