/**
 * @author kenny
 * form输入字符验证
 */
(function($){
   
   /** 是否是域名 */
   function isDomain(dm){
      	dm = (dm || "").replace(/(^\s*)|(\s*$)/g,"");
      	if("localhost" == dm){
      		return true;
      	}
      	//var re = /^([\w-]+\.)+((com)|(net)|(org)|(gov\.cn)|(info)|(cc)|(com\.cn)|(net\.cn)|(org\.cn)|(name)|(biz)|(tv)|(cn)|(mobi)|(name)|(sh)|(ac)|(io)|(tw)|(com\.tw)|(hk)|(com\.hk)|(ws)|(travel)|(us)|(tm)|(la)|(me\.uk)|(org\.uk)|(ltd\.uk)|(plc\.uk)|(in)|(eu)|(it)|(jp)|(co)|(me)|(mx)|(ca)|(ag)|(com\.co)|(net\.co)|(nom\.co)|(com\.ag)|(net\.ag)|(fr)|(org\.ag)|(am)|(asia)|(at)|(be)|(bz)|(com\.bz)|(net\.bz)|(net\.br)|(com\.br)|(de)|(es)|(com\.es)|(nom\.es)|(org\.es)|(fm)|(gs)|(co\.in)|(firm\.in)|(gen\.in)|(ind\.in)|(net\.in)|(org\.in)|(jobs)|(ms)|(com\.mx)|(nl)|(nu)|(co\.nz)|(net\.nz)|(org\.nz)|(tc)|(tk)|(org\.tw)|(idv\.tw)|(co\.uk)|(vg)|(ad)|(ae)|(af)|(ai)|(al)|(an)|(ao)|(aq)|(ar)|(as)|(au)|(aw)|(az)|(ba)|(bb)|(bd)|(bf)|(bg)|(bh)|(bi)|(bj)|(bm)|(bn)|(bo)|(br)|(bs)|(bt)|(bv)|(bw)|(by)|(cd)|(cf)|(cg)|(ch)|(ci)|(ck)|(cl)|(cm)|(cr)|(cu)|(cv)|(cx)|(cy)|(cz)|(dj)|(dk)|(dm)|(do)|(dz)|(ec)|(ee)|(eg)|(er)|(et)|(fi)|(fj)|(fk)|(fo)|(ga)|(gd)|(ge)|(gf)|(gg)|(gh)|(gi)|(gl)|(gm)|(gn)|(gp)|(gq)|(gr)|(gt)|(gu)|(gw)|(gy)|(hm)|(hn)|(hr)|(ht)|(hu)|(id)|(ie)|(il)|(im)|(iq)|(ir)|(is)|(je)|(jm)|(jo)|(ke)|(kg)|(kh)|(ki)|(km)|(kn)|(kr)|(kw)|(ky)|(kz)|(lb)|(lc)|(li)|(lk)|(lr)|(ls)|(lt)|(lu)|(lv)|(ly)|(ma)|(mc)|(md)|(mg)|(mh)|(mk)|(ml)|(mm)|(mn)|(mo)|(mp)|(mq)|(mr)|(mt)|(mu)|(mv)|(mw)|(my)|(mz)|(na)|(nc)|(ne)|(nf)|(ng)|(ni)|(no)|(np)|(nr)|(nz)|(om)|(ooo)|(pa)|(pe)|(pf)|(pg)|(ph)|(pk)|(pl)|(pm)|(pn)|(pr)|(ps)|(pt)|(pw)|(py)|(qa)|(re)|(ro)|(ru)|(rw)|(sa)|(sb)|(sc)|(sd)|(se)|(sg)|(si)|(sk)|(sl)|(sm)|(sn)|(sr)|(st)|(sv)|(sy)|(sz)|(td)|(tf)|(tg)|(th)|(tj)|(tl)|(tn)|(to)|(tr)|(tt)|(tz)|(ua)|(ug)|(uk)|(uy)|(uz)|(va)|(vc)|(ve)|(vi)|(vn)|(vu)|(wang)|(wf)|(xyz)|(ye)|(yt)|(yu)|(za)|(zm)|(zw))$/;
      	//return re.test(dm);
      	return /^([\w-]+\.)+([\w]+)$/.test(dm);
   }
   /* 是否是域名 */
   function isIp(ip){
      	var re = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/;
      	return re.test(ip);
   }
   
   function Form($form){
	  var me = this;	  
	  me.$form = $($form);
	  me.error = {};
	  $("input", $form).each(function(i, ele){
		 var $ele = $(ele);
		 if($ele.attr("required")){
			me.error[$ele.attr("name")] = {
				ele: $ele,
				check: false
			};
		 }
	  });
	  function eHandle(e){
		 handle($(e.target || e.srcElement));
	  }
	  var isHandle = false;
	  function handle($ele){
	  	 if(!$.contains(me.$form[0], $ele[0])) return true;
		 if($ele[0].tagName != "INPUT") return true;
		 if(isHandle)return;
		 isHandle=true
		 var bool = false;
		 try{
			//值必填
      		 if ($ele.attr("required") !=  null) {
      			bool = me._required($ele);
      		 }else{
      			delete me.error[$ele.attr("name")];
      		 }
      		 var val = $.trim($ele.val());
      		 if(val != ""){//
      			if ($ele.attr("check-domain")!=null) {
         			bool = me._checkDomain($ele);
         		}
         		if ($ele.attr("check-number")!=null) {
         			bool = me._checkNumber($ele);
         		}
         		if ($ele.attr("check-email")!=null) {
         			bool = me._checkEmail($ele);
         		} 
      		 }		     		 
		 }catch(e){
			console.log(e.stack, e);
		 }
		 isHandle = false;
		 return bool;
	  }
	  me._handle = handle;
	  function _submit(e){//表单提交时,触发的事件
		 var valid = me.valid();
		 me.$form.attr("valid", valid);
		 if( !valid ){			
			var $first;
			$.each(me.error, function(i, res){
			   var $ele = $(res.ele);
			   if(!$first) $first = $ele;
			   handle($ele);
			});
			$first.focus();
			e.stopPropagation();
			e.preventDefault();
		 }else{
		 	var btn = $(e.target||e.srcElement)[0];
		 	btn.disabled = true;
		 	setTimeout(function(){
		 		btn.disabled = false;
		 	}, 3000)
		 }
		 return valid;
	  }
	  me.$form.on({
		 //input: eHandle,
		 //change: eHandle,
		 submit: _submit
	  });
	  $("input", me.$form).live({
		 focus: function(e){
			$.trim($(this).val())!="" && eHandle(e);
		 },
		 blur: function(e){
		 	eHandle(e);
		 }
	  });
	  $("[type=submit]", me.$form).on({
		 click: _submit
	  })
   }
   $.extend(Form.prototype, {
	  valid: function(){//验证form表单
		 var me = this;
		 for(var name in me.error){
			var res = me.error[name];
			if(res){
			   var bool = me._handle(res.ele);
			   if(bool!=true){
				  return bool;
			   }
			}
		 }
		 return true;
	  },
	  // 必填
	  _required : function($ele) {
		 var me = this,
		 	val = $.trim($ele.val());
		 var res = !/^\s*$/g.test(val), name = $ele.attr("name");
		 var $tip = $("[show='"+name+".check"+"']", me.$form);
		 res ? $tip.hide() : $tip.show();
		 if(!res){
			me.error[name] = {
				  ele: $ele,
				  check: false
			};
		 }else{
			delete me.error[name];
		 }
		 return res;
	  },
	  _checkDomain : function($ele) {
		 var me = this,
		 	val = $.trim($ele.val());
		 var res = isDomain(val) || isIp(val);
		 var $tip = $("[show='"+$ele.attr("name")+".check"+"']", me.$form);
		 res ? $tip.hide() : $tip.show();
		 if(!res){
			me.error[name] = {
				  ele: $ele,
				  check: false
			};
		 }else{
			delete me.error[name];
		 }
		 return res;
	  },
	  _checkNumber : function($ele) {
		 var me = this,
		 	val = $.trim($ele.val());
		 var res = /^\d*$/.test(val), name=$ele.attr("name");
		 var $tip = $("[show='"+name+".check"+"']", me.$form);
		 res ? $tip.hide() : $tip.show();
		 if(!res){
			me.error[name] = {
				  ele: $ele,
				  check: false
			};
		 }else{
			delete me.error[name];
		 }
		 return res;
	  },
	  _checkEmail : function($ele) {
		 var me = this,
		 	val = $.trim($ele.val());
		 var res = /^[\.0-9a-zA-Z_-]+@[0-9a-zA-Z_-]+(\.[0-9a-zA-Z_-]+)+$/.test(val), name=$ele.attr("name");
		 var $tip = $("[show='"+name+".check"+"']", me.$form);
		 res ? $tip.hide() : $tip.show();
		 if(!res){
			me.error[name] = {
				  ele: $ele,
				  check: false
			};
		 }else{
			delete me.error[name];
		 }
		 return res;
	  }
   });
   $.fn.form = function(){
	  return new Form(this);
   };
   define("lib/jquery/form", function(require, exports, module){
	  module.exports = $ ;
   });
})(jQuery);