﻿$(function() {


    //搜索页面鼠标放上去的效果
    $(".s_list").hover(
      function() { $(this).css("border-color", "#ff5500"); },
      function() { $(this).css("border-color", "#eeeeee"); }
      );
    //首页排行
    $(".index_o_list li").hover(
    function() {
        var obj = $(this);
        $(this).parent("ol").find("li").each(function() {
            $(this).removeClass("frist");
            $(this).addClass("unselect");
        });
        obj.addClass("frist");
    },
    function() { }
    );
    //滑动滚动条
    $(window).scroll(function() {
        if ($(this).scrollTop() > 190)
            $(".fast_menu").css("top", $(this).scrollTop() - 190);
        else
            $(".fast_menu").css("top", 0);

    });
    //////购物车中原价购买商品
    $("#Originalbuing").click(function() {
        $.ajax({
            url: "/CartHandler.ashx",
            type: "GET",
            data: "action=Original",
            success: function(result) {
                alert(result);
            }
        })
    });

    //

    //咨询
    $("#question-btn").click(function() {
        var consultCategory = -1;
        $("input[name='consultCategory']").each(function() {
            if ($(this).attr("checked") == true)
                consultCategory = $(this).attr("value")
        })
        if (consultCategory == -1)
            alert("请选择咨询类别");
        else if ($("#questionArea").val() == "")
            alert("您忘记说点什么")
        else {
            $.ajax({
                url: "/ConsultHandler.ashx",
                datatype: "JOSN",
                type: "GET",
                data: "action=add&itemid=" + $("#itemid").val() + "&categoryid=" + consultCategory + "&content=" + escape($("#questionArea").val()),
                success: function(result) {
                    if (result != null && result != "") {
                        alert(result);
                        GetConsult(consultCategory, 5, 0);
                        $("#c_question").css("display", "none");
                    }
                    else
                        alert('请填写您想要咨询的相关内容！');
                }
            })
        }
    });

    //咨询1  gong公告咨询
    $("#question-btn1").click(function() {
        var NoticeId = 0;  //表示公告ID
        NoticeId = $("#itemid").val();
        if ($("#questionArea").val() == "")
            alert("您忘记说点什么")
        else {
            $.ajax({
                url: "/ConsultHandler.ashx",
                datatype: "JOSN",
                type: "GET",
                data: "action=add&itemid=" + NoticeId + "&categoryid=-1&content=" + escape($("#questionArea").val()),
                success: function(result) {
                    if (result != null && result != "") {

                        GetConsult(NoticeId, 5, -1);
                        $("#c_question").css("display", "none");
                    }
                    else
                        alert('请填写您想要咨询的相关内容！');
                }
            })
        }
    });
    if ($(".jqzoom").length > 0) {
        //放大图片
        var options =
            {
                zoomWidth: 350,
                zoomHeight: 290
            }

        $(".jqzoom").jqzoom(options);
    }
    //比较
    $(".c_button").click(function() {
        var flag = 0;
        if (cookies.Get(CompareCookies) != null && cookies.Get(CompareCookies) != "undefined") {
            var currentSelect = cookies.Get(CompareCookies).split(':');
            if (currentSelect.length < 2) {
                alert("至少两件以上产品才能做比较？");
                return false;
            }
            var categoryid = currentSelect[1].split('$')[0];
            for (var i = 1; i < currentSelect.length; i++) {
                if (categoryid != currentSelect[i].split('$')[0])
                    flag = 1
            }
        }
        if (flag == 1) {
            alert("不同类别的产品不能作比较");
            return false;
        }
        else
            return true;
    })
    if ($("#itemid").length > 0) {

        //获取相关商品
        $.ajax({
            url: "/ProductHandler.ashx",
            datatype: "JOSN",
            contentType: "application/json;charset=utf-8",
            type: "GET",
            data: "action=3&itemid=" + $("#itemid").val(),
            beforeSend: function() {
                $("#div_conn_item").html("<div style='text-align:center;'><img src=\"/images/ajax.gif\" alt=\"数据加载中\" /></div>");
            },
            success: function(result) {
                if (result != '[]') {
                    var josn = eval("(" + result + ")");
                    var html = "" +
                   '  <div class="borderdiv">' +
                   '     <h2>' +
                   '         看过该商品的还看过' +
                   '     </h2>' + GetConnItemListHtml(josn) +
                    '            <div class="clearDiv"></div></div>';
                    $("#connItem").html(html);
                }
            }
        })
        //获取以前浏览商品
        var cookiesname = "ItemToItem";
        var maxCount = 9;
        var itemToItem = $.cookie(cookiesname);
        if ($("#itemid").length > 0 && $("#itemid").val() != "0") {
            if (itemToItem == null || itemToItem == "") {
                //重新设置itemtoitem
                itemToItem = "[" + GetCurrentItem() + "]";
            } else {
                var josn = eval("(" + itemToItem + ")");
                var otlist = "";
                var html = "" +
'             <div class="c_right" style="min-height:0">' +
'                <div class="d_r_menu">最近浏览</div>' +
'                    <div id="div_near_view" style="height:auto;" >' + GetReviewItemListHtml(josn)
                '                </div>' +
'            </div>';
                $("#lview").html(html);
                //重新设置itemtoitem
                //判断是否已经包含该记录
                var bHaveItem = false;
                for (var i = 0; i < josn.length; i++) {
                    if (josn[i].Id + "" == $("#itemid").val()) {
                        bHaveItem = true;
                        break;
                    }
                }
                if (bHaveItem) {
                    //已经包含该商品,交换该商品到最后一个
                    itemToItem = "[";
                    for (var i = 0; i < josn.length; i++) {
                        if (josn[i].Id + "" != $("#itemid").val()) {
                            itemToItem += GetItem(josn[i]) + ",";
                            otlist += josn[i].Id + "|";
                        }
                    }
                    itemToItem += GetCurrentItem() + "]";
                }
                else {
                    if (josn.length < maxCount) {
                        itemToItem = itemToItem.substr(0, itemToItem.length - 1) + ',' + GetCurrentItem() + "]";
                    }
                    else {
                        itemToItem = "[";
                        for (var i = 1; i < maxCount - 1; i++) {
                            itemToItem += GetItem(josn[i]) + ",";
                            otlist += josn[i].Id + "|";
                        }
                        itemToItem += GetCurrentItem() + "]";
                    }
                }
                //上传关联信息
                if (otlist.length > 0) {
                    $.ajax({
                        url: "/ProductHandler.ashx",
                        type: "GET",
                        cache: false,
                        data: "action=4&itemid=" + $("#itemid").val() + "&otitemid=" + otlist.substr(0, otlist.length - 1) + "&t=" + (new Date().getMilliseconds())
                    })
                }
            }
            //记录最近浏览
            //$.cookie(cookiesname,itemToItem,{expires:7, path:"/", domain:"wagest.com", secure: false});
            $.cookie(cookiesname, itemToItem, { expires: 7, secure: false, path: "/" });
        } else {
            //非产品页面
            if (itemToItem != null && itemToItem != "") {
                var josn = eval("(" + itemToItem + ")");
                var otlist = "";
                var html = "" +
            '             <div class="c_right" style="min-height:0">' +
            '                <div class="d_r_menu">最近浏览</div>' +
            '                    <div id="div_near_view" >' + GetReviewItemListHtml(josn)
                '                </div>' +
            '            </div>';
                $("#lview").html(html);
            }
        }
        //收藏夹按钮
        $("#button_wishlist").click(function() {
            $.ajax({
                url: "/ProductHandler.ashx",
                type: "GET",
                data: "action=6&itemid=" + $("#itemid").val() + "&t=" + (new Date().getMilliseconds()),
                success: function(result) {
                    alert(result);
                }
            })
        });
        //到货通知
        $("#button_notice").click(function() {
            if ($("#productid").val() != "") {
                $.ajax({
                    url: "/ProductHandler.ashx",
                    type: "GET",
                    data: "action=8&itemid=" + $("#productid").val() + "&t=" + (new Date().getMilliseconds()),
                    success: function(result) {
                        if (result != null && result != "") {
                            alert(result);
                        }
                    }
                })
            }
            else {
                alert('请选择型号！');
            }
        });
        //降价提醒
        $("#button_price").click(function() {
            if ($("#productid").val() != "") {
                $.ajax({
                    url: "/ProductHandler.ashx",
                    type: "GET",
                    data: "action=9&itemid=" + $("#productid").val() + "&t=" + (new Date().getMilliseconds()),
                    success: function(result) {
                        if (result != null && result != "") {
                            alert(result);
                        }
                    }
                })
            }
            else {
                alert('请选择型号！');
            }
        });
        //提示框
        $("#inputShow").click(function() {
            $.ajax({
                url: "/ProductHandler.ashx",
                type: "GET",
                data: "action=115&itemid=" + 0 + "&t=" + (new Date().getMilliseconds()),
                success: function(result) {
                    if (result != null && result != "") {
                        var str = GetShowMess(result);
                        $("#showM").html(str);
                    }
                }
            })

        });

        //        //参加活动
        //        $("#button_price").click(function() {
        //            if ($("#productid").val() != "") {
        //                $.ajax({
        //                    url: "/ProductHandler.ashx",
        //                    type: "GET",
        //                    data: "action=9&ActvityId=" + $("#productid").val() + "&t=" + (new Date().getMilliseconds()),
        //                    success: function(result) {
        //                        if (result != null && result != "") {
        //                            alert(result);
        //                        }
        //                        
        //                    }
        //                })
        //            }
        //            else {
        //                            alert('请选择型号！');
        //                        }
        //        });
        //选择型号时样式

    }
})
function GetShowMess(josn) {
    var str = "";
    for (var i = 0; i < josn.length; i++) {
        var Mess = josn[i];
        if (Mess != null && Mess != "") {
            str += Mess.Msg + "dddddddddddddd";
        }
    }
    return str;
}
//same itemonError="ImgError(this)" src='<%=Wagest.Comm.Comm.GetImgSrc(itemInfo.PicPath,300,250) %>
function GetRightItemListHtml(josn) {
    var str = "";

    for (var i = 0; i < josn.length; i++) {
        var item = josn[i];
        if (item != null && item.Id != null && item.PicPath != null && item.PicPath != "undefined") {
            str += "<DL style='margin-left:10px;  margin-right:15px;'>" +
            "<DD style='background:white; text-algin:center'><A title='" + item.Name + "' href=\"http://www.wagest.com/product/" + item.Id + ".html\">" +
            "<IMG onError=\"ImgError(this)\"  border=0 style='width:80px;height:80px:overflow:hide;' alt=\"" + item.Name + "\" src='" + GetImgSrc(item.PicPath, 80, 80) + "'></A> </DD>" +
            "<DD style=\" PADDING-TOP:5px; \"><a title='" + item.Name.replace(" ", "").replace("（", "(").replace("）", ")") + "' href='/product/" + item.Id + ".html'>" + item.Name + "</a></DD>" +
            "<DD style=\"line-height:20px; COLOR: #3366ff; PADDING-TOP: 0px;\"><div style='float:left;width:100px;'> <span class='price'>" + (item.LowPrice == item.HighPrice ? item.LowPrice : (item.LowPrice + '~' + item.HighPrice)) + "</span></div><a href=\"http://www.wagest.com/product/" + item.Id + ".html\" class='smallBuy'></a></DD></DL>" +
            "<div class='clearDiv'></div>";
        }
    }
    return str;
}
//review
function GetReviewItemListHtml(josn) {
    var str = "";
    for (var i = josn.length - 1; i >= 0; --i) {
        var item = josn[i];
        if (item != null && item.Id != null && item.PicPath != null && item.PicPath != "undefined") {
            //            alert(item + typeof (item) + item.Id);
            str += "<DL style='width:52px;height:65px;margin-left:2px;float:left;overflow:hidden;text-algin:center'>" +
            "<DD style='background:white; text-algin:center'><A href=\"http://www.wagest.com/product/" + item.Id + ".html\">" +
            "<IMG onError=\"ImgError(this)\" style='border:1px solid #f4f4f4;width:40px;height:40px;display:block' alt=\"" + item.Name + "\" src='" + GetImgSrc(item.PicPath, 40, 40) + "'></A> </DD>" +
            "<DD style=\" PADDING-TOP: 0px; text-align:center\"> ¥" + (item.LowPrice == item.HighPrice ? item.LowPrice : (item.LowPrice + '~' + item.HighPrice)) + "</DD></DL>";
        }
    }
    return str + "<div style='border-top: 1px dashed #cccccc; height:25px; line-height: 25px; text-align: right;padding-right: 5px;clear:both'><a href='javascript:void(0)' onclick='clearReview();'>清空</a></div>";
}
function clearReview() {
    $.cookie("ItemToItem", null, { expires: -1, secure: false, path: "/" });
    var html = "" +
'             <div class="c_right" style="min-height:0">' +
'                <div class="d_r_menu">最近浏览</div>' +
'                    <div id="div_near_view" ></div>' +
'            </div>';
    $("#lview").html(html);
}
//获得conn商品
function GetConnItemListHtml(josn) {
    var str = '';
    for (var i = 0; i < josn.length; i++) {
        var item = josn[i];
        if (item != null && item.Id != null && item.PicPath != null && item.PicPath != "undefined") {
            str += "<ul class='n_product_list'";
            if (i == 0) str += "style='background-image:none'";
            str += "><li class='n_productImg'><A href=\"http://www.wagest.com/product/" + item.Id + ".html\">" +
            "<IMG onError=\"ImgError(this)\" border=0 alt=\"" + item.Name + "\" src='" + GetImgSrc(item.PicPath, 80, 80) + "'></A> </li>" +
            "<li class='n_productName'>" + item.Name + "</li>" +
            "<li class='n_productPrice'> <span class='price'>" + (item.LowPrice == item.HighPrice ? item.LowPrice : (item.LowPrice + '~' + item.HighPrice)) + "</span></li></ul>";
        }
    }
    return str;
}

function GetItem(item) {
    return "{\"Id\":" + item.Id + ",\"Name\":\"" + item.Name + "\",\"PicPath\":\"" + item.PicPath + "\",\"LowPrice\":" + item.LowPrice + ",\"HighPrice\":" + item.HighPrice + "}";
}

function GetCurrentItem() {
    return "{\"Id\":" + $("#itemid").val() + ",\"Name\":\"" + $("#itemName").val() + "\",\"PicPath\":\"" + $("#itemPicPath").val() + "\",\"LowPrice\":" + $("#itemLowPrice").val() + ",\"HighPrice\":" + $("#itemHighPrice").val() + "}";
}
//选中商品
function GetModel(nameid, valueId, obj) {
    var sv = $("#selectedModel").val();

    var regex = new RegExp("{" + nameid + ":\\d*}");
    $("#selectedModel").val(sv.replace(regex, "{" + nameid + ":" + valueId + "}"));
    $("a[name='modelName" + nameid + "']").css("border", "1px dashed #dcdddd").css("background-position", "100px 100px").css("color", "#999999");
    // $("model" + valueId).css("border", "1px solid red").css("background", "url(/images/s.gif) right bottom no-repeat").css("color", "#ff5500");
    $(obj).css("border", "1px solid red").css("background", "url(/images/s.gif) right bottom no-repeat").css("color", "#ff5500");

    if (CheckSelect() != false) {
        //a.b.c=0;
        $.ajax({
            url: "/ProductHandler.ashx",
            datatype: "JOSN",
            contentType: "application/json;charset=utf-8",
            type: "GET",
            data: "itemid=" + $("#itemid").val() + "&action=5&model=" + CheckSelect() + "&t=" + new Date().getMilliseconds(),
            success: function(result) {

                if (result == null || result == "" || result.substr(0, 1) != "{") {
                    $("#d_mallprice").html("价格未定");
                    $("#button_buy").css("display", "none");
                    $("#button_notice").css("display", "block");
                }
                else {
                    var josn = eval("(" + result + ")");
                    //alert(result.toString());

                    //                    $("#d_regprice").html("¥" + josn.RegPrice);
                    var savePrice = "¥" + Math.round((josn.RegPrice - josn.Price) * 100) / 100;
                    //                    $("#d_mallprice").html(josn.Price);
                    //                    $("#itemLowPrice").val(josn.Price);
                    ShowPrivilege(josn.Id, josn.Price, josn.RegPrice, savePrice);
                    $(".ComboPrice").each(function() {
                        $(this).html(josn.Price + parseFloat($(this).attr('price')))

                    });
                    try { $("#privilegePrice").html(((josn.Price - $("#discount").val()) * 100) / 100).toFixed(2) }
                    catch (Error) { }
                    if ($("#dh").val == "true") {
                        $("#SelectedText").html(josn.Name + "&nbsp;&nbsp;货源充足");
                        $("#productid").val(josn.Id);
                        return;
                    }
                    else
                        $("#SelectedText").html(josn.Name + "&nbsp;&nbsp;" + GetInventoryStatus(josn.Status));

                    //    if (josn.Status < 5 || !josn.IsDiaohuo && josn.Inventory <= 0)
                    if (
                        (josn.IsDiaohuo && josn.Status < 5) || (!josn.IsDiaohuo && (josn.Status < 5 || josn.Inventory <= 0))) {
                        $("#button_buy").css("display", "none");
                        $("#button_notice").css("display", "block");

                        $("#SelectedText").html(josn.Name + "&nbsp;&nbsp;<font color='red'>缺货</font>");
                    }
                    else {
                        $("#button_buy").css("display", "block");
                        $("#button_notice").css("display", "none");

                    }
                    $("#productid").val(josn.Id);
                    ClickByModelChoose(josn.Id)

                    // alert('getmode击事件调用ShowPrivilege');
                    //alert( $("#productid").val());
                }
            }
        })
    }
}

function GetInventoryStatus(id) {

    switch (id) {
        case 0: return "未知";
        case 1: return "<font color='red'>停产</font>";
        case 2: return "<font color='red'>已下架</font>";
        case 3: return "<font color='red'>即将上市</font>";
        case 4: return "<font color='red'>缺货</font>";
        case 5: return "货源紧张";
        case 6: return "货源充足";
    }
}
function buing(a) {
    if (!beChooseProduct())
        return;
    var url = "/ModelChoose.aspx?iid=" + $("#itemid").val() + " &pid=" + $("#productid").val() + "&comboId=" + $("#comboId").val() + "&ScoreAIID=" + $("#ScoreAIID").val();

    if (a != null || a != undefined)
        url = "http://www.wagest.com/ModelChoose.aspx?iid=" + a + " &pid=&comboId=";
    url += "&t=" + new Date().getMilliseconds();
    var str = "<iframe id='iframe1' src='" + url + "' marginheight=0  marginwidth=0  onload='this.height=iframe1.document.body.scrollHeight;this.width=iframe1.document.body.scrollWidth' frameborder=0 scrolling=no width=\"95%\" height=\"auto\" style='z-index:34;overflow:hiden' />";
    var d = $(window);
    $.weeboxs.open(str, { position: 'center', title: '', showButton: false });
    //解决ie6问题
    var ieversion = navigator.appVersion.split(";")[1].replace(/[ ]/g, "");
    if (ieversion == "MSIE6.0") {
        setTimeout("$('div.weedialog2.weebox iframe:last').get(0).src = '" + url + "'", 500);
        // setTimeout("$('div.weedialog2.weebox iframe:last').get(0).document.body.innerHTML = $('div.weedialog2.weebox iframe:last').get(0).document.body.innerHTML", 50);
        //    var iframe = $('div.weedialog2.weebox iframe').get(1);
        //    if (iframe != null)
        //           iframe.src = url;
    }
    return false;
}

function CheckSelect() {
    var sv = $("#selectedModel").val();
    if (/:0/.test(sv))
    //if (beChooseProduct())
        return false;
    else {
        var result = ""
        var data = sv.match(/:(\d*)/g);
        for (var i = 0; i < data.length; i++)
            result += data[i];
        return result.replace(":", "");
    }
}

function GetConsult(id, num, flag) {

    for (var i = 1; i <= num; i++) {
        try {
            if (id == i)
                document.getElementById('consult' + i).className = 'pro_d_m_select';
            else
                document.getElementById('consult' + i).className = 'pro_d_m_unselect';
        } catch (e) { }
    }
    $("#consultCategoryId").val(id);
    ConsultAjaxDate(1, flag)

}
//获取咨询
function ConsultAjaxDate(page, flag) {
    //  alert('asdf');


    if ($("#itemid").length > 0) {
        $.ajax({
            url: "/ConsultHandler.ashx",
            datatype: "JOSN",
            contentType: "application/json;charset=utf-8",
            type: "GET",
            data: "itemid=" + $("#itemid").val() + "&flag=" + flag + "&categoryid=0&pagesize=5&currentpage=" + page + "&t=" + new Date().getMilliseconds(),
            beforeSend: function() {
                $("#consultContentList").html("<div style='text-align:center;'><img src=\"/images/ajax.gif\" alt=\"数据加载中\" /></div>");
            },
            success: function(result) {
                var josn = eval("(" + result.split('&')[0] + ")");
                $("#consultContentList").html(GetConsultHtml(josn, flag));
                NewSetPage(parseInt(result.split('&')[1]), page, "setpage");
            }
        });
    }
}

function GetConsultHtml(josn, flag) {

    if (flag == -1) //表示是公告讨论
    {
        var str = "<dl>";
        for (var i = 0; i < josn.length; i++) {

            str += "<dd class=\"consult_q\">" + josn[i].UserName + "：" + josn[i].ConsultContent + "<span>" + renderTime(josn[i].ConsultDate) + "</span><a href='#' onclick='replayCosult(" + josn[i].Id + ")'>回复</a></dd>"
            str += "<dd id='ReAssessDiv_" + josn[i].Id + "'>" + showAllReCosult(josn[i].Id) + " </dd>";
            if (josn[i].Reply != null && josn[i].Reply != "") {
                str += "<dd class=\"consult_a\">" + josn[i].Reply + "<span>" + renderTime(josn[i].ReplyDate) + "</span></dd>"
            } else
                str += "<dd class=\"consult_a\"></dd>";
            str += " <br style=\"clear: both\" />";

        }
        return str + "</dl>";


    }
    else {

        var str = "<dl>";
        for (var i = 0; i < josn.length; i++) {
            str += "<dd class=\"consult_q\">" + josn[i].UserName + "：" + josn[i].ConsultContent + "<span>" + renderTime(josn[i].ConsultDate) + "</span></dd>"
            if (josn[i].Reply != null && josn[i].Reply != "")
                str += "<dd class=\"consult_a\">" + josn[i].Reply + "<span>" + renderTime(josn[i].ReplyDate) + "</span></dd>"
            else
                str += "<dd class=\"consult_a\"></dd>";
            str += " <br style=\"clear: both\" />";

        }
        return str + "</dl>";
    }
}
//解析时间
function renderTime(data) {
    if (data == null)
        return;
    var da = eval('new ' + data.replace('/', '', 'g').replace('/', '', 'g'));
    //return da.getFullYear() + "-" + da.getMonth() + "-" + da.getDay() + "-" + da.getHours() + ":" + da.getSeconds() + ":" + da.getMinutes();
    return da.toLocaleString();
}
//分页
var page;
var NewSetPage = function(pagecount, currentpage, id) {
    page = new SetPage(pagecount, currentpage, id);
    return page;
}

var SetPage = function(pagecount, currentpage, id) {
    this.currentpage = currentpage;
    this.count = pagecount;
    this.id = id;
    this.toPage(this.currentpage);
}

SetPage.prototype.toPage = function(page) {
    var html = "";
    if (this.count >= 1) {
        html = '<span id="info">' + page + '/' + this.count + '页</span>';
        if (page > 10) {
            html += '<a style="width:30px;" href="javascript:page.gototab(0)"><<</a>';
        }
        for (i = parseInt((page - 1) / 10) * 10 + 1; i <= this.count; i++) {
            if (i == page) {
                html += '<span class="current">' + i + '</span>';
            }
            else {
                html += '<a href="javascript:page.gotopage(' + i + ')">' + i + '</a>';
            }
            if (i == (parseInt((page - 1) / 10) + 1) * 10) {
                break;
            }
        }
        if (parseInt((page - 1) / 10) < parseInt(this.count / 10)) {
            html += '<a style="width:30px;" href="javascript:page.gototab(1)">>></a>';
        }
    }
    document.getElementById(this.id).innerHTML = html;
    document.getElementById(this.id).className = this.id;
}

SetPage.prototype.gotopage = function(page) {
    this.currentpage = page;
    this.loadPage(this.currentpage);
    this.toPage(page);
}
SetPage.prototype.gototab = function(tab) {
    if (tab == 1) {
        this.currentpage = (parseInt((this.currentpage - 1) / 10) + 1) * 10 + 1;
    }
    else if (tab == 0) {
        this.currentpage = (parseInt((this.currentpage - 1) / 10) - 1) * 10 + 1;
    }
    this.loadPage(this.currentpage);
    this.toPage(this.currentpage);
}
SetPage.prototype.loadPage = function(page) {
    ConsultAjaxDate(page);
}

//比较
var CompareCookies = "CompareCookies";
var maxCount = 4
var cookies =
  {
      Get: function(name) {
          return jQuery.cookie(name);
      },
      Set: function(name, value) {
          jQuery.cookie(name, value, { expires: 7, path: "/", domain: "wagest.com", secure: false });
      }
  }
//cookies
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
    else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}
var Compares =
{
    Add: function(categoryId, itemId, itemPic) {

        if (!this.HasOne(itemId)) {
            var items = cookies.Get(CompareCookies);
            var count = 0
            if (cookies.Get(CompareCookies) != null)
                count = parseInt(cookies.Get(CompareCookies).split(':').length);
            if (count >= maxCount) {
                alert('最多只能比较三件产品');
            }
            else {
                items += ":" + categoryId + "$" + itemId + "$" + itemPic;
                cookies.Set(CompareCookies, count + 1)
            }
            cookies.Set(CompareCookies, items);
        }
        else
            alert('对比框中已经有该商品了');
        Compares.showGSelected();
    },
    HasOne: function(itemId) {
        var reg = new RegExp("\\$" + itemId + "\\$");
        return reg.test(cookies.Get(CompareCookies))
    },
    RemoveAll: function() {
        return cookies.Set(CompareCookies, '');
        Compares.showGSelected('gCompare');
    },
    Remove: function(id) {
        var reg = new RegExp(":\\d*\\$" + id + "\\$\[^:]*")
        var currentSelect = cookies.Get(CompareCookies).replace(new RegExp('\/', 'g'), '%2f').split(':')
        for (var i = 1; i < currentSelect.length; i++) {
            if (currentSelect[i].split('$')[1] == id) {
                cookies.Set(CompareCookies, cookies.Get(CompareCookies).replace(reg, ''))
            }
        }
        Compares.showGSelected();
    },
    showGSelected: function() {
        var html = '';
        if (cookies.Get(CompareCookies) != null && cookies.Get(CompareCookies) != "undefined") {
            $("dl[class='comp_li'] dd").each(function() { $(this).html("") })
            var currentSelect = cookies.Get(CompareCookies).split(':')
            for (var i = 1; i < currentSelect.length; i++) {
                var divid = "comp_del_" + currentSelect[i].split('$')[1]
                $("dl[class='comp_li'] dd").eq(i - 1).html("<div id='" + divid + "' class='comp_del'onclick=\"Compares.Remove('" + currentSelect[i].split('$')[1] + "');\"  title='移出'></div><img onError=\"ImgError(this)\"  src='" + GetImgSrc(currentSelect[i].split('$')[2], 40, 40) + "' alt='' onmouseover=\"$(\'#" + divid + "\').show()\"  />")

            }
        }
    }
}

function Compare(categoryid, itemid, pic, obj) {
    if (obj.checked)
        Compares.Add(categoryid, itemid, pic);
    else
        Compares.Remove(itemid);
}

//设置星号,(值,div,最大值)
function SetRating(value, div, max, consultCount) {
    if (max == null || max < 1)
        max = 5;
    if (value == null || value <= 0 || value > max)
        value = max;
    if (div == null)
        div = "div_rating";
    if (consultCount == null)
        consultCount = "";
    else
        consultCount = "<a href='/product/" + div.replace("div_rating", "") + ".html#lmsg'>[" + consultCount + "]</a>";
    var html;
    intvalue = Math.floor(value);
    html = "<div class='Rating'>"
    for (var i = 1; i <= max; ++i) {
        if (i < intvalue)
            html += "<span/>";
        else if (i == intvalue) {
            html += "<span/>";
            if (intvalue < value) {
                //悬浮一层
                html += "<span style='position:absolute;z-index:99;width:" + Math.round((value - intvalue) * 16) + "px;'/>";
            }
        }
        else
            html += "<span style='background-position:0px 0px;'/>";
    }
    if (consultCount == "")
        html += "&nbsp;" + value + '分';
    html += consultCount + "</div>"
    $("#" + div).html(html);
}

//获取得分
function GetScore(obj) {
    var a = obj.split(',')
    for (var i = 0; i < a.length; i++) {
        var id = a[i];
        if (id != null && id != undefined && id != "")
            $.get("/consulthandler.ashx?action=getscore&id=" + id, function(data) {
                if (data.split(':')[2] > 0)
                    SetRating(formatFloat(data.split(':')[0], 2), "div_rating" + data.split(':')[1], 5, data.split(':')[2]);
            })
    }
}

function change_option(number, index) {
    for (var i = 1; i <= number; i++) {
        try {
            document.getElementById('current' + i).className = 'pro_d_m_unselect';
            document.getElementById('pro_des_content' + i).style.display = 'none';
        } catch (e) { }
    }

    try {
        document.getElementById('current' + index).className = 'pro_d_m_select';
        document.getElementById('pro_des_content' + index).style.display = 'block';
        document.getElementById('TabId').value = index;


    } catch (e) {
    }
}

function scroll_position(f) {
    var c = $("#" + f); c.show();
    var a = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

    var e = $("#questionArea").offset().top - document.documentElement.clientHeight;
    var d = $("#top").offset().left + 930;
    var b = a + document.documentElement.clientHeight - 190; c.css({ left: d + "px", top: b + "px" });
    // (a > 0) ? c.find(".go_top").fadeIn() : c.find(".go_top").fadeOut(); (a > e) ? c.find(".go_comment").fadeOut() : c.find(".go_comment").fadeIn()

}
function selectMenu(id) {
    var obj = $("#fristMenu li");
    obj.removeClass("no-selected").removeClass("selected").addClass("no-selected");
    $(obj.eq(id - 1)).removeClass("no-selected").addClass("selected");
    $("#m_menu_li" + id + "").get(0).fireEvent("onmousemove");
}
function formatFloat(src, pos) {
    return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
}
//产品图片加载错误
function ImgError(img) {
    try {
        var osrc = img.src;
        var re = new RegExp("/(\\d*)_(\\d*)/", "");
        var re2 = new RegExp("com/", "");
        var w = osrc.match(re)[1];
        var h = osrc.match(re)[2];
        img.src = (osrc.replace(re, "/").replace(re2, "com/GetImages.aspx?img=") + "&w=" + w + "&h=" + h);
    } catch (e) { }
}
//获得图片的地址
function GetImgSrc(path, w, h) {
    try {
        var i = path.lastIndexOf('/');
        return "http://img.wagest.com/" + path.substring(0, i) + "/" + w + "_" + h + path.substring(i, path.length);
    } catch (e) { }
}
//关闭型号div
window.closeShowDiv = function() {
    //            var MyDragPanelID = $("#MyDragPanelID").val();
    //            if (MyDragPanelID == null) {
    //                MyDragPanelID = $("#PanelID").val();
    //                if (MyDragPanelID != null) {
    //                    $('#' + MyDragPanelID).css("display", "none");
    //                }
    //            }
    $("div.weedialog2.weebox").css("display", "none");
    $("div.dialog-mask").css("display", "none");
}


jQuery.fn.loadthumb = function(options) {
    options = $.extend({
        src: ""
    }, options);
    var _self = this;
    _self.hide();
    var img = new Image();
    $(img).load(function() {
        _self.attr("src", options.src);
        _self.fadeIn("slow");
    }).attr("src", options.src);  //.atte("src",options.src)要放在load后面，
    return _self;
}

$(function() {
    var i = 3;  //已知显示的<a>元素的个数
    var m = 3;  //用于计算的变量
    var $content = $("#myImagesSlideBox .scrollableDiv");
    var count = $content.find("a").length; //总共的<a>元素的个数
    //下一张
    $(".next").bind("click", function() {
        var obj = $(this).siblings(".items").find(".scrollableDiv");
        if (!$(obj).is(":animated")) {  //判断元素是否正处于动画，如果不处于动画状态，则追加动画。
            if (m < count) {  //判断 i 是否小于总的个数
                m++;
                $(obj).animate({ left: "-=57px" }, 600);
            }
        }
        return false;
    });
    //上一张
    $(".prev").bind("click", function() {
        var obj = $(this).siblings(".items").find(".scrollableDiv");
        if (!$(obj).is(":animated")) {
            if (m > i) { //判断 i 是否小于总的个数
                m--;
                $(obj).animate({ left: "+=57px" }, 600);
            }
        }
        return false;
    });

    $(".scrollableDiv a").bind("click", function() {
        var src = $(this).find("img").attr("imgb");
        var bigimgSrc = $(this).find("img").attr("bigimg");
        $(this).parents(".myImagesSlideBox").find(".jqzoom").attr("href", bigimgSrc)
        $(this).parents(".myImagesSlideBox").find(".myImgs").loadthumb({ src: src }).attr("bigimg", bigimgSrc);
        $(this).addClass("active").siblings().removeClass("active");
        return false;
    });
    $(".scrollableDiv a:nth-child(1)").trigger("click");

})
