/**
 *  网站共用的基础方法
 *    @author kenny
 */
(function ($) {

    Date.prototype.format = function (fmt) { //author: meizz
        fmt = fmt || "";
        fmt = fmt.replace(/Y/ig, "y").replace(/H/ig, "h").replace(/D/ig, "d").replace(/S/ig, "s");
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    var Module = {
        /** 取环境
         local: 本地环境,静态.json假数据
         production: 生成环境
         */
        getEnvironment: function () {
            var config = parent.gConfig || gConfig || {};
            return config.environment || "production";
        },
        /**
         * 弹出窗口
         param:{
				url: //页面地址
				checkLogin: //是否需要验证页面登录,true=需要,默认需要, false=不需要

			}
         */
        popWindow: function (param) {
            param = param || {};
            var url = param.url;
            var checkLogin = param.checkLogin != false;
            if (/\?/.test(url)) {
                url += "&" + new Date().getTime();
            } else {
                url += "?" + new Date().getTime();
            }
            param.closeBtn = param.closeBtn || [0, true];
            var pop = function () {//检测用户登录
                parent.seajs.use("lib/jquery/layer", function () {
                    var layer = parent.__popWindowId;
                    parent.__popWindowId = parent.$.layer({
                        type: 2,
                        shade: [0.2, '#000'],
                        shadeClose: false,//点击背影关闭
                        closeBtn: param.closeBtn,
                        fix: false,
                        title: (param.title != null) ? param.title : '&nbsp;',
                        iframe: {
                            src: getBaseUrl() + url
                        },
                        area: [param.width || '400px', param.height || '390'],
                        border: [1, 1, '#ccc'],
                        close: function (index) {
                            param.callback && param.callback(index);
                        }
                    });
                    //设置firame的位置,防止偶尔出现被标题给遮住一部份
                    $(".xubox_iframe").css({
                        top: "50px"
                    }).on({
                        load: function () {
                            $(".xubox_iframe").css({
                                top: "50px"
                            });
                        }
                    });
                    try {
                        parent.$("#xubox_layer" + layer + ", #xubox_shade" + layer).hide();
                        //parent.layer.close(layer);
                    } catch (e) {
                    }
                });
            }
            if (checkLogin) {
                seajs.use("dbfen/client/api/user", function (User) {//取登录模块
                    User.checkLogin(function (user) {//检测登录
                        if (!user) {//用户登录没有成功或没有登录
                            console.log("用户登录没有成功或没有登录");
                            return;
                        }
                        ;
                        pop();
                    }, {
                        isShow: true
                    });
                });
            } else {
                pop();
            }
        },
        /**
         ajax方法封装,需要用户登录才能调用,, 如果用户没有登录,会弹出登录界面
         */
        ajaxLogin: function (param) {
            seajs.use("dbfen/client/api/user", function (User) {
                User.checkLogin(function (user) {//检测用户登录
                    if (!user) {
                        console.log("登录失败");
                        var callback = param.success || param.error;
                        callback && callback({code: 2001, msg: "用户未登录"});
                        return;//用户登录没有成功或没有登录
                    }
                    Module.ajax(param);
                }, {
                    isShow: true
                });
            });
        },
        /**
         * 封装ajax请求
         */
        ajax: function (param) {
            var funError = param.error;
            param.dataType = param.dataType || "json";
            param.type = param.type || 'POST';
            param.timeout = param.timeout || gConfig.timeout * 1000;
            param.cache = param.cache == null ? false : param.cache;
            param.error = function (e) {
                console.error('[ERROR][' + param.url + ']:', e.stack, e);
                if (funError) {
                    funError(e);
                } else {
                    //param.success && param.success({code:1, msg:"请求信息异常",error: e});
                }
            }
            if (Module.getEnvironment() == "local") {//本地环境,走json的测试数据
                param.type = "GET";
                param.url = "/testdata/" + param.url + ".json";
            }
            param.url = param.url + (/\?/.test(param.url) ? "&t=" : "?t=") + new Date().getTime();
            $.ajax(param);
        },
        /**
         *    把url序列化为对象
         *    如: name=kenny&age=22&sex=1 => {name:"kenny", age: 22, sex: 1};
         */
        serialize: function (search) {
            search = (search || "").replace(/^\s*\?/, "");
            var arrs = search.split("&");
            var result = {};
            for (var i in arrs) {
                var vals = arrs[i].split("=");
                result[vals[0]] = decodeURIComponent(vals[1]);
            }
            return result;
        },
        /** *
         *
         */
        getParam: function () {
            var search = location.search.replace(/^\s*\?/, "");
            return Module.serialize(search);
        },
        /**
         * 格式化字节大小,自动转到最接近的单位显示
         * value: 大小
         */
        formatByte: function (value) {
            if (value == 0) return 0;
            var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
            var srcsize = parseFloat(value);
            var index = Math.floor(Math.log(srcsize) / Math.log(1024));
            var size = srcsize / Math.pow(1024, index);
            size = (size + "").replace(/\.\d+$/, function (val) {
                return val.substring(0, 3);
            });
            return size + unitArr[index];
        },
        formatDate: function (value, format) {
            var date = value;
            if (!(value instanceof Date)) {
                date = new Date(date);
            }
            return date.format("yyyy-MM-dd hh:mm:ss");
        },
        /** 判断是否支持浏览器,ie6,7不支持 */
        isSupportBrowser: function () {
            var version = getIEVersion();
            if (/Internet Explorer/.test(navigator.appName) && version < 8) {
                return false;
            }
            return true;
        },
        isLocalhost: function (val) {
            return val == null || val == "" || val == "127.0.0.1" || val.toLocaleLowerCase() == "localhost"
        },
        /** 弹出html页面显示 */
        popPage: function (domId, param) {
            var pageId = $.layer({
                type: 1,
                border: [0],
                closeBtn: [0],
                shadeClose: true,
                title: false,
                fix: false,
                offset: ['', ''],
                border: false,
                area: [param.width || '100%', param.height || '100%'],
                page: {
                    dom: domId
                }
            });
            $("#xubox_layer" + pageId).css({
                top: "0px"
            });
            return pageId;
        },
        en: function (str) {
            str = (str || "").trim();
            if (str == "")return str;
            return (function (j) {
                function f(i) {
                    function c(u) {
                        u = (u || "").trim();
                        var r = $.base64.encode(u);
                        var t = u.length;
                        var o = t.toString(16);
                        var q = r.substring(0, parseInt(t / 2));
                        var p = r.substring(parseInt(t / 2));
                        var v = p.substring(0, 2);
                        v = v + "" + p.substring(2, 3) + "";
                        o = o.length < 2 ? ("0" + o) : o;
                        v = v + o + "" + q + p.substring(3);
                        return v
                    }

                    return c(i)
                }

                var b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", m = "", k = [256], e = [256], g = 0;
                var d = {
                    encode: function (c) {
                        var i = c.replace(/[\u0080-\u07ff]/g, function (o) {
                            var n = o.charCodeAt(0);
                            return String.fromCharCode(192 | n >> 6, 128 | n & 63)
                        }).replace(/[\u0800-\uffff]/g, function (o) {
                            var n = o.charCodeAt(0);
                            return String.fromCharCode(224 | n >> 12, 128 | n >> 6 & 63, 128 | n & 63)
                        });
                        return i
                    }, decode: function (i) {
                        var c = i.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, function (o) {
                            var n = ((o.charCodeAt(0) & 15) << 12) | ((o.charCodeAt(1) & 63) << 6) | (o.charCodeAt(2) & 63);
                            return String.fromCharCode(n)
                        }).replace(/[\u00c0-\u00df][\u0080-\u00bf]/g, function (o) {
                            var n = (o.charCodeAt(0) & 31) << 6 | o.charCodeAt(1) & 63;
                            return String.fromCharCode(n)
                        });
                        return c
                    }
                };
                while (g < 256) {
                    var h = String.fromCharCode(g);
                    m += h;
                    e[g] = g;
                    k[g] = b.indexOf(h);
                    ++g
                }
                function a(A, v, o, y, u, t) {
                    A = String(A);
                    var p = 0, r = 0, n = A.length, z = "", x = 0;
                    while (r < n) {
                        var w = A.charCodeAt(r);
                        w = w < 256 ? o[w] : -1;
                        p = (p << u) + w;
                        x += u;
                        while (x >= t) {
                            x -= t;
                            var q = p >> x;
                            z += y.charAt(q);
                            p ^= q << x
                        }
                        ++r
                    }
                    if (!v && x > 0) {
                        z += y.charAt(p << (t - x))
                    }
                    return z
                }

                var l = $.base64 = function (i, c, n) {
                    return c ? l[i](c, n) : i ? null : this
                };
                l.btoa = l.encode = function (c, i) {
                    c = l.raw === false || l.utf8encode || i ? d.encode(c) : c;
                    c = a(c, false, e, b, 8, 6);
                    return c + "====".slice((c.length % 4) || 4)
                };
                l.atob = l.decode = function (o, c) {
                    o = String(o).split("=");
                    var n = o.length;
                    do {
                        --n;
                        o[n] = a(o[n], true, k, m, 6, 8)
                    } while (n > 0);
                    o = o.join("");
                    return l.raw === false || l.utf8decode || c ? d.decode(o) : o
                };
                return f(j)
            })(str);
        },
        de: function (str) {
            str = (str || "").trim();
            if (str == "")return str;
            Module.en(str);
            return $.base64.decode(str);
        },
        /*字符串转化（反斜杠转正斜杠）*/
        antiEscape: function (str) {
            str = (str || "").trim();
            str = str.replace(/\\/g,'/');
            return str;
        },
        /*字符串转化（正斜杠转反斜杠）*/
        justEscape: function (str) {
            str = (str || "").trim();
            str = str.replace(/\//g,'\\');
            return str;
        }
    };

    function getIEVersion() {
        var browser = navigator.appName;
        var b_version = navigator.appVersion;
        var versions = b_version.split(";");
        var version = parseInt((versions[1] || "").replace(/[ ]*/g, "").replace(/[^\d\.]*/g, ""));
        var isIE = !!window.ActiveXObject && browser == "Microsoft Internet Explorer";
        if (isIE) {
            return version;
        }
    };

    /*调用css*/
    $.getCss = function (url) {
        var node = document.createElement("link");
        node.href = url;
        node.async = "async";
        node.rel = "stylesheet";
        node.text = "text/css";
        document.body.appendChild(node);
        return node
    };

    define("dbfen/client/com/dbfen", function (require, exports, module) {
        module.exports = Module;
    });

    window.dbfen = Module;
})(jQuery);