/*
 *  @author yangzeming
 *  @date  2014-04-01
 $('form').validate({
				onKeyup : true,
				eachValidField : function() {

					$(this).closest('div').removeClass('error').addClass('success');
				},
				eachInvalidField : function() {

					$(this).closest('div').removeClass('success').addClass('error');
				}
			});

			$.validateExtend({
				age : {
					required : true,
					conditional : function(value) {

						return Number(value) > 17;
					},
					pattern : /^[0-9]+$/
				}
			});
        data-validaterole : 标示需要检验的表单  data-pattern : 验证表达式  data-valid : 成功后的提示  data-invalid : 失败后的提示
        data-extend:  标示要另外需要验证扩展
 */
define("component/validate", function (require, exports, module) {
    var validateUtils = {
        // 是否为空
        isBlank: {
			condition : function (val,message) {
				if($.trim(val)==""){
					return {
						condition : false,
						message : message
					
					};
				}else{
					return {
						condition : true,
						message : message
					
					};
				}
				
			},
			message : "输入不能为空"
		},
        // 是否全为数字
        isNum: {
			pattern : /^[0-9]+$/,
			condition : null,
			message : "输入正确的电子邮箱"
		},
		// 是否为正确的邮箱
		isEmail : {
			pattern : /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,
			condition : null,
			message : "输入正确的电子邮箱"
		},
        // 是否为中文
		isChinese : {
			pattern : /^[\u2E80-\u9FFF]+$/,
			condition : null,
			message : "输入中文"
		},
        // 是否为正确的手机号码
		isPhone : {
			pattern : /^(130|131|132|133|134|135|136|137|138|139|145|147|150|151|152|153|155|156|157|158|159|180|181|182|183|185|186|187|188|189)\d{8}$/,
			condition : null,
			message : "输入正确的手机号"
		}
        
        // 是否为正确的身份证
        // 是否不超过多少位字符
        // 是否不超过多少位英文字符
        // 是否为正确的日期

    };
    var validateRules = {
		 "default" : ["isBlank"],
		 email : ["isBlank","isEmail"],
		 phone : ["isBlank","isPhone"],
		 chinese : ["isBlank","isChinese"]
	
	};
    var validate = _.Class({
        initial : function(options){
            var defaultOp = {
                onKeyup : true,    // 代表是否需要系统自己去监听keyup事件
                eachValidField : function(){},
				onBlur : true,
				onChange : true,
					// Default namespace
				nameSpace : 'validate',
				onSubmit : "",
				trigger:[],
                eachInvalidField : function(){
				}
            };
			this.validateCondition = $.extend(true,{},validateUtils);
			this.valdateRules = $.extend(true,{},validateRules);
            this.options = $.extend(true,{},defaultOp,options);
            this.$con = $(options.con);
			//this.$submit = $(options.onSubmit);
			this.validate();
        
        },
		// 获取元判断条件
		getValidateCon : function(key){
			var self = this,
				vcon = self.validateCondition[key] || self.validateCondition['default'];
			return vcon;
		
		},
	    // 正则匹配引擎
		patternEngine : function(pattern,message,val){
		
			//if($.type(pattern) == 'regexp'){
				if(!pattern.test(val)){
					return {
						condition : false,
						message : message
					
					};
				}else{
					return {
						condition : true,
						message : message
					
					};
				}
			
			//}
		},
		// 添加元条件判断
		setValidateCon : function(obj){
			var self = this;
			$.extend(true,self.validateCondition,obj);

		},
		// 设置拼装规则
		setValidateRule : function(obj){
			var self = this;
			$.extend(true,self.valdateRules,obj);
		
		},
		// 解析验证规则拼装引擎
		validateEngine : function(ruleKey,val){
			var conArray = this.valdateRules[ruleKey],
				self = this;
			for(var i = 0,len=conArray.length;i<len;i++){
				var vcon = self.getValidateCon(conArray[i]);
				var pattern = vcon.pattern,
					message = vcon.message,
					condition = vcon.condition,
					pattern = vcon.pattern;
				if($.isFunction(condition)){
					var state = condition(val,message);
					if(!state.condition){
						return state;
					}
				}
				if($.type(pattern) == 'regexp'){
					var sp = self.patternEngine(pattern,message,val);
					if(!sp.condition){
						return sp;
					}
				}
			}
			return {
				condition : true,
				message : "成功"
			};

		},
		// 自带的一些拼装规则
		validateField : function(that,event, options) {

			var
				// Field status
				status = {
					condition : true,
					message : "成功"
				},

				// Current field
				field = $(that),

				// Current field value
				fieldValue = field.val() || '',

				// An index of extend
				fieldValidate = field.data('rule') || 'default';
		
			status = this.validateEngine(fieldValidate,fieldValue);
			if(!status.condition){
				options.eachInvalidField(status,field);
			}else{
				options.eachValidField(status,field);
			}
			// Returns the field status
			return status;
		},
		validateAll : function(event,success,error){
			var formValid = true;
			var self = this,
				options = this.options;
			var fields = this.$con.find("[data-validaterole]");
			fields.each(function(){
				var status = self.validateField(this, event, options);
				if(!status.condition) {
						
					  formValid = false;
				}
			});
			if(formValid){
				if($.type(success)==="string")
					self.trigger(success);
				if($.type(success)==="function"){
					$.proxy(success,self);
					success();
				}
			}else{
				event.preventDefault();
				if($.type(error)==="string")
					self.trigger(error);
				if($.type(error)==="function"){
					$.proxy(error,self);
					error();

				}
			}
		
		},
        validate : function(){
            var fields = this.$con.find("[data-validaterole]"),
                options = this.options,
				self = this,
                namespace = options.namespace;
            if(!!options.onKeyup) {

			    fields.off('keyup.' + namespace).on('keyup.' + namespace, function(event) {

					self.validateField(this, event, options);
				});
			}

			// If onBlur is enabled
			if(!!options.onBlur) {

				fields.off('blur.' + namespace).on('blur.' + namespace, function(event) {

					self.validateField(this, event, options);
				});
			}

			// If onChange is enabled
			if(!!options.onChange) {

				fields.off('change.' + namespace).on('change.' + namespace, function(event) {

					self.validateField(this, event, options);
				});
			}
			// 做一些事件的绑定
			var onSubmit = this.options.onSubmit;
			if($.type(onSubmit) === "string"){
				var $temp = $(onSubmit);
				if(!!$temp){
					$temp.off('click.' + namespace).on('click.' + namespace, function(event) {
						self.validateAll(event,"onsubmit","onerror");
					});
				}
			}
			if($.type(onSubmit) === "array"){
				 var $t = onSubmit;
				 $t.each(function(index,value){
					 var $this = $(value);
					 if(!!$this){
						$this.off('click.' + namespace).on('click.' + namespace, function(event) {
							self.validateAll(event,"onsubmit"+value,"onerror"+value);
						});
					}
				 });			
			}
				
        
        }
    });

    module.exports = validate;
});