var PageSize = 15;//每页计数
var CurrentPage = 1; //当前页
var keyword = '';
var catID = '0';
var brandID = '0';
var searchType = '0';
var status = 0;//刚进入页面不要列出商品,点击"添加商品"后再获取列表
var showadv = 0;//高级搜索显示状态

var isSubmit = false;//点击提交按钮时将此变量设置为true;此时不执行$(window).unload()里的代码

var jsonPdtInfo = '';//添加商品时查询出的商品信息json数据
var Spec = '';
var SepcDesc = '';
var productID = '0';
var mid=-1;
var cartID;
var namePassed=true;

$(document).ready(function(){

    $('#loadingContainer').ajaxStart(function(){$(this).show();}).ajaxStop(function(){$(this).hide();});
	var isIE6 = ($.browser.msie && $.browser.version=='6.0');
	setInterval(function(){
        $('#sub_container').css('height',$(window.parent.frames.right).height()-$('div.sub_container_title').height()); //设置内容区域的高度
        if(isIE6){
            $('#datacontainer').css('height','300px');
        }else{
            $('#content').css('height',$('#popupContact').height()-$('#popupHead').height());
            $('#datacontainer').css('height',$('#content').height()-$('#sub_container_listhead').height()-$('#pageDataList1_Pager').height()-$('#divsave').height()-80);
        };
    },1000);
    
    //构造地区列表
    $('<option freeleast="0" hdfk="0" zdt="0" child="false" value="-1">请选择</option>').appendTo($('#ddlTopAreas'));
	for(var n=0;n<data.length/4;n++){
		$('<option freeleast="'+data[n*4][2]+'" hdfk="'+data[n*4][3]+'" ztd="'+data[n*4][4]+'" child="'+data[n*4][5]+'" value="'+data[n*4][1]+'">'+data[n*4][0].replace("->","")+'</option>').appendTo($('#ddlTopAreas'))
	}//end for
  
    //购物车商品列表，各个事件
    $('input[@name=quantity]').livequery('keydown',function(event){
	    var curobj = $(this);
	    curobj.attr('oldvalue',curobj.val());
	    if((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 8){
	    }else{return false;}
	}).livequery('keyup',function(event){
	    var curobj = $(this);
	    var min = $(this).siblings('[@name=min]').val();
	    if(curobj.attr('oldvalue') == curobj.val() || curobj.val() == ''){return false;};
	    if(Number(curobj.val()) < Number(min)){return false;}
        var IsDlvUnit = curobj.attr('IsDlvUnit');
        var DlvUnit = curobj.attr('DlvUnit');
//        if(IsDlvUnit == 1 && DlvUnit > 0){
//            if((curobj.val() % DlvUnit) > 0){return false;}
//        }
	    var memberPrice = curobj.siblings('input[@name=memberPrice]').val();   //会员单价
	    var oItemTotal = curobj.siblings('span.itemTotal');  //显示每项商品价格的元素
	    
	    var recordID = curobj.siblings('input[@name=recordID]').val();
	    var gid = curobj.siblings('input[@name=gid]').val();
	    var pid = curobj.siblings('input[@name=productID]').val();
		var weburl ="OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=UpdateCartNum&cartid="+cartID+"&mid="+mid+"&qty=" + curobj.val() + "&gid=" + gid + "&pid=" + pid;
		$.ajax({
		    url:weburl,
		    dataType:'text',
		    cache:false,
		    //async:false,
		    success:function(data){
                if(!checkLoginStatus(data)){return false;}
                if(data== 'nostorage'){
				    alert('输入的数量大于了剩余库存量');
                }
                else{
	                var str ="<span pid=\"" + pid+ "\" gid=\"" +gid+ "\" id=\"add_product_" + pid + "\" class=\"add_product hand\">加入购物车</span>";
                    curobj.parent().html(str);
				    $('#CartInfo').html(data);
                    ResetShippings();
                    setPriceInfo();
			    }
		    },
            error:function(){alert('error')}
        });// end ajax
	});
	$('input[@name=quantity]').livequery('blur',function(){
	    var curobj = $(this);
	    var min = curobj.siblings('[@name=min]').val();
	    if(Number(curobj.val()) < Number(min) || curobj.val() == ""){
	        alert('购买数量不能小于最少购买数量' + min);
	        curobj.val(min);
	        curobj.keyup();
	        return false;
	    }//end if
	});
	
	//删除商品
	$('.delpdt').livequery('click',function(){
		var curobj = $(this);
		if(confirm('确定要从购物车中删除此商品吗？')){
			var gid = curobj.parent().siblings('.row55').children('input[@name=gid]').val();
			var pid = curobj.parent().siblings('.row55').children('input[@name=productID]').val();
			var weburl = "OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=UpdateCartNum&cartid="+cartID+"&mid="+mid+"&qty=0&gid=" + gid + "&pid=" + pid;
			var obj=$('#add_product_'+gid);
			$.ajax({
				url:weburl,
				datatype:'text',
				cache:false,
				//async:false,
		        success:function(data){
                    if(!checkLoginStatus(data)){return false;}
                    if(data== 'nostorage'){
				        alert('输入的数量大于了剩余库存量');
                    }
                    else{
	                    var str ="<span pid=\"" + pid+ "\" gid=\"" +gid+ "\" id=\"add_product_" + pid + "\" class=\"add_product hand\">加入购物车</span>";
                        obj.parent().html(str);
				        $('#CartInfo').html(data);
                        ResetShippings();
                        setPriceInfo();
			        }
		        },
                error:function(){alert('error')}
            });// end ajax
		}//end confirm
	});	
	
	//减少数量
	$('[@id^=reduce_]').livequery('click',function(){
        var recID = $(this).attr('id').replace('reduce_','');
        var objNum = $('#quantity_' + recID);
        var min = $('#min_' + recID).val();
        if(Number(objNum.val()) <= Number(min)){
            alert('购买数量不能小于最少购买数量' + min);
            return false;
        }else{
            objNum.val(Number(objNum.val())-1);
            objNum.keyup();
        }
	});
	//增加数量
	$('[@id^=add_]').livequery('click',function(){
	    var recID = $(this).attr('id').replace('add_','');
        var objNum = $('#quantity_' + recID);
        objNum.val(Number(objNum.val())+1);
        objNum.keyup();
	});
	    
    //页面关闭时删除购物车记录
    $(window).unload(function(){
        if(!isSubmit){
            $.ajax({url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=ClearCart&CartID='+cartID});
        };
    });
    
//    $('#step1').toggle(function(){
//        $('#step_1').show();
//    },function(){
//        $('#step_1').hide();
//    });
//	$('#step2').toggle(function(){
//        $('#step_2').show();
//    },function(){
//        $('#step_2').hide();
//    });
//	$('#step3').toggle(function(){
//        $('#step_3').show();
//    },function(){
//        $('#step_3').hide();
//    });
//    
    
    $(".page").livequery('click',function(e){
        var curObj = $(this);
	    var PageNo =curObj.attr("href");
	    var tmpLength =curObj.attr("href").lastIndexOf('\/');
	    if(tmpLength >0){//解决a ie6 兼容问题
		    PageNo =curObj.attr("href").substr((curObj.attr("href").lastIndexOf('\/')+1));
	    }else{
		    PageNo =curObj.attr("href");
	    }
	    var ProductName =$("#search_name").val();
	    var ProductIds=$("#check_product_ids").val();
	    var PromotionId =$("#promotion_id").val();
	    var subcat =$("#subcat").val();
	    var bid=$("#brand").val();
	    var productIds =$("#productids").val();
	    GetProductInfo(PageNo,ProductName,ProductIds ,PromotionId ,subcat,productIds,bid);
	    return false;
    });
        
    $("#search_product").bind('click',function(e){
	    var PageNo=$("#PageNo").val();
	    var ProductName =$("#search_name").val();
	    var ProductIds=$("#check_product_ids").val();
	    var PromotionId=$("#promotion_id").val();
	    var subcat=$("#subcat").val();
	    var bid=$("#brand").val();
	    var productIds =$("#productids").val();
	    GetProductInfo(PageNo,ProductName,ProductIds ,PromotionId ,subcat,productIds,bid);
	    return false;
    });

    $('input[@name=qty]').livequery('click',function(e){
    $(this).select();
    });
    
    $('input[@name=qty]').livequery('blur',function(e){
        var qty=($(this).val());
        var min = $(this).parent().siblings('.pminibuy').text()-0;
        if(qty<min)
        {
            alert('购买数量不能小于最少购买数量'+min);
 //           $(this).val(min);
            return;
        }
        var test=/^[1-9]+[0-9]*$/;   
        test.test(qty)   
        if(!test.test(qty) )
        {
            alert('请输入正整数字');
//            $(this).val(1);
            return
        }
        var storage=$(this).parent().siblings('.pstorage').text()-0;
        if(qty>storage)
        {
            alert('输入的数量大于了剩余库存量');
//            $(this).val(storage);
        }
    });    
          
    //添加到购物车
	$(".add_product").livequery('click',function(){
		var pid =$(this).attr('pid');
		var gid=$(this).attr('gid');
		var qty=$('#qty_'+gid).val();
		var obj=$(this);
		//判断顾客的购买量是否满足商品的最小购买数量
        var min = $(this).parent().siblings('.pminibuy').text()-0;
        if(qty<min)
        {
            alert('购买数量不能小于最少购买数量'+min);
            return;
        }
        var test=/^[1-9]+[0-9]*$/;   
        test.test(qty)   
        if(!test.test(qty) )
        {
            alert('请输入正整数字');
            return
        }
        //判断商品的库存是否满足购买的数量
        var storage=$(this).parent().siblings('.pstorage').text()-0;
 		if(qty>storage)
		{
		    alert('输入的数量大于了剩余库存量');
		    return;
		}
		//添加商品到购物车中
        $.ajax({
            url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=AddCartItem',
            type: "POST",
            data: "cartID="+cartID+"&mid="+mid+"&pid="+pid+"&gid="+gid+"&qty="+qty+"&ptype=1",
            dataType:'text',
            cache:false,
            async:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;}
                if(data.indexOf('<')==0){
                    alert('商品已加入到购物车中');
                    var str ='<span class="cancel_product hand" id="cancel_product_'+gid+'" pid="'+pid +'" gid="'+gid+'">取消</span>';
                    if($('#cancel_product_'+gid).length==0){
                        obj.parent().html(str);  
                    }
                    $('#CartInfo').html(data);
                    //购物车的商品发生了变化后，要重新生成配送方式，因为运费因商品的重量，价格有关的
                    ResetShippings();
                    setPriceInfo();
                }
                else{
                    alert('商品未能加入到购物车中');
                }
            },
            error:function(){alert('error')}
        });
	});
	
	//删除购物车中指定的商品
	$(".cancel_product").livequery('click',function(){
		var pid =$(this).attr('pid');
		var gid=$(this).attr('gid');
		var curobj=$(this);
		if(confirm('确定要从购物车中删除此商品吗？')){
			var weburl = "OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=UpdateCartNum&cartid="+cartID+"&mid="+mid+"&qty=0&gid=" + gid + "&pid=" + pid;
			$.ajax({
				url:weburl,
                dataType:'text',
				cache:false,
				//async:false,
		        success:function(data){
                    if(!checkLoginStatus(data)){return false;}
                    if(data== 'nostorage'){
				        alert('输入的数量大于了剩余库存量');
                    }
                    else{
	                    var str ="<span pid=\"" + pid+ "\" gid=\"" +gid+ "\" id=\"add_product_" + pid + "\" class=\"add_product hand\">加入购物车</span>";
                        curobj.parent().html(str);
				        $('#CartInfo').html(data);
                        ResetShippings();
                        setPriceInfo();
			        }
		        },
                error:function(){alert('error')}
            });// end ajax
		}//end confirm

	});
	
	/*把输入的来电号码复制给后面的收货人电话或手机*/
//	$('#txtQuery').blur(function(){
//	    query=$('#txtQuery').val().trim();
//	    var phoneReg=/^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?/;
//	    var mobileReg=/^(?:13\d|15\d|18[123456789])-?\d{5}(\d{3}|\*{3})$/;
//	    //输入的是电话号码
//	    if(phoneReg.test(query) && query.length<20){
//	         isPhone=1;
//	    }
//	    //输入的是手机号码
//	    if(mobileReg.test(query)){
//	        isMobile=1;
//	    }
//	});	
	
    /*获取用户信息开始*/
    $('#search_user').click(function(){
        query=$('#txtQuery').val().Trim();
        $.ajax({
            url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=GetMemberInfo&query='+escape(query),
            dataType:'json',
            cache:false,
            async:false,
            success:function(msg){
                if(msg.Exist == 'true'){
                    var MemberInfo = msg.MemberInfo;
                    mid=MemberInfo.MemberID;  
                        var html="<table class=\"ptable\" cellspacing=\"0\" cellpadding=\"0\">";
						html+="<tr><th class=\"tl\">会员帐号：</th><td class=\"tr\">";
						html+= MemberInfo.MemberName+"</td>";
						html+="</tr>";
						html+="<tr><th class=\"tl\">会员级别：</th><td class=\"tr\">";
						html+= MemberInfo.GroupName+"</td>";
						html+="</tr>";
						html+="<tr><th class=\"tl\">折扣：</th><td class=\"tr\">";
						html+= MemberInfo.Discount+"</td>";	
						html+="</tr>";
                        html+="<tr><th class=\"tl\">预付款：</th><td class=\"tr\">";
						html+= Number(MemberInfo.AdvancePayment).toFixed(2)+"</td>";
						html+="</tr>";
//                        html+="<tr><th class=\"tl\">积分：</th><td class=\"tr\">";
//						html+= MemberInfo.Score+"</td>";	
//						html+="</tr>";
					html+="</table>";
					$('#info').html(html);
					$('#memberid').val(mid);
					
                    $('#GroupID').val(MemberInfo.GroupId);
                    //当读取到用户信息后要在此处理一些价格信息,显示预付款等.
                    if(Number(MemberInfo.AdvancePayment) > 0){
                        $('#advMoney').text(Number(MemberInfo.AdvancePayment).toFixed(2));
                        $('#frmAdvance').show();
                    };
                    //地址簿                    
                    $.ajax({
//                        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=GetAddress&MemberName=' + escape(membername),
                        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=GetAddress&mid=' + mid,
                        cache:false,
                        async:false,
                        success:function(data){
                            if(!checkLoginStatus(data)){return false;}
                            $('#shipAddr_0').prevAll().remove();
                            $('#shipAddr_0').before(data);
                            BindAddress();
                            $('[@name=shipAddr]').eq(0).attr('checked','checked').click();//默认选择收货地址中的第一项
                        },
                        error:function(){alert('get address error');}
                    });
                }
                else{
                    var isPhone=0;
                    var isMobile=0;
	                var phoneReg=/^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?/;
	                var mobileReg=/^(?:13\d|15\d|18[123456789])-?\d{5}(\d{3}|\*{3})$/;
	                //输入的是电话号码
	                if(phoneReg.test(query) && query.length<20){
	                     isPhone=1;
	                }
	                //输入的是手机号码
	                if(mobileReg.test(query)){
	                    isMobile=1;
	                }
                    var tempUser=$('#txtQuery').val().Trim();//默认会员账号
                    var tempPwd=tempUser.length>6 ? tempUser.substring(tempUser.length-6):tempUser;
                    html="<table class=\"ptable\" cellspacing=\"0\" cellpadding=\"0\">";
                    html+="<tr><th class=\"tl\"><em>*</em>会员帐号：</th><td class=\"tr\">";
					html+= "<input name=\"txtName\" type=\"text\" id=\"txtName\" maxlength=\"50\" tabindex=\"1\" class=\"\" style=\"font-size:11pt;height:17px;width:128px\" value=\""+tempUser +"\" /><span style=\"color: red; display: none;\" id=\"nameExist\">此用户名已被注册,请重新输入.</span><em><sapn id=\"tips\">(代顾客新注册账号，以方便下次使用，默认是来电号码)</td></span></em>";
					html+="</tr>";
					html+="<tr><th class=\"tl\"><em>*</em>会员密码：</th><td class=\"tr\">";
					html+="<input name=\"txtPassWord\" type=\"text\" id=\"txtPassWord\" maxlength=\"50\" tabindex=\"2\" class=\"\" style=\"font-size:11pt;height:17px;width:128px\" value=\""+tempPwd+ "\" /><em><span>(可按顾客的要求设置密码，默认是来电号码的后六位)</span></em></td>";
					html+="</tr>";
				    html+="</table>";
				    $('#memberid').val(-1);
				    //还原地址薄的值为默认值
                    $('#shipAddr_0').prevAll().remove();
                    $('#txtRName').val('');
                    if(isPhone==1)
                    {
                        $('#txtRPhone').val(query);
                    }
                    else{
                        $('#txtRPhone').val('');
                    }
                    if(isMobile==1)
                    {
                        $('#txtRMobile').val(query);
                    }
                    else{
                        $('#txtRMobile').val('');
                    }
                    $('#txtRAddress').val('');
                    $('#txtRPostalcode').val('');
                    $('#ddlTopAreas').val('0').change();
                    $('#txtREmail').val('');
                    $('#info').html(html);
                    $('#frmAdvance').hide();
                    $('[@name=shipAddr]').eq(0).attr('checked','checked').click();//默认选择收货地址中的第一项
                };
            },
            error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!')}else{alert('error')};}
        });
        //如果购物车中有商品的话，要刷新购物车中的商品,因为不同的会员有不同的折扣
        //20110206这里有个问题，如果再刷新购物车的话，配送费用会调用二次，因为BindAddress()里调用一次，ResetShippings()里还是会再调一次GetShippings()方法
        if($('#CartInfo').html()!=""){
            $.ajax({
		        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=LookCart&mid='+mid+"&cartID="+cartID,
		        type:'get',
		        datatype:'text',
		        async:false,
		        success:function(data){
                    if(!checkLoginStatus(data)){return false;}
                    if(data.indexOf('<')==0){
                        $('#CartInfo').html(data);
                        //购物车的商品发生了变化后，要重新生成配送方式，因为运费因商品的重量，价格有关的
                        ResetShippings();
                        setPriceInfo();
                    }
                    else{
                        alert('未能刷新购物车中的数据');
                    }
                },
		        error:function(){alert('error');}
		    });
		}
	});
    
    //检查账号是否存在
    $('#txtName').livequery('blur',function(){
		var obj = $(this);
		if($.trim(obj.val()) != ''){
			$.ajax({
				url:ShopFolder +'MemberRegister.aspx?NoCopyright=1&ajax=CheckName',
				type:'post',
				data:'name=' + escape($.trim(obj.val())),
				async:false,
				success:function(msg){
					if(msg == '1'){
						$('#nameExist').show();
						$('#tips').hide();
						obj.focus();
						namePassed = false;
					}else{
						$('#nameExist').hide();
						$('#tips').show();
						namePassed = true;
					}
				},error:function(){alert('error');}
			});
		};
	}).keyup(function(){
		$('#nameExist').hide();
	});
      
    $('#ddlTopAreas').change(function(){topAreaChange();});
    
    /*支付方式开始*/
    //选择从自提点取货
    $('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() == '指定日期'){
            $('#specal_day').show();
        }else{
            $('#specal_day').hide();
        };
    });
    $("#txt_Date").datepicker().click(function(){$(this).blur()});
    /*配送时间结束*/
    
    /*发票开始*/
    //发票
    $('#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();
	});
    /*发票结束*/
    
    /*预付款开始*/
    $('#advMoney').text(memberAdvance);
    //预付款
	if(Number(memberAdvance) > 0){
	    $('#frmAdvance').show();
	};
	$('#cbAdvPay').click(function(){
	    setPriceInfo();
	});
    /*预付款结束*/    
    
    //异步提交表单
    $('#btnSubmit').click(function(){
        if(!check_register()){return false;}
        if(!check_mobile()){return false;};
        if(!check_phone()){return false;};
        if(!check_phoneAndMobile()){return false;};
        if(!check_email()){return false;};
        if(!check_postcode()){return false;};
        if(!CheckShipping()){return false;};
        if(!CheckReceivAddr()){return false};
        if(!CheckPayment()){alert('请选择支付类型');return false;};        
        $("#__VIEWSTATE").remove();
        $("#__EVENTVALIDATION").remove(); 
        var options = { 
        target:        '#tip',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse,  // post-submit callback 
        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=AjaxSubmit',
        type:      'post',      // 'get' or 'post', override for form's 'method' attribute 
        dataType:  'json'        // 'xml', 'script', or 'json' (expected server response type) 
        }; 
        try{
        $('#Form1').ajaxSubmit(options);
        }
        catch(e){
                alert(e);

        }
        function showRequest(formData, jqForm, options) { 
            var queryString = $.param(formData);
        }
        function showResponse(data)  { 
            if(data.Flag=='0'){
                alert(data.Msg);
                window.location.href='OrderModify.aspx?OrderID='+data.OrderID;
            }
            else{
                alert(data.Msg)
            }
        }

//        var data= ($('#Form1') .serialize());
//        $.ajax({
//                url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=AjaxSubmit',
//                type:'post',
//                dataType:'json',
//                data:data,
//                cache:false,
//                success:function(data){
//                    if(data.Flag=='0'){
//                    alert(data.Msg);
//                    window.location.href='OrderModify.aspx?from=list&OrderID='+data.OrderID;
//                    }
//                    else{
//                    alert(data.Msg)
//                    }
//                },
//                error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!');}else{alert(textStatus)};}
//            });
        isSubmit = true;
        return false;
    });
});

//点击地址簿事件
function BindAddress(){
    $('[@name=shipAddr]').unbind('click').click(function(){
        var addrID = $(this).val();
        if(addrID != 0){
            $('#saveaddr').hide();$('#isSaveAddr').attr('checked','');
            $.ajax({
                url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=GetAddrDetail&AddrID='+addrID,
                type:'get',
                dataType:'json',
                cache:false,
                success:function(msg){
                    if(msg.Addr.length > 0){
                        var n = msg.Addr[0];
                        $('#txtRName').val(n.ReceiverName);
                        $('#txtRPhone').val(n.ReceiverPhone);
                        $('#txtRMobile').val(n.ReceiverMobile);
                        $('#txtRPostalcode').val(n.ReceiverZip);
                        $('#txtREmail').val(n.ReceiberEmail);
                        $('#ddlTopAreas').val(n.AddressID.split(',')[0]).unbind().change(function(){
                            topAreaChange();
                        }).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();});
                        $('#txtRMobile').change(function(){CheckSave();});
                        $('#txtRAddress').change(function(){CheckSave();});
                        $('#txtRPostalcode').change(function(){CheckSave();});
                        $('#ddlTopAreas').change(function(){CheckSave();});
                        $('#ddlSubAreas').change(function(){CheckSave();});
                        $('#ddlThirdAreas').change(function(){CheckSave();});
                        $('#txtREmail').change(function(){CheckSave();});
                    }else{
                        $('#txtRName').val('');
                        $('#txtRPhone').val('');
                        $('#txtRMobile').val('');
                        $('#txtRAddress').val('');
                        $('#txtRPostalcode').val('');
                        $('#ddlTopAreas').val('0').change();
                        $('#txtREmail').val('');
                    };
                },
                error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('身份已过期,请重新登陆!');}else{alert(textStatus)};}
            });
        }
        else
        {
            CheckSave();
            $('#txtRName').val('');
            $('#txtRPhone').val('');
            $('#txtRMobile').val('');
            $('#txtRAddress').val('');
            $('#txtRPostalcode').val('');
            $('#ddlTopAreas').val('0').change();
            $('#txtREmail').val('');
            setPriceInfo();
        };
    });//end click
}

function CheckSave(){$('#saveaddr').show();$('#isSaveAddr').attr('checked','checked');};//显示是否保存地址的选项

function SetChoosedRegions()
{
    $('#choosed_regions').empty();
    if($('#ddlTopAreas option[@selected]').val() != -1 && $('#ddlTopAreas option[@selected]').val() != undefined){
        $('#choosed_regions').html($('#choosed_regions').html()+$('#ddlTopAreas option[@selected]').text()+',');
    }
    if($('#ddlSubAreas option[@selected]').val() != -1 && $('#ddlSubAreas option[@selected]').val() != undefined){
        $('#choosed_regions').html($('#choosed_regions').html()+$('#ddlSubAreas option[@selected]').text()+',');
    }
    if($('#ddlThirdAreas option[@selected]').val() != -1 && $('#ddlThirdAreas option[@selected]').val() != undefined){
        $('#choosed_regions').html($('#choosed_regions').html()+$('#ddlThirdAreas option[@selected]').text()+',');
    }
}
function topAreaChange(){
    $('#ddlSubAreas').remove();
    $('#ddlThirdAreas').remove();
    var topoption = $('#ddlTopAreas option[@selected]');
    SetChoosedRegions();
    if(topoption.attr('child') == 'true'){
        var subareaoptions = $('<select id="ddlSubAreas" name="ddlSubAreas"></select>');
        $('<option freeleast="0" hdfk="0" zdt="0" child="false" value="-1">请选择</option>').appendTo(subareaoptions);
        GetNextStep($('#ddlTopAreas').val(),2,subareaoptions);
        if(subareaoptions.find('option').length > 1){
            $('#ddlTopAreas').after(subareaoptions);
            $('#ddlSubAreas').change(function(){
                $('#ddlThirdAreas').remove();
                var suboption = $('option[@selected]',this);
                SetChoosedRegions();
                $('[@name=Shipping]').eq(0).data('isHdfk','2')
                GetShippings(suboption.val(),false);
                setPriceInfo();
                if(suboption.attr('child') == 'true'){                   
                    var thirdareaoptions = $('<select id="ddlThirdAreas" name="ddlThirdAreas"></select>');
                    $('<option freeleast="0" hdfk="0" zdt="0" child="false" value="-1">请选择</option>').appendTo(thirdareaoptions);
                    GetNextStep($('#ddlSubAreas').val(),3,thirdareaoptions);
                    //alert(thirdareaoptions.find('option').length);
                    if(thirdareaoptions.find('option').length > 1){
                        $(this).after(thirdareaoptions);
                        $('#ddlThirdAreas').change(function(){
                            var thirdoption = $('option[@selected]',this);
                            SetChoosedRegions();
                            //三级地区自提点
                            if(thirdoption.attr('ztd') > 0){$('tr.paytype_6').show();}else{$('tr.paytype_6').hide();};
                            $('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();
                        });//end change
                    };//end if
                }else{
                    //没有三级地区,获取二级地区的配送方式
                    //$('[@name=Shipping]').eq(0).data('isHdfk','2');
                    //GetShippings($('#ddlSubAreas').val(),false);
                    //setPriceInfo();
                };//end if
                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');
            });//end change
        };//end if
    }else{
        //没有二级地区,获取一级地区的配送方式
        $('[@name=Shipping]').eq(0).data('isHdfk','2');
        GetShippings($('#ddlTopAreas').val(),false);
        setPriceInfo();
    };//end if
    
    //是否显示自提点选项
    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');}    
};

////获取子地区
//function GetSubArea(areaID){
//    var options = null
//    var login = true;
//    $.ajax({
//        url:ShopFolder+'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:'OrderAdd.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 GetShippings(areaID,isHdfk){
    $('.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();
    };
    //要传入商品重量，商品总价及商家ID
    var pdtPrice=$('#total').text();
    var pdtWeight=$('#totalweight').text();
    var sid=0; 
    if(areaID==0)
    {
        areaID=-1;
    }
    $.ajax({
        url:'OrderAdd.aspx?NoCopyRight=1&type=ajax&Action=GetShipps&st=' + (isHdfk ? '1' : '0') + '&aid=' + areaID + '&AreaIDForPrice=' + areaIDForPrice+'&p='+pdtPrice+'&w='+pdtWeight+'&sid='+sid,
        type:'get',
        dataType:'json',
        async: false,
        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+(n.remark==''? '' : ('('+n.remark+')')));
                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 ResetShippings(){
//    if($('#ddlThirdAreas').val()!=undefined &&$('#ddlThirdAreas').val()!=0 )
//    {
//        if($('option[@selected]',$('#ddlThirdAreas')).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);
//    }
//    else 
    if($('#ddlSubAreas').val()!=undefined &&$('#ddlSubAreas').val()!=0 )
    {
        if($('#ddlSubAreas option[@selected]').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($('#ddlSubAreas').val(),false);
    }
    else if($('#ddlTopAreas').val()!=undefined &&$('#ddlTopAreas').val()!=0 )
    {
        if($('#ddlTopAreas option[@selected]').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($('#ddlTopAreas').val(),false);
    }
//    //是否显示自提点选项
//    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');}  
}

//当改变购物车中的商品数量时，要重新设置购物车的
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{//按地区设置最低金额
        if( $('#ddlTopAreas').val()!=0){
            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();
            };
        }
    };
    setTaxPrice();
    setAdvancePrice();        
    $('#ptotalPrice').text($('#originaltotal').text());
    $('#couponPrice').text(Number($('#originaltotal').text() - $('#total').text()).toFixed(2));
    var lefttotal = Number($('#ptotalPrice').text()) + Number($('#shipPrice').text()) + Number($('#taxPrice').text()) - Number($('#advPrice').text()) - Number($('#pmtPrice').text());
    $('#lefttotal').text(Number(lefttotal).toFixed(2));

};

function setAdvancePrice(){
    if($('#cbAdvPay').attr('checked')){
        var tmpTotal = Number($('#total').text()) + Number($('#taxPrice').text()) + Number($('#shipPrice').text());
        var advMoney = Number($('#advMoney').text());
        if(advMoney >= tmpTotal){
            $('#advPrice').text(Number(tmpTotal).toFixed(2));
        }else{
            $('#advPrice').text(Number(data).toFixed(2));
        }
    }else{
        $('#advPrice').text('0');
    };
};

//获取的发票的金额
function setTaxPrice(){
    //普通发票
    if($('#chkInvoice').is(":checked") && $('#rbtnInvoiceTypeGeneral').is(":checked"))
    {
        $('#taxPrice').text(Number($('#total').text()*taxRateGeneral).toFixed(2));
    }
    //增值发票
    else if($('#chkInvoice').is(":checked") && $('#rbtnInvoiceTypeVAT').is(":checked"))
    {
        $('#taxPrice').text(Number($('#total').text()*taxRateGeneral).toFixed(2));
    }
}

//判断是否选择了完整的地区
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('请填写收货人姓名!');$('#txtRName').focus();return false;};
    if(!CheckFullAddr()){alert('请选择完整的地区');return false;};
    if($.trim($('#txtRAddress').val())==''){alert('请填写收货人详细地址!');$('#txtRAddress').focus();return false;};
//    if($.trim($('#txtRPostalcode').val())==''){alert('请填写收货人邮政编码!');$('#txtRPostalcode').focus();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 check_postcode()
{
   var postalcode=$("#txtRPostalcode").val();
   if(postalcode!=''){
       var myReg=/(^\s*)\d{6}(\s*$)/;
       if(!myReg.test(postalcode)){alert('邮编格式不正确');$("#txtRPostalcode").focus();return false;}
   }
   return true;
}
//检查联系电话
function check_phone(){
   var phone = $("#txtRPhone").val();
   var myReg=/(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/;
   if(phone!='' && !myReg.test(phone)){alert('固定电话格式不正确');$("#txtRPhone").focus();return false;}
   if(phone!='' && phone.length > 20 ){alert('固定电话格式不正确');$("#txtRPhone").focus();return false;}
   return true;
}
//检查手机号
function check_mobile()
{
   var mobile=$("#txtRMobile").val();
   if(mobile!=''){
       var myReg=/(^\s*)(((\(\d{3}\))|(\d{3}\-))?13\d{9}|1\d{10})(\s*$)/;
       if(!myReg.test(mobile)){alert('手机号格式不正确');$("#txtRMobile").focus();return false;}
   }
   return true;
}
//检查电话和手机是否都填写了
function check_phoneAndMobile()
{
   if($("#txtRPhone").val()=='' && $("#txtRMobile").val()==''){alert('固定电话和手机号码请至少填写一项！');$("#txtRMobile").focus();return false;}
   return true;
}
//检查Email
function check_email()
{  
   var email=$("#txtREmail").val();
   if(email!=''){
   var myReg=/(^\s*)\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\s*$)/;
   if(!myReg.test(email)){alert('电子邮件格式不正确');$("#txtREmail").focus();return false;}
   }
   return true;
}
//检查会员账号,邮箱等是否可以注册
function check_register(){
    if(!namePassed ){
        alert('用户名已被注册');
        $('#txtName').focus();
        return false;
    }
    return true;
}

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


//获取选择的最后一级地区ID
//百悦反映的问题
//这里选择第三个地区的ID，来查找配送方式跟配送价格，而上面方法function topAreaChange()是选第二级地区来查找配送方式跟配送价格，从已导致计算出错误的价格。这里改为选择第二级地区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 isNum(obj,msg){
	var reg = new RegExp(/\D/g);
	if(reg.test(obj.val()) || $.trim(obj.val()) == ''){
	    alert(msg);
	    obj.focus();
	    return false;
	};
	return true;
}

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


function SelectSpecs(){
    var selected_values = '';//记录选择的尺寸,用来匹配对应的GoodsID
    var text_spec_result = '';//存入数据库的文本内容
    if(mainSpecCount > 0){
        text_spec_result += mainSpecName + '：' + mainSpecValue + '<br/>';
    };
    $('input[type=radio][name^=spec_][@checked]').each(function(){
        selected_values += $(this).val() + ' ';
        text_spec_result += $(this).attr('specname') + '：' + $(this).val() + '<br/>';
    });
    if(selected_values != ''){
        selected_values = selected_values.substring(0,selected_values.length-1);
        text_spec_result = text_spec_result.substring(0,text_spec_result.length-5);
    };
    
    if($.trim(SpecDesc) != ''){
        var goods = eval('(' + SpecDesc + ')').Goods;
        $.each(goods,function(i,n){
            if(selected_values == n.Desc){
                $('#tmp_GID').val(n.GID);
            };
        });
    };
    $('#spectext').val(escape(text_spec_result));
    
    if($('#tmp_GID').val() != '0'){
        $('#btnAddPdt').removeAttr('disabled');
    }else{
        $('#btnAddPdt').attr('disabled','disabled');
    };
};
function GetProductInfo(a){
	PageNo =arguments[0];
	ProductName =arguments[1];
	CheckkedPids =$.trim(arguments[2]);
	if(CheckkedPids=='undefined') CheckkedPids ='';
	PromotionId =arguments[3];
	SubCat =arguments[4];
	var bid=arguments[6];
	if(typeof subcat=='undefined') subcat ='';
	var SearchPids =arguments[5];
	var PromotionType =$("#promotion_type").val();
	URL ='get_product.ashx',
	Param ={pageno:PageNo,keyword:ProductName ,checkedpids:CheckkedPids,promotion_id:PromotionId,promotion_type:PromotionType,searchpids:SearchPids ,cid:SubCat,bid:bid},
	$.post(URL ,Param ,function(data){
		$("#productlist").html(data);
	})
	searched=true;
	return true;
}