$(function(){
  $(".Coupon").click(function()
  {
	if ($("#couponnum").val()=='')
	{
	  $("#couponnum").focus();
	  alert('请输入优惠券号!');
	  return false;
	}
	$.get('../inc/ajax.asp',{action:"Shop_ValidateCoupon",CouponNum:$("#couponnum").val()},function(s){
	  var returnStr=unescape(s);
	  if (returnStr=='' || returnStr==null){
		alert('对不起,您输入的优惠券不可用!');
		$("#couponnum").val('');
		return ;
	  }else{
		updateOrderFee(returnStr);
	  }
	});  
	  
  });
  
})
function updateOrderFee(returnStr){
    var realmoney=0;
	var facevalue=0;
	var maxdiscount=0;
	var availablemoney=0;
	var minAmount=0;
	var rarr=null;
	var str='';
	if (returnStr!='' && returnStr !=null)
	{
	  rarr=returnStr.split('|');
	  if (rarr.length<=1)
	  {
	   alert(returnStr);
	   return;
	  }
	  facevalue=parseFloat(rarr[0]).toFixed(2);
	  minAmount=parseFloat(rarr[1]).toFixed(2);
	  maxdiscount=parseFloat(rarr[2]);
	  availablemoney=parseFloat(rarr[3]).toFixed(2);
	  realmoney=parseFloat($('#TRealTotalPrice').text().substr(1)).toFixed(2);
	  if (parseFloat(realmoney)<parseFloat(minAmount))
	  {
	    alert('对不起,该优惠券最小订单金额为￥'+minAmount+ ' 元才可使用!' );
	    return ;
	  }else if(availablemoney<=0){
	    alert('对不起,该优惠券已用完!');
		return;
	  }else{
	   if (maxdiscount==0){
	   alert('恭喜,该优惠券可抵用￥'+facevalue+ ' 元!');
	   }else{
	      var allowmoney=parseFloat(realmoney)* (maxdiscount/100);                         //按百分比得可抵扣金额
		  if (allowmoney>availablemoney){
		     allowmoney=availablemoney;
		  }
		  if (availablemoney==facevalue || availablemoney-allowmoney!=0){
		  alert('恭喜,该优惠券是按订单总金额的'+maxdiscount+'%抵用,最多不超过￥'+facevalue+'元,当前可用余额￥'+parseFloat(availablemoney).toFixed(2)+'元。在本订单中可抵用￥'+parseFloat(allowmoney).toFixed(2)+ ' 元,使用后该优惠券还剩￥'+(availablemoney-allowmoney).toFixed(2)+'元!');
		  }else{
		  alert('恭喜,该优惠券还可抵用￥'+parseFloat(allowmoney).toFixed(2)+ ' 元,使用后该优惠券还剩￥'+(availablemoney-allowmoney).toFixed(2)+'元!');
		  }
		  facevalue=allowmoney;
	   }
	  $("#CouponTotal").html('￥'+parseFloat(facevalue).toFixed(2));
	  realmoney=realmoney-facevalue+parseInt($('#freight').html().substr(1));
	  $("#TotalPrice").html("￥"+realmoney);
	  }
	}
}

function ajshowdata(city)
{
  var Weight,freight,TotalPrice
  $.get("../inc/ajax.asp",{city:escape(city),expressid:$("#DeliverType option:selected").val(),action:"delivery"},function(d){
	var r=unescape(d).split('|');
	if (r[0]=='error'){
		$("#jgxx").html('选择送货地点确定运费!');
	}else{ 
			$(".First").text(r[1]+"元/"+r[2]+"KG");
			$(".dHeavy").text(r[3]+"元/"+r[4]+"KG");
			$("#choosecity").val(r[0]);
			$("input[name='choosecity']").val(r[0]);
			Weight=$("#Weight").text()
			if (Weight>r[2])//'如果总重量>首重
			{
			  Weight=Math.ceil((Weight-r[2])/r[4])//续重的倍数向上取整=(总重-首重)/续重
			  freight=parseFloat(r[1])+Weight*r[3]//首重金额+续重的倍数*续重金额
			}
			else
			{
			  freight=r[1]
			}
			$("#freight").text("￥"+freight)
			TotalPrice=freight+parseFloat($('#TRealTotalPrice').text().substr(1))
			$("#TotalPrice").text("￥"+TotalPrice)
		}
  });
} 
