﻿/**
*验证数字
*/
String.prototype.isNumber = function() {
    var patrn = new RegExp("^[0-9]+$");
    return patrn.test(this);
}
/**
*匹配中文
*/
String.prototype.isChinese = function(minLength, maxLength) {
    var patrn = new RegExp("/^[\u4e00-\u9fa5]{" + minLength + "," + maxLength + "}$/");
    return patrn.test(this);
}

/**
*匹配网址 
*/
String.prototype.isUrl = function() {
    var patrn = new RegExp("^(http|https|ftp|rtsp|mms)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9]{2,4}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\\'/\\\\\\+&%\\$#\\=~\(\)\u4e00-\u9fa5])*$");
    return patrn.test(this);
}
/*替换回车字符串为HTML格式的回车符号*/
String.prototype.format = function() {
    var temp = this.replace(new RegExp("\r\n", "gm"), "\n").replace(new RegExp("\r", "gm"), "\n"); 
    return temp.replace(new RegExp("\n", "gm"), "<br />");
}
/*textarea中回车字符串编码*/
String.prototype.encodeEnter = function() {
    return this.replace(/\n/gm, '#enter#');
}
/*textarea中回车字符串还原*/
String.prototype.decodeEnter = function() {
    return this.replace(/#enter#/gm, '\n');
}
/*强制换行*/
String.prototype.breakWord = function() {
    var str = "";
    str += this;
    var lineLength = 15; //每行字节数
    if (str.length <= lineLength) {
        return str;
    } else {
        var strProcessed = ""; //已处理缓存
        var strProcessCache = str; //待处理缓存
        var strResult = ""; //处理结果
        var strCache = ""; //处理缓存
        var regEmot = /{\w{1,2}}/g;
        var regCHN = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;
        var regSpace = /\s/g;
        var regHtml = /<\/?.+?>/g;
        while (strProcessCache.length > 0) {
            strCache = strProcessCache.substr(0, lineLength); //初始化待处理缓存
            strProcessed += strCache; //更新已处理缓存
            strProcessCache = str.substr(strProcessed.length, str.length); // 刷新待处理缓存
            if (regEmot.test(strCache) || regCHN.test(strCache) || regSpace.test(strCache) || regHtml.test(strCache))
                strResult += strCache;
            else {
                var has = true;
                var last = strCache.lastIndexOf('{');
                var first = strProcessCache.indexOf('}');
                if (last > 0 && last > strCache.length - 4 && first < 3) {
                    strCache += strProcessCache.substring(0, first + 1);
                    strProcessed += strProcessCache.substring(0, first + 1);
                    strProcessCache = strProcessCache.substr(first + 1, strProcessCache.length)
                } else {
                    has = false;
                }
                last = strCache.lastIndexOf('<');
                var first = strProcessCache.indexOf('>');
                if (last > -1 && first > -1) {
                    strCache += strProcessCache.substring(0, first + 1);
                    strProcessed += strProcessCache.substring(0, first + 1);
                    strProcessCache = strProcessCache.substr(first + 1, strProcessCache.length)
                    has = true;
                } else {
                    has = false;
                }
                if (!has) strCache += '<wbr />'
                strResult += strCache;
            }
        }
        return strResult;
    }
}
/*截断字符串*/
String.prototype.getPreWord = function(maxLength) {
    var str = this;
    var result = "";
    var minLength = 0;
    var j=0;
    if (str.CHNLength() > maxLength) {
        for (var i = 0; i < maxLength; i++) {
            var charStr = str.charAt(j);
            if (charStr.CHNLength() == 2) { i++; }
            j++; minLength++;
        }
        if(str==str.substring(0, (minLength))){
            result = str;
        }
        else {
            result = str.substring(0, (minLength)) + "...";
        }
    }
    else {
        result = str;
    }
    return result;
}
/*获取URL地址内指定的参数值*/
String.prototype.getURLParamValue = function(name) {
    var list = this.split('?');
    if (list.length == 2) {
        list = list[1].split('&');
        for (var i = 0; i < list.length; i++) {
            var temp = list[i].split('=');
            if (temp.length == 2) {
                if (temp[0] == name) {
                    return temp[1];
                }
            }
        }
    }
    return "";
}
/**
*匹配邮箱
*/
String.prototype.isMail = function() {
    var patrn = new RegExp("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
    return patrn.test(this);
}
String.prototype.chkPassword = function() {
    var match = this.match(new RegExp(/^[a-zA-Z0-9!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\=\>\?\@\[\\\]\^\_]{6,16}$/gi));
    return match != null;

}
String.prototype.withoutEnter = function() {
    var temp = this.replace(new RegExp("\r\n", "gm"), "\n");
    return temp.replace(new RegExp("\n", "gm"), "");
}
String.prototype.showLength = function(lenNum) {
    var i, len = 0, temp = "", str = this;
    for (i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) { len += 2; }
        else { len += 1; }
        if (len > lenNum && i < this.length) {
            temp += "..";
            break;
        }
        else { temp += str.substring(i,i+1); }
    }
    return temp;
}
/**
将两个或者两个以上的空格合并成一个
**/
String.prototype.mergeSpace = function() {
    return this.replace(/\s{2,}/g, " ");
}
/**
将字符串中的空格去掉
**/
String.prototype.deleteSpace = function() {
    return this.replace(/\s/g, "");
}
String.prototype.isNum = function() {
    var match = this.match(new RegExp(/^[1-9]{1}\d{0,10}$/gi));
    return match != null;
}
/**
*验证长度
*/
String.prototype.isLength = function(minLength, maxLength) { //验证长度
    if (this.length >= minLength && this.length <= maxLength) {
        return true;
    } else {
        return false;
    }
}
/**
*验证中文长度,一个中文相当于两个英文
*/
String.prototype.isCHNLength = function(minLength, maxLength) { //验证中文长度
    var str = this.replace(/[^\x00-\xFF]/g, '**');
    return str.isLength(minLength, maxLength);
}
/**
*获取中文长度,一个中文相当于两个英文
*/
String.prototype.CHNLength = function() {
    return this.replace(/[^\x00-\xFF]/g, '**').length;
}
String.prototype.trim = function() { return this.replace(/^\s*/, "").replace(/\s*$/, ""); }
/**
*验证身份证
*/
String.prototype.checkIdCardNum = function() {
    var sex = 1; // 1 男 0 女
    var birthday = "";
    if (this.length == 15) {
        var Match = this.match(new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/));
        if (Match != null) {
            var D = new Date("19" + Match[3] + "/" + Match[4] + "/" + Match[5]);
            IsValid = D.getYear() == Match[3] && (D.getMonth() + 1) == Match[4] && D.getDate() == Match[5];
            if (IsValid) {
                birthday = "19" + Match[3] + "-" + Match[4] + "-" + Match[5];
                sex = (Match[6] % 2 == 1);
                return birthday + "|" + sex;
            }
            else return "";
        } else {
            return "";
        }

    }
    else if (this.length == 18) {
        var Match = this.match(new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d|[a-zA-Z])$/));
        if (Match != null) {
            var D = new Date(Match[3] + "/" + Match[4] + "/" + Match[5]);
            IsValid = D.getFullYear() == Match[3] && (D.getMonth() + 1) == Match[4] && D.getDate() == Match[5];
            if (IsValid) {
                if (CalculatePaperNum(this) == "X") { if (Match[7] != "x" && Match[7] != "X") { IsValid = false; } }
                else { if (Match[7] != CalculatePaperNum(this)) { IsValid = false; } }
            }
            if (IsValid) {
                birthday = Match[3] + "-" + Match[4] + "-" + Match[5];
                sex = (Match[6] % 2 == 1);
                return birthday + "|" + sex;
            }
            else return "";
        } else {
            return "";
        }
    } else {
        return "";
    }
}
//生成18位身份证号最后一位校验码
function CalculatePaperNum(str) {
    var PaperNumPowerArray = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    var Sum = 0;
    for (var i = 0; i < 17; i++) {
        Sum += PaperNumPowerArray[i] * parseInt(str.substring(i, i + 1));
    }
    var Index = 12 - Sum % 11;
    if (Index > 10) { Index = Index - 11; }
    if (Index == 10) { return "X"; } else { return "" + Index; }
}
//缩短网址
String.prototype.sortUrl = function(maxLength) {
    var str = this;
    if (this.length <= maxLength) {
        return str;
    } else {
        var res = str.substr(0, Math.floor(maxLength / 2));
        res += "..."
        res += str.substring((str.length - Math.floor(maxLength / 2)), str.length);
        return res;
    }
}
/**
*校验字符串是否为日期型
*返回值：
*如果为空，定义校验通过，           返回true
*如果字串为日期型，校验通过，       返回true
*如果日期不合法，                   返回false    参考提示信息：输入域的时间不合法！（yyyy-MM-dd）
*/
String.prototype.IsValidDate = function() {
    //如果为空，则通过校验
    if (this == "")
        return true;
    var pattern = /^((\d{4})|(\d{2}))-(\d{1,2})-(\d{1,2})$/g;
    if (!pattern.test(this))
        return false;
    var arrDate = this.split("-");
    if (parseInt(arrDate[0], 10) < 100)
        arrDate[0] = 2000 + parseInt(arrDate[0], 10) + "";
    var date = new Date(arrDate[0], (parseInt(arrDate[1], 10) - 1) + "", arrDate[2]);
    if (date.getYear() == arrDate[0]
       && date.getMonth() == (parseInt(arrDate[1], 10) - 1) + ""
       && date.getDate() == arrDate[2])
        return true;
    else
        return false;
}

//去掉字符串中的所有html标签
String.prototype.DelAllHtmlTag = function() {
    return this.replace(/<\/?.+?>/g, "");
}

//删除数组中的下标为dx的数据
Array.prototype.remove = function(dx) {
    if (isNaN(dx) || dx > this.length) { return false; }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i]
        }
    }
    this.length -= 1
}
/**
*校验两个日期的先后
*返回值：
*如果其中有一个日期为空，校验通过,          返回true
*如果起始日期早于等于终止日期，校验通过，   返回true
*如果起始日期晚于终止日期，                 返回false    参考提示信息： 起始日期不能晚于结束日期。
*/
this.checkDateEarlier=function(strStart, strEnd) {
    // if(checkIsValidDate(strStart) == false || checkIsValidDate(strEnd) == false)
    // return false;
    //如果有一个输入为空，则通过检验
    if ((strStart == "") || (strEnd == "") || (strStart == null) || (strEnd == null))
        return true;
    var arr1 = strStart.split("-");
    var arr2 = strEnd.split("-");
    var date1 = new Date(arr1[0], parseInt(arr1[1].replace(/^0/, ""), 10) - 1, arr1[2]);
    var date2 = new Date(arr2[0], parseInt(arr2[1].replace(/^0/, ""), 10) - 1, arr2[2]);
    if (arr1[1].length == 1)
        arr1[1] = "0" + arr1[1];
    if (arr1[2].length == 1)
        arr1[2] = "0" + arr1[2];
    if (arr2[1].length == 1)
        arr2[1] = "0" + arr2[1];
    if (arr2[2].length == 1)
        arr2[2] = "0" + arr2[2];
    var d1 = arr1[0] + arr1[1] + arr1[2];
    var d2 = arr2[0] + arr2[1] + arr2[2];
    if (parseInt(d1, 10) > parseInt(d2, 10))
        return false;
    else
        return true;
}
//将|分隔的字符串转为数组
this.stirngTransfer3 = function(_str) {
    var array = new Array();
    var temp = _str;
    var str = temp.split('|');
    for (i = 0; i < str.length - 1; ++i) {
        if (str[i] != "")
            array.push(str[i]);
    }
    return array;
}
//将,分隔的字符串转为数组并去除重复数据
this.stirngTransfer = function(_str) {
    var array = new Array();
    var temp = _str;
    var str = temp.split(',');
    for (i = 0; i < str.length - 1; ++i) {
        if (str[i] != "")
            array.push(str[i]);
    }
    return array.uniq();
}
//将|分隔的字符串转为数组并去除重复数据
this.stirngTransfer2 = function(_str) {
    var array = new Array();
    var temp = _str;
    var str = temp.split('|');
    for (i = 0; i < str.length - 1; ++i) {
        if (str[i] != "")
            array.push(str[i]);
    }
    return array.uniq();
}
//删除数组中的重复数据
Array.prototype.uniq = function() {
    var resultArr = [],
        returnArr = [],
        i = 1,
        origLen = this.length,
        resultLen;
    function include(arr, value) {
        for (var i = 0, n = arr.length; i < n; ++i) {
            if (arr[i] === value) {
                return true;
            }
        }
        return false;
    }
    resultArr.push(this[0]);
    for (i; i < origLen; ++i) {
        if (include(resultArr, this[i])) {
            returnArr.push(this[i]);
        } else {
            resultArr.push(this[i]);
        }
    }
    resultLen = resultArr.length;
    this.length = resultLen;
    for (i = 0; i < resultLen; ++i) {
        this[i] = resultArr[i];
    }
    return resultArr;
}
