﻿//辅助JS

//获取URL参数
function QueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]); return "";
}
//替换URL参数
String.prototype.replaceParam = function (param, value) {
    var url = this;
    var pattern = param + '=([^&]*)';
    var replaceText = param + '=' + value;
    if (url.match(pattern)) {
        var tmp = '/(' + param + '=)([^&]*)/gi';
        tmp = url.replace(eval(tmp), replaceText);
        return tmp;
    } else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        } else {
            return url + '?' + replaceText;
        }
    }
    return url + '\n' + param + '\n' + value;
}

//在图片名称前加入一个字符，得到缩略图的地址
function SmallImageFilePath(imagefile, smallstring) {
    var stem = "";
    if ($.trim(imagefile) != "") {
        var str = imagefile.split("/");
        for (var i = 0; i < str.length; i++) {
            //最后一个
            if (str.length != 0 && i == str.length - 1) {
                stem += smallstring + str[i];
            }
            else {
                stem += str[i] + "/";
            }
        }
    }
    return stem;
}

//字符串转时间
String.prototype.ToDate = function () {
    var str = this.replace("T", " ").replace(new RegExp("-", "gm"), "/");
    if (str.indexOf(".") != -1) str = str.substr(0, str.indexOf("."));
    return new Date(str);
}
//设置时间format
Date.prototype.Format = function (format) {
    /* 
    * eg:format="yyyy-MM-dd hh:mm:ss"; 
    */
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //hour
        "H+": this.getHours(), // hour  
        "m+": this.getMinutes(), // minute  
        "s+": this.getSeconds(), // second  
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter  
        "S": this.getMilliseconds()
        // millisecond  
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

//设置cookie
function setCookie(cname, cvalue, date) {
    if (date) {
        var d = new Date();
        d.setDate(d.getDate() + date);
        var expires = "expires=" + d.toGMTString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;";
    }
    else {
        document.cookie = cname + "=" + cvalue + ";path=/;";
    }
}
//读取cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return null;
}
//删除cookie
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/;";
}

//html编码/解码
function HtmlEncode(str) {
    var t = document.createElement("div");
    t.textContent ? t.textContent = str : t.innerText = str;
    return t.innerHTML;
}
function HtmlDecode(str) {
    var t = document.createElement("div");
    t.innerHTML = str;
    return t.innerText || t.textContent;
}

//过滤json特殊字符
function filterJson(str) {
    return str.replace(new RegExp("\\", "gm"), "\\\\").replace(new RegExp("\"", "gm"), "\\\"").replace(new RegExp("\n", "gm"), "\\n").replace(new RegExp("\r", "gm"), "\\r");
}
function filterJson2(str) {
    return str.replace(new RegExp("\\\"", "gm"), "\"").replace(new RegExp("\\\\", "gm"), "\\").replace(new RegExp("\\n", "gm"), "\n").replace(new RegExp("\\r", "gm"), "\r");
}

//复制字符串
function copyStr(str) {
    var $str = $("<input type=\"text\" id=\"copyStr\" value=\"" + str.replace(/"/g, "&quot;") + "\" />").appendTo("body").select();
    document.execCommand("Copy");
    $str.remove();
    top.layer.msg("复制成功！", { icon: 6 });
}

//获取表单数据
function getFormData(obj) {
    var formObj = obj ? obj : $("form");
    //对编辑器内容进行转码
    formObj.find("textarea.RichEditor_editor").each(function () {
        $(this).val(encodeURIComponent(tinyMCE.editors[$(this).attr("name")].getContent()));
    })
    formObj.find("textarea.CodeMirror_editor").each(function () {
        $(this).val(encodeURIComponent(eval("(" + $(this).attr("name") + "_editor.getValue())")));
    })
    var formData = {};
    var fieldElem = formObj.find("input,select,textarea"); //获取所有表单域
    fieldElem.each(function () {
        if (!this.name) return;
        if (/^checkbox|radio$/.test(this.type) && !this.checked) return;
        if (!formData[this.name]) formData[this.name] = $(this).attr("encoding") != undefined ? encodeURIComponent($(this).val()) : $(this).val();
    })
    return formData;
}
function ajaxHelper(url, data, successCallback) {
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        headers: {
            token: $("#token").val()
        },
        success: function (data, textStatus) {
            if (successCallback) successCallback(data, textStatus);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.closeAll("loading");
        }
    });
}
//ajax提交
function ajaxSubmit(url, successCallback) {
    ajaxHelper(url, getFormData(), successCallback);
}
//ajax操作执行提示
function ajaxPrompt(url, data, options) {
    layer.load(1);
    ajaxHelper(url, data, function (data) {
        try {
            var res = JSON.parse(data);

            if (!options) options = {};
            //若未自定义成功提示，则采用默认设置
            if (!options["1"]) {
                options["1"] = function () {
                    top.layer.msg(res.msg, { icon: 6 });
                }
            }
            //若未自定义失败提示，则采用默认设置
            if (!options["-1"]) {
                options["-1"] = function () {
                    top.layer.msg(res.msg, { icon: 5 });
                }
            }
            //执行提示
            if (options[res.flag]) {
                options[res.flag](res);
            }
            else {
                //其他提示
                top.layer.msg(res.msg, { icon: 7 });
            }
        } catch (e) {
            $("body").append(data);
        }
        layer.closeAll("loading");
    });
}

//加法
function add(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
}
//减法
function sub(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) - mul(b, e)) / e;
}
//乘法
function mul(a, b) {
    var c = 0,
        d = a.toString(),
        e = b.toString();
    try {
        c += d.split(".")[1].length;
    } catch (f) { }
    try {
        c += e.split(".")[1].length;
    } catch (f) { }
    return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}
//除法
function div(a, b) {
    var c, d, e = 0,
        f = 0;
    try {
        e = a.toString().split(".")[1].length;
    } catch (g) { }
    try {
        f = b.toString().split(".")[1].length;
    } catch (g) { }
    return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
}
//四舍五入
function toDecimal(num, pos) {
    return Math.round(num * Math.pow(10, pos)) / Math.pow(10, pos);
}
//判断是否是数字
function isNumber(str) {
    return !isNullOrEmpty(str) && !isNaN(str.toString());
}
//判断null或空值
function isNullOrEmpty(str) {
    return str == undefined || str == null || str == '' || str == 'null';
}

//前台弹窗
function windowDialog(url, title, width, height) {
    //计算宽度
    if (width.indexOf("%") != -1) {
        width = $(window).width() * parseFloat(width.replace("%", "")) / 100 + "px";
    }
    //计算高度
    if (height.indexOf("%") != -1) {
        height = $(window).height() * parseFloat(height.replace("%", "")) / 100 + "px";
    }
    var node = "";
    node += "<div class=\"popMid\" style=\"display:block;\">";
    node += "<div class=\"bg\">";
    node += "<div class=\"cell\">";
    node += "<div class=\"midBox white radius\">";
    node += "<label class=\"close trans\">×</label>";
    //设置标题
    if (title) {
        node += "<div class=\"tit\">" + title + "</div>";
    }
    node += "<div class=\"box\" style=\"width: " + width + "; height: " + height + ";\">";
    node += "<iframe src=\"" + url + "\"></iframe>";
    node += "</div>";
    node += "</div>";
    node += "</div>";
    node += "</div>";
    node += "</div>";
    $("body").append(node);

    //添加关闭事件
    $(".popMid .close").click(function () {
        $(this).closest(".popMid").remove();
    })
}
