/**
 * 版权说明,你可以任意的拷贝,发布,修改本js代码.但对于修改后的代码修改 必须发一份到jspxnet@163.com
 * 这样方便我在考虑
 * jspxnet.js 1.0 for mootools 1.21
 * date:2009-1-23
 * chenYan
 */
/////--------------------------------------RPC call TXWeb
Request.RPC = new Class({
    Extends: Request,
    options: {
        secure: true,
        method:'POST', //必须
        link : "chain",
        requestParam : false,
        result : "json",
        header:{"Content-type":"text/xml"},
        evalResponse:false,
        emulation:false,
        urlEncoded:false
    },
    initialize: function(options) {
        this.params = new Array(); //action全局参数
        this.methods = new Array(); //保存调用的方法,可以是多个
        this.parent(options);
    },
    setAction:function(act) {
        this.act = act; //action 动作
    }
    ,
    setMethod:function(mname, params) {
        var cmethod = new Object();
        cmethod.name = mname;
        cmethod.params = params;
        this.methods.push(cmethod);
    }
    ,
    setParams:function(params) {
        this.params = params;
    },
    getCallXml:function() {
        function getParamXml() {
            if (!this.params) return "";
            var result = "";
            for (var i = 0; i < this.params.length; i++) {
                result = result + "<" + this.params[i][0] + " name=\"" + this.params[i][1] + "\">" + this.params[i][2] + "</" + this.params[i][0] + ">\r\n";
            }
            return result.toString();
        }

        function getMethodParams(params) {
            var result = "";
            for (var i = 0; i < params.length; i++) {
                result = result + "<" + params[i][0] + " name=\"" + i + "\">" + params[i][1] + "</" + params[i][0] + ">\r\n";
            }
            return result;
        }

        if (this.requestParam == undefined) this.requestParam = false;
        if (this.result == undefined) this.result = "json";
        var callXML = "<?xml version=\"1.0\"?>\r\n" + "<call name=\"" + this.act + "\" request=\"" + this.requestParam + "\" result=\"" + this.result + "\">\r\n";
        for (var i = 0; i < this.methods.length; i++) {
            var method = this.methods[i];
            callXML = callXML + "<method name=\"" + method.name + "\">\r\n";
            callXML = callXML + getMethodParams(method.params);
            callXML = callXML + "</method>\r\n";
        }
        var paramx = getParamXml();
        if (paramx) {
            callXML = callXML + "<params>\r\n";
            callXML = callXML + paramx;
            callXML = callXML + "</params>\r\n";
        }
        callXML = callXML + "</call>\r\n";
        return callXML;
    }
    ,
    doAction:function() {
        this.send(this.getCallXml());
    }
});
/////-------------------------验证请求
Request.Validator = new Class({
    Extends: Request,
    options: {
        secure: true,
        method:'GET', //必须
        link : "chain",
        requestParam : false,
        result : "json",
        header:{"Content-type":"text/xml"},
        evalResponse:false
    },
    initialize: function(url, formId) {
        this.formId = formId;
        this.url = url; //验证ID
        this.options.url = url + "?formId=" + formId,
                this.options.onComplete = this.complete;
        this.options.onFailure = this.showErrorMessage;
        this.options.onException = this.showErrorMessage;
        this.parent(this.options);
        this.send();
        this.validForm = false;
    },
    complete:function(req) {
        this.validForm = new ValidForm(this.formId, JSON.decode(req));
    }
    ,
    showErrorMessage: function(info) {
        var msgEl = $("information");
        if (msgEl != undefined && msgEl.tagName != undefined) {
            msgEl.set("html", info);
        }
    }
});
//验证对象Form 做为一个单元
var ValidForm = function (formId, data) {
    var mForm = $(formId);
    if (!mForm) {
        alert('form id=' + formId + ' 没有定义');
        return false;
    }
    var jsonData = data;
    jsonData.each(function(vx) {
        var field = vx.field;
        if (field.indexOf(';') != -1) {
            var checkField = '';
            var fields = field.toArray(";");
            for (var r = 0; r < fields.length; r++) {
                checkField = checkField + '#' + fields[r];
                if (r != fields.length - 1) checkField = checkField + ',';
            }
            field = checkField;
        }
        var box = null;
        if (field.indexOf('#') != -1) {
            box = $$(field);
            vx.checkbox = true;

        } else  box = $(field);
        if (!box) {
            box = $$('input[name=' + field + ']');
            vx.checkId = box.get('id').toString().replace(/,/g, ";");
            vx.radio = true;
        }
        if (!box) {
            alert(field + ":表单没有找到,(input not find)");
            return;
        }
        if (box) {
            if (vx.checkbox || vx.radio)
                box.addEvent('click', validBlur);
            else
            {
                box.addEvent('focus', validFocus);
                box.addEvent('blur', validBlur);
            }
        }
    });
    var doSubmit = function () {
        var canDo = 0;
        var fileds = "";
        jsonData.each(function(vx) {
            if (doValidator(vx) == -1) {
                var tips = $(vx.msgId);
                if (!tips) {
                    alert(vx.msgId + ":Element not find,元素没有找到");
                    canDo = 1;
                    fileds = fileds + "," + vx.filed;
                    return false;
                }
                tips.set("class", "error");
                tips.set("html", vx.error);
                canDo++;
            }
        });
        if (canDo == 0) return true;
        var msgEl = $(formId + 'Msg');
        if (msgEl) msgEl = $('information');
        if (msgEl)
            msgEl.grab(new Element('li', {'html':'Error:有' + canDo + '个没有正确填写,  not fill out'}));
        else
            alert(canDo + ':个填写错误,(not input);' + fileds);
        return false;
    };
    mForm.addEvent("submit", doSubmit.bind(this));

    function validBlur() {
        var vx = getValidField(this.id);
        var tips = $(vx.msgId);
        var cas = doValidator(vx);
        if (cas == -1) {
            tips.set("class", "error");
            tips.set("html", vx.error);
        }
        else if (cas == 0) {
            tips.set("class", "message");
            tips.set("html", vx.message);
        }
        else {
            tips.set("class", "message");
            tips.set("html", vx.success);
        }
    }

    function validFocus() {
        var vx = getValidField(this.id);
        var input = $(vx.msgId);
        if (!input) alert(vx.msgId + ":没有定义|not define");
        input.set("html", vx.message);
    }

    function doValidator(vx) {
        //验证 -1:不通过 0:不需要验证 1:验证通过
        var needed = vx.needed;
        var checkValue;
        var dataType = vx.dataType;
        if (vx.radio) {   //单选
            var boxs = $$('input[name=' + vx.field + ']');
            if (boxs) for (var r = 0; r < boxs.length; r++) {
                if (boxs[r].getProperty("checked")) {
                    checkValue = boxs[r].get('value');
                    break;
                }
            }
        } else
        if (vx.checkbox) //多选方式
        {
            checkValue = vx.field.toArray(";");
        } else {
            checkValue = $(vx.field).get("value");
        }
        if (!needed && checkValue == "") return 0;
        dataType = dataType.injectUI();
        var expression = "";
        if (dataType.startsWith(" ")) expression = dataType;
        else {
            expression = "checkValue." + dataType;
            if (!dataType.endWith(")") && !dataType.indexOfArray([">","<","=","+","-","*","/"])) expression = expression + "()";
        }
        return  $try(function() {
            if (eval(expression)) return 1;
            return -1;
        }, function() {
            alert(field + '字段验证错误,联系管理人员, is error');
            return -1;
        });
    }

    function getValidField(field) {
        //返回配置
        for (var i = 0; i < jsonData.length; i++) {
            var vf = jsonData[i];
            if (vf.field == field || (vf.field.indexOf(";") != -1 && vf.field.indexOf(field) != -1) ||  (vf.radio&&vf.checkId.indexOf(field) != -1)) {
                return vf;
            }
        }
        return null;
    }
};
//常用的提交
function formButton(form, op) {
    if (!op) {
        alert("code error");
        return false;
    }
    if (op.indexOf("delete") != -1) {
        var q = confirm('delete ? 是否确定要删除?');
        if (q == "0" || q == 0) return false;
    }
    var oper = $("operation");
    if (!oper) {
        oper = new Element('input', {'id': 'operation','name':'operation','type':'hidden'});
        $(form).grab(oper);
    }
    oper.set("value", op);
    $(form).submit();
    return true;
}
//------------------------------js属性扩展 常用部分
var baseTypes = ["int","integer","long","bool","boolean","float","long","date","double","string","map"];
var imgTypes = ["jpg","bmp","png","gif","ico"];
function isBaseType(type) {
    for (var i = 0; i < baseTypes.length; ++i) {
        if (baseTypes[i] == type) return true;
    }
    return false;
}
//简单的java StringBuffer
function StringBuffer() {
    this._strings_ = new Array;
}
StringBuffer.prototype.append = function(str) {
    this._strings_.push(str);
};
StringBuffer.prototype.toString = function() {
    return this._strings_.join("");
};
//注入HTML中的单元变量
String.prototype.injectUI = function() {
    var str = this;
    var escapeVariable = "\\";
    var variableBegin = "${";
    var variableEnd = "}";
    if (!str) return "";
    var iend = str.getLength();
    var i = 0;
    var ivb = -1;
    var ys = 0;
    var yd = 0;
    var out = new StringBuffer();
    while (i < iend) {
        var c = str.charAt(i);
        var old = ' ';
        if (i > 0) {
            old = str.charAt(i - 1);
        }

        if (ivb == -1 && escapeVariable != old && str.startsWith(variableBegin, i)) {
            ys = 0;
            yd = 0;
            ivb = i + 2;
        } else if (ivb != -1) {
            if (c == '\"' && yd % 2 == 0) ys++;
            if (c == '\'' && ys % 2 == 0) yd++;
            if (ys % 2 == 0 && yd % 2 == 0 && old != escapeVariable && variableEnd == str.substring(i, i + variableEnd.getLength())) {
                var varName = str.substring(ivb, i);
                var oo = $(varName).get("value");
                if (!oo) oo = "";
                out.append(oo);
                ivb = -1;
            }
        }
        else {
            if (escapeVariable == c && str.startsWith(variableBegin, i + 1)) {

            } else out.append(c);

        }
        i++;
    }
    return out.toString();
};
//得到长度,为了兼容java
String.prototype.getLength = function() {
    var o = this;
    var elen;
    if (typeof(o.length) == "number")
        elen = o.length;
    else elen = o.length();
    return elen;
};
//得到浏览器URL
function getBrowserURL() {
    if (location.href.lastIndexOf('/') != -1) {
        firstpos = location.href.lastIndexOf('/') + 1;
        lastpos = location.href.length;
        return location.href.substring(0, firstpos);
    }
    return "";
}
//调用一个函数
function callBack(functionName, ev) {
    if (typeof(functionName) == 'string')
        return eval(functionName(ev));
    else
        return functionName(ev);
}
//将一个页面做为弹出窗口
function popupCenterWindow(url, name, width, height, scro) {
    var win = null;
    var left = (screen.width - width) / 2;
    var top = (screen.height - height) / 2;
    var features = 'height=' + height + ',';
    features += 'width=' + width + ',';
    features += 'top=' + top + ',';
    features += 'left=' + left + ',';
    features += 'scrollbars= ' + scro + ',';
    features += 'resizable=no';
    win = window.open(url, name, features);
    if (parseInt(navigator.appVersion) >= 4) {
        win.window.focus();
    }
    return win;
}
//反选 todo
function setCheckedContrast(form_nr, name) {
    if (name == undefined) name = "id";
    var form = document.forms[form_nr];

    for (var i = 0; i < form.elements.length; i++) {
        if (name != "" && form.elements[i].name != name) continue;
        if ((form.elements[i].type == "checkbox")
                && (form.elements[i].id != "checkedAll")
                && (form.elements[i].id != "checkedContrast")) {
            form.elements[i].checked = !form.elements[i].checked;
        }
    }
}
//全选 todo
function setCheckedAll(form_nr, name) {
    if (name == undefined) name = "id";
    var isChecked = true;
    if ($("checkedAll") && $("checkedAll").type == "checkbox")
        isChecked = $("checkedAll").checked;
    var form = document.forms[form_nr];

    for (i = 0; i < form.elements.length; i++) {
        if (name != "*" && form.elements[i].name != name) continue;
        if ((form.elements[i].type == "checkbox")
                && (form.elements[i].id != "checkedAll")
                && (form.elements[i].id != "checkedContrast")) {

            form.elements[i].checked = true;
        }
    }
}
//字符串转换到dom 对象
function loadXML(xmlStr) {
    if (!xmlStr)return null; //空串返回null
    var xmlDom = false;
    if (window.ActiveXObject) {
        var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
        for (var i = 0; i < prefixes.length; i++)
            try {
                xmlDom = new ActiveXObject(prefixes[i] + ".DomDocument");
                if (xmlDom) break;
            }
            catch (ex) {
                xmlDom = new ActiveXObject("Microsoft.XMLDOM");
            }
    } else
    if (document.implementation && document.implementation.createDocument) {
        xmlDom = document.implementation.createDocument("", "doc", null);
    }
    xmlDom.async = false;
    try {
        xmlDom.loadXML(xmlStr);
    }
    catch(e) {  //非IE浏览器
        var oParser = new DOMParser();
        xmlDom = oParser.parseFromString(xmlStr, "text/xml");
    }
    return xmlDom;
}
/**
 * 扩展mootools
 * deleteOptions 删除select 单元 中的选项
 * setOptions 设置 option
 */
Element.implement({
    deleteOptions: function() {
        if (this.tagName.toLowerCase() == "select") {
            var selLen = this.options.length;
            var i = 0;
            if (Browser.Engine.trident)
                for (i = 0; i < selLen; i++)
                    this.options.remove(0);
            else
                for (i = 0; i < selLen; i++)
                    this.remove(0);
            this.options.length = 0;
        } else alert(this.id + "错误的输入框类型");
    },
    setOptions:function(array, sel, keyf) {
        if ($type(array) == 'array')
            array.setOptions(this, sel, keyf);
        else
            array.split(";").setOptions(this, sel, keyf);
    }
    ,
    sendBind: function(bindId) {
        this.set('send', {onComplete: function(response) {
            var tagName = $(bindId).get('tag');
            if ("input" == tagName.toLowerCase() || "textarea" == tagName.toLowerCase())
                $(bindId).set('value', response);
            else if ("div" == tagName.toLowerCase() || "span" == tagName.toLowerCase())
                $(bindId).set('html', response);
            else if ("select" == tagName.toLowerCase())
                $(bindId).setOptions(response.toArray());
        }});
        this.send();
    }
});
/**
 * 扩展mootools 中array数据放入select 单元
 *   var data= ["aa:AA","bb:BB","cc:CC"];
 *   data.setOptions($('mcountry'),"cc");
 */
Array.implement({
    setOptions: function(select, sel, keyf) {
        select.deleteOptions();
        if (keyf == null || keyf == undefined) keyf = ":";
        var keys = null,vars = null,opt = null;

        function ie6OptionSelected() {
            this.selected = true;
        }

        this.each(function(av) {
            if ($type(av) == "string") {
                var hav = av.indexOf(keyf);
                if (hav == -1) {
                    opt = new Option(av, av);
                    if (av == sel)
                        if (Browser.Engine.trident4)
                            ie6OptionSelected.delay(1, opt);
                        else  opt.selected = true;

                } else {
                    keys = av.substring(0, hav);
                    vars = av.substring(hav + 1, av.getLength());
                    opt = new Option(vars, keys);
                    if (keys == sel) {
                        if (Browser.Engine.trident4)
                            ie6OptionSelected.delay(1, opt);
                        else  opt.selected = true;
                    }
                }
            } else {
                opt = new Option(av.key, av.value);
                if (keys == sel)
                    if (Browser.Engine.trident4)
                        ie6OptionSelected.delay(1, opt);
                    else  opt.selected = true;
            }
            select.options.add(opt);
        });

    }
});

///扩展mootools 中hash数据放入select 单元
Hash.implement({
    setOptions: function(selected, sel) {
        for (var key in this) {
            var opt = new Option(key, this[key]);
            if (keys == sel) opt.selected = true;
            selected.options.add(opt);
        }
    }
});
//------------------------------使用scriptmark   begin
//删除html
String.prototype.deleteHtml = function() {
    var str = this;
    if (str.indexOf(">") == -1) return str;
    var out = "";
    while (str.indexOf(">") != -1) {
        out = out + str.substring(0, str.indexOf("<"));
        if (str.indexOf(">") == -1) continue;
        str = str.substring(str.indexOf(">") + 1, str.length);
    }
    out = out + str;
    return  out.replace("&quot;", "\"");
};
String.prototype.cut = function(len, send) {
    if (send == undefined) send = "";
    if (this.length > len)
        return this.substring(0, len) + send;
    else return this;
};
//首字母大写
String.prototype.firstUpperCase = function() {
    return this.substring(0, 1).toUpperCase() + this.substring(1, this.length);
};
//首字母小写
String.prototype.firstLowerCase = function() {
    return this.substring(0, 1).toLowerCase() + this.substring(1, this.length);
};
//得到长度,为了兼容java
String.prototype.getLength = function() {
    var o = this;
    var elen;
    if (typeof(o.length) == "number")
        elen = o.length;
    else elen = o.length();
    return elen;
};
//得到字符前的
String.prototype.substringBefore = function (prefix) {
    if (this == null || prefix == undefined) return "";
    var pos = this.indexOf(prefix);
    if (pos == -1)
        return "";
    return this.substring(0, pos);
};
//得到
String.prototype.substringLastAfter = function(prefix) {
    if (this == null || prefix == undefined) return "";
    var pos = this.lastIndexOf(prefix);
    if (pos == -1)
        return "";
    return this.substring(pos + prefix.getLength(), this.getLength());
};
//得到字符传出现的次数
String.prototype.countMatches = function (c) {
    var elen = this.getLength();
    var clen = c.getLength();
    if (!this || elen < 1) return 0;
    if (elen < clen) return 0;
    var result = 0;
    for (var i = 0; i < elen - clen; i++) {
        if (c == this.substring(i, i + clen)) result++;
    }
    return result;
};
//转换为整数 ,separator 表示得到切分后的部分来转换,为了区分mootools
String.prototype.parseInt = function (separator) {
    var result = 0;
    if (separator && this.lastIndexOf(separator) != -1) {
        firstpos = this.lastIndexOf(separator) + separator.getLength();
        lastpos = this.getLength();
        result = parseInt(this.substring(firstpos, this.getLength()));
        if (isNaN(result)) return 0;
        return result;
    }
    result = parseInt(this.replace("px", ""));
    if (isNaN(result)) return 0;
    return result;
};
//转换为数字,有小数点
String.prototype.toNumber = function(dec) {
    var f = this.replace("px", "");
    if (dec < 0) dec = 2;
    var result = parseInt(this) + (dec == 0 ? "" : ".");
    f -= parseInt(f);
    if (f == 0)
        for (var i = 0; i < dec; i++)   result += '0';
    else {
        for (i = 0; i < dec; i++)  f *= 10;
        result += parseInt(Math.round(f));
    }
    return  result;
};
//去出空格
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.toBoolean = function () {
    if (this == '') return false;
    var temp = this.toLowerCase();
    return temp == 'true' || temp == '1' || temp == 'y';

};
//---------------验证功能部分 begin
String.prototype.isEmpty = function () {
    return (this == null) || this == undefined || (this.getLength() < 1);
};
//是否为中文
String.prototype.isChinese = function() {
    return /^[\u4e00-\u9fa5]+$/.test(this);
};
//是否为日期
String.prototype.isDate = function() {
    var r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    if (this.isInteger() && this.getLength() == 6) return r = this.match(/^(\d{1,2})(\d{1,2})(\d{1,2})$/);
    if (this.isInteger() && this.getLength() == 8) return r = this.match(/^(\d{1,4})(\d{1,2})(\d{1,2})$/);
    if (r == null) return false;
    var d = new Date(r[1], r[3] - 1, r[4]);
    if (this.getLength() == 6)
        return (d.getYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]);
    return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]);
};
//判断文本输入是不是时间格式,如13:25
String.prototype.isTime = function() {
    var a = this.match(/^(\d{1,2})(:)?(\d{1,2})$/);
    if (a == null)  return false;
    return !(a[1] > 24 || a[3] > 60);
};
//是否为email
String.prototype.isEmail = function () {
    if (this.isEmpty()) {
        return false;
    }
    var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
    return re.test(this);
};
//判断字符串中是否存在数组中的字符
String.prototype.indexOfArray = function(array) {
    if (typeof(array) == "string") return this.indexOf(array);
    for (var i = 0; i < array.length; i++) {
        if (this.indexOf(array[i]) != -1) return true;
    }
    return false;
};
//判断是否为正常的名称
String.prototype.isGoodName = function() {
    if (!this.isLengthBetween(4, 50)) return false;
    return !this.indexOfArray(['.','/',',',';','.',' ','^','&','|','[',']','!']);
};
//判断URL http格式的
String.prototype.isURL = function() {
    var reg = /^http:\/\/.{0,93}/;
    var reg2 = /^https:\/\/.{0,93}/;
    var reg3 = /^rtsp:\/\/.{0,93}/;
    var reg4 = /^mms:\/\/.{0,93}/;
    return reg.test(this) || reg2.test(this) || reg3.test(this) || reg4.test(this);
};
//比较开始是否相等 formI从那里开始比较
String.prototype.startsWith = function(prefix, formI) {
    if (!formI)
        formI = 0;
    if (this == null) return false;
    var iend = 0;
    if (typeof(prefix) == "string") {
        iend = formI + prefix.getLength();
        return iend <= this.getLength() && this.substring(formI, iend) == prefix;
    }
    else {
        for (var i = 0; i < prefix.length; i++) {
            iend = formI + prefix[i].getLength();
            if ((iend <= this.getLength()) && this.substring(formI, iend) == prefix[i])
                return true;
        }
        return false;
    }
};
//比较结束是否相等
String.prototype.endWith = function(prefix) {
    if (this == null) return false;
    if (typeof(prefix) == "string") {
        return this.substring(this.getLength() - prefix.getLength(), this.getLength()) == prefix;
    } else {
        for (var i = 0; i < prefix.length; i++) {
            if (this.substring(this.getLength() - prefix[i].getLength(), this.getLength()) == prefix[i])
                return true;
        }
        return false;
    }
};
//校验手机号码：必须以数字开头，除数字外，可含有“-”
String.prototype.isMobile = function () {
    var patrn = /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
    return patrn.exec(this);
};
//校验QQ
String.prototype.isQQ = function () {
    var patrn = /^[1-9]\d{4,8}$/;
    return patrn.exec(this);
};
//校验普通电话、传真号码：可以“+”开头，除数字外，可含有“-”
String.prototype.isPhone = function() {
    var patrn = /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
    return patrn.exec(this);
};
//是否为邮编
String.prototype.isPostcode = function() {
    var patrn = /^[a-zA-Z0-9 ]{3,12}$/;
    return patrn.exec(this);
};
//是否为整数
String.prototype.isInteger = function() {
    var patrn = /^[-\+]?\d+$/;
    return patrn.exec(this);
};
//是否为双精度数
String.prototype.isDouble = function() {
    var patrn = /^[-\+]?\d+(\.\d+)?$/;
    return patrn.exec(this);
};
//是否为英文
String.prototype.isEnglish = function() {
    var patrn = /^[A-Za-z]+$/;
    return patrn.exec(this);
};
//是否为正整数
String.prototype.isSafe = function() {
    var patrn = /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/;
    return !patrn.exec(this);
};
//IP地址转换成对应数值
String.prototype.isIP = function() {
    var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g; //匹配IP地址的正则表达式
    if (re.test(this)) {
        if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) return true;
    }
    return false;
};
//表达式验证
String.prototype.test = function(regex, params) {
    return ((typeof regex == 'string') ? new RegExp(regex, params) : regex).test(this);
};
//是否相等
String.prototype.equal = function(v) {
    return this == v;
};
//判断是否为数字
String.prototype.isNumber = function() {
    var objExp = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
    return objExp.test(this);
};
//转换为数字验证是否在范围内
String.prototype.isBetween = function(imin, imax) {
    if (!this.isNumber()) return false;
    return parseFloat(this).isBetween(imin, imax);
};
// 判断长度是否在之内
String.prototype.isLengthBetween = function(iMin, iMax) {
    return (this.length >= iMin) && (this.length <= iMax);
};
//判断为日期时间 2002-1-31 12:34:56
String.prototype.isDateTime = function() {
    var r,d;
    if (this.countMatches(':') == 2) {
        r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
        d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], r[7]);
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6] && d.getSeconds() == r[7]);
    }
    if (this.countMatches(':') == 1) {
        r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2})$/);
        d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], 0);
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6]);
    }
    if (this.countMatches(':') == 0)
        return this.isDate();
};
String.prototype.isCardCode = function() {
    var intStrLen = this.getLength();
    if ((intStrLen != 15) && (intStrLen != 18)) return false;
    var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
    var varArray = new Array();
    var lngProduct = 0;
    var intCheckDigit;
    var idNumber = this;
    // check and set value
    for (var i = 0; i < intStrLen; i++) {
        varArray[i] = idNumber.charAt(i);
        if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
            return false;
        } else if (i < 17) {
            varArray[i] = varArray[i] * factorArr[i];
        }
    }
    if (intStrLen == 18) {
        var date8 = idNumber.substring(6, 14);
        if (!date8.isDate()) return false;
        // calculate the sum of the products
        for (i = 0; i < 17; i++) lngProduct = lngProduct + varArray[i];

        intCheckDigit = 12 - lngProduct % 11;
        switch (intCheckDigit) {
            case 10:
                intCheckDigit = 'X';
                break;
            case 11:
                intCheckDigit = 0;
                break;
            case 12:
                intCheckDigit = 1;
                break;
        }
        if (varArray[17].toUpperCase() != intCheckDigit) return false;
    }
    else {
        var date6 = idNumber.substring(6, 12);
        if (!date6.isDate())
            return false;
    }
    //alert ("Correct.");
    return true;
};
//---------------验证功能部分 end
String.prototype.show = function (sel) {
    return this.split(";").show(sel);
};
String.prototype.toArray = function(sp) {
    if (sp == null || sp == undefined) {
        var charArr = new Array();
        for (var i = 0; i < this.getLength(); i++) charArr[i] = this.charAt(i);
        return charArr;
    }
    return this.split(sp);
};
String.prototype.xmlEscape = function () {
    var str = this;
    str = str.replace(/&/g, '&amp;');
    str = str.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/"/g, '&quot;');
    return str;
};
String.prototype.url = function () {
    return encodeURI(this);
};
String.prototype.toDate = function () {
    var r,d;
    if (this.countMatches(':') == 2) {
        r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
        d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], r[7]);
        if ((d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6] && d.getSeconds() == r[7]))
            return d;
    }
    if (this.countMatches(':') == 1) {
        r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2})$/);
        d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], 0);
        if ((d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6]))
            return d;
    }
    if (this.countMatches(':') == 0) {
        r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
        if (this.isInteger() && this.getLength() == 6) return r = this.match(/^(\d{1,2})(\d{1,2})(\d{1,2})$/);
        if (this.isInteger() && this.getLength() == 8) return r = this.match(/^(\d{1,4})(\d{1,2})(\d{1,2})$/);

        if (r == null) return new Date(this);
        d = new Date(r[1], r[3] - 1, r[4]);
        if (this.getLength() == 6)
            if ((d.getYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4])) return d;
        if ((d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4])) return d;
    }
    return new Date(this);
};

//---------------------------------------数字
Number.prototype.toInt = function() {
    return this.round(0);
};
Number.prototype.round = function(pos) {
    return Math.round(this * Math.pow(10, pos)) / Math.pow(10, pos);
};
Number.prototype.toDate = function() {
    return new Date(this);
};
Number.prototype.toDateString = function(fm) {
    var date = new Date(this);
    return date.string(fm);
};
Number.prototype.string = function(y, n) {
    if (this > 0)
        return y;
    else return n;
};
Number.prototype.abs = function() {
    return Math.abs(this);
};
Number.prototype.limit = function(mi, mx) {
    if (this < mi) return mi;
    if (this > mx) return mx;
    return this;
};
//判断一个数值是否在范围内
Number.prototype.isBetween = function (imin, imax) {
    return imin <= this & this <= imax;
};
Number.prototype.toFloat = function() {
    return parseFloat(this);
};
//转换为日期比较,返回小时
Number.prototype.compareHour = function(beginDate) {
    var lbegin = 0;
    if (typeof(beginDate) == "number") lbegin = beginDate;
    else lbegin = beginDate.getTime();
    var diffMillis = this - lbegin;
    return diffMillis / (60 * 60 * 1000);
};
//转换为日期比较,返回天数
Number.prototype.compareDay = function(beginDate) {
    var diffMillis = this.compareHour(beginDate);
    return diffMillis / 24;
};
//判断是否存在数组中
Number.prototype.indexOfArray = function(array) {
    for (var i = 0; i < array.length; i++) {
        if (this == array[i]) return true;
    }
    return false;
};
//--------------------------------------逻辑
Boolean.prototype.string = function(y, n) {
    if (this == true || "true" == this.toString() || "t" == this.toString() || "T" == this.toString() || "1" == this.toString()) return y;
    return n;
};

//-------------------------------------日期
Date.prototype.string = function(format, def) {
    if (this.getFullYear() == 1971 || this.getFullYear() == 1899 && this.getMonth() == 11)
        return def;
    return this.string(format);
};
Date.prototype.string = function(format) {
    var o = {
        "M+" : this.getMonth() + 1, //month
        "d+" : this.getDate(), //day
        "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;

};
Date.prototype.compareHour = function(beginDate) {
    var diffMillis = this.getTime() - beginDate.getTime();
    return diffMillis / (60 * 60 * 1000);
};
Date.prototype.compareDay = function(beginDate) {
    var diffMillis = this.getTime() - beginDate.getTime();
    return diffMillis / (24 * 60 * 60 * 1000);
};
Date.prototype.addMilliseconds = function(value) {
    this.setMilliseconds(this.getMilliseconds() + value);
    return this;
};
Date.prototype.addSeconds = function(value) {
    return this.addMilliseconds(value * 1000);
};
Date.prototype.addMinutes = function(value) {
    return this.addMilliseconds(value * 60000);
};
Date.prototype.addHours = function(value) {
    return this.addMilliseconds(value * 3600000);
};
Date.prototype.addDays = function(value) {
    return this.addMilliseconds(value * 86400000);
};
Date.prototype.addWeeks = function(value) {
    return this.addMilliseconds(value * 604800000);
};
Date.prototype.addMonths = function(value) {
    var n = this.getDate();
    this.setDate(1);
    this.setMonth(this.getMonth() + value);
    this.setDate(Math.min(n, this.getDaysInMonth()));
    return this;
};
Date.prototype.addYears = function(value) {
    return this.addMonths(value * 12);
};
Date.prototype.clearTime = function() {
    this.setHours(0);
    this.setMinutes(0);
    this.setSeconds(0);
    this.setMilliseconds(0);
    return this;
};
Date.prototype.isLeapYear = function() {
    var y = this.getFullYear();
    return(((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0));
};
Date.prototype.between = function(beginDate, end) {
    var ltime = this.getTime();
    var lbegin = 0;
    if (typeof(beginDate) == "number") lbegin = beginDate;
    else lbegin = beginDate.getTime();
    var lend = 0;
    if (typeof(end) == "number") lend = end;
    else lend = end.getTime();
    return lbegin < ltime && ltime < lend;
};
//得到当年的第几周
Date.prototype.getWeekOfYear = function() {
    var beginDate = new Date(this.getFullYear(), 0, 1, 0, 0, 0, 0);
    var times = this.getTime() - beginDate.getTime();
    times = (times / (1000 * 60 * 60 * 24 * 7)).toInt();
    var n = beginDate.getDay();   //今年第一天星期几
    if (n != 0)  times = times + 1;
    return times;
};
//--------------------------------------数组
//向数组中添加一项, 如果该项在数组中已经存在,则不再添加.
Array.prototype.include = function (item) {
    if (!this.contains(item)) this.push(item);
    return this;
};
//将主调数组和另一个数组进行组合(重复的项将不会加入)
Array.prototype.combine = function (array) {
    for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
    return this;
};
//判断当前环境是否有满足min,max,的环境变量,checkbox 验证的时候使用
//和服务器版本不同,检查表单,服务器版本检查请求变量
Array.prototype.any = function (min, imax) {
    var len = this.length;
    var m = 0;
    for (var i = 0; i < len; i++) {
        var fBox = $(this[i]);
        if (!fBox) continue;
        if ('checkbox' == fBox.getProperty('type').toLowerCase() && fBox.getProperty("checked")) m++;
        else
        if ('radio' == fBox.getProperty('type').toLowerCase() && fBox.getProperty("checked")) m++;
        else
        if ('text' == fBox.getProperty('type').toLowerCase() && fBox.get('value')!='') m++;
    }
    if (imax == undefined) return min <= m;
    return min <= m && m <= imax;
};
Array.prototype.sum = function () {
    var a = this;
    if ((a instanceof Array) || // if array
            (a && typeof a == "object" && "length" in a)) { // or array like
        var total = 0;
        for (var i = 0; i < a.length; i++) {
            var element = a[i];
            if (!element) continue;  // ignore null and undefined elements
            if (typeof element == "number") total += element;
            else throw new Error("sum(): all array elements must be numbers");
        }
        return total;
    }
    else throw new Error("sum(): argument must be an array");
};

Array.prototype.max = function () {
    var m = Number.NEGATIVE_INFINITY;
    for (var i = 0; i < this.length; i++)
        if (this[i] > m) m = this[i];
    return m;
};
Array.prototype.min = function () {
    var m = Number.MAX_VALUE;
    for (var i = 0; i < this.length; i++)
        if (this[i] < m) m = this[i];
    return m;
};
Array.prototype.avg = function () {
    var a = this;
    if ((a instanceof Array) || // if array
            (a && typeof a == "object" && "length" in a)) { // or array like
        var m = 0;
        for (var i = 0; i < a.length; i++)
            m = a[i] + m;
        return m / a.length;
    }
    else throw new Error("avg(): argument must be an array");
};
Array.prototype.getLast = function() {
    return (this.length) ? this[this.length - 1] : null;
};
Array.prototype.erase = function(item) {
    for (var i = this.length; i--; i) {
        if (this[i] === item) this.splice(i, 1);
    }
};
Array.prototype.empty = function() {
    this.length = 0;
    return this;
};
Array.prototype.options = function(sel) {
    return this.options(sel, ":");
};
Array.prototype.options = function(sel, keyf) {
    if (keyf == null || keyf == undefined) keyf = ":";
    var out = "";
    for (var i = 0; i < this.length; i++) {
        if (this[i] == "") continue;
        var hav = this[i].indexOf(keyf);
        if (hav == -1) {
            out = out + "<option value=\"" + this[i] + "\"";
            if (this[i] == sel) out = out + ' selected="selected"';
            out = out + ">" + this[i] + "</option>";
        } else {
            var keys = this[i].substring(0, hav);
            var vars = this[i].substring(hav + 1, this[i].getLength());
            out = out + "<option value=\"" + keys + "\"";
            if (keys == sel) out = out + ' selected="selected"';
            out = out + ">" + vars + "</option>";
        }
    }
    return out;
};
Array.prototype.show = function (sel) {
    if ($type(sel) == 'number') sel = sel + '';
    for (var i = 0; i < this.length; i++) {
        if (this[i] == "") continue;
        var hav = this[i].indexOf(":");
        if (hav != -1) {
            var keys = this[i].substring(0, hav);
            if (keys == sel)
                return this[i].substring(hav + 1, this[i].getLength());
        } else
        if (this[i] == sel) return sel;
    }
    return '';
};
Array.prototype.radio = function (rname, sel) {
    return this.radio(rname, sel, null, ":");
};
Array.prototype.radio = function (rname, sel, style, keyf) {
    if (keyf == null || keyf == undefined) keyf = ":";
    var out = "";
    for (var i = 0; i < this.length; i++) {
        if (this[i] == "") continue;
        var hav = this[i].indexOf(keyf);
        if (hav == -1) {
            out = out + '<label class="radioLabel">';
            out = out + ' <input id="' + rname + i + '" name="' + rname + '" type="radio" value="' + this[i] + '"';
            if (this[i] == sel) out = out + ' checked="checked"';
            if (style && style != "") out = out + ' style="' + style + '" ';
            out = out + ' />' + this[i] + '</label>';
        } else {
            var keys = this[i].substring(0, hav);
            var vars = this[i].substring(hav + 1, this[i].getLength());
            out = out + '<label class="radioLabel">';
            out = out + '<input id="' + rname + i + '" name="' + rname + '" type="radio" value="' + keys + '" ';
            if (keys == sel) out = out + 'checked="checked" ';
            if (style && style != "") out = out + 'style="' + style + '" ';
            out = out + ' />' + vars + '</label>';
        }
    }
    return out;
};
Array.prototype.checkbox = function (rname, sel) {
    return this.checkbox(rname, sel, null, ":");
};
Array.prototype.checkbox = function (rname, selected, style, keyf) {
    if (keyf == null || keyf == undefined) keyf = ":";
    var sel;
    if (typeof(selected) == "string")
        sel = selected.split(";");
    else sel = selected;
    var out = "";
    for (var i = 0; i < this.length; i++) {
        if (this[i] == "") continue;
        var hav = this[i].indexOf(keyf);
        if (hav == -1) {
            out = out + '<label class="radioLabel">';
            out = out + ' <input id="' + rname + i + '" name="' + rname + '" type="checkbox" value="' + this[i] + '" ';
            if (sel && sel.contains(this[i])) out = out + 'checked="checked" ';
            if (style && style != "") out = out + 'style="' + style + '" ';
            out = out + ' />' + this[i] + '</label>';
        } else {
            var keys = this[i].substring(0, hav);
            var vars = this[i].substring(hav + 1, this[i].getLength());
            out = out + '<label class="radioLabel">';
            out = out + '<input id="' + rname + i + '" name="' + rname + '" type="checkbox" value="' + keys + '"';
            if (sel && sel.contains(keys)) out = out + ' checked="checked" ';
            if (style && style != "") out = out + 'style="' + style + '" ';
            out = out + ' />' + vars + '</label>';
        }
    }
    return out;
};
//将数组转换为ajax请求参数的形式
Array.prototype.toQueryString = function (name) {
    var paramStr = '';
    for (var i = 0; i < this.length; i++) {
        paramStr = paramStr + name + '=' + this[i];
        if (this.length - 1 != i) paramStr = paramStr + '&';
    }
    return paramStr;
};
//--------------------------------------全局函数
//最大值
//noinspection JSDuplicatedDeclaration
function max(/* ... */) {
    var m = Number.NEGATIVE_INFINITY;
    for (var i = 0; i < arguments.length; i++)
        if (arguments[i] > m) m = arguments[i];
    return m;
}
//最小值
//noinspection JSDuplicatedDeclaration
function min(/* ... */) {
    var m = Number.MAX_VALUE;
    for (var i = 0; i < arguments.length; i++)
        if (arguments[i] < m) m = arguments[i];
    return m;
}
//合计
//noinspection JSDuplicatedDeclaration
function sum(/* ... */) {
    var m = 0;
    for (var i = 0; i < arguments.length; i++)
        m = arguments[i] + m;
    return m;
}
//平均
//noinspection JSDuplicatedDeclaration
function avg(/* ... */) {
    var m = 0;
    for (var i = 0; i < arguments.length; i++)
        m = arguments[i] + m;
    return m / arguments.length;
}

/**
 * 得到url参数，能得到3种url参数
 * 1. 例如：friendlist.jsp#a=3&b=7   得到参数a的值  $g("#","a")
 * 2. 例如：friendlist.jsp#3_7   得到参数a的值  $g("#",1) 得到7  从0开始
 * 3. 例如：friendlist.jsp?a=3&b=7   得到参数a的值  $g("b") 得到7
 *
 */
function $g() {
    var Url = top.window.location.href;
    var u,vname;
    if (arguments[0] == "#") {
        u = Url.split("#");
        if (arguments[1] == '*') return u[1];
        var bq = "";
        if (u[1] && u[1].indexOf('_') != -1) bq = u[1].split("_");
        if ($type(arguments[1]) == 'number' && bq.length >= arguments[1]) return bq[arguments[1]];
        vname = arguments[1] + "=";
    }
    else {
        u = Url.split("?");
        vname = arguments[0] + "=";
    }
    if (u.length <= 1) g = '';
    else g = u[1];
    if (g != '') {
        gg = g.split("&");
        for (i = 0; i < gg.length; i++) {
            var indexof = gg[i].indexOf(vname);
            if (indexof == 0) {
                return gg[i].substring(vname.length, gg[i].length);
            }
        }
    }
    return '';
}
/**
 * iframe自适应高度
 * iframeHeightBind.periodical(1000,"plist");
 */
var iframeHeightBind = function() {
    var iframe = document.getElementById(this);
    var height = 0;
    if (Browser.Engine.trident && iframe.Document && iframe.Document.body && iframe.Document.body.scrollHeight) //ie5+ syntax
    {
        height = iframe.Document.body.scrollHeight;
    } else {
        var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
        if (innerDoc && innerDoc.body && innerDoc.body.offsetHeight) {
            height = innerDoc.body.offsetHeight + 32; //Extra height FireFox
        }
        //else if (height<10) height = 800;
    }
    if (height < 1) height = 400;
    iframe.height = height;
};
//得到屏幕宽高
window.document.getPosition = function() {
    var doc = document.documentElement;
    if (document.documentElement && document.documentElement.clientHeight) {
        return {x :(doc.clientWidth > doc.scrollWidth) ? doc.clientWidth - 1 : doc.scrollWidth,
            y:(doc.clientHeight > doc.scrollHeight) ? doc.clientHeight : doc.scrollHeight};
    }
    else {
        return {x: (window.innerWidth > doc.scrollWidth) ? window.innerWidth : doc.scrollWidth,
            y:(window.innerHeight > doc.scrollHeight) ? window.innerHeight : doc.scrollHeight};
    }
};
