

function FormatTime(jsonDate) {
    jsonDate = jsonDate.split('(')[1].split(')')[0];
    var rDate = new Date(parseInt(jsonDate));
    return rDate.toLocaleDateString();
}

var productCount = 1;
var starImg = "<img src=\"" + xImgURI + "cpn_17.jpg\" />";

var userID = MemberUID;
var userName = MemberName;

var tempCommentsTemplate = "<h2><span>评论时间:{creatTime}</span><b>{userArea}</b> {userType}{userName}:{anyImg}{star}星评分</h2><p><img src=\"" + xImgURI + "cpn_15.jpg\" />：{content}</p>";
var commentsWithReplayTemplate = "<h2><span>评论时间:{creatTime}</span><b>{userArea}</b> {userType}{userName}:{anyImg}{star}星评分</h2><p><img src=\"" + xImgURI + "cpn_15.jpg\" />：{content}</p><p><img src=\"" + xImgURI + "cpn_16.jpg\" />:{reply}</p>";

var pageSize = "6";
var recordCount = "-1";

$().ready(function () {
    InitData(0);
    if (userName != undefined && userName != "") {
        var userInput = $("#userNameInput");
        userInput.val(userName);

        userInput.attr("readonly", true);
    }
});

function pageselectCallback(page_id, jq) {
    InitData(page_id);
    return false;
}
function InitData(pageIndex) {
    var postData = "{productID:'" + productID + "',pageIndex:'" + escape(pageIndex) + "',pageSize:'" + escape(pageSize) + "'}";
    var url = WebSite + "Services/WebService.asmx/GetProduceReviewInfos";
    var tbody = "";
    var recordCount = 0;
    $.ajax({
        url: url,
        type: "POST",
        data: postData,
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        beforeSend: function () { $("#divload").show(); $("#Pagination").hide(); }, //发送数据之前
        complete: function () { $("#divload").hide(); $("#Pagination").show() }, //接收数据完毕
        success: function (json) {
            var productData = json.d.Products;
            recordCount = json.d.RecordCount;
            $.each(productData, function (i, n) {
                var uType = "";
                var anyImg = starImg + starImg + starImg + starImg + starImg;
                switch (n.Star) {
                    case 5: anyImg = starImg + starImg + starImg + starImg + starImg; break;
                    case 4: anyImg = starImg + starImg + starImg + starImg; break;
                    case 3: anyImg = starImg + starImg + starImg; break;
                    case 2: anyImg = starImg + starImg; break;
                    case 1: anyImg = starImg; break;
                }
                if (n.Customer_ID != undefined && n.Customer_ID != null && n.Customer_ID != "") {
                    uType = "绿瘦会员";
                }
                else {
                    uType = "绿瘦网友";
                }
                var tmpCustomerName = n.CustomerName.replace(/(\d{3})(\d{4})/g, "$1****");
                var tmpIP = "未知";
                if (n.IP != undefined && n.IP != null && n.IP != "") {
                    tmpIP = n.IP.replace(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/g, "$1.***.***.$4");
                }
                var tmpArea = "";

                if (typeof n.Area != "undefined" && n.Area != null && n.Area != "") {
                    tmpArea = n.Area;
                }
                if (n.Reply == null || n.Reply == "") {
                    tbody += tempCommentsTemplate.replace("{userArea}", tmpArea).replace("{userType}", uType).replace("{userName}", tmpCustomerName).replace("{anyImg}", anyImg).replace("{star}", n.Star).replace("{content}", n.Content.replace("\r\n", "<br />")).replace("{creatTime}", FormatTime(n.ReviewDate));
                }
                else {
                    tbody += commentsWithReplayTemplate.replace("{userArea}", tmpArea).replace("{userType}", uType).replace("{userName}", tmpCustomerName).replace("{anyImg}", anyImg).replace("{star}", n.Star).replace("{content}", n.Content.replace("\r\n", "<br />")).replace("{creatTime}", FormatTime(n.ReviewDate)).replace("{reply}", n.Reply);
                }

            });
            $("#mainComents").html("");
            $("#mainComents").append(tbody);
            $("#Pagination").pagination(recordCount, {
                callback: pageselectCallback,
                prev_text: '上一页',
                next_text: '下一页',
                items_per_page: pageSize,
                num_display_entries: 6,
                current_page: pageIndex,
                num_edge_entries: 2
            });
        }
    });
}
var UserArea = "";

function sendComment() {

    if (MemberName == undefined || MemberName == "")
        MemberName = $("#userNameInput").val();
    userName = SafeRequest(MemberName);
    var content = SafeRequest($("#comments_info").val());
    var star = $("input[name='scores'][checked]").val();
    var checkCode = SafeRequest($("#comments_code").val());
    var userType;
    var anyImg = starImg + starImg + starImg + starImg + starImg;
    switch (star) {
        case "5": anyImg = starImg + starImg + starImg + starImg + starImg; break;
        case "4": anyImg = starImg + starImg + starImg + starImg; break;
        case "3": anyImg = starImg + starImg + starImg; break;
        case "2": anyImg = starImg + starImg; break;
        case "1": anyImg = starImg; break;
    }
    if (userName == "") {
        alert("用户名不能为空！");
        $("#userNameInput").focus();
        return false;
    }

    if (content == "") {
        alert("评论内容不能为空！");
        $("#comments_info").focus();
        return false;
    }
    if (checkCode == "") {
        alert("验证码不能为空！");
        $("#comments_code").focus();
        return false;
    }

    if (MemberUID == undefined || MemberUID == "") {
        userType = "绿瘦网友";
    }
    else {
        userType = "绿瘦会员";
    }
    var tmpUserName = userName.replace(/(\d{3})(\d{4})/g, "$1****");
    var tmpIP = "未知";
    if (typeof UserIP != "undefined" && UserIP != null && UserIP != "") {
        tmpIP = UserIP.replace(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/g, "$1.***.***.$4");
    }
    var tmpArea = "";

    if (typeof UserArea != "undefined" && UserArea != null && UserArea != "") {
        tmpArea = UserArea;
    }
    else {
        GetCustomerArea(false);
        tmpArea = UserArea;
    }
    var comment = tempCommentsTemplate.replace("{userArea}", tmpArea).replace("{userType}", userType).replace("{userName}", tmpUserName).replace("{anyImg}", anyImg).replace("{star}", star).replace("{content}", content).replace("{creatTime}", (new Date()).toLocaleTimeString());
    var postData = "{productID:'" + productID + "',userID:'" + escape(userID) + "',userName:'" + escape(userName) + "',content:'" + escape(content) + "',star:'" + star + "',checkCode:'" + escape(checkCode) + "', area: '" + escape(tmpArea) + "'}";
    var url = WebSite + "Services/WebService.asmx/AddProduceReviewInfo";
    $.ajax({
        url: url,
        type: "POST",
        data: postData,
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        success: function (data) {
            if (data.d != "1") {
                ReLoadCheckCode();
                alert(data.d);

                return false;
            }
            else {
                $("#mainComents").append(comment);
                $("#comments_info").val("");
                ReLoadCheckCode();
                return false;
            }
        }
    });
    return false;
}

function BuyProduct(value) {
    if (typeof xIsOutStock != "undefined" && xIsOutStock != "" && xIsOutStock == "True") {
        alert("尊敬的客户您好，该产品目前属于缺货状态，无法下单!");
        return;
    }
    var quantity = $("#goods_quantity").val();
    if (quantity <= 0) {
        alert("购买件数不能小于1件！"); return;
    }
    if (points == undefined || points == "")
        points = 0;
    AddCarByID(productID, "", quantity, price, points, 0, function (data) {
        if (value == 0) {
            window.location.href = WebSite + "Member/Car.aspx";
        }
        else {
            $("#productRecord").html("(" + data.ProductCount + ")");
            $("#amount").html(data.Amount);
            $('.buy_tips:visible').hide();
            $('.collect_tips:visible').hide();
            $('#buy_tips').animate({ opacity: 'show' }, { duration: 500 });
        }
    });
}

function FastBuyProduct(pID, qty, pri, pois) {
    if (typeof xIsOutStock != "undefined" && xIsOutStock != "" && xIsOutStock == "True") {
        alert("尊敬的客户您好，该产品目前属于缺货状态，无法下单!");
        return;
    }
    if (qty <= 0) {
        alert("购买件数不能小于1件！"); return;
    }
    if (pois == undefined || pois == "")
        pois = 0;
    AddCarByID(pID, "", qty, pri, pois, 0, function (data) {
        window.location.href = WebSite + "Member/Car.aspx";
    });
}

function BuyCurrentProduct(pID, qty, pri, pois) {
    if (typeof xIsOutStock != "undefined" && xIsOutStock != "" && xIsOutStock == "True") {
        alert("尊敬的客户您好，该产品目前属于缺货状态，无法下单!");
        return;
    }
    if (typeof qty == 'undefined' || qty == "" || qty <= 0)
        qty = 1;
    if (typeof pois == 'undefined' || pois == "")
        pois = points;
    if (typeof pois == 'undefined' || pois == "")
        pois = 0;
    if (typeof pID == 'undefined' || pID == "")
        pID = productID;
    if (typeof pri == 'undefined' || pri == "")
        pri = price;
    AddCarByID(pID, "", qty, pri, pois, 0, function (data) {
        window.location.href = WebSite + "Member/Car.aspx";
    });
}
function GetCustomerArea(state) {
    var url = WebSite + "Services/WebService.asmx/GetCustomerArea";
    var postdata = "";
    var result = "";
    $.ajax({
        url: url,
        data: postdata,
        type: "Post",
        contentType: "Application/json; Charset=UTF-8",
        dataType: "json",
        async: state,
        success: function (data) {
            result = data.d.toString();
            UserArea = result;
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });
    //debugger;
}

function CollectProduct() {
    if (MemberUID == undefined || MemberUID == "") {
        alert("请确认会员已登录！或请先注册为会员！"); return;
    }
    var postData = "{productID:'" + productID + "'}";
    var url = WebSite + "Services/WebService.asmx/CollectProduct";
    $.ajax({
        url: url,
        type: "POST",
        data: postData,
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        success: function (data) {
            if (data.d == null) {
                alert("添加到收藏夹失败！");
                return false;
            }
            else {
                $("#collectCount").html("(" + data.d + ")");
                $('#collect_tips').animate({ opacity: 'show' }, { duration: 500 });
            }
        },
        error: function (f) {

        }
    });
    // return false;
}

function close_buy() {
    $('#buy_tips').animate({ opacity: 'hide' }, { duration: 500 });
}
//buy_tips////////
function collect_tips() {
    $('.buy_tips:visible').hide();
    $('.collect_tips:visible').hide();
    $('#collect_tips').animate({ opacity: 'show' }, { duration: 500 });
}
function close_collect() {
    $('#collect_tips').animate({ opacity: 'hide' }, { duration: 500 });
}

function ReLoadCheckCode() {
    var d = $('#codeImg');
    d.attr("src", "../Services/CheckCode.ashx?type=comment&ii=" + Math.random());
}

function ChangeProduct(id, RetailPrice, CurrentPrice, num, count) {
    var i = 1;
    for (i = 1; i <= count; i++) {
        $("#spanCP" + i).attr("class", "");
    }
    $("#spanCP" + num).attr("class", "hover");
    productID = id;
    retailPrice = RetailPrice;
    price = CurrentPrice;
    productCount = 1;
    $("#goods_quantity").val(productCount);
    $("#PricePage").html("<span><s>市场价：￥" + (retailPrice * productCount) + "元</s></span><span>商城会员：￥<b>" + (price * productCount) + "</b>元</span><span>赠送积分：<i>" + (price * productCount) + "</i>分</span></p>");

    // var title = ID("tab" + m).getElementsByTagName('span');
    var info = ID("tabi1").getElementsByTagName('blockquote');
    num--;
    for (i = 0; i < count; i++) {
        //   title[i].className = i == n ? "hover" : "";
        info[i].style.display = i == num ? "block" : "none";
    }
}
function ChangeProductQuantity(num) {
    productCount = num;
    $("#PricePage").html("<span><s>市场价：￥" + (retailPrice * productCount) + "元</s></span><span>商城会员：￥<b>" + (price * productCount) + "</b>元</span><span>赠送积分：<i>" + (price * productCount) + "</i>分</span></p>");
}

window.setTimeout("GetCustomerArea(true)", 1000); //获取地区