﻿//Cart.addBy(id,num);增加num个

//Cart.updateTo(id,num);增加至num个

//Cart.remove(id);移除

//Cart.getAll();
//返回一个数组，每个数组元素是一个object类型数据{id:'A100',num:5,addedTime:'2009-12-1 14:20'}

//Cart.clearAll();

//cookie 格式：1000,5,2009-12-05 15:20&1005,1,2009-09-01 09:24
//cookie 过期：一年

/*购物js,处理cookie用，小强写*/
/*
2010.08.03
增加type:1 普通商品，2 换购商品
2010.08.10
增加promoId:换购商品参加的活动id
cookie格式：{id,sid,num,date,type,promoId}
*/
Cart = {
    /*获得购物袋中多规格同一产品的总数*/
    getNumById: function (id) {
        var realVar = 0, ls = Cart.getAll(),
        k = ls.length - 1;
        for (; k > -1; k--) {
            if (ls[k]['id'] == id && ls[k]['type'] == 1) {/*换购商品不参与限购*/
                realVar += ls[k]['num'];
            }
        }
        return realVar;
    },
    addBy: function (id, sid, num, flag, type, promoId) {/*增加换购活动id*/
        type = type || 1;
        promoId = promoId || 0;
        var num = parseInt(num, 10),
        ls = Cart.getAll(),
        k = ls.length - 1;
        for (; k > -1; k--) {
            if (ls[k]['sid'] == sid && ls[k]['type'] == type) {
                if (flag) {
                    ls[k]['num'] = num;
                } else {
                    ls[k]['num'] += num;
                }
                break;
            }
        }
        if (k >= 0) {
            if (!Cart._isAllowedQuantity(ls[k]['num'])) {
                //Cart._updateCartTop(0);
                return false;
            }
            if (ls[k]['num'] <= 0) {
                Array.prototype.splice.call(ls, k, 1);
            }
        } else {
            if (num > 0) {
                if (!Cart._isAllowedQuantity(num)) {
                    //Cart._updateCartTop(0);
                    return;
                }
                var dt = new Date(),
                year = dt.getFullYear(),
                month = '0' + (dt.getMonth() + 1),
                day = '0' + dt.getDate(),
                hours = '0' + dt.getHours(),
                minutes = '0' + dt.getMinutes();
                seconds = '0' + dt.getSeconds();
                month = month.substr(month.length - 2);
                day = day.substr(day.length - 2);
                minutes = minutes.substr(minutes.length - 2);
                hours = hours.substr(hours.length - 2),
                seconds = seconds.substr(seconds.length - 2),
                t = [[year, month, day].join('-'), [hours, minutes, seconds].join(':')].join(' '),
                p = {
                    id: id,
                    sid: sid,
                    num: num,
                    addedTime: t,
                    type: type,
                    promoId: promoId
                };
                Array.prototype.unshift.call(ls, p);
            } else {
                //Cart._updateCartTop(0);
                return;
            }
        }
        Cart._flush(ls);

    },
    updateTo: function (id, sid, num, flag, type, promoId) {
        flag = flag || true;
        type = type || 1;
        promoId = promoId || 0;
        Cart.addBy(id, sid, num, flag, type, promoId);
    },
    remove: function (id, sid, type) {
        type = type || 1;
        Cart.updateTo(id, sid, 0, true, type);
    },
    getAll: function () {
        var c = $.cookie('C'),
        ls = [];
        if (c) {
            var ps = c.split('&'),
            p = [];
            for (var i = ps.length - 1; i > -1; i--) {
                p = ps[i].split(',');
                Array.prototype.unshift.call(ls, {
                    id: p[0],
                    sid: p[1],
                    num: parseInt(p[2], 10),
                    addedTime: p[3],
                    type: p.length >= 5 ? parseInt(p[4]) : 1, /*兼容换购前cookie格式  >=*/
                    promoId: p.length == 6 ? parseInt(p[5]) : 0
                });
            }
        }
        return ls;
    },
    clearAll: function () {
        $.cookie('C', null, -1, '/');
    },
    _flush: function (ls) {
        var ps = [];
        for (var i = ls.length - 1; i > -1; i--) {
            Array.prototype.unshift.call(ps, [ls[i]['id'], ls[i]['sid'], ls[i]['num'], ls[i]['addedTime'], ls[i]['type'], ls[i]['promoId']].join(','));
        }
        if (ps.length === 0) {
            Cart.clearAll();
        } else {
            $.cookie('C', ps.join('&'), 365, '/'); //,'.yobrand.com'
        }
        Cart._updateCartTop(ls.length);
    },
    _isAllowedQuantity: function (num) {
        var r = true;
        if (num > 10) {
            alert('每件商品的购买量不能超过10件!');
            r = false;
        }
        return r;
    },
    _updateCartTop: function (len) {
        var spCartCountTop = $("#spCartCountTop");
        if (spCartCountTop != null) {
            if (len == 0) {
                $("#spCartImgTop").html("购物袋");
                $("#spCartImgTop").attr("class", "cart")
            } else {
                $("#spCartImgTop").html("购物袋(<span id='spCartCountTop' class='cnum'>" + len + "</span>)");
                $("#spCartImgTop").attr("class", "cartfull")
            }
        }
    }
};

addNameSpace("Ac.Product");

addNameSpace("Ac.Product.SelectSpecProcessorInstance");

//Ac.Product.CartInfo.addByPid(pid);列表方法 购买

//Ac.Product.CartInfo.addFavorByPid(pid);列表方法 收藏

//Ac.Product.CartInfo.addBySaleNo(pid,saleNo,num);购买单个规格产品

//Ac.Product.CartInfo.addByBound(str);购买绑定产品

//Ac.Product.CartInfo.addFavor(pid,gid);加入收藏

Ac.Product.CartInfo = function () {

    var _CartInfo = function () {
        var initialized = false;
        var bag = null; /*购物袋容器引用*/
        var mycart = null; /*页面顶端购物袋商品数量元素引用*/
        var ybmycart = null;
        /*购物袋*/
        var html = "<div class='gray_bg'></div>" +
            "<div class='shoppingbag' id='shoppingbag'>" +
                "<div class='bagtop'>" +
                    "<div class='top_mid fl'></div>" +
                    "<div class='top_right fl'></div>" +
                "</div>" +
                "<div class='mid'>" +
                    "<div class='mid_cont' id='DetailCart'> " +
                    "</div>" +
                "</div>" +
                "<div class='btm'>" +
                    "<div class='btm_mid fl'></div>" +
                    "<div class='btm_right fl'></div>" +
                "</div>" +
                "<img src='" + Ac.Config.WebStaticServer + "/content/site/images/close.gif' class='close_bag' />" +
            "</div>";
        /*选择规格*/
        var html2 = "<div class='shoppingbag2' id='shoppingbag2'> " +
             "   <div class='bagtop'> " +
              "      <div class='top_mid fl'></div> " +
               "     <div class='top_right fl'></div> " +
                "</div> " +
                "<div class='mid'> " +
                 "   <div class='mid_cont' id='DetailCart2'> " +
                   " </div> " +
               " </div> " +
               " <div class='btm'> " +
               "     <div class='btm_mid fl'></div> " +
               "     <div class='btm_right fl'></div> " +
               " </div> " +
               " <img src='" + Ac.Config.WebStaticServer + "/content/site/images/close.gif' class='close_bag' /> " +
           " </div>";

        /*初始化*/
        var initialize = function () {
            if (initialized == false) {

                $(document.body).prepend(html);

                $(document.body).prepend(html2);

                bag = $("#DetailCart");

                mycart = $("#mycart");

                ybmycart = $("#yb_my_cart");

                initialized = true;

                html = null;

                html2 = null;

            }
        };
        this.PopDiv = function (html) {
            if (!initialized) initialize();
            $("#DetailCart").html("<p>提示：</p><div>" + html + "</div>");

            pop();

        };
        /*列表方法 购买*/
        this.addByPid = function (pid, googlebuttontrack) {
            if (!pid) return;
            if (!initialized) initialize();
            this.showSpecSelect(pid, true);

            this.googlebuttontrack = googlebuttontrack || null;
        };
        this.googlebuttontrack = null;
        /*列表方法 收藏*/
        this.addFavorByPid = function (pid, node) {
            if (!pid) return;
            if (Ac.Page.IsLogin == undefined) return;
            if (!Ac.Page.IsLogin) {
                //alert("请先登录");
                if (location.href.indexOf("msn.yobrand.com") != -1 || location.href.indexOf("shop.msn.com.cn") != -1) {
                    location.href = "https://ids.msn.com.cn/rpsservice/signin.aspx?c=1001&v=1000&rt=http://www.yobrand.com&o=" + location.href;
                } else { quickLogin(); }
                return;
            }
            if (!initialized) initialize();
            this.showSpecSelect(pid, false, node);
        };
        /*防止多次点击换购产品购买多件*/
        this.addTradeIning = false;
        /*购买换购商品*/
        this.addTradeIn = function (pid, saleNo, promoId) {
            if (this.addTradeIning) return;
            this.addTradeIning = true;
            Cart.addBy(pid, saleNo, 1, false, 2, promoId);
            if (this.OnaddBySaleNo != null) {
                this.OnaddBySaleNo();
            } else {
                location = location;
            }
        };
        /*购物袋页面购买最近浏览的商品，不弹出购物袋层，此处特殊处理，单例方法一个页面只能处理一种情况，有多种情况再修改*/
        this.OnaddBySaleNo = null;
        /*购买单个规格产品 详细页面方法
        eg:pid,saleNo,num
        */
        this.addBySaleNo = function (pid, saleNo, num) {//alert(pid);alert(saleNo);alert(num)
            if (!pid || !saleNo) return;
            if (!initialized) initialize();
            Cart.addBy(pid, saleNo, num || 1);

            if (this.OnaddBySaleNo != null) {
                this.OnaddBySaleNo();
            } else {
                showCart();
            }
            //

            /*如果没有设置googlebuttontrack，则从当前路径中取参数*/
            if (this.googlebuttontrack == null) {
                if (location.href.toLowerCase().indexOf("/brand/") > -1) {
                    this.googlebuttontrack = "brand";
                }
                else if (location.href.toLowerCase().indexOf("/products/") > -1) {
                    this.googlebuttontrack = "products";
                }
                else if (location.href.toLowerCase().indexOf("/product/") > -1) {
                    this.googlebuttontrack = "product";
                }
                else if (location.href.toLowerCase().indexOf("/promotion/") > -1) {
                    this.googlebuttontrack = "promotion";
                }
            }
            if (this.googlebuttontrack != null) {
                pageTracker._trackPageview("/" + this.googlebuttontrack + '/button/addcart');
            }
            //监控脚本
            var scriptDom = document.createElement("script");
            scriptDom.src = "http://acs86.com/v.htm?pv=2&sp=45154,13668,0,61,0,0,0&cb=" + (new Date()).getTime();
            var headDom = document.getElementsByTagName("head").item(0);
            headDom.appendChild(scriptDom);
        };
        /*购买绑定产品 详细页面方法
        eg:pid,saleNo,num:pid,saleNo,num
        */
        this.addByBound = function (str) {
            if (!str || str == "") return;
            if (!initialized) initialize();
            var p = str.split(':');
            if (!p || p.length == 0) return;
            for (var i = 0; i < p.length; i++) {
                var pt = p[i].split(',');
                if (!pt || pt.length != 3) return;
                var productId = pt[0];
                var saleNo = pt[1];
                var num = pt[2];

                Cart.addBy(productId, saleNo, num);
            }
            showCart();
        };
        /*加入收藏  详细页面方法*/
        this.addFavor = function (ele, pid, gid) {
            /*首先判断需要登录*/
            if (Ac.Page.IsLogin == undefined) return;
            if (!Ac.Page.IsLogin) {
                //alert("请先登录");
                if (location.href.indexOf("msn.yobrand.com") != -1 || location.href.indexOf("shop.msn.com.cn") != -1) {
                    location.href = "https://ids.msn.com.cn/rpsservice/signin.aspx?c=1001&v=1000&rt=http://www.yobrand.com&o=" + location.href;
                } else { quickLogin(); }

                return;
            }

            /*兼容详细页面的另一种收藏方法，只穿入当前元素，为了解决ie8下，参数中使用GetDetailObj().productId，GetDetailObj()中return;时仍然弹出脚本错误*/
            if (arguments.length == 1) {
                var obj = Ac.Product.AtrribProcessor.GetDetailObj(true);
                if (obj != null) {
                    pid = obj.productId;
                    gid = obj.productGroupId;
                }
            }
            if (!pid) return; //gid可以等于0
            Ac.Common.Tip.Favorite.Ele = ele;
            var _this = this;
            ajaxFavor(pid, gid, function (data) {
                Ac.Common.Tip.Favorite.Show(data, { left: -100, top: -95 });
            });

        };
        /*加入收藏 购物袋页面方法*/
        this.addFavor2 = function (pid, gid, saleNo, onsucess) {
            if (!pid) return; //gid可以等于0
            if (Ac.Page.IsLogin == undefined) return;
            if (!Ac.Page.IsLogin) {
                alert("请先登录");
                return;
            } else {
                //加入到收藏中
                ajaxFavor(pid, gid);
                Cart.remove(pid, saleNo);
                if (!!onsucess) onsucess();
            }
        };
        this.insertFavor = function (pid, gid, node) {
            Ac.Common.Tip.Favorite.Ele = node;
            var _this = this;
            ajaxFavor(pid, gid, function (data) {
                Ac.Common.Tip.Favorite.Show(data, { left: -100, top: -95 });
            });
        };
        var ajaxFavor = function (pid, gid, func) {

            $.post("/Views/Handle/Favorite.ashx".randomUrl(), { "type": "savefavorite", "ProductId": pid, "GroupId": gid }, function (data) {
                Ac.Common.Tip.Favorite.productId = pid;
                if (!!func)
                    func(data);
            }
            );
        };
        /*购物袋*/
        var showCart = function () {
            if (bag == null) return;
            bag.load("/Views/Shared/syn_prod_cartinfo.aspx".randomUrl(), null, function () {
                pop();
            });
        }

        /*弹出 购物袋 层 和其他层*/
        var pop = function () {
            if ($('.shoppingbag').height() > $(window).height())
            { $('.shoppingbag').css({ "top": 0 + $(document).scrollTop() }); }
            else { $('.shoppingbag').css({ "top": parseInt(($(window).height() - $('.shoppingbag').height()) / 2) + $(document).scrollTop() }); }
            $('.gray_bg').css('height', document.documentElement.scrollHeight);
            $('.shoppingbag').show();
            $('.gray_bg').show();
            $("select").hide();
            $('.close_bag,.closebtn', "#shoppingbag").click(function () {
                $('.shoppingbag').hide();
                $('.gray_bg').hide();
                $("select").show();
            });
        };
        /*弹出 选择规格 层*/
        var pop2 = function () {
            if ($('.shoppingbag2').height() > $(window).height())
            { $('.shoppingbag2').css({ "top": 0 + $(document).scrollTop() }); }
            else { $('.shoppingbag2').css({ "top": parseInt(($(window).height() - $('.shoppingbag2').height()) / 2) + $(document).scrollTop() }); }
            $('.gray_bg').css('height', document.documentElement.scrollHeight);
            $('.shoppingbag2').show();
            $('.gray_bg').show();

            $('.close_bag,.closebtn', "#shoppingbag2").click(function () {
                $('.shoppingbag2').hide();
                $('.gray_bg').hide();
            });
        };
        /*选择规格*/
        this.showSpecSelect = function (pid, isbuy, node) {
            var _this = this;
            $.getJSON("/Views/Handle/GetSpecInfo.ashx".randomUrl(), { pid: pid }, function (detailObj) {

                if (detailObj == null) return;

                detailObj.productName = unescape(detailObj.productName);
                /*建立规格选择实例*/
                if (isbuy) {
                    Ac.Product.SelectSpecProcessor.CreateBuy(detailObj);
                } else {
                    Ac.Product.SelectSpecProcessor.CreateFavor(detailObj, node);
                }

                /*如果是多规格，弹出规格选择层*/
                if (detailObj.ismulti) {

                    pop2();

                } else {/*无规格则直接购买或收藏*/
                    if (isbuy) {
                        var inventory = Ac.Product.SelectSpecProcessorInstance.td[0].Repertory;
                        var mydetailObj = Ac.Product.SelectSpecProcessorInstance.GetDetailObj();
                        if (inventory <= 0) {
                            Ac.Product.StockRegist.addStockregist(mydetailObj.productId, mydetailObj.productSaleNumber, "", mydetailObj.userEmail, true);
                        } else {
                            var canbuy = Ac.Product.SelectSpecProcessorInstance.IsInRange();
                            if (canbuy) {
                                _this.addBySaleNo(Ac.Product.SelectSpecProcessorInstance.GetDetailObj().productId, Ac.Product.SelectSpecProcessorInstance.GetDetailObj().productSaleNumber, 1);
                            }
                        }
                    } else {
                        _this.insertFavor(Ac.Product.SelectSpecProcessorInstance.GetDetailObj().productId, Ac.Product.SelectSpecProcessorInstance.GetDetailObj().productGroupId, node);
                    }
                }

            });

        };
        /*更新页面头部购物袋中商品的数量*/
        this.Update = function (num) {
            if (!initialized) initialize();
            mycart.text(num);
            ybmycart.text(num);
            $("#mycart2").text(num);
        }
    }

    var cartinfo = new _CartInfo();
    return cartinfo;
} ();


/*缺货登记，弹出层*/
Ac.Product.StockRegist = function () {
    var _StockRegist = function () {
        var initialized = false;
        /*选择规格*/
        var htmlyodu = "";
        var bz = true;
        /*初始化*/
        var initialize = function (pid, saleno, webtype, userEmail, type) {
            if (initialized == false) {
                var htmlmsn = "<div class='bf_wrap' id='stockcontent' style='display:none'><table cellpadding='0' cellspacing='0' class='note_box buhuo' >" +
                                "<tr><td class='nb_lt'><span class='cross_nb' id='closeDiv' style='height:0px'><img src='/content/site/images/cross_fb.gif' /></span>" +
                                "<div class='nb_con' id='stockinfo' style=''><h4 >如果该商品到货，我们会通过手机短信或邮件通知您</h4>" +
                                "<div class='yl_form'><div class='formline' ><label>邮箱地址：</label><div><input  class='fm_ipt'  type='text' id='txtemail' /> " +
                                "<i id='emailsummary'></i></div></div><div class='formline' ><label>手机号码：</label><div><input style='width:120px;' class='fm_ipt'  type='text' id='txtphone' /> " +
                                "<i id='phonesummary'></i></div></div><div class='formline' ><label>验证码：</label><div>" +
                                "<input style='width:120px;' class='fm_ipt'  type='text' id='txtcode' name='checkCode' /> " +
                                "<img id='validateCodePic' src='/views/shared/syn_verificationpicture.aspx' alt='error' style='height: 25px;'> 看不清楚？<a id='changeValPic' class='imp'  style='cursor:pointer'>换张图</a><i  id='codesummary' style='margin-left:5px;'></i></div></div>" +
                                "<div class='formline' ><label>&nbsp;</label><div><a id='btnpoststock' class='youdu_btn'  ><b style='height:25px;display:inline-block'>提交</b></a></div></div></div>";
                if (webtype == "yobrand" || location.href.indexOf("yobrand") != -1) {
                    htmlmsn += "<div class='msn_ulink'>还不是yobrand用户？<a href='/register/'>快速注册</a></div>";
                }
                htmlmsn += "</div><div id='closeinfo' style='display:none' ><div style='padding: 50px 0pt 0pt 180px;'><img  src='/content/site/images/dj_ok.gif' alt='ok'></img></div><div style='margin: 10pt 0pt 50px 250px; color: rgb(43, 82, 246); font-size: 12px;'><a id='closediv'  class='imp' style='cursor:pointer'>关闭</a></div></div >";
                htmlmsn += "</td><td class='nb_rt' ></td></tr><tr><td class='nb_lb'></td><td class='nb_rb'></td></tr></table></div>";
                if (type) {
                    htmlmsn = "<div class='gray_bg'  id='gback'></div>" + htmlmsn;
                    $(document.body).prepend(htmlmsn);
                }
                else {
                    $('.price').append(htmlmsn);
                }

                initialized = true;
                htmlmsn = null;
                htmlyodu = null;
                var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                $("#txtemail").blur(function () {
                    if ($.trim(this.value) == "") {
                        $("#emailsummary").html("不能为空");
                        return;
                    }
                    else if (!filter.test(this.value)) {
                        $("#emailsummary").html("邮箱格式不对");
                        return;
                    }
                });

                $("#txtemail").focus(function () {
                    // $("#txtemail").val("");
                    $("#emailsummary").html("");
                });

                $("#txtphone").blur(function () {
                    var p1 = /^1[358]\d{9}$/g;
                    if ($.trim(this.value) != "") {
                        var m1 = this.value.match(/^1[358]\d{9}$/g);
                        var m2 = this.value.match(/^15[0-35-9]\d{8}$/g);
                        var m3 = this.value.match(/^18[05-9]\d{8}$/g);
                        if (m1 == null && m2 == null && m3 == null) {
                            $("#phonesummary").text("手机格式不对");
                            return;

                        }
                    }
                });

                $("#txtphone").focus(function () {
                    //   $("#txtphone").val("");
                    $("#phonesummary").html("");
                });

                $('#txtcode').blur(function () {
                    if ($.trim(this.value) == "") {
                        $("#codesummary").html("不能为空");
                        return;
                    }
                });

                $("#closeDiv").click(function () {
                    HideStock();
                    if (type) {
                        $(".gray_bg").hide();
                    }

                });
                $('#closediv').click(function () {
                    HideStock();
                    if (type) {
                        $(".gray_bg").hide();
                    }
                });

                $('#changeValPic').click(function () {
                    $('#validateCodePic').attr("src", "/views/shared/syn_verificationpicture.aspx?ran=" + (new Date()).getTime());
                });

                $('#validateCodePic').click(function () {
                    this.src = "/views/shared/syn_verificationpicture.aspx?ran=" + (new Date()).getTime();
                });

                $('[name=checkCode]').blur(function () {
                    var vad = $.trim(this.value);
                    if (vad == "") return;
                    if (vad.length != 5) return;

                    $.post('/views/handle/userinfo.ashx', { op: 'checkvad', vad: vad, ran: (new Date()).getTime() }, function (d) {
                        if (d.status) {
                        } else {
                            $('#validateCodePic').attr("src", "/views/shared/syn_verificationpicture.aspx?ran=" + (new Date()).getTime());
                        }
                    }, 'json');
                });

                $('[name=checkCode]').focus(function () {
                    $("#codesummary").html("");
                });

                $("#btnpoststock").click(function () {
                    var email = $("#txtemail").val();
                    var phone = $("#txtphone").val();
                    var vadcode = $("#txtcode").val();
                    if (checkallinfo(email, phone, vadcode)) {
                        $.post('/views/handle/Favorite.ashx', { type: 'productstockregist', email: email, phone: phone, vad: vadcode, saleno: saleno }, function (d) {
                            if (d.status) {
                                $('#stockinfo').hide();
                                $('#closeinfo').show();
                            } else {
                                if (d.type == "vad") {
                                    $("#codesummary").html("验证码错误");
                                }
                                else { alert("新增失败！"); }
                            }
                        }, 'json');

                    }
                });
            }
        };

        this.addStockregist = function (pid, saleNo, webtype, userEmail, type) {//alert(pid);alert(saleNo);alert(num)
            if ($("#shoppingbag2").length > 0) { $("#shoppingbag2").hide(); }
            if ($("#shoppingbag").length > 0) { $("#shoppingbag").hide(); }
            if (!pid || !saleNo) return;
            if (!initialized) initialize(pid, saleNo, webtype, userEmail, type);
            showStockDiv(saleNo, userEmail, type);
        }
        var showStockDiv = function (saleno, userEmail, type) {
            var SaleNo = saleno;
            if (type) {
                pop();
            }
            $("#stockcontent").show();
            $('#stockinfo').show();
            $('#closeinfo').hide();
            if (userEmail != "") {
                $("#txtemail").val(userEmail);
            }
        }

        /*弹出缺货登记 层 和其他层*/
        var pop = function () {
            if ($('.bf_wrap').height() > $(window).height())
            { $('.bf_wrap').css({ "top": 0 + $(document).scrollTop() }); }
            else { $('.bf_wrap').css({ "top": parseInt(($(window).height() - $('.shoppingbag').height()) / 2.5) + $(document).scrollTop() }); }
            $('.bf_wrap').css({ "left": "40%" });
            $('.gray_bg').css('height', document.documentElement.scrollHeight);
            $('#gback').show();
        };
        var HideStock = function () {
            $('#validateCodePic').attr("src", "/views/shared/syn_verificationpicture.aspx?ran=" + (new Date()).getTime());
            $("#txtemail").val("");
            $("#txtphone").val("");
            $("#txtcode").val("");
            $("#emailsummary").html("");
            $("#phonesummary").html("");
            $("#codesummary").html("");
            $("#stockcontent").hide();
        }
        var checkallinfo = function (email, phone, code) {
            var bz = true;
            var f = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            var pp1 = /^13\d{9}$/g;
            var pp2 = /^15[0-35-9]\d{8}$/g;
            var pp3 = /^18[05-9]\d{8}$/g;
            if (email == "") {
                $("#emailsummary").html("不能为空");
                bz = false;
            }
            else if (!f.test(email)) {
                $("#emailsummary").html("邮箱格式不对");
                bz = false;
            }
            if ($.trim(phone) == "") { }
            else {
                var r1 = phone.match(/^1[358]\d{9}$/g);
                var r2 = phone.match(/^15[0-35-9]\d{8}$/g);
                var r3 = phone.match(/^18[05-9]\d{8}$/g);
                if (r1 == null && r2 == null && r3 == null) {
                    $("#phonesummary").text("手机格式不对");
                    bz = false;

                }
            }
            if (code == "") { $("#codesummary").html("不能为空"); bz = false; }
            return bz;
        }
    }
    var stockregist = new _StockRegist();
    return stockregist;
} ();


/*礼品卡绑定，弹出层*/


Ac.Product.GiftCardBind = function () {
    var _giftCardBind = function () {
        var initialized = false;
        /*选择规格*/
        var htmlgift = "";
        var bz = true;
        var count = 0;
        var GiftCardBackHandel = null;
        /*初始化*/
        var initialize = function () {
            if (initialized == false) {
                var htmlgift = "";
                htmlgift += "<div class='gray_bg'  id='gback'></div><div class='bf_wrap' id='giftcardinfo' style='display:none'><table cellpadding='0' cellspacing='0' class='note_box pop_gc pop_gc2' >";
                htmlgift += "<tr><td class='nb_lt '><span class='cross_nb' id='closeDiv' style='height:0px;cursor:pointer;'><img src='/content/site/images/cross_fb.gif' /></span>";
                /*one div*/
                htmlgift += "<div class='gc_con' id='giftinfo1' style='display:none'><h4 >绑定礼品卡</h4><div class='gc_form'>";
                htmlgift += "<div class='formline' ><label>卡号：</label><div><input class='fm_ipt'  type='text' id='txtNo' />&nbsp;<i id='noinfo'></i></div></div>";
                htmlgift += "<div class='formline' ><label>密码：</label><div><input class='fm_ipt'  type='text' id='txtpd'  />&nbsp;<i id='pdinfo'></i></div></div>";
                htmlgift += "<div class='formline' ><label>验证码：</label><div><input class='fm_ipt1'  type='text' id='txtCode' />&nbsp;<img style='height: 25px;alt='error' ";
                htmlgift += "align='absmiddle' src='/views/shared/syn_verificationpicture.aspx?ran=1281693714804' id='validateCodePic'>&nbsp;<i id='codeinfo'></i></div></div>";
                htmlgift += "<div class='formline' ><div><a class='btn_normal'  id='Nextbtn'><span>下一步</span></a>&nbsp;<a style='cursor:pointer;' class='cancelupdate'>取消</a></div></div>";
                htmlgift += "<div class='formline' ><div><i id='allinfo'></i></div></div></div></div>";
                /*two div*/
                htmlgift += " <div class='gc_con' id='giftinfo2' style='display:none'>";
                htmlgift += "<h5 >礼品卡绑定后将仅限本账号使用。</h5><div class='gc_form'>";
                htmlgift += "<div class='formline' ><label>卡号：</label><div id='nodiv'></div></div>";
                htmlgift += "<div class='formline' ><label>余额：</label><div id='accountdiv'>5000.00元</div></div>";
                htmlgift += "<div class='formline' ><label>有效期：</label><div id='expirdiv'>2010-09-09</div></div>";
                htmlgift += "<div class='formline' id='mypost' style='display:none'><div><a class='btn_normal' id='bindbtn'><span>完成</span></a>&nbsp;<a style='cursor:pointer;' class='cancelupdate'>取消</a></div></div>";
                htmlgift += "</div><div id='setpassword' style='display:none'><h4 >设置支付密码<span>(使用礼品卡和资金账户购物需设置统一的支付密码!)</span></h4><div class='gc_form1'><div class='formline' ><label>支付密码：";
                htmlgift += "</label><div><input class='fm_ipt'  type='password' id='paypd1' />&nbsp;<i id='paypdinfo' style='color:#FF0000;font-style:normal;'></i><p>密码可由大小写英语、数字、特殊字符组成、长度6-30位</p></div></div><div class='formline' ";
                htmlgift += "><label>确认密码：</label><div><input class='fm_ipt'  type='password' id='paypd2' /><p class='pred' id='notsameinfo'></p></div></div><div class='formline' ><div><a ";
                htmlgift += "class='btn_normal'  id='bindpassbtn'><span>完成</span></a></div></div></div></div></div>";
                /*three div*/
                htmlgift += "<div class='gc_con' id='giftinfo3' style='display:none'>";
                htmlgift += "<div class='gc_success'>礼品卡绑定成功！</div>";
                htmlgift += "<div class='gc_success_info'>为保证资金安全，使用礼品卡和账户支付都需要输入支付密码。</div>";
                htmlgift += "<div class='formline' style='margin:0 120px;' ><div ><a class='btn_normal cancelupdate'  ><span>关闭</span></a></div></div></div>";
                htmlgift += "</td><td class='nb_rt' ></td></tr><tr><td class='nb_lb'></td><td class='nb_rb'></td></tr></table></div>";
                $(document.body).prepend(htmlgift);
                initialized = true;
                htmlgift = null;
                $('#txtNo').focus(function () {

                    $('#noinfo').text("");
                    $('#allinfo').text("");
                });
                $('#txtpd').focus(function () {
                    $('#pdinfo').text("");
                });
                $('#txtCode').focus(function () {
                    $('#codeinfo').text("");
                });
                $('#validateCodePic').blur(function () {
                    var vad = $.trim(this.value);
                    if (vad == "") return;
                    if (vad.length != 5) return;

                    $.post('/views/handle/userinfo.ashx', { op: 'checkvad', vad: vad, ran: (new Date()).getTime() }, function (d) {
                        if (d.status) {
                        } else {
                            $('#validateCodePic').attr("src", "/views/shared/syn_verificationpicture.aspx?ran=" + (new Date()).getTime());
                        }
                    }, 'json');
                });
                $('#validateCodePic').click(function () {
                    this.src = "/views/shared/syn_verificationpicture.aspx?ran=" + (new Date()).getTime();
                });
                $('#Nextbtn').click(function () {

                    var no = $('#txtNo').val();
                    var pd = $('#txtpd').val();
                    var code = $('#txtCode').val();
                    count++;
                    if (checkCard(no, pd, code)) {
                        $.getJSON("/Views/Handle/GiftCard.ashx?a=" + count,
                           { type: "checkcard", cno: no, pd: pd, cd: code },
                       function (data) {
                           if (data.status == "0") { $('#allinfo').text('礼品卡不存在或已使用，请核对后输入'); $('#noinfo').text('卡号错误'); }
                           else if (data.status == "1") { $('#pdinfo').text('密码错误'); }
                           else if (data.status == "4") { $('#codeinfo').text("验证码错误") }
                           else {
                               $('#giftinfo1').hide();
                               $('#nodiv').html(data.Data[0].CardNumber);
                               $('#nodiv').data("gcid", data.Data[0].GcDetailId);
                               $('#accountdiv').html(data.Data[0].RemainderAmount + "元");
                               $('#expirdiv').html(formatDate(data.Data[0].ExpiryDate).substring(0, 10));
                               $('.bf_wrap table').toggleClass('pop_gc2');
                               $('#giftinfo2').show();
                               if (data.status == "2") {
                                   $('#setpassword').hide();
                                   $('#mypost').show();
                               }
                               else {
                                   $('#mypost').hide();
                                   $('#setpassword').show();
                               }
                           }
                       });
                    }
                });
                $('#bindbtn').click(function () {
                    var gdid = $('#nodiv').data("gcid");
                    $.post('/views/handle/GiftCard.ashx', { type: 'bindcard', gdid: gdid, pd: "" }, function (d) {
                        if (d.status) {
                            $('#giftinfo2').hide();
                            $('.bf_wrap table').toggleClass('pop_gc2');
                            $('#giftinfo3').show();
                        } else {
                            alert(d.note + "，刷新后重试");
                        }
                    }, 'json');
                });

                $('#bindpassbtn').click(function () {
                    var p1 = $('#paypd1').val();
                    var p2 = $('#paypd2').val();
                    if (checkpassword(p1, p2)) {
                        var gdid = $('#nodiv').data("gcid");
                        $.post('/views/handle/GiftCard.ashx', { type: 'bindcard', gdid: gdid, pd: p1 }, function (d) {
                            if (d.status) {
                                $('#giftinfo2').hide();
                                $('#giftinfo3').show();
                            } else {
                                alert(d.note + "，刷新后重试");
                            }
                        }, 'json');
                    }
                });

                $("#closeDiv").click(function () {
                    clearInfo();
                });

                $(".formline .cancelupdate").click(function () {
                    clearInfo();
                });
            }
        }

        this.showGiftCardBindDiv = function (loaddata) {
            if (!initialized) initialize();
            GiftCardBackHandel = loaddata;
            pop();
            $('.bf_wrap table').removeClass('pop_gc2');
            $("#giftcardinfo").show();
            $('#giftinfo1').show();
        }
        /*礼品卡绑定弹出层 和其他层*/
        var pop = function () {
            if ($('.bf_wrap').height() > $(window).height())
            { $('.bf_wrap').css({ "top": 0 + $(document).scrollTop() }); }
            else { $('.bf_wrap').css({ "top": parseInt(($(window).height() - $('.shoppingbag').height()) / 2.5) + $(document).scrollTop() }); }
            $('.bf_wrap').css({ "left": "40%" });
            $('.gray_bg').css('height', document.documentElement.scrollHeight);
            $('#gback').show();
        };

        var checkCard = function (number, password, code) {
            var bz = true;
            if (number == "") {
                $('#noinfo').text("不能为空");
                bz = false;
            }
            if (password == "") { $('#pdinfo').text("不能为空"); bz = false; }
            if (code == "") { $("#codeinfo").text(" 不能为空"); bz = false; }
            return bz;
        }

        var clearInfo = function () {
            $(".formline input").val("");
            $(".formline  i").text("");
            $('#giftinfo1').hide();
            $('#giftinfo2').hide();
            $('#giftinfo3').hide();
            $('#giftcardinfo').hide();
            $('#gback').hide();
            $('#validateCodePic').attr("src", "/views/shared/syn_verificationpicture.aspx?ran=" + (new Date()).getTime());
           // alert(GiftCardBackHandel);
            if (GiftCardBackHandel != null) {
                GiftCardBackHandel();
            }

        }
        var checkpassword = function (pd1, pd2) {
            var b = true;
            if (pd1 == "") { $('#paypdinfo').text('不能为空'); b = false; }
            if (pd1.length < 6 || pd1.length > 30) { $('#paypdinfo').text('长度不正确'); b = false; }
            if ($.trim(pd1) == $.trim(pd2)) { } else { $('#notsameinfo').text('密码不一致'); b = false; }
            return b;
        }
    }
    var Giftcard = new _giftCardBind();
    return Giftcard;
} ();







/*列表页面选择规格，弹出层*/

Ac.Product.SelectSpecProcessor = function () {

    var attrib_tmps2 = "<h5>{productname:2}</h5> " +
                   "     <dl> " +
                    "        <dt><img src='{productpic:3}' /></dt> " +
                     "       <dd class='first'>规格选择...</dd> " +
                  "      <dd>数量：<select class='nubs' name='' onchange='Ac.Product.SelectSpecProcessorInstance.IsInRange()' id='DetailNum2'>{options:1}</select><span>件</span></dd>{attribs:0}" +
                        "<dd>价格：<span id='DetailPrice2'></span></dd>" +
                       " </dl> " +
                       " <div class='add_btm'><span class='{CssClass:4}' id='DetailBtn2' onclick='Ac.Product.SelectSpecProcessorInstance.PutInCart();' style='cursor:pointer'></span><label>&lt;&lt; <a href='javascript:Ac.Product.SelectSpecProcessorInstance.hide()'>返回</a></label></div> ";

    var Price = function (obj) {
        this.UseIsInRange = true;
        /*每单限购*/
        this.IsInRange = function () {
            if (!this.UseIsInRange) return true;
            var Var = this.numObj2.val();
            var max = detailObj.maxBuyNum || Ac.Config.LimitQtyPerOrder;
            var cookieNum = Cart.getNumById(detailObj.productId);
            if ((parseInt(Var) + cookieNum) > max) {
                this.numObj2.reverse();
                alert("该商品只限购买" + max + "个，您已超过购买上限");
                return false;
            } else {
                return true;
            }
        };
        this.Config = { BtnText: "立即购买" };
        this.GetDetailObj = function () {
            return detailObj;
        };
        var detailObj = null;
        this.td = [];
        this.multi = true; /*是否多规格*/
        var Spec = []; /*具体规格Spec*/
        var flag = null; /*默认为不能购买*/

        //var jifenTpl="每购买一件赠送 {0} 个积分( <a href='#'>积分规则？</a>)";/*积分模板*/
        //var priceTmp =["市场价：<del>","</del><br />","<b>¥","</b>"];/*价格模板*/
        var priceObj = null; /*价格*/
        //var specImgObj = null;/*规格图片*/
        //var jifenObj =null;/*积分*/
        this.numObj = null;
        this.numObj2 = null;
        this.curb = "buy"; /*当前状态*/
        this.btnObj = null;
        this.isStockSearch = false; /*是否搜索第一个库存不为0的规格*/
        var _this = this;
        /*初始化*/
        this.initialize = function (obj) {
            detailObj = obj;
            Spec = [];
            flag = null;
            this.td = [];
            this.multi = detailObj.ismulti;
            /*加载价格计算规则*/
            this.load(detailObj.productListPrice);
            /*初始化HTML*/
            var specObj = null;

            this.generateHtml();
            /*计算价格*/
            this.stFind();
        };
        /*规格是否为有效组合*/
        this.isFullSpec = function () {
            var l = (detailObj.specData || []).length;
            var hasNull = false;
            if (l !== Spec.length) {
                hasNull = true;
            } else {
                for (var i = 0; i < Spec.length; i++) {
                    if (!Spec[i]) {
                        hasNull = true;
                        break;
                    }
                }
            }
            return !hasNull;
        };
        /*更改状态*/
        this.changeStatus = function (b) {

            if (!this.isFullSpec()) {
                this.bt["buy"].css();
            } else {
                var a = b > 0;
                if (a == flag) return;

                if (detailObj.isgift) {
                    this.curb = "gift";
                }
                else if (a) {
                    this.curb = "buy";
                }
                else {
                    this.curb = "sellout";
                }

                /*更改样式*/
                this.bt[this.curb].css();
                flag = a;
            }
        };
        /*设置当前规格*/
        this.setCurrent = function (saleno, groupid) {
            detailObj.productSaleNumber = saleno;
            detailObj.productGroupId = groupid;
        };
        /*根据选择计算价格*/
        this.stFind = function () {
            /*计算多规格时的价格和数量,SaleNo,并更新按钮状态*/
            var price = this.find(Spec);

            /*无规格选择时，显示第一个价格*/
            /*取最低价格2010.07.14*/
            if (price == null) {
                price = this.td.minFloat("Pr");
            }

            /*存在该规格组合产品*/
            if (price != null) {
                /*得到SaleNo*/
                var saleNo = price.SaleNo;

                var data = price.ActurePrice;
                //var data = detailObj.discountPrice[saleNo];

                /*显示价格和规格图片*/
                priceObj.innerHTML = data || price.Pr;

            } else {
            }

        };
        /*选择规格方法*/
        this.Pick = function (btn, i) {
            $(btn).parent().parent().find("a").removeClass("on");
            $(btn).addClass("on");

            Spec[i] = $(btn).attr("val");
            this.stFind();
        };
        /*是否使用第一个规格为默认*/
        var useDefault = false;
        /*生成HTML*/
        this.generateHtml = function (spec) {
            var h = "";
            if (spec != undefined && isArray(spec)) {/*根据规格号初始化界面*/
                h = detailObj.specData.aggregate(
                    function (i, a) {
                        return "<dd>" + a.k + "：" +
                            a.g.aggregate(
                            function (j, b) {
                                return "<span><a onclick='Ac.Product.SelectSpecProcessorInstance.Pick(this," + i + ");' val='" + b.v + "' class='" + function () { if (spec.indexOf(b.v) != -1) { Spec[Spec.length] = b.v; return "on"; } return ""; } () + "'>" + b.n + "</a></span>"
                            })
                            + "</dd>";
                    }
                );
            } else {/*默认初始化界面*/
                if (useDefault) {
                    h = detailObj.specData.aggregate(function (i, a) { return "<dd>" + a.k + "：" + a.g.aggregate(function (j, b) { if (j == 0) { Spec[Spec.length] = b.v; } return "<span><a onclick='Ac.Product.SelectSpecProcessorInstance.Pick(this," + i + ");' val='" + b.v + "' class='" + (j == 0 ? "on" : "") + "'>" + b.n + "</a></span>" }) + "</dd>"; });
                } else {
                    h = detailObj.specData.aggregate(function (i, a) { return "<dd>" + a.k + "：" + a.g.aggregate(function (j, b) { var singleSpec = a.g.length == 1; if (singleSpec) { Spec[i] = b.v; } return "<span><a onclick='Ac.Product.SelectSpecProcessorInstance.Pick(this," + i + ");' val='" + b.v + "' class='" + (singleSpec ? "on" : "") + "'>" + b.n + "</a></span>" }) + "</dd>"; });
                }
            }
            var sel = Range.create(1, detailObj.maxBuyNum || Ac.Config.LimitQtyPerOrder).aggregate(function (i, a) { return "<option>{0}</option>".template(a); });
            Ulity.E2("DetailCart2").innerHTML = attrib_tmps2.template2(h, sel, "", Ac.Config.ImgStaticServer + detailObj.productPicThumbString.split(',')[0], this.Config.CssClass);
            priceObj = Ulity.E2("DetailPrice2");
            this.numObj = Ulity.E2("DetailNum2");
            this.btnObj = Ulity.E2("DetailBtn2");
            this.numObj2 = new ReversableSelect(this.numObj);
        };
        this.hide = function () {
            $('.shoppingbag2').hide();
            $('.gray_bg').hide();
        };
        this.getErrorMsg = function () {
            /*是否超过限购*/
            var islogined = Ac.Page.IsLogin != undefined && Ac.Page.IsLogin;
            if (!islogined && detailObj.maxBuyNum) {
                /*非注册用户不能购买限购产品*/
                alert("{0}只限注册用户购买，请登录后购买".template(detailObj.productName));
            } else {
                var restraint = this.IsInRange();
                if (restraint) {
                    var m = "";
                    var h = false; /*是否有规格没有选择*/
                    var l = detailObj.specData.length;
                    for (var i = 0; i < l; i++) {
                        if (!Spec[i]) {
                            if (!h) h = true;
                            m += detailObj.specData[i].k + " ";
                        }
                    }
                    if (h) {
                        return "请选择 ：  " + m + "!";
                    } else {
                        return null;
                    }
                }
            }
            return "";
        };
        this.getErrorMsg2 = function () {
            var m = "";
            var h = false; /*是否有规格没有选择*/
            var l = detailObj.specData.length;
            for (var i = 0; i < l; i++) {
                if (!Spec[i]) {
                    if (!h) h = true;
                    m += detailObj.specData[i].k + " ";
                }
            }
            if (h) {
                return "请选择 ：  " + m + "!";
            } else {
                return null;
            }
        };
    }
    /*多规格和单规格*/
    var PriceMulti = function (obj) {
        var __this = this;
        this.load = function (a) {
            if (a == undefined || a == "") return;
            if (this.multi) {
                var t1 = a.split(',');
                var l1 = t1.length;
                while (l1) {
                    var t2 = t1[--l1].split(':');
                    //this.td[l1] = { "Pr": t2[0], "It": t2[1], "SaleNo": t2[2], "GroupId": t2[3], "Repertory": t2[4], "PrMarket": t2[5], "SpecImg": t2[6] };
                    this.td[l1] = { "Pr": t2[0], "It": t2[1], "SaleNo": t2[2], "GroupId": t2[3], "Repertory": t2[4], "PrMarket": t2[5], "SpecImg": t2[6], "ActurePrice": t2[7] };

                }
            } else {
                var t2 = a.split(':')
                this.td[0] = { "Pr": t2[0], "It": null, "SaleNo": t2[1], "GroupId": 0, "Repertory": t2[2], "PrMarket": t2[3], "SpecImg": t2[4], "ActurePrice": t2[5] };
                //this.td[0] = { "Pr": t2[0], "It": null, "SaleNo": t2[1], "GroupId": 0, "Repertory": t2[2], "PrMarket": t2[3], "SpecImg": t2[4] };
            }
        };
        this.find = function (a) {//alert(a);
            if (this.multi) {
                if (!this.td.length || !a.length || a.length == 0) return;
                var ar = a, al = a.length, l = this.td.length;
                while (l) {
                    var v = this.td[--l].It;
                    var f = true;
                    for (var i = 0; i < al; i++) {
                        if (v.indexOf(ar[i]) == -1) {
                            f = false;
                            break;
                        }
                    }
                    if (f) {
                        this.setCurrent(this.td[l].SaleNo, this.td[l].GroupId)
                        this.changeStatus(this.td[l].Repertory);
                        return this.td[l];
                    }
                }
                this.setCurrent(null, null);
                return null;
            } else {
                this.setCurrent(this.td[0].SaleNo, this.td[0].GroupId)
                this.changeStatus(this.td[0].Repertory);
                return this.td[0];
            }
        };


    };
    PriceMulti.prototype = new Price();

    /*多规格购买*/
    var PriceMutliBuy = function (obj) {
        var _this = this;
        this.isStockSearch = true;
        this.bt = {
            "buy": {
                action: function () {
                    var msg = _this.getErrorMsg();
                    if (msg == null) {
                        _this.hide();
                        if (typeof (CartInfo) == undefined) return;
                        Ac.Product.CartInfo.addBySaleNo(_this.GetDetailObj().productId, _this.GetDetailObj().productSaleNumber, $(_this.numObj).val());
                    } else {
                        /*如果规格没有选中*/
                        if (msg != "") {
                            alert(msg);
                        }
                    }
                },
                //      css:function(){$(_this.btnObj).html('购买');}},
                css: function () { $(_this.btnObj).css("cursor", "pointer"); $(_this.btnObj).attr('class', 'sure_btn'); }
            },
            "gift": { action: function () { alert("gift"); }, css: function () { } },
            // "sellout":{action:function(){},css:function(){$(_this.btnObj).html('缺货');}},
            "sellout": { action: function () { Ac.Product.StockRegist.addStockregist(_this.GetDetailObj().productId, _this.GetDetailObj().productSaleNumber, '', _this.GetDetailObj().userEmail, true); },
                css: function () { $(_this.btnObj).css("cursor", "pointer"); $(_this.btnObj).attr('class', 'sure_btn1'); }
            },
            "fail": { action: function () { alert("fail"); }, css: function () { } }
        };
        //this.Config = {BtnText:"购买"};
        this.Config = { BtnText: "", CssClass: "sure_btn" };
        /*购买*/
        this.PutInCart = function () {
            this.bt[this.curb].action();
        };
        this.init = function (obj) {
            this.initialize(obj);
        };
        this.init(obj);
    };
    PriceMutliBuy.prototype = new PriceMulti();

    /*多规格收藏*/
    var PriceMutliFavor = function (obj, node) {
        var _this = this;
        this.isStockSearch = false;
        this.UseIsInRange = false;
        /*当期收藏按钮，提示Tip位置相对它显示*/
        this.node = node;
        this.bt = {
            "buy": {
                action: function () {
                    _this.hide();
                    if (typeof (CartInfo) == undefined) return;
                    Ac.Product.CartInfo.insertFavor(_this.GetDetailObj().productId, _this.GetDetailObj().productGroupId, _this.node);
                },
                css: function () { $(_this.btnObj).html(''); }
            },
            "gift": { action: function () { alert("gift"); }, css: function () { } },
            "sellout": { action: function () {
                _this.hide();
                if (typeof (CartInfo) == undefined) return;
                Ac.Product.CartInfo.insertFavor(_this.GetDetailObj().productId, _this.GetDetailObj().productGroupId, _this.node);
            }, css: function () { }
            },
            "fail": { action: function () { alert("fail"); }, css: function () { } }
        };
        this.Config = { BtnText: "", CssClass: "add_btn" };
        /*收藏*/
        this.PutInCart = function () {
            var msg = this.getErrorMsg2();
            if (msg == null) {
                this.bt[this.curb].action();
            } else {
                /*如果规格没有选中*/
                alert(msg);
            }
        };
        this.init = function (obj) {
            this.initialize(obj);
        };
        this.init(obj);
    };
    PriceMutliFavor.prototype = new PriceMulti();

    /*创建当前规格选择实例并把引用保存到Ac.Product.SelectSpecProcessorInstance*/
    var PriceManager = {
        CreateBuy: function (obj) {
            Ac.Product.SelectSpecProcessorInstance = new PriceMutliBuy(obj);
        },
        CreateFavor: function (obj, node) {
            Ac.Product.SelectSpecProcessorInstance = new PriceMutliFavor(obj, node);
        }
    }
    return PriceManager;


} ();



//Bruce.li add
//快速登录代码，使用iframe实现，动态创建
function quickLogin() {
    if (!document.getElementById("div_quickLogin")) {
        generateQuickLogin()
        $(window).resize(function () {
            if (bruce.browser.isIE6()) {
                var objQuickLogin = document.getElementById("div_quickLogin");
                objQuickLogin.style.top = (((bruce.browser.height() - 324) / 2) + bruce.browser.scrollTop()) + 'px';
                objQuickLogin.style.left = (((bruce.browser.width() - 791) / 2) + bruce.browser.scrollLeft()) + 'px';
            } else {
                var objQuickLogin = document.getElementById("div_quickLogin");
                objQuickLogin.style.top = ((bruce.browser.height() - 324) / 2) + 'px';
                objQuickLogin.style.left = ((bruce.browser.width() - 791) / 2) + 'px';
            }
        });
        $(window).scroll(function () {
            if (bruce.browser.isIE6()) {
                var objQuickLogin = document.getElementById("div_quickLogin");
                objQuickLogin.style.top = (((bruce.browser.height() - 324) / 2) + bruce.browser.scrollTop()) + 'px';
                objQuickLogin.style.left = (((bruce.browser.width() - 791) / 2) + bruce.browser.scrollLeft()) + 'px';
            }
        });
    }

    var objQuickLogin = document.getElementById("div_quickLogin");
    objQuickLogin.style.display = "block";
    objQuickLogin.style.zIndex = 99999;
    if (bruce.browser.isIE6()) {
        objQuickLogin.style.position = "absolute";
    } else objQuickLogin.style.position = "fixed";
    objQuickLogin.style.top = ((bruce.browser.height() - 324) / 2) + 'px';
    objQuickLogin.style.left = ((bruce.browser.width() - 791) / 2) + 'px';


}

function generateQuickLogin() {
    var quickloginDiv = document.createElement("div");
    quickloginDiv.id = "div_quickLogin";
    //quickloginDiv.style.width = "791px";
    quickloginDiv.style.position = "absolute";
    //quickloginDiv.style.left = "100px";
    //quickloginDiv.style.top = "100px";

    var headDiv = document.createElement("div");
    //head content
    var closeSpan = document.createElement("span");
    closeSpan.innerHTML = "X";
    closeSpan.style.backgroundColor = "black";
    closeSpan.style.color = "white";
    closeSpan.style.cursor = "pointer";
    closeSpan.style.padding = "0px 3px";
    closeSpan.style.styleFloat = "right";
    closeSpan.style.cssFloat = "right";
    closeSpan.onclick = function () {
        document.getElementById("div_quickLogin").style.display = "none";
    };
    //end
    headDiv.appendChild(closeSpan);

    var contentDiv = document.createElement("div");
    //content 
    //var iframeHtml = '<iframe id="iframe_quickLogin" frameborder="0" width="791px" height="245px" src="/views/account/fastlogin.html"></iframe>';
    var iframeHtml = '<iframe id="iframe_quickLogin" frameborder="0" width="791px" height="245px"></iframe>';
    var tempDom = document.createElement("div");
    tempDom.innerHTML = iframeHtml;
    var iframeDom = tempDom.childNodes[0];
    //end
    contentDiv.appendChild(iframeDom);

    quickloginDiv.appendChild(headDiv);
    quickloginDiv.appendChild(contentDiv);
    document.body.appendChild(quickloginDiv);

    iframeDom.src = "/views/account/fastlogin.html";
}

var bruce = {};
bruce.browser = {
    scrollLeft: function () { return (document.documentElement.scrollLeft || window.pageXOffset) || 0; },
    scrollTop: function () { return (document.documentElement.scrollTop || window.pageYOffset) || 0; },
    height: function () { return (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight; },
    width: function () { return (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth; },
    isIE: function () { return ! -[1, ]; },
    isIE6: function () { return bruce.browser.isIE() && !window.XMLHttpRequest ? true : false; }
};

var GiftCardManager = {
    OrderNo: ""
    , PayUrl: ""
    , PayPrice: 0
    , GiftDiscountPrice: 0
    , GiftCardTotalAmount: 0
    , HadCheckPayPwd: false
    , UsedGiftCards: []
    , ReBindPayGiftList: function () {
        GiftCardManager.BindPayGiftList(GiftCardManager.PayPrice);
    }
    , BindPayGiftList: function (payprice) {
        this.PayPrice = payprice == undefined ? 0 : payprice;
        this.GiftDiscountPrice = 0;
        this.GiftCardTotalAmount = 0;
        this.UsedGiftCards = [];

        $("#giftnowuseamount").html(GiftCardManager.GiftDiscountPrice.toFixed(2));
        $("#giftendneedprice").html((GiftCardManager.PayPrice - GiftCardManager.GiftDiscountPrice).toFixed(2));
        $("#giftnowusecount").html("0");

        var gcrow = "<td><input onclick=\"GiftCardManager.GiftCardSelect(this);\" name=\"giftcardused\" type=\"checkbox\" title=\"{4}\" /> &nbsp;{0}</td><td><div class=\"pright\">{1}</div></td><td><div class=\"pright\">{2}</div></td><td> &nbsp;{3}</td><td><div class=\"pright upay_num\" >0.00</div></td>";
        $.getJSON("/Views/Handle/GiftCard.ashx?a=" + 50 + "&time=" + Date(),
            {
                type: "getgcdetail", id: "26064", datacase: "onlycanuse"
            },
            function (data) {
                var tab = $("#tabgiftcardlist");
                $("#tabgiftcardlist tr[class=\"DataAddRow\"]").remove();
                for (var i = 0; i < data.Data.length; i++) {
                    if (data.Data[i].RemainderAmount <= 0) {
                        continue;
                    }
                    var tr = document.createElement("TR");
                    tr.className = "DataAddRow";
                    var htm = gcrow.template(data.Data[i].CardNumber, data.Data[i].GcValue.toFixed(2), data.Data[i].RemainderAmount.toFixed(2), formatDate(data.Data[i].ExpiryDate).substring(0, 10), data.Data[i].GcDetailId);
                    $(tr).append(htm);
                    tr.data = data.Data[i];
                    GiftCardManager.GiftCardTotalAmount += data.Data[i].RemainderAmount;
                    tab.append(tr);
                }
                $("#gifttotalamount").text(GiftCardManager.GiftCardTotalAmount.toFixed(2));
            });
    }
    , GiftCardSelect: function (checkbox) {
        $("#tabgiftcardlist div.upay_num").html("0.00");
        $("#giftnowuseamount").html("0.00");
        $("#giftnowusecount").html("0");
        GiftCardManager.GiftDiscountPrice = 0;
        GiftCardManager.UsedGiftCards = [];

        var cks = $("#tabgiftcardlist input[name=\"giftcardused\"]");
        var ckcount = 0;
        cks.each(function () {
            if (this.checked) {
                var tr = $(this).parents("TR")[0];
                var namount = 0;
                var nowneed = GiftCardManager.PayPrice - GiftCardManager.GiftDiscountPrice;
                if (nowneed > 0) {
                    namount = tr.data.RemainderAmount > nowneed ? nowneed : tr.data.RemainderAmount;
                    $("div.upay_num", tr).html("-" + namount.toFixed(2));
                    GiftCardManager.GiftDiscountPrice += namount;
                    ckcount++;
                    GiftCardManager.UsedGiftCards.push(this.title);
                }
            }
        });
        var paymore = GiftCardManager.PayPrice - GiftCardManager.GiftDiscountPrice;
        $("#giftnowuseamount").html(GiftCardManager.GiftDiscountPrice.toFixed(2));
        $("#giftendneedprice").html(paymore.toFixed(2));
        $("#giftnowusecount").html(ckcount.toFixed(0));

        var totalamount = GiftCardManager.GiftCardTotalAmount - GiftCardManager.GiftDiscountPrice;
        $("#gifttotalamount").text(totalamount.toFixed(2));
        if (paymore > 0) {
            $("#divgcp_pay_more").show();
        } else {
            $("#divgcp_pay_more").hide();
        }
    }
    , CheckUserPayPwd: function () {
        var pwd = $("#txtgiftcarduserpaypwd").val();
        $("#giftpayerrormsg").html("");
        $.getJSON("/Views/Handle/GiftCard.ashx?a=" + 10,
            {
                type: "checkpaypwd", paypwd: pwd
            },
            function (data) {
                if (data.status == 1) {
                    GiftCardManager.ShowGiftCardPay(false);
                    GiftCardManager.HadCheckPayPwd = true;
                    var paymore = GiftCardManager.PayPrice - GiftCardManager.GiftDiscountPrice;
                    if (paymore == 0) {
                        $('#a_giftcardpayurl').click();
                        if (GiftCardManager.GiftCardPay()) {
                            window.location.href = GiftCardManager.PayUrl;
                        }
                    }
                }
                else {
                    $("#giftpayerrormsg").html(data.Data);
                    GiftCardManager.HadCheckPayPwd = false;
                }
            });
    }
    , ShowGiftCardPay: function (bl) {
        if (bl) {
            $("#sp_bindgiftcard").show();
            $("#divgiftcardpay").show();
            $("#sp_reselectgiftcard").hide();
            $("#txtgiftcarduserpaypwd").val("");
            GiftCardManager.BindPayGiftList(GiftCardManager.PayPrice);
            GiftCardManager.HadCheckPayPwd = false;
        } else {
            $("#sp_bindgiftcard").hide();
            $("#divgiftcardpay").hide();
            $("#sp_reselectgiftcard").show();
            $("#tabgiftcardlist tr.DataAddRow").each(function () {
                if ($("input[name=\"giftcardused\"]", this)[0].checked) {
                    $("input[name=\"giftcardused\"]", this).attr("disabled", true);
                } else {
                    $(this).hide();
                }
            });
        }
    }
    , GiftCardPay: function () {
        var bl = false;
        if (GiftCardManager.HadCheckPayPwd == false) {
            alert("请先输入支付密码,再点击支付!");
            return bl;
        }
        var url = "/views/account/giftcardpayrediect.aspx?payrediect=true&bankId=";
        var pwd = $("#txtgiftcarduserpaypwd").val();
        var bankid = $('#a_giftcardpayurl')[0].bankid;
        var cards = "";
        for (var i = 0; i < GiftCardManager.UsedGiftCards.length; i++) {
            if (i == 0) {
                cards = GiftCardManager.UsedGiftCards[i];
            } else {
                cards += "," + GiftCardManager.UsedGiftCards[i];
            }
        }
        var paymore = GiftCardManager.PayPrice - GiftCardManager.GiftDiscountPrice;
        url += bankid + "&paypwd=" + pwd + "&cards=" + cards + "&orderno=" + GiftCardManager.OrderNo + "&paymore=" + paymore.toFixed(2);
        $('#a_giftcardpayurl').attr("href", url);
        GiftCardManager.PayUrl = url;
        bl = true;
        return bl;
    }
};