$(document).ready(function(){
    
    $('[@name=shipAddr]').click(function(){
        var addrID = $(this).val();
        var no=$(this).attr("no");
        if(addrID != 0){
            $('#saveaddr').hide();$('#isSaveAddr').attr('checked','');
            if(json.Addr.length > 0){
                var n = json.Addr[no];
                $('#txtRName').val(n.ReceiverName);
                $('#txtRPhone').val(n.ReceiverPhone);
                $('#txtRPostalcode').val(n.ReceiverZip);
                $('#ddlTopAreas').val(n.AddressID.split(',')[0]).change();
                if($('#ddlSubAreas').length > 0){
                    $('#ddlSubAreas').val(n.AddressID.split(',')[1]).change();
                    $('#ddlThirdAreas').val(n.AddressID.split(',')[2]).change();
                };
                
                var area = n.ReceiverAddress.replace($('#ddlTopAreas option[@selected]').text(),'').replace($('#ddlSubAreas option[@selected]').text(),'').replace($('#ddlThirdAreas option[@selected]').text(),'');
                while(area.indexOf(',') == 0){
                    area = area.replace(',','');
                };
                $('#txtRAddress').val(area);
                
                $('#txtRName').change(function(){CheckSave();});
                $('#txtRPhone').change(function(){CheckSave();});
                $('#txtRAddress').change(function(){CheckSave();});
                $('#txtRPostalcode').change(function(){CheckSave();});
                $('#ddlTopAreas').change(function(){CheckSave();});
                $('#ddlSubAreas').change(function(){CheckSave();});
                $('#ddlThirdAreas').change(function(){CheckSave();});
            }else{
                $('#txtRName').val('');
                $('#txtRPhone').val('');
                $('#txtRAddress').val('');
                $('#txtRPostalcode').val('');
                $('#ddlTopAreas').val('0').change();
            };
        }else{
            CheckSave();
            $('#txtRName').val('');
            $('#txtRPhone').val('');
            $('#txtRAddress').val('');
            $('#txtRPostalcode').val('');
            $('#ddlTopAreas').val('0').change();
            setPriceInfo();
        };
    });//end click
    $('[@name=shipAddr]').eq(0).attr('checked','checked').click();//默认选择收货地址中的第一项

	//预付款
	if(Number(memberAdvance) > 0){
	    $('#frmAdvance').show();
	};
	$('#cbAdvPay').click(function(){
	    setPriceInfo();
	});
    //选择从自提点取货
    $('input[@name=rbPayType][@value=6]').click(function(){
        if(!CheckReceivAddr()){return false};
        GetZtds($('#ddlTopAreas').val());
        $('#ztdContainer').show();
        $('.shipContainer').hide();
        
        setZtdVisible();
    });
    $('input[@name=rbPayType][@value!=6]').click(function(){
        if(!CheckReceivAddr()){return false};
        ClearZtds();
        $('#ztdContainer').hide();
        
        var areaID = GetAreaID();
        if(areaID == 0){return false;};
        if($(this).val()==5){
            GetShippings(areaID,true);//该地区仅支付货到付款的配送方式
        }else{
            GetShippings(areaID,false);//该地区所有配送方式
        }
    });
    
    
    $('#ddlDate').change(function(){
        if($(this).val() == '3'){
            $('#specal_day').show();
        }else{
            $('#specal_day').hide();
        };
    });
    
    $('#txt_Date').click(function(){$('#picktime').click();});
    
    //发票
    $('#chkInvoice').click(function(){
        if($(this).attr('checked')){
            $('#invoice').show();
            $('#rbtnInvoiceTypeGeneral').click();
        }else{
            $('#invoice').hide();
            $('#taxPrice').text('0');
        };

        setPriceInfo();
        $(this).blur();
    });
    //普通发票税金
    $('#rbtnInvoiceTypeGeneral').click(function(){
        $('#taxPrice').text(Number($('#total').text()*taxRateGeneral).toFixed(2));
        setPriceInfo();
    });
    //增值税发票税金
    $('#rbtnInvoiceTypeVAT').click(function(){
        $('#taxPrice').text(Number($('#total').text()*taxRateVAT).toFixed(2));
        setPriceInfo();
    });
	
	$('#rbtnInvoiceHeadCompany').click(function(){
		$('#txtCompanyName').show();
	});
	$('#rbtnInvoiceHeadPerson').click(function(){
		$('#txtCompanyName').hide();
	});
	$('#rbtnInvoiceContentOther').click(function(){
		$('#txtInvoiceContent').show();
	});
	$('#rbtnInvoiceContentDetails').click(function(){
		$('#txtInvoiceContent').hide();
	});
	
	$('input[@id^=rblCoupons_]').click(function(){
		if($(this).val() != '0'){
			$('#txtCoupons').val($(this).val());
			$('#btnCoupons').click();
			$('#txtCoupons').val('');
			if(!$('#rblCoupons_0').attr('checked')){
			    $('#coupons').hide();
			}
		}else{
			$('#cancelCoupons').click();
			$('#coupons').show();
		}
	});
	
    //保存按扭
    $('#pleaseWaitButtonDiv_PleaseWaitButton1').show();
    $('#btnSave').click(function(){
        if(!CheckReceivAddr()){return false};
        if(!CheckPayment()){alert('请选择支付类型');return false;};
        if(!CheckShipping()){return false;};
        $('#pleaseWaitButtonDiv_PleaseWaitButton1').hide();
        $('#pleaseWaitButtonDiv2_PleaseWaitButton1').html('Ordering...');
    });
    
	//--刚进入页面的时候需要判断此购物车有没有使用优惠券，如果有的话，嘿嘿，需要显示出来哦
	start();
	//--添加优惠券
	$('#btnCoupons').click(function(){
		if($.trim($('#txtCoupons').val()) == '') {return false;}
		$.ajax({
			type:"get",
			url:'ajax.aspx?NoCopyRight=1',
			data:'Type=CheckCoupons&CouponsCode=' + $.trim($('#txtCoupons').val()) + '&TotalPrice=' + $('#total').text() + '&ran=' + Math.random(),
			cache:false,
			async:false,
			success:function(msg){
				switch(msg)
				{
					case '^0':
						alert('您还没有登录！');
						$('#rblCoupons_0').attr('checked',true);
						break;
					case '^1':
						alert('此优惠券号码无效！');
						break;
					case '^2':
						alert('此优惠券号码已被使用！');
						break;
					case '^3':
						alert('此优惠券号码不在使用有效期内！');
						break;
					case '^4':
						alert('此优惠券号不符合使用条件！');
						$('#rblCoupons_0').attr('checked',true);
						break;
					case '^5':
						alert('您所属的会员组不能使用此优惠券！');
						$('#rblCoupons_0').attr('checked',true);
						break;
					case '^6':
						alert('有促销活动期间不允许使用优惠券！');
						$('#txtCoupons').val('');
						$('#rblCoupons_0').attr('checked',true);
						break;
					case '^7':
						alert('购物车内不包含使用此优惠券可以打折的商品！');
						$('#txtCoupons').val('');
						$('#rblCoupons_0').attr('checked',true);
						break;
					default:
						var msgs = msg.split('^');
						//location.href = 'ajax.aspx?NoCopyRight=1&' + 'Type=AddShoppingCartCoupons&Add=1&CouponsCode=' + $.trim($('#txtCoupons').val()) + '&CartID=' + cartID + '&PromotionType=' + msgs[1] + '&Discount=' + msgs[2] + '&CouponsID=' + msgs[3] + '&PromotionID=' + msgs[4] + '&ran=' + Math.random();
						$.ajax({
							type:"get",
							url:'ajax.aspx?NoCopyRight=1',
							data:'Type=AddShoppingCartCoupons&Add=1&CouponsCode=' + $.trim($('#txtCoupons').val()) + '&CartID=' + cartID + '&PromotionType=' + msgs[1] + '&Discount=' + msgs[2] + '&CouponsID=' + msgs[3] + '&PromotionID=' + msgs[4] + '&ran=' + Math.random(),
							cache:false,
							async:false,
							success:function(msg){
								$('#favourable').html(msg.split('^')[0]);
								$('#total').text(msg.split('^')[2]);
								$('#usedCoupons').text($.trim($('#txtCoupons').val()));
								//重新绑定商品信息
								GetShoppingCart();
							},
							error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('输入错误！')};}
						});
						
						$('#txtCoupons').hide();
						$('#btnCoupons').hide();
						$('#spanCoupons').show();
						$('#cancelCoupons').show().unbind().click(function(){
							$.ajax({
								type:"get",
								url:'ajax.aspx?NoCopyRight=1',
								data:'Type=AddShoppingCartCoupons&Add=-1&CartID=' + cartID + '&ran=' + Math.random(),
								cache:false,
								success:function(msg){
									$('#favourable').html(msg.split('^')[0]);
									$('#total').text(msg.split('^')[2]);
									$('#usedCoupons').text($.trim($('#txtCoupons').val()));
								    //重新绑定商品信息
								    GetShoppingCart();
								},
								error:function(){alert('输入错误！')}
							});
							$('#txtCoupons').show();
							$('#btnCoupons').show();
							$('#spanCoupons').hide();
						});
						break;
				}
			},
			error:function(){alert('输入错误3！')}
		});
		
	});
	
	$("#ddlTopAreas").change(function(){
	    var topoption = $('option[@selected]',this);
	    if(topoption.attr('child') == "false"){
	        //没有二级地区,获取一级地区的配送方式
            $('[@name=Shipping]').eq(0).data('isHdfk','2');
            GetShippings($('#ddlTopAreas').val(),false);
            setPriceInfo();
	    };
	    //是否显示自提点选项
        showZtd(topoption.attr('ztd'));
        //是否显示货到付款选项
        if(topoption.attr('hdfk') > 0){$('tr.paytype_5').show();}else{$('tr.paytype_5').hide();$('input[@name=rbPayType][@value=5]').removeAttr('checked');}    
	});
	
	$("#ddlSubAreas").change(function(){
	    var suboption = $('option[@selected]',this);
	    if(suboption.attr('child') == "false"){
	        //没有三级地区,获取二级地区的配送方式
            $('[@name=Shipping]').eq(0).data('isHdfk','2')
            GetShippings($('#ddlSubAreas').val(),false);
            setPriceInfo();
	    };
	    showZtd(suboption.attr('ztd'));
        //二级地区货到付款
        if(suboption.attr('hdfk') > 0){$('tr.paytype_5').show();}else{$('tr.paytype_5').hide();};
        $('input[@name=rbPayType][@value=5]').removeAttr('checked');
	});
	
	$('#ddlThirdAreas').change(function(){
	    alert($(this).val());
	    var thirdoption = $('option[@selected]',this);
        //三级地区自提点
        if(thirdoption.attr('ztd') > 0){$('tr.paytype_6').show();};
        $('input[@name=rbPayType][@value=6]').removeAttr('checked');
        $('#ztdContainer').hide();
        //三级地区货到付款
        if(thirdoption.attr('hdfk') > 0){$('tr.paytype_5').show();}else{$('tr.paytype_5').hide();};
        $('input[@name=rbPayType][@value=5]').removeAttr('checked');
        $('[@name=Shipping]').eq(0).data('isHdfk','2');
        GetShippings($('#ddlThirdAreas').val(),false);
        setPriceInfo();
    });
	
})  //$(document).ready 结束


//获取子地区
function GetSubArea(areaID){
    var options = null
    var login = true;
    $.ajax({
        url:'Order.aspx?NoCopyRight=1&type=ajax&Action=GetSubArea&AreaID='+areaID,
        type:'get',
        async:false,
        success:function(data){
            if(!checkLoginStatus(data)){login=false;return false;};
            options = data;
        },
        error:function(){alert('error');}
    });
    if(!login){return false};
    return options;
};

//获取自提点
function GetZtds(areaID){
    ClearZtds();
    $.ajax({
        url:'Order.aspx?NoCopyRight=1&type=ajax&Action=GetZtds&AreaID='+areaID,
        type:'get',
        dataType:'json',
        async:false,
        cache:false,
        success:function(msg){
            var data = msg.Ztd;
            $.each(data,function(i,n){
                var row = $('#tmp_ztd').clone().show();
                row.find('.ztdname').html('<input type="radio" id="rbZtd_' + i + '" name="rbZtd" value="' + n.ZtdNo + '" /><label for="rbZtd_' + i + '">' + n.ZtdName + '</label>');
                row.find('.ztdAddr').html(n.Address);
                row.find('.ztdRemark').html(n.Remark);
                row.attr('id','row_ztd_'+i).attr('ztd_areaID',n.AreaID).appendTo($('#ztdContainer tbody'));//id以row_ztd_开头,名为ztd_areaID的属性,在选择子地区显示隐藏对应的自提点时要用到
            });//end each
        },
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });
};

//显示隐藏自提点容器
function showZtd(ztdNum){
    if(ztdNum > 0){$('tr.paytype_6').show();}else{$('tr.paytype_6').hide();$('#ztdContainer').hide();}
    $('input[@name=rbPayType][@value=6]').removeAttr('checked');
};

//显示隐藏自提点
function setZtdVisible(){
    if($('#ddlThirdAreas')[0]){
        if($('#ddlThirdAreas option[@selected]').attr('ztd') > 0){
            $('[@ztd_areaID]').hide();
            $('[@ztd_areaID^=' +$('#ddlThirdAreas').val()+ ']').show();
        }else if($('#ddlSubAreas option[@selected]').attr('ztd') > 0){
            $('[@ztd_areaID]').hide();
            $('[@ztd_areaID^=' +$('#ddlSubAreas').val()+ ']').show();
        };
    }else if($('#ddlSubAreas')[0]){
        if($('#ddlSubAreas option[@selected]').attr('ztd') > 0){
            $('[@ztd_areaID]').hide();
            $('[@ztd_areaID^=' +$('#ddlSubAreas').val()+ ']').show();
        };
    };
};


//清除自提点
function ClearZtds(){$('#tmp_ztd').nextAll().remove();};

//根据地区获取配送方式
function GetShippings(areaID,isHdfk){
return;
    $('.shipContainer').show();
    if($('[@name=Shipping]')[0]){
        if($('[@name=Shipping]').eq(0).data('isHdfk') == (isHdfk ? "1" : "0")){
            return false;//不用读取
        };
    }else{
        $('[@name=Shipping]').eq(0).data('isHdfk','0');
    };
    var areaIDForPrice = 0;
    if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() != 0){
        areaIDForPrice = $('#ddlSubAreas').val();
    }else{
        areaIDForPrice = $('#ddlTopAreas').val();
    };

    $.ajax({
        url:'Order.aspx?NoCopyRight=1&type=ajax&Action=GetShipps&ShipType=' + (isHdfk ? '1' : '0') + '&AreaID=' + areaID + '&AreaIDForPrice=' + areaIDForPrice,
        type:'get',
        dataType:'json',
        cache:false,
        success:function(msg){
            $('#tmp_ship').nextAll().remove();
            var data = msg.Shippings;
            $.each(data,function(i,n){
                var row = $('#tmp_ship').clone().show();
                row.find('.shipname').html('<input type="radio" id="ship_' + i + '" name="Shipping" value="' + n.ShippingID + '" price="' + n.Price + '" /><label for="ship_' + i + '">' + n.Name + '</label>');
                row.find('.shipprice').html(n.Price);
                row.find('.shipdetail').html(n.Description);
                row.find('[@name=Shipping]').click(function(){
                    if(!CheckPayment()){alert('请先选择支付类型');return false;};
                    setPriceInfo();
                });
                row.attr('id','row_ship_'+i).appendTo($('#shipContainer tbody'));
            });
            $('[@name=Shipping]').eq(0).data('isHdfk',(isHdfk ? '1' : '0'));//记录当前读取的是所有配送方式还是仅支持货到付款的配送方式
            
        },
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert(textStatus)};}
    });
};

function CheckSave(){$('#saveaddr').show();$('#isSaveAddr').attr('checked','checked');};//显示是否保存地址的选项
//获取选择的最后一级地区ID
function GetAreaID(){
    var areaID = 0;
    if($('#ddlThirdAreas')[0] && $('#ddlThirdAreas').val() != 0){
        areaID = $('#ddlThirdAreas').val();
    }else if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() != 0){
        areaID = $('#ddlSubAreas').val();
    }else{
        areaID = $('#ddlTopAreas').val();
    }
    return areaID;
};

//判断是否选择了完整的地区
function CheckFullAddr(){
    if($('#ddlThirdAreas')[0] && $('#ddlThirdAreas').val() == 0){
        return false;
    }else if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() == 0){
        return false;
    }else if($('#ddlTopAreas').val() == 0){
        return false;
    }else{
        return true;
    };
};

//判断收货地址是否填写完整
function CheckReceivAddr(){
    if($.trim($('#txtRName').val())==''){alert('请填写收货人姓名!');return false;};
    if(!CheckFullAddr()){alert('请选择完整的地区');return false;};
    if($.trim($('#txtRAddress').val())==''){alert('请填写收货人详细地址!');return false;};
    if($.trim($('#txtRPostalcode').val())==''){alert('请填写收货人邮政编码!');return false;};
    return true;
};

//判断是否选择了支付类型
function CheckPayment(){
    if($('[@name=rbPayType][@checked]').length==0){return false;};
    return true;
};
//检查配送信息
function CheckShipping(){
    if($('input[@name=rbPayType][@checked]').val() == 6){
        if($('[@name=rbZtd][@checked]').length == 0){alert('请选择自提点!');return false};//如果选择了到自提点提货,判断是否选择了自提点
    }else{
        if($('[@name=Shipping][@checked]').length == 0){alert('请选择配送方式');return false};//如果没有选择从自提点取货,判断是否选择了送货方式
    };
    return true;
};

function setAdvancePrice(){
    if($('#cbAdvPay').attr('checked')){
        var tmpTotal = Number($('#total').text()) + Number($('#taxPrice').text()) + Number($('#shipPrice').text()) - Number(usdScore)*scoreRate;
        $.ajax({
            url:'Order.aspx?NoCopyRight=1&type=ajax&Action=GetAdvancePayment',
            type:'get',
            cache:false,
            async:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;};
                $('#advMoney').text(Number(data).toFixed(2));
                if(data >= tmpTotal){
                    $('#advPrice').text(Number(tmpTotal).toFixed(2));
                }else{
                    $('#advPrice').text(Number(data).toFixed(2));
                };
            },
            error:function(){alert('error');}
        });
    }else{
        $('#advPrice').text('0');
    };
};

function GetShoppingCart(){
    $.ajax({
	    url:'Order.aspx?NoCopyRight=1&type=ajax&Action=GetShoppingCart',
	    type:'get',
	    dataType:'json',
	    cache:false,
	    async:false,
	    success:function(data){
	        $('#tmp_cart').nextAll().remove();
	        $.each(data.Cart,function(i,n){
	            var row = $('#tmp_cart').clone().show();
	            row.find('._productno').text(n.ProductNo);
	            row.find('._productname').html('<a href="/' + shopFolder + 'products/product-' + n.ProductID + '.' + extend + '" target=_blank>' + n.ProductName + '</a>');
	            row.find('._productspecs').html(n.ProductSpecs);
	            row.find('._price').text(currencySign+n.MemberPrice);
	            row.find('._num').text(n.Quantity);
	            row.find('._score').text(n.Score);
	            row.find('._usedscore').text(n.UsedScore);
	            row.appendTo($('#cart_product'));
	        });
	    },
	    error:function(){alert('error');}
	});
//	setAdvancePrice();
	setPriceInfo();//重新设置费用信息
};

function setPriceInfo(){
    var shipPrice = 0;
    if($('[@name=Shipping][@checked]').attr('price')){
        shipPrice = $('[@name=Shipping][@checked]').attr('price');
    };
    $('#shipPrice').text(shipPrice);
    $('#freeTip').hide();
    if(shipFreeType==0){//不开通免运费
        $('#shipPrice').text(shipPrice);
    }else if(shipFreeType==1){//全国统一最低金额
        if($('#total').text() >= leastMoney){
            $('#shipPrice').text('0');
            $('#freeTip').show();
        };
    }else{//按地区设置最低金额
        var arealeast = 0;
        if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() != 0){
            arealeast = $('#ddlSubAreas option[@selected]').attr('freeleast') ? $('#ddlSubAreas option[@selected]').attr('freeleast') : 0;
        }else{
            arealeast = $('#ddlTopAreas option[@selected]').attr('freeleast') ? $('#ddlTopAreas option[@selected]').attr('freeleast') : 0;
        };
        if(Number($('#total').text()) >= Number(arealeast)){
            $('#shipPrice').text('0');
            $('#freeTip').show();
        };
    };
    
    setAdvancePrice();
    
    $('#ptotalPrice').text($('#originaltotal').text());
    $('#couponPrice').text(Number($('#originaltotal').text() - $('#total').text()).toFixed(2));
    $('#ScoreAmount').text(Number(usdScore)*scoreRate);
    var lefttotal = Number($('#ptotalPrice').text()) + Number($('#shipPrice').text()) + Number($('#taxPrice').text()) - Number($('#advPrice').text()) - Number($('#couponPrice').text()) - Number($('#ScoreAmount').text());
    $('#lefttotal').text(Number(lefttotal).toFixed(2));
};


function start()
{
	if(couponsCode != '')
	{
		$('#txtCoupons').hide();
		$('#btnCoupons').hide();
		$('#spanCoupons').show();
		$('#cancelCoupons').show().click(function(){
			$.ajax({
				type:"get",
				url:'ajax.aspx?NoCopyRight=1',
				data:'Type=AddShoppingCartCoupons&Add=-1&CartID=' + cartID + '&ran=' + Math.random(),
				cache:false,
				success:function(msg){
					$('#favourable').html(msg.split('^')[0]);
					$('#total').text(msg.split('^')[2]);
					$('#usedCoupons').text($.trim($('#txtCoupons').val()));
				},
				error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('输入错误！')};}
			});
			$('#txtCoupons').show();
			$('#btnCoupons').show();
			$('#spanCoupons').hide();
			$('#rblCoupons_0').attr('checked',true);			
		});
		$('#usedCoupons').text(couponsCode);
		
		$('input[@id^=rblCoupons_]').each(function(i){
			if($(this).val() == couponsCode)
			{
				$(this).attr('checked',true);
				$('#txtCoupons').val('');
				$('#txtCoupons').show();
				$('#btnCoupons').show();
				$('#spanCoupons').hide();
				$('#coupons').hide();
			}
		});
	}
	
}

function checkLoginStatus(data){
    var result = true;
    if(data.indexOf('<!DOCTYPE') != -1){
        result = false;
        alert('身份已过期,请重新登陆!');
    };
    return result;
};