define(function(require){
	var $ = require('jquery');
	var IFA=require('util');
	require('dialog')($);
	require('uriTemplate')($);
	require('dateTimePicker')($);
	require('validation')($);
	require('globalization');
	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 contextPath = $("#contextPath").val();
	//resHistory审计历史
	$("#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);
	});
	//坐席编辑  
	$("#editButton").bind("click",function(){
		//if(vhlAuthority=="true"){
			$("#travelRouteDivShow").css('display','none');
			$("#travelRouteDiv").css('display','');
			$("#buttonTitleShow").css('display','none');
			$("#buttonTitle").css('display','');
		//}
		$("#serviceTbodyShow").css('display','none');
		$("#serviceTbody").css('display','');
	/*	if($("#paymentTypeShow :selected").val()!=2){			
			if($("#paymentTypeShow :selected").val()==1){
				if($("#billingStatus").val()==''||$("#billingStatus").val()<1){
					changePayment();
				}
			}else if($("#paymentTypeShow :selected").val()==4){
				if($("#cashReserveStauts").val()==''||$("#cashReserveStauts").val()<1){
					changePayment();
				}
			}else{
				changePayment();
			}
			
//			$("#paymentTypeShow").css('display','none');
//			$("#paymentType").css('display','');
//			$("#cdpNoInfoShow").css('display','none');
//			$("#cdpNoInfo").css('display','');
//			$("#paymentTypeInfoShow").css('display','none');
//			$("#paymentTypeInfo").css('display','');
		};*/
		$("#paymentManageShowTitle").hide();
		$("#paymentManageShow").hide();
		$("#paymentManageTableTitle").show();
		$("#paymentManageTable").show();
		$("#saveButton").css('display','');
		$("#cancelEditButton").css('display','');
		//$("#serviceHokKey").focus();
		$("#editButton").hide();
		$("#returnButton").hide();
	});
	//取消编辑
	$("#cancelEditButton").bind("click",function(){
		location.reload();
	});
	//返回按钮
	$("#returnButton").bind("click",function(){
		location.href=$("#indexUrl").val();
	});
	
	//总费用
	totalFeeFunction();
	//金额调整理由
	checkAjustAbleReason("checkAjustAbleReason",i18n["JS.workOrder.ajustableFeeTitle"]);
	//服务表单验证
	serviceFormValidate();
	//实际信息表单验证
	travelRouteFormValidate();
	travelRouteFormInfoValidate();
	//支付信息validate
	paymentInfoFormValidate();
	//销售人员热键
	hotKeySalerId();
	//产品代码热键
	hotKeyProduct();
		
	//服务元素验证
	serviceCheck("serviceCheck",i18n["JS.workOrder.prdCountsTipsMax"]);
	
	//服务代码
	$("#serviceHokKey").bind("keyup",function(){
		if(!this.value){
			$("#showMaxService,#isRestrictive,#serviceId").val("");
			$("#serviceForm").validate().element("#serviceCount");
			$("#serviceForm").validate().element("#serviceId");
		}
	});
	
	//保存
	$("#saveButton").bind("click",saveForm);
	//初始化日期
	initializehDate();
	
  	//服务产品数据处理
  	function serviceDataHandler(data){
  		$("#isRestrictive").val(data.isRestrictive);
  		$("#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+")");
	  		}
  		$("#serviceForm").validate().element("#serviceId");
  	}
  	
  	
  //初始化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");
				}
			}
		}
		//编辑部分
		extraaddAllHide2=$("#extraAddallHide2 :input");
		extraaddHide2=$("#extraAddHide2 :input");
		extraMullAllHide2=$("#extraMulallHide2 :input");
		extraMullHide2=$("#extraMulHide2 :input");
		for(var i=0;i<extraaddAllHide2.length;i++){
			for(var k=0;k<extraaddHide2.length;k++){
				if($(extraaddAllHide2[i]).val()==$(extraaddHide2[k]).val()){
					$(extraaddAllHide2[i]).attr("checked","checked");
				}
			}
		}
		for(var i=0;i<extraMullAllHide2.length;i++){
			for(var k=0;k<extraMullHide2.length;k++){
				if($(extraMullAllHide2[i]).val()==$(extraMullHide2[k]).val()){
					$(extraMullAllHide2[i]).attr("checked","checked");
				}
			}
		}
	}
	//计算extra cost
	 $("#extraAddallHide2 :input").bind("click",cal);
	 $("#extraMulallHide2 :input").bind("click",cal);
	
	$("#serviceHokKey").bind("blur",showExtra);
	//显示价格详情-extra cost
	function showExtra(){
	 	var url=$("#checkPrice").val().trim();
    	var para=$("#serviceId").val();
    	var temp= new $.Template(url);
    	 para={"serviceId":para};
    	 url = temp.expand(para);
    	// alert(url);
    	 $.ajax({
    		 type:"POST",
    		 url:url,
    		 async:false,
    		 dataType:"json",
    		 success:function(data){
    			 //alert(data.extra[0].ratePrice);
    			 var extra = data.extra;
    			 var targetAnd = $("#showExtraAndcg");
    			 var targetMul = $("#showExtraMulcg");
    			 	targetAnd.empty();	
    			 	targetMul.empty();
    			 for(var i=0;i<extra.length;i++){
    				 if(extra[i].discount==0){
    					 //targetMul.append("N/A");
    					 if(extra[i].required==0){
    						 targetAnd.append("<input type='checkbox' value='"+extra[i].rateId+"' alt='hide' price='"+extra[i].ratePrice+"'/>"+extra[i].rateName+":"+extra[i].ratePrice+" &nbsp&nbsp");
    					 }else if(extra[i].required=='1'){
    						 targetAnd.append("<input type='checkbox' readOnly='readOnly' enbled='false' alt='hide'  onclick='return false' checked value='"+extra[i].rateId+"' price='"+extra[i].ratePrice+"'/>"+extra[i].rateName+":"+extra[i].ratePrice+" &nbsp&nbsp");
    					 }
    				 }
//    				 if(extra[i].discount==1){
//    					 if(extra[i].required==0){
//    						 targetMul.append("<input type='checkbox' value='"+extra[i].rateId+"' alt='hide' price='"+extra[i].ratePrice+"'/>"+extra[i].rateName+":"+extra[i].ratePrice+" &nbsp&nbsp");
//    					 }else if(extra[i].required=='1'){
//    						 targetMul.append("<input type='checkbox' readOnly='readOnly' enbled='false' alt='hide' onclick='return false' checked value='"+extra[i].rateId+"' price='"+extra[i].ratePrice+"'/>"+extra[i].rateName+":"+extra[i].ratePrice+" &nbsp&nbsp");
//    					 }
//    				 }
    			 }
    			 if($("#showExtraAndcg :input").length==0){
    				 targetAnd.append("N/A");
    			 }
////    			 if($("#showExtraMulcg :input").length==0){
//    				 targetMul.append("N/A");
//    			 }
    			 $("#showExtraAndcg :input").bind("click",cal);
//    			 $("#showExtraMulcg :input").bind("click",cal);
    		 }
    		 
    	 });
    	 cal();
	}
	
	 function cal(){
			if($(this).attr("readOnly")){
				return false;//如果是只读则不进行计算
			}
			var add = $("#extraAddallHide2 :input");
			var addValue=0;
			for(var i=0;i<add.length;i++){
				if($(add[i]).attr("checked")){
					addValue+=-(-$(add[i]).attr("price"));//加法结果
				}
			}
					var dailyRate =Globalize.parseFloat($("#totalRental").val());//报价
					var mul = $("#extraMulallHide2 :input");
					var mulValue=0;
					for(var k=0;k<mul.length;k++){
						if($(mul[k]).attr("checked")){
							mulValue=accMul(dailyRate,$(mul[k]).attr("price"));//乘法结果
						}
					}
					//计算非EXTRA 值
					var allObj=$("#travelRouteForm :input:not(#remarks,#totalCharges,#ajustableReason,#uncharge,:checkbox)");
					//alert(allObj);
					var total=0;
					var amount=allObj;
					for(var i=0;i<amount.length;i++){
						var item=amount[i];
//						var items=(item[1]==""?0:item[1]);
						total+=Globalize.parseFloat($(item).val());
					}
					//计算非EXTRA 值 end
					if(mulValue==0){
						var temp = total-(-addValue);
					}else{
						var temp = total-(-addValue)-(-mulValue)-dailyRate;
					}
					$("#totalCharges").val(Globalize.format(temp,'n2'));	
					$("#totalFee").html(Globalize.format(temp,'c2'));
					$("#showTotalfee").html(Globalize.format(temp,'c2'));
		
			}
		//乘法计算
		function mul(){
			var check =	$(this).attr("checked");
			 if(check){
				 var extra=$(this).attr("price");
				 var revenue = $("#revenue").val();
				// alert(extra*revenue);
				 $("#revenue").val(accMul(extra,revenue));	
			 }
			 if(!check){
				 var extra=$(this).attr("price");
				 var revenue = $("#revenue").val();
				 // alert(extra*revenue);
				 $("#revenue").val(revenue/extra);	
			 }
		}
		
		function accMul(arg1,arg2)
		{
		  var m=0,s1=arg1.toString(),s2=arg2.toString();
		  try{m+=s1.split(".")[1].length}catch(e){}
		  try{m+=s2.split(".")[1].length}catch(e){}
		  return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
		}
		
	//服务验证表单
	function serviceFormValidate(){
      $("#serviceForm").validate({
			rules:{
    	        serviceId:{
			       required:true
		        }
//      ,
//		        serviceCount:{
//		           required:true,
//		           digits:true,
//		           serviceCheck: true,
//		           min:1
//		        }
		    },
			errorPlacement:function(error,element){
				$("<span />").html(error).insertAfter(element);
			}
		});
	}
		function resHistory(url){
			window.open(url,window);
		}
		//支付信息validate
		function paymentInfoFormValidate(){
			 $("#paymentInfoForm").validate();
		}
		//实际行程信息表单验证
		function travelRouteFormInfoValidate(){
	      $("#travelRouteFormInfo").validate({
			rules:{
	    	  startingOdometer:{
	    	  regex:common.validateFloat
	      },
	            endingOdometer:{
	    	  regex:common.validateFloat
	    	  
	      },    pickupOdometer:{
	    	  regex:common.validateFloat
	    	  
	      },   dropoffOdometer:{
	    	  regex:common.validateFloat
	    	  
	      },     usedKilometer:{
	    	  regex:common.validateFloat
	    	  
	      },     overkm:{
	    	  regex:common.validateFloat
	    	  
	      },     vehicleOccupy:{
	    	  regex:common.validateFloat
	    	  
	      },      actualOccupy:{
	    	  regex:common.validateFloat
	    	  
	      }, totalWorkingHours:{
	    	  regex:common.validateFloat
	    	  
	      },          overtime:{
	    	  regex:common.validateFloat
	    	  
	      }},
			errorPlacement:function(error,element){
					$("<span />").html(error).insertAfter(element);
				}
			});
		}
		//实际行程信息表单验证
		function travelRouteFormValidate(){
			$("#travelRouteForm").validate({
				rules:{
				noShowFee:{
					required:true,
					regex:common.validateFloat
				},
				tollFee:{
					required:true,
					regex:common.validateFloat
				},
				overnightFee:{
					required:true,
					regex:common.validateFloat
				},
				parkingFee:{
					required:true,
					regex:common.validateFloat
				},
				otherFee:{
					required:true,
					regex:common.validateFloat
				},
				totalRental:{
					required:true,
					regex:common.validateFloat
				},
				totalAboveKmFee:{
					required:true,
					regex:common.validateFloat
				},
				totalOvertimeFee:{
					required:true,
					regex:common.validateFloat
				},
				addtionalSurcharge:{
					required:true,
					regex:common.validateFloat
				},
				foreignerLicenseFee:{
					 required:true,
					 regex:common.validateFloat 
				},
				extraCoversFee:{
					required:true,
					regex:common.validateFloat  
				},
				vipFee:{
					required:true,
					regex:common.validateFloat   
				},
				conciergeFee:{
					required:true,
				    regex:common.validateFloat   
				},
				carCosts:{
					required:true,
					regex:common.validateFloat   
				},
				insuranceCosts:{
					required:true,
					regex:common.validateFloat   
				},
				gpsFee:{
					required:true,
					regex:common.validateFloat   
				},
				babySeatFee:{
					required:true,
					regex:common.validateFloat   
				},
				carWear:{
					required:true,
				    regex:common.validateFloat   
				},
				accelaratedFee:{
					required:true,
					regex:common.validateFloat   
				},
				trafficStopFee:{
					required:true,
					regex:common.validateFloat   
				},
				emergencyServiceFee:{
					required:true,
					regex:common.validateFloat   
				},
				ajustableFee:{
					regex:common.validateFloat
				},
				oilCharge:{
					regex:common.validateFloat
				},
				ajustableReason:{
					checkAjustAbleReason: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);
		}
	//公司图片显示
	$("#companyImageHandlerShow").bind("click",companyImageFun);
	//公司价格链接显示图片
	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');}
			}}); 
	}
	
	//初始化日期 联动
	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);
			}
			}
			}});
		$("#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);
			}
			}
			}});
		$("#estimatedArrival").datetimepicker({
			showSecond:false,
			stepMinute:15,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#estimatedDeparture").datetimepicker("option","minDate",new Date(date));
			}});
		$("#estimatedDeparture").datetimepicker({
			showSecond:false,
			stepMinute:15,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#estimatedArrival").datetimepicker("option","maxDate",new Date(date));
			}});
		//$("#pickupTime").datetimepicker({showSecond:false});
		//$("#dropoffTime").datetimepicker({showSecond:false});
		$("#pickupTime").datetimepicker({
			//minDate:-14,
			//stepMinute:15,
			//appendText:'yyyy-mm-ss',
			showSecond:false,
			//min:0,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#dropoffTime").datetimepicker("option","minDate",new Date(date));
			}});
		$("#dropoffTime").datetimepicker({
			//minDate:-14,
			showSecond:false,
			//stepMinute:15,
		    onSelect:function(date){
			var date=date.split("-").join("/");
			$("#pickupTime").datetimepicker("option","maxDate",new Date(date));
			}});
		}
	
	//全局变量序列化所有表单信息
	var formSerialize=allFormSerialize();
	function allFormSerialize(){
		return $("#serviceForm").serialize()+"&"+$("#travelRouteFormInfo").serialize()+"&"+$("#travelRouteForm").serialize()+"&"+$("#paymentInfoForm").serialize();
	}
	//保存所有信息
	function saveForm(){
		if(formSerialize!=allFormSerialize()){
			var a = $("#serviceForm").valid();
			var b = $("#travelRouteFormInfo").valid();
			var c = $("#travelRouteForm").valid();
			var d = $("#paymentInfoForm").valid();
		   if(a&&b&&c&&d){
			   if(!gfe.checkIsSameAmount()){
					return;
				}
			   allFormSave();
			   }else{
				   $(".error:first").parent().find("input:first").focus();
				   }
		   }else{
			   $.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.noChangeNoSaveTips"]);
			   }
		}
	
	//页面所有元素保存
	function allFormSave(){
		$.msg.confirm(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.saveClosedConfirm"] ,function(result){
			if(result){
				var checked = $("input[alt='hide']");
				var serviceId = $("#resIdShow").text().trim();
				var fk="";
				for(var i=0;i<checked.length;i++){
					if($(checked[i]).attr("checked")){
						fk+=$(checked[i]).val()+",";
					}
				}
				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:allFormSerialize(),
					success:function(response){
					    $.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.saveClosedSuccess"],function(result){
					    	//不需要修改状态，而且需要继续操作 审核 因此reload页面
					    	location.reload(true);
					    });
					},
					error:function(){
						$.msg.alert(i18n["JS.workOrder.system.tips"],i18n["JS.workOrder.saveClosedFailed"]);
						}
				});}});
		
	}
	
	function changePayment(){
		$("#paymentTypeShow").css('display','none');
		$("#paymentType").css('display','');
		$("#cdpNoInfoShow").css('display','none');
		$("#cdpNoInfo").css('display','');
		$("#paymentTypeInfoShow").css('display','none');
		$("#paymentTypeInfo").css('display','');
	}
	
	//计算总费用
	function totalFeeFunction(){
		$("#travelRouteForm :input:not(#remarks,#totalCharges,#ajustableReason)").bind("keyup",function(){ totalFeeAdd();});
		$("#travelRouteForm :input:not(#remarks,#totalCharges,#ajustableReason)").each(function(i){ 
			$(this).bind("blur",function(){
				formatPrice(this.value,this.id);
				$("#travelRouteForm").validate().element("#"+this.id);
				totalFeeAdd();
			});
			});
	}
	
	//格式化价钱
	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 reg=/^-?\d{1,10}\.$/;
//		var reg1=/^-?\d{1,10}$/;
//		if(value.match(reg)){
//			$("#"+element).val(Globalize.format(value,'c2'));
//			}
//		else if(value.match(reg1)){
//			$("#"+element).val(Globalize.format(value,'c2'));
//			}
//		else if(!value){
//				$("#"+element).val(0);
//			}
	}
	
	//费用计算
	function totalFeeAdd(){
		var status=validateTotalFee();
		if(status){
			//var allObj=$("#travelRouteForm :input:not(#remarks,#totalCharges,#ajustableReason)").serialize();
			
			var allObj=$("#travelRouteForm :input:not(#remarks,#totalCharges,#ajustableReason,#uncharge,:checkbox)");
			//alert(allObj);
			var total=0;
			var amount=allObj;
			for(var i=0;i<amount.length;i++){
				var item=amount[i];
//				var items=(item[1]==""?0:item[1]);
				total+=Globalize.parseFloat($(item).val());
			}
			//extra cost
			var add = $("#extraAddallHide2 :input");
			var addValue=0;
			for(var i=0;i<add.length;i++){
				if($(add[i]).attr("checked")){
					addValue+=-(-$(add[i]).attr("price"));//加法结果
				}
			}
					var dailyRate =Globalize.parseFloat($("#totalRental").val());//报价
					var mul = $("#extraMulallHide2 :input");
					var mulValue=0;
					for(var k=0;k<mul.length;k++){
						if($(mul[k]).attr("checked")){
							mulValue=accMul(dailyRate,$(mul[k]).attr("price"));//乘法结果
						}
					}
					// extra cost end
			total+=addValue;
			total+=mulValue;
			$("#totalCharges").val(Globalize.format(total,'n2'));
			$("#totalFee").html(Globalize.format(total,'c2'));
		}
	}
	
	//为费用计算验证
	function validateTotalFee(){
		var status=true;
		$("#travelRouteForm").validate().element("#ajustableReason");
		$("#travelRouteForm :input:not(#remarks,#totalCharges,#ajustableReason,#uncharge,:checkbox)").each(function(i){
			if(!$("#travelRouteForm").validate().element("#"+this.id)){
				status=false;
			}
		});
		return status;
	}
	
	//千分位正则替换",",并且仅保留两位小数
	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;   
	}
	
	//金额调整理由
	function checkAjustAbleReason(method,message){
		$.validator.addMethod(method,function(value,element,params){
			var money=$("#ajustableFee").val().trim();
			var reason=$("#ajustableReason").val().trim();
			if(!isNaN(money)){
				if(parseFloat(money)!=parseFloat("0")){
					$("#ajustableReasonFont").css('display','');
					if(reason==""){
						return false;
					}else{
						return true;
					}
			}else{
				$("#ajustableReasonFont").css('display','none');
				return true;
			}
			}else{
				$("#ajustableReasonFont").css('display','none');
				return true;
			}
			
		},message);
		
	}
	//销售人员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 hve_display(tId,iId){//显示隐藏程序
		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 off_img=contextPath+"/images/btn_arrow_right.gif";//隐藏时图片
		//console.log(tal);
		var i = 0;
		$.each(tal,function(){
			hve_close(tal.get(i),img.get(i));
//			tal.get(i).style.display="none";
//			img.get(i).src=off_img;
			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++;
		});
	});
	

});