﻿////////////////////
//验证组件
//Created By : Yozo Chen
// 兼容(IE 6.0+, Firefox , Opera 和 Safari )
////////////////////

var DataValidator = new Class({
	options: {
	    msgWidth:180,
		msgContainerTag: "div",
		msgClass: "DataValidator-msg",

        styleMouseOver: {"background-color": "#ffffff", "border-color": "#26AC00"},//聚焦的样式
		styleNeutral: {"background-color": "#ffffff", "border-color": "#67BFEA"},//正常的样式
		styleInvalid: {"background-color": "#ffffff", "border-color": "#67BFEA"},//错误的样式
		styleValid: {"background-color": "#ffffff", "border-color": "#67BFEA"},//正确后的样式

		required: {type: "required", re: /[^.*]/, msg: "此项是必填项。",neutralMsg: "",invalidMsg:"此项是必填项。"},
		alpha: {type: "alpha", re: /^[a-z ._-]+$/i, msg: "只能输入字母字符。",neutralMsg: "只能输入字母字符",invalidMsg:"只能输入字母字符。"},
		alphanum: {type: "alphanum", re: /^[a-z0-9 ._-]+$/i, msg: "只能输入字母和数字。",neutralMsg: "只能输入字母和数字",invalidMsg:"只能输入字母和数字。"},
		integer: {type: "integer", re: /^[-+]?\d+$/, msg: "请输入整数。",neutralMsg: "请输入整数",invalidMsg:"请输入整数。"},
		plusint: {type: "plusint", re: /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/, msg: "不能输入负数。",neutralMsg: "",invalidMsg:"不能输入负数。"},
		real: {type: "real", re: /^[-+]?\d*\.?\d+$/, msg: "请输入数字。",neutralMsg: "请输入数字",invalidMsg:"请输入数字。"},
		date: {type: "date", re: /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/, msg: "请输入有效的日期，格式为(mm/dd/yyyy)。",neutralMsg: "请输入有效的日期，格式为(mm/dd/yyyy)",invalidMsg:"无效的日期，格式为(mm/dd/yyyy)。"},
		email: {type: "email", re: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i, msg: "请输入有效的邮件地址。",neutralMsg: "请输入有效的邮件地址",invalidMsg:"请输入有效的邮件地址。"},
		phone: {type: "phone", re: /^[\d\s ().-]+$/, msg: "请输入有效的电话号码。",neutralMsg: "请输入有效的电话号码",invalidMsg:"请输入有效的电话号码。"},
		url: {type: "url", re: /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i, msg: "请输入有效的url.",neutralMsg: "请输入有效的url",invalidMsg:"请输入有效的url。"},
		confirm: {type: "confirm", msg: "两次输入的密码不一致。",neutralMsg: "请您再次输入上面设置的密码!",invalidMsg:"两次输入密码不一致，请重新输入!"},
        //20080121,Yozo:添加ajax验证
        ajaxCheck:{type: "ajaxCheck",url:'', msg: "不可用。",neutralMsg: "不可用",invalidMsg:"不可用。"},
        //
        //20080121,Yozo:添加图片验证码
        checkCode:{type: "checkCode",cookieName:'CheckCode', msg: "输入的验证码不正确。",neutralMsg: "输入验证码",invalidMsg:"输入的验证码不正确。"},
        //
 
 	    submitButtonId:'Submit1',
	    onButtonClick:Class.empty,//function(){alert('111')}
		onValid: Class.empty,
		onInvalid: Class.empty
	},

	initialize: function(form, options) {
	    this.sFormId = form;
		this.form = $(form);
		this.setOptions(options);
        //this.options.submitButtonId = form.id + '_submit';
        
		this.fields = this.form.getElements("*[class^=DataValidate]");
		this.validations = [];
        this.checkErrors = [];
        this.submitButton = $(this.options.submitButtonId);
        if(this.submitButton){
            this.submitButton.addEvents({
			    "click": this._onButtonClick.bind(this)
		    });
        }
		this.fields.each(function(element) {
			if(!this._isChildType(element)) element.setStyles(this.options.styleNeutral);
			element.cbErr = 0;
			var classes = element.getProperty("class").split(' ');
			classes.each(function(klass) {
				if(klass.match(/^DataValidate(\[.+\])$/)) {
					var aFilters = eval(klass.match(/^DataValidate(\[.+\])$/)[1]);
					for(var i = 0; i < aFilters.length; i++) {
					
						if(this.options[aFilters[i]]){
						    this.register(element, this.options[aFilters[i]]);
						}else{		
				            //20080122,Yozo:添加区间验证
                            var aRangPropertys = aFilters[i].split('-');
                            if(aRangPropertys.length == 3){
                                var rangOption = {type: "rang",re:/^.{1,50}$/, msg: "字符数必须在1—50区间。",neutralMsg: "字符数必须在1—50区间",invalidMsg:"字符数必须在1—50区间。"};
                                switch(aRangPropertys[0]){
                                    case "numEnRang":
                                        rangOption.re = new RegExp("^[\\w]{"+aRangPropertys[1] +","+aRangPropertys[2] +"}$");
                                        rangOption.msg = '输入字符(英文和数字)数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                        rangOption.neutralMsg = '输入字符(英文和数字)数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间';
                                        rangOption.invalidMsg = '输入字符(英文和数字)数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                        break;
                                    case "allRang":
                                        rangOption.re = new RegExp("^.{"+aRangPropertys[1] +","+aRangPropertys[2] +"}$");
                                        rangOption.msg = '输入字符数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                        rangOption.neutralMsg = '输入字符数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间';
                                        rangOption.invalidMsg = '输入字符数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                        break;
                                    case "cnRang":
                                        rangOption.re = new RegExp("^[\u4e00-\u9fa5]{"+aRangPropertys[1] +","+aRangPropertys[2] +"}$");
                                        rangOption.msg = '输入字符数(中文)必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                        rangOption.neutralMsg = '输入字符数(中文)必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间';
                                        rangOption.invalidMsg = '输入字符数(中文)必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                        break;
                                    default:
                                        rangOption.re = new RegExp("^.{"+aRangPropertys[1] +","+aRangPropertys[2] +"}$");
                                        rangOption.msg = '输入字符数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                        rangOption.neutralMsg = '输入字符数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间';
                                        rangOption.invalidMsg = '输入字符数必须在'+aRangPropertys[1] +'—'+aRangPropertys[2] +'之间。';
                                }
                                
                                this.register(element, rangOption);
                            }
                            // 
						}
						if(aFilters[i].charAt(0) == '='){
						    //20080124,Yozo:添加不区分大小写比较
						    var aUpLow = aFilters[i].split('-');
						    if(aUpLow[1]){
						        this.register(element, $extend(this.options.confirm, {idField: aUpLow[0].substr(1), noUpLow: true}));
						    }else{
						        this.register(element, $extend(this.options.confirm, {idField: aFilters[i].substr(1), noUpLow: false}));
						    }
						    //
						} 
					}
				}
			}.bind(this));
		}.bind(this));

		this.form.addEvents({
			//"submit": this._onSubmit.bind(this),
			"reset": this._onReset.bind(this)
		});
	},

	register: function(field, options) {
	    if(!field) return;

	    if(field.form){
	        if(field.form.id != this.sFormId) return;
	    }else{
	        return;
	    }

	    

		
		if(!this._isChildType(field)) field.setStyles(this.options.styleNeutral);
		field.parentNode.style.position = 'relative';
		field.setAttribute('cbErr',0);
		this.validations.push([field, options]);
		
		field.addEvent("blur", function() {
		    field.setStyles(this.options.styleNeutral);
			if(this._isChildType(field))
			    this._validateChild(field, options);
			else
			    if((field.value.length == 0 && options.type =='required') || field.value.length > 0){
			        this._validate(field, options);
			    }else{
			        //清除错误计数
			        var iTemp = field.getAttribute('cbErr');
			        var sInvalidTextId = field.getProperty("id") + "_Msg_Invalid_" + options.type;
			        for(var i = 0; i < this.checkErrors.length; i++){
                        if(this.checkErrors[i] == sInvalidTextId){
                            this.checkErrors.splice(i,1);
	                        iTemp--;
	                        field.setAttribute('cbErr',iTemp);
	                        this._chkStatus(field, options);
                            break;
                        }
                    }
			        //field.setAttribute('cbErr',0);
			        //移除正常信息
			        var eIconNeutral = $(field.getProperty('id') + '_Icon_Neutral');
		            var eMsgNeutral = $(field.getProperty('id') + '_Msg_Neutral');

		            if(eIconNeutral){
                        //移除
                        eIconNeutral.effect("opacity", {
			                duration: 500,
			                transition: Fx.Transitions.linear,
			                onComplete: function() {if(eIconNeutral.parentNode) eIconNeutral.remove();}
		                }).start(1, 0);
		            }
			        if(eMsgNeutral){
                        //移除
                        eMsgNeutral.effect("opacity", {
			                duration: 500,
			                transition: Fx.Transitions.linear,
			                onComplete: function() {if(eMsgNeutral.parentNode) eMsgNeutral.remove();}
		                }).start(1, 0);
		            }
			    }
		}.bind(this));
		field.addEvent("focus", function() {
		    //if(field.getAttribute('cbErr') <= 0 )    //有错误的时候聚焦不显示正常信息
		    field.setStyles(this.options.styleMouseOver);
		    
			    this._showNeutralTip(field, options);	    
		}.bind(this));
	},

	_isChildType: function(el) {

		 var elType = el.type.toLowerCase();
		if((elType == "radio") || (elType == "checkbox")) return true;
		return false;
	},

	_validate: function(field, options) {
		switch(options.type) {
			case "confirm":
			    //20080124,Yozo:添加不区分大小写比较
			    var sIdField = "";
			    var sField = "";
			    if(options.noUpLow){
			        sIdField = $(options.idField).getValue().toLowerCase();
			        sField = field.getValue().toLowerCase();
			    }else{
			        sIdField = $(options.idField).getValue();
			        sField = field.getValue();
			    }
			    //
				if(sIdField == sField) this._msgRemove(field, options);
				else this._msgInject(field, options);
				break;
				
			//20080121,Yozo:添加ajax验证
//			case "ajaxCheck":
//			    var my = this;
//			    if(field.getValue() != ""){
//			        var myAjax = new Ajax(options.url+field.getValue(), {
//                        method: 'get',onSuccess:function(text,xml){
//                            if(text == 'true'){
//                                my._msgRemove(field, options);
//                            }else{
//                                my._msgInject(field, options);
//                            }
//                        }
//                    }).request();
//			    }else{
//			        my._msgRemove(field, options);
//			    }
//                break;
            //
            case "ajaxCheck":
                var my = this;
                if(field.getValue() != ""){
                    var xmlData = new AjaxXml("User.ValidatorUserName","UserInfo");
                    xmlData.setTextNode("UserName",field.getValue().trim());
                    var d = xmlData.getXML();
                    var myAjax = new Ajax('',{method:'post',data:d,onComplete:function(txt,xml){
                        try{
                            var xmlDom = new XMLDom(xml);       
                            var sucessed = xmlDom.getValue("Succeed");   
                            if(sucessed == "1"){                                                             
                                if(xmlDom.getValue("Bool")=="True"){      
                                    my._msgRemove(field, options);
                                }else{
                                    my._msgInject(field, options);
                                }  
                            }else{
                                //显示失败提示信息
                                alert(xmlDom.getValue("Message"));
                            }                        
                            
                        }catch(e){
                            alert(e.message);
                        }
                    },onFailure:function(){
                        //alert('网络连接失败，请重新再试');
                    }}).request();
			    }else{
			        my._msgRemove(field, options);
			    }
                break;
            case "ajaxCheckEmail":
                var my = this;
                if(field.getValue() != ""){
                    var xmlData = new AjaxXml("User.ValidatorEmail","UserInfoAssis");
                    xmlData.setTextNode("Email",field.getValue().trim());
                    var d = xmlData.getXML();
                    var myAjax = new Ajax('',{method:'post',data:d,onComplete:function(txt,xml){
                        try{                        
                            var xmlDom = new XMLDom(xml);       
                            var sucessed = xmlDom.getValue("Succeed");   
                            if(sucessed == "1"){                                                             
                                if(xmlDom.getValue("Bool")=="True"){      
                                    my._msgRemove(field, options);
                                }else{
                                    my._msgInject(field, options);
                                }  
                            }else{
                                //显示失败提示信息
                                alert(xmlDom.getValue("Message"));
                            }                        
                            
                        }catch(e){
                            alert(e.message);
                        }
                    },onFailure:function(){
                        //alert('网络连接失败，请重新再试');
                    }}).request();
			    }else{
			        my._msgRemove(field, options);
			    }
                break;
            
            //20080121,Yozo:添加图片验证码
			case "checkCode":
                var checkCode = Cookie.get("CheckCode");
			    if(field.getValue().toLowerCase() != checkCode.toLowerCase()){
                    this._msgInject(field, options);
			    }else{
			        this._msgRemove(field, options);
			    }
                break;
            //
            
			default:
				if(options.re.test(field.getValue())) this._msgRemove(field, options);
				else this._msgInject(field, options);
		}
	},

	_validateChild: function(child, options) {
		var nlButtonGroup = this.form[child.getProperty("name")];
		var cbCheckeds = 0;
		var isValid = true;
 		for(var i = 0; i < nlButtonGroup.length; i++) {
			if(nlButtonGroup[i].checked) {
				cbCheckeds++;
//				if(!options.re.test(nlButtonGroup[i].getValue())) {
//					isValid = false;
//					break;
//				}
			}
		}
		if(cbCheckeds == 0 && options.type == "required") isValid = false;
		if(isValid) this._msgRemove(child, options);
		else this._msgInject(child, options);
	},



    _showNeutralTip: function(owner, options) {
    	var iIconLeft = owner.offsetLeft +owner.offsetWidth + 3;
        var iIconTop = owner.offsetTop + 3;
        var iMsgLeft = iIconLeft + 23;
        var iMsgTop = owner.offsetTop;
    
	    var eIconNeutral = $(owner.getProperty('id') + '_Icon_Neutral');
        var eIconInvalid = $(owner.getProperty('id') + '_Icon_Invalid');
		var eIconValid = $(owner.getProperty('id') + '_Icon_Valid');
		var eMsgNeutral = $(owner.getProperty('id') + '_Msg_Neutral');
		var eMsgInvalid = $(owner.getProperty('id') + '_Msg_Invalid');
        
		if(eIconValid){
            //移除
            eIconValid.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eIconValid.parentNode) eIconValid.remove();}
		    }).start(1, 0);
		}
		if(eIconInvalid){
            //移除
            eIconInvalid.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eIconInvalid.parentNode) eIconInvalid.remove();}
		    }).start(1, 0);
		}
        
        if(eMsgInvalid){
            //移除
            eMsgInvalid.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eMsgInvalid.parentNode) eMsgInvalid.remove();}
		    }).start(1, 0);
		}
		
        if(!eIconNeutral && options.neutralMsg !=''){
            //添加
			eIconNeutral = new Element('div', {'id': owner.getProperty('id') + '_Icon_Neutral' })
		        .setStyle('position', 'absolute')
		        .setStyle('text-align', 'left')
                .setStyle('top', iIconTop)
                .setStyle('left', iIconLeft)
                .setHTML('<img src=\'/Images/Hqen/icon_note_small.gif\'>')
                .setStyle("opacity", 0)
                .injectAfter(owner)
				.effect("opacity", {
					duration: 500,
					transition: Fx.Transitions.linear
				}).start(0, 1);
		}
		
		if(!eMsgNeutral && options.neutralMsg !=''){
		    //添加
			eMsgNeutral = new Element('div', {'id': owner.getProperty('id') + '_Msg_Neutral' })
                .setStyle('position', 'absolute')
                .setStyle('text-align', 'left')
                .setStyle('z-index', '100001')
                .setStyle('left', iMsgLeft)
                .setStyle('top', iMsgTop)
                .setStyle('width', this.options.msgWidth+'px')
                .setStyle('border', 'solid 1px #BEBEBE')
                .setStyle('padding', '6px 5px 4px 5px')
                .setStyle('background-color', '#E7F9FF')
                .setHTML('<img src="/Images/Hqen/tipArrow_blue.gif" style="position:absolute;top:6px;left:-7px;">')
                .setStyle("opacity", 0)
                .injectAfter(owner)
				.effect("opacity", {
					duration: 500,
					transition: Fx.Transitions.linear
				}).start(0, 1);
		}
		
		var sNeutralTextId = owner.getProperty("id") + "_Msg_Neutral_" + options.type;
        var eNeutralText = $(sNeutralTextId);
// && (options.type != 'required' || (options.type == 'required' && !eMsgNeutral))
        if(!eNeutralText && options.neutralMsg !=''){
            eNeutralText = new Element('div', {"id": sNeutralTextId})
                .setStyle('text-align', 'left')
                .setStyle('word-wrap', 'break-word')
                .setStyle('word-break', 'break-all')
                .setStyle('z-index', '100002')
                .setHTML(options.neutralMsg)
                .setStyle("opacity", 0)
                .injectInside(owner.getProperty("id") + "_Msg_Neutral")
				.effect("opacity", {
					duration: 500,
					transition: Fx.Transitions.linear
				}).start(0, 1);
        }
		

	},

	_msgInject: function(owner, options) {
	    var iIconLeft = owner.offsetLeft +owner.offsetWidth + 3;
        var iIconTop = owner.offsetTop + 3;
        var iMsgLeft = iIconLeft + 23;
	    var iMsgTop = owner.offsetTop;
	
	    var eIconNeutral = $(owner.getProperty('id') + '_Icon_Neutral');
        var eIconInvalid = $(owner.getProperty('id') + '_Icon_Invalid');
		var eIconValid = $(owner.getProperty('id') + '_Icon_Valid');
		
		var eMsgNeutral = $(owner.getProperty('id') + '_Msg_Neutral');
		var eMsgInvalid = $(owner.getProperty('id') + '_Msg_Invalid');
		//添加出错图标
		var sIconInvalidId = owner.getProperty('id') + '_Icon_Invalid';
		var sIcon = 'function removeIcon(sIconInvalidId){var eIconInv = $(sIconInvalidId);if(!eIconInv) return; eIconInv.effect("opacity", { duration: 500, transition: Fx.Transitions.linear, onComplete: function() {eIconInv.remove()} }).start(1, 0);}removeIcon(\''+sIconInvalidId+'\'); ';
		
		if(!eIconInvalid){
			eIconInvalid = new Element('div', {'id': owner.getProperty('id') + '_Icon_Invalid' })
		        .setStyle('position', 'absolute')
                .setStyle('top', iIconTop)
                .setStyle('left', iIconLeft)
                .setHTML('<img src=\'/Images/Hqen/icon_error_small.gif\'>')
                .setStyle("opacity", 0)
                .injectAfter(owner)
				.effect("opacity", {
					duration: 500,
					transition: Fx.Transitions.linear,
					onComplete: function() {setTimeout(sIcon,3000);}
				}).start(0, 1);
		}
		if(eIconNeutral){
            //移除
            eIconNeutral.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eIconNeutral.parentNode) eIconNeutral.remove();}
		    }).start(1, 0);
		}
		if(eIconValid){
            //移除
            eIconValid.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eIconValid.parentNode) eIconValid.remove();}
		    }).start(1, 0);
		}
		if(eMsgNeutral){
            //移除
            eMsgNeutral.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eMsgNeutral.parentNode) eMsgNeutral.remove();}
		    }).start(1, 0);
		}
		//添加出错消息容器
		if(!eMsgInvalid){
		
		var sMsgInvalidId = owner.getProperty('id') + '_Msg_Invalid';
		var str = 'function removeMsg(sMsgInvalidId){var eMsgInv = $(sMsgInvalidId);if(!eMsgInv) return; eMsgInv.effect("opacity", { duration: 500, transition: Fx.Transitions.linear, onComplete: function() {eMsgInv.remove()} }).start(1, 0);}removeMsg(\''+sMsgInvalidId+'\');';

			eMsgInvalid = new Element('div', {'id': owner.getProperty('id') + '_Msg_Invalid' })
                .setStyle('position', 'absolute')
                .setStyle('text-align', 'left')
                .setStyle('z-index', '100001')
                .setStyle('left', iMsgLeft)
                .setStyle('top', iMsgTop)
                .setStyle('width', this.options.msgWidth+'px')
                .setStyle('border', 'solid 1px #BEBEBE')
                .setStyle('padding', '6px 5px 4px 5px')
                .setStyle('background-color', '#FFF2E9')
                .setHTML('<img src="/Images/Hqen/tipArrow_red.gif" style="position:absolute;top:6px;left:-7px;">')
                .setStyle("opacity", 0)
                .injectAfter(owner)
				.effect("opacity", {
					duration: 500,
					transition: Fx.Transitions.linear,
					onComplete: function() {setTimeout(str,3000);}
				}).start(0, 1);
		}
		
        var sInvalidTextId = owner.getProperty("id") + "_Msg_Invalid_" + options.type;
        var eInvalidText = $(sInvalidTextId);
        var isExist = false;
        
        this.checkErrors.each(function(sError){
            if(sError == sInvalidTextId){
                isExist = true;
            }
        });
        if(!isExist){
            this.checkErrors.push(sInvalidTextId);
            var iTemp = owner.getAttribute('cbErr');
            iTemp++;
            owner.setAttribute('cbErr',iTemp);
            this._chkStatus(owner, options);
        }
        
        if(!eInvalidText){
            eInvalidText = new Element('div', {"id": sInvalidTextId})
                .setHTML(options.invalidMsg)
                .setStyle('text-align', 'left')
                .setStyle('word-wrap', 'break-word')
                .setStyle('word-break', 'break-all')
                .injectInside(owner.getProperty("id") + "_Msg_Invalid")
                .setStyle("opacity", 0)
				.effect("opacity", {
					duration: 500,
					transition: Fx.Transitions.linear
				}).start(0, 1);
        }
	},

	_msgRemove: function(owner, options, isReset) {
	    isReset = isReset || false;
		var iIconLeft = owner.offsetLeft +owner.offsetWidth + 3;
        var iIconTop = owner.offsetTop + 3;
        var iMsgLeft = iIconLeft + 23;
	    
	    var eIconNeutral = $(owner.getProperty('id') + '_Icon_Neutral');
        var eIconInvalid = $(owner.getProperty('id') + '_Icon_Invalid');
		var eIconValid = $(owner.getProperty('id') + '_Icon_Valid');
		var eMsgNeutral = $(owner.getProperty('id') + '_Msg_Neutral');
		var eMsgInvalid = $(owner.getProperty('id') + '_Msg_Invalid');
            
		if(eIconNeutral){
            //移除
            eIconNeutral.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eIconNeutral.parentNode) eIconNeutral.remove();}
		    }).start(1, 0);
		}
        if(eMsgNeutral){
            //移除
            eMsgNeutral.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eMsgNeutral.parentNode) eMsgNeutral.remove();}
		    }).start(1, 0);
		}
        var iTemp = owner.getAttribute('cbErr');
        var sInvalidTextId = owner.getProperty("id") + "_Msg_Invalid_" + options.type;
        var eInvalidText = $(sInvalidTextId);
        //var isExist = false;
        if(!isReset) {
            for(var i = 0; i < this.checkErrors.length; i++){
                if(this.checkErrors[i] == sInvalidTextId){
                    //isExist = true;
                    this.checkErrors.splice(i,1);
	                iTemp--;
	                owner.setAttribute('cbErr',iTemp);
	                this._chkStatus(owner, options);
                    break;
                }
            }
        }
        if(eInvalidText){
		    eInvalidText.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {if(eInvalidText.parentNode) eInvalidText.remove();}
		    }).start(1, 0);
        }

        if(iTemp < 1 ){
            if(eIconInvalid){
                //移除
                eIconInvalid.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {if(eIconInvalid.parentNode) eIconInvalid.remove();}
		        }).start(1, 0);
            }
            if(eMsgInvalid){
                //移除
                eMsgInvalid.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {if(eMsgInvalid.parentNode) eMsgInvalid.remove();}
		        }).start(1, 0);
            }
            //添加正确图标
//            if(!eIconValid && !isReset){
//                //添加
//                eIconValid = new Element('div', {'id': owner.getProperty('id') + '_Icon_Valid' })
//		            .setStyle('position', 'absolute')
//                    .setStyle('top', iIconTop)
//                    .setStyle('left', iIconLeft)
//                    .setHTML('<img src=\'/Images/Hqen/icon_ok_small.gif\'>')
//                    .setStyle("opacity", 0)
//                    .injectAfter(owner)
//				    .effect("opacity", {
//					    duration: 500,
//					    transition: Fx.Transitions.linear
//				    }).start(0, 1);
//            }
            if(eIconValid && isReset){
                //移除
                eIconValid.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {if(eIconValid.parentNode) eIconValid.remove();}
		        }).start(1, 0);
            }
        }else{
            if(eIconValid){
                //移除
                eIconValid.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {if(eIconValid.parentNode) eIconValid.remove();}
		        }).start(1, 0);
            }
        }
	},

	_chkStatus: function(field, options) {
		if(field.cbErr == 0) {
			//field.effects({duration: 500, transition: Fx.Transitions.linear}).start(this.options.styleValid);
			this.fireEvent("onValid", [field, options], 50);
		} else {
			//field.effects({duration: 500, transition: Fx.Transitions.linear}).start(this.options.styleInvalid);
			this.fireEvent("onInvalid", [field, options], 50);
		}
	},
    _onButtonClick: function(event) {
		if(this._onSubmit(event)) this.options.onButtonClick();
	},
	getState:function(){
	    var isValid = true;

		this.validations.each(function(array) {
			if(this._isChildType(array[0]))
			    this._validateChild(array[0], array[1]);
			else{
			    if((array[0].value.length == 0 && array[1].type =='required') || array[0].value.length > 0){
			        this._validate(array[0], array[1]);
			    }else{
			        //清除错误计数
			        var iTemp = array[0].getAttribute('cbErr');
			        var sInvalidTextId = array[0].getProperty("id") + "_Msg_Invalid_" + array[1].type;
			        for(var i = 0; i < this.checkErrors.length; i++){
                        if(this.checkErrors[i] == sInvalidTextId){
                            this.checkErrors.splice(i,1);
	                        iTemp--;
	                        array[0].setAttribute('cbErr',iTemp);
	                        this._chkStatus(array[0], array[1]);
                            break;
                        }
                    }
                }
			}
			    
			if(array[0].getAttribute('cbErr') > 0)
			    isValid = false;
			
		}.bind(this));
		
		return isValid;
	},
	_onSubmit: function(event) {
		event = new Event(event);
		var isValid = true;

		this.validations.each(function(array) {
			if(this._isChildType(array[0]))
			    this._validateChild(array[0], array[1]);
			else{
			    if((array[0].value.length == 0 && array[1].type =='required') || array[0].value.length > 0){
			        this._validate(array[0], array[1]);
			    }else{
			        //清除错误计数
			        var iTemp = array[0].getAttribute('cbErr');
			        var sInvalidTextId = array[0].getProperty("id") + "_Msg_Invalid_" + array[1].type;
			        for(var i = 0; i < this.checkErrors.length; i++){
                        if(this.checkErrors[i] == sInvalidTextId){
                            this.checkErrors.splice(i,1);
	                        iTemp--;
	                        array[0].setAttribute('cbErr',iTemp);
	                        this._chkStatus(array[0], array[1]);
                            break;
                        }
                    }
                }
			}
			    
			if(array[0].getAttribute('cbErr') > 0)
			    isValid = false;
			
		}.bind(this));

		if(!isValid) event.stop();
		return isValid;
		
	},

	_onReset: function() {
	    this.checkErrors.splice(0,this.checkErrors.length);
		this.validations.each(function(array) {
			if(!this._isChildType(array[0])) array[0].setStyles(this.options.styleNeutral);
			array[0].setAttribute('cbErr',0);
			this._msgRemove(array[0], array[1], true);
		}.bind(this));
	}
});
DataValidator.implement(new Events); // Implements addEvent(type, fn), fireEvent(type, [args], delay) and removeEvent(type, fn)
DataValidator.implement(new Options);// Implements setOptions(defaults, options)



function AutoDataValidator(){
    var url = "/XML/DataValidateXML/RegExpRule.xml";
    var myAjax = new Ajax(url,{method:'get',onComplete:getDataRuleXml,onFailure:function(){alert("未能加载数据验证文件，请确认网络是否连接！\n");}}).request();
    
}


function getRexExp(fieldName,xmlDom){
    var sRexExp = xmlDom.getNodeValue(xmlDom.getNode(xmlDom.getNodes("RuleConfig"),"RuleCode",fieldName),"JSRegExp");
    return new RegExp(sRexExp);
}


