﻿document.execCommand("BackgroundImageCache", false, true); 

// 关闭查询窗口
function closeQueryProduct() {
    $('#DivQueryByCode').hide();
    $('#ProductCode').val('');
    $('#SearchResultMessage').text('');
    $('#SearchResultMessage').hide();
}
    
// 查询
function JumpToSearch() {
    var objAgeScope = $("#AgeScope").val();
    var objCategory = $("#Categories").val();
    var objKeywords = $.trim($("#Keywords").val().replace('%','').replace('<','').replace('>','').replace('#',''));
    objKeywords = objKeywords.replace('/','').replace('\\','').replace('$','');
    objKeywords = objKeywords.replace('~','').replace('@','').replace('^','').replace('&','').replace('*','');
    objKeywords = objKeywords.replace('(','').replace(')','').replace(',','').replace('.','').replace('?','');
     objKeywords = objKeywords.replace('|','');
     
    objKeywords = objKeywords.replace("想找什么？请输入商品或品牌名称试试，如：奶粉。","");
    
    if (objAgeScope == '-1' && objCategory == '-1' && (objKeywords=='想找什么？请输入商品或品牌名称试试，如：奶粉。'|| objKeywords == '')) {
        alert('请选择或输入至少一个查询条件。');
        $("#Keywords").focus();
        return;
    } else {
          $.get("/Product/Handler/GetProductListByCondition.ashx",{CategoryId:objCategory,BrandId:"-1",Age:objAgeScope,
               Keyword:objKeywords,OrderType:"0",Page:"1",ListType:"0",IsForSearch:"T"},function(data){
            if (data.indexOf('很抱歉') == -1){
                window.location.href = "/Product/ProductList/" + objCategory + "_-1_" + objAgeScope + "_0_1_" + objKeywords + ".htm";
            } else {
                window.location.href = '/NotFound.aspx?k='+escape(objKeywords);
            } 
        });
    } 
}

// 清空默认显示的搜索关键字
function ClearDefaultKeywords() {
    var objKeywords = $("#Keywords");
    $("#Keywords").val("");
}

function focusUserId() {
    $('#UserId').val('');
    $('#Password').val('');
    $('#Password').show();
    $('#Password1').hide();
}

// 根据搜索关键字查询
function GoToSearch(keywords) {
    document.location.href = "/Product/ProductList/-1_-1_-1_0_1_" + keywords + '.htm';
}

// 回车后进行搜索
function EnterToSearch() {
    if (event.keyCode == 13) {
        JumpToSearch();
    }
}

// 调用Ajax来显示公告栏内容
function ShowBulletion(bulletionId) {
         var windowWidth = document.body.offsetWidth/2-200; 
         var objBulletinShow = $('#BulletinShow');
         var objContent = $('#Content');
         var objBulletinClose = $('#BulletinClose');
         var objTitle = $('#Title');
         var objCreateDateTime = $('#CreateDateTime');
         
         objBulletinShow.css({"scrollbar-face-color":"#9FF7E1",position: "absolute", border: "1px solid #0C8869","border-bottom-color":"#fff"});
         objBulletinShow.css({left:windowWidth,top:"130px",background:"#fff",width:"400px",height:"300px"});
         objBulletinShow.css('overflow',"auto");
         objBulletinShow.css("filter","alpha(opacity=94,style=1)");
         objBulletinShow.css("opacity","0.94");
         objBulletinShow.css("color","red");
         objContent.text("Loading...");
         objBulletinShow.show();
         objBulletinClose.css({"cursor":"hand","text-decoration":"underline","vertical-align":"middle","text-align":"center",position: "absolute"});
         objBulletinClose.css({border: "1px solid #0C8869","border-top-color":"#fff",left:windowWidth,top:"432px",background:"#fff",width:"400px",height:"20px"});
         objBulletinClose.text('关闭');
         objBulletinClose.show();
         
    $.get("/Bulletin/BulletinShow.ashx", { BulletinId: bulletionId}, function(data){
         objBulletinShow.css("color","#000000");
         objTitle.html(data.split("|")[0]);
         objCreateDateTime.html("发布日期：" + data.split("|")[1]);
         objContent.html(data.split("|")[2]);
         objTitle.css({padding:"10px","text-align":"center","font-weight":"bold"});
         objCreateDateTime.css({"text-align":"right",padding:"5px 10px 5px"});
         objContent.css({"word-break":"break-all",padding:"5px 10px 5px 10px"});
       });
}

// 调用Ajax来显示所有商品分类
function showAllCategories() {
    var objAllCategories = $('#AllCategories');
    var visibleWinWidth = document.body.scrollWidth;
    
    objAllCategories.css({"scrollbar-face-color":"#9FF7E1",position: "absolute", border: "1px solid #0C8869"});
    objAllCategories.css({left:visibleWinWidth/2-320,top:700,background:"#fff",width:"980px",height:"900px"});
    objAllCategories.css('overflow',"auto");
    objAllCategories.css("filter","alpha(opacity=96,style=1)");
    objAllCategories.css("opacity","0.96");
    
    $.get("/Product/Handler/GetProductCategories.ashx", function(data){
        objAllCategories.html('');
        objAllCategories.html('<div style=\"padding: 5px 0px 8px 5px; color: Red; font-weight: bold; cursor: pointer;\"onclick=\"javascript:closeAllCategories();\">[关闭分类显示]</div>')
        objAllCategories.append(data);
        objAllCategories.show();
    })
    
    window.onresize = function() {
        var visibleWinWidth = document.body.scrollWidth;
        objAllCategories.css({left:visibleWinWidth/2-320,top:700});
    }
}

function closeAllCategories() {
    $('#AllCategories').hide();
}

// 关闭窗口
function CloseWindow() {
    $('#BulletinShow').hide();
    $('#BulletinClose').hide();
}

// 用户登录（快速注册页登录）
function Login(backUrl) {
    var $userId = $('#txtLoginId');
    var $password = $('#txtPassword');
    var $imageLogin = $('#ImgBtnLogin');
    var $objLoginStatus = $('#LoginStatus');
    var $objAjaxLoadingShow = $('#AjaxLoadingShow');
    
    if ($.trim($userId.val()) == '') {
        $('.error').show();
        $('.error').html('请输入用户名。');
        $userId.css("background-color","#FFE9D7");
        $userId.focus();
        return;
    } else if ($.trim($password.val()) == '') {
        $('.error').show();
        $('.error').html('请输入密码。');
        $password.css("background-color","#FFE9D7");
        $password.focus();
        return;
    }
    
    $userId.attr("disabled","disabled");
    $password.attr("disabled","disabled");
    $imageLogin.attr("disabled","disabled");


    var visibleWinWidth = document.documentElement.clientWidth;
    var visibleWinHeight = document.documentElement.clientHeight;
    
    var fullWinWidth = document.body.scrollWidth;
    var fullWinHeight = document.body.scrollHeight;
    
    var popupHeight = $objAjaxLoadingShow.height();
    var popupWidth = $objAjaxLoadingShow.width();
    
    $objLoginStatus.css({"font-weight":"normal","padding-top":"10px","text-align":"center", color:"red",position: "absolute"});
    $objLoginStatus.css({left:"0px",top:"0px",background:"#f3f3f3",width:fullWinWidth,height:fullWinHeight});
    $objLoginStatus.css("filter","alpha(opacity=85,style=1)");
    $objLoginStatus.css("opacity","0.85");
    $objLoginStatus.show();
    $objAjaxLoadingShow.show();
    $objAjaxLoadingShow.css({left:visibleWinWidth/2-popupWidth/2,top:visibleWinHeight/2-popupHeight/2});
    
    window.onresize = function() {
        var visibleWinWidth = document.documentElement.clientWidth;
        var visibleWinHeight = document.documentElement.clientHeight;
        $objLoginStatus.css({width:fullWinWidth,height:fullWinHeight});
        $objAjaxLoadingShow.css({left:visibleWinWidth/2-popupWidth/2,top:visibleWinHeight/2-popupHeight/2});
    } 
     
    $.get("/Account/Handler/Login.ashx", { UserId: $.trim($userId.val()),Password:$.trim($password.val())}, function(data){
          if ('0' == data) {
              $objAjaxLoadingShow.hide();
              $('.error').show();
              $('.error').html('用户名或密码错误。');
              $objLoginStatus.css("display","none");
              $userId.removeAttr("disabled");
              $password.removeAttr("disabled");
              $imageLogin.removeAttr("disabled");
              return;
          } else if ('-1' == data) {
              $objAjaxLoadingShow.css("display","none");
              $('.error').show();
              $('.error').html('登录失败，请重试或联系网站管理员。');              
              $objLoginStatus.hide();
              $userId.removeAttr("disabled");
              $password.removeAttr("disabled");
              $imageLogin.removeAttr("disabled");
              return;
          } else {
              //$objLoginStatus.hide();
              //$objAjaxLoadingShow.hide();
              if ($.trim(backUrl).length > 0)
                  window.location = backUrl;
              else
                  window.location = '/';
          }
      });
 }
      
// 用户登录（顶部）
function UserLogin() {
    var userId = $('#UserId').val();
    var password = $('#Password').val();
    
    if (userId == '' || 'ID' == userId) {
        alert('请输入用户名。');
        $('#UserId').focus();
        return;
    } else if (password == '') {
        alert('请输入密码。');
        $('#Password').focus();
        return;
    }
    
    $('#UserId').attr("disabled","disabled");
    $('#Password').attr("disabled","disabled");
    $('#BtnLogin').attr("disabled","disabled");

    var objLoginStatus = $('#LoginStatus');
    var objAjaxLoadingShow = $('#AjaxLoadingShow');
    
    var visibleWinWidth = document.documentElement.clientWidth;
    var visibleWinHeight = document.documentElement.clientHeight;
    
    var fullWinWidth = document.body.scrollWidth;
    var fullWinHeight = document.body.scrollHeight;
    
    var popupHeight = objAjaxLoadingShow.height();
    var popupWidth = objAjaxLoadingShow.width();
    
    objLoginStatus.css({"font-weight":"normal","padding-top":"10px","text-align":"center", color:"red",position: "absolute"});
    objLoginStatus.css({left:"0px",top:"0px",background:"#f3f3f3",width:fullWinWidth,height:fullWinHeight});
    objLoginStatus.css("filter","alpha(opacity=85,style=1)");
    objLoginStatus.css("opacity","0.85");
    objLoginStatus.show();
    objAjaxLoadingShow.show();
    objAjaxLoadingShow.css({left:visibleWinWidth/2-popupWidth/2,top:visibleWinHeight/2-popupHeight/2});
    
    window.onresize = function() {
        var visibleWinWidth = document.documentElement.clientWidth;
        var visibleWinHeight = document.documentElement.clientHeight;
        objLoginStatus.css({width:fullWinWidth,height:fullWinHeight});
        objAjaxLoadingShow.css({left:visibleWinWidth/2-popupWidth/2,top:visibleWinHeight/2-popupHeight/2});
    } 
     
    $.get("/Account/Handler/Login.ashx", { UserId: userId,Password:password}, function(data){
          if ('0' == data) {
              objAjaxLoadingShow.hide();
              alert('用户名或密码错误。');
              objLoginStatus.css("display","none");
              $("#UserId").removeAttr("disabled");
              $("#Password").removeAttr("disabled");
              $("#BtnLogin").removeAttr("disabled");
              return;
          } else if ('-1' == data) {
              objAjaxLoadingShow.css("display","none");
              alert('内部服务器错误，请重试或联系网站管理员。');
              objLoginStatus.hide();
              $("#UserId").removeAttr("disabled");
              $("#Password").removeAttr("disabled");
              $("#BtnLogin").removeAttr("disabled");
              return;
          } else {
//              var objUserLogin = $('#UserLogin');
                var objWelcomeUser = $('#WelcomeUser');
                objWelcomeUser.text(data);
//              var temp = "<img style=\"border: 0px; height: 29px; cursor: pointer;\" title=\"天天乐在线客服\" alt=\"\"";
//              temp += " src=\"/SiteCommon/Images/online_new.gif\"";
//              temp += " onclick=\"window.open('http://www.mybabyjoy.com:8082/Message.aspx?eid=103&username=" + data;
//              temp += "', 'newwindow', 'height=500, width=665, top=200, left=250, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')\" />";
//           
//              $("#OnlineService").html(temp);
              $('.welcome').show();
              $('.loginbar').hide();
              $('.loginbutton').hide();
              objLoginStatus.hide();
              objAjaxLoadingShow.hide();
              //window.location.reload();
          }
      });
}

// 回车后触发登录事件
function enterToLogin() {
    if (event.keyCode == 13) {
        UserLogin();
    }
}

// 回车后触发登录事件
function enterToLogin2(backUrl) {
    if (event.keyCode == 13) {
        Login(backUrl);
    }
}

// 点击注册按钮定位到注册页面
function UserReg() {
    window.location.href = '/Account/Login.aspx';
}

// 验证用户名中是否有空格
function isWhiteWpace (s) {
    var whitespace = " \t\n\r";
    var i;
    for (i = 0; i < s.length; i++){  
       var c = s.charAt(i);
       if (whitespace.indexOf(c) >= 0) {
           return true;
       }
   }
    return false;
}

// 验证用户名是否合法
function isSsnString (ssn) {
    var re=/^[0-9a-z][\w-.]*[0-9a-z]$/i;
    if(re.test(ssn)) {
        return true;
    } else {    
            return false;
      }
}

// 验证用户名
function checkUserName(){
    var ssn = $.trim($('#RegUserId').val());
    if(ssn.length < 5 || ssn.length > 20 ) {
        $('#RegUserId').css("background-color","#FFE9D7");
        $('#RegUserIdNote').removeClass("note");
        $('#RegUserIdNote').addClass("error");
        $('#RegUserIdSuccess').hide();
        $('#RegUserIdNote').html('请输入正确的用户名，用户名长度为5-20位。');

        return false;
    }
    if (isWhiteWpace(ssn)) {
         $('#RegUserId').css("background-color","#FFE9D7");
         $('#RegUserIdNote').removeClass("note");
         $('#RegUserIdNote').addClass("error");
         $('#RegUserIdSuccess').hide();
         $('#RegUserIdNote').html('请输入正确的用户名,用户名中不能包含空格。');
         return false;
    }
    if (!isSsnString(ssn)) {
        $('#RegUserId').css("background-color","#FFE9D7");
        $('#RegUserIdNote').removeClass("note");
        $('#RegUserIdNote').addClass("error");
        $('#RegUserIdSuccess').hide();
        $('#RegUserIdNote').html('用户名不合法，用户名应该由不区分大小写的[a-z 0-9 ._-]字符组成。');
        return false;
    }
    $.post("/Account/Handler/GetCustomerByLoginId.ashx", { RegUserId:  $('#RegUserId').val()}, function(data){
        if ('-1' == data){
            $('#RegUserId').css("background-color","#FFE9D7");
            $('#RegUserIdNote').removeClass("note");
            $('#RegUserIdNote').addClass("error");
            $('#RegUserIdSuccess').hide();
            $('#RegUserIdNote').html('该用户ID已存在，请换用其它的进行注册。');
            return false;
        } else if ('-2' == data) {
            $('#RegUserId').css("background-color","#FFE9D7");
            $('#RegUserIdNote').removeClass("note");
            $('#RegUserIdNote').addClass("error");
            $('#RegUserIdSuccess').hide();
            $('#RegUserIdNote').html('验证用户名失败，服务未启动或网络故障。');
            return false;
        } else if ('1' == data) {
              $('#RegUserId').css("background-color","#FFFFFF");
              $('#RegUserIdNote').html('');
              $('#RegUserIdNote').removeClass("error");
              $('#RegUserIdNote').addClass("note");
              $('#RegUserIdSuccess').show();
        }
    });
    return true;
}

// 验证密码
function checkRegPassword() {
    var password = $('#RegPassword').val();
    if ($.trim(password) == '') {
        $('#RegPassword').css("background-color","#FFE9D7");
        $('#RegPasswordNote').removeClass("note");
        $('#RegPasswordNote').addClass("error");
        $('#RegPasswordSuccess').hide();
        $('#RegPasswordNote').html('密码不能为空');
        
        return false;
    } else if ($.trim(password).length < 6 || $.trim(password).length > 20) {
        $('#RegPassword').css("background-color","#FFE9D7");
        $('#RegPasswordNote').removeClass("note");
        $('#RegPasswordNote').addClass("error");
        $('#RegPasswordSuccess').hide();
        $('#RegPasswordNote').html('密码长度数在6~20位之间。');
        return false;
    }
    $('#RegPasswordNote').removeClass("error");
    $('#RegPasswordNote').addClass("note");
    $('#RegPasswordNote').html('');
    $('#RegPasswordSuccess').show();
    $('#RegPassword').css("background-color","#FFFFFF");
    return true;
}

function checkCfmPassword() {
    checkRegPassword();
    var password = $.trim($('#RegPassword').val());
    var cfmPassword = $.trim($('#ConfrmPwd').val());
    if (cfmPassword == '') {
        $('#ConfrmPwd').css("background-color","#FFE9D7");
        $('#ConfrmPwdNote').removeClass("note");
        $('#ConfrmPwdNote').addClass("error");
        $('#CfmPasswordSuccess').hide();
        $('#ConfrmPwdNote').html('确认密码不能为空。');
        return false;
    } else if (cfmPassword != password) {
        $('#ConfrmPwd').css("background-color","#FFE9D7");
        $('#ConfrmPwdNote').removeClass("note");
        $('#ConfrmPwdNote').addClass("error");
        $('#CfmPasswordSuccess').hide();
        $('#ConfrmPwdNote').html('确认密码与原始密码不匹配。');
        return false;
    } else if ($.trim(cfmPassword).length < 6 || $.trim(cfmPassword).length > 20) {
        $('#ConfrmPwd').css("background-color","#FFE9D7");
        $('#ConfrmPwdNote').removeClass("note");
        $('#ConfrmPwdNote').addClass("error");
        $('#CfmPasswordSuccess').hide();
        $('#ConfrmPwdNote').html('密码长度数在6~20位之间。');
        return false;
    }
    
    $('#ConfrmPwd').css("background-color","#FFFFFF");
    $('#ConfrmPwdNote').removeClass("error");
    $('#ConfrmPwdNote').addClass("note");
    $('#ConfrmPwdNote').html('');
    $('#CfmPasswordSuccess').show();
    return true;
}

// 通用方法验证EMAIL格式是否正确
function checkEmailRegex(email){
    // 规则验证
    var myreg = /^([a-zA-Z0-9]+[_|\_|\.|-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.|-]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if(!myreg.test(email))
        return false;
    else
        return true;
}

// 通用方法验证手机号码格式是否正确
function checkMobileRegex(mobile){
     var reg0 = /^13\d{5,9}$/; 
     var reg1 = /^15\d{5,9}$/; 
     var reg2 = /^18\d{5,9}$/; 
     
     var myreg = false; 
     if (reg0.test(mobile)) myreg=true; 
     if (reg1.test(mobile)) myreg=true; 
     if (reg2.test(mobile)) myreg=true; 
     
     return myreg
}

// 通用方法验证邮政编码格式是否正确
function checkPostCodeRegex(postcode){
    var regZip=/^[0-9]{6}$/;  
    if(!regZip.test(postcode))
        return false;
    else
        return true;
}

// 通用方法验证固话号码格式是否正确
function checkTelRegex(tel){
    var RegTel=/^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/;
    if(!RegTel.test(tel))
        return false;
    else
        return true;
}

// 验证电子邮件
function checkEmail() {
    var email = $.trim($('#Email').val());
    
    if (email == '') {
        $('#Email').css("background-color","#FFE9D7");
        $('#EmailNote').removeClass("note");
        $('#EmailNote').addClass("error");
        $('#EmailSuccess').hide();
        $('#EmailNote').html('邮箱地址不能为空。');
        return false;
    }
    
    if(!checkEmailRegex(email)) {
        $('#Email').css("background-color","#FFE9D7");
        $('#EmailNote').removeClass("note");
        $('#EmailNote').addClass("error");
        $('#EmailSuccess').hide();
        $('#EmailNote').html('请输入有效的E-mail地址。');
        return false;
    }
    $('#Email').css("background-color","#FFFFFF");
    $('#EmailNote').removeClass("error");
    $('#EmailNote').addClass("note");
    $('#EmailNote').html('');
    $('#EmailSuccess').show();
    return true;
}

// 验证手机号码的有效性
function checkMobile() {
     var mobile = $.trim($("#Mobile").val());        
     if ('' == mobile) {
        $('#Mobile').css("background-color","#FFE9D7");
        $('#MobileNote').removeClass("note");
        $('#MobileNote').addClass("error");
        $('#MobileSuccess').hide();
        $('#MobileNote').html('手机号码不能为空。');
        return false;
     }
     if(!checkMobileRegex(mobile)) {
        $('#Mobile').attr('value','');
        $('#Mobile').css("background-color","#FFE9D7");
        $('#MobileNote').removeClass("note");
        $('#MobileNote').addClass("error");
        $('#MobileSuccess').hide();
        $('#MobileNote').html('手机号码无效，请重新输入。');
        return false;
     }
     $('#Mobile').css("background-color","#FFFFFF");
     $('#MobileNote').removeClass("error");
     $('#MobileNote').addClass("notge");
     $('#MobileNote').html('');
     $('#MobileSuccess').show();
   return true;
}

// 注册操作
function doRegister(backurl) {
    
    if (!checkUserName())
        return;
    if (!checkRegPassword())
        return;
    if (!checkCfmPassword())
        return;

    if (!checkEmail())
        return;
    
    if (!checkMobile())
        return;
               
    var isAccept = $('#ChkAccept');

    if (!$('#ChkAccept').attr("checked")) {
        alert('注册前，您必须阅读并接受《天天乐用户协议》。');
        return;
    }
    
    // 使垂直滚动条滚动到顶部
    window.scrollTo(0,0);
    
    var objRegStatus = $('#RegStatus');
    var objAjaxLoadingShow = $('#RegAjaxLoadingShow');
    
    var visibleWinWidth = document.documentElement.clientWidth;
    var visibleWinHeight = document.documentElement.clientHeight;
    
    var fullWinWidth = document.body.scrollWidth;
    var fullWinHeight = document.body.scrollHeight;
    
    var popupHeight = objAjaxLoadingShow.height();
    var popupWidth = objAjaxLoadingShow.width();
    
    objRegStatus.css({"font-weight":"normal","padding-top":"10px","text-align":"center", color:"red",position: "absolute"});
    objRegStatus.css({left:"0px",top:"0px",background:"#f3f3f3",width:fullWinWidth,height:fullWinHeight});
    objRegStatus.css("filter","alpha(opacity=85,style=1)");
    objRegStatus.css("opacity","0.85");
    objRegStatus.show();
    objAjaxLoadingShow.show();
    objAjaxLoadingShow.css({left:visibleWinWidth/2-popupWidth/2,top:visibleWinHeight/2-popupHeight/2});
    
    window.onresize = function() {
        var visibleWinWidth = document.documentElement.clientWidth;
        var visibleWinHeight = document.documentElement.clientHeight;
        objRegStatus.css({width:fullWinWidth,height:fullWinHeight});
        objAjaxLoadingShow.css({left:visibleWinWidth/2-popupWidth/2,top:visibleWinHeight/2-popupHeight/2});
    } 
    
    // 获取注册表单信息
    var regUserId = $.trim($("#RegUserId").val());
    var regPwd = $.trim($("#RegPassword").val());
    var email = $.trim($("#Email").val());
    var mobile = $.trim($("#Mobile").val());
    var realName = $.trim($("#RealName").val());
    var rcmdUserId = $.trim($("#RcmdUserId").val());
    var relation = $("input[name='Relation'][@type=radio][checked]").val();
    
    if ("undefined" == relation || null == relation)
        relation = '';
    var bithdayYear = $("#BirthdayYear>option:selected").get(0).value;
    var bithdayMonth = $("#BirthdayMonth>option:selected").get(0).value;
    var bithdayDay = $("#BirthdayDay>option:selected").get(0).value;
    
    var birthday = bithdayYear + "-" + bithdayMonth + "-" + bithdayDay;
    if ('a-a-a' != birthday){
        if (birthday.indexOf("a") >= 0){
            objRegStatus.hide();
            objAjaxLoadingShow.hide();
            alert('请选择完整的宝宝出生日期。');
            birthday = '';
            return;
        }
    } else
        birthday = '';
    
    var sex = $("input[name='sex'][@type=radio][checked]").val();
    if ('undefined' == sex || null == sex)
        sex = "";
    var babyName = $.trim($("#BabyName").val());
    var hospital = $.trim($("#Hospital").val());
    var babyPhoto = $.trim($("#BabyPhoto").val());
    
    $("#ButtonOK").attr("disabled","disabled");
        $.post("/Account/Handler/Register.ashx", { RegUserId: regUserId,RegPwd:regPwd,Email:email,Mobile:mobile,
                                           RealName:realName,RcmdUserId:rcmdUserId,Relation:relation,
                                           Birthday:birthday,Sex:sex,BabyName:babyName,Hospital:hospital,BabyPhoto:babyPhoto}, function(data) {
        if ('-1' == data){
            objAjaxLoadingShow.hide();
            alert('该用户已存在，请使用新的登录名注册。');
            objRegStatus.hide(); 
            $('#RegUserId').css("background-color","#FFE9D7");
            $('#RegUserId').select();
            $("#ButtonOK").removeAttr("disabled");
            return;
          } else if ('-2' == data) {
              objAjaxLoadingShow.hide();
              alert('用户注册失败，请重试或联系网站管理员。');
              objRegStatus.hide(); 
              $("#ButtonOK").removeAttr("disabled");
              return;
          } else if ('-3' == data) {
              objAjaxLoadingShow.hide();
              alert('验证注册用户信息失败，请重试或联系网站管理员。');
              objRegStatus.hide(); 
              $("#ButtonOK").removeAttr("disabled");
              return;
          } else if ('1' == data) {
              objRegStatus.text(""); 
              if(backurl =='/Account/'){
                  alert('恭喜您，注册成功！系统将跳转到【我的账户】。');
                  window.location.href = '/Account/';
                 }
              else{
                  alert('恭喜您，注册成功！感谢您对天天乐的信任和支持！');
                  window.location.href = backurl;
                }
          } 
          else {
              objAjaxLoadingShow.hide();
              alert('注册时系统发生异常，请重试或联系网站管理员。');
              $('#RegStatus').hide(); 
              $("#ButtonOK").removeAttr("disabled");
              return;
          }
      });
}

// 明细页商品相关项选择
function TabSelect(TabName){
    $('#Detail').hide();
    $('#Promote').hide();
    $('#Specif').hide();
    $('#DetailTab').attr('src', '../SiteCommon/Images/fy/DetailTabOff.jpg');
    $('#PromoteTab').attr('src', '../SiteCommon/Images/fy/PromoteTabOff.jpg');
    $('#SpecifTab').attr('src', '../SiteCommon/Images/fy/SpecifTabOff.jpg');
    
    $('#'+ TabName).removeAttr('style');
    $('#' + TabName + 'Tab').attr('src', '../SiteCommon/Images/fy/' + TabName + 'TabOn.jpg');
}

var radioValue=5;

function RadioSeclet(value){
    
    radioValue=value;
};
  
// 添加多个商品到购物车
var codeNum="";
function addCart()
{
    var checkedCodes = "";
    var checkedObs = "";
    $("[id='chkDel'][checked]").each(function(){              
         checkedCodes += $(this).val().split(',')[0] + ',';
         checkedObs += $(this).val().split(',')[1] + ',';
     });
    if ("" == checkedCodes)
        alert('请至少选择一个商品后再添加。');
    else
    {
        var Code=checkedCodes.substring(0,checkedCodes.length-1);
        codeNum =Code.split(',').length ;              
        for(i=0;i<Code.split(',').length;i++)
        {
            codeNum--;          
            UpdateCart(Code.split(',')[i],'1',checkedObs.split(',')[i]);
        } 
    }
}

// 把商品放入到购物车
function UpdateCart(ProductCode,ProductQty,IsObsolete){ 
    
    var Count = 1;
    
    // 如果该商品时属于停用商品，则购买时给客户以提示。       
    if ('T' == IsObsolete) {
        alert('对不起，该商品已停用，无法购买。');
        return;
    }
    var Cart = $.cookie('TTLWebSiteCart');         
    
    var isExisted = false;                
    
    if(Cart != null && Cart != 'undefined'){        

        var limitedBuy = $('#LimitedBuyCode').val().split(',');
        var isLimited = false;
        
        for(j=0;j<limitedBuy.length;j++){
            if(limitedBuy[j] == ProductCode){
                isLimited = true;
                break;
            }
        }
                                  
        Cart = Cart.split(',');           

        for(var i =0;i<Cart.length;i++){
            var code = Cart[i].split(';')[0];
            
            if(code == ProductCode){
                if(isLimited){
                    for(j=0;j<limitedBuy.length;j++){
                        if(limitedBuy[j] == code){                        
                            if (confirm('每人每天只能抢购一件商品，选择该商品将替代已有抢购商品，是否继续？')) {                                               
                                Cart[i] = "";                            
                            }
                            else{
                                return;
                            };
                            
                            break;
                        }
                    }
                }
                else{
                    Count = parseInt(Cart[i].split(';')[1]) + parseInt(ProductQty);
                };
            }
            else{
                if(isLimited){
                    for(j=0;j<limitedBuy.length;j++){
                        if(limitedBuy[j] == code){                        
                            if (confirm('每人每天只能抢购一件商品，选择该商品将替代已有抢购商品，是否继续？')) {                                               
                                Cart[i] = "";                            
                            }
                            else{
                                return;
                            };
                            
                            break;
                        }
                    }
                }
            }
            
            if(Cart[i].split(';')[0] == ProductCode){
                                    
                var cookie = new String(Cart);                    
                cookie = cookie.replace(code + ';'+ Cart[i].split(';')[1],code + ';' + Count);                    
                $.cookie('TTLWebSiteCart',cookie, {expires: 7,path:'/'});
                isExisted = true;
                
            }
        }

        if(!isExisted){   
            Cart = Cart.toString();
            Cart += ',' + ProductCode + ';' + ProductQty;                 
            $.cookie('TTLWebSiteCart', Cart, {expires: 7,path:'/'});
        }
        
        $.post('/Account/Handler/ShoppingCart.ashx',{querytype:6,isaddproduct:'T'},
            function(data) {                                 
                 if(data == '-1')
                 {
                    alert('加载促销信息失败，请联系网站管理员。');
                 }                                         
            }) 
    }
    else{
        cookie = new String(ProductCode + ';' + ProductQty);             
        $.cookie('TTLWebSiteCart',cookie, {expires: 7,path:'/'});
        
        $.post('/Account/Handler/ShoppingCart.ashx',{querytype:6,isaddproduct:'T'},
            function(data) {                                 
                 if(data == '-1')
                 {
                    alert('加载促销信息失败，请联系网站管理员。');
                 }                                         
            }) 
    }
    
    var objCartItemsCount = $('#CartItemsTotalCount');
    var cartItemsCount = objCartItemsCount.text().replace("(","").replace(")","");
    objCartItemsCount.text("(" + (parseInt(cartItemsCount) + 1) + ")");
    if(codeNum==""&&codeNum!="0")
    {
        if (confirm('该商品已添加到购物车，总数量为：' + Count + '。\r\n\r\n是否现在查看购物车？'))
        {
            window.location.href='/Account/ShoppingCart.aspx';
        }
    }
    else
    {
        if(codeNum=="0")
        {
            codeNum="";
            if (confirm('所有商品已成功添加到购物车。\r\n\r\n是否现在查看购物车？'))
            {
                window.location.href='/Account/ShoppingCart.aspx';
            } 
        }
    }
};

jQuery.fn.getParmByUrl = function(o){
  var url = window.location.toString();
  var tmp;
  if(url && url.indexOf("?")){
    var arr = url.split("?");
    var parms = arr[1];
    if(parms && parms.indexOf("&")){
      var parmList = parms.split("&");
      jQuery.each(parmList,function(key,val){
        if(val && val.indexOf("=")){
          var parmarr = val.split("=");
          if(o){
            if(typeof(o) == "string" && o == parmarr[0]){
              tmp = parmarr[1] == null?'':parmarr[1];
            }
          }
          else{
            tmp = parms;
          }
        }
      });
    }
  }
  return tmp;
}

// 保存修改后的用户密码
function modifyPassword() {
    
    // 输入内容的有效性验证
    var oldPwd = $.trim($('#OldPwd').val());
    var newPwd = $.trim($('#NewPwd').val());
    var cfmNewPwd = $.trim($('#CfmNewPwd').val());
    
    if (oldPwd == '') {        
        $('#OldPwdMSG').show();
        $('#OldPwd').focus();
        return;
    }
    $('#OldPwdMSG').hide();
    if (newPwd == '') {
         $('#NewPwdMSG').show();       
        $('#NewPwd').focus();
        return;
    }
    if (newPwd.length > 20 || newPwd.length < 6) {
        $('#NewPwdMSG').show();
        $('#NewPwd').val('');
        $('#NewPwd').focus();
        return;
    }
    $('#NewPwdMSG').hide();
    if (cfmNewPwd == '') {
        $('#CfPwdMSG').show();
        $('#CfmNewPwd').val('');
        $('#CfmNewPwd').focus();
        return;
    }
    if (cfmNewPwd != newPwd) {
        $('#CfPwdMSG').show();
        $('#CfmNewPwd').val('');
        $('#CfmNewPwd').focus();
        return;
    }
    $('#CfPwdMSG').hide();


    // 调用AJAX进行保存更新
    $.get("/Account/Handler/LoginPasswordModify.ashx", {OldPassword:oldPwd,NewPassword:newPwd}, function(data){
      if ('-1' == data) {          
          alert('密码修改失败，请重试或联系网站管理员。');
          $("#BtnModify").removeAttr("disabled");
          return;
      } else if ('1' == data) {
          alert('密码修改成功。');
          window.location.href = '/Account/';   
      } else if ('0' == data) {
          alert('原始密码不正确，请重新输入。');
          $("#BtnModify").removeAttr("disabled");
          $("#BtnModify").attr("value","登 录");
          return;
      }
   });
}

// 重置密码
function resetPassword() {
    $('#OldPwd').val('');
    $('#NewPwd').val('');
    $('#CfmNewPwd').val('');
}

// 更新用户信息
function saveCustomerInfo() {
    
    // 获取注册表单信息
    var email = $.trim($("#Email").val());
    var realName = $.trim($("#RealName").val());
    var familyAddr = $.trim($("#FamilyAddr").val());
    var deliverAddr = $.trim($("#DeliveryAddr").val());
    var receiver = $.trim($("#Receiver").val());   
    var city = $.trim($("#City").val());
    var tel = $.trim($("#Tel").val());
    var fax = $.trim($("#Fax").val());
    var mobile = $.trim($("#Mobile").val());   
    var postCode = $.trim($("#PostCode").val());
    var homepage = $.trim($("#Homepage").val());
 
     if ('' == $.trim($("#RealName").val())) {
        alert('请输入个人姓名或称呼。')
        $('#RealName').css("background-color","#FFE9D7");
        $('#RealName').focus();
        return;
    }
    if ('-1' == $.trim($("#City").val())) {
        alert('请选择您所在上海的区。');
        $('#City').css("background-color","#FFE9D7");
        $('#City').focus();
        return;
    }  
           
    if ('' == $.trim($("#Tel").val())) {
        alert('请输入确认订购电话。');
        $('#Tel').css("background-color","#FFE9D7");
        $('#Tel').focus();
        return;
    }
   
    if(!checkTelRegex($.trim($('#Tel').val()))){
        alert("请输入正确的确认订购电话。");
        $('#Tel').attr('value','');
        $('#Tel').css("background-color","#FFE9D7");
        $('#Tel').focus();
        return false;
    } 
    if(''!=$.trim($("#Fax").val())){
       if(!checkTelRegex($.trim($('#Fax').val()))){
        alert("请输入正确的传真。");
        $('#Fax').attr('value','');
        $('#Fax').css("background-color","#FFE9D7");
        $('#Fax').focus();
        return false;
    }
    }  
    if (mobile == '') {
        alert('请输入手机号码。');
        $('#Mobile').css("background-color","#FFE9D7");
        $('#Mobile').focus();
        return;
    }
    if(!checkMobileRegex(mobile)) {
        alert('输入的手机或小灵通号码无效，请重新输入。');
        $('#Mobile').attr('value','');
        $('#Mobile').css("background-color","#FFE9D7");
        $('#Mobile').focus();
        return;
    }    
    if ('' == $.trim($("#PostCode").val())) {
        alert('请输入邮政编码。');
        $('#PostCode').css("background-color","#FFE9D7");
        $('#PostCode').focus();
        return;
    }
 
    if(!checkPostCodeRegex($.trim($('#PostCode').val()))){
        alert("请输入正确的邮政编码。");
        $('#PostCode').attr('value','');
        $('#PostCode').css("background-color","#FFE9D7");
        $('#PostCode').focus();
        return ;
    }  
    
    if (!checkEmail())
        return;
              
    $("#BtnSave").css("color","red");
    $("#BtnSave").attr("disabled","disabled");
    $("#BtnSave").attr("value","保存中,请稍等...");

   $.get("/Account/Handler/CustomerInfoModify.ashx", {Email:email,RealName:realName,
                                  FamilyAddr:familyAddr,City:city,
                                  Tel:tel,Fax:fax,Mobile:mobile,PostCode:postCode,Homepage:homepage}, function(data) { 
        if ('-1' == data) {
            alert('客户资料保存失败，请重试或联系网站管理员。');
            $("#BtnSave").removeAttr("disabled");
            $("#BtnSave").attr("value","保存");
            return;
          } else if ('1' == data) {
              $('#RegStatus').text(""); 
              alert('客户资料保存成功。');
              window.location.href = '/Account/';
          }
      });
}


// 填写配送信息，提交订单。
function PaymentChange(){
        var payment = $('#Payment').val();
        if(payment == 2)
        {
            $('#BankInfo').removeAttr('style');
        }
        else
        {
            $('#BankInfo').hide();
        }
    };

function ShippingChange(totalGoodsValue,isDiscount){
        var shipping = $('#Shipping').val();
        var $selfgetaddr = $('#SelfGetAddr'); 
        var ProductPrice = $('#ProductPrice').val().replace(",","");
        totalGoodsValue = parseFloat(totalGoodsValue) - parseFloat($('#VocherAmount').text());
        
        if(shipping == 1)
        {
            // 显示门店自提地址
            $selfgetaddr.show();
            
            $('#DivDelieryFee').hide();
            $('#Fee1').attr('checked','checked');
            $('#DelieryFee').html("0");
            var DelieryFee = 0;  
            $('#DelieryFee').text('0');
            $('#TotalFee').text(parseFloat(totalGoodsValue).toFixed(2));
        }
        else
        {
            // 隐藏自提门店地址
            $selfgetaddr.hide();
            
            $('#rad1').removeAttr('checked');
            $('#rad2').removeAttr('checked');
            $('#DeliveryCost').hide();
            $('#CountDeliveryCost').hide();
            $('#DeliveryCostMsg').hide();
            $('#DefaultDeliveryCostMsg').show();
            $('#DefaultDeliveryCostMsg').text('请选择以上的送货地所处位置以便计算运费（崇明三岛、金山不在配送范围内）。');
            $('#DivDelieryFee').removeAttr('style');
            $('#Fee3').attr('checked','checked');
            $('#DelieryFee').html("0");
            var DelieryFee = 0;            
            $('#DelieryFee').text('0');
            $('#TotalFee').text(parseFloat(totalGoodsValue).toFixed(2));
        }
    };


// 提交订单
function OrderSubmit(){
        var Shipping = '';
        var Payment = $("input[name='paymenttype'][@type=radio][checked]").val();
        var deliveryType = $("input[name='freightage'][@type=radio][checked]").val();
        var invoiceContent = $("input[name='invoicecontent'][@type=radio][checked]").val();
        var Message = $.trim($('#Message').val());
        var DelieryFee = $('#DelieryFee').text(); 
        var totalGoodsValues = $('#ProductTotalValue').val();
        var invoiceTitle = $.trim($('#invoicetitle').val());
        
        // 根据配送方式设定订单类型
        if ('-1' == deliveryType)
            Shipping = '1';     // 自提订单
        else
            Shipping = '0';     // 普通订单
            
        // 如果是送货上门，则对以下规则进行判断。
        if (deliveryType == null || 'undefined' == deliveryType) {
            if (parseFloat(totalGoodsValues) < 150) {
                alert('请选择送货地所处位置，以便计算运费。');
                return;
            }       
        }
        
        if($('#SelectContact').val() == null){
            alert('没有联系人不能提交订单，请先添加联系人。');
            AddContactInfo();
            return false;
        }

        $('#SaveOrderButtonWait').show();
        $('#SaveOrderButton').hide(); 
        
        var voucherNo = '0';
        if (null != $("input[name='rdVoucher']:checked").val())
            voucherNo = $("input[name='rdVoucher']:checked").val().split('{')[1];
        
        $.post('/Account/Handler/DistriButable.ashx',
            {ContactInfo:$('#SelectContact').val(),Shipping:Shipping,DelieryFee:DelieryFee,
            Payment:Payment,Message:Message,Voucher:voucherNo,Recommended:$('#Recommended').val(),
            InvoiceTitle:invoiceTitle,InvoiceContent:invoiceContent},
            function(data) {                        
             if(data == '-1')
             {
                //alert('订单提交失败。');
                location.href='/Account/OrderFailure.aspx';               
             }
             else if(data == '-999')
             {
                alert('您选择的限时抢购商品已抢完。');
                
                location.href='/Account/ShoppingCart.aspx';
             }
             else if(data == '-998')
             {
                alert('您今天已经购买过限时抢购商品，一天内只能购买一个限时抢购商品。');
                
                location.href='/Account/ShoppingCart.aspx';
             }
             else
             {
                location.href='/Account/OrderSuccess.aspx?OrderID=' + data + '#Bottom';
             };
        });
    }

// 根据商品索引来获取商品品牌    
function showBrand(brandIndex) {
    var x = document.body.scrollLeft+event.clientX;
    var y = document.body.scrollTop+event.clientY;
    
    $('#ShowBrand').css({padding:"5px",position: "absolute",left:x+10,top:y+10,width:"300px",height:"200px",border: "1px solid #0C8869",background:"#fff"});
    $('#ShowBrand').css("filter","alpha(opacity=93,style=1)");
    $('#ShowBrand').css("opacity","0.93");
    $('#ShowBrand').css("color","red");
    
    $.get("/Product/Handler/ShowBrands.ashx", {Brand:brandIndex}, function(data) {
        var $apdiv = $('#apDiv1');
        $apdiv.hide();
        $('#ShowBrand').show();
        $('#ShowBrand').html(data);
    });
}

// 隐藏品牌显示
function hiddenBrand() {
    var $apdiv = $('#apDiv1');
    $('#ShowBrand').hide();
    $apdiv.show();
}

// 新增问题
function insertNewQuestion() {
    var question = $.trim($('#NewQuestion').val());
    if ('' == question) {
        alert('请填写提问内容。');
        $('#NewQuestion').focus();
        return;
    }
    $('#BtnNewQuestion').attr('disabled','disabled');
    $.get("/Professor/Handler/QuestionInsert.ashx", {Question:question}, function(data) {
        if (0 < data) {
            $('#BtnNewQuestion').removeAttr('disabled');
            $('#NewQuestion').val('');
            alert('提问新增成功。');
            //getSingleQuestion(data);
            window.location.reload();
            
        } else if ('0' == data) {
            $('#BtnNewQuestion').removeAttr('disabled');
            $('#NewQuestion').val('');
            $('#NewQuestion').focus();
            alert('提问新增失败。');
        } else {
            $('#BtnNewQuestion').removeAttr('disabled');
            $('#NewQuestion').val('');
            $('#NewQuestion').focus();
            alert('提问新增失败，请重试或者联系网站管理员。');
        }
    });  
}

// 获取所有问题
function getAllQuestion() {
    $.get("/Professor/Handler/GetAllQuestion.ashx",function(data) {
        if ('' != data){
            $('#QuestionContent').html(data);
        }
    }); 
}

// 获取单个问题
function getSingleQuestion(questionId) {
    $.get("/Professor/Handler/GetSingleQuestion.ashx", {QuestionId:questionId}, function(data) {
        $(data).insertBefore('#QuestionBottom');
    }); 
}

// 根据关键字查询问答
function doQuestionSearch() {
    var keyWords = $('#QuestionKeywords').val();
    $.get("/Professor/Handler/GetQuestionByKeywords.ashx", {QuestionKeywords:keyWords}, function(data) {
        $('#QuestionContent').html(data);
    });  
}

// 清除问题关键字输入框
function clearQuestionKeywords() {
    $('#QuestionKeywords').val('');
}

//新增送货地址
function adddeliveryaddress() {
    var deliverAddr = $.trim($("#DeliverAddr").val());   
    var tel = $.trim($("#Tel").val());
    var fax = $.trim($("#Fax").val());   
    var postCode = $.trim($("#PostCode").val());  
      
    if ('' == $.trim($("#DeliverAddr").val())) {
        alert('请输入收货地址。');
        $('#DeliverAddr').css("background-color","#FFE9D7");
        $('#DeliverAddr').focus();
        return;
    } 
     if ( $.trim($("#DeliverAddr").val()).length>50) {
        alert('地址小于等于50个字符。');
        $('#DeliverAddr').css("background-color","#FFE9D7");
        $('#DeliverAddr').focus();
        return;
    } 
     if ('' == $.trim($("#PostCode").val())) {
        alert('请输入邮政编码。');
        $('#PostCode').css("background-color","#FFE9D7");
        $('#PostCode').focus();
        return;
    } 
    
    if(!checkPostCodeRegex($.trim($('#PostCode').val()))){
        alert("请输入正确的邮政编码。");
        $('#PostCode').attr('value','');
        $('#PostCode').css("background-color","#FFE9D7");
        $('#PostCode').focus();
        return ;
    } 
    if ('' == $.trim($("#Tel").val())) {
        alert('请输入固定电话或手机或小灵通号码。');
        $('#Tel').css("background-color","#FFE9D7");
        $('#Tel').focus();
        return;
    } 
    
    if(!checkTelRegex(tel)){      
        var mobile = $.trim($("#Tel").val());   
        if(!checkMobileRegex(mobile)) {
            alert('输入的固定电话或手机或小灵通号码无效，请重新输入。');
            $('#Tel').attr('value','');
            $('#Tel').css("background-color","#FFE9D7");
            $('#Tel').focus();
            return ;
         } 
    } 
    
    if(''!=$.trim($("#Fax").val())){
       if(!checkTelRegex($.trim($('#Fax').val()))){
            alert("请输入正确的传真。");
            $('#Fax').attr('value','');
            $('#Fax').css("background-color","#FFE9D7");
            $('#Fax').focus();
            return false;
       }
    }       
   
    $('#BtnReset').css("visibility","hidden");
    $('#ButtonOK').css("background-color","#F3F3F3");
    $('#ButtonOK').attr("value","送货地址添加中，请稍等。。。")
    $('#ButtonOK').attr("disabled","disabled");
    
    // 获取注册表单信息   
  $.get("/Account/Handler/AddDeliveryAddress.ashx", {DeliverAddr:deliverAddr,Tel:tel,Fax:fax,PostCode:postCode}, function(data){
    if ('-1' == data) {          
          alert('添加失败，请重试或联系网站管理员。');
          $("#ButtonOK").removeAttr("disabled");
          $("#BtnReset").css("visibility","visible");
          return;
      } else if ('1' == data) {
          alert('添加成功。');
          window.location.href = '/Account/AddressList.aspx';   
      } 
   });
}

//修改送货地址
function updateDeliveryAddress() {
    var deliverAddr = $.trim($("#DeliverAddr").val());   
    var tel = $.trim($("#Tel").val());
    var fax = $.trim($("#Fax").val());   
    var postCode = $.trim($("#PostCode").val()); 
    
    if ('' == $.trim($("#DeliverAddr").val())) {
        alert('请输入收货地址。');
        $('#DeliverAddr').css("background-color","#FFE9D7");
        $('#DeliverAddr').focus();
        return;
    } 
    if ( $.trim($("#DeliverAddr").val()).length>50) {
        alert('地址小于等于50个字符。');
        $('#DeliverAddr').css("background-color","#FFE9D7");
        $('#DeliverAddr').focus();
        return;
    }  
     if ('' == $.trim($("#PostCode").val())) {
        alert('请输入邮政编码。');
        $('#PostCode').css("background-color","#FFE9D7");
        $('#PostCode').focus();
        return;
    } 
      
    if(!checkPostCodeRegex($.trim($('#PostCode').val()))){
        alert("请输入正确的邮政编码。");
        $('#PostCode').attr('value','');
        $('#PostCode').css("background-color","#FFE9D7");
        $('#PostCode').focus();
        return ;
    }  
    if ('' == $.trim($("#Tel").val())) {
        alert('请输入固定电话或手机或小灵通号码。');
        $('#Tel').css("background-color","#FFE9D7");
        $('#Tel').focus();
        return;
    }
    
    if(!checkTelRegex(tel)){
        var mobile = $.trim($("#Tel").val());      
        if(!checkMobileRegex(mobile)) {
            alert('输入的固定电话或手机或小灵通号码无效，请重新输入。');
            $('#Tel').attr('value','');
            $('#Tel').css("background-color","#FFE9D7");
            $('#Tel').focus();
            return ;
         } 
     }
    
    if(''!=$.trim($("#Fax").val())){
       if(!checkTelRegex($.trim($('#Fax').val()))){
           alert("请输入正确的传真。");
           $('#Fax').attr('value','');
           $('#Fax').css("background-color","#FFE9D7");
           $('#Fax').focus();
           return false;
       }
    }
    
    $('#BtnReset').css("visibility","hidden");
    $('#ButtonOK').css("background-color","#F3F3F3");
    $('#ButtonOK').attr("value","送货地址更改中，请稍等。。。")
    $('#ButtonOK').attr("disabled","disabled");
    
    // 获取注册表单信息
    var deliverAddr = $.trim($("#DeliverAddr").val());   
    var tel = $.trim($("#Tel").val());
    var fax = $.trim($("#Fax").val());   
    var postCode = $.trim($("#PostCode").val());        
  
  $.get("/Account/Handler/UpdateDeliveryAddress.ashx", {DeliverAddr:deliverAddr,Tel:tel,Fax:fax,PostCode:postCode}, function(data){
    if ('-1' == data) {          
          alert('更改失败，请重试或联系网站管理员。');
          $("#ButtonOK").removeAttr("disabled");
          $("#BtnReset").css("visibility","visible");
          return;
      } else if ('1' == data) {
          alert('更改成功。');
          window.location.href = '/Account/AddressList.aspx';   
      } 
   });
}

//新增联系人
function addContact() {
    
    if ('' == $.trim($("#FullName").val())) {
        alert('请输入联系人姓名。');
        $('#FullName').css("background-color","#FFE9D7");
        $('#FullName').focus();
        return;
    }  
      if ( $.trim($("#FullName").val()).length>20) {
        alert('联系人姓名小于等于20个字符。');
        $('#FullName').css("background-color","#FFE9D7");
        $('#FullName').focus();
        return;
    }   
    
    if ('' != $.trim($("#Tel").val())) {
        if(!checkTelRegex($.trim($('#Tel').val()))){
            alert("请输入正确的固定电话。");
            $('#Tel').val('');
            $('#Tel').css("background-color","#FFE9D7");
            $('#Tel').focus();
            return false;
        } 
    }
    if(''!=$.trim($("#Fax").val())){
       if(!checkTelRegex($.trim($('#Fax').val()))){
           alert("请输入正确的传真。");
           $('#Fax').val('');
           $('#Fax').css("background-color","#FFE9D7");
           $('#Fax').focus();
           return false;
       }
    }
    
    if ('' == $.trim($("#Mobile").val())) {
        alert('请输入手机号码。');
        $('#Mobile').css("background-color","#FFE9D7");
        $('#Mobile').focus();
        return;
    }
      
    var mobile = $.trim($("#Mobile").val());        
    if(!checkMobileRegex(mobile)) {
        alert('输入的手机或小灵通号码无效，请重新输入。');
        $('#Mobile').attr('value','');
        $('#Mobile').css("background-color","#FFE9D7");
        $('#Mobile').focus();
        return;
    }     
    
     if('' != $.trim($("#Email").val())){
     if ($.trim($("#Email").val()).length>50) {
        alert('Email内容小于等于50个字符。');
        $('#Email').css("background-color","#FFE9D7");
        $('#Email').focus();
        return;
    }         
   
    if(!checkEmailRegex($.trim($("#Email").val()))) {
        alert('请输入有效的E-mail地址。');
        $('#Email').css("background-color","#FFE9D7");
        $('#Email').select();
        return false;
    }    
    }
    $('#BtnReset').css("visibility","hidden");
    $('#ButtonOK').css("background-color","#F3F3F3");
    $('#ButtonOK').attr("value","送货地址添加中，请稍等。。。")
    $('#ButtonOK').attr("disabled","disabled");
    
    // 获取注册表单信息
   
    var fullName = $.trim($("#FullName").val());   
    var tel = $.trim($("#Tel").val());
    var fax = $.trim($("#Fax").val());   
    var mobile = $.trim($("#Mobile").val()); 
    var email = $.trim($("#Email").val());      
   
   var sex ='';
    if ($("#SexMale").attr("checked"))
        sex = 'M';
    else if ($("#SexFmale").attr("checked"))
        sex = 'F';
    else
        sex = 'F';
        
  $.get("/Account/Handler/AddContact.ashx", {FullName:fullName,Tel:tel,Fax:fax,Mobile:mobile,Email:email,Sex:sex}, function(data){
    if ('-1' == data) {          
          alert('添加失败，请重试或联系网站管理员。');
          $("#ButtonOK").removeAttr("disabled");
          $("#BtnReset").css("visibility","visible");
          return;
      } else if ('1' == data) {
          alert('添加成功。');
          window.location.href = '/Account/ContactList.aspx';   
      } 
   });
}

//修改联系人
function updateContact() {
    
    if ('' == $.trim($("#FullName").val())) {
        alert('请输入联系人姓名。');
        $('#FullName').css("background-color","#FFE9D7");
        $('#FullName').focus();
        return;
    }  
     if ( $.trim($("#FullName").val()).length>20) {
        alert('联系人姓名小于等于20个字符。');
        $('#FullName').css("background-color","#FFE9D7");
        $('#FullName').focus();
        return;
    } 
    
    if ('' != $.trim($("#Tel").val())) {
        if(!checkTelRegex($.trim($('#Tel').val()))){
            alert("请输入正确的固定电话。");
            $('#Tel').val('');
            $('#Tel').css("background-color","#FFE9D7");
            $('#Tel').focus();
            return false;
        } 
    }
    
    if(''!=$.trim($("#Fax").val())){
       if(!checkTelRegex($.trim($('#Fax').val()))){
           alert("请输入正确的传真。");
           $('#Fax').val('');
           $('#Fax').css("background-color","#FFE9D7");
           $('#Fax').focus();
           return false;
       }
    }
    if ('' == $.trim($("#Mobile").val())) {
        alert('请输入手机号码。');
        $('#Mobile').css("background-color","#FFE9D7");
        $('#Mobile').focus();
        return;
    }  
    var mobile = $.trim($("#Mobile").val());
    if(!checkMobileRegex(mobile)) {
        alert('输入的手机或小灵通号码无效，请重新输入。');
        $('#Mobile').attr('value','');
        $('#Mobile').css("background-color","#FFE9D7");
        $('#Mobile').focus();
        return;
    }    
    if('' != $.trim($("#Email").val())){    
        if ($.trim($("#Email").val()).length>50) {
            alert('Email内容小于等于50个字符。');
            $('#Email').css("background-color","#FFE9D7");
            $('#Email').focus();
            return;
        }     
        if(!checkEmailRegex($.trim($("#Email").val()))) {
            alert('请输入有效的E-mail地址。');
            $('#Email').css("background-color","#FFE9D7");
            $('#Email').select();
            return false;
        }    
    }
    
    $('#BtnReset').css("visibility","hidden");
    $('#ButtonOK').css("background-color","#F3F3F3");
    $('#ButtonOK').attr("value","联系人修改中，请稍等。。。")
    $('#ButtonOK').attr("disabled","disabled");
    
    // 获取注册表单信息
    var fullName = $.trim($("#FullName").val());   
    var tel = $.trim($("#Tel").val());
    var fax = $.trim($("#Fax").val());   
    var mobile = $.trim($("#Mobile").val());
    var email = $.trim($("#Email").val());       
  
    var sex ='';
    if ($("#radMale").attr("checked"))
        sex = 'M';
    else if ($("#radFamle").attr("checked"))
        sex = 'F';
    else
        sex = 'F';        
  $.get("/Account/Handler/UpdateContact.ashx", {FullName:fullName,Tel:tel,Fax:fax,Mobile:mobile,Email:email,Sex:sex}, function(data){
    if ('-1' == data) {          
          alert('修改失败，请重试或联系网站管理员。');
          $("#ButtonOK").removeAttr("disabled");
          $("#BtnReset").css("visibility","visible");
          return;
      } else if ('1' == data) {
          alert('修改成功。');
          window.location.href = '/Account/ContactList.aspx';   
      } 
   });
}

// 计算订单运费
function calcDeliveryCost (calcType,orderSum,isDiscount) {
    var objCountDeliveryCost = $('#CountDeliveryCost');
    var objDefaultDeliveryCostMsg = $('#DefaultDeliveryCostMsg');
    var orderSum = parseFloat(orderSum.replace(",",""));
    var objDelieryFee = $('#DelieryFee');
    var objTotalFee = $('#TotalFee');
    
    objDefaultDeliveryCostMsg.hide();
    
    if ('0' == calcType || '2' == calcType || '3' == calcType) {
        if (orderSum >= 50 || '2' == calcType || '3' == calcType) {
            $('#DelieryFee').text('0');
            orderSum = parseFloat(orderSum) - parseFloat($('#VocherAmount').text());
            $('#TotalFee').text(parseFloat(orderSum).toFixed(2));
            objCountDeliveryCost.show();
            objCountDeliveryCost.text('￥0.00');

        } else {
            $('#DelieryFee').text('5.00');
            orderSum = parseFloat(orderSum) - parseFloat($('#VocherAmount').text());
            $('#TotalFee').text((parseFloat(orderSum)+5).toFixed(2));
            objCountDeliveryCost.show();
            objCountDeliveryCost.text('￥5.00');
            objDelieryFee.text('5.00');
        }
    } else if ('1' == calcType) {
        if (orderSum >= 150) {
            $('#DelieryFee').text('0');
            orderSum = parseFloat(orderSum) - parseFloat($('#VocherAmount').text());
            $('#TotalFee').text(parseFloat(orderSum).toFixed(2));
            objCountDeliveryCost.show();
            objCountDeliveryCost.text('￥0.00');
        } else {
            $('#DelieryFee').text('10.00');
            orderSum = parseFloat(orderSum) - parseFloat($('#VocherAmount').text());
            $('#TotalFee').text((parseFloat(orderSum)+10).toFixed(2));
            objCountDeliveryCost.text('￥10.00');
            objDelieryFee.text('10.00');
        }
    }
}




