base.js 32 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
/*!
* base.js
*/
//定义JS命名空间、防止JS签名重复
var Namespace = Namespace || new Object();
Namespace.register = function(path){var arr = path.split("."),ns = "";;for(var i=0;i<arr.length;i++){if(i>0){ns += ".";}ns += arr[i];eval("if(typeof(" + ns + ")=='undefined'){" + ns + " = new Object();}");}};
var globalValidator=null;
// $(document).ready(function() {
	// //使所有在页面定义的dialog可以拖动,不包括动态生成的dialog,动态生成的dialog在调用之后增加如下语句
	// //只有拖动对话框的头部才能拖动,其他部位不能拖动,便于右键可以选择对话框中的文本进行选择
	// $("div[class='modal-dialog']").draggable({  
	    // handle: ".modal-header"
	// });
// });
//基础框架
Namespace.register("XUI");
(function(){
	String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, "");};
	String.prototype.ltrim=function(){return this.replace(/^\s+/g, "");};
	String.prototype.rtrim=function(){return this.replace(/\s+$/g, "");};
	String.prototype.firstIndexOf=function(prefix){var index=-1,temp = -1,str = this;while((temp = str.lastIndexOf(prefix))>=0){str = str.substring(0,temp);index = temp;}return index;};
	String.prototype.endsWith=function(suffix){var C=this.length;var D=suffix.length;if(D>C)return false;return (D==0 || this.substr(C-D,D)==suffix);};
	String.prototype.replaceAll=function(regex,replacement) {var raRegExp = new RegExp(regex,"g");return this.replace(raRegExp,replacement);};
	String.prototype.chineseLength=function(){ return this.replace(/[^\x00-\xff]/g,"**").length;};
	String.prototype.remove=function(startIndex,removeLength) {var s='';if(startIndex>0)s=this.substring(0,startIndex);if(startIndex+removeLength<this.length)s+=this.substring(startIndex+removeLength,this.length);return s;};
	Date.prototype.format=function(mask){var d = this;var zeroize = function (value, length) {if (!length) length = 2;value = String(value);for (var i = 0, zeros = ''; i < (length - value.length); i++) {zeros += '0';}return zeros + value;};return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function($0) {switch($0) {case 'd':return d.getDate();  case 'dd':return zeroize(d.getDate());case 'ddd':return ['Sun','Mon','Tue','Wed','Thr','Fri','Sat'][d.getDay()];case 'dddd':return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][d.getDay()];case 'M':return d.getMonth() + 1;case 'MM':return zeroize(d.getMonth() + 1);case 'MMM':return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];  case 'MMMM':return ['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];case 'yy':return String(d.getFullYear()).substr(2);case 'yyyy':return d.getFullYear();case 'h':return d.getHours() % 12 || 12;  case 'hh':return zeroize(d.getHours() % 12 || 12);  case 'H':return d.getHours();case 'HH':return zeroize(d.getHours());case 'm':return d.getMinutes();case 'mm':return zeroize(d.getMinutes());case 's':return d.getSeconds();case 'ss':return zeroize(d.getSeconds());case 'l':return zeroize(d.getMilliseconds(), 3);case 'L':var m = d.getMilliseconds();if (m > 99) m = Math.round(m / 10);return zeroize(m);case 'tt':return d.getHours() < 12 ? 'am' : 'pm';case 'TT':return d.getHours() < 12 ? 'AM' : 'PM';case 'Z':return d.toUTCString().match(/[A-Z]+$/);default:return $0.substr(1, $0.length - 2);}});};
	XUI.isne = function(str){return str==null||str=="undefined"||str.trim()=="";};
	XUI.vmContainer = function(){return $("#vmContainer");};
	
	XUI.constructor = new Array();//构造方法列表
	XUI.addConstructor = function(func){XUI.constructor.push(func);};//新增构造方法
	XUI.init = function(panel){//初始化执行所有构造方法
		var execute = function(func){try{eval("func();");}catch(e){console.log(e);}};
		for(var func in XUI.constructor){execute(function(){XUI.constructor[func](panel);});}
		$("SPAN.pageLoad").each(function(i,o){execute(function(){eval($(o).remove().attr("data-pageLoad"));});});
	};
})();


Namespace.register("XUI.tip");
(function(){
	XUI.tip.init = function(panel) {//鼠标提示
		var content = "BODY";
		if(panel != null) {content = panel;}
		$(content).find("*[rel=popover]").each(function(i,o){var contentEl = $(o).attr("data-content"),contentFunc=null;if(!XUI.isne(contentEl) && contentEl.indexOf("javascript:")==0){$(o).removeAttr("data-content");contentFunc = function(){var text = eval(contentEl.substr(11));$(o).attr("data-content",text);return text;};}$(o).removeAttr("rel").popover({content:contentFunc});});
		$(content).find("*[rel=tooltip]").each(function(i,o){$(o).removeAttr("rel").tooltip();});
		$(content).find("*.tip").each(function(i,o){$(o).removeClass("tip").attr("title",$(o).text().trim());});
	};
	XUI.addConstructor(XUI.tip.init);
})();


Namespace.register("XUI.table");
(function(){
	XUI.table.resizable = function(panel){
		var table = "TABLE.table thead th,TABLE.table thead td";
		if(panel != null) {tbale = $(panel).find(table);}
		var oldCursor = $(table).attr("title","点击排序").css('cursor');
		var resizeWidth = 2;//拖动偏离像素
		//表格拖动
		$(table).unbind("mousemove").bind("mousemove",function(ev){
			var th = $(this);
			if (th.prevAll().length < 1 || th.nextAll().length < 1) {return;}//不给第一列和最后一列添加效果
			//距离表头边框线左右4像素才触发效果
			var left = th.offset().left;
			var effect = (ev.clientX - left) < resizeWidth || (th.outerWidth() - (ev.clientX - left)) < resizeWidth;
			if (effect) {th.css('cursor','col-resize');} else{th.css('cursor',oldCursor);}
		}).unbind("mousedown").bind("mousedown", function(ev) {
			var dd = new Object();
			dd.obj = $(this);//TH对象
			var pos = dd.obj.offset();
			dd.table = dd.obj.parent().parent().parent();//Table对象
			var effect = (ev.clientX - pos.left) < resizeWidth || (dd.obj.outerWidth() - (ev.clientX - pos.left)) < resizeWidth;
			if (!effect || dd.obj.prevAll().length < 1 || dd.obj.nextAll().length < 1) {return;}//跳过第一列和最后一列
			dd.line = $("<div class='dragLine'></div>");//竖线
			dd.line.css({ "height": dd.table.height(), "top": dd.table.offset().top,"left":ev .clientX,"display":"block" });//显示调整线
			if (ev.clientX - pos.left < dd.obj.width() / 2){dd.obj = dd.obj.prev();}//记录当前TH
			var x = ev.clientX;dd.rangeStart = dd.table.offset().left;dd.rangeEnd = dd.rangeStart + dd.table.width();
			$("body").append(dd.line).bind("selectstart",function(){
				return false;
			}).bind("mousemove",function(event){
				if(dd.rangeStart < event.clientX && dd.rangeEnd > event.clientX){dd.line.css({"left":event.clientX});dd.deltaX = event.clientX - x;}
			}).bind("mouseup",function(event){
				dd.line.remove();dd.obj.width(Math.max(40, dd.obj.width() + dd.deltaX));
				var defaultWidth = parseInt(dd.table.attr("defaultWidth"));
				dd.table.width(Math.max(defaultWidth, dd.table.width() + dd.deltaX));
				$("body").unbind("mousemove").unbind("mouseup").unbind("selectstart").css('cursor','default').attr("unselectable","off").css("MozUserSelect","");
			}).css('cursor','col-resize').attr("unselectable","on").css("MozUserSelect","none");
		});
	};
	XUI.addConstructor(XUI.table.resizable);
	
	//表格排序
	XUI.table.sorting = function(panel){
		var sorting = "TABLE.table .sorting,TABLE.table .sorting_ASC,TABLE.table .sorting_DESC";
		if(panel != null) {sorting = $(panel).find(sorting);}
		$(sorting).unbind("click").bind("click",function(){
			var field = $(this).attr("data-orderField"),type = $(this).attr("data-orderFieldType");
			var form = XUI.vmContainer().find("FORM")[0];
			if(form["orderField"]==null){$(form).append("<input type='hidden' name='orderField'/>");}
			if(form["orderFieldType"]==null){$(form).append("<input type='hidden' name='orderFieldType'/>");}
			form["orderField"].value = field;
			form["orderFieldType"].value = type;
			$(form).submit();
		});
	};
	XUI.addConstructor(XUI.table.sorting);
})();


Namespace.register("XUI.window");
(function(){
	//打开窗口
	XUI.window.open = function(url,params,method,conf){
		var open = function(data) {
			
			//JSON数据或者页面数据
			try{if(data != null && !XUI.isne(data.result)){alert(data.result);return;}}catch(e){}
			var modal = XUI.window.openDialog(data,conf);
			
		};
		
		XUI.ajax.send(url,params,method,null,{callback:open});
	};
	
	XUI.window.queue = new Array();//当前已经打开的窗口
	//打开动态对话框窗口,窗口的宽度在base.css中进行了重新设置
	XUI.window.openDialog = function(content,conf){
		var temp = bootbox.dialog({
			message : content,
			title :conf.title,
			buttons:conf.buttons
		});
		//使动态dialog可以拖动
		//只有拖动对话框的头部才能拖动,其他部位不能拖动,便于右键可以选择对话框中的文本进行选择
		try{
			$("div[class='modal-dialog']").draggable({
				handle: ".modal-header"
			}); 						
		}catch(e){
			//ingore
		}
	};
	//关闭顶层窗口
	XUI.window.close = function(){
		var length = XUI.window.queue.length;
		if(length>0){XUI.window.queue[length-1].find('DIV.modal-header>A.close').click();}
	};
	//关闭所有窗口
	XUI.window.closeAll = function(){
		$("DIV.modal-backdrop,DIV.modal").remove();
		XUI.window.queue = new Array();
	};
	XUI.window.refresh = function(){//刷新顶层窗口
		if(XUI.window.queue.length <= 0) {return false;}
		var modal = XUI.window.queue[XUI.window.queue.length-1];
		var opts = {"url": modal.attr("data-url"),"params": modal.attr("data-params"),"method": modal.attr("data-method")};
		if(opts.url == null){return false;}
		var refresh = function(data) {
			try{if(data != null && !XUI.isne(data.result)){alert(data.result);return false;}}catch(e){}
			var content = modal.find("DIV.modal-body");
			XUI.init(content.html(data));
		};
		XUI.ajax.send(opts.url,opts.params,opts.method,null,{callback:refresh});
		return true;
	};
	
	XUI.window.confirm=function(operation){
		bootbox.dialog({
			message: "你确认要执行此项操作吗?",
			title:'确认',
			draggable:true,
			closeable:true,
			buttons: {
				success: {
					label: "是",
					className: "btn-success",
					callback: operation
			    },
			    danger: {
					label: "否",
					className: "btn-danger"
			    }
			}
			});
	};
})();

Namespace.register("XUI.ajax");
(function(){
	//内部私有方法
	var successMethod = function(data,dataType){//请求成功
		try{if(data != null && !XUI.isne(data.result)) {alert(data.result);return;}} catch (e) {}
		XUI.init(XUI.vmContainer().html(data));
	},errorMethod = function(xhr,url,requestType){//请求错误
		var message = {"code":"failure","result":"请求URL["+url+"],发生"+xhr["statusText"]+"错误."};
		var dataType = XUI.isne(requestType) ? "" : requestType.toUpperCase();
		switch (xhr["status"]) {
			case 403: message["result"]="您无权访问本页面.";break;
			case 404: message["result"]="不存在的URL["+url+"]";break;
			case 500: message["result"]="服务器内部错误."+xhr["statusText"];break;
		}
		if(dataType == "JSON" || (!XUI.isne(url) && url.toUpperCase().endsWith(".JSON"))) {successMethod(message,dataType);}
		else{successMethod("<div class='alert'>"+message["result"]+"</div>",dataType);}
	},vmData = new Object();
	
	
	//页面跳转
	XUI.gotoPage = function(url,params,method){
		vmData = {"url":url,"params":params,"method":method};
		XUI.refreshVM();
	};
	//刷新当前VM
	XUI.refreshVM = function(){
		XUI.ajax.send(vmData.url,vmData.params,vmData.method);return true;
	};
	
	//Ajax请求
	XUI.ajax.send = function(url,params,method,type,config){
		var cfg = $.extend(true, {}, {"closeWindow":false,"refresh":false,"callback":null}, config || {});
		var ajaxOptions = {
			url:domain + url,data:params,
			success:function(data){
				var type = XUI.isne(this.dataType) ? "" : this.dataType.toUpperCase();
				if(cfg.callback != null) {
					cfg.callback(data);
				} else {
					successMethod(data,type);
				}
				if(type=="JSON" && data.code == "failure") {return;}
				if(cfg.closeWindow == true) {
					XUI.window.close();
				}
				if(cfg.refresh == true && XUI.window.refresh()==false) {
					XUI.refreshVM();
				}
			},
			error : function(error) {
				alert(error);
            }
		};
		if(!XUI.isne(method)) {ajaxOptions["type"] = method;}
		if(!XUI.isne(type)) {ajaxOptions["dataType"] = type;}
		jQuery.ajax(ajaxOptions);
	};
	
	//以JSON的方式执行DELETE方法
	XUI.ajax["delete"] = function(url,params,config) {
		var cfg = $.extend(true, {}, {"confirm":"您确定要删除吗?"}, config || {});
		if(window.confirm(cfg.confirm)) {
			XUI.ajax.send(url,params,"DELETE","",config);
		}
	};
	
	//请求时界面遮罩
	XUI.ajax.mask = function(msg){var info = msg;if($("#winModal,#loadInfo").length == 0) {var msg = (!XUI.isne(info)) ? info:"正在努力为您获取数据,请稍候...";$("body").append("<div id='winModal' class='modal-backdrop fade in' style='z-index:9999'></div><div id='loadInfo' class='infobox infobox-grey infobox-dark'><i class='icon-coffee bigger-110'></i>"+msg+"</div>");}};
	XUI.ajax.unmask = function(){$("#winModal,#loadInfo").remove();};
	
	//Ajax全局设置
	jQuery.ajaxSetup({
		type:"POST",cache:false,
		beforeSend :function(xhr){XUI.ajax.mask();},
		error :function(xhr, ts,et){errorMethod(xhr, this.url,this.dataType);this.complete(xhr, ts);},
		complete :function(xhr, ts){XUI.ajax.unmask();}
	});
})();
Namespace.register("XUI.check");
(function(){
	XUI.check.isRequestExecutedSuccess=function(responseMsg){
		if(responseMsg != null && !XUI.isne(responseMsg.result) && responseMsg.code == "200"){
    		return true;
    	}
    	return false;
	};
})();

Namespace.register("XUI.nonAjax");
(function(){
	
	XUI.nonAjax.getGo=function(url, params) {
		 if(null==params){
			 document.location = domain+url;
			 return;
		 }
		 document.location = domain+url + '?' + $.param(params);
    };
	
	XUI.nonAjax.postGo=function(url, params) {
		var formId=$("#queryservice");
		if(formId!=undefined)
		{
			formId.remove();
		}
        var form= $('<form></form>');  
        form .attr("method", "post");
        form .attr("id", "queryservice");
		form.attr("action", domain+url);
         if(null!=params){
        	 $.each(params, function(name, value) {
        		 $("<input type='hidden'>")
        		 .attr("name", name)
        		 .attr("value", value)
        		 .appendTo(form);
        	 });
         }
         form.appendTo(document.body).submit();
    };
})();

Namespace.register("XUI.form");
(function(){
	
	populateFormActionUrl=function(form,currentPage,pageSize){
		var url="?";
		var encodeValue;
		//form参数编码设置
		for(var i = 0 , j = form.length;i <j;++i){
			
			if($.trim(form[i].name)!="" && $.trim(form[i].value)!="")
			{
				encodeValue=encodeURI(form[i].value);
				if(url.indexOf("&")!=-1)
				{
					url+="&"+form[i].name+"="+encodeValue;
				}
				else if(url.indexOf("=")!=-1)
				{
					url+="&"+form[i].name+"="+encodeValue;
				}else{
					url+=""+form[i].name+"="+encodeValue;
				}
			}
		}

		if(url.indexOf("pageSize")==-1 && url.indexOf("currentPage")==-1){
			if(url.indexOf("&")!=-1 || url.indexOf("=")!=-1)
			{
				url+="&pageSize="+pageSize;
				url+="&currentPage="+currentPage;
			}else{
				url+="pageSize="+pageSize;
				url+="&currentPage="+currentPage;
			}
			url+="&backUrl="+base64encode(utf16to8(window.location));
		}
		return form.action+url;
	};
	
	//validator为jquery validator对象,用于表单验证
	XUI.form.page=function(num,globalValidator)
	{
		if(null==globalValidator || typeof globalValidator === 'undefined'){
			$('#currentPage').val(num);
			var form=$('form')[0];
			var currentPage=num;
			var pageSize=$("#pageSize option:selected").val();
			var actionUrl=populateFormActionUrl(form,currentPage,pageSize);
			window.location.href=actionUrl;
			return actionUrl;		
		}
		if(globalValidator.valid()){
			$('#currentPage').val(num);
			var form=$('form')[0];
			var currentPage=num;
			var pageSize=$("#pageSize option:selected").val();
			var actionUrl=populateFormActionUrl(form,currentPage,pageSize);
			window.location.href=actionUrl;
			return actionUrl;			
		}
	};
	
	/**不指定表名*/
	XUI.form.submit=function()
	{
		var form=$('form')[0];
		var currentPage=1; //表单每次查询从第一页开始显示
		var pageSize=$("#pageSize option:selected").val();
		var actionUrl=populateFormActionUrl(form,currentPage,pageSize);
		window.location.href=actionUrl;
		return actionUrl;
	};
	
	XUI.form.backUrl=function()
	{
		var form=$('form')[0];
		var currentPage=$('#currentPage').val();
		var pageSize=$("#pageSize option:selected").val();
		var actionUrl=populateFormActionUrl(form,currentPage,pageSize);
		return actionUrl;
	};
	
	XUI.form.reset=function()
	{
		var form=$('form')[0];
		for(var i = 0 , j = form.length;i <j;++i){
			form[i].value="";
			}
	};
})();

Namespace.register("XUI.history");
(function(){
	XUI.history.goBack=function(backUrl)
	{
		if(backUrl=="")
		{
			history.back();
		}
		else{
			window.location=utf8to16(base64decode(backUrl)); 
		}	
	};
})();

Namespace.register("XUI.validator");
(function(){
	XUI.validator.isContainSpecialStr=function(str)
	{
		var regExp = new RegExp("[`~!@%#$^&*()=|{}':;',\\[\\]<>/?/\]\\.;:%……+ ¥()【】‘”“'.。,、?1234567890-=_+~?!@#$%^&*)]"); 
		return regExp.test(str);
	};
})();
Namespace.register("XUI.message");
(function(){
	XUI.message.errordivrelocation=function(errorDivId)
	{
		var errorDiv=$("#"+errorDivId);
    	if(errorDiv!=null){
    		$("i").css("position","relative");
    		$("i").css("display","");
    		$("i").css("font-style","normal");
    		errorDiv.css("top","0");
    	}
	};
})();
/**重写浏览器 alert 方法 
window.alert = function(msg,okCallback) {
        bootbox.alert({
            buttons : {
                ok : {
                    label : '确定',
                    className : 'btn-success'
                }
            },
            message : msg,
            callback : function() {
                if ( typeof (okCallback) == 'function') {
                    okCallback();
                }
            },
            title : "提示信息",
        });
    };
*/
//回车查询
$(function(){
	$("#queryForm input").keypress(function(event){
		if(event.keyCode == "13")    
		{
			$("#queryBtn").click();
		}	
	});
});

/**
 *  主要用于页面表单有效性验证。
 */
var PatternsDict = new Object();
/*
 * 正则表达式检测
 */
/*
 * 1、电话号码的验证
 * 
 * 要求: (1)电话号码由数字、"("、")"和"-"构成 (2)电话号码为3到8位 (3)如果电话号码中包含有区号,那么区号为三位或四位
 * (4)区号用"("、")"或"-"和其他部分隔开 (5)移动电话号码为11或12位,如果为12位,那么第一位为0
 * (6)11位移动电话号码的第一位和第二位为"13" (7)12位移动电话号码的第二位和第三位为"13" 根据这几条规则,可以写出以下正则表达式:
 * (^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)
 * 2、Integer数据类型验证:正负Integer数据类型,0 3、EMail验证 4、Select下拉框选择验证 5、全中文输入验证 6、全英文输入验证
 * 7、Double数据类型验证:正负Double数据类型,0 8、邮政编码验证:610041 9、Url输入验证:http://www.163.com
 * 10、全数字验证  11.传真
 */
PatternsDict.PhonePat = /(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}1[3-9][0-9]{9}$)/;
PatternsDict.IntegerPat = /^\-*\d+$/;
PatternsDict.EmailPat = /^\w+([-+.]\w+)*@\w+([-.]\\w+)*\.\w+([-.]\w+)*$/;
PatternsDict.SelectPat = /.+/;
PatternsDict.ChinesePat = /^[\u0391-\uFFE5]+$/;
PatternsDict.EnglishPat = /^[A-Za-z]+$/;
PatternsDict.DoublePat = /^(\+)?\d+(\.\d+)?$/;
//精确到小数点两位
PatternsDict.DoublePatjq = /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/;
PatternsDict.ZipPat = /^[1-9]\d{5}$/;
PatternsDict.UrlPat = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
PatternsDict.NumberPat = /^\d+$/;
PatternsDict.Fax = /^(\d{3,4}-)?\d{7,8}$/;
// 整数12位正则式
PatternsDict.IntNumberPat = /^[1-9]\d{1,12}?|(0)$/;
// 大于0小于100的正则表达式
PatternsDict.IntDoublePat = /^(([1-9]\d?)|(100)|(0))$|^(([1-9]\d?)|(100)|(0))\.\d{1,6}$/;
PatternsDict.MyDoublePat = /^([1-9]\d{0,10}|[0])(\.\d{1,6})?$/;
PatternsDict.MyDoublePat1 = /^([0-9]\d{0,7})(\.\d{0,4})$/;//最多7位整数,最多4位小数的浮点数
/*
 * 函数检测 1、radio或checkbox选中验证 2、身份证验证 3、Textarea文字长度检测 4、Textarea文字字节长度检测
 * 5、判断日期的表达式,2005-7-20 6、判断时间的表达式,13:04:06 7、判断日期时间的表达式,2003-12-05 13:04:06
 */
PatternsDict.GroupPat = "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))";
PatternsDict.IdCardPat = "this.isIdCardNo(value)";
PatternsDict.TextareaPat = "this.TextareaLen(value.length,getAttribute('min'),getAttribute('max'))";
PatternsDict.TextareaBPat = "this.TextareaLen(this.ByteLen(value),getAttribute('min'),getAttribute('max'))";
PatternsDict.DatePat = "this.isDate(value)";
PatternsDict.TimePat = "this.isTime(value)";
PatternsDict.DateTimePat = "this.isDateTime(value)";
//手机号码长度为11位数字(0-9);第1位必须是1;第2位必须是3 4 5 7 8 9几个数字,后期可能会扩展;第3-11位为数字即可;
PatternsDict.mobile=/^1[345789][0-9]{9}$/;

//得到字符串字节长度
function ByteLen(str) {
	return str.replace(/[^\x00-\xff]/g, "**").length;
}

//检查单选按钮或者复选框是否有选中
function MustChecked(name, min, max) {
	var groups = document.getElementsByName(name);
	var hasChecked = 0;
	min = min || 1;
	max = max || groups.length;
	for ( var i = groups.length - 1; i >= 0; i--)
		if (groups[i].checked)
			hasChecked++;
	return min <= hasChecked && hasChecked <= max;
}

//检查Textarea中文字长度 
function TextareaLen(len, min, max) {
	min = min || 0;
	max = max || Number.MAX_VALUE;
	return min <= len && len <= max;
}

//错误条目和错误提示信息
ErrorItem = [ document.forms[0]];
ErrorMessage = [ "以下原因导致出错:\t\t\n" ];

function AddError(index, str) {
	this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
	this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length
			+ "、" + str;
}

function validateForm(theForm){
//var payWay=$("input[name='payWay']:checked").val();
//var payNo=$("#payNo").val();
//var payMoeny = $("#payMoeny").val();
	var elArr = theForm.elements;
	var obj = theForm || event.srcElement;
	this.ErrorMessage.length = 1;
	this.ErrorItem.length = 1;
	this.ErrorItem[0] = obj;
	for ( var i = 0; i < elArr.length; i++)
		with (elArr[i]) {
		// 获取其require属性,必填项,判断是否为空
		var _require = getAttribute("require");
		if (_require == "false" && value == "") {
			// 添加错误提示信息
			this.AddError(i, getAttribute("msg"));
		}
		// 不是必填项的,没有值时忽略
		if (value == ""){
			continue;
		}
		// 获取其dataType属性
		var _dataType = getAttribute("dataType");
		// 如果有dataType,就验证
		if (_dataType) {
			// 选择验证用的正则表达式
			var thePat = PatternsDict[_dataType];
			// 根据数据类型不同,选择不同操作
			switch (_dataType) {
				case "IdCardPat":
					// 身份证号码的验证
					var str = eval(thePat);
					if (str != "") {
						this.AddError(i, str);
					}
					gotIt = "true";
					break;
				case "GroupPat":
					// 是否必须选择
					if (!_require){
						var gotIt = eval(thePat);
					}
				case "DatePat":
				case "TimePat":
				case "DateTimePat":
				case "TextareaPat":
				case "TextareaBPat":
					// 执行对应函数,进行验证
					var gotIt = eval(thePat);
					break;
				default:
					// 用正则表达式验证elArr[i]的值
					var gotIt = thePat.test(value);
				break;
			}
			if (!gotIt) {
				// 添加错误提示信息
					this.AddError(i, getAttribute("msg"));
			}
		} 
		// 获取其max属性,指定输入内容最大长度
		if("GroupPat"!=_dataType){
		var _max = getAttribute("max");
		// 如果存在属性,则验证
		if (_max) {// 验证输入值是否超出范围
			var _leg = ByteLen(value);
			if (_leg > _max) {
				// 添加错误提示信息
				var _msg = "输入值超出最大范围,限制长度为" + _max + "位,当前值为" + _leg
						+ "位。(其中每个中文占2位字符)";
				this.AddError(i, getAttribute("label") + _msg);
			}
		}
		}
	}
	// 显示所有错误提示信息,并聚焦到第一个出错点
	if (this.ErrorMessage.length > 1) {
	    this.ErrorItem[1].focus();
		var msg = this.ErrorMessage.join("\n");
		alert(msg);
		return false;
	}
	return true;
}

//城市代码,用于身份证验证
var aCity = {
	11 : "北京",
	12 : "天津",
	13 : "河北",
	14 : "山西",
	15 : "内蒙古",
	21 : "辽宁",
	22 : "吉林",
	23 : "黑龙江",
	31 : "上海",
	32 : "江苏",
	33 : "浙江",
	34 : "安徽",
	35 : "福建",
	36 : "江西",
	37 : "山东",
	41 : "河南",
	42 : "湖北",
	43 : "湖南",
	44 : "广东",
	45 : "广西",
	46 : "海南",
	50 : "重庆",
	51 : "四川",
	52 : "贵州",
	53 : "云南",
	54 : "西藏",
	61 : "陕西",
	62 : "甘肃",
	63 : "青海",
	64 : "宁夏",
	65 : "新疆",
	71 : "台湾",
	81 : "香港",
	82 : "澳门",
	91 : "国外"
};

/*
 * 
 * ==============================================================================================
 * 函数名称: isIdCardNo(sId) 功能说明: 身份证号码的验证。 所需参数: sId:身份证号码 返回结果: 返回错误提示信息str。
 * 使用说明: 主要用于ValidateForm(theForm)、CheckForm(theForm)函数中。也可以单独使用。传递进相应的参数即可,
 * ==============================================================================================
 * 
 */

function isIdCardNo(sId) {
	var str = "";
	var len = sId.length;
	if (len == 15)
		re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/);
	else if (len == 18)
		re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d|x|X)$/);
	else {
		str = "输入的身份证号码位数不对,应该是15位或者18位!";
		return str;
		return false;
	}
	if (len == 15)
		if (isNaN(sId)) {
			str = "输入的身份证号码不是数字!";
			return str;
			return false;
		}
	if (len == 18)
		if (isNaN(sId.substr(0, 17))) {
			str = "输入的身份证号码不是数字!";
			return str;
			return false;
		}
	// 根据正则表达式判定身份证号码的正确性
	var a = sId.match(re);
	if (a != null) {
		// 验证身份证地区是否正确
		if (aCity[parseInt(sId.substr(0, 2))] == null
				|| aCity[parseInt(sId.substr(0, 2))] == "undefined") {
			str = "输入的身份证号码里地区不对!";
			return str;
			return false;
		}
		// 验证身份证出生日期是否正确
		if (len == 15) {
			var D = new Date("19" + a[3] + "/" + a[4] + "/" + a[5]);
			var B = D.getYear() == a[3] && (D.getMonth() + 1) == a[4]
					&& D.getDate() == a[5];
		} else {
			var D = new Date(a[3] + "/" + a[4] + "/" + a[5]);
			var B = D.getFullYear() == a[3] && (D.getMonth() + 1) == a[4]
					&& D.getDate() == a[5];
		}
		if (!B) {
			str = "输入的身份证号码里出生日期不对!";
			return str;
			return false;
		}
	}
	// 验证身份证号码是否正确
	if (len == 18) {
		if (a == null) {
			str = "输入的身份证号码里验证码无效!";
			return str;
			return false;
		} else {
			// 校验身份证号码
			var strJiaoYan = [ "1", "0", "X", "9", "8", "7", "6", "5", "4",
					"3", "2" ];
			var intQuan = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4,
					2, 1 ];
			var intTemp = 0;
			for (i = 0; i < len - 1; i++)
				intTemp += sId.substring(i, i + 1) * intQuan[i];
			intTemp %= 11;
			if (sId.substring(len - 1, len).toUpperCase() != strJiaoYan[intTemp]) {
				str = "输入的身份证号码无效!";
				return str;
				return false;
			}
		}
	}
	return str;
}

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
var base64DecodeChars = new Array(  
		  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  
		  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  
		  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,  
		  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,  
		  -1, 0, 1, 2, 3,  4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,  
		  15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,  
		  -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,  
		  41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);  
		function base64encode(str) {  
		  var out, i, len;  
		  var c1, c2, c3;  
		  len = str.length;  
		  i = 0;  
		  out = "";  
		  while(i < len) {  
		 c1 = str.charCodeAt(i++) & 0xff;  
		 if(i == len)  
		 {  
		   out += base64EncodeChars.charAt(c1 >> 2);  
		   out += base64EncodeChars.charAt((c1 & 0x3) << 4);  
		   out += "==";  
		   break;  
		 }  
		 c2 = str.charCodeAt(i++);  
		 if(i == len)  
		 {  
		   out += base64EncodeChars.charAt(c1 >> 2);  
		   out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));  
		   out += base64EncodeChars.charAt((c2 & 0xF) << 2);  
		   out += "=";  
		   break;  
		 }  
		 c3 = str.charCodeAt(i++);  
		 out += base64EncodeChars.charAt(c1 >> 2);  
		 out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));  
		 out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));  
		 out += base64EncodeChars.charAt(c3 & 0x3F);  
		  }  
		  return out;  
		}  
		function base64decode(str) {  
		  var c1, c2, c3, c4;  
		  var i, len, out;  
		  len = str.length;  
		  i = 0;  
		  out = "";  
		  while(i < len) {  
		 /* c1 */  
		 do {  
		   c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];  
		 } while(i < len && c1 == -1);  
		 if(c1 == -1)  
		   break;  
		 /* c2 */  
		 do {  
		   c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];  
		 } while(i < len && c2 == -1);  
		 if(c2 == -1)  
		   break;  
		 out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));  
		 /* c3 */  
		 do {  
		   c3 = str.charCodeAt(i++) & 0xff;  
		   if(c3 == 61)  
		 return out;  
		   c3 = base64DecodeChars[c3];  
		 } while(i < len && c3 == -1);  
		 if(c3 == -1)  
		   break;  
		 out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));  
		 /* c4 */  
		 do {  
		   c4 = str.charCodeAt(i++) & 0xff;  
		   if(c4 == 61)  
		 return out;  
		   c4 = base64DecodeChars[c4];  
		 } while(i < len && c4 == -1);  
		 if(c4 == -1)  
		   break;  
		 out += String.fromCharCode(((c3 & 0x03) << 6) | c4);  
		  }  
		  return out;  
		}  
		function utf16to8(str) {  
		  var out, i, len, c;  
		  out = "";  
		  len = str.length;  
		  for(i = 0; i < len; i++) {  
		 c = str.charCodeAt(i);  
		 if ((c >= 0x0001) && (c <= 0x007F)) {  
		   out += str.charAt(i);  
		 } else if (c > 0x07FF) {  
		   out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));  
		   out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));  
		   out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));  
		 } else {  
		   out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));  
		   out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));  
		 }  
		  }  
		  return out;  
		}  
		function utf8to16(str) {  
		  var out, i, len, c;  
		  var char2, char3;  
		  out = "";  
		  len = str.length;  
		  i = 0;  
		  while(i < len) {  
		 c = str.charCodeAt(i++);  
		 switch(c >> 4)  
		 {  
		  case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:  
		   // 0xxxxxxx  
		   out += str.charAt(i-1);  
		   break;  
		  case 12: case 13:  
		   // 110x xxxx  10xx xxxx  
		   char2 = str.charCodeAt(i++);  
		   out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));  
		   break;  
		  case 14:  
		   // 1110 xxxx 10xx xxxx 10xx xxxx  
		   char2 = str.charCodeAt(i++);  
		   char3 = str.charCodeAt(i++);  
		   out += String.fromCharCode(((c & 0x0F) << 12) |  
		    ((char2 & 0x3F) << 6) |  
		    ((char3 & 0x3F) << 0));  
		   break;  
		 }  
		  }  
		  return out;  
		}