﻿var favStr = "<div class='login_zx'>·会员购物优惠<span style=' color:#CE0086'>5%</span><br />·使用银行支付或在线支付再优惠<span style=' color:#CE0086'>5%</span></div>";
$(document).ready(/*程序加载时添加事件*/
    function(){
    
        $("#btnRegister").click(function(){
            window.open("Member/Register.aspx");
        });
        $("#btnRegister").attr("title","·注册会员即送现金礼券\r\n·会员购物优惠5%\r\n·用银行支付或在线支付再优惠5%");
        
        /*在电子邮箱，密码框上回车*/
        $("#txtUserEmail").keypress(function(event){
            if(event.keyCode == 13){$("#btnLogin").click();event.preventDefault();}
        });
        
        $("#txtUserPwd").keypress(function(event){
            if(event.keyCode == 13){$("#btnLogin").click();event.preventDefault();}
        });
    
        /*会员登录*/
        $("#btnLogin").click(function(){
            ValidateLoginAll();
        });
        
        /*换购商品*/
        $("input[@name='btnPresent']").click(function(){
            var pid = GetPID($(this).attr("id"));
            var exist = ExistPresent(pid);
            if(exist){
                var resultStr = "换购商品已添加成功,无需重复添加!";
                ShowMsg(resultStr);                             //列表中不存在，这时的换购商品 
            }else{
                AddFavProduct(pid);                                //添加换购商品
            }
        });
               
        /*购物车列表*/
        $("input[@name='amount']").click(function(){
            this.select();
        });
        //修改数量,阻止输入非法字符
        $("input[@name='amount']").keypress(function(event){
            if(event.keyCode && (event.keyCode < 48 || event.keyCode > 57)){event.preventDefault();}
        });
        //修改数量
       $("input[@name='amount']").change(function(){
            var pAmount = this.value;
            if(isNaN(parseInt(this.value))){
                pAmount = "1";
                this.value = 1;
            }else{
                if(parseInt(this.value) == 0){
                    pAmount = "1";
                    this.value = 1;
                }
            }
            
            var pName = $(this).parent().parent().find("td:eq(0)").text();
            var subTotalPrice = $(this).parent().next();
            $.getJSON("JQueryCenter.aspx",{"cmd":"amount","pid":GetPID(this.id),"num":pAmount,"time":GetTime()},function (data){
                 var resultStr = "修改成功！" + RedColor(pName) + " 现在数量: " + RedColor(pAmount) +" 小计价格：" + RedColor(data[0].subtotalprice);                     
                     if(data[0].havepresent.toLowerCase() == "true"){//如果有赠品，则增加赠品的数量
                        var preIDs = data[0].presentids;
                        var preArray = preIDs.split(",");
                        for(var i=0;i < (preArray.length-1);i++){
                            $("#pAmount-" + preArray[i]).text(pAmount);                            
                        }
                     }
                     
                    subTotalPrice.text(data[0].subtotalprice);
                    ShowMsg(resultStr);
                   //计算统计金额
                    CalcSubPrice();
		    });
        }); 
        
        //删除按钮            
       $("#tab-productlist tbody span:has(img)").click(function(){
            //删除行元素
            DeleteProduct($(this).attr("id"));
        });
        
        $("#sp-ShopCartEmpty").click(function(){
            if(!confirm("确认要清空购物车?")){return;}            
            $.getJSON("JQueryCenter.aspx",{
                "cmd":"empty",
                "pid":GetPID(this.id),
                "time":GetTime()},function(data){
                    if(data[0].sign == "1"){
                        $("#tab-productlist tbody").html("");
                        ShowMsg("购物车清空成功!");
                        //计算统计金额
                        CalcSubPrice();
                    }
                    else{
                       alert(data[0].sign);
                    }
                });
        });
        //验证商品数量

        /*********礼券模块************/
        
        //使用礼券
        $("#btn-usegc").bind("click",function(){
            ValidateGC();
        });
        
        //选择礼券
        $("#btn-choosegc").bind("click",function(){
             var gcNumber = showModalDialog("OrderAffirmSelectCustomerGiftNumber.aspx?time=" + GetTime(),window,"dialogwidth:250px;dialogheight:300px;help:0;center:yes;resizable:0;status:0;scroll:yes");
             if(gcNumber != undefined)
             {
                $("#txtGCNumber").attr("value",gcNumber);
                //选择礼券后自动使用
                $("#btn-usegc").click();
             }
        });
        $("#txtGCNumber").focus(function(){
            //得到焦点
            var gcNumber = this.value;
            if(gcNumber == "请输入礼券号"){
               this.value = "";
            }
        });
        
        $("#txtGCNumber").blur(function(){
            //失去焦点
            var gcNumber = this.value;
            if(gcNumber == ""){
               this.value = "请输入礼券号";
            }
        });
        
        //取消使用礼券
        $("#btn-cancelusegc").click(function(){
            $.getJSON("JQueryCenter.aspx",{"cmd":"cancelusegc","time":GetTime()},
            function(data){
                switch(data[0].sign){
                    case "0":
                        alert("抱歉! 取消使用礼券失败 请刷新重试");
                        break;
                    case "1":
                        $("#GCMsg").html("");
                        $("#txtGCNumber").show();
                        $("#btn-usegc").show();
                        $("#btn-choosegc").show();
                        $("#btn-cancelusegc").hide();
                        break;
                    default:
                        alert("抱歉! 取消使用礼券失败 原因可能是网络不畅通 请刷新重试");
                        break;
                }
            });
        });
        
        $("#GCMsg").click(function(){
            if($(this).text().indexOf("可以使用") == -1){
                $(this).hide();
            }
        });
            /*********礼券模块 结束************/
            
            //联系电话只允许输入数字
            /*
            $("#txtPhone").keypress(function(event){
                //48->0    57->9   32->空格 45->-
                if(event.keyCode && (event.keyCode < 48 || event.keyCode > 57))
                {
                    if((event.keyCode == 32 || event.keyCode == 45))
                    {
                        return;
                    }
                    event.preventDefault();
                }
            });
            */
            $("#txtPhone").blur(function(){
                if(ValidateFormat(this.value) == false){
                    alert("联系电话只允许输入数字，－，和空格");
                }
            });
        
            //邮编只允许输入数字
            /*
            $("#txtPostCode").keypress(function(event){
                if(event.keyCode && (event.keyCode < 48 || event.keyCode > 57))
                {
                    if((event.keyCode == 32 || event.keyCode == 45))
                    {
                        return;
                    }
                    event.preventDefault();
                }
            });
            */
            $("#txtPostCode").blur(function(){
                if(ValidateFormat(this.value)==false)
                {
                    alert("邮编只允许输入数字，－，和空格");
                }
            });
            
          //绑定省市区
           new PCAS("select-province","select-city","select-area");
          
          //默认随时
          $("#radio-anytime").click();
          //指定日期默认为当天
          $("#txtDateTime")[0].value = GetDateTimeNow();
          //绑定时间控件
          $("#txtDateTime").focus(function(){
                SelectDate(this,'yyyy-MM-dd');
                $("#radio-appoint").click();
          });      
          /***********选择联系日期************/
          $("#txtDateTime").keypress(function(event){
                event.preventDefault();
          });
          
         //绑定小时
         var hour = GetHours();
         var timeIndex = 0;
         var timeStr = "<option value='09'>09</option>";
         for(var i = 10;i<24;i++){
            timeStr += "<option value='"+i+"'>"+i+"</option>";
         }
         //判断当前时间，向后推迟两个小时
         var hour = GetHours();
//       if(hour >= 9){hour += 2;}
         $("#select-time").prepend(timeStr);
         if((hour >8) && (hour < 24)){
            timeIndex = (hour-9);
         }

         $("#select-time")[0].selectedIndex = timeIndex;
         
         //判断当前分钟，选择时间段
         var minuteStr = "<option value='00'>00</option><option value='15'>15</option><option value='30'>30</option><option value='45'>45</option>";
         $("#select-minute").prepend(minuteStr);
         var minIndex = 0;
         var min = GetMinutes();
         if(min < 15){
             minIndex = 1;
         }else if(min < 30){
            minIndex = 2;
         }else if(min < 45){
            minIndex = 3;
         }

         $("#select-minute")[0].selectedIndex = minIndex;
         //绑定分钟
  
         
         //默认随时联系
         $("#radio-anytime").click();
         
         $("#select-time").focus(function(){
                $("#radio-appoint").click();
            }
         );
          $("#select-minute").focus(function(){
                $("#radio-appoint").click();
            }
         );
         
         /***********选择联系日期 结束************/
         //送货上门
         $("#radio-home").bind("click",function(){
             $("#payment-32")[0].disabled = "";
             $("#sp-payment32").html("(需购物满200元)");
             $("#div-SendMethodIntro").html(RedColor("送货上门:")+" 全国1910个城市开通上门服务，涵盖全国大部分地区。送货费：￥20.00");
         });
         //邮政包裹
         $("#radio-post").bind("click",function(){
            $("#payment-32")[0].disabled = "disabled";
            $("#sp-payment32").html("(邮政包裹不支持货到付款)");
            //如果已经选中则设置为银行汇款
            var $payment = $('input[@name="payment"][@checked]').val();
            if($payment == "32")
            {
                $("#payment-0").click();
            }            
            
            $("#div-SendMethodIntro").html(RedColor("邮政包裹:")+" 不支持货到付款，10个工作日内送达。送货费：￥10.00");
         });
         
         //选择收货地址
         $("#btn-chooseaddress").bind("click",function(){
            var info = showModalDialog("ChooseConsigneeInfo.aspx?time="+GetTime(),window,"dialogwidth:590px;dialogheight:310px;help:0;center:yes;resizable:0;status:0;scroll:yes");
            
            if(info == undefined){return;}
            $.each(info,function(){
                //绑定信息
                BindConsigneeInfo(this["name"],this["mobiletelephone"],this["address"],this["postcode"],0,0);            
            });
          });

         //默认是送货上门
         $("#radio-home").click();
         //银行汇款
         $("#payment-0").bind("click",function(){
            $("#div-netpay").hide();
            $("#div-cod").hide();
            $("#div-bank").show();
         });
         //网银在线
         $("#payment-25").bind("click",function(){
            $("#div-bank").hide();
            $("#div-cod").hide();
            $("#div-netpay").show();
         });
         //货到付款
         $("#payment-32").bind("click",function(){
            $("#div-netpay").hide();
            $("#div-bank").hide();
            $("#div-cod").show();
         });
         //默认是网银在线
         $("#payment-25").click();
         //点table的td则选中
         $("#table-bank td").bind("click",function(){
            $(this).find("input").click();
         });
         
         //文件框获得焦点时变换颜色
        $("input[@type='text']").focus(function(){
            $(this).addClass("input-focus");
        });
        $("input[@type='password']").focus(function(){
            $(this).addClass("input-focus");
        });
        
            
        $("input[@type='text']").blur(function(){
            $(this).removeClass("input-focus");
        });
        $("input[@type='password']").blur(function(){
            $(this).removeClass("input-focus");
        });
         //为文本框设定内左边距
         //$("input[@type='text'],[@type='password']").addClass("text-indent");
         
         //保存收货人信息
         $("#btn-submit").bind("click",function(){
            var returnStr = ValidateRequireItem();
            if(returnStr == ""){
               SubmitOrder();           //提交订单
            }
            else{
                if(returnStr == "false"){
                    return;
                }else{
                    alert(returnStr);
                }
            }
         });
         
         //不满100元提示
         $("#btn-submit").mouseover(function(){
            var minConsume = 100;
            var totalPrice = $("#product-td-totalprice").html();
            totalPrice = parseFloat(RemoveRMBSymbol(totalPrice));
            if(totalPrice < minConsume){
                $("#divVoidTips").fadeIn("slow");
            }
         });
         
         $("#btn-submit").mouseout(function(){
            $("#divVoidTips").fadeOut("slow");
         });
         
        //计算统计金额
        CalcSubPrice();
        //控制显示隐藏选择礼券和选择收货人地址
        $("#div-msg").dblclick(function(){
            $(this).fadeTo("slow",0);
        });
});
//显示提示框
function ShowMsg(msg){
 if($("#div-msg").css("background-color") == "transparent"){
    $("#div-msg").css("background-color","#FFF4B9")
 }
    $("#div-msg").fadeTo(2000,1);
    $("#div-msg").html("&nbsp;&nbsp;&nbsp;"+msg+"&nbsp;&nbsp;&nbsp;");
    //setTimeout("HideMsg()",3000);
}
//隐藏提示框
function HideMsg(){
    $("#div-msg").fadeTo("slow",0);
}
//从ID中获取ProductID
function GetPID(id){
    if(id.indexOf("-") != -1){
        return id.substring((id.indexOf("-")+1),id.length);
    }
    else{
        return id;
    }
}
//获取时间
function GetTime(){
    //方法返回一个整数值，这个整数代表了从 1970 年 1 月 1 日开始计算到 Date 对象中的时间之间的毫秒数
    var date = new Date();
    return date.getTime();
}
//获取当前日期 格式:2008-12-12
function GetDateTimeNow(){
    var dt = new Date();
    var year = dt.getFullYear();
    var month = dt.getMonth();
    var date = dt.getDate();
    
    if((month + 1) <10){month = "0" + (month + 1);}
    if(date <10){date = "0" + date;}
    return year + "-" + month + "-" + date;
}
//获取时间的小时
function GetHours(){
    var dt = new Date();
    return dt.getHours();
}
//获取时间的分钟
function GetMinutes(){
    var dt = new Date();
    return dt.getMinutes();
}
//发送请求验证会员登录
function ValidateMemberLogin()
{
    $("#sp-loginmsg").html("正在验证...");
    var userEmail = $("#txtUserEmail")[0].value;
    var userPwd = $("#txtUserPwd")[0].value;

    $.get("JQueryCenter.aspx",{"cmd":"login","useremail":userEmail,"userpwd":userPwd,"time":GetTime()},function(data){
        var resultStr = "";
        switch(data)
        {
            case "0":
                resultStr = "验证失败,也许是网络故障，或服务器暂时不可用!";
                break;
            case "1":
                $("#tab-login tbody").hide();
                $("#btn-choosegc").show();
                $("#btn-chooseaddress").show();
                
                resultStr = userEmail + "<br />您好! " + LogoutBtn() + favStr;
                
                $("#txtUserPwd")[0].value = "";
                
                $("#ul-login div:has(input)").hide();
                
                
                //登录成功，绑定最近一次购物记录
                BindRecentlyInfo();
                break;
            case "2":
                resultStr = "电子邮箱不存在!";
                break;
            case "3":
                resultStr = "登录密码错误!";
                break;
        }
        $("#sp-loginmsg").html(resultStr);
    });
}
//会员登录　回车，按钮的验证
function ValidateLoginAll(){
   var result = ValidateLoginInput();
   if(result != ""){
      $("#sp-loginmsg").html(result);
   }
   else{
      ValidateMemberLogin();
   }
}

//验证登录输入是否正确
function ValidateLoginInput(){
    var userEmail = $("#txtUserEmail")[0].value;
    var userPwd = $("#txtUserPwd")[0].value;
    
    if(userEmail == ""){
        $("#txtUserEmail")[0].focus();
        return "电子邮箱不能为空!";
    }
    
    if(!IsEmail(userEmail)){
        $("#txtUserEmail")[0].focus();
        return "电子邮箱格式不正确!";
    }
    
    if(userPwd ==""){
        $("#txtUserPwd")[0].focus();
        return "登录密码不能为空!";
    }
    
    if(userPwd.length < 6){
        $("#txtUserPwd")[0].focus();
        return "登录密码不能少于6位!";
    }
    return "";
}

//验证礼券
function ValidateGC(){
     var gcNumber = $("#txtGCNumber")[0].value;
     $("#GCMsg").show();
     if(gcNumber != "" && gcNumber != "请输入礼券号"){
          $("#GCMsg").text("正在验证礼券...");
          $("#txtGCNumber").hide();
          $("#btn-usegc").hide();
          $.getJSON("JQueryCenter.aspx",{"cmd":"usegc","gcnumber":gcNumber,"time":GetTime()},
            function(data){
                var resultStr = "";
                switch(data[0].sign){
                    case "0":
                        resultStr = "缺少参数gcnumber";
                        $("#txtGCNumber").show();
                        break;
                    case "1":
                        resultStr = "使用此礼券需最低消费 " + parseFloat(data[0].money).toFixed(2) + " 元";
                        $("#txtGCNumber").show();
                        $("#btn-usegc").show();
                        $("#btn-choosegc").show();
                        $("#txtGCNumber")[0].value = "请输入礼券号";
                        break;
                    case "2":
                        resultStr = "礼券可以使用,面值: " + parseFloat(data[0].money).toFixed(2) + " 元";
                        $("#txtGCNumber").hide();
                        $("#btn-usegc").hide();
                        $("#btn-choosegc").hide();
                        $("#btn-cancelusegc").show();
                        break;
                    case "3":
                        resultStr = "无效礼券,可能已使用或已过期 ";
                        $("#txtGCNumber").show();
                        $("#btn-usegc").show();
                        $("#btn-choosegc").show();
                        break;
                }
                $("#GCMsg").text(resultStr);
            });
         }
         else
         {
            $("#GCMsg").text("请输入礼券号码");
         }
}
//验证Email格式是否正确
function IsEmail(mail){
    return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(mail));
}
//限制用户不可修改优惠和赠品的数量
function LimitEditAmount(){
    if(hideProductIDs != "" && hideProductIDs != undefined){
        //如果有赠品或优惠商品
        var pid = hideProductIDs.split(",");                
        for(var i=0;i<pid.length;i++){
            var pCount = $("#pAmount-" + pid[i]).attr("value");
            var pParent = $("#pAmount-" + pid[i]).parent();
                pParent.append("<span id=\"pAmount-"+pid[i]+"\">"+pCount+"</span>");
                $("#pAmount-" + pid[i]).remove();
        }
        
        if(presentIDs != "" && presentIDs != undefined){
            var preIDs = presentIDs.split(",");
            for(var i=0;i<pid.length;i++){
                $("#delbtn-" + preIDs[i]).remove();
            }
        }
    }
}
//验证表单必填项
function ValidateRequireItem()
{
    //商城最低消费金额100元
    var minConsume = 100;
    var totalPrice = $("#product-td-totalprice").html();
        totalPrice = parseFloat(RemoveRMBSymbol(totalPrice));
    var $payment = $('input[@name="payment"][@checked]').val(); 
    var codPrice = 200;         //(Cash on Delivery)货到付款
    
    var returnStr = "";
    if(totalPrice < minConsume){//不满最低消费
        return "false";
    }else if(($payment == "32") && (totalPrice < codPrice)){
        returnStr = "货到付款，您需要购物满200元";
        return returnStr;
    }else if($("#txtName")[0].value == ""){//姓名必填
        returnStr = "请输入您的姓名! 例如:王先生";
        $("#txtName").focus();
        return returnStr;
    }else if($("#txtPhone")[0].value == ""){
        returnStr = "请输入您的联系电话!";
        $("#txtPhone").focus();
        return returnStr;
    }else if($("#select-province option[@selected]").val() == ""){//地区必选
        returnStr = "请选择您所在的地区!";
        return returnStr;
    }else{
        return returnStr;
    }
}

//提交订单
function SubmitOrder(){
    var $name = $("#txtName")[0].value;            
    var $phone = $("#txtPhone")[0].value;
    var $province = $("#select-province option[@selected]").val();            
    var $city = $("#select-city option[@selected]").val();
    var $area = $("#select-area option[@selected]").val();
    var $address = $("#txtAddress")[0].value;
    //去除逗号
    while($address.indexOf(",")!= -1){
        $address = $address.replace(",","");
    }

    var $postcode = $("#txtPostCode")[0].value;         
    
    var $contacttime = $('input[@name="time"][@checked]').val();            
    var $datetime = $("#txtDateTime")[0].value;
    var $time = $("#select-time option[@selected]").val();
    var $minute = $("#select-minute option[@selected]").val();
    var cTime = "";
    if($contacttime == "anytime"){
        cTime = "";//联系时间任意
    }else if($contacttime == "appoint"){
        //指定联系时间
        cTime = $datetime + " " + $time + ":" + $minute + ":00" 
    }
    //配送方式
    var $sendmethod = $('input[@name="sendmethod"][@checked]').val();          
    var $payment = $('input[@name="payment"][@checked]').val();            
    var $bankremit = $('input[@name="bankremit"][@checked]').val();
    //支付方式
    var pMent = $payment;
    if($payment == "0"){
        pMent = $bankremit;
    }
    var $remark = $("#txtRemark")[0].value;

    //控制按钮不可用
    $("#btn-submit")[0].disabled = "disabled";
   
    $.post("JQueryCenter.aspx",
    {cmd:"affirm",
     name:escape($name),
     phone:$phone,
     address:escape($province) + "," + escape($city) + "," + escape($area) + "," + escape($address),
     postcode:$postcode,
     contacttime:escape(cTime),
     sendmethod:$sendmethod,
     payment:pMent,
     remark:escape($remark)
    },function RetFun(data){
        data = data.replace("[","(").replace("]",")");
        var json = eval(data);
        switch(json.sign){
            case "0":
                //$("#btn-submit")[0].value = "提交订单";
                $("#btn-submit")[0].disabled = "";
                $("#btn-cancelusegc").click();                
                alert("此礼券最低消费金额为: "+json.minconsumemoney+" 元");
                break;
            case "1":
                //$("#btn-submit")[0].value = "提交订单";
                $("#btn-submit")[0].disabled = "";
                $("#btn-cancelusegc").click();
                alert("此礼券已被使用或已过期");
                break;
            case "3":
                  //json.ordernumber 为订单号
                  window.location.href = "OrderFinish.aspx";
                break;
        }
    });
}

//控制按钮可用性
var delay = 20;
function unlocksubmit(){
	$("#btn-submit")[0].disabled = "";
}
function unlocksubmit_delay(){
	if(delay > 0){
		delay -= 1;
		$("#btn-submit")[0].value = delay + "秒可用";
	}
	else{
		clearInterval(time_delay);
		delay = 20;
		$("#btn-submit")[0].disabled = "";
		$("#btn-submit")[0].value = "提交订单";
	}
}
//验证电话和邮编的格式是否正确，专对火狐
function ValidateFormat(str){
    var arr = str.split("");
    var ableStr = "0123456789- ";
    for(var i=0;i < arr.length;i++){
        if(ableStr.indexOf(arr[i]) == -1){
            return false;// 字符不存在
        }
    }
    return true;
}

//去掉人民币符号和逗号
function RemoveRMBSymbol(moneyStr){
    while((moneyStr.indexOf("￥")!= -1) || (moneyStr.indexOf(",")!= -1)){
        moneyStr = moneyStr.replace("￥","");
        moneyStr = moneyStr.replace(",","");
    }
    return moneyStr;
}
//统一计算金额：需要支付，先付款，为您节省
function CalcSubPrice(){
    var $subPrice = $("#tab-productlist tbody tr td[title]");
    var pCount = $subPrice.length;
    if(pCount > 0){
        $("#tab-productlist tfoot tr[@id='tr-tips']").hide();
        $("#tab-productlist tfoot tr[@id='tr-ShopCartEmpty']").show();
        var subTotalPrice = 0;
        //有商品
        $subPrice.each(function(index){
            subTotalPrice += parseFloat(RemoveRMBSymbol($(this).html()));
        })
        //先付款优惠百分比
        var favPercent = 0.95;
        var firstPayPrice = subTotalPrice * favPercent;
        var saveMoney = subTotalPrice - firstPayPrice;
        $("#product-td-totalprice").html("￥" + subTotalPrice.toFixed(2));
        $("#product-td-firstpayprice").html("￥" + firstPayPrice.toFixed(2));
        $("#sp-savemoney").html("￥" + saveMoney.toFixed(2));
    }
    else{   
        //无商品
        if($("#tab-productlist tbody tr").length == 0){
            ShowEmptyTips();
        }
        
        $("#tab-productlist tfoot tr[@id='tr-ShopCartEmpty']").hide();
        $("#product-td-totalprice").html("￥0.00");
        $("#product-td-firstpayprice").html("￥0.00");
        $("#sp-savemoney").html("￥0.00");
    }
}
//返回红色的span
function RedColor(str){
    return "<span style='color:Red;'>" + str + "</span>";
}
//从cookie中绑定礼券
function BindGC(){
    if((gcNumber != undefined) && (gcPrice != undefined)){
        $("#txtGCNumber").attr("value",gcNumber);
        setTimeout("BtnUseGCClick()",500);
    }
}
//使用礼券
function BtnUseGCClick(){
    $("#btn-usegc").click();
}
//非会员，隐藏选择礼券和选择收货地址 CT = Control控制
function CTGCAndAddr(){
    if((isMember != undefined) && (userEmail != undefined)){
        if(Boolean(isMember)){
            //如果是会员
            $("#tab-login tbody").hide();
            $("#btn-choosegc").show();
            $("#btn-chooseaddress").show();
            $("#sp-loginmsg").html(userEmail + "<br />您好! " + LogoutBtn() + favStr);
            $("#ul-login div:has(input)").hide();
            //如果是会员，加载页面后绑定最后一次购物记录
            BindRecentlyInfo();
        }
    }
}
//注销按钮
function LogoutBtn(){
    return "<span style='cursor:pointer;color:balck;' onclick='javascript:MemberLogout();'>[注销]</span>";
}
//用户注销
function MemberLogout(){
    $("#sp-loginmsg").html("正在注销...");
     $.getJSON("JQueryCenter.aspx",{"cmd":"logout"},function(data){
        if(data[0].sign == "1"){
            $("#tab-login tbody").show();
            $("#sp-loginmsg").html("");
            $("#btn-choosegc").hide();
            $("#btn-chooseaddress").hide();
            $("#ul-login div:has(input)").show();
        }else{
            $("#sp-loginmsg").html("注销失败,请重试!" + LogoutBtn());
        }
     });
}

//绑定最后一次购物记录
function BindRecentlyInfo(){
  $.getJSON("JQueryCenter.aspx",{"cmd":"recently","time":GetTime()},function(data){
        if(parseInt(data[0].count) > 0){
            BindConsigneeInfo(data[0].name,data[0].phone,data[0].address,data[0].postcode,data[0].sendmethodid,data[0].paymentid);
        }else{
        
        }
     });
}
//绑定收货人信息
function BindConsigneeInfo(name,phone,address,postcode,sendmethodid,paymentid){
    $("#txtName")[0].value = name;
    var addr = address.split(",");
    var province = addr[0];
    var city = addr[1];
    var area = addr[2];
    var street = addr[3];
    
    $("#select-province").empty();
    $("#select-city").empty();
    $("#select-area").empty();
    
    new PCAS("select-province","select-city","select-area",province,city,area);
     
    $("#select-province").attr("value",province);            
    $("#select-city").attr("value",city);
    $("#select-area").attr("value",area);
    
    $("#txtAddress")[0].value = street;
    $("#txtPostCode")[0].value = postcode;
    $("#txtPhone")[0].value = phone;
    
    if(sendmethodid != 0){
        if(sendmethodid == "17"){
            
            $("#radio-home").click();
        }else if(sendmethodid == "16"){
            $("#radio-post").click();
        }
    }
    
    if(paymentid == "25" || paymentid == "32"){
        //网银支付和货到付款
        $("#payment-" + paymentid).click();
    }
    else{
        //银行汇款
        if(paymentid != "0"){
            $('input[@id="payment-0"]').click();
            $("#bank-" + paymentid).click();
        }
    }
}
//加19元换购功能,添加赠品
function AddFavProduct(pid){
    var resultStr = "";
    $.getJSON("JQueryCenter.aspx",{"cmd":"favproduct","pid":pid,"time":GetTime()},function RetFun(data){
        var sign = data[0].sign;

        switch(sign){
            case "0":
                alert("缺少参数pid,赠品添加失败");
                return;
            break;
            case "1":
                if(data[0].ispresent.toLowerCase() == "true"){
                    alert(data[0].name + " 是赠品,不可单独添加!");
                    return;
                }else{
                    var present = PresentLine(pid,data[0].name,data[0].marketprice,data[0].shopprice,data[0].ispresent,data[0].isfavorable);
                    DeletePresentList();                                        //如果列表中已存在其它的换购商品
                    //如果有赠品，放到赠品前面
                    var $pPresent = $("#tab-productlist tbody tr:contains('[赠]')");
                    if($pPresent.length > 0){
                        $pPresent.eq(0).before(present);
                    }else{
                        $("#tab-productlist tbody").append(present);                //添加到最后一行，
                    }
                    resultStr = "换购商品：" + RedColor(data[0].name) + " 添加成功!";
                    ShowMsg(resultStr);
                   //计算统计金额
                    CalcSubPrice();
                }
            break;
            case "2":
                alert("此商品没设定为赠品,赠品添加失败");                   //此商品没有在web.config中设定为赠品
                return;
            break;
            case "3":
                alert("此商品数据库中不存在!")
                return;
            break;
            default:
                alert("没有此方法");
            break;
        }
    });
}
//赠品行
function PresentLine(pid,name,marketPrice,shopPrice,ispresent,isfavorable){
    if(Boolean(isfavorable)){
        name = "<span style=\"color:Red;\">[特]</span> " + name;
    }
  var pStr = "<tr style='background-color:#FFF3FA'>"
              + "<td class='list_n'><a href='Product." + pid + ".aspx' target='_blank'>" + name + "</a></td>"
              + "<td class='list_n2'>" + marketPrice + "</td>"
              + "<td class='list_n2'>" + shopPrice + "</td>"
              + "<td class='list_n3'><span id='pAmount-" + pid + "'>1</span></td>"
              + "<td title='小计金额' class='list_n2'>" + shopPrice + "</td>"
              + "<td class='list_n3'><span id='delbtn-" + pid + "' class='delbutton' onclick='javascript:DeleteProductPro(\"delbtn-" + pid + "\");'><img src='images/shopcart_new/scnew_46.gif' alt='删除' /></span></td>"
            +"</tr>";
  return pStr;
}
function DeleteProductPro(id){
    $("#div-msg").text("");
    DeleteProduct(id);
}
//删除商品
function DeleteProduct(id){
    var $parent = $("#" + id).parent().parent();
    $parent.css("background-color","#FFF9A6");
    $.getJSON("JQueryCenter.aspx",{"cmd":"delete","pid":GetPID(id),"time":GetTime()},function(data){
        //删除商品所在行
        $parent.remove();
        $.each(data,function(entryIndex,entry){
            if(entry["present"]!=""){//如有赠品则删除
                var pids = entry["present"].split(",");
                for(var i=0;i < pids.length;i++){
                    var $ele = $("#pAmount-" + pids[i]);
                    if($ele.length > 0){
                        $ele.parent().parent().remove();
                    }
                }
            }
            if(entry["givepresent"] != ""){//如果不存在一个正常购物的商品(非赠品，非优惠),则删除赠送商品
                var $ele = $("#pAmount-" + entry["givepresent"]);
                if($ele.length > 0){
                    $ele.parent().parent().remove();
                }
            }            
        });
        var pName = $parent.find("td:eq(0)").text();
        var msgTxt = $("#div-msg").text().indexOf("换购商品");
        
        if(msgTxt == -1){
            ShowMsg("商品：" + RedColor(pName) + " 删除成功!");
        }
        //计算统计金额
        CalcSubPrice();
    });
}
//判断是否已存在赠品
function ExistPresent(pid){
    var b = false;
    var pList = ProductList();
    if(pList.indexOf(pid + ",") != -1){
        b = true;
    }
    return b;
}
//商品列表,不包括赠品
function ProductList(){
    var proIDList = "";
    $("#tab-productlist tbody span:has(img)").each(function(){
        proIDList += GetPID(this.id) + ",";
    });
    return proIDList;
}
//换购商品列表
function PresentList(){
    var preIDList = "";
    $("input[@name='btnPresent']").each(function(){
        preIDList += GetPID(this.id) + ",";
    });
    return preIDList;
}
//删除商品列表中的换购商品
function DeletePresentList(){
    var proList = ProductList();        //商品列表
    var preList = PresentList();        //优惠商品
    
    proList = proList.substring(0,(proList.length-1));
    preList = preList.substring(0,(preList.length-1));
    
    proList = "[" + proList + "]";
    while(proList.indexOf(",") != -1){
        proList = proList.replace(",","][");
    }

    var preListArr = preList.split(",");
    for(var i=0;i < preListArr.length;i++){
        if(proList.indexOf("[" + preListArr[i] + "]") != -1){
            $("#delbtn-" + preListArr[i]).click();
        }
    }
}
//显示无商品提示
function ShowEmptyTips(){
    $("#tab-productlist tfoot tr[@id='tr-tips']").show();
}