﻿////////////////////
//验证组件
//Created By : Yozo Chen
// 兼容(IE 6.0+, Firefox , Opera 和 Safari )
////////////////////

var DataValidatorBaseEx = new Class({
	options: {
	    msgWidth:180,
		msgContainerTag: "div",
		msgClass: "DataValidator-msg",
		BaseBrowser:false,
		ifrHeight:130,
		ifrID:'',

//      styleMouseOver: {"background-color": "#ffffff", "border-color": "#00ff00"},//聚焦的样式
//		styleNeutral: {"background-color": "#ffffff", "border-color": "#67BFEA"},//正常的样式
//		styleInvalid: {"background-color": "#ffffff", "border-color": "#67BFEA"},//错误的样式
//		styleValid: {"background-color": "#ffffff", "border-color": "#67BFEA"},//正确后的样式

        styleMouseOver: {"background-color": "", "border-color": ""},	                
        styleNeutral: {"background-color": "", "border-color": ""},
        styleInvalid: {"background-color": "", "border-color": ""},
        styleValid: {"background-color": "", "border-color": ""},

		required: {type: "required", re: /[^.*]/, msg: "此项是必填项。",neutralMsg: "",invalidMsg:"此项是必填项。"},
		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,
		onValid: Class.empty,
		onInvalid: Class.empty,
		className:'',
		functionName:'',
		showAlertMessage:false
	},

	initialize: function(form, options) {
	    this.sFormId = form;
		this.form = $(form);
		this.setOptions(options);
        
		this.fields = this.form.getElements("*[class^=DataValidate]");
		this.validations = [];
        this.checkErrors = [];
        this.submitButton = $(this.options.submitButtonId);
        if(this.submitButton)
        {

            //Create By KennyPeng On 20080522
            //实现表单回车提交
           this.form.action='javascript:;';
           this.form.addEvents({"submit":this._onButtonClick.bind(this)});
            var buttonHtml = this.submitButton.outerHTML;
            buttonHtml = buttonHtml.replace('type=button','type=submit');   //IE
            buttonHtml = buttonHtml.replace('type="button"','type="submit"');   //FireFox
            this.submitButton.outerHTML = buttonHtml;

//            this.submitButton.addEvents({
//			    "click": this._onButtonClick.bind(this)
//        
//		    });
        }
//       var me = this;
//       this.form.addEvents({
//		 "keypress": function(event){
//		    var e = new Event(event);
//		    if (e.key == 'enter') 
//		    {
//		        me._onButtonClick(e);
//		    }
//		  }
//	    });

        
        
        
		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));
		
		//根据xml配置自动填充
		this.AutoDataValidator(options);
		
		this.form.addEvents({
			//"submit": this._onSubmit.bind(this),
			"reset": this._onReset.bind(this)
		});
	},

    AutoDataValidator:function(options)
    {          
        //设置参数
        this.setOptions(options);   
        
        var my = this;

        //如果函数名和类名为空，直接返回
        if((this.options.className == '') && (this.options.functionName == ''))
        {
            alert("需要校验的表单，类名和函数名必须同时具备！");
            return;
        }        
         //获取正则表达式字典
         var myAjax = new Ajax('/XML/DataValidateXML/RegExpRule.xml',{method:'get',onComplete:function(txt,xmlRule)
         {            
                var ruleXmlDom = new XMLDom(xmlRule);            
                var arr = my.options.className.split(".");
                var path = "/XML/DataValidateXML/" +arr[arr.length-2] + "/" + arr[arr.length-1] + ".xml";
                //获取验证配置
                var myAjax = new Ajax(path,{method:'get',onComplete:function(txt,xmlFun)
                {                    
                    var xmlDom = new XMLDom(xmlFun);                    
                    //循环加载数据验证
                    var nodes = xmlDom.getNodesByNode(xmlDom.getNodeByAttribute(xmlDom.getNodes("Function"),'Name',my.options.functionName),"Property");
                    for(var i=0;i<nodes.length;i++)
                    {                        
                        var name = xmlDom.getNodeAttributeValue(nodes[i],"Name");
                        var ruleCode = xmlDom.getNodeAttributeValue(nodes[i],"RuleCode");
                        var message = xmlDom.getNodeAttributeValue(nodes[i],"Message");
                        var errMessage = xmlDom.getNodeAttributeValue(nodes[i],"ErrorMessage");
                        var reg = ruleXmlDom.getNodeValue(ruleXmlDom.getNode(ruleXmlDom.getNodes("RuleConfig"),"RuleCode",ruleCode),"JSRegExp")
                        switch (ruleCode)
                        {                            
                            case "NotNull":
                                my.register($(name), {type: "required",re:new RegExp(reg),neutralMsg: message,invalidMsg:errMessage});
                                break;                                
                            case "AjaxCheck":
                                my.register($(name), {type: "ajaxCheck", neutralMsg: message,invalidMsg:errMessage});
                                break;
                            case "AjaxCheckEmail":
                                my.register($(name), {type: "ajaxCheckEmail", neutralMsg: message,invalidMsg:errMessage});
                                break;
                            default:
                                my.register($(name), {type: "custom", re:new RegExp(reg), neutralMsg: message,invalidMsg:errMessage}); 
                                break;
                        }                    
                    }           
                
                },onFailure:function(){                
                    //显示失败提示信息
                    //alert("服务器连接失败，请检查网络是否断开！");       
                    
                }}).request();        
        },onFailure:function(){
        //alert("数据加载失败！"); 
        }}).request();      
    },    

	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][1] == 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) {
         if (this.options.showAlertMessage)
         {
            return;
         }
    	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() {eIconValid.remove()}
		    }).start(1, 0);
		}
		if(eIconInvalid){
            //移除
            eIconInvalid.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {eIconInvalid.remove()}
		    }).start(1, 0);
		}
        
        if(eMsgInvalid){
            //移除
            eMsgInvalid.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {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);
				if(this.options.BaseBrowser=='true' && (owner.getProperty('id')==this.options.ifrID))
				{
				    ifr = new Element('iframe',{'id': owner.getProperty('id') + '_Msg_Neutral_ifr' });                
				    ifr.setStyle('position', 'absolute');
                    ifr.setStyle('text-align', 'left');
                    ifr.setStyle('z-index', '100000');
                    ifr.setStyle('left', iMsgLeft);
                    ifr.setStyle('top', iMsgTop);
                    ifr.setStyle('height', this.options.ifrHeight+'px');
                    ifr.setStyle('width', this.options.msgWidth+12+'px');
                    ifr.setProperty('frameborder', '0');
                    ifr.setProperty('border', '0');
                    ifr.setStyle('filter', 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0) ');
				    ifr.injectAfter(owner);
				}

		}
		
		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('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 sInvalidTextId = owner.getProperty("id") + "_Msg_Invalid_" + options.type;
        var eInvalidText = $(sInvalidTextId);
        var isExist = false;
        this.checkErrors.each(function(errorObj){
            if(errorObj[1] == sInvalidTextId){
                isExist = true;
            }
        });
        if(!isExist){
            var errorObj = new Array();
            errorObj[0] = owner.getProperty("id");
            errorObj[1] = sInvalidTextId;
            errorObj[2] = options.invalidMsg;                
            this.checkErrors.push(errorObj);
            var iTemp = owner.getAttribute('cbErr');
            iTemp++;
            owner.setAttribute('cbErr',iTemp);
            this._chkStatus(owner, options);
        }
         if (this.options.showAlertMessage)
         {           
            return;
         }
	
	    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(this.options.BaseBrowser=='true' && (owner.getProperty('id')==this.options.ifrID))
		{
		    var eMsgifr = $(owner.getProperty('id') + '_Msg_Neutral_ifr');
		}
		//添加出错图标
		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() {eIconNeutral.remove()}
		    }).start(1, 0);
		}
		if(eIconValid){
            //移除
            eIconValid.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {eIconValid.remove()}
		    }).start(1, 0);
		}
		if(eMsgNeutral){
            //移除
            eMsgNeutral.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {eMsgNeutral.remove()}
		    }).start(1, 0);
	    
		}
		if(this.options.BaseBrowser=='true' && (owner.getProperty('id')==this.options.ifrID))
		{
		    if(eMsgifr){
                //移除
                eMsgifr.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {try{eMsgifr.remove()}catch(e){}}
		        }).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);
		}		

        if(!eInvalidText){
            eInvalidText = new Element('div', {"id": sInvalidTextId})
                .setHTML(options.invalidMsg)
                .setStyle('text-align', 'left')
                .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) {
        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][1] == sInvalidTextId){
                    //isExist = true;
                    this.checkErrors.splice(i,1);
	                iTemp--;
	                owner.setAttribute('cbErr',iTemp);
	                this._chkStatus(owner, options);
                    break;
                }
            }
        }	
         if (this.options.showAlertMessage)
         {
            return;
         }
	    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(this.options.BaseBrowser=='true' && (owner.getProperty('id')==this.options.ifrID))
		{
		    var eMsgifr = $(owner.getProperty('id') + '_Msg_Neutral_ifr');
		}
            
		if(eIconNeutral){
            //移除
            eIconNeutral.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {eIconNeutral.remove()}
		    }).start(1, 0);
		}
        if(eMsgNeutral){
            //移除
            eMsgNeutral.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {eMsgNeutral.remove()}
		    }).start(1, 0);
		}
		if(this.options.BaseBrowser=='true' && (owner.getProperty('id')==this.options.ifrID))
		{
		    if(eMsgifr){
                //移除
                eMsgifr.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {try{eMsgifr.remove()}catch(e){}}
		        }).start(1, 0);
		        
		    }
		}		

        if(eInvalidText){
		    eInvalidText.effect("opacity", {
			    duration: 500,
			    transition: Fx.Transitions.linear,
			    onComplete: function() {eInvalidText.remove()}
		    }).start(1, 0);
        }

        if(iTemp < 1 ){
            if(eIconInvalid){
                //移除
                eIconInvalid.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {eIconInvalid.remove()}
		        }).start(1, 0);
            }
            if(eMsgInvalid){
                //移除
                eMsgInvalid.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {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() {eIconValid.remove()}
		        }).start(1, 0);
            }
        }else{
            if(eIconValid){
                //移除
                eIconValid.effect("opacity", {
			        duration: 500,
			        transition: Fx.Transitions.linear,
			        onComplete: function() {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][1] == 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][1] == 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();
		
		if ((!isValid) && (this.options.showAlertMessage))
		{
		       for(var i=0;i<this.checkErrors.length;i++)
		       {
		            $(this.checkErrors[i][0]).focus();
		            alert(this.checkErrors[i][2]);
                    break;
		       }
//                this.checkErrors.each(function(sError){
//                    
//                });				
		}
		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));
	}
});
DataValidatorBaseEx.implement(new Events); // Implements addEvent(type, fn), fireEvent(type, [args], delay) and removeEvent(type, fn)
DataValidatorBaseEx.implement(new Options);// Implements setOptions(defaults, options)

