var J = window.J = {};
var Jade = window.Jade = {
    url: "/ajax/Index.ashx",

    imgUrl: "http://www.zhsggw.com",

    defaultImgUrl: '/image/nopic.gif',

    eccypkey: "a1d25rr5g36y6",

    pageSize: 15,

    /*
    * 有权限的按钮
    */
    PurviewButton: {},

    /*
    * 允许上传的文件类型
    */
    allowExtension: ["gif", "jpg", "jpeg", "png", "bmpswf", "flv", "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb", "doc", "docx", "xls", "xlsx", "ppt", "htm", "html", "txt", "zip", "rar", "gz", "bz2"],

    /**
    * 统一ajax调用方法
    * @param {} cn 后台类名
    * @param {} mn 后台方法名
    * @param {} p 传个后台的参数
    * @param {} sc 成功时的回调方法
    * @param {} fc 失败时的回调方法
    */
    ajax: function (cn, mn, p, sc, fc) {
        var pms = Easy.apply({}, p);
        pms.classname = cn.replace(/\+/g, "Server");
        pms.methodname = mn;
        Easy.Ajax.post({
            url: Jade.url,
            params: pms,
            success: function (r) {
                var o = Easy.decode(r);
                if (Easy.isFunction(sc)) {
                    sc.call(o, o, pms);
                }
            },
            failure: function (o) {
                if (Easy.isFunction(fc)) {
                    fc.call(o, o, pms);
                }
            }
        });
    },
    /**
    * 统一ajax调用方法
    * @param {} cn 后台类名
    * @param {} mn 后台方法名
    * @param {} p 传个后台的参数
    * @param {} sc 成功时的回调方法
    * @param {} fc 失败时的回调方法
    */
    upload: function (cn, mn, p, sc, fc) {
        var pms = Easy.apply({}, p);
        pms.classname = cn.replace(/\+/g, "Server");
        pms.methodname = mn;
        Easy.Ajax.upload({
            url: Jade.url,
            params: pms,
            form: pms.form,
            success: function (r) {
                var o = Easy.decode(r);
                if (Easy.isFunction(sc)) {
                    sc.call(o, o, pms);
                }
            },
            failure: function (o) {
                if (Easy.isFunction(fc)) {
                    fc.call(o, o, pms);
                }
            }
        });
    },
    /**
    * 把对象转换成后台能接受的json字符串
    * @param {} ps 要转换的对象
    * @return {} 返回转换好的json字符串对象
    */
    parseParams: function (ps) {
        var p = {};
        Easy.each(ps, function (v, k) {
            if (!Easy.isPrimitive(v)) {
                p[k] = Easy.encode(v);
            } else {
                p[k] = v;
            }
        });
        return p;
    },

    /**
    * 从URL里读取参数
    * @param {} name 参数名称
    * @return {} 如果没有值返回NULL
    */
    request: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        "".match(reg);
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    },

    /**
    * 从URL里读取参数(返回int)
    * @param {} name 参数名称
    * @return {} 如果没有值返回0
    */
    requestID: function (name) {
        var id = 0;
        var val = Jade.request(name);
        if (val != null && !isNaN(val)) {
            id = parseInt(val);
        }
        return id;
    },

    /**
    * 去空格, 去除所有空格
    * @param {} s 要去空格的字符串
    * @return {} 去掉空格的字符串
    */
    trim: function (s) {
        return Easy.String.trim(s);
    },

    /**
    * 绑定下拉框的值
    * @param {} el 下拉框对象 
    * @param {} cn 后台类名
    * @param {} mn 后台方法名,改方法必须是返回SelectionItem的集合
    * @param {} param 传给后台的参数
    * @param {} len 保留原有Option的个数
    * @param {} v 要绑定下拉框的值  
    * @param {} cb 绑定完下拉框后的回调函数
    */
    fillSelect: function (el, cn, mn, param, len, v, cb) {
        this.ajax(cn.replace(/\+/g, "Server"), mn, param, function (o) {
            if (!o.exception) {
                if (el) {
                    el.length = len || 0;
                }
                Easy.each(o, function (a, i) {
                    el.options.add(new Option(a.text, a.value));
                });
                if (v) {
                    el.value = v;
                }
                if (Easy.isFunction(cb)) {
                    cb.call(el, o);
                }
                if (Jade.Form && Jade.Form.beautySelect) {
                    Jade.Form.beautySelect(el);
                }
            } else {
                Jade.Msg.alert(o.message);
            }
        });
    },

    /**
    * 绑定下拉框的值,其中数据是JS对象,尽量不用
    * @param {} el
    * @param {} data
    * @param {} len
    * @param {} v
    * @param {} cb
    */
    fillSelectData: function (el, data, len, v, cb) {
        el.length = len || 0;
        Easy.each(data, function (a, i) {
            el.options.add(new Option(a.text, a.value));
        });
        if (v) {
            el.value = v;
        }
        if (Easy.isFunction(cb)) {
            cb.call(el, data);
        }
        if (Jade.Form && Jade.Form.beautySelect) {
            Jade.Form.beautySelect(el);
        }
    },

    /**
    * Tab切换, 选项卡必须要有 pos 属性(表示它要显示div的位置)
    * @param {} dom 被点击的选项卡
    * @param {} ev 鼠标点击事件(Easy.event.EventObject)的对象
    */
    tabStripClick: function (dom, ev) {
        var tag = Easy.DOM.getParent(new Easy.event.EventObject(ev).target, "li");
        var pos = Easy.DOM.getAttribute(tag, "pos");
        if (pos != null) {
            pos = pos - 0;
            var cn = Easy.DOM.getChildren(Easy.DOM.getNext(dom, "div"), "div");
            Easy.each(cn, function (c, i) {
                Easy.DOM[pos != i ? "hide" : "show"](c);
            });
            Easy.each(Easy.DOM.getChildren(dom, "li"), function (li, i) {
                Easy.DOM[li == tag ? "addClass" : "removeClass"](li, "on");
            });
        }
    },

    /**
    * 获取下拉框选中的文本
    * @param {} sel 下拉框对象
    * @return {} 没有值,则返回false
    */
    getSelectText: function (sel) {
        var vle = sel.value;
        var t = "";
        Easy.each(sel.options, function (v, i) {
            if (v.value == vle) {
                t = v.text;
                return false;
            }
        });
        return t;
    },

    /**
    * 把下拉框转换给知道完成的形式
    * @param {} el 下拉框
    * @param {} d 
    * @param {} w 宽度
    * @param {} oncomplete 输入关键字查出符合的数据后回调的方法
    */
    tranformSelet2Autocomplate: function (el, d, w, oncomplete) {
        if (Easy.DOM.isHide(el)) { return; }
        if (el) {
            var p = Easy.DOM.getParent(el);
            var autoCorp = Easy.DOM.create({
                tag: 'input',
                id: 'auto_' + el.name,
                value: Jade.getSelectText(el) || "",
                style: { width: w || Easy.DOM.getWidth(p) }
            }, p);
            var xy = Easy.DOM.getPosition(autoCorp);
            var wrap = Easy.DOM.create({
                tag: 'div',
                cls: 'autocomplete'
            }, p);
            var t = Easy.DOM.getText(Easy.DOM.getChildren(Easy.DOM.getParent(p), "label")[0]);
            Easy.DOM.hide(wrap);
            Easy.DOM.setStyle(p, { position: "relative" });
            Easy.DOM.on(autoCorp, "keyup", function (p, e) {
                var v = Jade.findForSelect(el, p.value);
                Easy.DOM.show(wrap);
                wrap.innerHTML = v;
                if (oncomplete) {
                    oncomplete(wrap, el, autoCorp, v);
                }
            });

            Easy.DOM.on(wrap, "click", function (p, e) {
                var target = e.target;
                if (target && target.tagName.toLowerCase() == "a") {
                    var v = Easy.DOM.getAttribute(target, "value");
                    el.value = v;
                    autoCorp.value = Easy.DOM.getText(target);
                    Easy.DOM.hide(wrap);
                    if (v && v != "0") {
                        clearError(el);
                    } else {
                        makError(el, "请选择" + t);
                    }
                }
            });
            Easy.DOM.hide(el);
            el.autoCtl = autoCorp;
        }
    },

    /**
    * 自动完成功能
    * @param {} el 要有自动完成功能的输入框
    * @param {} cfg 配置信息,包括: width, classname, methodname, valueField(默认为:value), textField(默认为:text)
    */
    autoComplete: function (el, cfg) {
        if (el) {
            var p = Easy.DOM.getParent(el);
            var autoCorp = el;
            var xy = Easy.DOM.getPosition(autoCorp);
            var wrap = Easy.DOM.create({
                tag: 'div',
                cls: 'autocompleteajax',
                style: { width: (cfg.width || Easy.DOM.getWidth(el) - 8), top: (cfg.top || Easy.DOM.getHeight(el)) - 2,
                    left: cfg.left || Easy.DOM.getWidth(Easy.DOM.getChildren(p, "label")[0])
                }
            }, p);
            Easy.DOM.hide(wrap);
            Easy.DOM.setStyle(p, { position: "relative" });
            Easy.DOM.on(autoCorp, "keyup", function (p, e) {
                if (p.value) {
                    Jade.ajax(cfg.classname.replace(/\+/g, "Server"), cfg.methodname, { key: p.value }, function (data) {
                        var d = [];
                        Easy.each(data, function (a, i) {
                            d.push("<li><a href='javascript:;' value='" + a[cfg.valueField || "value"] + "'>" + a[cfg.textField || "text"] + "</a></li>");
                        });
                        Easy.DOM.show(wrap);
                        wrap.innerHTML = "<ul><li><a href='javascript:;' value='0'>请选择...</a></li>" + d.join("") + "</ul>";
                    });
                }
            });

            Easy.DOM.on(wrap, "click", function (p, e) {
                var target = e.target;
                if (target && target.tagName.toLowerCase() == "a") {
                    var v = Easy.DOM.getAttribute(target, "value");
                    Easy.DOM.setAttributes(el, { "data-value": v });
                    autoCorp.value = Easy.DOM.getText(target);
                    Easy.DOM.hide(wrap);
                    if (cfg.callback) {
                        cfg.callback(v);
                    }

                    if (Easy.DOM.getAttribute(autoCorp, "mustInput") == "true") {
                        if (v && v != "0" && clearError) {
                            clearError(el);
                        } else {
                            if (makError) makError(el, "请选择");
                        }
                    }
                }
            });
        }
    },

    findForSelect: function (el, key) {
        var d = [];
        Easy.each(Easy.Array.toArray(el), function (a, i) {
            if (a && a.text.indexOf(key) > -1) {
                d.push("<li><a href='javascript:;' value='" + a.value + "'>" + a.text + "</a></li>");
            }
        });
        return d.join("");
    },

    /**
    * 获取cookie里的值
    * @param {} name cookie里的key
    * @return {} 没有值,返回null
    */
    getCookie: function (name) {//获取指定名称的cookie的值
        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null) return unescape(arr[2]); return null;
    },

    /**
    * 设置cookie的值
    * @param {} name 要设置的Key
    * @param {} value 设置的值
    * @param {} day 过期时间,单位天,可以是小数
    */
    setCookie: function (name, value, day) {
        var Days = day || 30; //此 cookie 将被保存 30 天
        var exp = new Date();    //new Date("December 31, 9998");
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
    },

    /**
    * 判断对象是否是空对象
    * @param {} o 要判断的对象
    * @return {}
    */
    isEmptyObject: function (o) {
        var f = true;
        for (var a in o) {
            f = false;
            break;
        }
        return f;
    },

    /**
    * 截取小数点后面2位
    * @param {} num 要截取的数字
    * @return {}
    */
    getMoney: function (num) {
        var v = Math.round(num * 100) / 100;
        if (v % 1 == 0 && v < 1000) {
            return v + ".00";
        }
        if (v % 1 != 0 && (v * 10) % 1 == 0) {
            return v + "0";
        }
        return v;
    },

    /**
    * js加密
    * @param {} str 要加密的字符串
    * @param String pwd 加码密钥, 用Jade.eccypkey
    */
    enChTo: function (str, pwd) { /*加密*/
        if (pwd == null || pwd.length <= 0) {
            alert("Please enter a password with which to encrypt the message.");
            return null;
        }
        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.ceil(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        if (mult < 2) {
            alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
            return null;
        }
        var salt = Math.round(Math.random() * 1000000000) % 100000000;
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i++) {
            enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
            if (enc_chr < 16) {
                enc_str += "0" + enc_chr.toString(16);
            } else enc_str += enc_chr.toString(16);
            prand = (mult * prand + incr) % modu;
        }
        salt = salt.toString(16);
        while (salt.length < 8) salt = "0" + salt;
        enc_str += salt;
        return enc_str;
    },

    /**
    * js解密
    * @param {} str 要解密的字符串
    * @param String pwd 解码密钥, 用Jade.eccypkey
    */
    deChTo: function (str, pwd) { /*解密*/
        if (str == null || str.length < 8) {
            alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
            return;
        }
        if (pwd == null || pwd.length <= 0) {
            alert("Please enter a password with which to decrypt the message.");
            return;
        }
        var prand = "";
        for (var i = 0; i < pwd.length; i++) {
            prand += pwd.charCodeAt(i).toString();
        }
        var sPos = Math.floor(prand.length / 5);
        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
        var incr = Math.round(pwd.length / 2);
        var modu = Math.pow(2, 31) - 1;
        var salt = parseInt(str.substring(str.length - 8, str.length), 16);
        str = str.substring(0, str.length - 8);
        prand += salt;
        while (prand.length > 10) {
            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
        }
        prand = (mult * prand + incr) % modu;
        var enc_chr = "";
        var enc_str = "";
        for (var i = 0; i < str.length; i += 2) {
            enc_chr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255));
            enc_str += String.fromCharCode(enc_chr);
            prand = (mult * prand + incr) % modu;
        }
        return enc_str;
    },

    create: {

        /**
        * 创建后台管理里表格的Store
        * @param {} cn 后台类名
        * @param {} cfg 传给后台的参数
        * @param {} sort 排序字段
        * @param {} msk 加载时候是否要遮罩
        * @param {} notAutoLoad 是否不自动加载
        * @return {}
        */
        store: function (cn, cfg, sort, msk, notAutoLoad) { //cn类名;cfg参数,sort//排序字段
            if (!sort) { alert('创建表格的Store时，没有传入 排序字段！'); sort = "apptime" }
            cfg = cfg ? cfg : {};
            cfg.params = Easy.apply(cfg || {}, (cfg || {}).params);
            delete cfg.params.params;
            var store = new Easy.data.Store({
                url: Jade.url,
                root: 'Records',
                noMask: !msk,
                autoLoad: !notAutoLoad,
                totalField: 'Count',
                baseParams: Easy.apply({
                    classname: cn.replace(/\+/g, "Server"),
                    methodname: 'GetPage',
                    start: 0, //开始行号
                    limit: Jade.pageSize, //每页大小
                    sort: sort, //排序字段
                    dir: 'desc'//排序方式
                }, cfg)
            });
            return store;
        },

        /**
        * 创建后台管理里的工具栏(上方按钮部分)
        * @param {} el 渲染的位置
        * @param {} items 具体的按钮
        * @return {} 如没有items,则返回false
        */
        toolbar: function (el, items) {
            var cn = [];
            var toolbar = { buttons: [] };
            if (items && items.length > 0) {
                Easy.each(items, function (it, i) {
                    var wrap = Jade.create.button(it);
                    cn.push(wrap);
                    toolbar.buttons.push(wrap);
                });
            }
            if (cn.length == 0) {
                return false;
            }
            var wrap = toolbar.wrap = Easy.DOM.create({
                tag: 'div',
                cls: 'j-toolbar',
                children: cn
            }, Easy.get(el));
            return toolbar;
        },

        /**
        * 创建后台管理里的按钮,
        * @param {} cfg 按钮的配置,有属性:text(显示的文字), el(渲染的位置), fn(按钮点击时调用的方法), cls(按钮样式)
        * @return {}
        */
        button: function (cfg) {
            var fn = cfg.fn;
            Easy.Object.remove(cfg, "fn");
            var cls = "";
            if (cfg.iconCls) {
                cls = "icon " + cfg.iconCls;
            }
            var wrap = Easy.DOM.create(Easy.apply({
                tag: 'input',
                type: 'button',
                cls: cls,
                value: cfg.text
            }, cfg));

            Easy.DOM.render(wrap, Easy.get(cfg.el))
            Easy.DOM.on(wrap, "click", fn);
            cfg.fn = fn;
            // 验证权限
            if (cfg.model) {
                				if (!top.Userpurview[cfg.model]) {
                					Easy.DOM.setAttributes(wrap, { disabled: true, title: "您当前登录的用户没有" + cfg.text + "功能" });
                					Easy.DOM.addClass(wrap, "disabledBtn");
                				}
                				Jade.PurviewButton[cfg.model] = {
                					purview: cfg.model,
                					wrap: wrap,
                					fn: fn
                				};
            }
            return wrap;
        },

        /**
        * 创建后台管理里的表单按钮,
        * @param {} cfg 按钮的配置,有属性:text(显示的文字), pstyle(样式), style(文字dom的样式), 
        * 				 isBlue(是否显示成蓝色), el(渲染的位置), fn(按钮点击时调用的方法), cls(按钮样式)
        * @return {}
        */
        formButton: function (cfg) {
            var fn = cfg.fn;
            Easy.Object.remove(cfg, "fn");
            var btn = Easy.DOM.create({
                tag: 'a',
                style: cfg.pstyle,
                href: 'javascript:;',
                cls: 'button' + (cfg.isBlue ? "" : " btn-gray") + " " + cfg.cls,
                children: [{
                    tag: 'i',
                    cls: 'ico-btn ib-offline'
                }, {
                    tag: 'span',
                    style: cfg.style,
                    html: cfg.text
                }]
            }, Easy.get(cfg.el));
            Easy.DOM.on(btn, "click", fn);
            cfg.fn = fn;
            return btn;
        }
    },

    /**
    * 获取表格中某个字段的值
    * @param {} g 表格对象
    * @param {} id 要获取数据的字段名
    * @return {} 没有数据,返回false, 如果多个,则返回第一个
    */
    getGridId: function (g, id) {
        var ids = g.getValues(id);
        if (ids.length == 1) {
            return ids[0];
        } else {
            Jade.Msg.alert(ids.length == 0 ? "请选择要处理的数据!" : ("您选择了" + ids.length + "条数据，该操作只能一条一条操作，请重新选择!"))
            return false;
        }
    },

    /**
    *  获取表格中某个字段的多个值
    * @param {} g 表格对象
    * @param {} id 要获取数据的字段名
    * @return {} 没有数据,返回false
    */
    getGridIds: function (g, id) {
        var ids = g.getValues(id);
        if (ids.length == 0) {
            Jade.Msg.alert("请选择要处理的数据!");
            return false;
        } else {
            return ids;
        }
    },

    CacheEl: {},

    /**
    * 存放大数据(数据比较多的,而且固定的)
    * @type 
    */
    Cache: {},

    Msg: {
        btns: {
            OK: "确定",
            CANCEL: "取消",
            YES: "是",
            NO: "否"
        },
        show: function (cfg) {
            var arr = [];
            var kv = this.btns;
            Easy.each(cfg.buttons, function (b, i) {
                arr.push("<a href='javascript:;' class='msg-btn" + ((i == "OK" || i == "YES") ? "on" : "") + "' event='" + i + "'>" + kv[i] + "</a>");
            });
            var doig = Jade.Dailog.show(cfg.title, "<table><tr><td><div class='" + cfg.cls + "'></div></td><td><div class='msg-text'>" + cfg.msg +
                "</div></td></tr><tr><td colspan='2' align='right' id='msgbtnwrap'>" + arr.join("") + "</td></tr></table>", 280, this.getHeight(cfg.msg) + 22 + 32 + 34, cfg.cb);
            var cn = Easy.DOM.getChildren(Easy.get("msgbtnwrap"), "a");
            Easy.each(cn, function (c, i) {
                var e = Easy.DOM.getAttribute(c, "event");
                if (e && cfg.buttons[e]) {
                    Easy.DOM.on(c, "click", cfg.buttons[e]);
                }
            });
            return doig;
        },
        showX: function (cfg) {
            var arr = [];
            var kv = this.btns;
            Easy.each(cfg.buttons, function (b, i) {
                arr.push("<a href='javascript:;' class='msg-btn" + ((i == "OK" || i == "YES") ? "on" : "") + "' event='" + i + "'>" + kv[i] + "</a>");
            });
            var doig = Jade.Dailog.showX(cfg.title, "<table><tr><td><div class='" + cfg.cls + "'></div></td><td><div class='msg-text'>" + cfg.msg +
                "</div></td></tr><tr><td colspan='2' align='right' id='msgbtnwrap'>" + arr.join("") + "</td></tr></table>", 280, this.getHeight(cfg.msg) + 22 + 32 + 34, cfg.cb);
            var cn = Easy.DOM.getChildren(Easy.get("msgbtnwrap"), "a");
            Easy.each(cn, function (c, i) {
                var e = Easy.DOM.getAttribute(c, "event");
                if (e && cfg.buttons[e]) {
                    Easy.DOM.on(c, "click", cfg.buttons[e]);
                }
            });
            return doig;
        },
        getHeight: function (msg) {
            var tn = Easy.DOM.create({
                tag: "div",
                cls: "msg-text",
                html: msg,
                style: "position:absolute;left:-1000px;top:-1000px;"
            }, Easy.getBody());
            return Math.max(Easy.DOM.getHeight(tn), 86);
        },
        /**
        * 弹出框,(info,warn,error)都是同一配置,只是标题,图标不一样
        * @param {} msg 要显示的文字, 支持html
        * @param {} callback 点击确定后回调的方法
        */
        alert: function (msg, callback) {
            var fn = function () { tip.close(); };
            if (Easy.isFunction(callback)) {
                fn = function () {
                    callback(true);
                    tip.close();
                };
            }
            var tip = this.show({ msg: msg, title: '提 示', cls: 'msg-alert', buttons: {
                OK: fn
            }
            });
        },
        info: function (msg, callback) {
            var fn = function () { tip.close(); };
            if (Easy.isFunction(callback)) {
                fn = function () {
                    callback(true);
                    tip.close();
                };
            }
            var tip = this.show({ msg: msg, title: '信 息', cls: 'msg-info', buttons: {
                CANCEL: function () { tip.close(); },
                OK: fn
            }
            });
        },
        warn: function (msg, callback) {
            var fn = function () { tip.close(); };
            if (Easy.isFunction(callback)) {
                fn = function () {
                    callback(true);
                    tip.close();
                };
            }
            var tip = this.show({ msg: msg, title: '警 告', cls: 'msg-warn', buttons: {
                OK: fn
            }
            });
        },
        error: function (msg, callback) {
            var fn = function () { tip.close(); };
            if (Easy.isFunction(callback)) {
                fn = function () {
                    callback(true);
                    tip.close();
                };
            }
            var tip = this.show({ msg: msg, title: '错误提示', cls: 'msg-error', buttons: {
                OK: fn
            }
            });
        },
        /**
        * 确认框
        * @param {} msg 要显示的文字, 支持html
        * @param {} callback 点击是否后的回调方法,其中有一个参数,表示点击的"是",还是"否", "是"返回true,"否"返回false
        */
        confirm: function (msg, callback) {
            var fn = function () { tip.close(); };
            if (Easy.isFunction(callback)) {
                fn = function () {
                    callback(true);
                    tip.close();
                };
            }
            var tip = this.show({ msg: msg, title: '确 认', cls: 'msg-confirm', buttons: {
                NO: function () {
                    if (Easy.isFunction(callback)) {
                        callback(false);
                    }
                    tip.close();
                },
                YES: fn
            }
            });
        },
        confirmX: function (msg, callback) {
            var fn = function () { tip.close(); };
            if (Easy.isFunction(callback)) {
                fn = function () {
                    callback(true);
                    tip.close();
                };
            }
            var tip = this.showX({ msg: msg, title: '确 认', cls: 'msg-confirm', buttons: {
                NO: function () {
                    if (Easy.isFunction(callback)) {
                        callback(false);
                    }
                    tip.close();
                },
                YES: fn
            }
            });
        }
    },


    Dailog: {
        zIndex: 10,

        /**
        * 弹出窗口
        * @param {} title 标题
        * @param {} el 窗口内容,可以是的字符串也可以是一个dom的ID,一个可以是一个dom对象
        * @param {} width 要显示的宽度
        * @param {} height 要显示的高度
        * @param {} onclose 关闭窗口时回调的方法
        * @return {}
        */
        show: function (title, el, width, height, onclose) {
            return Jade.Dailog.create({
                title: title,
                width: width,
                height: height,
                el: el,
                onClose: onclose
            });
        },
        showX: function (title, el, width, height, onclose) {
            return Jade.Dailog.createX({
                title: title,
                width: width,
                height: height,
                el: el,
                onClose: onclose
            });
        },

        /**
        * 弹出窗口,其中内容是一个IFrame
        * @param {} title 标题
        * @param {} url iframe的地址
        * @param {} width 要显示的宽度
        * @param {} height 要显示的高度
        * @param {} onclose 关闭窗口时回调的方法
        * @return {}
        */
        showFrame: function (title, url, width, height, onclose) {
            return Jade.Dailog.create({
                title: title,
                width: width,
                height: height,
                iframe: Easy.util.urlAppend(url, { s_c_o_p_e: true, r: new Date().getTime() }),
                onClose: onclose
            });
        },

        /**
        * 关闭窗口
        * @param {} id 内容为dom时的DOM ID
        */
        close: function (id) {
            var cfg = Jade.CacheEl["dailog_" + id]
            if (cfg.el) {
                Easy.DOM.render(Easy.get(cfg.el), cfg.parentEl);
            }
            if (cfg.wrap) {
                Easy.removeNode(cfg.wrap);
            }
            if (cfg.msk) {
                Easy.removeNode(cfg.msk);
            }
            if (Easy.isFunction(cfg.callback)) {
                cfg.callback();
            }
        },
        create: function (cfg) {
            var elDom = Easy.get(cfg.el), id, head;
            if (elDom) {
                id = "dailog_" + (cfg.el || cfg.id);
            } else {
                id = "dailog_" + (cfg.id || ++Jade.Dailog.zIndex);
            }
            var closeBtn = Easy.DOM.create({
                tag: 'a',
                dailogid: id,
                href: 'javascript:;'
            });
            Easy.DOM.on(closeBtn, "click", function (p) {
                if (cfg.el) {
                    var dlgs = Jade.CacheEl[Easy.DOM.getAttribute(p, "dailogid")];
                    Easy.DOM.render(Easy.get(cfg.el), dlgs.parentEl);
                    Easy.Object.remove(Jade.CacheEl, dlgs);
                }

                if (msk) {
                    Easy.removeNode(msk);
                }
                Easy.removeNode(wrap);
                if (Easy.isFunction(cfg.onClose)) {
                    cfg.onClose();
                }
            });
            var head = Easy.DOM.create({
                tag: 'h2',
                children: [{
                    tag: 'span',
                    html: cfg.title || '提示信息'
                }, closeBtn]
            });
            var body = Easy.DOM.create({
                tag: 'div',
                cls: 'j-dailog-body'
            });
            var footer = Easy.DOM.create({
                tag: 'div',
                cls: 'j-dailog-footer'
            });
            var render = /*Jade.request("s_c_o_p_e") ? window.top.document.body :*/window.document.body;
            var wrap = Easy.DOM.create({
                tag: 'div',
                cls: 'j-dailog-wrap',
                id: id,
                style: {
                    width: cfg.width,
                    height: cfg.height,
                    zIndex: (Jade.Dailog.zIndex += 3)
                },
                children: [{
                    tag: 'div',
                    cls: 'j-dailog',
                    children: [head, body, footer]
                }, {
                    tag: 'div',
                    cls: 'j-shadow'
                }]
            }, render);
            var center = function () {
                var scroll = Easy.getScroll();
                Easy.DOM.setStyle(wrap, {
                    left: (size.width - (cfg.width == "auto" ? wrap.offsetWidth : cfg.width)) / 2,
                    top: scroll.y + (size.height - cfg.height) / 2
                });
            }
            var oj = {
                id: id,
                wrap: wrap,
                el: cfg.el,
                center: center
            };
            if (cfg.iframe) {
                var iframe = Easy.DOM.create({
                    tag: 'iframe',
                    frameborder: '0',
                    cls: 'iframectl',
                    width: '100%',
                    height: '100%',
                    style: 'width:100%;height:100%',
                    src: cfg.iframe
                }, body);
            } else {
                if (elDom) {
                    oj["parentEl"] = Easy.DOM.getParent(elDom);
                    Easy.DOM.render(elDom, body);
                } else {
                    body.innerHTML = cfg.el
                }
            }
            Jade.CacheEl[id] = oj;

            if (Easy.DD) {
                new Easy.DD(wrap, null, head);
            }
            var size = Easy.getSize(),
            topPxl = Math.max((size.height - (cfg.height == "auto" ? wrap.offsetHeight : cfg.height)) / 2, 80);
            var msk = Easy.DOM.create({
                tag: 'div',
                style: {
                    position: "absolute",
                    top: 1,
                    left: 1,
                    height: document.body.scrollHeight - 1,
                    width: size.width - 1,
                    zIndex: Jade.Dailog.zIndex - 1,
                    background: "#ccc"
                },
                html: ''
            }, render);
            Easy.DOM.setOpacity(msk, 0.4);
            oj.msk = msk;

            Easy.DOM.setStyle(body, {
                height: cfg.height == "auto" ? 'auto' : cfg.height - 37 + (cfg._h ? cfg._h : 0)
            });
            center();
            return { wrap: wrap, footer: footer,
                body: body, id: id, center: center,
                width: cfg.width, height: cfg.height,
                close: function () {
                    Jade.Dailog.close(id.replace("dailog_", "")); if (Easy.isFunction(cfg.onClose)) {
                        cfg.onClose();
                    }
                },
                resize: function (w, h) {
                    Easy.DOM.setStyle(wrap, function () {
                        var s = {};
                        if (w) {
                            s["width"] = w;
                        }
                        if (h) {
                            s.height = h;
                        }
                        return s;
                    });
                    Easy.DOM.setStyle(body, function () {
                        var s = {};
                        if (h) {
                            s.height = h - 37 + (cfg._h ? cfg._h : 0);
                        }
                        return s;
                    });
                }
            };
        },
        createX: function (cfg) {
            var elDom = Easy.get(cfg.el), id, head;
            if (elDom) {
                id = "dailog_" + (cfg.el || cfg.id);
            } else {
                id = "dailog_" + (cfg.id || ++Jade.Dailog.zIndex);
            }
            var closeBtn = Easy.DOM.create({
                tag: 'a',
                dailogid: id,
                href: 'javascript:;'
            });
            Easy.DOM.on(closeBtn, "click", function (p) {
                if (cfg.el) {
                    var dlgs = Jade.CacheEl[Easy.DOM.getAttribute(p, "dailogid")];
                    Easy.DOM.render(Easy.get(cfg.el), dlgs.parentEl);
                    Easy.Object.remove(Jade.CacheEl, dlgs);
                }

                if (msk) {
                    Easy.removeNode(msk);
                }
                Easy.removeNode(wrap);
                if (Easy.isFunction(cfg.onClose)) {
                    cfg.onClose();
                }
            });
            var head = Easy.DOM.create({
                tag: 'h2',
                children: [{
                    tag: 'span',
                    html: cfg.title || '提示信息'
                }, closeBtn]
            });
            var body = Easy.DOM.create({
                tag: 'div',
                cls: 'j-dailog-body'
            });
            var footer = Easy.DOM.create({
                tag: 'div',
                cls: 'j-dailog-footer'
            });
            var render = /*Jade.request("s_c_o_p_e") ? window.top.document.body :*/window.document.body;
            var wrap = Easy.DOM.create({
                tag: 'div',
                cls: 'j-dailog-wrap',
                id: id,
                style: {
                    width: cfg.width,
                    height: cfg.height,
                    zIndex: (Jade.Dailog.zIndex += 3)
                },
                children: [{
                    tag: 'div',
                    cls: 'j-dailog',
                    children: [head, body, footer]
                }, {
                    tag: 'div',
                    cls: 'j-shadow'
                }]
            }, render);
            var center = function () {
                var scroll = Easy.getScroll();
                Easy.DOM.setStyle(wrap, {
                    left: (size.width - (cfg.width == "auto" ? wrap.offsetWidth : cfg.width)) / 2,
                    top: scroll.y + cfg.height
                });
            }
            var oj = {
                id: id,
                wrap: wrap,
                el: cfg.el,
                center: center
            };
            if (cfg.iframe) {
                var iframe = Easy.DOM.create({
                    tag: 'iframe',
                    frameborder: '0',
                    cls: 'iframectl',
                    width: '100%',
                    height: '100%',
                    style: 'width:100%;height:100%',
                    src: cfg.iframe
                }, body);
            } else {
                if (elDom) {
                    oj["parentEl"] = Easy.DOM.getParent(elDom);
                    Easy.DOM.render(elDom, body);
                } else {
                    body.innerHTML = cfg.el
                }
            }
            Jade.CacheEl[id] = oj;

            if (Easy.DD) {
                new Easy.DD(wrap, null, head);
            }
            var size = Easy.getSize(),
            topPxl = Math.max((size.height - (cfg.height == "auto" ? wrap.offsetHeight : cfg.height)) / 2, 80);
            var msk = Easy.DOM.create({
                tag: 'div',
                style: {
                    position: "absolute",
                    top: 1,
                    left: 1,
                    height: document.body.scrollHeight - 1,
                    width: size.width - 1,
                    zIndex: Jade.Dailog.zIndex - 1,
                    background: "#ccc"
                },
                html: ''
            }, render);
            Easy.DOM.setOpacity(msk, 0.4);
            oj.msk = msk;

            Easy.DOM.setStyle(body, {
                height: cfg.height == "auto" ? 'auto' : cfg.height - 37 + (cfg._h ? cfg._h : 0)
            });
            center();
            return { wrap: wrap, footer: footer,
                body: body, id: id, center: center,
                width: cfg.width, height: cfg.height,
                close: function () {
                    Jade.Dailog.close(id.replace("dailog_", "")); if (Easy.isFunction(cfg.onClose)) {
                        cfg.onClose();
                    }
                },
                resize: function (w, h) {
                    Easy.DOM.setStyle(wrap, function () {
                        var s = {};
                        if (w) {
                            s["width"] = w;
                        }
                        if (h) {
                            s.height = h;
                        }
                        return s;
                    });
                    Easy.DOM.setStyle(body, function () {
                        var s = {};
                        if (h) {
                            s.height = h - 37 + (cfg._h ? cfg._h : 0);
                        }
                        return s;
                    });
                }
            };
        }
    },

    actions: {

        /**
        * 返回
        */
        back: function () {
            var url;
            var hs = Jade.getCookie("historyArray");
            if (hs) {
                hs = Easy.decode(hs);
                var url = hs.pop();
            }
            if (url) {
                Jade.setCookie("historyArray", Easy.encode(hs));
                var iframe = top.document.getElementById("right");
                if (iframe) {
                    iframe.src = Easy.util.urlAppend(url, { r: new Date().getTime() });
                }
            } else {
                var iframe = top.document.getElementById("right");
                if (iframe) {
                    if (iframe && iframe.contentWindow)
                        iframe.contentWindow.history.back();
                }
            }
        },

        /**
        * url跳转
        * @param {} url 要跳转到
        * @param {} w 
        */
        redirect: function (url, w) {
            var iframe = window.parent.document.getElementById("right");
            iframe.src = Easy.util.urlAppend(url, { isRdt: true, r: new Date().getTime() });
        },

        /**
        * 根据主键删除数据, 后台必须是Remove 方法
        * @param {} grid 表格
        * @param {} classname 后台类名
        * @param {} primaryKey 主键名
        * @param {} isrealdelete 是否真删除
        * @param {} v 主键值
        */
        removeByID: function (grid, classname, primaryKey, isrealdelete, v) {
            var me = Jade;
            if (v && v.length > 0) {
                Jade.Msg.confirm("你确定要删除选中的" + v.length + "条数据吗？", function (cmd) {
                    if (cmd) {
                        me.ajax(classname, "Remove", { key: Easy.encode(v) }, function (d) {
                            if (!d.exception) {
                                grid.load();
                            } else {
                                Jade.Msg.error(d.message);
                            }
                        });
                    }
                });
            } else {
                Jade.Msg.error("请选择要删除的数据！");
            }
        },

        /**
        * 根据主键删除数据, 后台必须是Remove 方法
        * @param {} grid 表格
        * @param {} classname 后台类名
        * @param {} primaryKey 主键名
        * @param {} isrealdelete 是否真删除
        */
        remove: function (grid, classname, primaryKey, isrealdelete) {
            var v = grid.getValues(primaryKey);
            this.removeByID(grid, classname, primaryKey, isrealdelete, v);
        },

        /**
        * 根据主键删除数据
        * @param {} grid 表格
        * @param {} classname 后台类名
        * @param {} methodname 后台方法名
        * @param {} primaryKey 主键名
        * @param {} isrealdelete 是否真删除
        */
        removeByMethod: function (grid, classname, methodname, primaryKey, isrealdelete) {
            var me = Jade;
            var v = grid.getValues(primaryKey);
            if (v && v.length > 0) {
                Jade.Msg.confirm("你确定要删除选中的" + v.length + "条数据吗？", function (cmd) {
                    if (cmd) {
                        me.ajax(classname, methodname || "Remove", { key: Easy.encode(v) }, function (d) {
                            if (!d.exception) {
                                grid.load();
                            } else {
                                Jade.Msg.error(d.message);
                            }
                        });
                    }
                });
            } else {
                Jade.Msg.error("请选择要删除的数据！");
            }
        },

        createWin: function (grid, classname, primaryKey, cfg, isedit, methodname) {
            if (cfg.el) {
                var form = Easy.get(cfg.el).getElementsByTagName("form")[0];
                Jade.actions.resetForm(form);
                var v;
                if (grid) {
                    v = grid.getValues(primaryKey);
                }
                if (isedit) {
                    if (v && v.length == 1) {
                        Jade.Dailog.create({
                            title: cfg.title || '弹出框',
                            width: cfg.width,
                            height: cfg.height,
                            onClose: cfg.onClose,
                            el: cfg.el
                        });
                        Easy.Ajax.post({
                            url: Jade.url,
                            params: {
                                classname: classname.replace(/\+/g, "Server"),
                                methodname: methodname || "GetByID",
                                id: v[0]
                            },
                            success: function (r) {
                                var o = Easy.decode(r);
                                if (o) {
                                    Easy.Form.setRecord(form, o);
                                    if (Easy.isFunction(cfg.callback)) {
                                        cfg.callback.call(form, o);
                                    }
                                }
                            }
                        });
                    } else {
                        Jade.Msg.error("请选择要修改的数据！");
                    }
                } else {
                    Jade.Dailog.create({
                        title: cfg.title || '弹出框',
                        width: cfg.width,
                        height: cfg.height,
                        onClose: cfg.onClose,
                        el: cfg.el
                    });
                    if (Easy.isFunction(cfg.callback)) {
                        cfg.callback.call(form);
                    }
                }
            } else {
                Jade.Dailog.create({
                    title: cfg.title || '弹出框',
                    width: cfg.width,
                    height: cfg.height,
                    iframe: cfg.el,
                    onClose: cfg.onClose
                });
            }
        },

        /**
        * 重置表单
        * @param {} form 要重置的表单
        */
        resetForm: function (form) {
            var values = Jade.FormData[form.id] || {};
            Easy.each(Easy.Array.toArray(form), function (el, i) {
                clearError(el);
                if ((el.tagName.toLowerCase() == "textarea" || el.tagName.toLowerCase() == "input") && el.type != "radio" && el.type != "checkbox") {
                    el.value = values[el.name];
                }
                if (!Easy.supports.placeholder) {
                    placeholder = Easy.DOM.getAttribute(el, "placeholder");
                    if (placeholder) {
                        if (el.value == "") {
                            el.value = placeholder;
                            Easy.DOM.addClass(el, "e-placeholder");
                        }
                    }
                }
            });
        },

        /**
        * 保存表单
        * @param {} form 要保存的表单
        * @param {} classname 后台类名
        * @param {} methodname 后台方法名
        * @param {} grid 表格
        * @param {} domid 弹出的窗口ID
        * @param {} cb 保存成功后的回调
        * @param {} pms 传给后台的参数
        */
        save: function (form, classname, methodname, grid, domid, cb, pms) {
            var kv = Easy.Form.getValues(form);
            if (kv) {
                Easy.apply(kv, pms || {});
                Jade.ajax(classname.replace(/\+/g, "Server"), methodname, kv, function (o) {
                    if (!o.exception) {
                        Jade.Msg.alert("保存成功！", function () {
                            if (grid) {
                                grid.load();
                            }
                            if (cb) {
                                cb(o);
                            }
                            if (domid) {
                                Jade.Dailog.close(domid);
                            }
                        });
                    } else {
                        Jade.Msg.error(o.message);
                    }
                });
            }
        },

        /**
        * 审核数据, 后台方法必须是Audit
        * @param {} grid 表格
        * @param {} cn 后台类名
        * @param {} pk 主键字段名
        * @param {} status 要更新的状态
        */
        audit: function (grid, cn, pk, status) {
            var ids = Jade.getGridIds(grid, pk);
            if (ids) {
                Jade.Msg.confirm("确定要修改选择" + ids.length + "条数据的状态吗？", function (b) {
                    if (b) {
                        Jade.ajax(cn, "Audit", {
                            key: Easy.encode(ids),
                            status: status
                        }, function (o) {
                            if (!o.exception) {
                                Jade.Msg.alert("审核状态修改成功！", function () {
                                    if (grid) {
                                        grid.load();
                                    }
                                });
                            } else {
                                Jade.Msg.error(o.message);
                            }
                        });
                    }
                })
            }
        }
    },
    /**
    * 获取文本在html里的长度
    * @param {} tag 要测试长度的标签名称
    * @param {} txt 要测试长度的文本
    * @param {} cls 要测试长度文本的样式
    * @return {}
    */
    getTxtInnerWidth: function (tag, txt, cls) {
        var txw = Easy.DOM.create({
            tag: tag || "div",
            cls: cls,
            html: txt,
            style: {
                visibility: "hidden"
            }
        }, Easy.getBody());
        setTimeout(function () {
            Easy.removeNode(txw);
        }, 300);
        var w = Easy.DOM.getWidth(txw), l = Easy.DOM.getStyle(txw, "paddingLeft"), r = Easy.DOM.getStyle(txw, "paddingRight"),
		bl = Easy.DOM.getStyle(txw, "borderLeftWidth"), br = Easy.DOM.getStyle(txw, "borderRightWidth");

        return w - l - r - bl - br;
    },
/**
    * 根据时间获取和当前时间的时间差
    * @param {} date 比较的时间
    **/
    getDate: function (date) {
        var dnow = new Date() - new Date(date);
        var d = parseInt(dnow / 1000 / 60 / 60 / 24);
        var h = parseInt(dnow / 1000 / 60 / 60);
        var m = parseInt(dnow / 1000 / 60);
        var s = parseInt(dnow / 1000);
        if (d > 3) {
            return Easy.Date.format(new Date(date), "yyyy-MM-dd");
        }
        else if (d > 0) {
            return d + "天前";
        }
        else if (d == 0 && h > 0) {
            return h + "小时前";
        }
        else if (d == 0 && h == 0 && m > 0) {
            return m + "分钟前";
        }
        else if (d == 0 && h == 0 && m == 0 && s > 0) {
            return "刚刚";
        }
        return "";
    }
};

var editBodyHeight = 400;
Easy.ready(function () {
    if (top && top.document) {
        var iframe = top.document.getElementById("right");
        if (iframe) {
            editBodyHeight = iframe.offsetHeight - 55;
            var height = iframe.offsetHeight - 45;
            Jade.pageSize = Math.floor(height / 30) - 3;
        }
    }
    var qbar = Easy.get("_querybar");
    if (qbar) {
        var cn = Easy.DOM.getChildren(qbar);
        var t = cn[1];
        if (t) {
            Easy.DOM.setAttributes(t, { title: "点击展开查询！" });
            var isover = false;
            var timer;
            Easy.on(t, "mouseover", function (p, e) {
                isover = true;
                timer = setTimeout(function () {
                    if (isover) {
                        if (Easy.DOM.hasClass(qbar, "querybar")) {
                            Easy.DOM.show(cn[0]);
                            Easy.DOM.addClass(t, "exp");
                        } else {
                            Easy.DOM.hide(cn[0]);
                            Easy.DOM.removeClass(t, "exp");
                        }
                        Easy.DOM.removeClass(qbar, "querybar");
                        Easy.DOM.addClass(qbar, "expquerybar");
                    }
                }, 500);
            });
            Easy.on(t, "mouseout", function (p, e) {
                isover = false;
                clearTimeout(timer);
            });
            Easy.on(t, "click", function (p, e) {
                if (Easy.DOM.hasClass(qbar, "querybar")) {
                    Easy.DOM.show(cn[0]);
                    Easy.DOM.addClass(t, "exp");
                } else {
                    Easy.DOM.hide(cn[0]);
                    Easy.DOM.removeClass(t, "exp");
                }
                Easy.DOM.toggleClass(qbar, "querybar");
                Easy.DOM.toggleClass(qbar, "expquerybar");
            });
        }
    }
});

if (!Easy.UI) {
    Easy.UI = { Manage: {} };
}
