define(function(require,exports){
	var $ = require('jquery');
	var IFA=require('util');
	require('uriTemplate')($);
	require('dialog')($);
	require('cookie')($);	
	require('dateTimePicker')($);
	require('globalization');
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../styles/cim/cim-grid.css');
	require('../../../styles/cim/validation.css');
	require('../../../styles/cim/autoComplete.css');
	require('../../../js/seaJsExtends/autoComplete.js')($);
	exports.getPrice = getPrice;
	exports.calculateRentalDays = CalculateRentalDays;
	exports.hotKeyCity = hotKeyCity;
	exports.clearPrice = clearPrice;
	exports.cal = cal;
	exports.mul = mul;
	exports.showExtra = showExtra;
	exports.validateInt = /^((([0-9]|\,)*)|(([0-9]|\.)*)|(([0-9]|\')*))$/;
	exports.validateFloat = /^((([0-9]|\,)*(\.[0-9]{1,2})?)|(([0-9]|\.)*(\,[0-9]{1,2})?)|(([0-9]|\')*((\.|\,)[0-9]{1,2})?))$/;
	exports.validPrice=validPrice;
	exports.validTravelRoutePrice=validTravelRoutePrice;
	exports.setCookieData=setCookieData;
	exports.getCookieData=getCookieData;
	$(function(){
		
	
	});
	
	//自动计算价格
	function getPrice(){
		var category=$("#category").val().trim();
		var pickupLocation =$("#pickupLocation").val();
		var returnLocation =$("#returnLocation").val();
		if(pickupLocation==null ||pickupLocation==""){
			if($("#pickupLocation").val()==null||$("#pickupLocation").val()==""){
				$.msg.alert(i18n["RateSheet.productPrice.Validate.pickupLocation"]);
				return false;
			}else{
				$.msg.alert(i18n["RateSheet.productPrice.ValidateAgain.pickupLocation"]);
				return false;
			}
			}
		if(returnLocation==null ||returnLocation==""){
			if($("#returnLocation").val()==null||$("#returnLocation").val()==""){
				$.msg.alert(i18n["RateSheet.productPrice.Validate.pickupLocation"]);
				return false;
			}else{
				$.msg.alert(i18n["RateSheet.productPrice.ValidateAgain.dropoffLocation"]);
				return false;
			}
		}

		var APT =$("#serviceId").val();//机场
		var trip = $("#isRound").val();
		if(trip==1){
			trip="Single Trip";
		}else if(trip==2){
			trip="Round Trip";
		}
		var airport = "";
		var apt = APT.split("_");
		airport=apt[1];

		var carGroup = $("#categoryId").val();
		var rentalDays =$("#rentalDays").val();
		var pcCode = $("#pcHotKey").val();//pccode
		var cdp = $("#companyCdp").val();//cdp
		var urlStr = $("#calculatePrice").val();
	    $.ajax({
	    	type:"POST",
	    	url:urlStr+".json",
			async:false,
	    	data:{"cdp":cdp,"trip":trip,"airport":airport,"pcCode":pcCode,"category":category,"pickupLocation":pickupLocation,"returnLocation":returnLocation,"carGroup":carGroup,"days":rentalDays},
		    success: function(response,ioArgs){
		    	if(response.data==null){
		    		clearPrice();
		    		$.msg.alert(i18n["RateSheet.excel.calculate.price"]);		    		
		    		return false;
		    	}
		    	if(response.data.price=="-1"){
		    		$.msg.alert(i18n["RateSheet.excel.calculate.price"]);
		    		return false;
		    	}
		    
		    	
		    	if(category=="Chauffeur drive"){
		    		if(rentalDays<=0.167){
		    			$("#dailyRate").val(response.data.price);
			    		$("#revenue").val(response.data.price);
		    		}else{
		    			$("#dailyRate").val(response.data.price*rentalDays);
			    		$("#revenue").val(response.data.price*rentalDays);
		    		}
		    	}else if(category=="self-drive"){
			    		$("#dailyRate").val(response.data.price*rentalDays);
			    		$("#revenue").val(response.data.price*rentalDays);
		    	}else{
		    		$("#dailyRate").val(response.data.price);
		    		$("#revenue").val(response.data.price);
		    	}
		    	$("#maxKmAllowable").val(response.data.capKmDay);
		    	$("#maxHourAllowable").val(response.data.hoursDay);
		    	$("#perExtraKmCharge").val(response.data.extraKmCharge);
		    	$("#perExtraHourCharge").val(response.data.extraHourCharge);
		    	cal();
		   	},error:function(response,ioArgs){
		   		clearPrice();
		   		$.msg.alert(i18n["Reservation.failedToCalculate"]);
		   	}
	   	});
	    
	   
	}
	
	//自动计算价格
	function clearPrice(){
   		$("#dailyRate").val("0");
		$("#revenue").val("0");
		$("#maxKmAllowable").val("");
    	$("#maxHourAllowable").val("");
    	$("#perExtraKmCharge").val("");
    	$("#perExtraHourCharge").val("");
	}
	
	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) {
						if(obj.selector=="#pickUpLocationName"){
							$("#pickUpLocation").val(data.id);
							$("#pickUpLocation_q").val(data.name);
							$("#pickUpLocationId_q").val(data.id);
						}
						if(obj.selector=="#returnLocationName"){
							$("#returnLocation").val(data.id);
							$("#returnLocation_q").val(data.name);
							$("#returnLocationId_q").val(data.id);
						}
						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);
						       }
						   });				
						clearPrice();
						changeDetail();
					});
		}
		});
	};
	
	function CalculateRentalDays(){

		var returnDate = $('#returnDate').val();
		var pickDate =  $('#pickupDate').val();

		if(returnDate==""||pickDate==""){
			$('#rentalDays').val("");
		}else{
			var rentalDays = DateDiff(pickDate,returnDate);
			$('#rentalDays').val(rentalDays);
		}
	}
	
    function DateDiff(sPickupDate, sDropoffDate){ //sDate1和sDate2是2002-12-18格式    

        var pickupArrayDate, dropoffArrayDate, pickupArrayHour,dropoffArrayHours,iDays;  
        var strHour = sPickupDate.substr(sPickupDate.lastIndexOf('-')+3);
        pickupArrayHour = strHour.split(":");
        sPickupDate = sPickupDate.substr(0,sPickupDate.lastIndexOf('-')+3);
        pickupArrayDate = sPickupDate.split("-");    
        pickupDate = new Date(pickupArrayDate[0],pickupArrayDate[1]-1,pickupArrayDate[2],pickupArrayHour[0],pickupArrayHour[1]);
        strHour = sDropoffDate.substr(sDropoffDate.lastIndexOf('-')+3);
        dropoffArrayHours = strHour.split(":");
        sDropoffDate = sDropoffDate.substr(0,sDropoffDate.lastIndexOf('-')+3);
        dropoffArrayDate = sDropoffDate.split("-");    
        dropoffDate = new Date(dropoffArrayDate[0],dropoffArrayDate[1]-1,dropoffArrayDate[2],dropoffArrayHours[0],dropoffArrayHours[1]);        
        //logic : -1 second mean : 24 hours only count as 1 day nor 2 days
        iDays = parseInt((Math.abs(pickupDate - dropoffDate)-1) / 1000 / 60 / 60 / 24);
        var category = $("#category").val();
        if(category=="Chauffeur drive"){
        	 iDays = parseInt(Math.abs(pickupDate - dropoffDate) / 1000 / 60 / 60 );
        	 if(iDays/24<=0.1667){
        		 var templeDay=Math.round(iDays/24*1000)/1000;
        		 	if(templeDay==0.167){
        		 		return 0.166;//处理4小时临界值问题
        		 	}else{
        		 		return Math.round(iDays/24*1000)/1000 ;
        		 	}	
        	 }else if(iDays/24>0.1667) {
        		 return parseInt(iDays/24) +1;
        	 }
        }else{
        return iDays+1; 
        }	
    }
    
  //加计算
	function cal(){
		if($(this).attr("readOnly")){
			return false;//如果是只读则不进行计算
		}
		var add = $("#showExtraAndcg :input");
		var addValue=Number(0);
		var extraCostId = "";
		for(var i=0;i<add.length;i++){
			if($(add[i]).attr("checked")){
				var id = $(add[i]).attr("value");
				extraCostId += id+"-";
				if(isFreePcCode(id)){
					continue;
				}
				addValue+=Number($(add[i]).attr("price"));//加法结果
			}
		}
		$("#extraCostFk").val(extraCostId);//用于cds segement绑定extra Cost
		//额外的价计算
		var foreignerLicenseFee = Globalize.parseFloat($("#foreignerLicenseFee").val());
		var extraCoversFee = Globalize.parseFloat($("#extraCoversFee").val());
		var gpsFee = Globalize.parseFloat($("#gpsFee").val());
		var babySeatFee = Globalize.parseFloat($("#babySeatFee").val());
		var oilCharge =Globalize.parseFloat($("#oilCharge").val());
		addValue+=oilCharge+foreignerLicenseFee+extraCoversFee+gpsFee+babySeatFee;
	
		 	var dailyRate =Globalize.parseFloat($("#dailyRate").val());//报价
			 //$("#revenue").val(extra-(-addValue));	
				var mul = $("#extraMul :input");
				var mulValue=0;
				for(var k=0;k<mul.length;k++){
					if($(mul[k]).attr("checked")){
						dailyRate=accMul(dailyRate,Globalize.parseFloat( $(mul[k]).attr("value")));//乘法结果
					}
				}
				var revenueValue=dailyRate+addValue;
				revenueValue=revenueValue.toFixed(2);
				 $("#revenue").val(Globalize.format(Number(revenueValue),"n2"));	
	
		}
	/**
	 * 是否是免费项
	 */
	function isFreePcCode(extraId){
		var freePc = $("#freePcCode").find("input");
		var flag=false;
		for(var i=0;i<freePc.length;i++){
			if($(freePc[i]).attr("value")==extraId){
				flag = true;
				break;
			}
		}
		return flag;
	}
	//乘法计算
	function mul(){
		var check =	$(this).attr("checked");
		 if(check){
			 var extra=$(this).attr("value");
			 var revenue = $("#revenue").val();
			// alert(extra*revenue);
			 $("#revenue").val(accMul(extra,revenue));	
		 }
		 if(!check){
			 var extra=$(this).attr("value");
			 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)
	}
	
	//显示价格详情-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 = $("#showExtraMul");
    			 	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' alt='hide' price='"+extra[i].ratePrice+"' value='"+extra[i].rateId+"'/>"+extra[i].rateName+":"+Globalize.format(extra[i].ratePrice,'n2')+" &nbsp&nbsp");
    					 }else if(extra[i].required=='1'){
    						 targetAnd.append("<input type='checkbox' readOnly='readOnly' enbled='false'  alt='hide'  onclick='return false' checked price='"+extra[i].ratePrice+"' value='"+extra[i].rateId+"'/>"+extra[i].rateName+":"+extra[i].ratePrice+" &nbsp&nbsp");
    					 }
    				 }
//    				 if(extra[i].discount==1){
//    					 if(extra[i].required==0){
//    						 targetMul.append("<input type='checkbox' rateId='"+extra[i].rateId+"' value='"+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' onclick='return false' checked rateId='"+extra[i].rateId+"' value='"+extra[i].ratePrice+"'/>"+extra[i].rateName+":"+extra[i].ratePrice+" &nbsp&nbsp");
//    					 }
//    				 }
    			 }
    			 if($("#showExtraAndcg :input").length==0){
    				 targetAnd.append("N/A");
    			 }
//    			 if($("#extraMul :input").length==0){
//    				 targetMul.append("N/A");
//    			 }
    			 $("#showExtraAndcg :input").bind("click",cal);
    			 //$("#extraMul :input").bind("click",cal);
    		 }
    		 
    	 });
    	 cal();
	}
	
	function validPrice(){
		$("#dailyRate").val(Globalize.parseFloat($("#dailyRate").val()));
		$("#rentalDays").val(Globalize.parseFloat($("#rentalDays").val()));
		$("#maxKmAllowable").val(Globalize.parseInt($("#maxKmAllowable").val()));
		$("#maxHourAllowable").val(Globalize.parseInt($("#maxHourAllowable").val()));
		$("#perExtraKmCharge").val(Globalize.parseFloat($("#perExtraKmCharge").val()));
		$("#perExtraHourCharge").val(Globalize.parseFloat($("#perExtraHourCharge").val()));
		$("#perExtraDayCharge").val(Globalize.parseFloat($("#perExtraDayCharge").val()));
		$("#revenue").val(Globalize.parseFloat($("#revenue").val()));
		$("#foreignerLicenseFee").val(Globalize.parseFloat($("#foreignerLicenseFee").val()));
		$("#extraCoversFee").val(Globalize.parseFloat($("#extraCoversFee").val()));
		$("#gpsFee").val(Globalize.parseFloat($("#gpsFee").val()));
		$("#babySeatFee").val(Globalize.parseFloat($("#babySeatFee").val()));
		$("#oilCharge").val(Globalize.parseFloat($("#oilCharge").val()));
	}
	function validTravelRoutePrice(){
		$("#tollFee").val(Globalize.parseFloat($("#tollFee").val()));
		$("#overnightFee").val(Globalize.parseFloat($("#overnightFee").val()));
		$("#parkingFee").val(Globalize.parseFloat($("#parkingFee").val()));
		$("#otherFee").val(Globalize.parseFloat($("#otherFee").val()));
		$("#totalRental").val(Globalize.parseFloat($("#totalRental").val()));
		$("#totalAboveKmFee").val(Globalize.parseFloat($("#totalAboveKmFee").val()));
		$("#totalOvertimeFee").val(Globalize.parseFloat($("#totalOvertimeFee").val()));
		$("#addtionalSurcharge").val(Globalize.parseFloat($("#addtionalSurcharge").val()));
		$("#foreignerLicenseFee").val(Globalize.parseFloat($("#foreignerLicenseFee").val()));
		$("#extraCoversFee").val(Globalize.parseFloat($("#extraCoversFee").val()));
		$("#vipFee").val(Globalize.parseFloat($("#vipFee").val()));
		$("#conciergeFee").val(Globalize.parseFloat($("#conciergeFee").val()));
		$("#carCosts").val(Globalize.parseFloat($("#carCosts").val()));
		$("#insuranceCosts").val(Globalize.parseFloat($("#insuranceCosts").val()));
		$("#gpsFee").val(Globalize.parseFloat($("#gpsFee").val()));
		$("#babySeatFee").val(Globalize.parseFloat($("#babySeatFee").val()));
		$("#carWear").val(Globalize.parseFloat($("#carWear").val()));
		$("#accelaratedFee").val(Globalize.parseFloat($("#accelaratedFee").val()));
		$("#trafficStopFee").val(Globalize.parseFloat($("#trafficStopFee").val()));
		$("#emergencyServiceFee").val(Globalize.parseFloat($("#emergencyServiceFee").val()));
		$("#ajustableFee").val(Globalize.parseFloat($("#ajustableFee").val()));
		$("#oilCharge").val(Globalize.parseFloat($("#oilCharge").val()));
	}
	function setCookieData(){
		$.cookie('customerName',$("#customerName").val(),{expires:1,path:'/'});
		$.cookie('paymentType',$("#paymentType").val(),{expires:1,path:'/'});
		$.cookie('rentalNo',$("#rentalNo").val(),{expires:1,path:'/'});
		$.cookie('serviceHokKey',$("#serviceHokKey").val(),{expires:1,path:'/'});
		$.cookie('serviceId',$("#serviceId").val(),{expires:1,path:'/'});
		$.cookie('districtHokKey',$("#districtHokKey").val(),{expires:1,path:'/'});
		$.cookie('districtId',$("#districtId").val(),{expires:1,path:'/'});
		$.cookie('categoryId',$("#categoryId").val(),{expires:1,path:'/'});
		$.cookie('pickupLocation',$("#pickupLocation").val(),{expires:1,path:'/'});
		$.cookie('pickupDateStart',$("#pickupDateStart").val(),{expires:1,path:'/'});
		$.cookie('pickupDateEnd',$("#pickupDateEnd").val(),{expires:1,path:'/'});
		$.cookie('returnLocation',$("#returnLocation").val(),{expires:1,path:'/'});
		$.cookie('returnDateStart',$("#returnDateStart").val(),{expires:1,path:'/'});
		$.cookie('returnDateEnd',$("#returnDateEnd").val(),{expires:1,path:'/'});
		$.cookie('driverName',$("#driverName").val(),{expires:1,path:'/'});
		if($("#longTerm").attr("checked")=='checked'){
			$.cookie('longTerm',$("#longTerm").val(),{expires:1,path:'/'});
		}else{
			$.cookie('longTerm',null,{path:'/'});
		}	
		$.cookie('cdpNo',$("#cdpNo").val(),{expires:1,path:'/'});
		$.cookie('conciergeHokKey',$("#conciergeHokKey").val(),{expires:1,path:'/'});
		$.cookie('resStatus',$("#resStatus").val(),{expires:1,path:'/'});
		if($("#sortPickupDate").attr("checked")=='checked'){
			$.cookie('sortPickupDate',$("#sortPickupDate").val(),{expires:1,path:'/'});
			$.cookie('sortVehicle',null,{path:'/'});
			$.cookie('sortDriver',null,{path:'/'});
			$.cookie('sortConflicts',null,{path:'/'});
		}
		else if($("#sortVehicle").attr("checked")=='checked'){
			$.cookie('sortPickupDate',null,{path:'/'});
			$.cookie('sortVehicle',$("#sortVehicle").val(),{expires:1,path:'/'});
			$.cookie('sortDriver',null,{path:'/'});
			$.cookie('sortConflicts',null,{path:'/'});
		}
		else  if($("#sortDriver").attr("checked")=='checked'){
			$.cookie('sortPickupDate',null,{path:'/'});
			$.cookie('sortVehicle',null,{path:'/'});
			$.cookie('sortDriver',$("#sortDriver").val(),{expires:1,path:'/'});
			$.cookie('sortConflicts',null,{path:'/'});
		}
		else  if($("#sortConflicts").attr("checked")=='checked'){
			$.cookie('sortPickupDate',null,{path:'/'});
			$.cookie('sortVehicle',null,{path:'/'});
			$.cookie('sortDriver',null,{path:'/'});
			$.cookie('sortConflicts',$("#sortConflicts").val(),{expires:1,path:'/'});
		}
	}
	function getCookieData(){
		$("#customerName").val($.cookie('customerName'));
		$("#paymentType option[value="+$.cookie('paymentType')+"]").attr("selected", true);
		$("#rentalNo").val($.cookie('rentalNo'));
		$("#serviceHokKey").val($.cookie('serviceHokKey'));
		$("#serviceId").val($.cookie('serviceId'));
		$("#districtHokKey").val($.cookie('districtHokKey'));
		$("#districtId").val($.cookie('districtId'));
		$("#categoryId option[value="+$.cookie('categoryId')+"]").attr("selected", true);
		$("#pickupLocation").val($.cookie('pickupLocation'));
		$("#pickupDateStart").val($.cookie('pickupDateStart'));
		$("#pickupDateEnd").val($.cookie('pickupDateEnd'));
		$("#returnLocation").val($.cookie('returnLocation'));
		$("#returnDateStart").val($.cookie('returnDateStart'));
		$("#returnDateEnd").val($.cookie('returnDateEnd'));
		$("#driverName").val($.cookie('driverName'));
		if($.cookie('longTerm')){
			$("#longTermExchange").val("Y");
			$("#longTerm").attr("checked",true);
		}else{
			$("#longTermExchange").val("N");
		}
		$("#cdpNo").val($.cookie('cdpNo'));
		$("#conciergeHokKey").val($.cookie('conciergeHokKey'));
		$("#resStatus option[value="+$.cookie('resStatus')+"]").attr("selected", true);
		if($.cookie('sortPickupDate'))
			$("#sortPickupDate").attr("checked",true);
		else  if($.cookie('sortVehicle'))
			$("#sortVehicle").attr("checked",true);
		else  if($.cookie('sortDriver'))
			$("#sortDriver").attr("checked",true);
		else  if($.cookie('sortConflicts'))
			$("#sortConflicts").attr("checked",true);
	}
});

