/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */
var LANG_formplus = {
    validate: {
        required: '本项必填',
        minLength: '输入不正确，至少{minLength}个字符(已输入{length}个)',
        maxLength: '输入不正确，最多{maxLength}个字符(已输入{length}个)',
        unsignedint: '请填写正整数',
        number: '请填写数值',
        digits: '请填写整数',
        unsigned: '请填写大于等于0的数值',
        positive: '请输入大于0的数值',
        alpha: '请填写英文字母',
        alphaint: '请填写英文字母或者数字',
        alphanum: '请填写英文字母、中文及数字',
        date: '请填写日期，格式yyyy-mm-dd',
        email: '请填写正确的email地址',
        mobile: '请填写正确的手机号码',
        tel: '请填写正确的固定电话',
        phone: '请填写正确的电话或手机',
        zip: '请填写正确的邮编',
        url: '请填写正确的网址'
    }
};
//==扩展js方法
// 替换字符串中的字段
String.prototype.substitute = function (object, regexp) {
    return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function (match, name) {
        if (match.charAt(0) == '\\') return match.slice(1);
        return (object[name] != null) ? object[name] : ((name.indexOf(':') != -1) ? '{' + name + '}' : '');
    });
};
String.prototype.test = function (regex, params) {
    return (($.type(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
};
//＝基本表单验证
var validatorMap = {
    'required': [LANG_formplus['validate']['required'], function (element, v, type) {
        if (type == 'select-one' || type == 'select') {
            var index = element.selectedIndex;
            v = element.options[index].value;
            return index >= 0 && (v != '' && v != '_NULL_');
        }
        return v !== null && v.length !== 0;
    }],
    'minLength': [function (element, v, props) {
        if (props != 'null') {
            return LANG_formplus['validate']['minLength'].substitute({ minLength: props, length: v.length });
        }
        return '';
    }, function (element, v, type, props) {
        if (props != 'null') return v.length >= (props || 0);
        return true;
    }],
    'maxLength': [function (element, v, props) {
        if (props != 'null') {
            return LANG_formplus['validate']['maxLength'].substitute({ maxLength: props, length: v.length });
        }
        return '';
    }, function (element, v, type, props) {
        if (props != 'null') return v.length <= (props || 10000);
        return true;
    }],
    'digits': [LANG_formplus['validate']['digits'], function (element, v) {
        return v == null || v == '' || !/[^\d]/.test(v);
    }],
    'unsignedint': [LANG_formplus['validate']['unsignedint'], function (element, v) {
        return v == null || v == '' || (!/[^\d]/.test(v) && v > 0);
    }],
    'number': [LANG_formplus['validate']['number'], function (element, v) {
        return !isNaN(v) && !/^\s+$/.test(v);
    }],
    'unsigned': [LANG_formplus['validate']['unsigned'], function (element, v) {
        return (!isNaN(v) && !/^\s+$/.test(v) && v >= 0);
    }],
    'positive': [LANG_formplus['validate']['positive'], function (element, v) {
        return v == null || v == '' || (!isNaN(v) && !/^\s+$/.test(v) && v > 0);
    }],
    'alpha': [LANG_formplus['validate']['alpha'], function (element, v) {
        return v === null || v == '' || /^[a-zA-Z]+$/.test(v);
    }],
    'alphaint': [LANG_formplus['validate']['alphaint'], function (element, v) {
        return !/\W/.test(v) || /^[a-zA-Z0-9]+$/.test(v);
    }],
    'alphanum': [LANG_formplus['validate']['alphanum'], function (element, v) {
        return !/\W/.test(v) || /^[\u4e00-\u9fa5a-zA-Z0-9]+$/.test(v);
    }],
    'date': [LANG_formplus['validate']['date'], function (element, v) {
        return v === null || v == '' || /^(19|20)[0-9]{2}-([1-9]|0[1-9]|1[012])-([1-9]|0[1-9]|[12][0-9]|3[01])$/.test(v);
    }],
    'email': [LANG_formplus['validate']['email'], function (element, v) {
        return v === null || v == '' || /^[a-z\d][a-z\d_.]*@[\w-]+(?:\.[a-z]{2,})+$/i.test(v);
    }],
    'mobile': [LANG_formplus['validate']['mobile'], function (element, v) {
        return v === null || v == '' || /^0?1[3-9]\d{9}$/.test(v);
    }],
    'tel': [LANG_formplus['validate']['tel'], function (element, v) {
        return v === null || v == '' || /^(0\d{2,3}-?)?[2-9]\d{5,7}(-\d{1,5})?$/.test(v);
    }],
    'phone': [LANG_formplus['validate']['phone'], function (element, v) {
        return v === null || v == '' || /^0?1[3-9]\d{9}$|^(0\d{2,3}-?)?[2-9]\d{5,7}(-\d{1,5})?$/.test(v);
    }],
    'zip': [LANG_formplus['validate']['zip'], function (element, v) {
        return v === null || v == '' || /^\d{6}$/.test(v);
    }],
    'url': [LANG_formplus['validate']['url'], function (element, v) {
        var pattern = "^((https|http|ftp|rtsp|mms)?://)"
            + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
            + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP
            + "|" // 允许IP和域名
            + "([0-9a-z_!~*'()-]+\.)*" // 主机名 www.
            + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
            + "[a-z]{2,6})" // 顶级域名 .com or .museum
            + "(:[0-9]{1,4})?" // 端口
            + "((/?)|" // 最后的/非必需
            + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; //查询参数
        var re = new RegExp(pattern, 'i');
        return v === null || v == '' || re.test(v);
    }]
};

var validate = function (control, success, error) {
    var _return = true;
    var inputs;
    if ($(control).is('form')) {
        inputs = $(control).find('[vtype],[pattern],[required]');
    } else {
        inputs = $(control);
    }
    inputs.each(function (i, element) {
        var vthis = $(this), vtype = vthis.attr('vtype');
        if ($(this).is(':hidden') || $(this).is(':disabled')) return true;

        var vtypes = vtype ? vtype.split('&&') : [], pattern = vthis.attr('pattern'),
            re = new RegExp(pattern), msg = vthis.data('caution') || vthis.attr('vtips') || '',
            ckey = 'custom_' + Date.parse(new Date()) + '_' + (100 + Math.round(Math.random() * 900));
        if (pattern) {
            if (!validatorMap[ckey]) {
                validatorMap[ckey] = [msg, function (element, v) {
                    return v === null || v === '' || re.test(v);
                }];
                vtypes.push(ckey);
            }
        }
        if (vthis.attr('required') && $.inArray('required', vtypes) == -1) {
            vtypes.push('required');
        }
        if (!vtypes.length) return true;
        //this.tagName

        if (_return == false) return true;

        $.each(vtypes, function (i, key) {
            if (!key) return true;
            var tips = '', keyprops = key.split(':');
            key = keyprops[0];
            if (keyprops.length > 1) {
                var props = keyprops[1];
            }

            var validator = validatorMap[key];

            if (!validator) return true;
            validator = $.isArray(validator) ? validator : ['', validator];

            if (msg) {
                tips = msg.split('&&');
                tips = tips[i] || '';
            }

            var caution = {
                el: element,
                msg: tips || ($.isFunction(validator[0]) ? validator[0](element, $.trim(vthis.val()), props) : validator[0])
            };

            validator = validator[1] || function () {
                return true
            };

            if (validator(element, $.trim(vthis.val()), element.type, props)) {
                success && success.call(vthis);
                return true;
            } else {
                _return = false;
                error && error.call(vthis, caution.msg);
                return false;
            }

        });


    });

    return _return;
};