var transCost = 0;
function removeProduct(obj){
   if(confirm('确定不购买该商品？')){
      window.location=removeProduct_url+obj;
   }
}
var hamount = 0;
function changeTxtOnFocus(obj,num){
   hamount = obj.value;
}
function changeProductCount(obj,index,limitedAmount) {
   //检测输入是否为数字
   if(!checknumber(obj.value) || obj.value == 0){
   		if(obj.value != 0) {
	   		alert("您输入的格式不正确！");
   		}
	   	obj.value=hamount;
	   	return;
   	}
   	hpriceHandler(obj,index,limitedAmount);
}
var total = 0;
var totalPoints = 0;
function priceHandler(type,num,limitedAmount,obj) {
		var txtC=$('#og_'+num);
		var count = parseInt(txtC.attr('value'));
		if(count == 1 && type == '-') return;
		
		if(type == '-') {
			count -=1
		} else {
			count +=1;
		}
		txtC.val(count);
		
		if(count > limitedAmount && limitedAmount != -1 && limitedAmount != -2){
			alert("本商品为限量购买商品，您的购买数量已经超过限量("+limitedAmount+")");
			txtC.val(count - 1);
			return;
		}
		var basedCount = txtC.attr('baseC');
		if(count < basedCount && limitedAmount == -2){
			alert("本商品起购数量为("+basedCount+")");
			txtC.val(basedCount);
			return;
		}
		var memberprice = parseFloat(moneyStr($('#price_'+num).html()));
		var points = parseFloat($('#points_'+num).html());
		if(total == 0){
			total = parseFloat(moneyStr($('#total').html()));
		}
		if(totalPoints == 0){
			totalPoints = parseFloat($('#tpoints').html());
		}
		if(type == '-') {
			total -= memberprice;
			totalPoints -= points;
		} else{
			total += memberprice;
			totalPoints += points;
		}
		document.getElementById("total").innerHTML = cc(formatfloat1(total)+'');
		document.getElementById("tpoints").innerHTML = totalPoints;
}
function hpriceHandler(obj,index,limitedAmount) {
		var txtC=$('#og_'+index);
		var count = parseInt(obj.value);
		
		if(count > limitedAmount && limitedAmount != -1 && limitedAmount != -2){
			alert("本商品为限量购买商品，您的购买数量已经超过限量("+limitedAmount+")");
			txtC.val(hamount);
			return;
		} 
		var basedCount = txtC.attr('baseC');
		if(count < basedCount && limitedAmount == -2){
			alert("本商品起购数量为("+basedCount+")");
			txtC.val(basedCount);
			return;
		}
		var memberprice = parseFloat(moneyStr($('#price_'+index).html()));
		var points = parseFloat($('#points_'+index).html());
		if(total == 0){
			total = parseFloat(moneyStr($('#total').html()));
		}
		if(totalPoints == 0){
			totalPoints = parseFloat($('#tpoints').html());
		}
		var difference = count - hamount;
		total = total + memberprice * difference;
		totalPoints = totalPoints + points * difference;
		$("#total").html(cc(formatfloat1(total)+''));
		$("#tpoints").html(totalPoints);
}

function clearCart() {
   if(confirm('确定清空购物车吗？')){
   	  window.location=deleteAllInCart_url;
   }
}

function checkQuantity() {
	$.login({
				complete : function(result) {
					if (result != null && result.IsAuthenticated != null
							&& result.IsAuthenticated) {
							var gc = new Array();
							$("input[@name*=count_]").each(function() { 
								  	var name = $(this).attr('name');
								  	var gId = name.split('_')[1];
								  	var count = $(this).val();
								  	gc.push(gId+"_"+count);
								  });
							$.ajax({
							   type: "POST",
							   url: ajax_validateGoodQuantity_url,
							   cache: false,
							   async: false,
							   data: "gCount="+gc.join(','),
							   success: function(res){
							     if(res =='has_virtual'){
							     	alert("虚拟商品必须单独下单，请先删除其他商品。");
							     } else if(res != '0'){
									alert("'"+res+"' 库存数量不足!");
								} else {
									document.cartForm.submit();
								}
							   }
							 });
							 }
				}
	});
}
function saveOneAddress() {
	if(validateAddressForm()){
	var name = g('name').value;
	var province = g('province').value;
	var city = g('city').value;
	var district = g('district').value;
	var address = g('address').value;
	var postcode = g('postcode').value;
	var mobile = g('mobile').value;
	var phoneCode = g('phoneCode').value;
	var phone = g('phone').value;
	var phoneStr = phoneCode + '-' +phone;
	var queryString = {
		'name' : name,
		'province' : province,
		'city' : city,
		'district' : district,
		'address' : address,
		'code' : postcode,
		'mobile' : mobile,
		'phone' : phoneStr,
		'ajax':true
	};
	$.post(ajax_add_address, queryString, function(data) {
			$('#showAddress').html(data);
			$('#addressBar').show();
	});
	}
}
function saveAddress(pop) {
	var form = $('#addressForm');
	var options = {
    target:     '#showAddress',
    url:        form.attr('action'),
    beforeSubmit:  validateAddressForm,
    success: function() {
    	if(pop) $.unblockUI();
    	transprice();
    }};
	$('#addressForm').ajaxForm(options);
}
function validateAddressForm(formData, jqForm, options) {
	var address = g('address').value;
	var name = g('name').value;
	var phone = g('phone').value;
	var phoneCode = g('phoneCode').value;
	var mobile = g('mobile').value;
	var postcode = g('postcode').value;
	if (name == '') {
		setInnerHtml('message','收货人姓名不能为空');
		setDisplay('message',"block");
		return false;
	}
	if (address == '') {
		setInnerHtml('message','街道地址不能为空');
		setDisplay('message',"block");
		return false;
	}
	if (postcode == '') {
		setInnerHtml('message','邮政编码不能为空');
		setDisplay('message',"block");
		return false;
	}
	if(phone == '' && mobile == ''){
		setInnerHtml('message','电话号码和手机不能同时为空');
		setDisplay('message',"block");
		return false;
	}
	if(phoneCode != '')
		phone = phoneCode + '-' +phone;
	if (phone != '') {
		var array = phone.split('-');
		if (array.length < 2 || array.length > 3) {
			setInnerHtml('message','电话号码格式有误');
			setDisplay('message',"block");
			return false;
		}
		for (var i = 0; i < phone.length; i++) {
			var t = phone.charAt(i);
			if (!(t >= '0' && t <= '9' || t == '-')) {
				setInnerHtml('message','电话号码要为数字');
				setDisplay('message',"block");
				return false;
			}
		}
	}
	setDisplay('message',"none");
	return true;
}

function selectAddress() {
	$.get(ajax_select_address,{'t':new Date(),'addressId':getAddressId()},function(res){
		spanUI.html(res);
		blockUI(spanUI);
			});
}
function updateAddress() {
	var id = $("input[@name=selectAddress][@checked]").val();
	$.get(ajax_update_address,{'t':new Date(),"addressId":id},function(res){
		$('#showAddress').html(res);
		$.unblockUI();
		transprice()
	});
}
function orderAddAddress() {
	$.get(ajax_new_address,{'t':new Date()},function(res){
		if(res == 'invalid') {
			alert('最多保存5个有效地址');
		} else {
			spanUI.html(res);
			blockUI(spanUI);
			loadSelect('province','city','district');
		}
			});
}
function modifyAddress() {
	var id = getAddressId();
	if(id) {
		$.get(ajax_new_address+id,{'t':new Date()},function(res){
		spanUI.html(res);
		blockUI(spanUI);
		loadSelect('province','city','district');
			});
	}
}
function getAddressId() {
	var id;
	var obj = $('#showAddress div');
	if(obj.attr('class') == 'cart_54') {
		id = obj.attr('id');
	}
	return id;
}
function transprice(paytype){
	transportPrice= 0;
	var pt = 0;
	if(paytype) pt = paytype;
	var id = getAddressId();
	if(id) {
		jQuery.getJSON(ajax_transprice_url + '?' + new Date(), {'addressId':id,payType:pt}, function(res) {
				transCost =  parseFloat(res);
				$("span[@name*='tp']").each(function() {
			  		$(this).html(cc(transCost+''));
			  		var gtotal = parseFloat(moneyStr($('#gtotal').html()));
			  		var charge = parseFloat($('#pcash').html());
			  		var beans = parseFloat($('#bcash').html());
			  		$('#total').html(cc(transCost+gtotal-beans-charge+''));
			  	});
		});
	}
}
var modifyBut;
function modifyDisplayType(typeName,obj) {
	showWaitInfo('加载中...',obj);
	modifyBut = obj;
	obj.setAttribute('disabled',true);
	obj.parentNode.parentNode.style.width ='200px';
	setTimeout('clearWaitInfo()',500);
	setTimeout('transferDisplay("'+typeName+'")',500);
}

function transferDisplay(typeName) {
	setDisplay("basic"+typeName,"none");
	setDisplay("select"+typeName,"block");
}

function closeDisplayType(typeName) {
	setDisplay("basic"+typeName,"block");
	setDisplay("select"+typeName,"none");
	if(modifyBut) modifyBut.disabled = false;
	modifyBut = null;
}

function submitPayType() {
	var payType = $("input[@name=payType][@checked]");
	var payString = payType.parent().siblings().html();
	$('#basicPayType ul li:nth-child(1) span').html(payString);
	var shipType = $("input[@name=shipType][@checked]");
	var shipTypeString = shipType.parent().siblings().html();
	$('#basicPayType ul li:nth-child(2) span').html(shipTypeString);
	var shipTime = $("input[@name=shipTime][@checked]");
	var shipTimeString = shipTime.parent().siblings().eq(1).html();
	var t = "送货时间：<span>"+shipTimeString+"</span>";
	$('#basicPayType ul li:nth-child(4)').html(t);
	if(payType.val() == 3) {
		var selfPickBranch = $("input[@name=selfPickBranchId][@checked]");
		t = "自提时间：<span>"+$("input[@name=selfPickTime][@checked]").val()+"</span>";
		$('#basicPayType ul li:nth-child(4)').html(t);
		$('#basicPayType ul li:nth-child(2) span').html(payString+"("+$('#selfAddress'+selfPickBranch.val()).html()+")");
	}
	transprice(payType.val());
	closeDisplayType("PayType");
}

function submitInvoiceInfo() {
	var invoiceType = $("input[@name=invoiceType][@checked]");
	var invoiceTypeString = $('#invoiceType'+invoiceType.val()).html();
	$('#basicInvoiceInfo ul li:nth-child(1) span').html(invoiceTypeString);
	
	var invoiceName = $(".cart_152").val();
	$('#basicInvoiceInfo ul li:nth-child(2) span').html(invoiceName);
	
	var invoiceContent = $("input[@name=invoiceContent][@checked]");
	var invoiceContentString = $('#invoiceContent'+invoiceContent.val()).html();
	$('#basicInvoiceInfo ul li:nth-child(3) span').html(invoiceContentString);
	closeDisplayType("InvoiceInfo");
}

var submitForm;
function createFrom(name) {
	submitForm = document.createElement('form');
	submitForm.setAttribute("method","post");
}

function appendElement(type,name,value) {
	var m = document.createElement('input'); 
	m.setAttribute('type', type);
	m.setAttribute('name', name);
	m.setAttribute('value', value);
  	submitForm.appendChild(m); 
}

function submitComment() {
	var comments = $('#comments').val();
	if(comments.length > 20){
		alert('订单备注限20个字符以内!');
		return;
	}
	if(comments.length > 0){
		$('#basicComments ul li:nth-child(1) span').html(comments);
	}
	closeDisplayType("Comments");
}

function pointsChange() {
	var rp = parseInt($('#rp').html());
	var pc = parseInt($('#points').val());
	var gtotal = parseFloat(moneyStr($('#gtotal').html()));
	var tprice = parseFloat($('#tprice').html());
	var t = gtotal+tprice-beans-pc;
	if(pc > rp) {
		formChecked = false;
		alert('使用返现点已超出您的当前返现点!');
		$('#points').val(0);
		return;
	} else {
		var beans = parseInt($('#beans').val());
		t = Math.ceil(gtotal+tprice)-(beans+pc);
		if(t<0) {
			formChecked = false;
			alert('抵扣额不能超过所需支付的订单总额!');
			$('#points').val(0);
			return;
		} 
		if((beans+pc) < (gtotal+tprice)) {
			t = (gtotal+tprice-beans-pc).toFixed(2);
		}
		$('#pcash').html(cc(pc+''));
		$('#total').html(cc(t+''));
	}
}

var formChecked = true;
function beansChange() {
	var rb = parseInt($('#rb').html());
	var beans = parseInt($('#beans').val());
	var gtotal = parseFloat(moneyStr($('#gtotal').html()));
	var tprice = parseFloat($('#tprice').html());
	var t = gtotal+tprice-beans-pc;
	if(beans > rb) {
		alert('使用欢乐豆已超出您的当前欢乐豆!');
		formChecked = false;
		$('#beans').val(0);
		return;
	} else {
		var pc = parseInt($('#points').val());
		t = Math.ceil(gtotal+tprice)-(beans+pc);
		if(t<0) {
			formChecked = false;
			alert('抵扣额不能超过所需支付的订单总额!');
			$('#beans').val(0);
			return false;
		} 
		if((beans+pc) < (gtotal+tprice)) {
			t = (gtotal+tprice-beans-pc).toFixed(2);
		}
		$('#bcash').html(cc(beans+''));
		$('#total').html(cc(t+''));
	}
}

function confirmOrder(){
	var ub = $('#beans').val();
	var up = $('#points').val();
	if(modifyBut) {alert('请完成修改的内容');return};
	submitForm = document.confirmForm;
	var addressId = getAddressId();
	if(!addressId) {
		alert('请选择收货地址!');
		return;
	}
	if (ub != 0 || up != 0) {
		if(!checkBeans(ub,up)) {
			return;
		}
	}
	appendElement('hidden','addressId',addressId);
	submitForm.submit();
}

function checkBeans(ub,up) {
	var result = true;
	$.ajax({
	   type: "POST",
	   url: ajax_check_beans,
	   cache: false,
	   async: false,
	   data: "t="+Math.random()+"&useBeans="+ub+"&usePoints="+up,
	   success: function(res){
	     if(res != '') {
				alert('您订单在抵扣时发现余额不足，点击确定后将为您重新获取数据。');
				var a = res.split('#');
				$('#rb').html(a[0]);
				$('#ub').html(a[0]);
				$('#mb').html(a[0]);
				$('#rp').html(a[1]);
				$('#up').html(a[1]);
				$('#mp').html(a[1]);
				result = false;
			}}
	 });
	return result;
}

function orderPay(code,obj){
	obj.disabled = 'disabled';
	$.get(pay_tip,{'t':new Date()},function(res){
			spanUI.html(res);
			blockUI(spanUI);
		});
	submitForm = null;
	createFrom();
	submitForm.setAttribute('action',ajax_order_pay);
	submitForm.setAttribute('target','_blank');
	appendElement('hidden','ordercode',code);
	appendElement('hidden','payType','alipay');
	document.body.appendChild(submitForm);
	submitForm.submit();
}
var arrayCoupon = new Array();
var useCoupon = new HashMap();
function showCoupon(uid,id,name,amount,totalCount) {
	var flag = uid.replace(id, "");
	var coupon = totalCount.split('_')[0];
	var count = totalCount.split('_')[1];
	
	if(flag == 'unused') {
		if(useCoupon.containsKey(coupon)) {
			if(useCoupon.get(coupon) == count) {
				alert('没有找到可供抵用的商品（每件商品只能使用一张抵用券）');
				return;
			}
			useCoupon.put(coupon,useCoupon.get(coupon)+1);
		} else {
			useCoupon.put(coupon,1);
		}
	} else {
		useCoupon.put(coupon,useCoupon.get(coupon)-1);
	}
	var newId = flag == 'unused' ? 'used' : 'unused';
	var ht = "<div class='cart_161' id='${newId}${id}'><div class='cart_162'>${couponName}</div>"
			+ "<div class='cart_163'><span class='yelo'>${amount}元</span></div>" +
					"<div class='cart_75'><label><input type='button' " +
					'onclick=\'showCoupon(\"${newId}${id}\",\"${id}\",\"${couponName}\",\"${amount}\",\"${totalCount}\")\' ' + 
					"class='dyq_butt01' onmouseover='this.className= \"dyq_butt01b\"' " +
					"onmouseout='this.className= \"dyq_butt01\"' name='Submit2' " +
					'value=\'{if newId == \'unused\'}使用{else}不使用{/if}\'/></label></div></div>';
	
	ht = ht.process({'newId':newId,'id':id,'couponName':name,'amount':amount,'totalCount':totalCount});
	
	$("#"+uid).remove();
	if($("#used").children().size() == 0) {
		if($("#nouset").is(':visible')){
			$("#nouset").hide();
		} else {
			$("#nouset").show();
		}
	}
	if($("#unused").children().size() == 0) {
		if($("#uset").is(':visible')){
			$("#uset").hide();
		} else {
			$("#uset").show();
		}
	}
	$("#"+newId).append(ht); 
	var usedCount = $('#usedCoupon').html();
	var leftCoupon = $('#leftCoupon').html();
	if(flag == 'unused') {	//used
		$('#usedCoupon').html(parseInt(usedCount)+1+"");
		var aa = parseInt(leftCoupon)-1;
		$('#leftCoupon').html(aa+"");
		$('#u1').html(parseInt($('#u1').html())+1+"");
		$('#u3').html(parseInt($('#u3').html())-1+"");
		$('#u2').html(parseInt($('#u2').html())+parseInt(amount)+"");
		arrayCoupon.push(id);
	} else {
		var aa = parseInt(usedCount)-1;
		$('#usedCoupon').html(aa+"");
		$('#leftCoupon').html(parseInt(leftCoupon)+1+"");
		$('#u1').html(parseInt($('#u1').html())-1+"");
		$('#u3').html(parseInt($('#u3').html())+1+"");
		$('#u2').html(parseInt($('#u2').html())-amount+"");
		arrayCoupon.pop(id);
	}
	$('#deductCouponAmount').html('-'+cc($('#u2').html()));
	$('#couponIds').val(arrayCoupon.join(','));
	
	var gtotal = parseFloat(moneyStr($('#gtotal').html()));
	var tprice = parseFloat($('#tprice').html());
	var pc = $('#pc').val();
	$('#total').html(cc(gtotal+tprice-pc/100-moneyStr($('#u2').html())+''));
}

function downCoupon() {
	if($('#arraw').attr('src').indexOf('dyq_01.') != -1) {
		$('.cart_158').slideDown();
		g('arraw').setAttribute('src',context+'/images/dyq_01_b.gif');
	} else {
		$('.cart_158').slideUp();
		g('arraw').setAttribute('src',context+'/images/dyq_01.gif');
	}
}