var jQuery
var isIE6 = false;
(function ($) {
        $.fn.popwindow = function (cssOptions) {
        var cssOptions = $.extend({}, cssOptions);
        if (this.context) {
            $(this).click(function () {
                open(this);
                return false;
            });
        } else {
            open(null);
        }
        function open(e) {
            html = [];
            html.push();
            html.push("<div id=\"Overlay\">");
            if (cssOptions.title) {
                var title = cssOptions.title;
                if(typeof(cssOptions.title)=="function")
                    title = cssOptions.title(e);
                html.push("<div class=\"KmainBox\">");
                html.push("<h2 class=\"msgboxhead\">");
                html.push("    <span>" + title + "</span> ");
                html.push("    <a style=\"color: #fff;\" href=\"#\" class=\"close track\" name=\"item-close\">关闭</a><a href=\"#\" class=\"close track\" name=\"item-close\"><img src=\"//i.vanclimg.com/Others/2011/2/15/dpbox_06.gif\" /></a></h2>");
            }
            html.push("    <iframe id=\"LoadedContent\" frameborder=\"0\"></iframe>");
            if (cssOptions.title) {
                html.push("</div>");
            }
            html.push("</div>");
            $("body").prepend(html.join(""));
            if (!cssOptions.noOverlayClose) {
                $("#Overlay").click(function () { $(this).remove(); });
            }
            if ($.fn.decorateIframe) {
                $("#Overlay").decorateIframe();
            }
            var $LoadedContent = $("#LoadedContent");
            var url = "";
            if (cssOptions.href) {
                url = cssOptions.href;
            } else {
                url = $(e).attr("href");
            }
            // url += "&t=" + Math.random();

            $LoadedContent.attr("src", url);

            $("#Overlay").children().eq(0).css(cssOptions);
            windowresize();

            $("#Overlay .close").click(function () {
                $("#Overlay").fadeOut().remove();
                return false;
            });
        };
    }

    $.fn.popwindow.close = function () {
        $("#Overlay").fadeOut().remove();
    }

    $.fn.popwindow.resize = function (css) {
        $("#LoadedContent").css(css);
    }


    function windowresize() {
        var $LoadedContent = $("#LoadedContent");

        if (isIE6) {
            ie6.windowresize();
        } else {
            $("#Overlay").css({ position: "fixed" });
        }
        var position = {
            marginLeft: ($(window).width() - $LoadedContent.width()) / 2,
            marginTop: ($(window).height() - $LoadedContent.height()) / 2
        };
        $("#Overlay").children().eq(0).css(position);
    }
    $(window).resize(windowresize);
})(jQuery);
String.prototype.cut = function (len) {
    var strlen = 0;
    var s = [];
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 128)
            strlen += 2;
        else
            strlen++;
        s.push(this.charAt(i));
        if (strlen >= len)
        { s.push("..."); break; }
    }
    return s.join("");
}
String.prototype.gblen = function() {  
    var len = 0;  
    for (var i=0; i<this.length; i++) {  
        if (this.charCodeAt(i)>128) {  
             len += 2;  
         } else {  
             len ++;  
         }  
     }  
    return len;  
} 
var stockTimeout = null;
function stockIn() {
    if (stockTimeout != null) {
        window.clearTimeout(stockTimeout);
    }
    $(".addressWindows").show();
    $(".cityAdd").addClass("cityAddHover");

}

function stockOut() {
    stockTimeout = window.setTimeout(function () {
        $(".addressWindows").hide();
        $(".cityAdd").removeClass("cityAddHover");
    }, 50);
}

function checkStocking() {
    var closeCode = getCloseCode();
    if (closeCode != null) {
        var addr = $(".addressWindows a:contains('" + $.trim($("span.goodsAdd").text()) + "')");
        if (addr.length == 0) {
            return;
        }
        var housecode = addr.attr("name").replace("hs-", "");
        var url = [];
        url.push("/styles/stocking.aspx");
        url.push("?clothescode=" + closeCode);
        url.push("&housecode=" + housecode);
        $.get(url.join(""), function (data) {
            //$("#stockinfo,#stocktip").empty();
            if (data == "True") {
                $("#stockinfo").text("最近库房有货");
            } else {
                //if(housecode=="610000"){
                //    $("#stocktip").html("<span class=\"blank8\"></span><div class=\"stock\"><span class=\"sprites\" style=\"height: 16px; display: block; width: 16px; background-position: -1911px 0pt; margin: 2px;float: left; \"></span><p>非常抱歉！该商品缺货，不能送至您选择的区域。</p></div>");
                //}
                //else{
                    $("#stockinfo").text("最近库房缺货, 预计从其他库房发出");
                //}
            }
        });
    }
    stockOut();	
}

//获取CloseCode
function getCloseCode() {
    if ($(".selSize #onlickSelSize").length == 0) {
        return null;
    }
    return $(".selSize #onlickSelSize").attr("name")
}

function ajaxIsLogined(callback, productcode) {
    var url = "styles/IsLogined.aspx";
    var parm = [];
    if (productcode != null && productcode.length > 0)
        parm.push("productcode=" + productcode);
    if (parm.length > 0)
        url = url + "?" + parm.join("&");
    $.getScript(url, callback);
}
var sizetitle = ""; //尺码或净含量

$(function () {
    isIE6 = (typeof ie6 != "undefined");
    //sizetitle = $.trim($("#selectedSize").text().split('：')[0]);
    if ($.fn.decorateIframe) {
        $("#bigView,#collectbox,#shopbox").decorateIframe();
    }
    var productcode = $("#productcode").text().split("：")[1];

    $("#addToShoppingCar").live("click", function () {
        $("#shoploading").html("<img src=\"//i.vanclimg.com/logo/loading.gif\" alt=\"loading\">");
        $(".shoppingErrTips").remove();
        if ($("#shopbox").css("display") != "none") {
            $("#collectbox").fadeOut();
        } else {
            $("#collectbox,#shopbox").fadeOut();
        }
        var closeCode = getCloseCode();
        if (closeCode == null) {
            $(".danpin_xuanzeGMcm").show();
            return false;
        }
        var url = [];
        url.push("http://shopping.vancl.com");
        url.push("/mycart/batchadd");
        url.push("?sku=");
        url.push(closeCode);
        url.push("&price=");
        url.push($("#pricearea >.cuxiaoPrice>span>strong:eq(0)").text());
        url.push("&qty=");
        url.push($("#selectedAmount").val());

        var refLink = (function (o) {
            var href = o.attr("href");
            var index = href.indexOf("#");
            if (index > -1 && index + 1 < href.length) {
                var href = href.substring(index + 1, href.length);
                return "&" + href;
            }
        })($(this));

        if (refLink) {
            url.push(refLink);
        }

        url.push("&async=true");
        url.push("&callback=?");

        $("#shopbox").css({ "top": $("#addToShoppingCar").offset().top - 120 }).show();

        if (isIE6) {
            $("#shopbox").css({ "left": ie6.setLeft(538) });
        }

        $("#shopbox").find(".close,.jxgwbtn").click(function () {
            $("#shopbox").hide();
            $("#shoploading").show().next().hide();
            return false;
        });

        var shoppingurl = url.join("");
        //修补积分问题
        if ($(".cuxiaoPrice").find("strong").length == 1 && shoppingurl.indexOf("&isPoint=true") > 0) {
            shoppingurl = shoppingurl.replace("&isPoint=true", "");
        }

        $.getJSON(shoppingurl, function (data) {
            if (!data.Type || data.Type == "") {
                $("#shopboxprice").text(data.TotalPrice);
                $("#shopboxcount").text(data.TotalProducts);
                $.getJSON("/api/buynow.aspx?callback=?", function (json) {
                    var html = [];

                    if (json.msg == 'Y') {
                        html.push("<style>.Shoppingcart_Btna{ cursor:pointer; width:97px; height:27px; line-height:26px; _line-height:27px; background:url(\"//i5.vanclimg.com/others/2012/8/14/sprites2.png\") no-repeat -1033px -32px; display:block; float:left; margin-left:10px; _margin-left:14px; text-align:center;}</style><a style=\"color:#fff;\" class=\"Shoppingcart_Btna track\" name=\"item-buynow\" href=\"http://buy.vancl.com?from=item\" target=\"_parent\">立即结算</a>");
                        html.push("<a class=\"track\" name=\"item-gocart\" href=\"http://shopping.vancl.com/mycart?showbuy=true\" rel=\"nofollow\" target=\"_parent\"><span style=\"width: 97px; height: 27px; background-position: -1033px 0pt; margin-left: 170px; display: block; cursor: pointer\" class=\"sprites\"></span></a>");

                        $(".itembuynow").html(html.join("")).show();

                        var today = new Date();
                        var buynowdatetime = (today.getFullYear()) + "-" + (today.getMonth() + 1) + "-" + today.getDate();
                        $.getScript("http://counter.vanclimg.com/counter?key=item" + buynowdatetime);
                    }
                });

                var clothes = "";
                if (typeof (data.clothes) != 'undefined')
                    clothes = data.clothes;
                var paramJson = "[{Position:\"rp_item_cart\", ProductCodes:\"" + productcode + "\",Rows:\"" + 5 + "\",Remark:\"NeedExclude\",ClothesCodes:\"" + clothes + "\"}]";
                var $gmlist = $("#shopbox").find(".gmlist");
                var $weblog = $("<img style='display:none;' src='//item.vancl.com/api/user.aspx?closeCode=" + closeCode + "' />");
                $("body").append($weblog);
                recmApi(paramJson, $gmlist, "dp_add2cart_similarpurchase", "item-shopping-pap", "cart");

                $("#shoploading").fadeOut(function () { $(this).next().show(); });

                VA_GLOBAL.va.track(null, "va_atc", shoppingurl.substr(shoppingurl.indexOf('?') + 1));
                //$.getScript("/api/trace.aspx?" + $("#addToShoppingCar").attr("href").replace("#", ""));
                if (typeof (sbu_continue_shopping) != undefined) {
                    sbu_continue_shopping.saveme();
                }

            } else {
                $("#shopbox").hide();
                var $tip = $("<p class=\"shoppingErrTips\"><span></span>"+data.Content+"</p>");
                if(data.Content.indexOf("请先登录")>0){
                    $tip = $("<p class=\"shoppingErrTips\"><span></span>本商品限购，<a href=\"javascript:location.href='https://login.vancl.com/login/login.aspx?'+location.href\"> 请先登录</a> 确认您的会员等级能否购买</p>");
                }
                $(".shoppingCarArea").after($tip);
            }
        });

        return false;

    });

    $("img[original]").lazyload();

    var producttype = $("#pricearea").attr("name");
    var styleid = $("#styleinfo").attr("name");

    //点击到中图
    //var midChangeHandler = null;
    $("#imageMenu li span").live("mouseover", function () {
        if ($(this).attr("id") != "onlickImg") {
            midChange($(this).attr("name").replace("small", "mid"));
            $("#imageMenu li").removeAttr("id");
            $(this).parent().attr("id", "onlickImg");
        }
    });

    function midChange(src) {
        $("#midimg").attr("src", src).load(function () { changeViewImg(); });
    }

    //滑动左边小图
    $("#imageMenu").scrollTop(0);

    (function () {
        function mouseEnter(e) {
            if ($("#winSelector").css("display") == "none") {
                $("#winSelector,#bigView").show();
            }
            $("#winSelector").css(fixedPosition(e));
            e.stopPropagation();
            return false;
        }

        function mouseOut(e) {
            if ($("#winSelector").css("display") != "none") {
                $("#winSelector,#bigView").hide();
            }
            e.stopPropagation();
            return false;
        }

        if (document.createTouch) {
            $("#midimg,#winSelector").live("touchmove", mouseEnter).live("touchend", mouseOut);
        } else {
            $("#midimg, #winSelector").live("mouseenter", mouseEnter); //中图事件
            $("#winSelector").live("mousemove", mouseEnter); //选择器事件
            $("#midimg,#winSelector").live("mouseout", mouseOut);
        }

        var $divWidth = $("#winSelector").width(); //选择器宽度
        var $divHeight = $("#winSelector").height(); //选择器高度
        var $imgWidth = $("#midimg").width(); //中图宽度
        var $imgHeight = $("#midimg").height(); //中图高度
        var $viewImgWidth = $viewImgHeight = $height = null; //IE加载后才能得到 大图宽度 大图高度 大图视窗高度

        $(window).load(changeViewImg);

        $("#bigView").scrollTop(0);
        function fixedPosition(e) {
            if (e == null) {
                return;
            }
            var pageX = e.clientX + $(document).scrollLeft();
            var pageY = e.clientY + $(document).scrollTop();
            if (document.createTouch) {
                pageX = event.touches[0].pageX;
                pageY = event.touches[0].pageY;
            }

            var $imgLeft = $("#midimg").offset().left; //中图左边距
            var $imgTop = $("#midimg").offset().top; //中图上边距
            X = pageX - $imgLeft - $divWidth / 2; //selector顶点坐标 X
            Y = pageY - $imgTop - $divHeight / 2; //selector顶点坐标 Y

            X = X < 0 ? 0 : X;
            Y = Y < 0 ? 0 : Y;
            X = X + $divWidth > $imgWidth ? $imgWidth - $divWidth : X;
            Y = Y + $divHeight > $imgHeight ? $imgHeight - $divHeight : Y;

            if ($viewImgWidth == null) {
                $viewImgWidth = $("#bigView img").outerWidth();
                $viewImgHeight = $("#bigView img").height();
                if ($viewImgWidth < 200 || $viewImgHeight < 200) {
                    $viewImgWidth = $viewImgHeight = 800;
                }
                $height = $divHeight * $viewImgHeight / $imgHeight;
                $("#bigView").width($divWidth * $viewImgWidth / $imgWidth);
                $("#bigView").height($height);
            }

            var scrollX = X * $viewImgWidth / $imgWidth;
            var scrollY = Y * $viewImgHeight / $imgHeight;
            $("#bigView img").css({ "left": scrollX * -1, "top": scrollY * -1 });

            //确定上边距
            //用户视窗高度
            var viewH = document.documentElement.clientHeight == 0 ? document.body.clientHeight : document.documentElement.clientHeight;
            var top = ((viewH - $height) / 2) + $(document).scrollTop();
            top = top < 240 ? 240 : top;
            var left = 537;
            if (isIE6) {
                left = ie6.setLeft(left);
            }

            $("#bigView").css({ "top": top, "left": left });

            return { left: X, top: Y };
        }
    })();

    //售罄
    $("#saleout").live("click", function () {
        var productcode = $("#productcode").text().split("：")[1];
        var saleoutWidth = 466;
        var saleoutHeight = 208;
        ajaxIsLogined(function () {
            if (!isLogined) {
                saleoutWidth = 451;
                saleoutHeight = 156;
            }
            $.fn.popwindow({ width: saleoutWidth, height: saleoutHeight, title: "到货通知我",
                href: "http://www.vancl.com/Product/ProductSaleOutNotify.aspx?oper=1&productCode=" + productcode + "&r=" + Math.random()
            });
        });
        return false;
    });

    function selectedAmount_click() {
        var number = parseFloat($("#selectedAmount").val());
        re = /\d/g;
        var text = $(".cuxiaoPrice span").text().replace(/[\d|\.]+/g, function ($1, i) { if (i == 1) i = 2; else i = 0; return (parseFloat($1) * number).toFixed(i) });
        $(".goodsPrice em").text(text);
    }
    $("#selectedAmount").click(selectedAmount_click);
    selectedAmount_click();
    //分享
    (function () {
        var api = ["sina", "sohu", "qq", "qqzone", "kaixin", "renren", "douban"];

        $("#share a").live("click", function () {
            var index = $(this).prevAll("a").length;
            var img = $("#midimg").attr("src");
            var title = "我在凡客诚品看到了一个非常不错的商品：" + $.trim($("#styleinfo").text()) + "，仅售" + $.trim($(".cuxiaoPrice").find("strong").text()) + "元； " + $.trim($(".danpin_YhTsBox").find("li:first").text()) + " @VANCL粉丝团，地址：" + document.location.href.replace(/(demo|my)item/ig, "item");

            $.fn.share({ api: api[index], title: title, url: getencodelochref(), pic: img });
            return false;
        });
        function getencodelochref() {
            return encodeURIComponent(document.location.href.replace(/(demo|my)item/ig, "item"));
        }
    })();
    //成为VIP
    $(".question a").hover(function () {
        var divIframe = $("#vipiframe");
        if (divIframe.length == 0) {
            var divIframe = $("<iframe />");
            divIframe.attr("id", "vipiframe").attr("frameborder", "0").appendTo("body");
        }
        divIframe.attr("src", $(this).attr("href"))
            .css({ "width": 340, "height": 125, "top": $(this).offset().top + 20, "left": 650 })
            .show();
    }, function () { $("#vipiframe").hide() }).click(function () { return false; });

    if ($("#onlickColor .colorBlock").attr("name") == "True") {
        $("#comeon").fadeIn();
    }

    $(".dp_scbtn").live("click", function () {
        $("#collectbox,#shopbox").hide();
        ajaxIsLogined(function () {
            if (!isLogined) {
                openLoginDiv("addFavorite()");
            } else {
                addFavorite();
            }
        });
        return false;
    });
    //支付方式
    //$(".payRight a").popwindow({ width: 800, height: 380, title: "支付方式" });

    //库存信息
    var closeCode = getCloseCode();
    if (closeCode == null) {
        $(".cityAdd").click(function () {
            $(".danpin_xuanzeGMcm").show();
        });
    } else {
        //默认选择尺码
        //        $("#selectedSize").text(sizeLable() + "：" + $.trim($(".selSize #onlickSelSize").text()));
        //        $(".selSizeArea h3 strong").text($.trim($(".selSize #onlickSelSize").text()));

        $(window).load(checkStocking);
        SumPrice();
        $(".cityAdd").hover(stockIn, stockOut);
        $(".addressWindows").hover(stockIn, stockOut);
    }
    $(".goodsAddArea").fadeIn("slow");
    if (window.localStorage) {
        var myprovince = window.localStorage["myprovince"];
        if (myprovince == null) {
            myprovince = "北京";
        }
        $("span.goodsAdd").text(myprovince);
    } else if (document.body.style.behavior != "undefined") {
        var o = document.getElementById("bigView");
        o.style.behavior = "url('#default#userData')"
        o.addBehavior("#default#userData");
        o.load("my");
        var myprovince = o.getAttribute("province");

        if (myprovince == null) {
            myprovince = "北京";
        }
        $("span.goodsAdd").text(myprovince);
    }

    $(".addressWindows a").live("click", function () {
        $("span.goodsAdd").text($(this).text());
        //写入
        if (window.localStorage) {
            window.localStorage["myprovince"] = $(this).text();
        } else if (document.body.style.behavior != "undefined") {
            var o = document.getElementById("bigView");
            o.setAttribute("province", $(this).text());
            o.save("my");
        }
        checkStocking();
        return false;
    });

    (function () {
        $(".RsetTabMenu li").click(function () {
            var menu = $(".RsetTabMenu li");
            menu.removeClass("hover").addClass("down");
            $(this).addClass("hover").removeClass("down");
            var index = $(this).prevAll().length;
            var tabs = $(".RsetTabCon");
            tabs.hide();
            if ($.trim(tabs.eq(index).html()) == "") {
                $.get($(this).find("a").attr("href"), function (data) {
                    tabs.eq(index).html(data);
                }).success(function () { tabs.eq(index).show(); });
            } else {
                tabs.eq(index).show();
            }

            if (index > 0) {
                $(".RsetTabArea>.liketabfg,.RsetTabArea>.blank20,.RsetTabArea>.blank15,#starvancl").hide();
            } else {
                $(".RsetTabArea>.liketabfg,.RsetTabArea>.blank20,.RsetTabArea>.blank15,#starvancl").show();
                tabs.eq(1).show();
                tabs.eq(2).show();
            }

            return false;
        });
    })();

    $("#selectedAmount").live("change", SumPrice);

    $("#tiwen").click(function () {
        ajaxIsLogined(function () {
            if (!isLogined) {
                $.fn.alert('此操作需要登录，您现在要登录吗？', function (b) {
                    if (b)
                        location.href = 'https://login.vancl.com/login/login.aspx?' + location.href;
                }, { type: 2 });
            }
            else {
                $.fn.popwindow({
                    href: '/styles/static.aspx?position=Ask',
                    width: '821px',
                    height: "380px",
                    title: "提问"
                });
            }
        });
        return false;
    });

    $(".selectArea").hover(function () { $(this).css({ "border": "1px solid #b4b4b4" }); }, function () { $(this).css({ "border": "1px solid #fff" }); });

    //ajax显示区域
    $(window).one("scroll", function () {
        var productcode = $("#productcode").text().split("：")[1];
        $.get("/styles/ajaxload.aspx?productcode=" + productcode + "&producttype=" + producttype + "&styleid=" + styleid, function (data) {
            $(".danpinRight").append(($("#promotion", data).html()));
            $(".sideBarArea").append(($("#left", data).html()));
            $("#starvancl").append($("#starvancl", data).html());
            $(".hzcTitle").after($("#luckyguys", data).html());
            $(".dpShuXing ul").append($("#productporperty", data).html());
            if ($(".dpShuXing ul li").length > 0) { $("#attr").show(); } else { $("#attr").hide(); }

            if (typeof (vjiaAd) != "undefined" && vjiaAd.imageUrl && vjiaAd.imageLink) {
                try {
                    var adlink = "<a class='track' name='" + vjiaAd.track + "' href='" + vjiaAd.imageLink + "?source=" + vjiaAd.source + "' target='_blank'><img src='" + vjiaAd.imageUrl + "' style='width: 200px;height:220px;' /></a>";
                    $(".sideBarArea").append("<div class='itemad' style='width: 200px;height:220px;overflow:hidden;'>" + adlink + "</div>");
                } catch (e) { }
            }
            bindShowStarWindow();
            $lazyload = $(".danpin_TJtaozTab,#starvancl,.sideBarArea").find("img[original]").not("[src])");
            if ($lazyload.length > 0) { $lazyload.lazyload(); }
        });
        $.ajax({ "url": "//jsy.vanclimg.com/js.ashx?href=item/unimportant.js&compress&v=20120711", "cache": true, dataType: "script" });
    });

    //setShoppingUrl();
    //go up
    (function () {
        var viewH = document.documentElement.clientHeight == 0 ? document.body.clientHeight : document.documentElement.clientHeight;
        if (window.screen.width > $(document.body).width() + 100) {
            var scrollit = function () {
                if ($(window).scrollTop() == 0) {
                    goup.fadeOut();
                } else {
                    goup.fadeIn();
                    if (isIE6) {
                        goup.css({ "top": ie6.goUpTop() });
                    }
                }
            }
            var goup = $("<div style=\"right:0px;POSITION: absolute;z-index:1\"><a href=\"javascript:window.scrollTo(0,0);\"><div class=\"sprites\" style=\"width:34px;height:24px;background-position:-88px -321px\"></div></a></div>").hide();
            if (!isIE6) {
                goup.css({ "position": "fixed", "bottom": 5, "right": ($(window).width() / 2 - $(document.body).width() / 2 - 100) < 0 ? 0 : ($(window).width() / 2 - $(document.body).width() / 2 - 100) });
            } else {
                if ($(window).scrollTop() > 0) {
                    goup.css({ "top": ie6.goUpTop() }).show();
                }
                ie6.windowresize();
                $(window).resize(scrollit);
            }
            $(window).scroll(scrollit);
            $("body").prepend(goup);
        }
    })();

    //搭配翻页
    (function () {
        var pageCount = $("#relatedPager").find("a[id*='relatedPager_']").length;

        if (pageCount > 0) {
            $("#relatedLeft").hide();
            $("#relatedPager").find("a[id*='relatedPager_']").click(function () {
                var pagerID = $(this).attr("id");
                setRelatedCurent(pagerID);
                window.location.hash = "relatedshow";
                return false;
            });
            $("#relatedRight").click(function () {
                relatedPageStep(1);
                window.location.hash = "relatedshow";
                return false;
            });
            $("#relatedLeft").click(function () {
                relatedPageStep(-1);
                window.location.hash = "relatedshow";
                return false;
            });
        }
    })();
    (function () {
        //load后加载的
        $(window).load(function () {
            LimitPurchase();
            var styleID = $("#styleinfo").attr("name");
            //尺码计算器
            $.get('/SizeCalculate/IniColorBox.aspx?styleID=' + styleID,
                function (r) {
                    if (r) {
                        sizeCalObj = eval('(' + r + ')');
                        if (sizeCalObj.isHave) {
                            $("#sizeCal_text").show();
                            if (sizeCalObj.start) {
                                $("#showSizeCalculate").attr("href", "/SizeCalculate/PageRedirect.aspx?pageName=" + sizeCalObj.start);
                            }
                            $("#showSizeCalculate").popwindow({ width: '530px', height: '354px', noOverlayClose: true });
                        }
                    }
                }
            );
            //ref&pv实验记录
            //if (location.href.indexOf("ref=") > 0) {
            //    $.getScript("/api/trace.aspx?pv=true&" + location.href.substr(location.href.indexOf("?") + 1));
            //}
        });
    })();
});
//大视窗看图
function changeViewImg() {
    $("#bigView").empty().append("<span>正在加载中……</span><img style=\"display:none\"/>");
    $("#bigView img").load(function () { $("#bigView span").remove(); $(this).show(); }).attr("src", $("#midimg").attr("src").replace("mid", "big"));
}

//达人晒单
function bindShowStarWindow() {
    var productcode = $("#productcode").text().split("：")[1];
    $('#showstar').attr("href", "//seller.vancl.com/suit/show?productid=" + productcode);
    $('#showstar').unbind("click");
    $('#showstar').click(function () {
        ajaxIsLogined(function () {
            if (!isLogined) {
                $.fn.alert('此操作需要登录，您现在要登录吗？', function (b) {
                    if (b)
                    location.href = 'https://login.vancl.com/login/login.aspx?' + location.href;
                }, { type: 2 });
                return false;
            } else {
                if (isPurchased && isPurchased > 0) {
                    if (trialproductcode != '') {
                        $("#showstar").attr('href', "http://seller.vancl.com/suit/show?productid=" + trialproductcode);
                    }
                    $.fn.popwindow({ href: $("#showstar").attr('href'), width: '821px', height: "500px", title: "我要晒单" });
                } else {
                    $.fn.alert('您尚未购买此商品，或订单未完成，还不能晒单。');
                    return false;
                }
            }
        }, productcode);
        return false;
    });

    //$("#starItemPager a").attr({'class':'track', name:'item-showstar-2-f'});
    $("#starItemPager a").live('click', function(e){
            var url = $(this).attr("href");
            if (!url)
                return false;
            renderStar(url);
            return false;
    });
    function renderStar(url)
    {
        $.get(url, function(data){
            $("#starItem .bask").html($(".baskcontainer", data).html());
            $("#starItemPager").html($(".pagercontainer", data).html());    
        });
    }
}

function relatedPageStep(step) {
    var curObj = $("#relatedPager").find("strong").parent();
    var ID = curObj.attr("id");
    var arr = ID.split("_");
    var nextNum = Number(arr[1]) + step;
    var nextID = arr[0] + "_" + nextNum;
    setRelatedCurent(nextID);
}

function setRelatedCurent(id) {

    var curObj = $("#relatedPager").find("strong");
    var s = curObj.html();
    curObj.parent().html(s);
    $("#" + id).html("<strong>" + $("#" + id).html() + "</strong>");
    $(".relatedshow").removeClass("relatedshow").addClass("relatedhide");
    var i = 0;
    var c = 5;
    var showPageStart = Number(id.split("_")[1]) * c;
    var total = Number($("#relatedTotal").html());

    if (showPageStart + c >= total) {
        c = total - showPageStart;
        $("#relatedRight").hide();
    }
    else {
        $("#relatedRight").show();
    }
    if (showPageStart == 0) {
        $("#relatedLeft").hide();
    }
    else {
        $("#relatedLeft").show();
    }
    //alert(showPageStart)
    while (i < c) {
        var t = showPageStart + i;
        // alert(t);
        $("#relatedImage_" + t).removeClass("relatedhide").addClass("relatedshow");
        i++;
    }
}

function ChooseThisSize($this, SKU, maxNum) {
    $(".danpin_xuanzeGMcm").hide();
    $(".shoppingErrTips").remove();
    if (maxNum < 10) {
        $("#comeon").fadeIn();
    } else {
        $("#comeon").fadeOut();
    }
    $(".selSize li").removeAttr("id");
    $($this).attr("id", "onlickSelSize");
    maxNum = parseInt(maxNum);

    $($this).siblings().find("span").remove();

    $("<span></span>").appendTo($($this));
//    $("#selectedSize").text(sizeLable() + "：" + $.trim($($this).text()));
//    $(".selSizeArea h3 strong").text($.trim($($this).text()));
    var span = $("#selectedAmount option").length - maxNum;
    if (span > 0) {
        //减少option
        $("#selectedAmount option").eq(maxNum - 1).nextAll().remove();
    } else if (span < 0) {
        //增加option
        span = Math.abs(span);
        var array = new Array(span);
        $.map(array, function (n, i) {
            var val = parseInt($("#selectedAmount option:last-child").val()) + 1;
            $("#selectedAmount").append("<option value=\"" + val + "\">" + val + "</option>");
        });
    }
    checkStocking();
	SumPrice();
    $(".cityAdd").unbind();
    $(".cityAdd").hover(stockIn, stockOut);
    $(".addressWindows").hover(stockIn, stockOut);
}
//尺码计算器用到的变量
var preUrlArr = ['/SizeCalculate/PageRedirect.aspx?pageName=HWCompute'];
var sizeCalObj;
var preParam = {};

function setTab(name, cursel, n) {
    for (i = 1; i <= n; i++) {
        var menu = document.getElementById(name + i);
        var con = document.getElementById("con_" + name + "_" + i);
        menu.className = i == cursel ? "hover" : "";
        con.style.display = i == cursel ? "block" : "none";
    }
}
function recmApi(param, $container, relhead, track, position) {
    if ($container.length > 0) {
        $.getJSON("//app-recm.vancl.com/RecmService/GetProductByPosition" + "?jsoncallback=?",
        { strJson: param },
        function (data) {
            if (data.Success) {
                var productcode = $("#productcode").text().split("：")[1];
                var html = [];
                html.push("<h6>");
                html.push(data.Title);
                html.push("<a href='/favourate?productcode=" + productcode + "&p=" + position + "' style='color:#A10000;margin-left:120px;' class='track' name='" + track + "' target='_blank'>更多您可能喜欢的商品>></a></h6>");
                html.push("<ul>");
                $.each(data.Items, function (i, item) {
                    var url = "//item.vancl.com/" + item.ProductCode + ".html";
                    var rel = item.Ref + "_" + productcode;
                    html.push("<li>");
                    html.push("<div class=\"ygmPic\">");
                    html.push("<a class='track' name='"+track+"' href=\"" + url + "\" target=\"_blank\" rel=\"" + rel + "\">");
                    html.push("<img src=\"" + item.ImageUrl + "\" /></a></div>");
                    html.push("<a class=\"ygmName track\" name='"+track+"' href=\"" + url + "\" target=\"_blank\" rel=\"" + rel + "\">" + item.ProductName + "</a>");
                    html.push("<p class=\"ygmPrice\">");
                    html.push("<span>售价￥" + item.Price + "</span>");
                    html.push("</p>");
                    html.push("</li>");
                });
                html.push("</ul>");
                $container.html(html.join("")).show();
            }
            else {
                $container.hide();
            }
        });
    }
}
function addFavorite() {
    $("#collectboxloaging").html("<img src=\"//i.vanclimg.com/logo/loading.gif\" alt=\"loading\">");

    $.fn.popwindow.close();
    $("#collectbox").css({ "top": $(".dp_scbtn").offset().top - 100 }).show();

    if (isIE6) {
        $("#collectbox").css({ "left": ie6.setLeft(539) });
    }

    isLogined = true;
    setWelcome();
    var productcode = $("#productcode").text().split("：")[1];
    var paramJson = "[{Position:\"rp_item_favorite\", ProductCodes:\"" + productcode + "\",Rows:\"" + 5 + "\",Remark:\"NeedExclude\"}]";
    var $gmlist = $(".collectbox").find(".gmlist");	

	var jsonparam = {productcode:productcode};
	jsonparam.price = $.trim($(".cuxiaoPrice strong:eq(0)").text());
	jsonparam.endcatename = $.trim($(".breadNav a:last").text());
    $.getJSON("/api/likethis.aspx", jsonparam, function (json) {
        if (json.msg == "Y") {
            $("#collectbox").find(".msgboxhead2 a").click(function () {
                $("#collectbox").hide();
                $("#collectboxloaging").show().nextAll().hide();
				//reset marks area
				$(".fonttext,.tishi, .baocun").hide();
				$(".icte").val("");
				$(".inCti").find("span").removeClass().addClass("inCti_img02");
                return false;
            });
			recmApi(paramJson, $gmlist, "dp_collect_SimilarWatching", "item-favorite-pab", "favorite");
            $("#collectboxloaging").hide().nextAll().show();
			//load mark info
			$.getJSON("/api/FavoriteMark.aspx?styleid=" + $("#styleinfo").attr("name"), function(json){
				if (json.Success=='Y')
				{
					/*var mymarks = $.map(json.MyFavoriteMarks, function(n){return n.MarkName});
					$("#bq").val(mymarks.join(','));*/
					var remarks = json.CommonRemarks || [];
					if (remarks.length == 0)
					{
						var navs = $.map($(".breadNav a:gt(0)"), function(s){
							return $.trim($(s).text());
						});
						navs.reverse().splice(3-remarks.length);
						//ie6
						if (navs.length>3)
							navs.length=3;

						$.merge(remarks, navs);
					}
					else if(remarks.length>3)
					   remarks.length = 3;
					$("#commonmarks").hide();
					if (remarks.length > 0)
					{					
						$("#commonmarks").show().html("常用标签：" + $.map(remarks, function(s){return '<label><input type="checkbox" class="input" />'  + s + '</label>';}).join(' '));
					}
				}
		   });
        }
        else {
            $.fn.alert("添加错误。");
        }
    });
}

function openLoginDiv(functionName) {
    var url = [];
    url.push("https://login.vancl.com");
    url.push("/PublicControls/LoginDiv.aspx");
    url.push("?url=");
    url.push(escape(window.location.href));
    url.push("&location=");
    url.push(escape("http://item.vancl.com/styles/closeit.aspx?func=" + functionName));
    $.fn.popwindow({ href: url.join(""), width: 384, height: 463, title: "操作提示", noOverlayClose: true });
}

function CommentVote(url) {
    $.fn.popwindow.close();
    isLogined = true;
    setWelcome();
    url = unescape(url).replace("#mvc",".mvc")
    //问答
    var $span = $(".new-btn").find("a[href='" + url + "']").find("span");
    //评论
    if (!$span.html())
        $span = $(".new-btn[href='" + url + "']").find("strong em");
    
    $.ajax({ "url": url + "&t=" + Math.random(), "dataType": "text" })
            .success(function (msg) {
                if (msg == "Y") {
                    $span.fadeOut(function () {
                        var count = "(" + (parseInt($span.text().replace('\(', '').replace('\)', '')) + 1) + ")";
                        $span.text(count).fadeIn();

                    }).closest(".new-comment, .plDYinfo").find(".new-btn, .new-btn a").attr("href", "");
                } else {
                    $.fn.alert(msg);
                }
            }).error(function (msg) { $.fn.alert(msg) });
}

function LimitPurchase()
{
	function SetSelectStyle(direction, message, num)
	{
		var $selectedAmount = $("#selectedAmount");
		var $selectedOptions = $("#selectedAmount option");
		$selectedAmount.after("<span id='limitinfo' style='margin-left:5px;'>"+message+"</span>");
		var $options = $selectedOptions.eq(num-1).prevAll();
		if(direction=='down'){
			$options = $selectedOptions.eq(num-1).nextAll();			
		}
		$options.attr("disabled", true);
		if ($.browser.msie && $.browser.version <= 7)
		{
			$options.css({color:"graytext"});
			$selectedAmount.unbind("focus").focus(function(){$(this).data("f", this.selectedIndex);});
			$selectedAmount.unbind("change").change(function(){
				var b = direction=='down'?this.selectedIndex>num-1:this.selectedIndex<num-1;
				if(b)
					this.selectedIndex=$(this).data("f");
				else{
					$(this).data("f", this.selectedIndex);
				}
			});
		}
		if ($.browser.msie && $.browser.version == 8){
			$selectedAmount.unbind("keypress").keypress(function(e){
				var key=e.keyCode;						
				var b = direction=='down'? key > (num+48): key < (num+48);
				if (key>48 && key<58 && b){
					if (key == 49 && direction=='down')
						this.selectedIndex=0;
					return false;
				}
			});
		}
	}
	$("#selectedAmount").next("#limitinfo").remove();
    var productcode = $("#productcode").text().split("：")[1];
	//丝袜限购		——> 起购
	if ((productcode=='0003338' || productcode=='0168974') && new Date() < new Date(2012,08, 01))
	{
		if ($("#selectedAmount option").length>2){
			SetSelectStyle('up', "本商品3件起购", 3);
			$("#selectedAmount").get(0).selectedIndex=2;
			SumPrice();
		}
		return;
	}
	//其他产品限购	——> 限购
	$.getJSON("api/LimitPurchase.aspx?productcode="+productcode, function(json){		
		if (json.msg == 'Y' && typeof(json.direction) != 'undefined')
			SetSelectStyle(json.direction, json.err, json.num);
	});
}

function SumPrice()
{
	if (getCloseCode())
	{
		var v = Number($("#selectedAmount").val());
		var p = Number($(".cuxiaoPrice strong").eq(0).text());
		$(".goodsCar span span").html((v*p).toFixed(2));
	}
}

//$(function () {
//    if ($.trim($('#skey').val()).length == 0) {
//        $.ajax({
//            url: '/api/defaultautocompleteitems.aspx?callback=?',
//            dataType: 'jsonp',
//            success: function (result) {
//                defaultAutocompleItem = result;
//                $('#skey').val(' ' + defaultAutocompleItem.description);
//            }
//        });
//    }
//});