define(function(require){
	var $ = require('jquery');
	require('dialog')($);
	require('uriTemplate')($);
	require('validation')($);
	require('globalization'); 
	var IFA = require('util');
	require('dateTimePicker')($);
	require('../../../styles/cim/jquery-ui-1.8.14.custom.css');
	require('../../../styles/cim/validation.css');
	var gfe = require('../paymethod/generatorForEditting.js');
	var common = require('../workOrder/reservationCommon.js');
	var reservationId=$("#id").val().trim();
	var contextPath = $("#contextPath").val();
	var isNoShow =false;
	$(function(){
		$("#resHistory").bind("click",function(){
			var urlString=new $.Template($("#searchOrderBySegmentIndex").val());
			var urlParams={"segmentNo":$("#segmentNo").val(),
					      "personId":$("#personId").val()};
			var url=urlString.expand(urlParams);
			resHistory(url);
		});
		//呼叫中心权限
		var ccAuthority=$("#ccAuthority").val();
		//车管中心权限
		var vhlAuthority=$("#vhlAuthority").val();
		
		var nextstepAuthority = $("#nextstepAuthority").val();
		
		//重新调配车辆和司机权限 
		var resDisAuthority = $("#resDisAuthority").val();
		var resDisDriverAuthority = $("#resDisDriverAuthority").val();
		var editAuthority = $("#editAuthority").val();
		var noshowAuthority = $("#noshowAuthority").val();
		var excelExportAuthority = $("#excelExportAuthority").val();
		
		$("#a_availableVehicle").bind("click",countAvailableVehicle);
		//自动计算价格
		$("#foreignerLicenseFee").blur(common.cal);
		$("#extraCoversFee").blur(common.cal);
		$("#gpsFee").blur(common.cal);
		$("#babySeatFee").blur(common.cal);
		$("#oilCharge").blur(common.cal);
		
		//计算价格
		$("#rentalDays").bind("keyup",common.getPrice);
		$("#calculate").bind("click",common.getPrice);
		//预锁车按钮
		$("#preLock").bind("click",preLockFun);
		$("#ignoreVehicle").bind("click",ignore);
		$("#upgradeVehicle").bind("click",upgrade);
		$("#printPDFBtn").bind("click",chooseTypeForPDF);
		$("#editOrderButton").bind("click",function(){
			var url = $("#editOrderUrl").val();
			url=new $.Template(url);
			var para={"orderId":$("#orderId").val()};
			url=url.expand(para);
			location.href=url;
		});
		$("#categoryId").bind("click",disableSelect);
		function disableSelect(){
			var index = this.selectedIndex;    
	          this.onchange = function() {     
	              this.selectedIndex = index;     
	  };     
		}
		//坐席编辑
		$("#editButton").bind("click",function(){
			if(ccAuthority=="true"){
				$("#detailDiv").css('display','none');
				$("#editDiv").css('display','');
				$("#saveButton").css('display','');
				$("#buttonTitleShow").css('display','none');
				$("#buttonTitle").css('display','');
			}
			$("#dispatcherVhlButton").css('display','');
//			$("#dispatcherDriverButton").css('display','');
			$("#dispatcherVhlButtonShow").css('display','');
//			$("#dispatcherDriverButtonShow").css('display','');
			$("#cancelEditButton").css('display','');
			$("#a1").focus();
			$("#editButton").hide();
			if(noshowAuthority=="true"){
			$("#cancelButton").hide();
			}
			$("#sendConfirmButton").hide();
			$("#returnButton").hide();
			if(nextstepAuthority=="true"){
			$("#nextStep").hide();
			}
			if(resDisAuthority=="true"){
			$("#dispatcherVhlButtonShow").hide();
			}
//			if(resDisDriverAuthority=="true"){
//			$("#dispatcherDriverButton").hide();	
//			}
			if(excelExportAuthority=="true"){
				$("#printPDFBtn").hide();
			}
		});

				
		$("#serviceHokKey").bind("blur",common.showExtra);
				
			   
		//计算extra cost
		 $("#extraAddallHide :input").bind("click",common.cal);
		 $("#extraMulallHide :input").bind("click",common.cal);
		
		//取消编辑
		$("#cancelEditButton").bind("click",function(){
			location.reload();
		});
		//调配司机
//		$("#dispatcherDriverButton").bind("click",dispatchDirver);
//		$("#dispatcherDriverButtonShow").bind("click",dispatchDirver);
		//调配车辆
		$("#dispatcherVhlButtonShow").bind("click",dispatchVhl);
		$("#dispatcherVhlButton").bind("click",dispatchVhl);
		//分配礼宾
		$("#dispatchConciergeButton").bind("click",dispatchConcierge);
		$("#redispatchConciergeButton").bind("click",redispatchConcierge);
		$("#dispatchConciergeButtonShow").bind("click",dispatchConcierge);
		$("#redispatchConciergeButtonShow").bind("click",redispatchConcierge);
		//发送确认函
		$("#sendConfirmButton").bind("click",sendConfirmation);
		//返回按钮
		$("#returnButton").bind("click",function(){
			location.href=$("#indexUrl").val().trim();
		});
		//格式化租金
		$("#revenue").bind("blur",function(){
			formatPrice(this.value,this.id);
			$("#afterPreLockForm").validate().element("#revenue");
		});
		//格式化paymentAmount
		$("#paymentAmount").bind("blur",function(){
			formatPrice(this.value,this.id);
			$("#afterPreLockForm").validate().element("#paymentAmount");
		});
		
		//初始化extra cost 数据
		initExtroCost();
		function initExtroCost(){
			extraaddAll=$("#extraAddall :input");
			extraadd=$("#extraAdd :input");
			extraMullAll=$("#extraMulall :input");
			extraMull=$("#extraMul :input");
			for(var i=0;i<extraaddAll.length;i++){
				for(var k=0;k<extraadd.length;k++){
					if($(extraaddAll[i]).val()==$(extraadd[k]).val()){
						$(extraaddAll[i]).attr("checked","checked");
					}
				}
			}
			for(var i=0;i<extraMullAll.length;i++){
				for(var k=0;k<extraMull.length;k++){
					if($(extraMullAll[i]).val()==$(extraMull[k]).val()){
						$(extraMullAll[i]).attr("checked","checked");
					}
				}
			}
			extraaddAllHide=$("#extraAddallHide :input");
			extraaddHide=$("#extraAddHide :input");
			extraMullAllHide=$("#extraMulallHide :input");
			extraMullHide=$("#extraMulHide :input");
			for(var i=0;i<extraaddAllHide.length;i++){
				for(var k=0;k<extraaddHide.length;k++){
					if($(extraaddAllHide[i]).val()==$(extraaddHide[k]).val()){
						$(extraaddAllHide[i]).attr("checked","checked");
					}
				}
			}
			for(var i=0;i<extraMullAllHide.length;i++){
				for(var k=0;k<extraMullHide.length;k++){
					if($(extraMullAllHide[i]).val()==$(extraMullHide[k]).val()){
						$(extraMullAllHide[i]).attr("checked","checked");
					}
				}
			}
		}

		//格式化nowShowFee
		$("#noShowFee").bind("blur",function(){
			formatPrice(this.value,this.id);
			$("#noShowFeeForm").validate().element("#noShowFee");
			$("#noShowFeeForm").validate().element("#noshowReason");
		});
		/**
		 * 跳过发送确认涵
		 */
		$("#nextStep").click(function(){
		 	var id = $("#id").val();
		    var urlStr = new $.Template($("#skipSendConfirmation").val());
		 	var param = {'id':id};
		 	var url = urlStr.expand(param);
		 	location.href = url;
		});
		
		//取消预订单按钮
		$("#cancelButton").bind("click",function(){
			$.msg.confirm(i18ns("JS.workOrder.system.tips"),i18n["JS.workOrder.adjustPayment"],function(){},{buttons:IFA.generateJson(i18n["Entity.page.YES"],function(){
				$(this).dialog("close"); 
				isNoShow = true;
				$("#editButton").trigger("click");
			},i18n["Entity.page.No"],function(){
				$(this).dialog("close"); 
				$.msg.confirm(i18n["JS.workOrder.cancleRes"],$('#noShowFeeForm'),function(){},{width:'370px',buttons:
					 IFA.generateJson(i18n["Entity.page.YES"],function(){
							if($("#noShowFeeForm").valid()){
								if(Globalize.parseFloat($("#noShowFee").val())!=Globalize.parseFloat($("#payAmountShow").text())){
									$.msg.alert(i18n["JS.workOrder.notEqual"]);
									return;
								}
								var cancelUrl = $("#cancelUrl").val().trim();
								$.ajax({
									type:"post",
									url:cancelUrl,
									data:{noShowFee:$("#noShowFee").val(),id:$("#id").val(),conciergeId:$("#conciergeId").val(),noshowReason:$("#noshowReason").val().trim()},
									success:function(response){
										if(response.auth){
										$('#noShowFeeForm').dialog('close');
									    $.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.resCancleSuccess"],function(){
									    	location.href=$("#indexUrl").val().trim();
									    });
									    }else{
									    	$('#noShowFeeForm').dialog('close');
									    	$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.noAuthorityCancle"]);
									    }
									},
									error:function(){
										$('#noShowFeeForm').dialog('close');
										$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.resDeleteFailed"]);
										}
								});
							}
							 
						 },i18n["Entity.page.No"],function(){
							 $("#noShowFee").val('0');
							 $("#noshowReason").val('');
							 $('#noShowFeeForm').dialog('close');
						 })
				 } );
			})});
	
		});
	 	
		//服务元素验证
		serviceCheck("serviceCheck",i18n["JS.workOrder.prdCountsTipsMax"]);
		//公司图片显示
		$("#companyImageHandler,#companyImageHandlerShow").bind("click",companyImageFun);
		//PC价格图片显示
		$("#pcImageHandler").bind("click",pcImageShowFunction);
		//保存
		$("#saveButton").bind("click",saveForm);
		//初始化日期
		//initializehDate();
		//表单验证
		preLockFormValidate();
		afterLockValidate();
		noShowFeeValidate();
		//tourCostFormValidate();
		//计算自驾费用
		//totalFeeFunction();
		paymentCheck("paymentCheck","&nbsp;");
		alipayCheck("alipayCheck","&nbsp;");
		checkRevenuePayment("checkRevenuePayment",i18n["JS.workOrder.revenueLimitedTips"]+":"+$("#limit").val()+"RMB");

		//销售人员热键
		hotKeySalerId();
		//产品代码热键
		hotKeyProduct();
		//地区热键
	    hotKeyDistrict();
	    
	    //城市热键
	    common.hotKeyCity($("#pickupLocation"),$("#pickupLocationDetail")); 
	    common.hotKeyCity($("#returnLocation"),$("#returnLocationDetail"));
	    
		//PC回车绑定
		$("#pcHotKey").bind("keyup",function(e){
			var e = e ?  e : window.event;
			if(e.keyCode==13){
				pcImageShowFunction();
			}
		});
		//车辆长租/短租
		$("#longTerm").bind("click",function(){
			var status=$("#longTerm").attr("checked");
			if(status == 'checked'){
				$("#longTermExchange").val("Y");
				$("#longTermShow").attr("checked",true);
			}else{
				$("#longTermExchange").val("N");
				$("#longTermShow").attr("checked",false);
			}
		});
		$("#subject").blur(function(){$("#afterPreLockForm").validate().element("#subject");});
		$("#paymentAmount").blur(function(){$("#afterPreLockForm").validate().element("#paymentAmount");});
		$("#tradeDesc").blur(function(){$("#afterPreLockForm").validate().element("#tradeDesc");});
		$("#settlingUnit").blur(function(){$("#afterPreLockForm").validate().element("#settlingUnit");});
		$("#recipient").blur(function(){$("#afterPreLockForm").validate().element("#recipient");});
		$("#mailingAddress").blur(function(){$("#afterPreLockForm").validate().element("#mailingAddress");});
		//付款方式
		$("#paymentType").change(function(){
			$("#afterPreLockForm").validate().element("#subject");
			$("#afterPreLockForm").validate().element("#tradeDesc");
			$("#afterPreLockForm").validate().element("#paymentAmount");
			$("#afterPreLockForm").validate().element("#settlingUnit");
			$("#afterPreLockForm").validate().element("#recipient");
			$("#afterPreLockForm").validate().element("#mailingAddress");
			if(this.value=='2'){
				$("#paymentHandler").css('display','');
				$("#settlingUnitFont").css('display','none');
				$("#recipientFont").css('display','none');
				$("#mailingAddressFont").css('display','none');
			}else if(this.value=='1'){
				$("#paymentHandler").css('display','none');
				$("#settlingUnitFont").css('display','');
				$("#recipientFont").css('display','');
				$("#mailingAddressFont").css('display','');
			}else{
				$("#settlingUnitFont").css('display','none');
				$("#recipientFont").css('display','none');
				$("#mailingAddressFont").css('display','none');
				$("#paymentHandler").css('display','none');
				}
		});
		//绑定礼券使用
		$("#voucherId").change(function(){
			var voucherId = $("#voucherId").val();
			if(voucherId==""){
				$("#comments").val('');
				$("#messageComments").css('display','none');
				}
			else{
				var voucherUrl = $("#voucherUrl").val();
				var voucherUrlStr = new $.Template(voucherUrl);
				var voucherParam = {"id":voucherId};
				var url = voucherUrlStr.expand(voucherParam);
				 $("#messageComments").css('display','');
				 $.ajax({
			         url:url+".json",
			         async: false,
			         dataType:"json",
			         success:function(data){
			            $("#comments").val(data.voucher.remarks);
			             }
			         } );   
				}
		});
		//服务代码
		$("#serviceHokKey").bind("keyup",function(){
			if(!this.value){
				$("#showMaxService,#isRestrictive,#serviceId").val("");
		  		$("#reservationForm").validate().element("#serviceCount");
		  		$("#reservationForm").validate().element("#serviceId");
			}
		});
		//地区代码
	    $("#districtHokKey").bind("keyup",function(){
			if(!this.value){
				$("#districtId").val("");
				$("#reservationForm").validate().element("#districtId");
			}
		});
	  //公司代码
	    $("#companyCdp").bind("keyup",function(){
			if(!this.value){
				$("#companyId,#settlingUnit,#recipient,#mailingAddress").val("");
			}
			
			common.clearPrice();
		});
	});
	//页面加载支付宝序列化
	var alipaySerialize = alipaySerializeFun();
	//序列化支付宝选项与金额
	function alipaySerializeFun(){
		var serialize = "paymentType="+$("#paymentType").val()+"&";
		serialize+="paymentAmount="+$("#paymentAmount").val();
		return serialize;
	}
	loadCategory();
	//加载对应的category
	function loadCategory(){
		var serviceId = $("#serviceId").val();
		var url = $("#loadCategory").val();
		$.ajax({
			type:"post",
			url:url,
			data:{"serviceId":serviceId},
			success:function(response){
				var category = response.category;
				$("#category").val(category);
			}
		});
		
	}
	common.calculateRentalDays();
	//服务产品数据处理
  	function serviceDataHandler(data){
  		$("#isRestrictive").val(data.isRestrictive);
  		$('#category').val(data.category.trim());//hetz 3 为计算价格使用
  		var category = data.category.trim();
  		if(category=="APT transfer"){//apt 只有location
  			//$("#province2").attr("disabled","false");
  			$("#round").children().remove();
  		}
  		else if(category!="Cross Border"&&category!="Inter City"){
  			//$("#province2").attr("disabled","false");
  			$("#round").children().remove();
  		}else{
  			//$("#province2").removeAttr("disabled");
  			$("#round").children().remove();
  			$("#round").append("<th>"+i18n['RateSheet.intercity.isround']+"</th>")
  						.append("<td><select id='isRound' name='resType'><option value='1'>"+i18n['RateSheet.intercity.single']+"</option><option value='2'>"+i18n['RateSheet.intercity.round']+"</option></select></td>");
  			$("#isRound").bind("change",common.clearPrice);
  		}
  		$("#serviceId").val(data.serviceId);
  		$("#showMaxService").html("("+i18n["JS.workOrder.prdCountsTipsNolimited"]+")");
  		if(data.isRestrictive == 'Y'){
	  		$("#confine").val(data.isRestrictive);
	  		$("#eachQuota").val(data.avgTransactionActual);
	  		$("#fullQuota").val(data.fullUsageHrs);
	  		var maxService=Math.floor(data.fullUsageHrs/data.avgTransactionActual);
	  		$("#maxService").val(maxService);
	  		$("#serviceForm").validate().element("#serviceCount");
	  		$("#showMaxService").html("("+i18n["JS.workOrder.prdTipsMaxCounts"]+":"+maxService+")");
	  		}
  		$("#reservationForm").validate().element("#serviceId");
  	}
	//初始化日期 联动
	function initializehDate(){
		$("#pickupDate").datetimepicker({
			stepMinute:15,
			showSecond:false,
		    onSelect:function(date){
			var date=$(this).datetimepicker("getDate");
			var returnDate = $("#returnDate").datetimepicker("getDate");
			var returnDateShow;
			if(returnDate){
			  returnDateShow = $("#returnDate").val();
			}
			$("#returnDate").datetimepicker("option","minDate",new Date(date.getTime()));
			$("#returnDate").datetimepicker("option","minDateTime",new Date(date.getTime()));
			if(returnDate){
			if(date.getTime()>returnDate.getTime()){
				$("#returnDate").val($(this).val());
			}else{
				$("#returnDate").val(returnDateShow);
			}
			}
			common.calculateRentalDays();
			common.clearPrice();
			}});
		$("#returnDate").datetimepicker({
			stepMinute:15,
			showSecond:false,
			beforeShow:function(date){
			var pickupDate = $("#pickupDate").val();
			if(pickupDate==""){
			}else{
				var date=$("#pickupDate").datetimepicker("getDate");
				 $("#returnDate").datetimepicker("option","minDate",new Date(date.getTime()));
				 $("#returnDate").datetimepicker("option","minDateTime",new Date(date.getTime()));
			}
			},
		    onSelect:function(date){
			var date=$(this).datetimepicker("getDate");
			var pickupDate = $("#pickupDate").datetimepicker("getDate");
			var pickupDateShow;
			if(pickupDate){
				pickupDateShow = $("#pickupDate").val();
			}
			$("#pickupDate").datetimepicker("option","maxDate",new Date(date.getTime()));
			$("#pickupDate").datetimepicker("option","maxDateTime",new Date(date.getTime()));
			if(pickupDate){
			if(date.getTime()<pickupDate.getTime()){
				$("#pickupDate").val($(this).val());
			}else{
				$("#pickupDate").val(pickupDateShow);
			}
			}
			common.calculateRentalDays();
			common.clearPrice();
			}});
		$("#estimatedArrival").datetimepicker({
			stepMinute:15,
			showSecond:false
			});
		$("#estimatedDeparture").datetimepicker({
			stepMinute:15,
			showSecond:false
			});
		}

	//全局变量序列化预锁
//	var formSerialize=$("#reservationForm").serialize()+"&"+$("#afterPreLockForm").serialize()+"&"+$("#tourCostForm").serialize();
	var formSerialize=$("#reservationForm").serialize()+"&"+$("#afterPreLockForm").serialize();
	//保存所有信息
	function saveForm(){
//		if(formSerialize!=($("#reservationForm").serialize()+"&"+$("#afterPreLockForm").serialize()+"&"+$("#tourCostForm").serialize())){
		if(formSerialize!=($("#reservationForm").serialize()+"&"+$("#afterPreLockForm").serialize())){
//			if(($("#reservationForm").valid())&&($("#afterPreLockForm").valid())&&($("#tourCostForm").valid())){
				var a = $("#reservationForm").valid();
				var b = $("#afterPreLockForm").valid();
			   if(a&&b){
				   if(!gfe.checkIsSameAmount(isNoShow)){
						return;
					}
			   allFormSave();
			   }else{
				   $(".error:first").parent().find("input:first").focus();
				   }
		   }else{
			   $.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.noChangeNoSaveTips"]);
			   }
		}
	//序列化预锁车项
	function preLockSerializeFun(){
		var serialize="districtHokKey="+$("#districtHokKey").val()+"&";
		serialize+="categoryId="+$("#categoryId").val()+"&";
		serialize+="pickupDate="+$("#pickupDate").val()+"&";
		serialize+="returnDate="+$("#returnDate").val();
		return serialize;
	}
	//页面所有元素保存
	function allFormSave(){
		if(alipaySerialize!=alipaySerializeFun()){
			$("#alipayChange").val('Y');
		}
		$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.reSaveResTips"] ,function(result){
			if(result){
				updateReservation();
				}
			});
		
	}
	//预锁验证表单
	function preLockFormValidate(){
      $("#reservationForm").validate({
			rules:{
    	        serviceId:{
			       required:true
		        },
//		        serviceCount:{
//		           required:true,
//		           digits:true,
//		           serviceCheck: true,
//		           min:1
//		        },
		        districtId:{
		        	required:true
		        },
		        categoryId:{
					required:true
				},
				pickupDate:{
					required:true
				},
				returnDate:{
					required:true
				}
		    },
			errorPlacement:function(error,element){
				$("<span />").html(error).insertAfter(element);
			},
			message:{
				districtId:{
	        	required:i18n["JS.workOrder.districtIdTips"]
	        		},
        		serviceId:{
 			       required:i18n["JS.workOrder.serviceIdTips"]
 		        }
			}
		});
	}
	//预锁后表单验证
	function afterLockValidate(){
		$("#afterPreLockForm").validate({
			rules:{
			settlingUnit:{
			paymentCheck:true
		},
			recipient:{
			paymentCheck:true
		},
			mailingAddress:{
			paymentCheck:true
		},
		    subject:{
			alipayCheck:true
		},
		    tradeDesc:{
			alipayCheck:true
		},  
		    paymentAmount:{
			alipayCheck:true,
			number:true
		},
		dailyRate:{
			regex:common.validateFloat
		},
//		    rentalDays:{
//		    regex:common.validateInt
//		},
		  maxKmAllowable:{
			regex:common.validateInt
		},
		  maxHourAllowable:{
			regex:common.validateInt
		},
		 perExtraKmCharge:{
			 regex:common.validateFloat
		},
		 perExtraHourCharge:{
			 regex:common.validateFloat
		},
		 perExtraDayCharge:{
			 regex:common.validateFloat
		},
		    revenue:{
			required:true,
			regex:common.validateFloat,
			checkRevenuePayment:true

		},
		foreignerLicenseFee:{
			 regex:common.validateFloat 
		},
		extraCoversFee:{
			regex:common.validateFloat
		},
		gpsFee:{
			regex:common.validateFloat
		},
		babySeatFee:{
			regex:common.validateFloat
		},
		oilCharge:{
			regex:common.validateFloat
		}
		},
		errorPlacement:function(error,element){
			$("<span />").html(error).insertAfter(element);
			}
		});
	}
	//预估金额
	function checkRevenuePayment(method,message){
		$.validator.addMethod(method,function(value,element,params){
			//需要校验
		 if($("#credibility").val() == 'Y'){
			if(parseFloat(value)>parseFloat($("#limit").val())){
				return false;
			}else{
				return true;
			}
			}else{
				return true;
			}
			
		},message);
	}
	//NO SHOW FEE 验证
	function noShowFeeValidate(){
		$("#noShowFeeForm").validate({
			rules:{
			    noShowFee:{
			        required:true,
					regex:common.validateFloat
				 },
				 noshowReason:{
					 required:true 
				 }
		},
		errorPlacement:function(error,element){
			$("<span />").html(error).insertAfter(element);
			}
		});
	}
	
	//产品服务验证
	function serviceCheck(method,message){
		$.validator.addMethod(method,function(value,element,params){
			//需要校验
		 if($("#isRestrictive").val() == 'Y'){
			if(value){
				//已选服务产品
				if($("#serviceId").val()){
					if(parseInt(value) > parseInt($("#maxService").val())){
						return false;
					}else{
						return true;
					}
				}else{
					return true;
				}
			}else{
				return true;
			}
			}else{
				return true;
			}
			
		},message);
	}
	//付款check
	function paymentCheck(method,message){
		$.validator.addMethod(method,function(value,element,params){
			//付款方式
			var type=$("#paymentType").val();
			if(type=='1'){
                if(!value){
                	return false;
                }else{
                	return true;
                }
			}else{
				return true;
			}
		},message);
	}
	//Alipay付款check
	function alipayCheck(method,message){
		$.validator.addMethod(method,function(value,element,params){
			//付款方式
			var type=$("#paymentType").val();
			if(type=='2'){
                if(!value){
                	return false;
                }else{
                return true;
                }
			}else{
				return true;
			}
		},message);
	}
	//显示价格PC图片
	function pcImageShow(imageSrc){
		$("#imageDragPc").removeAttr("style");
		$("#imageDragPc").attr("src",imageSrc);
		$("#pcImage").dialog({title:i18n["JS.workOrder.pcPricePic"], height:420,width:340, 
			modal: false,closeOnEscape:true,overlay: { opacity: 0.5, background: 'black',overflow:'auto'},
			buttons:{
			'ReDo':function(){$("#imageDragPc").removeAttr("style");},	
			'Zoom In':function(){
				$("#imageDragPc").css({
				      width: function(index, value) {
				        return parseFloat(value) * 1.2;
				      }, 
				      height: function(index, value) {
				        return parseFloat(value) * 1.2;
				      }});
			},
			'Zoom Out':function(){
				$("#imageDragPc").css({
				      width: function(index, value) {
				        return parseFloat(value) / 1.2;
				      }, 
				      height: function(index, value) {
				        return parseFloat(value) / 1.2;
				      }});
			},
			'Close':function(){$(this).dialog('close');}
			}}); 
	}
	//PC价格AutoComplete显示
	function pcImageShowFunction(){
		  if($("#pcHotKey").val()){
				//pc关键字不为空
			$("#imageDragPc").removeAttr("style");
			var pcUrl=$("#pcImageUrl").val();
			$.ajax({
					type:"post",
					url:pcUrl,
					timeout:3000,
					data:{hotKey:$("#pcHotKey").val()},
					success:function(response){
						var pc= response.pc;
						if(pc.length>1){
							$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.hotKeyTitleTips"]+"<font color='red'>"+$("#pcHotKey").val()+"</font>.</BR>"+i18n["JS.workOrder.pcPricePicMoreTips"]);
							$("#pcHotKey").autocomplete(pc,
								      {
										caption: "&nbsp;&nbsp;"+i18n["JS.pcHotKey.caption"],
										findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
										noFindCaption: "&nbsp;&nbsp;"+i18n["JS.pcHotKey.noFindcaption"]+":&nbsp; ",
										max: 5,
										selectedFirst:true,
										width: 200,
										formatItem: function(row, i, max) {
								             var title=row.pcRemarks;
								             var content=row.pcRemarks;
								             if(row.pcRemarks.length>10){
								            	 content= row.pcRemarks.substring(0,15)+"...";
								             }
											return '<span title="{2}"><span class="ac_code" >{0}</span><span class="ac_Name">{1}</span></span>'.patchContent(row.pcId,content,title);
										},
										formatMatch: function(row, i, max) {
											return "{0} {1}".patchContent(row.pcId, row.pcRemarks);
										},
										formatResult: function(row) {
											return "{0}".patchContent(row.pcId);
										}
									}).result(function(event, data, formatted) {
										pcImageShow($("#imageSource").val().trim()+data.fileSource);
									});
						}else if(pc.length ==1){
							pcImageShow($("#imageSource").val().trim()+pc[0].fileSource);
						}else{
							$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.keyWord"]+"：<font color='red'>"+$("#pcHotKey").val()+"</font>,"+i18n["JS.pcHotKey.noAvaiablePcInfo"]);
						}
					},
					error:function(response){
						$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.pcHotKey.failed"]);
					}
					});
		}else{
			$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.pcHotKey.noNull"]);
		}
	}
	//公司价格链接显示图片
	function companyImageFun(){
		$("#imageDrag").removeAttr("style");
		$("#companyImage").dialog({title:i18n["JS.workOrder.companyPricePic"], height:420,width:330, 
			modal: false,closeOnEscape:true,overlay: { opacity: 0.5, background: 'black',overflow:'auto'},
			buttons:{
			'ReDo':function(){$("#imageDrag").removeAttr("style");},	
			'Zoom In':function(){
				$("#imageDrag").css({
				      width: function(index, value) {
				        return parseFloat(value) * 1.2;
				      }, 
				      height: function(index, value) {
				        return parseFloat(value) * 1.2;
				      }});
			},
			'Zoom Out':function(){
				$("#imageDrag").css({
				      width: function(index, value) {
				        return parseFloat(value) / 1.2;
				      }, 
				      height: function(index, value) {
				        return parseFloat(value) / 1.2;
				      }});
			},
			'Close':function(){$(this).dialog('close');}
			}}); 
	}
	//销售人员ID热键
	function hotKeySalerId(){
		$.ajax({
			type:"get",
			url:$("#salerIDUrl").val(),
			success:function(response){
			var acdata=response.salers;
			$("#salerId").autocomplete(acdata,
				      {
						caption: "&nbsp;&nbsp;"+i18n["JS.salerIdHotKey.caption"],
						findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
						noFindCaption: "&nbsp;&nbsp;"+i18n["JS.salerIdHotKey.notFindCaption"]+":&nbsp; ",
						width: 200,
						max: 5,
						formatItem: function(row, i, max) {
				           //  var title="";
//				             if(row.isRestrictive == 'Y'){
//				            	 var maxService=Math.floor(row.fullUsageHrs/row.avgTransactionActual);
//				            	 title=i18n["JS.productHotKey.title0"]+".&#13;"+i18n["JS.productHotKey.title1"]+":"+maxService;
//				             }else{   
//				            	 title=i18n["JS.productHotKey.title2"];
//				             }
							return '<span class="ac_Name" >{0}</span></br><span class="ac_Name" >{1} </span><span> {2}</span>'.patchContent(row.jobNumber, row.cnName,row.enName);
						},
						formatMatch: function(row, i, max) {

							return "{0} {1} {2}".patchContent(row.jobNumber, row.cnName, row.enName);

						},
						formatResult: function(row) {

							return "{0}".patchContent(row.jobNumber);

							
						}
					}).result(function(event, data, formatted) {
						$("#salerId").val(data.jobNumber);
						$("#salerName").val(data.enName);
					});
		}
		});
	}
	
	//产品代码热键
	function hotKeyProduct(){
	  	$.ajax({
			type:"get",
			url:$("#hotkeyProduct").val(),
			success:function(response){
			var acdata=response.servicingProduct;
			$("#serviceHokKey").autocomplete(acdata,
				      {
						caption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.caption"],
						findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
						noFindCaption: "&nbsp;&nbsp;"+i18n["JS.productHotKey.noFindCaption"]+":&nbsp; ",
						width: 200,
						max: 5,
						formatItem: function(row, i, max) {
				             var title="";
				             if(row.isRestrictive == 'Y'){
				            	 var maxService=Math.floor(row.fullUsageHrs/row.avgTransactionActual);
				            	 title=i18n["JS.productHotKey.title0"]+".&#13;"+i18n["JS.productHotKey.title1"]+":"+maxService;
				             }else{
				            	 title=i18n["JS.productHotKey.title2"];
				             }
							return '<span title="{2}"><span class="ac_code" >{0}</span><span class="ac_Name" >{1}</span></span>'.patchContent(row.serviceId, row.serviceDescription,title);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.serviceId, row.serviceDescription);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.serviceDescription);
						}
					}).result(function(event, data, formatted) {
						serviceDataHandler(data);
						var oilCharge = 0.00;
			        	if(data.oilCharge!=null&&data.oilCharge!=""){
			        		oilCharge=data.oilCharge;
			        	}
			        	$("#oilCharge").val(oilCharge);
					});
		}
		});
	}
	//地区热键
	function hotKeyDistrict(){
	  	$.ajax({
			type:"get",
			url:$("#hotkeyDistrict").val(),
			success:function(response){
			var acdata=response.district;
			$("#districtHokKey").autocomplete(acdata,
				      {
						caption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.caption"],
						findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
						noFindCaption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.noFindCaption"]+":&nbsp; ",
						width: 200,
						max: 5,
						formatItem: function(row, i, max) {
							return '<span class="ac_code">{0}</span><span class="ac_Name">{1}</span>'.patchContent(row.districtHotkey, row.districtName);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1}".patchContent(row.districtHotkey, row.districtName);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.districtName);
						}
					}).result(function(event, data, formatted) {
						$("#districtId").val(data.districtId);
						$("#reservationForm").validate().element("#districtId");
					});
		}
		});
	}
	//全局变量预订单ID reservationId 
	function dispatchVhl(){
		$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.afterRedispatchVehicle"],function(result){
			if(result){
				$(this).dialog("close");
				var urlStr = new $.Template($("#redispatchVehicle").val());
				var params = {'reservationId':$("#id").val().trim(),'type':1};
				var url = urlStr.expand(params);
				location.href = url;
			}else{
				$(this).dialog("close");
			}
		});
	}
	//重新调配司机 
	function  dispatchDirver(){
		$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.afterRedisDriver"],function(result){
			if(result){
				$(this).dialog("close");
				var urlStr = new $.Template($("#redispatchDriver").val());
				var params = {'reservationId':reservationId,'type':0};
				var url = urlStr.expand(params);
				location.href = url;
			}else{
				$(this).dialog("close");
			}
		});
	
	}
	//分配礼宾 
	function dispatchConcierge(){
		var urlStr = new $.Template($("#dispatchConcierge").val());
		var params = {'reservationId':reservationId};
		var url = urlStr.expand(params);
		location.href = url;
	}
	//重新分配礼宾
	function redispatchConcierge(){
		var urlStr = new $.Template($("#redispatchConcierge").val());
		var params = {'reservationId':reservationId};
		var url = urlStr.expand(params);
		location.href = url;
	}
	
	//发送确认函 
	function sendConfirmation(){
		  var resId = reservationId;
	      var urlVal = $('#sendConfirmLetter').val().trim();
	      var urlStr = new $.Template(urlVal);
		  var urlParam = {"resId":resId};
		  var url = urlStr.expand(urlParam);	
	      location.replace(url);
	}
	
	//导入PDF
	function chooseTypeForPDF(){
		var div = $('#excelTemplate');
		$.msg.alert(i18n["Validation.send.plzchoose"],div,{
			buttons:
				IFA.generateJson(i18n["Entity.Operation.ok"],function(){
					$(this).dialog("close");
					url=$('#printPdfUrl').val();
					$('#exportForm').attr("action",url);
					excelChooseCheck();
					$("#exportForm").attr("method", "post");      
			        $("#exportForm").attr('target', '_blank');
					$('#exportForm').submit();
				}),
				width:350,height:210
		});
	}
	function excelChooseCheck(){
		$("#excelType").val($(":radio[name='excelTypes']:checked").val());
	}
	//格式化价钱
	function formatPrice(value,element){
		if(value.match(common.validateFloat)){
			$("#"+element).val(Globalize.format(Globalize.parseFloat(value),'n2'));
		}else{			
			$("#"+element).val(Globalize.format(0,'n2'));
		}
//		var money=value.split(".")[0];
//		if(money.length>10){
//			value=value.substring(0,10);
//		}
//		var reg=/^\d{1,10}\.$/;
//		var reg1=/^\d{1,10}$/;
//		if(value.match(reg)){
//			$("#"+element).val(value+"00");
//			}
//		else if(value.match(reg1)){
//			$("#"+element).val(value+".00");
//			}
//		else if(!value){
//				$("#"+element).val("0.00");
//			}
	}
	function resHistory(url){
		window.open(url,window);
	}
	
	//查询可用预锁车数量
	function countAvailableVehicle(){
		var districtId = $("#districtId").val();
		var categoryId = $("#categoryId").val();
		var startDate = $("#pickupDate").val();
		var returnDate = $("#returnDate").val();
		if( districtId=='' ||categoryId=='' ||startDate=='' || returnDate==''){
			$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.avaiableVhlTipsRequired"]);
			return false;
		}
		var rentalNo = $("#rentalNo").val();
		if(rentalNo==''){
			rentalNo=$("#empty_path_variable").val();
		}
		var urlTemplate=$("#countAvailableVehicleUrl").val();
		var urlString=new $.Template(urlTemplate);
		var urlParam = {"rentalNo":rentalNo,"districtId":districtId,"categoryId":categoryId,"startDate":startDate,"returnDate":returnDate};
		var url=urlString.expand(urlParam);
		$.ajax({
			type:"GET",
			url:url,
			async:false,
			data:urlParam,
			timeout:3000,
			success:function(response,ioArgs){
			$("#avaiableVhl").html(response.availableVehicle);
			if(response.availableVehicle<=0){
				$("#ignoreVehicle").show();
			}else{
				$("#ignoreVehicle").hide();
			}
			},
			error:function(){
				$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.failed"]);
			}
		});
	}
	//全局变量序列化预锁
	var preLockSerialize="";
	var lockSerialize="";
	function preLockFun(){
		  if($("#reservationForm").valid()){
			if($("#beforeUpgrade").val()!=""||(Number($("#avaiableVhl").html())>0&&$("#beforeUpgrade").val()=="")){
			if($("#id").val()){
				//锁车后 变更锁车因子
				if(preLockSerialize!=($("#reservationForm").serialize())){
					$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.preLockAgainTips"] ,function(result){
					   if(result){
			              if(lockSerialize!=preLockSerializeFun()){
			            	  lockVhlTips("update");
			            	  }else{
			            		  preLockUpdate();
			            	  }
			              }});
					}else{
						$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.lockNoChangeNoSave"]);
						}
				}else{
					$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.insertAndLockResTips"] ,function(result){
						if(result){
							lockVhlTips("insert");
							}
						});
					}
			  }else{
				  $.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.noAvaiableVhlTips"]);
			  }
			}
		  }
	
	function lockVhlTips(status){
		var vhlTotal=$("#avaiableVhl").html();
		if($("#beforeUpgrade").val()==""&&vhlTotal>0){
			$("#queueFlag").val("N");
				preLockUpdate();
		}else if($("#beforeUpgrade").val()!=""){
			$("#queueFlag").val("U");
			    preLockUpdate();	
		}else if(vhlTotal<=0){
			$("#preLock").focus();
	    			// 置空设置升级前车组ID
	    		$("#beforeUpgradeNameShow").hide();
	    		$("#beforeUpgradeName").html("");
	    		$("#beforeUpgrade").val("");
	    		$("#queueFlag").val("O");
	    		preLockUpdate();
		 }
			
	}
	
	   function preLockUpdate(){
			$.ajax({
				type:"post",
				url:$("#preLockUpdateUrl").val(),
				data:$("#reservationForm").serialize(),
				async:false,
				success:function(response){
				 if(response.noLogin){
					 $.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.nologIn"]);
				 }
				 else{
					 lockSerialize=preLockSerializeFun();
					 preLockSerialize=$("#reservationForm").serialize();
				     updateReservation();
				 }
				},
				error:function(){
					$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.preLockFailed"]);
					}
			});
	   }
	   function updateReservation(){
//		   common.validPrice();
		   var revenueTemp=$("#revenue").val();
		   $("#revenue").val(Globalize.parseFloat($("#revenue").val()));//单独处理
		   var price=[];
		   $("input[data='paymentAmount']").each(function(){
			   price.push($(this).val());
			});
		   $("input[data='paymentAmount']").each(function(){
			   $(this).val(Globalize.parseFloat($(this).val()));
			});
			var dataSerialize="";
			if($("#paymentType").removeAttr("disabled")){
				$("#paymentType").removeAttr("disabled");
				$("#subject").removeAttr("disabled");
				$("#tradeDesc").removeAttr("disabled");
				$("#paymentAmount").removeAttr("disabled");
				dataSerialize=$("#reservationForm").serialize()+"&"+$("#afterPreLockForm").serialize();
				$("#paymentType").attr("disabled","disabled");
				$("#subject").attr("disabled","disabled");
				$("#tradeDesc").attr("disabled","disabled");
				$("#paymentAmount").attr("disabled","disabled");
			}else{
				dataSerialize=$("#reservationForm").serialize()+"&"+$("#afterPreLockForm").serialize();
			}
			//if(tourFormSerialize!=$("#tourCostForm").serialize()){
				//dataSerialize+="&"+$("#tourCostForm").serialize();
			//}
			var checked = $("input[alt='hide']");
			var serviceId = $("#resId").val();
			var fk="";
			for(var i=0;i<checked.length;i++){
				if($(checked[i]).attr("checked")){
					fk+=$(checked[i]).val()+",";
				}
			}
//			var updateUrl = $("#updateExtraCost").val();
//			$.ajax({
//				type:"post",
//				url:updateUrl,
//				data:{"serviceId":serviceId,"fk":fk}
//			});
			var url = $("#updateUrl").val().trim();
			var temp= new $.Template(url);
	   	    var para={"serviceId":serviceId,"fk":fk};
	   	    url = temp.expand(para);
			$.ajax({
				type:"post",
				url:url,
				data:dataSerialize,
				success:function(response){
				    $.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.rentalUpdateDispatch"],function(){
				    	 //只要修改页面信息,需要变更预订单状态，因此不reload返回Index页面
				    	 location.href=$("#indexUrl").val();
				    });
				},
				error:function(){
					$("#revenue").val(revenueTemp);
					var i=0;
					$("input[data='paymentAmount']").each(function(){
						   $(this).val(price[i++]);
					});
					$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.rentalSaveFailedTips"]);
					}
			});
	   }
	   
		function upgrade(){
		    $("#beforeUpgrade").val($("#categoryId").val());
			$("#beforeUpgradeName").html($("#categoryId").find("option:selected").text());
			$("#beforeUpgradeNameShow").show();
			$("#queueFlag").val("U");
		}
		function ignore(){
			 if($("#reservationForm").valid()){
			if($("#id").val()){
				//锁车后 变更锁车因子
				if(preLockSerialize!=($("#reservationForm").serialize())){
					$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.preLockAgainTips"] ,function(result){
					   if(result){
			              if(lockSerialize!=preLockSerializeFun()){
			            	  lockVhlTips("update");
			            	  }else{
			            		  preLockUpdate();
			                 }
			              }});
					}else{
						$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.lockNoChangeNoSave"]);
						}
				}else{
					$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.insertAndLockResTips"],function(result){
						if(result){
							lockVhlTips("insert");
							}
						});
					}
			 }
		}
		  //实际行程信息表单验证
/*		function tourCostFormValidate(){
			$("#tourCostForm").validate({
				rules:{
				foreignerLicenseFee:{
					 regex:/^(([0-9]+[\.]?[0-9]+)|[0-9])$/,
					 number:true 
				},
				extraCoversFee:{
					regex:/^(([0-9]+[\.]?[0-9]+)|[0-9])$/,
					number:true  
				},
				gpsFee:{
					regex:/^(([0-9]+[\.]?[0-9]+)|[0-9])$/,
					number:true   
				},
				babySeatFee:{
					regex:/^(([0-9]+[\.]?[0-9]+)|[0-9])$/,
					number:true   
				}
			}
			});
		}
		//计算总费用
		function totalFeeFunction(){
			$("#tourCostForm :input:not(#totalCharges)").bind("keyup",function(){ totalFeeAdd();});
			$("#tourCostForm :input:not(#totalCharges)").each(function(i){
				$(this).bind("blur",function(){
					formatPrice(this.value,this.id);
					$("#tourCostForm").validate().element("#"+this.id);
					totalFeeAdd();
				});
				});
		}
		
		//费用计算
		function totalFeeAdd(){
			if($("#tourCostForm").valid()){
				var allObj=$("#tourCostForm  :input:not(#totalCharges)").serialize();
				var total=0;
				var amount=allObj.split("&");
				for(var i=0;i<amount.length;i++){
					var item=amount[i].split("=");
					var items=(item[1]==""?0:item[1]);
					total+=parseFloat(items);
				}
				$("#totalCharges").val(parseMoney(total));
				$("#totalFee").html(parseMoney(total)+i18n["Page.workOrder.yuan"]);
			}
		}
		*/
		//千分位正则替换",",并且仅保留两位小数
		function parseMoney(s){
			var minus=false;
			if(parseFloat(s)<0){
				minus=true;
				s=s.toString().substring(1);
			}
			s=s.toString();
		    s=s.replace(/^(\d*)$/,"$1.");
		    s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");   
		    s=s.replace(".",",");   
		    var re=/(\d)(\d{3},)/;   
		    while(re.test(s))   
		    s=s.replace(re,"$1,$2");   
		    s=s.replace(/,(\d\d)$/,".$1");
		    s=s.replace(/^\./,"0.");
		    if(minus){
		    	s="-"+s;
		    }
		    return s;   
		}  
	//全局变量序列化 初始的自驾信息
	//var tourFormSerialize=$("#tourCostForm").serialize();
		
		function hve_display(tId,iId){//显示隐藏程序
//			console.log(t_id);
//			console.log(i_id);
			var t_id = tId;//表格ID
			var i_id = iId;//图片ID
			var on_img=contextPath+"/images/btn_arrow_down.gif";//打开时图片
			var off_img=contextPath+"/images/btn_arrow_right.gif";//隐藏时图片
			if (t_id.style.display == "none") {//如果为隐藏状态
				t_id.style.display="";//切换为显示状态
				i_id.src=on_img;//换图
			}
			else{
				t_id.style.display="none";//切换为隐藏状态
				i_id.src=off_img;//换图
			}
			}
		
		$(".tableRes h2").bind("click",function(){
			var tal = $(this).parents(".tableRes").next(".tableRes");
			var img = $(this).children();
			hve_display(tal.get(0),img.get(0));
		});
		
		$("#allOpen").bind("click",function(){
			var tal = $("table[name='table']");
			var img = $("img[name='img']");
			var i = 0;
			$.each(tal,function(){
				hve_open(tal.get(i),img.get(i));
				i++;
			});
		});
		
		$("#allClose").bind("click",function(){
			var tal = $("table[name='table']");
			var img = $("img[name='img']");
			var i = 0;
			$.each(tal,function(){
				hve_close(tal.get(i),img.get(i));
				i++;
			});
		});
		function hve_open(tId,iId){//显示隐藏程序
			var t_id = tId;//表格ID
			var i_id = iId;//图片ID
			var on_img=contextPath+"/images/btn_arrow_down.gif";//打开时图片
				t_id.style.display="";//切换为显示状态
				i_id.src=on_img;//换图
			}
		
		function hve_close(tId,iId){//显示隐藏程序
			var t_id = tId;//表格ID
			var i_id = iId;//图片ID
			var off_img=contextPath+"/images/btn_arrow_right.gif";//隐藏时图片
				t_id.style.display="none";//切换为隐藏状态
				i_id.src=off_img;//换图
			}
		$("#editAllClose").bind("click",function(){
			var tal = $("table[name*='table']");
			var img = $("img[name*='img']");
			var i = 0;
			$.each(tal,function(){
				hve_close(tal.get(i),img.get(i));
				i++;
			});
		});
		$("#editAllOpen").bind("click",function(){
			var tal = $("table[name*='table']");
			var img = $("img[name*='img']");
			var i = 0;
			$.each(tal,function(){
				hve_open(tal.get(i),img.get(i));
				i++;
			});
		});
		
		function hotKeyCity(obj,objBind){
			$.ajax({
				type:"get",
				url:$("#hotkeyCity").val(),
				success:function(response){
				var acdata=response.cityHotkey;
				obj.autocomplete(acdata,
					      {
							caption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.caption"],
							findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
							noFindCaption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.noFindCaption"]+":&nbsp; ",
							width: 200,
							max: 8,
							formatItem: function(row, i, max) {
								return '<span class="ac_code" style="width:50%">{0}</span><span class="ac_Name">{1}</span>'.patchContent(row.hotKey, row.name);
							},
							formatMatch: function(row, i, max) {
								return "{0} {1}".patchContent(row.hotKey, row.name);
							},
							formatResult: function(row) {
								return "{0}".patchContent(row.name);
							}
						}).result(function(event, data, formatted) {
							
							var url = $("#queryParentCity").val();
							var parentName = '';
							$.ajax({
								   url:url,
								   type:"POST",
								   data:{"id":data.parentId},
								   dataType:"json",
								   timeout:5000,
								   success:function(response,ioArgs){								   
									   parentName = response.city.name + ',';
									   objBind.val(parentName + data.name);
									  
							       },
							       error:function(response,ioArgs){
							    	   objBind.val(data.name);
							       }
							   });
						});
			}
			});
		};
});