var Common = new Object();
Common.trim = function(str){
	return str.replace(/(^\s*)|(\s*$)/g, "");
}

Common.strlen = function (str){
	var Charset = jQuery.browser.msie ?document.charset : document.characterSet
	if(Charset.toLowerCase() == 'utf-8'){
		return str.replace(/[\u4e00-\u9fa5]/g, "***").length;
	} else {
		return str.replace(/[^\x00-\xff]/g, "**").length;
	}
}
validator={
	formid:'form1',
	blurcheck:1,//是否每步都验证
	lastcheckmode:1,//0为检验错误信息，1为再重复验一遍
	lastcheck:1,//最后提交时是否再检查
	lastcheckalert:1,//最后提交时是否弹出提示框
	clickconfirm:1,//如为1当确定按钮提交时只验证，不提交表单，因为ajax不需要表单提交
	alerterrormsg:"数据输入有误，请再检查下",
	elements:"",
	outertag:":hidden",
	lastchecktime:0,//如为1表示已进入最后提交时刻
	controlancestortag:'tr',
	errmsg : 'errmsg',
	successMsg : '&nbsp;',
	errcls : 'no',
	yescls : 'yes',
	tipBox:'tipBox',
	errorTip : 'errorTip',
	successTip : 'successTip',
	normalTip : 'littletip',
	notest:'',
	errInput : 'errInput',//input框的错误类
	infoTags : 'div',
	validTip   : 'validTip',
	require : /[^(^\s*)|(\s*$)]/,
	notempty: /^[1-9]+.*$/,
	email : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
	phone : /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/,
	e532c28d5 : /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[89]\d{8}?$/,
	url : /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,	
	currency : /^\d+(\.\d+)?$/,
	currency2 : /^[0-9\$￥]+(\.\d+)?$|^$/,
	number : /^\d+$/,
	numberempty : /^\d*$/,
	numbernot0 : /^[1-9]+\d*$/,
	zip : /^[1-9]\d{5}$/,
	notnumber : /^[A-Za-z]*[\u0391-\uFFE5]*$/,
	ip  : /^[\d\.]{7,15}$/,
	qq : /^[1-9]\d{4,8}$/,
	integer : /^[-\+]?\d+$/,
	double : /^[-\+]?\d+(\.\d+)?$/,
	english : /^[A-Za-z]*[^\u0391-\uFFE5]+$/,
	emptyenglish : /^[A-Za-z]*[^\u0391-\uFFE5]+$|^$/,
	engnum : /^[A-Za-z0-9\*]+$/,
	chinese : /^[\u0391-\uFFE5]+$/,
	userName : /^[A-Za-z0-9_]{3,}$/i,
	//unSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
	unSafe : /[<>\?\#\$\*\&;\\\/\[\]\{\}=\(\)\.\^%,]/,
	//safeStr : /[^#\'\"~\.\*\$&;\\\/\|]/,

	idCard : "this.isIdCard(value)",
	boxrequire: "this.judgeboxempty()",
	safeString : "this.isSafe(value)",
	filter : "this.doFilter(value)",
	limit : "this.checkLimit(Common.strlen(value))",
	limitB : "this.checkLimit(this.LenB(value))",
	date : "this.isDate(value)",
	repeat : "this.checkRepeat(value)",
	range : "this.checkRange(value)",
	compare : "this.checkCompare(value)",
	custom : "this.Exec(value)",
	group : "this.mustChecked()",
	minimum:"this.isminimum(value)",
	dateaftertoday:"this.dateaftertoday2(value)",	
	maximum:"this.ismaximum(value)",
	ischecked:"this.Checked()",
	selected:/^[^0]/,
	change:"element.get(0).options.selectedIndex>-1",//select标签里面的option选中项必须大于-1
	select:"element.get(0).value!=''",
	selecthasoption:"element.find('option').length>0",//select标签里面必须有option
	verifypass:"getCookie('changesnet_userpwd')==MD5(value)",
	ajax: "this.doajax(value)",

	isSafe : function(str){return !this.unSafe.test(str);},
	isIdCard : function(number){
	var date, Ai;
	var verify = "10x98765432";
	var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
	var area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','西藏','','','','','','','陕西','甘肃','青海','宁夏','新疆','','','','','','台湾','','','','','','','','','','香港','澳门','','','','','','','','','国外'];

	var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i);
	if(re == null) return false;
	if(re[1] >= area.length || area[re[1]] == "") return false;
	if(re[2].length == 12){
		Ai = number.substr(0, 17);
		date = [re[9], re[10], re[11]].join("-");
	} else {
		Ai = number.substr(0, 6) + "19" + number.substr(6);
		date = ["19" + re[4], re[5], re[6]].join("-");
	}
	if(!this.isDate(date, "ymd")) return false;
	var sum = 0;
	for(var i = 0;i<=16;i++){
		sum += Ai.charAt(i) * Wi[i];
	}
	Ai += verify.charAt(sum%11);

	return (number.length ==15 || number.length == 18 && number == Ai);
	},
	
	
	dateaftertoday2:function(op) {
		if(op){
			today = new Date(); 
			today = new Date(today.getYear()+1900,today.getMonth() + 1,today.getDate());
			inputdatearr=op.split("-");
			inputdate= new Date(inputdatearr[0],inputdatearr[1],inputdatearr[2]);
			if(today>inputdate)
			{
				return false;
			}
		}
		return true; 
	},

	isDate : function(op){
		var formatString = this['element'].attr('format');
		formatString = formatString || "ymd";
		var m, year, month, day;
		switch(formatString){
		case "ymd" :
			m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
			if(m == null ) return false;
			day = m[6];
			month = m[5]*1;
			year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
		break;
		case "dmy" :
			m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
			if(m == null ) return false;
			day = m[1];
			month = m[3]*1;
			year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
		break;
		default :
			break;
		}
		if(!parseInt(month)) return false;
		month = month==0 ?12:month;
		var date = new Date(year, month-1, day);
		return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
		function GetFullYear(y){
			return ((y<30 ? "20" : "19") + y)|0;
		}
	}, //end isDate
	doFilter : function(value){
		var filter =this['element'].attr('accept');
		return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g,filter.split(/\s*,\s*/).join("|")),"gi").test(value);
	},
	judgeboxempty : function(){
		return this['element'].parent().find(":checked").length>0||this['element'].parent().find("option:selected").length>0;
	},
	

	checkLimit:function(len){
		var minval=this['element'].attr('min') ||Number.MIN_VALUE;
		var e9e56cd74=this['element'].attr('max') ||Number.MAX_VALUE;
		return (minval<= len && len<=e9e56cd74);

	},

	LenB : function(str){
		return str.replace(/[^\x00-\xff]/g,"**").length;
	},

	checkRepeat:function(value){
		var to = this['element'].attr('to');
		var xxx = jQuery('input[name="'+to+'"]').eq(0).val();
		if(!xxx) xxx = jQuery('#'+to).val();
		return value==xxx;
	},

	checkRange : function(value){
		value = value|0;
		var minval=this['element'].attr('min') || Number.MIN_VALUE;
		var e9e56cd74=this['element'].attr('max') || Number.MAX_VALUE;
		return (minval<=value && value<=e9e56cd74);
	},
	isminimum:function(value){
		value = Common.strlen(value);
		var minval=this['element'].attr('min') || Number.MIN_VALUE;
		return (minval<=value);
	},
	ismaximum:function(value){
		value = Common.strlen(value)|0;
		var e9e56cd74=this['element'].attr('max') || Number.MAX_VALUE;
		return (value<=e9e56cd74);
	},
	
	checkCompare : function(value){
		var compare=this['element'].attr('compare');
		
		if(isNaN(value)) return false;
		value = parseInt(value);
		return eval(value+compare);
	},

	Exec : function(value){
		var reg = this['element'].attr('regexp');
		return new RegExp(reg,"gi").test(value);
	},

	mustChecked : function(){
		var tagName=this['element'].attr('name');
		var f=this['element'].parents('form');
		var n=f.find('input[name="'+tagName+'"][checked]').length;
		var count = f.find('input[name="'+tagName+'"]').length;
		var minval=this['element'].attr('min') || 1;
		var e9e56cd74=this['element'].attr('max') || count;
		return (minval<=n && n<=e9e56cd74);
	},
	Checked : function(){
		
		return this['element'].attr("checked");
	},
	doajax : function(value) {	
		var result=false;
		var element = this['element'];
		var errindex = this['errindex'];
		var val = this['element'].val();
		var url=this['element'].attr('url');
		var type=this['element'].attr('type');
		var Charset = jQuery.browser.msie ? document.charset : document.characterSet;
		//var methodtype = (Charset.toLowerCase() == 'utf-8') ? 'post' : 'get';
		var methodtype	=	'post';
		var method=this['element'].attr('method') || methodtype;
		var name = this['element'].attr('name');
		if(url=="" || url==undefined) {
			alert('Please specify url');
      			return false ;
			}
		//if(url.indexOf('?')>-1){
	     // url = url+"&"+name+"="+val;
		//	} else {
	     // url = url+'?'+name+"="+val;
		//}
		check_data	=	name+"="+val;
		
		var e_name = element.attr('name');
		var s = $.ajax({
			type: method,
			url: url,
			data: check_data,
			dataType: "json" ,
			cache: false,
			async: false,
			success: function(data){
				//data = data.replace(/(^\s*)|(\s*$)/g, "");				
				if(data.status==1){
					 result=true;
					   return true;
					}else{
					  return false;
					}
			   }
		 });
		 return result;
		// s = s.replace(/(^\s*)|(\s*$)/g, "");
		// return s == 'success' ? true : false;
	}
};

// element 
validator.showErr=function (element, errindex){
	var pretitle=element.attr('pretitle') ||'';
	var str_errmsg=element.attr('msg') ||'unkonwn';
	var arr_errmsg = str_errmsg.split('|');
	var errmsg = arr_errmsg[errindex] ? arr_errmsg[errindex]: arr_errmsg[0];
	alerterrormsg=pretitle+errmsg;
	var msgid= jQuery('#'+element.attr('msgid'));
	var type=element.attr('type');
	(type!='checkbox' && type!='radio' && element.addClass(this['errInput']));
	
	//element.parent('*').parent('*').find('.'+this['Tip']).remove();
	
	if(msgid.length>0) {
		msgid.removeClass(this['validTip']).addClass(this['errorTip']).html(errmsg);
	} else {
		// jQuery("<span class='"+this['errorTip']+"'>&nbsp;&nbsp;&nbsp;</span>").html(errmsg).insertAfter(element);
		var e_name =this['messagebox']?this['messagebox']: element.attr('name');
		var ancestor=element.closest(this['controlancestortag']);
		if(this['hypotaxis']==4)ancestor=$('body');
		ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']).hide();
		//$('#'+e_name+'_'+validator['tipBox']+' span').hide();
		ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']+'.'+validator['errorTip']).html(errmsg);
		ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']+'.'+validator['errorTip']).show();
	}
	return false ;
}
validator.showInit=function (element){
	var e_name =this['messagebox']?this['messagebox']: element.attr('name');
	var ancestor=element.closest(this['controlancestortag']);
	if(this['hypotaxis']==4)ancestor=$('body');
	ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']).show();
	ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']+'.'+validator['errorTip']).hide();
	ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']+'.'+validator['successTip']).hide();
}
validator.showSuc=function (element, errindex){
	element.removeClass(validator.errInput);
	var e_name =this['messagebox']?this['messagebox']: element.attr('name');
	var ancestor=element.closest(this['controlancestortag']);
	if(this['hypotaxis']==4)ancestor=$('body');
	var okMsg =validator['successMsg'];
	ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']).hide();
	ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']+'.'+validator['successTip']).html(okMsg);
	ancestor.find('#'+e_name+'_'+validator['tipBox']+' '+validator['infoTags']+'.'+validator['successTip']).show();

}
validator.removeErr =  function(element){
	var e_name =this['messagebox']?this['messagebox']: element.attr('name');
	var ancestor=element.closest(this['controlancestortag']);
	if(this['hypotaxis']==4)ancestor=$('body');
	element.removeClass(this['errInput']);
	ancestor.find('#'+e_name+'_'+this['tipBox']+' span').hide();
	if(element.attr('name')=='ufaxa'||element.attr('name')=='ufaxn'){
		e_name='ufaxc';
		var ancestor=this['hypotaxis']==1?element.parent():(this['hypotaxis']==2?element.parent().parent():element.parent().parent().parent());
		ancestor.find('#'+e_name+'_'+this['tipBox']+' span').hide();
	}
}


validator.checkajax = function(element, datatype, errindex) {
	var value=jQuery.trim(element.val());
	this['element'] = element;
	this['errindex'] = errindex;
	validator.removeErr(element);
	return eval(this[datatype]);
}

validator.checkDatatype = function(element,datatype){
	
	var value=jQuery.trim(element.val());
	this['element'] = element;
	validator.removeErr(element);
	switch(datatype){
		case "idCard" :
		case "date" :
		case "repeat" :
		case "range" :
		case "compare" :
		case "custom" :
		case "group" :
		case "limit" :
		case "limitB" :
		case "safeString" :
		case "filter" :
		case "minimum" :
		case "ajax" :
		case "dateaftertoday" :
		case "maximum" :
		case "ischecked" :
		case "change" :
		case "select" :
		case "selecthasoption" :
		case "verifypass" :
		case "boxrequire" :
		//alert(this[datatype]+" "+eval(this[datatype]));
		return eval(this[datatype]);
		break;

		default:
			return this[datatype].test(value);
			break;
		}
}

validator.check=function(obj){
	var datatype = obj.attr('datatype');
	var value = jQuery.trim(obj.val());
	
	//if(typeof(datatype) == "undefined") return true;

	if(obj.attr('require')!="true" && value=="") {validator.showInit(obj); return true;}
	var datatypes = datatype.split('|');
	var isValid = true;
	jQuery.each(datatypes,function(index,type){
		//alert('qq'+type);
		if(typeof(validator[type]) == "undefined") {
			isValid = false;alert('没有此种验证类型：'+type);
			return  false;
		}
				
		//ajax validate 
		//if(type=='ajax') return isValid = validator.checkajax(obj, type, index);
		
		if(type== "notest"||validator.checkDatatype(obj,type)!=false){  //the form element validate failed
			//alert('aaa');
			validator.showSuc(obj, index);
			isValid = true;
		} else { // validate success
			//alert('bbb');
			obj.addClass(validator.errInput);
			validator.showErr(obj, index);
			return isValid=false;
		}
	});
	return isValid;
}
alerterrormsg="数据输入有误，请再检查下";
validator.init=function(form){
	htmlform=form;
	if(validator['outertag']){
		this.elements = form.find('tr').not(this.outertag).find(':input[require]');
	
	}else this.elements = form.find(':input[require]');

	if(this.blurcheck==1){
		this.elements.blur(function(index){
			jQuery(this).attr('init',1);
			return validator.check(jQuery(this));
		});
	}
};

validator.lastcheck=function(){
	var isValid = true;
	var errIndex= new Array();
	var n=0;
	if(validator['outertag']){
		this.elements = htmlform.find('tr').not(this.outertag).find(':input[require]');
	
	}else this.elements = htmlform.find(':input[require]');
	
	if(this.lastcheck==0)return true;
	this.elements.each(function(i){
		if(validator.check(jQuery(this))==false){
			isValid  = false;
			errIndex[n++]=i;
			return false;
		};	
	});
	if(isValid==false){
		if(this.lastcheckalert==1){alert(alerterrormsg);}  
		this.elements.eq(errIndex[0]).focus().select();
		return false;
	}
	return true;
}
validator.yanzheng=function (){
	var form=jQuery("form#"+this.formid);
	var elements = form.find(':input[require]:visible');
	
		var isValid = true;
		var errIndex= new Array();
		var n=0;
		if(validator['lastcheck']==0)return true;
		
		validator['lastchecktime']=1;
		if(validator['lastcheckmode']==0){
		elements.each(function(i){
			var ancestor=element.closest(this['controlancestortag']);
			if(($(this).attr('init')==0&&$(this).attr('require'))||($(this).attr('init')!=0 && ancestor.find('.'+validator['errorTip']+':visible').length>0)){
				isValid  = false;
				errIndex[n++]=i;
				$(this).attr('init',0);
				//validator.showInit($(this));
			};
		});
		}else{
		elements.each(function(i){
			if(validator.check(jQuery(this))==false){
				isValid  = false;
				errIndex[n++]=i;
				return false;
			};	
		});

		}

		if(isValid==false){
			if(validator['lastcheckalert']==1){alert(alerterrormsg);}  
			elements.eq(errIndex[0]).focus().select();
			return false;
		}
		return isValid;
	}
jQuery.fn.checkForm = function(){
	var form=jQuery(this);
	var elements = form.find(':input[require]');
	
	//for(var i=0;i<9;i++){alert(elements[i].tagName);}
	if(validator['blurcheck']==1){
	elements.blur(function(index){
		jQuery(this).attr('init',1);
		return validator.check(jQuery(this));
	});
	elements.click(function(){
		validator.showInit(jQuery(this));
	});
	}
	/*
	if(validator['clickconfirm']==1){
		$('input[name="Submit"]',form).click(yanzheng);
	}  
	else{
		form.submit(yanzheng);
	}
	*/
};