﻿/*  
Common Js Library & BaseType Extendtions
*/
String.prototype.ToCharArray = function () { return this.split(""); }
String.prototype.Reverse = function () { return this.split("").reverse().join(""); }
String.prototype.IsContains = function (str) { return (this.indexOf(str) > -1); } /* include or not ?*/
String.prototype.Format = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, i, o, n) { return args[i]; }); }
String.prototype.JsonFormat = function (config, reserve) { return this.replace(/\{([^}]*)\}/g, (typeof config == 'object') ? function (m, i) { var ret = config[i]; return ret == null && reserve ? m : ret } : config); };
String.prototype.ResetBlank = function () { return this.replace(/s+/g, ""); }
String.prototype.LTrim = function () { return this.replace(/^s+/g, ""); }
String.prototype.RTrim = function () { return this.replace(/s+$/g, ""); }
String.prototype.Trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); }
String.prototype.TrimEnd = function (string) { if (!string) { string = "\\s+"; } var trimEndPattern = new RegExp("(" + string + ")+$", "g"); return this.replace(trimEndPattern, ""); };
String.prototype.GetNum = function () { return this.replace(/[^d]/g, ""); } /*num only*/
String.prototype.GetEn = function () { return this.replace(/[^A-Za-z]/g, ""); } /* english charctar only */
String.prototype.GetCn = function () { return this.replace(/[^\u4e00-\u9fa5\uf900-\ufa2d]/g, ""); } /* chinese charctar only */
String.prototype.ByteLength = function () { return this.replace(/[^\x00-\xff]/g, "aa").length; } /* get Byte Length */
String.prototype.Left = function (n) { return this.slice(0, n); }
String.prototype.Right = function (n) { return this.slice(this.length - n); }
String.prototype.Insert = function (index, str) { return this.substring(0, index) + str + this.substr(index); }
String.prototype.Copy = function () { if (IE) window.clipboardData.setData("text", this.toString()); } /* ie only */
String.prototype.HtmlEncode = function () { var i, e = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }, t = this; for (i in e) t = t.replace(new RegExp(i, 'g'), e[i]); return t }
String.prototype.UrlEncode = function () { return encodeURIComponent(this); }
String.prototype.Unicode = function () { var tmpArr = []; for (var i = 0; i < this.length; i++) tmpArr.push("&#" + this.charCodeAt(i) + ";"); return tmpArr.join(""); }
String.prototype.GetFileExt = function () { return this.replace(/.+./, ""); }
String.prototype.ConvertExt = function (newExt) { alert(this.GetFileExt()); return this.replace(this.GetFileExt(), newExt); }
/*-- Common Tools Class  --*/

/*Validate*/
String.prototype.replaceAll = function (s1, s2) { return this.replace(new RegExp(s1, "gm"), s2); }
String.prototype.IsNumOrChart = function () { return /^[A-Za-z0-9]+$/.test(this); }
String.prototype.IsEmpty = function () { return this.Trim() == ""; }
String.prototype.IsEmail = function () { return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this); }
String.prototype.IsChinese = function () { return /^[\u0391-\uFFE5]+$/.test(this); }
String.prototype.IsQQ = function () { return /^[0-9]{5,9}$/.test(this); }
String.prototype.IsTel = function () { return /^(([0-9]{3,4})|[0-9]{3,4}-)?[0-9]{7,8}(-[0-9]{2,4})?$/.test(this); }
String.prototype.IsTelAll = function () { return /^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/.test(this) || /^\d{11}$/.test(this); } /* include cell phone */
String.prototype.IsNum = function () { return /^(\d+)$/.test(this); }
String.prototype.IsMac = function () { return /[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/.test(this); }
String.prototype.IsMobile = function () { return /^(13|15|18)[0-9]{9}$/.test(this); }
String.prototype.IsPostCode = function () { return /^[0-9]{6}$/.test(this); }
String.prototype.IsValidName = function () { return /^(([\u4e00-\u9fa5]{2,5})|([a-zA-Z]{1,10}[a-zA-Z. ]{1,20}[a-zA-Z]{1,10}))$/.test(this); }
String.prototype.IsURL = function () { return /http:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(this); }
String.prototype.IsIP = function () { return /^([1-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){2}([1-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/.test(this); }
String.prototype.GetTextLen = function () { return (this.GetCn() + this.GetEn() + this.GetNum()).length; } /* en + cn + num charctar's length */
String.prototype.parseDate = function () { new RegExp("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[ ]+([0-9]{1,2})[:]([0-9]{1,2})[:]([0-9]{1,2})", "ig").exec(this); return new Date(RegExp.$1, parseInt(RegExp.$2) - 1, RegExp.$3, RegExp.$4, RegExp.$5, RegExp.$6); }
String.prototype.JsonTimeToLocal = function (len) {
    var reg = (/\/Date\(([-]?[0-9]+)\)\//gi).exec(this);
    if (reg) {
        var temp = this.replace("\/Date(", "").replace("\)\/", "");
        var l = new Date(parseInt(temp));
        var str = l.getFullYear() + "-" + (100 + l.getMonth() + 1 + "").substr(1, 2) + "-" + (100 + l.getDate() + "").substr(1, 2)
            + " " + (100 + l.getHours() + "").substr(1, 2) + ":" + (100 + l.getMinutes() + "").substr(1, 2) + ":" + (100 + l.getSeconds() + "").substr(1, 2)
            + "." + (1000 + l.getMilliseconds() + "").substr(1, 3);
        if (typeof len != "number" || len < 1 || len > 23) {
            len = 19;
        }
        return str.substr(0, len);
    }
    return "";
}
Number.prototype.toFloat = function () {
    var n = arguments[0];
    if (typeof n == "undefined" || n == null || isNaN(n)) {
        n = 2;
    }
    else if (n > 4) {
        n = 4;
    }
    var str = '' + (this + 0.00001 * (this >= 0 ? 1 : -1));
    return str.substr(0, str.indexOf(".") + (n > 0 ? n + 1 : 0));
}

var Js = {};
Js.CopyRight = "(C) 51MobApp.COM";
Js.Tiny = {};
Js.Tiny.ElapsedTime = 2; //seconds
Js.Tiny.DefaultWidth = 200; //pixes

Js.Str2Json = function (str) {
    return eval('(' + str + ')');
};
//将序列化的时间字符串转成Date对象
Js.Str2Date = function (str) {
    return eval('new' + str.replace(/\//g, ' '));
};
//2010-5-12 to 5/12/2010
Js.DateChangeFormat = function (str) {
    new RegExp("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", "ig").exec(str);
    return "{0}/{1}/{2}".Format(RegExp.$2, RegExp.$3, RegExp.$1);
};
//JS委托
Js.Delegate = function (func) {
    this.arr = new Array();
    this.add = function (func) { this.arr[this.arr.length] = func; };
    this.run = function () {
        for (var i = 0; i < this.arr.length; i++) {
            var func = this.arr[i];
            if (typeof func == "function") {
                func();
            }
        }
    };
    this.add(func);
};
//分页互助方法
Js.GetPageNum = function (ele, pageCount) {
    var pagerInputVar = document.getElementById(ele).value;
    if (pagerInputVar == '') { return false; }
    else if (pagerInputVar < 1) { pagerInputVar = 1; }
    else if (pagerInputVar > pageCount) { pagerInputVar = pageCount; };
    return pagerInputVar;
};

/******** JS调试 ********/
Js.debug = function (obj) {
    if (obj == null) {
        sys_alert('null');
        return;
    }
    var type = typeof obj;
    if (type == 'undefined' || type == 'string' || type == 'function' || type == 'number' || type == 'boolean') {
        sys_alert(obj);
    }
    else if (obj.constructor == Array) {
        var arr = [];
        for (var i = 0; i < obj.length; ++i) {
            try {
                arr.push(JSON.stringify(obj[i]));
            } catch (e) { arr.push('{object}') }
        }
        sys_alert(arr.join('\n'));
    }
    else if (type == 'object') {
        var str = '';
        for (p in obj) {
            str += '\n\n' + p + ': ';
            try {
                str += JSON.stringify(obj[p]);
            } catch (e) { str += '{object}'; }
        }
        sys_alert(str);
    }
}

function sys_alert(str) {
    alert(str);return;
    var newDiv = document.createElement("div");
    newDiv.innerHTML = str.replace(/\n/g,"<br />");
    newDiv.setAttribute("style", "background-color:white;padding:20px;word-break:break-all;");
    document.body.appendChild(newDiv);
}

/****** 已过去时间 ******/
Js.TimePast = function (dateTimeStamp) {
    if (typeof dateTimeStamp == "string") {
        dateTimeStamp = dateTimeStamp.parseDate();
    }
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var result = "";
    var diffValue = now - dateTimeStamp.getTime();

    if (diffValue > 0) {

        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;

        if (monthC >= 1) {
            result = parseInt(monthC) + "个月前";
        }
        else if (weekC >= 1) {
            result = parseInt(weekC) + "个星期前";
        }
        else if (dayC >= 1) {
            result = parseInt(dayC) + "天前";
        }
        else if (hourC >= 1) {
            result = parseInt(hourC) + "个小时前";
        }
        else if (minC >= 1) {
            result = parseInt(minC) + "分钟前";
        } else
            result = "刚刚";
    }
    return result;
};

/****** 取星座,month 月份,day 日期 *******/
Js.GetStarName = function (month, day) {
    var d = new Date(1999, month - 1, day, 0, 0, 0);
    var arr = [];
    arr.push(["魔羯座", new Date(1999, 0, 1, 0, 0, 0)])
    arr.push(["水瓶座", new Date(1999, 0, 20, 0, 0, 0)])
    arr.push(["双鱼座", new Date(1999, 1, 19, 0, 0, 0)])
    arr.push(["牡羊座", new Date(1999, 2, 21, 0, 0, 0)])
    arr.push(["金牛座", new Date(1999, 3, 21, 0, 0, 0)])
    arr.push(["双子座", new Date(1999, 4, 21, 0, 0, 0)])
    arr.push(["巨蟹座", new Date(1999, 5, 22, 0, 0, 0)])
    arr.push(["狮子座", new Date(1999, 6, 23, 0, 0, 0)])
    arr.push(["处女座", new Date(1999, 7, 23, 0, 0, 0)])
    arr.push(["天秤座", new Date(1999, 8, 23, 0, 0, 0)])
    arr.push(["天蝎座", new Date(1999, 9, 23, 0, 0, 0)])
    arr.push(["射手座", new Date(1999, 10, 22, 0, 0, 0)])
    arr.push(["魔羯座", new Date(1999, 11, 22, 0, 0, 0)])
    for (var i = arr.length - 1; i >= 0; i--) {
        if (d >= arr[i][1]) {
            return arr[i][0];
        }
    }
};


/**** Url处理 *****/
Js.Url = {
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },
    request: function (string) {
        var url = location.href; var paraObj = {}; var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
        for (i = 0; j = paraString[i]; i++) { paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length); }
        var returnValue = paraObj[string.toLowerCase()];
        if (typeof (returnValue) == "undefined") { return ""; } else { return returnValue; }
    },
    // private method
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};

/***** JSON 处理 *****/
if (!this.JSON) {
    this.JSON = {};
}
(function () {
    function f(n) {
        return n < 10 ? '0' + n : n;
    }
    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
        };
        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;
    function quote(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }
    function str(key, holder) {
        var i,
            k,
            v,
            length,
            mind = gap,
            partial,
            value = holder[key];

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':
                return isFinite(value) ? String(value) : 'null';
            case 'boolean':
            case 'null':
                return String(value);
            case 'object':
                if (!value) {
                    return 'null';
                }
                gap += indent;
                partial = [];
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }
                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }
                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {
            var i;
            gap = '';
            indent = '';
            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

            } else if (typeof space === 'string') {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }
            return str('', { '': value });
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {
            var j;
            function walk(holder, key) {
                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }
            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                j = eval('(' + text + ')');

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }
            throw new SyntaxError('JSON.parse');
        };
    }
} ());

Js.Guid = function() {
    var guid = "";
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
            guid += "-";
    }
    return guid;
};
