
$(document).ready(function(){
    var selectedReceiverAddr = ''; //全局变量,在GetAddress()中赋值,在BindShippings()中使用
    var areaID = 0;//全局变量,在GetAddress()中赋值,在BindShippings()中使用
    var isModify = false;   //全局变量,记录是否为修改状态
    var strHr = "<hr noshade color='#cccccc' size='1' style='border-style: dotted; border-width: 1' width='100%'>";
    
    $('#ddlSubAreas option[@value=0]').text(strSelectArea);     //var strSelectArea = '<%=GetResourceString("SelectArea")%>';
    $('#ddlThirdAreas option[@value=0]').text(strSelectArea);
    $('input[@name=btnSelectShipping]').val(strShippingToThisAddress);
    $('#btnAddAddress').val(strShippingToThisAddress);
    $('input[@type=button][@id*=_next_]').val(strNext)
    
    var isCoupon = false;
    if($('input[@name=rblCoupon]').length != 0 && iscoupons == 'true'){
        isCoupon = true;    //可以使用优惠券
    }else{
        $('#S_Coupon').hide(); // 隐藏导航li
        $('#mCoupon').hide();   //隐藏显示信息
    }
    
    //useShippingTime, 后台Response.Write()
    if(useShippingTime == ''){
        $('#sShippintTime').hide();
        $('#mShippingTime').hide();
    }
    else
	{
		$('#shippingTime').show();
    }
    
    if(parseFloat(advancepayment) <= 0){
        $('#cbPayment').attr('disabled','disabled');
    }else{
        $('#cbPayment').attr('disabled','');
    };
    
    //隐藏所有
    function HideAll(){
	    $("#sInfo").hide();
        $("#addressList").hide();
	    $("#sAddress").hide();
	    $("#buyer").hide();
	    $('#shipping').hide();
	    $('#coupon').hide();
	    $('#payment').hide();
	    $('#remark').hide();
	    $('#btn_back_save').hide();
	    $('#btnSave').hide();
    }
    
    HideAll();
    $("#sInfo").hide();
    $("#addressList").show();
    $("#sAddress").show();
    
    if(username == 'anonymous'){
        $('#addressList').hide();
    }
    //如果地址簿里有地址,显示地址簿列表,否则隐藏
    if($('input[@name=btnSelectShipping]','#addressList').length != 0){$('#addressList').show();}else{$('#addressList').hide();}
    
    //显示最后一步
    function GoToConfirm(){
        HideAll();
	    $("#sInfo").show();
        $('#remark').show();
        $('#btn_back_save').show();
        $('#btnSave').show();
        
        $("#S_Confirm").addClass('current').siblings().removeClass('current');
    }
    
    //绑定地区的方法
    function BindAreas(obj1,obj2){
	    var svalue = obj1.value; 
	    var weburl = "ajax.aspx?NoCopyright=1&parent_id="+svalue + "&r=" + Math.random(); 
	    $.get(weburl,function(data){
		    document.getElementById(obj2).length = 0; 
		    document.getElementById(obj2).options.add(new Option(strSelectArea,"0")); 
		    if(data!=""){ 
			    var allArray = data.split("<")[0].toString().split(","); 
			    for(var i=1;i<allArray.length;i++){ 
				    var thisArray = allArray[i].split("|"); 
				    document.getElementById(obj2).options.add(new Option(thisArray[1].toString(),thisArray[0].toString())); 
			    } 
		    } 
	    });
	    
	    //根据选择的地区绑定相应的配送价格
	    var areaID = $('#ddlSubAreas').val() == '0' ? $('#ddlTopAreas').val() : $('#ddlSubAreas').val();
	    var url_getShippings = "ajax.aspx?NoCopyright=1&type=GetShippings&areaID=" + areaID + "&ran=" + Math.random();
	    $.get(url_getShippings,function(data){
	        $('#shippingsList').html(data);
	    })

    } //End BindAreas()
    
    //给地区下拉框绑定事件
    $('#ddlTopAreas').change(function(){$('#ddlSubAreas option:gt(0)').remove();$('#ddlThirdAreas option:gt(0)').remove();if($(this).val()!='0'){BindAreas(this,'ddlSubAreas')};});
    $('#ddlSubAreas').change(function(){$('#ddlThirdAreas option:gt(0)').remove();if($('option[selected]',this).val() != '0')(BindAreas(this,'ddlThirdAreas'));});
    
    //点击选择优惠券的事件
    $('input[@type=radio][@name=rblCoupon]').click(function(){
        var couponMemberID = $('input[@type=radio][@name=rblCoupon][@checked]').val();
        if(couponMemberID != "0"){
            var weburl = "ajax.aspx?NoCopyright=1&type=GetCouponAlert&CouponMemberID="+couponMemberID+"&ts="+Math.random(); 
            $.ajax({
                url:weburl,
                async:false,    //设置为同步
                success:function(data){
                    if(data == "NOLOGIN"){
                        alert(strPleaseLogin); return false;
                    }else if(data == "1"){
                        alert(checkout_js_1);
                    }
                },
                error:function(){
                    alert('error'); return false;
                }
            });  
        }
    });
  
    //给选择配送地址的按扭添加事件
    $('input[@name=btnSelectShipping]').each(function(){
        $(this).click(function(){
            var rAddressID = $(this).next().val();
            ShippingThisAddress(rAddressID);
        });
    })
    
    //选择地址
    function ShippingThisAddress(sid){
	    $("#said").val(sid);
	    GetAddress(sid);
        BindShippings();
        
        if(!isModify){
            HideAll();
            $('#buyer').show();
            $("#S_Buyer").addClass('current').siblings().removeClass('current');
        }else{
            HideAll();
            $('#shipping').show();
            $("#S_Shipping").addClass('current').siblings().removeClass('current');
            if(useShippingTime != ''){
                $('#shippingTime').show();
            }
        };
        
        
    }
    
    //显示选择的配送地址
    function GetAddress(said){ 
        var weburl = "ajax.aspx?NoCopyright=1&type=GetAddress&said="+said+"&ts="+Math.random(); 
        $.ajax({
            url:weburl,
            async:false,    //设置为同步才能在BindShippings中获得selectedReceiverAddr的值
            success:function(data){
                var aResult = data.split("|");
                $('#sRName').html(aResult[0]);
                selectedReceiverAddr = aResult[1];  //给selectedReceiverAddr赋值,在BindShippings()中使用;
                var rArea = aResult[1].split(",")[0];
                if(aResult[1].split(",")[1] != ""){
                    rArea = rArea + "—" + aResult[1].split(",")[1];
                }
                if(aResult[1].split(",")[2] != ""){
                    rArea=rArea+"—"+aResult[1].split(",")[2];
                }
               
                $('#sRArea').html(rArea);
                $('#sRAddress').html(aResult[1].split(",")[3]);
                $('#sRZip').html(aResult[2]);
                $('#sRMobile').html(aResult[3] + ' ,  '+ aResult[4]);
                
                areaID = aResult[5].split(',')[1] != 0 ? aResult[5].split(',')[1] : aResult[5].split(',')[0] ;
                
                if(!isModify){
                    //如果不是修改,默认购买人信息与收货人信息相同
                    $('#txtBName').val($('#sRName').html());
                    $('#txtBAddress').val(rArea + ($('#sRAddress').html() != '' ? '—' + $('#sRAddress').html() : ''));
                    $('#txtBPostalcode').val($('#sRZip').html());
                    $('#txtBPhone').val($('#sRMobile').html());
                }
            },
            error:function(){
                alert('error'); return false;
            }
            
        })
         
    }   //End GetAddress();
    
    //根据选择的配送地址绑定相应的配送费用
    function BindShippings(){
        var url_getShippings = "ajax.aspx?NoCopyright=1&type=GetShippings&areaID=" + areaID + "&ran=" + Math.random();
	    $.get(url_getShippings,function(data){
	        $('#shippingsList').html(data);
	    })     
        
    }   //End BindShippings();
    
    //添加新配送地址的按扭事件
    $('#btnAddAddress').click(function(){
		var url = "ajax.aspx?NoCopyright=1&type=GetMemmberMaxAddressCount&ran=" + Math.random();
		var pass = false;
		var isLogin = true;
		$.ajax({
			url:url,
			async:false,
			success:function(data){
				if(data == 'NOLOGIN'){isLogin = false;}else{pass = data;}
			}
		});
		
		if(!isLogin){
			alert(strPleaseLogin);return false;
		}
		
		//如果用户的地址簿数量已经达到系统设置的最大上限,则不能再添加地址
		if(pass == 'false'){
			alert(strNewAddressAlert);return false;
		}
		
		if($('#ddlTopAreas').val() == '0'){
		    alert(strSelectArea); return false;
		}
		
        if($("#txtRName").val()==""){
		    alert(strCheckOut_Alert1);return false;
	    }
	    if($('#txtREmail').val()==""){
	        alert(strCheckOut_Alert1);return false;
	    }
	    if($("#txtRAddress").val()==""){
		    alert(strCheckOut_Alert1);return false;
	    }
	    if($("#txtRMobile").val()==""){
		    alert(strCheckOut_Alert1); return false;
	    }
   
	    $('#sRName').html($('#txtRName').val());
	    var rArea = $('#ddlTopAreas option[@selected]').text();
	    if($('#ddlSubAreas').val() != '0'){
	        rArea += "—" + $('#ddlSubAreas option[@selected]').text();
	    }
	    if($('#ddlThirdAreas').val() != '0'){
	        rArea += "—" + $('#ddlThirdAreas option[@selected]').text();
	    }
	    
	    $("#said").val('');
	    
	    $('#sRArea').html(rArea);
	    $('#sRAddress').html($('#txtRAddress').val());
	    $('#sRZip').html($('#txtRPostalcode').val());
	    $('#sRMobile').html($('#txtRMobile').val());
	    
        if(!isModify){
	        //默认购买人信息与收货人信息相同
            $('#txtBName').val($('#sRName').html());
            $('#txtBAddress').val(rArea + ($('#sRAddress').html() != '' ? '—' + $('#sRAddress').html() : ''));
            $('#txtBPostalcode').val($('#sRZip').html());
            $('#txtBPhone').val($('#sRMobile').html());
            $('#txtBEmail').val($('#txtREmail').val());
	        
	        HideAll();
            $('#buyer').show();
            $("#S_Buyer").addClass('current').siblings().removeClass('current');
            
            if(useShippingTime != '')
            {
                $('#shippingTime').show();
            }
	    }else{
	        HideAll();
            $('#shipping').show();
            $('#hr_buyer').html(strHr);
            $("#S_Shipping").addClass('current').siblings().removeClass('current');
	    }
    });
    
     //选择配送方式时的下一步按扭事件
    $('#btn_next_shipping').click(function(){
        if($('input[@type=radio][@name=rblShipping][@checked]').length == 0){
            alert(strSelectShippingWay); return false;
        }else{
            var shippingID = $('input[@name=rblShipping][@checked]').val();
            var url_getShippingName = 'ajax.aspx?NoCopyright=1&type=GetShippingName&ShippingID=' + shippingID + '&ran=' + Math.random();
            $.ajax({
                url:url_getShippingName,
                async:false,
                success:function(data){
                    $('#sSType').html(strShippingWay + '：'+data);
                }
            });
            if(useShippingTime != ''){return SelectShippingtime();}
            
            if(!isModify){
                HideAll();
                $('#h1').html(strHr);
//                if(!useShippingTime)    //不使用送货时间
//                {
                    //如果有优惠券,则显示优惠券
                    if(isCoupon)
                    {
                        $('#coupon').show();
                        $("#S_Coupon").addClass('current').siblings().removeClass('current');
                    }
                    else
                    {
                        //没有优惠券,显示支付方式
                        $('#payment').show();
                        $("#S_Payment").addClass('current').siblings().removeClass('current');
                    }
//                }
//                else
//                {
//                   $('#shippingTime').show();
//                   $("#S_ShippingTime").addClass('current').siblings().removeClass('current');
//                }
            }else{
                GoToConfirm();
            }
        }
    });
        
    function SelectShippingtime(){
        var shippingTime = new Date();
        if(useShippingTime == '0'){
            shippingTime = $('#txt_Date').val();
        }
        else if(useShippingTime == '1'){
            if($('#ddlHours').val() == '24' || $('#ddlHours1').val() == '24'){
                alert(strSelectTime); return false;
            }
            
            //开始时间
            var startTime =$('#txt_Date').val() + ',' + $('#ddlHours option[@selected]').text();
            startTime = startTime.replace(' ',',').replace('-',',').replace('-',',').replace(':',',');
            var sTimes = startTime.split(',');
            var sYear = sTimes[0];
            var sMonth = sTimes[1] - 1;
            var sDay = sTimes[2];
            var sHour = sTimes[3];
            var sMinutes = sTimes[4];
            startTime = new Date(sYear,sMonth,sDay,sHour,sMinutes);
            
            //结束时间
            var endTime =$('#txt_Date').val() + ',' + $('#ddlHours1 option[@selected]').text();
            endTime = endTime.replace(' ',',').replace('-',',').replace('-',',').replace(':',',');
            var eTimes = endTime.split(',');
            var eYear = eTimes[0];
            var eMonth = eTimes[1] - 1;
            var eDay = eTimes[2];
            var eHour = eTimes[3];
            var eMinutes = eTimes[4];
            endTime = new Date(eYear,eMonth,eDay,eHour,eMinutes);
            
            if(startTime < new Date()){
                alert(strTimeError);
                $('#ddlHours')[0].focus(); return false;
            }

            if(startTime.getHours() >= endTime.getHours()){
                alert(startTime.getHours()); return false;
            }
            shippingTime = $('#txt_Date').val() + ',' + strTimeFrom + startTime.toLocaleTimeString() + strTimeTo + endTime.toLocaleTimeString();
            
        } //else if 结束

        $('#sSType').html($('#sSType').html() + '  ' + strDeliverGoodsDate + '：' + shippingTime);
        
        if(!isModify){
            HideAll();
            $('#h4').html(strHr);
            
             //如果有优惠券,则显示优惠券
            if(isCoupon){
                $('#coupon').show();
                $("#S_Coupon").addClass('current').siblings().removeClass('current');
            }else{
                //没有优惠券,显示支付方式
                $('#payment').show();
                $("#S_Payment").addClass('current').siblings().removeClass('current');
            }
        }else{
            GoToConfirm();
        }
    }
    
    //选择配送时间后的下一步按扭
    $('#btn_next_shippingTime').click(function(){
        
    });
    
    //选择优惠券时的下一步按扭事件
    $('#btn_next_coupon').click(function(){
        var couponMemberID = $('input[@name=rblCoupon][@checked]').val();
        if($('input[@name=rblCoupon][@checked]').length == 0 || $('input[@name=rblCoupon][@checked]').val() == "0"){
			$('#sCoupon').html(strCoupon+'：'+checkout_js_2);
        }else{
			var url_getCouponName = 'ajax.aspx?NoCopyright=1&type=GetCouponName&CouponMemberID=' + couponMemberID + '&ran=' + Math.random();
			$.get(url_getCouponName,function(data){
				if(data != ''){
					$('#sCoupon').html(strCoupon + '：' + data);
				}else{
					$('#sCoupon').html(strCoupon+'：'+checkout_js_2);
				}
			})
        }
        if(!isModify){
            HideAll();
            $('#payment').show();
            $('#h2').html(strHr);
            $("#S_Payment").addClass('current').siblings().removeClass('current');
        }else{
            GoToConfirm();
        }
    });
    
    //选择支付方式时的按扭事件
    $('input[@name=rblPayment]').click(function(){
        var text = $(this).next().html();
        var endIndex = text.indexOf('<br>') != -1 ? text.indexOf('<br>') : text.indexOf('<BR>');    //在html中看到的是<br>,在firefox中识别的是<br>,但在IE中识别成<BR>;
        var paymentName = text.substr(0,endIndex);
        $('#sSPay').html(strPayment + '：' + paymentName);
        $('#h3').html(strHr);       
        
    });
    
    $('#btn_next_rblPayment').click(function(){
		if($('input[@type=radio][@name=rblPayment][@checked]').length == 0){
            alert(strSelectPayment);
            return false;
        }
        var text = $('input[@type=radio][@name=rblPayment][@checked]').next().html();
        var endIndex = text.indexOf('<br>') != -1 ? text.indexOf('<br>') : text.indexOf('<BR>');    //在html中看到的是<br>,在firefox中识别的是<br>,但在IE中识别成<BR>;
        var paymentName = text.substr(0,endIndex);
        $('#sSPay').html(strPayment + '：' + paymentName);
        $('#h3').html(strHr);
        isModify = true;
        GoToConfirm();
    });
    
    $('#btn_back_save').click(function(){
        HideAll();
        $('#payment').show();
    });
    
    //最后一步,点击提交订单
    $('#btnSave').click(function(){
        if($('input[@type=radio][@name=rblPayment][@checked]').length == 0){
            alert(strSelectPayment);return false;
        }
        
        $('#pleaseWaitButtonDiv_PleaseWaitButton1').hide();
        $('#pleaseWaitButtonDiv2_PleaseWaitButton1').html('Ordering...');
    });
    
    //点修改按扭返回对应的地方
    //修改收货人
    $('#mReceiver').click(function(){
        HideAll();
        $("#addressList").show();
        $("#sAddress").show();
        $("#S_Receiver").addClass('current').siblings().removeClass('current');
        isModify = true;
    });
    
    //修改购买人
    $('#mBuyer').click(function(){
        HideAll();
        $('#buyer').show();
        $("#S_Buyer").addClass('current').siblings().removeClass('current');
    });
    
    //修改送货方式
    $('#mShipping').click(function(){
        HideAll();
        $('#shipping').show();
        $("#S_Shipping").addClass('current').siblings().removeClass('current');
        if(useShippingTime != ''){
            $('#shippingTime').show();
        }
    });
    
    //修改送货时间
    $('#mShippingTime').click(function(){
        HideAll();
        $('#shippingTime').show();
        $("#S_ShippingTime").addClass('current').siblings().removeClass('current');
    });
    
    //修改优惠券
    $('#mCoupon').click(function(){
        HideAll();
        $('#coupon').show();
        $("#S_Coupon").addClass('current').siblings().removeClass('current');
    });
    
    //修改支付方式
    $('#mPay').click(function(){
        HideAll();
        $('#payment').show();
        $("#S_Payment").addClass('current').siblings().removeClass('current');
    }); 
    
    //输入购买人信息时的下一步按扭事件
    $('#btn_next_buyer').click(function(){
        $('#buyerTitle').html(strBuyerInfo);
        $('#bName').html(strBuyerName + '：' + $('#txtBName').val());
        $('#bAddress').html(BuyerAddress + '：' + $('#txtBAddress').val());
        $('#bEmail').html(BuyerEmail + '：' + $('#txtBEmail').val());
        $('#bPhone').html(BuyerTelephone + '：' + $('#txtBPhone').val());
        $('#bZip').html(BuyerPostalcode + '：' + $('#txtBPostalcode').val());
        
       if(!isModify){
           HideAll();
           $('#shipping').show();
           $('#hr_buyer').html(strHr);
           $("#S_Shipping").addClass('current').siblings().removeClass('current');
       }else{
           GoToConfirm();
       }
    });
    
})  //$(document).ready 结束