﻿// 通用验证类v1.005
function ObjValidator() {
    // 验证信息数组
    this.ChkInfos = new Array();
    
    // 提示信息的方向
    this.MsgDirection = "right";
    
    // 当鼠标移出时，是否验证为空
    this.FocusOutChkRequired = false;
    
    // 是否显示验证成功的提示信息
    this.ShowSucceed = true;
    
    // 是否锁定验证成功信息
    this.LockSucceed = true;
    
    // 是否锁定验证失败信息
    this.LockError = true;
    
    // 默认提示信息样式 
    this.DefaultCss = "";
    
    // 获得焦点时提示信息样式
    this.FocusCss = "";
    
    // 获得焦点时控件的样式
    this.FocusControlCss = "";
    
    // 验证失败时提示信息样式
    this.ErrorCss = "";
    
    // 验证成功时提示信息样式
    this.SucceedCss = "";
    
    // 系统提示消息Id
    this.SysMsgId = "sysmsg";
    
    // 是否使用iframe遮盖, 解决select遮盖
    this.Iframe = true;
    
    // 提示层的位置
    this.zIndex = 999;
    
    // 验证控件类型
    this.ChkControlType = function(type) {
        var types = new Array("text", "password", "select-one", "file", "textarea", "checkbox");
        for (var i = 0; i < types.length; i++) {
            if (type == types[i]) {
                return true;
            }
        }
        
        return false;
    }
    
    // 显示提示信息
    this.ShowMessage = function(ctl, css, chkinfo, msg, lock) {
        var alerter_id = ctl.attr("id") + "_msg";
        var alerter = $("#" + alerter_id);
        var iframe_id = ctl.attr("id") + "_iframe";
        var iframe = $("#" + iframe_id);
        
        // 如果不存在alerter则创建
        if (alerter.length < 1) {
            $("body").append("<div id='" + alerter_id + "'></div>");
            alerter = $("#" + alerter_id);
        }
        
        // 如果不存在iframe则创建
        if (this.Iframe) {
            if (iframe.length < 1) {
                $("body").append("<iframe id='" + iframe_id + "' frameborder='0' scrolling='no'><html></iframe>");
                iframe = $("#" + iframe_id);
            }
        }
        
        // 如果chkinfo有值，则进行锁定判断
        if (lock) {
            if (chkinfo.lockerror) {
                if (alerter.attr("class") == chkinfo.errorcss && ctl.val() != "") {
                    return;
                }
            }
            if (chkinfo.locksucceed) {
                if (alerter.attr("class") == chkinfo.succeedcss) {
                    return;
                }
            }
        }
        
        // 隐藏
        this.HiddenMessage(ctl);
        
        // 设置样式
        this.zIndex = this.zIndex >= 10000 ? 10000 : this.zIndex + 1;
        alerter.attr("class", css);
        alerter.css({"position" : "absolute", "z-index" : this.zIndex});
        
        // 设置提示内容
        alerter.html("");
        if (msg != undefined) {
            if (msg != "") { alerter.html(msg);}
        }
        
        // 设置位置
        var pos = ctl.offset();
        switch (chkinfo.msgdirection) {
            case "top":
                alerter.css({"top" : pos.top - alerter.height(), "left" : pos.left});
                break;
            case "left":
                alerter.css({"top" : pos.top, "left" : pos.left - alerter.width()});
                break;
            case "right":
                alerter.css({"top" : pos.top, "left" : pos.left + ctl.width()});
                break;
            case "bottom":
                alerter.css({"top" : pos.top + ctl.height(), "left" : pos.left});
                break;
            default:
                alerter.css({"top" : 0, "left" : 0});
                break;
        }
        
        // 设置iframe样式
        if (this.Iframe) {
            iframe.css({
                "position" : "absolute", 
                "z-index" : alerter.css("z-index") - 1, 
                "width" : alerter.width(), 
                "height" : alerter.height(), 
                "top" : alerter.css("top"), 
                "left" : alerter.css("left"),
                "display" : ""
            });
            
            iframe.attr("allowtransparency", "true");
            
            // 设置iframe的padding与margin
            var drifts = new Array("padding-top", "padding-right", "padding-bottom", "padding-left", "margin-top", "margin-right", "margin-bottom", "margin-left");
            for (var i = 0; i < drifts.length; i++) {
                if (alerter.css(drifts[i]) != "" && alerter.css(drifts[i]) != "0px" && alerter.css(drifts[i]) != 0) {
                    iframe.css(drifts[i], alerter.css(drifts[i]));
                }
            }
            
            // 设置iframe的border
            var borders = new Array("border-top-width", "border-right-width", "border-bottom-width", "border-left-width");
            for (var i = 0; i < borders.length; i++) {
                if (alerter.css(borders[i]) != "" && alerter.css(borders[i]) != "0px" && alerter.css(borders[i]) != 0) {
                    if (i == 0 || i == 2) {
                        var height = parseInt(iframe.height()) + parseInt(alerter.css(borders[i]));
                        iframe.css("height", height);
                    }
                    else {
                        var width = parseInt(iframe.width()) + parseInt(alerter.css(borders[i]));
                        iframe.css("width", width);
                    }
                }
            }
        }

        // 显示提示消息
        alerter.css({"display" : ""});
    }
    
    // 隐藏提示信息
    this.HiddenMessage = function(ctl) {
        var alerter_id = ctl.attr("id") + "_msg";
        var alerter = $("#" + alerter_id);
        var iframe_id = ctl.attr("id") + "_iframe";
        var iframe = $("#" + iframe_id);
        if (alerter.length > 0) {
            if (alerter.css("display") != "none") {
                alerter.attr("class", "");
                alerter.css("display", "none");
            }
        }
        if (iframe.length > 0) {
            if (iframe.css("display") != "none") {iframe.css("display", "none");}
        }
    }
    
    // 隐藏指定ID的消息
    this.HiddenMessagesById = function(id) {
        var ids = id.split(",");
        for (var i = 0; i < ids.length; i++) {
            this.HiddenMessage($("#" + ids[i]));
        }
    }
    
    // 显示提示信息为服务端
    this.ShowServerMessage = function(id, css, direction, msg) {
        var ctl = $("#" + id);
        var chkinfo = {msgdirection: direction};
        this.ShowMessage(ctl, css, chkinfo, msg, false);
    }
    
    // 显示指定位置的提示信息
    this.ShowSysMessage = function(css, msg) {
        var alerter = $("#" + this.SysMsgId);
        if (alerter.length < 1) {
            return;
        }
        
        // 设置样式
        alerter.attr("class", css);
        alerter.css("display", "block");
        
        // 设置提示内容
        alerter.html(msg);
    }
    
    // 隐藏指定位置的提示信息
    this.HiddenSysMessage = function() {
        var alerter = $("#" + this.SysMsgId);
        if (alerter.length > 0) {
            if (alerter.css("display") != "none") {
                alerter.css("display", "none");
            }
        }
    }
    
    // 绑定控件获得焦点时样式
    this.BindControlFocusCss = function(ctl, focuscontrolcss) {
        // 确定样式
        var defcss = ctl.attr("class");
        var newcss = defcss != "" ? defcss + " " + focuscontrolcss : focuscontrolcss;
        
        // 绑定事件
        ctl.focusin(function(){
            ctl.addClass(newcss);
        });
        ctl.focusout(function(){
            ctl.removeClass(focuscontrolcss);
        });
    }
    
    // 绑定控件内部提示信息
    this.BindControlInnerMsg = function(ctl, innermsg) {
        if (ctl.val() == "") {
            ctl.val(innermsg);
            ctl.css("color", "#999");
        }
        
        // 焦点进入
        ctl.focusin(function() {
            if (ctl.val() == innermsg) {
                ctl.val("");
                ctl.css("color", "");
            }
        });
        
        // 焦点离开
        ctl.focusout(function(){
            if (ctl.val() == "") {
                ctl.val(innermsg);
                ctl.css("color", "#999");
            }
        });
    }
    
    // 初始化配置信息
    this.InitChkInfoConfig = function(chkinfo) {
        // 全局
        if (chkinfo.msgdirection == undefined) {
            chkinfo.msgdirection = this.MsgDirection;
        }
        if (chkinfo.focusoutchkrequired == undefined) {
            chkinfo.focusoutchkrequired = this.FocusOutChkRequired;
        }
        if (chkinfo.showsucceed == undefined) {
            chkinfo.showsucceed = this.ShowSucceed;
        }
        if (chkinfo.locksucceed == undefined) {
            chkinfo.locksucceed = this.LockSucceed;
        }
        if (chkinfo.lockerror == undefined) {
            chkinfo.lockerror = this.LockError;
        }
        if (chkinfo.defaultcss == undefined) {
            chkinfo.defaultcss = this.DefaultCss;
        }
        if (chkinfo.focuscss == undefined) {
            chkinfo.focuscss = this.FocusCss;
        }
        if (chkinfo.focuscontrolcss == undefined) {
            chkinfo.focuscontrolcss = this.FocusControlCss;
        }
        if (chkinfo.errorcss == undefined) {
            chkinfo.errorcss = this.ErrorCss;
        }
        if (chkinfo.succeedcss == undefined) {
            chkinfo.succeedcss = this.SucceedCss;
        }
        
        // 验证项
        if (chkinfo.chkrequired == undefined) {
            chkinfo.chkrequired = false;
        }
        if (chkinfo.chklen == undefined) {
            chkinfo.chklen = false;
        }
        if (chkinfo.chkcompare == undefined) {
            chkinfo.chkcompare = false;
        }
        if (chkinfo.chkregular == undefined) {
            chkinfo.chkregular = false;
        }
        if (chkinfo.chkcustom == undefined) {
            chkinfo.chkcustom = false;
        }
        if (chkinfo.chkajax == undefined) {
            chkinfo.chkajax = false;
        }
        
        return chkinfo;
    }
    
    // 注册验证控件
    this.RegValidator = function(chkinfo) {
        // 验证基础信息
        if (!chkinfo) {
            return;
        }
        else if (!chkinfo.id) {
            return;
        }
        
        // 获取控件
        var ctl = $("#" + chkinfo.id);
        if (ctl.length < 1) {
            return;
        }
        
        // 验证控件类型
        var ctltype = ctl.get(0).type.toLowerCase(); 
        if (!this.ChkControlType(ctltype)) {
            return;
        }
        
        // 初始化信息
        chkinfo = this.InitChkInfoConfig(chkinfo);
        
        // 加入数组
        this.ChkInfos[this.ChkInfos.length] = chkinfo;
        
        // 绑定控件获得焦点时样式
        if (chkinfo.focuscontrolcss != "") {
            this.BindControlFocusCss(ctl, chkinfo.focuscontrolcss);
        }
        
        // 绑定控件默认提示信息
        if (chkinfo.defaultmsg && chkinfo.defaultmsg != "") {
            this.ShowMessage(ctl, chkinfo.defaultcss, chkinfo, chkinfo.defaultmsg);
        }
        
        // 绑定控件内部提示信息,仅限text,textarea
        if (chkinfo.innermsg && chkinfo.innermsg != "" && (ctltype == "text" || ctltype == "textarea")) {
            this.BindControlInnerMsg(ctl, chkinfo.innermsg);
        }
        
        // 绑定获得焦点时的提示信息
        if (chkinfo.focusmsg && chkinfo.focusmsg != "") {
            with(this) {
                ctl.focusin(function(){
                    ShowMessage(ctl, chkinfo.focuscss, chkinfo, chkinfo.focusmsg, true);
                });
            }
        }
        
        // 隐藏系统消息
        with(this) {
            ctl.focusin(function(){
                HiddenSysMessage();
            });
        }
        
        // 失去焦点时进行验证
        with(this) {
            ctl.focusout(function(){
                ValidateControl("focusout", ctl, chkinfo);
            });
        }
    }
    
    // 验证
    this.ValidateControl = function(validatetype, ctl, chkinfo) {
        // 取值
        var val = ctl.val();
        val = $.trim(val);
        
        // 获取控件类型
        var ctltype = ctl.get(0).type.toLowerCase(); 
        
        // 特殊值处理
        if (chkinfo.innermsg && chkinfo.innermsg != "" && val == chkinfo.innermsg) {
            val = "";
        }
        else if (ctltype == "checkbox") {
            if (ctl.attr("checked")) {
                val = "1";
            }
            else {
                val = "";
            }
        }
        
        // 必填验证
        if (chkinfo.chkrequired && (validatetype == "form" || (validatetype == "focusout" && chkinfo.focusoutchkrequired))) {
            if (val == "") {
                this.ShowMessage(ctl, chkinfo.errorcss, chkinfo, chkinfo.requiredmsg);
                return false;
            }
        }
        else {
            // 非必填为空时，则跳出验证
            if (val == "") {
                // 绑定控件默认提示信息
                if (chkinfo.defaultmsg && chkinfo.defaultmsg != "") {
                    this.ShowMessage(ctl, chkinfo.defaultcss, chkinfo, chkinfo.defaultmsg);
                }
                else {
                    this.HiddenMessage(ctl);
                }
                return true;
            }
        }
        
        // 隐藏上次提示
        this.HiddenMessage(ctl);
        
        // 长度验证,只text,password,textarea允许
        if (chkinfo.chklen && (ctltype == "text" || ctltype == "password" || ctltype == "textarea")) {
            if (val.length < chkinfo.minlen || val.length > chkinfo.maxlen) {
                this.ShowMessage(ctl, chkinfo.errorcss, chkinfo, chkinfo.lenmsg);
                return false;
            }
        }
        
        // 比较验证,只text,password,textarea允许
        if (chkinfo.chkcompare && (ctltype == "text" || ctltype == "password" || ctltype == "textarea")) {
            var comparectl = $("#" + chkinfo.compareid);
            if (comparectl.length < 1 || comparectl.val() != val) {
                this.ShowMessage(ctl, chkinfo.errorcss, chkinfo, chkinfo.comparemsg);
                return false;
            }
        }
        
        // 正则检查, select不允许正则检查
        if (chkinfo.chkregular && ctltype != "select-one") {
            // 判断是否有外部正则对象
            var haveobj = false;
            if (chkinfo.regobj != undefined) {
                if (typeof(chkinfo.regobj) == "object") {
                    haveobj = true;
                }
            }
            
            // 构造正则对象
            var reg;
            if (haveobj) {
                reg = chkinfo.regobj;
            }
            else {
                var haveattr = false;
                if (chkinfo.attributes != undefined) {
                    if (chkinfo.attributes != "") {
                        haveattr = true;
                    }
                }

                if (haveattr) {
                    reg = new RegExp(chkinfo.pattern, chkinfo.attributes);
                }
                else {
                    reg = new RegExp(chkinfo.pattern);
                }
            }
            
            // test
            if (!reg.test(val)) {
                this.ShowMessage(ctl, chkinfo.errorcss, chkinfo, chkinfo.regularmsg);
                return false;
            }
        }
        
        // 自定义外部函数检查
        if (chkinfo.chkcustom) {
            var reslut = eval(chkinfo.cusfunc + "('" + val + "')");
            if (!reslut) {
                this.ShowMessage(ctl, chkinfo.errorcss, chkinfo, chkinfo.cusmsg);
                return false;
            }
        }
        
        // ajax验证
        if (chkinfo.chkajax) {
            var async = validatetype == "form" ? false : true;
            var data = "data=" + val + "&r=" + Math.random();
            
            if (chkinfo.ajaxappend != undefined) {
                data = data + "&append=" + $("#" + chkinfo.ajaxappend).val();
            }
            
            if (chkinfo.ajaxobj != undefined && chkinfo.ajaxobj.length > 0) {
                data = data + "&append=" + chkinfo.ajaxobj.val();
            }
            
            with(this) {
                var result;
                $.ajax({
                    type: "GET",
                    url: chkinfo.ajaxurl,
                    cache: false,
                    async: async,
                    data: data,  
                    success: function(data) {
                        if (data == "0") {
                            // 成功提示
                            if (chkinfo.showsucceed) {
                                ShowMessage(ctl, chkinfo.succeedcss, chkinfo, chkinfo.succeedmsg);
                            }
                            else {
                                // 绑定控件默认提示信息
                                if (chkinfo.defaultmsg && chkinfo.defaultmsg != "") {
                                    ShowMessage(ctl, chkinfo.defaultcss, chkinfo, chkinfo.defaultmsg);
                                }
                                else {
                                    HiddenMessage(ctl);
                                }
                            }
                            
                            if (validatetype == "form") {
                                result = true;
                            }
                            else {
                                return true;
                            }
                        }
                        else {
                            ShowMessage(ctl, chkinfo.errorcss, chkinfo, data);
                            if (validatetype == "form") {
                                result = false;
                            }
                            else {
                                return false;
                            }
                        }
                    }
                });
                
                return result;
            }
        }
        else{
            // 成功提示
            if (chkinfo.showsucceed) {
                this.ShowMessage(ctl, chkinfo.succeedcss, chkinfo, chkinfo.succeedmsg);
            }
            else {
                // 绑定控件默认提示信息
                if (chkinfo.defaultmsg && chkinfo.defaultmsg != "") {
                    this.ShowMessage(ctl, chkinfo.defaultcss, chkinfo, chkinfo.defaultmsg);
                }
                else {
                    this.HiddenMessage(ctl);
                }
            }
            
            return true;
        }
    }
    
    // 销毁已绑定验证信息
    this.DestroyValidate = function(ctl) {
        // 解绑所有事件
        ctl.unbind();
        
        // 清空innermsg
        var chkinfo;
        for (var i = 0; i < this.ChkInfos.length; i++) {
            if (this.ChkInfos[i].id == ctl.attr("id")) {
                chkinfo = this.ChkInfos[i];
                break;
            }
        }
        
        if (chkinfo.innermsg && chkinfo.innermsg != "") {
            
            if (ctl.val() == chkinfo.innermsg) {
                ctl.val("");
                ctl.css("color", "");
            }
        }
        
        // 隐藏message
        this.HiddenMessage(ctl);
        
        // 重构验证数组
        var oldInfos = this.ChkInfos;
        this.ChkInfos = new Array();
        for (var i = 0; i < oldInfos.length; i++) {
            if (oldInfos[i].id != ctl.attr("id")) {
                this.ChkInfos[this.ChkInfos.length] = oldInfos[i];
            }
        }
    }
    
    // 验证表单
    this.ValidateForm = function() {
        // 检测
        if (this.ChkInfos.length < 1) {
            return;
        }
        
        // 循环验证
        var succeed = true;
        for (var i = 0; i < this.ChkInfos.length; i++) {
            var chkinfo = this.ChkInfos[i];
            var result = this.ValidateControl("form", $("#" + chkinfo.id), chkinfo);
            if (succeed) {
                succeed = result;
            }
        }
        
        return succeed;
    }
}

