Tuesday, October 29, 2013

javascript prototype extends attempt, 2009

/////////////////////////////////prototype extends///////////////////////////////////

//prototype

Date.prototype.formatedString = function () {
    var Y = "" + this.getFullYear();
    var mm = "" + (this.getMonth() + 1);
    var d = "" + this.getDate();
    var h = "" + this.getHours();
    var m = "" + this.getMinutes();
    var s = "" + this.getSeconds();
    return Y + "." + (mm.length == 1 ? "0" + mm : mm) + "." + (d.length == 1 ? "0" + d : d)
                + " " + (h.length == 1 ? "0" + h : h) + ":" + (m.length == 1 ? "0" + m : m) + ":" + (s.length == 1 ? "0" + s : s);
}
Date.prototype.isBetween = function (start, end) {
    return (start <= this && this <= end);
}
String.prototype.isBool = function () {
    return (/^true$/i).test(this) || (/^false$/i).test(this);
};
String.prototype.isInt = function () {
    return (/^[0-9]+$/).test(this);
};
String.prototype.isDouble = function () {
    return (/^(-{0,1})([0-9]+)(\.{0,1})([0-9]*)$/).test(this);
};
String.prototype.isMoney = function () {
    return (/^\$?\d+(\.(\d{2}))?$/).test(this);
};
String.prototype.isTrue = function () {
    return (/^true$/i).test(this);
};

//StringBuilder

StringBuilder = function (value) {
    this.strings = new Array("");
    this.append(value);
}
StringBuilder.prototype.append = function (value, unshift) {
    if (unshift) {
        this.strings.unshift(value);
    } else {
        this.strings.push(value);
    }
}
StringBuilder.prototype.clear = function () {
    this.strings.length = 1;
}
StringBuilder.prototype.toString = function () {
    return this.strings.join("");
}

//convert methods

__ToTimeStr = function (n) {
    var v = n + '';
    return (v.length == 1 ? '0' + v : v);
}

__ToNumeric = function (s) {
    var i = 0;
    var v = s + '';
    do {
        var c = v.charAt(i);
        if (c == '0') i++; else break;
    } while (i < v.length);
    if (i == v.length) return 0;
    return parseInt(i == 0 ? v : v.substr(i, v.length - i));
}

__DateStrToArray = function (value) {
    var values = new Array();
    values["year"] = __ToNumeric(value.substr(0, 4));
    values["month"] = __ToNumeric(value.substr(5, 2));
    values["day"] = __ToNumeric(value.substr(8, 2));
    values["hour"] = __ToNumeric(value.substr(11, 2));
    values["minute"] = __ToNumeric(value.substr(14, 2));
    values["second"] = __ToNumeric(value.substr(17, 2));
    return values;
}

//string utility

__has = function (text) {
    return !(text == null || _trim(text) == '');
};

__trim = function (text) {
    return text.replace(/^\s+|\s+$/g, "");
}

__date = function (value) {
    var arr = __DateStrToArray(value);
    var d = new Date();
    d.setFullYear(arr["year"], arr["month"] - 1, arr["day"]);
    d.setHours(arr["hour"], arr["minute"], arr["second"], 0);
    return d;
}

//browser data utility

__cookie = function (name, value, exp_date) {
    if (name && !value && !exp_date) {
        //get
        var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
        if (results)
            return (unescape(results[2]));
        else
            return null;
    }
    if (name && value == false) {
        //delete
        var cookie_date = new Date();  // current date & time
        cookie_date.setTime(cookie_date.getTime() - 1);
        document.cookie = name + "=; expires=" + cookie_date.toGMTString();
    } else {
        var cookie_string = name + "=" + escape(value);
        if (exp_date) {
            if (typeof exp_date != 'string')
                cookie_string += "; expires=" + exp_date.toGMTString();
            else
                cookie_string += "; expires=" + exp_date;
        }
        if (path)
            cookie_string += "; path=" + escape(path);
        if (domain)
            cookie_string += "; domain=" + escape(domain);
        if (secure)
            cookie_string += "; secure";
        document.cookie = cookie_string;
    }
}

__cookieForever = function (name, value) {
    if (value != null) {
        value = value.toString();
        var expireDate = new Date();
        expireDate.setMonth(expireDate.getMonth() + 12);

        document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + expireDate.toGMTString();
        return document.cookie;
    } else {
        if (document.cookie != "") {
            var arr = document.cookie.split(";");
            for (var i = 0; i < arr.length; i++) {
                var val2 = arr[i].split("=");
                if (val2[0].replace(' ', '') == name)
                    return decodeURIComponent(val2[1]);
            }
        }
        return null;
    }
}

//if use this method path=/
__cookieWide = function (name, value) {
    if (value != null) {
        value = value.toString();
        var expireDate = new Date();
        expireDate.setMonth(expireDate.getMonth() + 12);

        document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + expireDate.toGMTString() + ";path=/";
        return document.cookie;
    } else {
        if (document.cookie != "") {
            var arr = document.cookie.split(";");
            for (var i = 0; i < arr.length; i++) {
                var val2 = arr[i].split("=");
                if (val2[0].replace(' ', '') == name)
                    return decodeURIComponent(val2[1]);
            }
        }
        return null;
    }
}

__postdata = function () {
    var r20 = /%20/g;
    //('name','value')
    if (arguments.length == 2) {
        if (typeof arguments[2] !== 'function') {
            var key = arguments[0];
            var value = arguments[1];
            return encodeURIComponent(key) + "=" + encodeURIComponent(value).replace(r20, "+");
        }
    } else {
        var s = [], add = function (key, value) {
            // If value is a function, invoke it and return its value
            s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value).replace(r20, "+");
        }, arr = arguments[0];
        //any string
        if (typeof arr == 'string') {
            return encodeURIComponent(arr).replace(r20, "+");
        } else {
            //[{name:'name'},{value:'value'}]
            for (i = 0; i < arr.length; i++) {
                add(arr[i].name, arr[i].value);
            }
            return s.join("&").replace(r20, "+");
        }
    }
}

__homepage = function (url) {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage(url);
    }
    else if (window.sidebar) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert("this action was aviod by your browser,if you want to enable,please enter about:config in your address line,and change the value of signed.applets.codebase_principal_support to true");
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', url);
    }
}

__copy = function (id) {
    if (window.clipboardData && window.clipboardData.setData) // Internet Explorer
    {
        window.clipboardData.setData("text", text);
    }
    else {
        unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
        clipboardHelper.copyString(text);
    }
}

//event methods

__RemoveSelection = function () {
    if (window.getSelection) {
        var selection = window.getSelection();
        selection.removeAllRanges();
    } else if (document.selection.createRange) {
        var range = document.selection.createRange();
        document.selection.empty();
    }
}

__NumericKeyDown = function (e) {
    var obj = e.srcElement ? e.srcElement : e.target;
    var key = e.keyCode ? e.keyCode : e.which;
    if (key == 8 || key == '8' || key == 9 || key == '9' || key == 46 || key == '46') return true;
    if (key == 37 || key == '37' || key == 39 || key == '39') return true;
    if (key == 189 || key == '189' || key == 109 || key == '109') {
        if (obj.value.indexOf('-') > -1 || obj.value.indexOf('-') > -1) {
            if (e.preventDefault) e.preventDefault(); else e.returnValue = false;
            return false;
        }
        else {
            return true;
        }
    }
    if (key == 190 || key == '190' || key == 110 || key == '110') {
        if (obj.value.indexOf('.') > -1 || obj.value.indexOf('.') > -1) {
            if (e.preventDefault) e.preventDefault(); else e.returnValue = false;
            return false;
        }
        else {
            return true;
        }
    }
    if (!(48 <= key && key <= 57 || 96 <= key && key <= 105)) {
        if (e.preventDefault) e.preventDefault(); else e.returnValue = false;
        return false;
    }
    return true;
}

__FormattedKeyDown = function (evt, format) {
    try {
        var obj;
        if (evt.srcElement) obj = evt.srcElement; else obj = evt.target;
        if (evt.keyCode == '8' || evt.witch == '8' || evt.keyCode == '46' || evt.witch == '46') {
            if (document.execCommand) document.execCommand('undo', false, null);
            return false;
        }
        var locs = format;
        var cpos = __doGetCaretPosition(obj) - 1;
        if (cpos < 0) cpos = 0;
        var chr = __doGetCaretChar(obj, cpos);
        /*String.fromCharCode(evt.keyCode);*/

        if (evt.keyCode == '36' || evt.witch == '36') {
            __doSetCaretPosition(obj, 0);
            return true;
        }
        if (evt.keyCode == '37' || evt.witch == '37' || evt.keyCode == '38' || evt.witch == '38') {
            __doSetCaretPosition(obj, cpos);
            return true;
        }
        if (evt.keyCode == '39' || evt.witch == '39' || evt.keyCode == '35' || evt.witch == '35') {
            if (evt.srcElement) {
                if (cpos >= locs.length - 1) cpos = obj.value.length - 1; else cpos++;
                __doSetCaretPosition(obj, cpos);
                return true;
            } else {
                __doSetCaretPosition(obj, cpos);
                return true;
            }
        }

        var loc = locs.charAt(cpos);
        __doSetCaretPosition(obj, cpos);
        if (chr.length > 0) {
            if (loc == '#') {
                if ("0123456789".indexOf(chr.charAt(0)) == -1) __doSetCaretChar(obj, cpos, "0");
            }
            else if (loc != '*') __doSetCaretChar(obj, cpos, loc);
            __doSetCaretPosition(obj, cpos + 1);
        }
        return true;
    } catch (e) {
        alert(e);
        return false;
    }
}

__doGetCaretChar = function (oField, iCaretPos) {
    return oField.value.substr(iCaretPos);
}
__doSetCaretChar = function (oField, iCaretPos, oText) {
    if (oField.value.length <= 0 || oField.value.length < iCaretPos) return;
    oField.value = oField.value.substr(0, iCaretPos) + oText + oField.value.substr(iCaretPos + 1);
}
__doGetCaretPosition = function (oField) {
    var iCaretPos = 0;
    if (document.selection) {
        oField.focus();
        var oSel = document.selection.createRange();
        oSel.moveStart('character', -oField.value.length);
        iCaretPos = oSel.text.length;
    } else if (oField.selectionStart) iCaretPos = oField.selectionStart;
    return iCaretPos;
}
__doSetCaretPosition = function (oField, iCaretPos) {
    if (document.selection) {
        __RemoveSelection();
        var oSel = document.selection.createRange();
        oSel.moveStart('character', iCaretPos);
        oSel.moveEnd('character', 1);
        oSel.select();
    } else {
        oField.selectionStart = iCaretPos;
        oField.selectionEnd = iCaretPos + 1;
        oField.focus();
    }
}

No comments: