﻿//将商品加入购物车 buyType 1纸书购买 2在线阅读购买 3下载  mType资源类型，对应枚举DataBaseType
function addToCart(doi, buyType, mType) {
    $.ajax({
        type: "Post",
        url: "/Book/BuyBook",
        cache: false,
        data: { doi: doi, type: buyType, mType: mType },
        success: function (data) {
            if (data.state == "-1") {
                alert("请先登录");
            }
            else if (data.state == "0") {
                alert("操作失败！请重试")
            }
            else if (data.state == "-4") {
                alert("您已购买");
            }
            else if (data.state == "-5") {
                alert("您是机构用户，包库记录中不存在该书，请先购买");
            }
            else if (data.state == "1") {
                window.location.href = "/OrderList/MyCart";
            }
        }
    });
}


//将商品加入购物车 buyType 1纸书购买 2在线阅读购买 3下载  mType资源类型，对应枚举DataBaseType
function addToCartAjax(doi, buyType, mType) {
    $.ajax({
        type: "Post",
        url: "/Book/BuyBook",
        cache: false,
        data: { doi: doi, type: buyType, mType: mType },
        success: function (data) {
            if (data.state == "-1") {
                alert("请先登录");
            }
            else if (data.state == "0") {
                alert("操作失败！请重试")
            }
            else if (data.state == "-4") {
                alert("您已购买");
            }
            else if (data.state == "-5") {
                alert("您是机构用户，包库记录中不存在该书，请先购买");
            }
            else if (data.state == "1") {
                alert("成功加入购物车");
                var cartCount = $("#myCart").attr("data-cart");
                $("#myCart").text("购物车(" + parseInt(parseInt(cartCount) + 1) + ")");
                $("#myCart").attr("data-cart", parseInt(parseInt(cartCount) + 1));
            }
        }
    });
}








//通过ajax获取的价格的对象
function BookPriceDetail() {
    var guid = "";
    //商品优惠后的价格
    var podPrice = 0;
    var readPrice = 0;
    var downPrice = 0;
    //商品未优惠价格
    var podOldPrice = 0;
    var readOldPrice = 0;
    var downOldPrice = 0;
}
//通过ajax获取价格信息 并绑定到页面
function GetPriceBuyAjax(doi, priceService, funcName) {
    var podPrice;
    var readPrice;
    var downPrice;
    var podOldPrice;
    var readOldPrice;
    var downOldPrice;
    $.getJSON(priceService + "/PriceService.svc/GetPrice?jsoncallback=?",
        { guid: doi },
        function (data) {
            var json = $.parseJSON(data);
            if (json.Success) { // 如果连接正确
                var PBook = json.Book;
                if (PBook != null) {
                    var PDiscountRate = PBook.DiscountRate;
                    var Discount = PBook.Discount;
                    var PPirce = PBook.Price;
                    podOldPrice = PPirce;
                    if (PDiscountRate != null) {
                        if (PDiscountRate.Value > 0) { // 如果减价,不考虑打折
                            podPrice = PPirce - PDiscountRate.Value;
                        } else { // 打折
                            if (Discount != null) {
                                podPrice = multiplication(PPirce, Discount.Value);
                            } else {
                                podPrice = PPirce;
                            }
                        }
                    }
                    else {
                        if (Discount != null) {
                            podPrice = multiplication(PPirce, Discount.Value);
                        }
                        else {
                            podPrice = PPirce;
                        }
                    }
                }
                // 电子书 (在线阅读)
                var EBook = json.EBook;
                //alert("EBook----" + EBook);
                if (EBook != null) {
                    var EPrice = EBook.Price;
                    var EDiscountRate = EBook.DiscountRate;
                    var EDiscount = EBook.Discount;
                    readOldPrice = EPrice;
                    if (EDiscountRate != null) {
                        if (EDiscountRate.Value > 0) { // 降价
                            readPrice = EPrice - EDiscountRate.Value;
                        } else { // 打折
                            if (EDiscount != null) {
                                readPrice = multiplication(EPrice, EDiscount.Value);
                            }
                            else {
                                readPrice = EPrice;
                            }

                        }
                    }
                    else {
                        if (EDiscount != null) {
                            readPrice = multiplication(EPrice, EDiscount.Value);
                        }
                        else {
                            readPrice = EPrice;
                        }
                    }
                }
                // 下载阅读

                var DLBook = json.Downloading;
                //alert("DLBook----"+DLBook);
                if (DLBook != null) {
                    var DLPrice = DLBook.Price;
                    var DLDiscountRate = DLBook.DiscountRate;
                    var DLDiscount = DLBook.Discount;
                    downOldPrice = DLPrice;
                    if (DLDiscountRate != null) {
                        if (DLDiscountRate.Value > 0) { // 降价
                            downPrice = DLPrice - DLDiscountRate.Value;
                        } else { // 打折
                            if (DLDiscount != null) {
                                downPrice = multiplication(DLPrice, DLDiscount.Value);
                            } else {
                                downPrice = DLPrice;
                            }
                        }
                    }
                    else {
                        if (DLDiscount != null) {
                            downPrice = multiplication(DLPrice, DLDiscount.Value);
                        } else {
                            downPrice = DLPrice;
                        }
                    }
                }
            }
            var bookPrice = new BookPriceDetail();
            bookPrice.podPrice = podPrice;
            bookPrice.readPrice = readPrice;
            bookPrice.downPrice = downPrice;
            bookPrice.podOldPrice = podOldPrice;
            bookPrice.readOldPrice = readOldPrice;
            bookPrice.downOldPrice = downOldPrice;
            if (funcName && typeof (funcName) == "function") {
                funcName(bookPrice, doi);
            }
        }
    );
}
//通过Ajax加载价格列表信息
function GetPriceArrayByAjax(xml, priceService, funcName) {

    $.getJSON(priceService + "/PriceService.svc/GetPriceArray?jsoncallback=?", { xmlDocument: xml, resourceTypeFlag: 0 },
    function (data) {
        //alert(data);
        var arr = new Array();
        var json = $.parseJSON(data);

        if (json.Success) {
            var priceList = json.PriceList;
            for (var j = 0; j < priceList.length; j++) {
                var guid = "";
                var podPrice = 0;
                var podOldPrice = 0;
                var readPrice = 0;
                var downPrice = 0;
                if (priceList[j].Success) {
                    guid = priceList[j].Guid;
                    var PBook = priceList[j].Book;
                    if (PBook != null) {
                        var PDiscountRate = PBook.DiscountRate;
                        var Discount = PBook.Discount;
                        var PPirce = PBook.Price;
                        podOldPrice = PPirce;
                        if (PDiscountRate != null) {
                            if (PDiscountRate.Value > 0) {
                                podPrice = PPirce - PDiscountRate.Value;
                            } else {
                                if (Discount != null) {
                                    podPrice = multiplication(PPirce, Discount.Value);
                                } else {
                                    podPrice = PPirce;
                                }
                            }
                        }
                        else {
                            if (Discount != null) {
                                podPrice = multiplication(PPirce, Discount.Value);
                            } else {
                                podPrice = PPirce;
                            }
                        }
                    }

                    // 电子书 (在线阅读)
                    var EBook = priceList[j].EBook;
                    if (EBook != null) {
                        var EPrice = EBook.Price;
                        var EDiscountRate = EBook.DiscountRate;
                        var EDiscount = EBook.Discount;
                        if (EDiscountRate != null) {
                            if (EDiscountRate.Value > 0) { // 降价
                                readPrice = EPrice - EDiscountRate.Value;
                            } else { // 打折
                                if (EDiscount != null) {
                                    readPrice = multiplication(EPrice, EDiscount.Value);
                                }
                                else {
                                    readPrice = EPrice;
                                }
                            }
                        }
                        else {
                            if (EDiscount != null) {
                                readPrice = multiplication(EPrice, EDiscount.Value);
                            }
                            else {
                                readPrice = EPrice;
                            }
                        }
                    }
                    // 下载阅读
                    var DLBook = priceList[j].Downloading;
                    if (DLBook != null) {
                        var DLPrice = DLBook.Price;
                        var DLDiscountRate = DLBook.DiscountRate;
                        var DLDiscount = DLBook.Discount;
                        if (DLDiscountRate != null) {
                            if (DLDiscountRate.Value > 0) { // 降价
                                downPrice = DLPrice - DLDiscountRate.Value;
                            }
                            else { // 打折
                                if (DLDiscount != null) {
                                    downPrice = multiplication(DLPrice, DLDiscount.Value);
                                }
                                else {
                                    downPrice = DLPrice;
                                }
                            }
                        }
                        else {
                            if (DLDiscount != null) {
                                downPrice = multiplication(DLPrice, DLDiscount.Value);
                            }
                            else {
                                downPrice = DLPrice;
                            }
                        }

                    }
                }
                var bookPrice = new BookPriceDetail();
                bookPrice.guid = guid;
                bookPrice.podPrice = podPrice;
                bookPrice.podOldPrice = podOldPrice;
                bookPrice.readPrice = readPrice;
                bookPrice.readOldPrice = EPrice;
                bookPrice.downPrice = downPrice;
                bookPrice.downOldPrice = DLPrice;
                arr.push(bookPrice);
            }
        }
        if (funcName && typeof (funcName) == "function") {
            funcName(arr);
        }
    }
);
}
//js 浮点型相乘时会有问题，所以需要特殊处理
function multiplication(numA, numB) {
    var divisionNum = 1;
    var indexNum = numA.toString().lastIndexOf(".")
    if (indexNum != -1) {
        var positionNum = numA.toString().length - indexNum - 1;
        numA = positionNum * numA;
        for (var i = 0; i < positionNum; i++) {
            divisionNum = divisionNum * 10;
            numA = numA * 10;
        }
    }
    var indexNum = numB.toString().lastIndexOf(".")
    if (indexNum != -1) {
        var positionNum = numB.toString().length - indexNum - 1;
        for (var j = 0; j < positionNum; j++) {
            divisionNum = divisionNum * 10;
            numB = numB * 10;
        }
    }
    return numA * numB / divisionNum;
}
//图书详情页
function loadPrice(doi, priceService) {
    GetPriceBuyAjax(doi, priceService, loadPrice_Success);
}
function loadPrice_Success(priceObj) {
    if (priceObj.podPrice) {
        $("#podPrice").text(priceObj.podPrice);
        if (priceObj.podPrice != priceObj.podOldPrice) {
            $("#podPrice").before("<p>" + priceObj.podOldPrice + "元</p>&nbsp;");
        }
    }
    if (priceObj.readPrice) {
        $("#readPrice").text(priceObj.readPrice);
        if (priceObj.readPrice != priceObj.readOldPrice) {
            $("#readPrice").before("<p>" + priceObj.readOldPrice + "元</p>&nbsp;");
        }
    }
    if (priceObj.downPrice) {
        $(".book_price  strong").text(priceObj.downPrice);
        if (priceObj.downPrice != priceObj.downOldPrice) {
            $(".book_price strong").before("<font>" + priceObj.downOldPrice + "元</font>&nbsp;");
        }
    }
}


//绑定评论
function BindEvaluation(doi, resourceType, pageNo, pageSize) {
    var query = "doi=" + doi + "&type=" + resourceType;
    if (pageNo && pageSize) {
        query += "&pageno=" + pageNo + "&pagesize=" + pageSize;
    }
    $.ajax({
        type: "GET",
        url: "/Ajax/GetEvaluation.ashx",
        cache: false,
        data: query,
        dataType: "json",
        success: function (data) {
            if (data) {
                if (!pageNo || !pageSize) {
                    $("#evaluationcontainer").empty();
                }
                for (var i = 0; i < data.length; i++) {
                    var evaText = "<div class='bookView'>";
                    evaText += "<div class='vTopic'>";
                    evaText += "<span>" + data[i].UserName + "</span>"; { 0 }
                    evaText += "<em>" + data[i].CreateDateTime + "</em>";
                    evaText += "</div>";
                    evaText += "<div class='stars sa" + data[i].Point + "'></div>";
                    evaText += "<div class='comment-content'>主题：" + data[i].Title + "<br/>评价：" + data[i].Content + "</div>";
                    evaText += "</div>";
                    $("#evaluationcontainer").append(evaText);
                }
                //判断如果已经到最后一条了，则修改查看更多评论的click事件
                if ($("#evaluationcontainer .bookView").length >= data[0].RecordCount) {
                    $(".moreEval").attr("onclick", "alert('没有更多评论了！')");
                }
                else {
                    //计算下一个页的页码
                    pageSize = 5; //后台默认的pagesize为5，如果当前的pagesize不为五的话，计算下一页的方法需要更换
                    pageNo = ($("#evaluationcontainer .bookView").length - 1) / 5 + 2;
                    $(".moreEval").attr("onclick", "BindEvaluation('" + doi + "'," + resourceType + "," + pageNo + "," + pageSize + ")");
                }
            }
        }
    });
}

//提交评论 然后重新获取评论列表，更新到图书细览页
function SendEvaluation(doi, username, title, content, ip, point, titleID, contentID, resourceType) {
    if (username == "") {
        alert("请先登录，然后再评论！");
        window.location.href = "../Login.aspx?ReturnUrl=" + encodeURIComponent(document.URL);
        return false;
    }
    else {
        if (title.length == 0 || content.length == 0) {
            alert("主题和内容不能空");
            return false;
        }
        if (title.length > 50 || content.length > 500) {
            alert("主题不能超过50个字，内容不能超过140个字");
            return false;
        }

        //if ($("#IsFirst").val() == "1") {
        //    $("#IsFirst").val("2");
        //}
        //else {
        //    alert("已经评论！");
        //    $("#" + titleID + "").val("");
        //    $("#" + contentID + "").val("");
        //}
        //获取评论列表
        //$.ajax({
        //    type: "Get",
        //    url: "/Ajax/CreateEvaluation.ashx",
        //    cache: false,
        //    data: "doi=" + doi + "&title=" + encodeURIComponent(title) + "&content=" + encodeURIComponent(content) + "&ip=" + ip + "&username=" + username + "&point=" + point,
        //    success: function (data) {
        //        if (data) {
        //            var arr = data.split('|#$%^&*|');
        //            if (arr.length == 2) {
        //                if (arr[0] == "true" || arr[0] == "True") {
        //                    $("#showEvaluation").html(arr[1]);
        //                    $("#" + titleID + "").val("");
        //                    $("#" + contentID + "").val("");
        //                }
        //            }
        //        }
        //    }
        //}); 

        $(".com_submit").text("正在提交").removeAttr("onclick");
        // 发表评论
        $.ajax({
            type: "GET",
            url: "/Ajax/CreateEvaluation.ashx",
            cache: false,
            data: "doi=" + doi + "&title=" + encodeURIComponent(title) + "&content=" + encodeURIComponent(content) + "&ip=" + ip + "&username=" + username + "&point=" + point + "&type=" + resourceType,
            success: function (data) {
                if (data == "-1") {
                    alert("请先登陆！");
                    $(".com_submit").text("发表评论").attr("onclick", "sendEval()");
                }
                else if (data == "0") {
                    alert("操作失败，请重试！");
                    $(".com_submit").text("发表评论").attr("onclick", "sendEval()");
                }
                else if (data == "1") {
                    BindEvaluation(doi, resourceType);
                    // alert("恭喜您评论成功，您的评论经过审核后即会在页面上显示");
                    alert("恭喜您评论成功!");
                    $(".com_submit").text("评论成功").css("background-color", "gray");
                }
                else if (data == "-2") {
                    alert("您是机构用户，不能进行评论！");
                    $(".com_submit").text("发表评论").attr("onclick", "sendEval()");
                }
            }
        });
    }
}

//图书细览页面，点击目录试读章节
function catalogClick(doi, mType) {
    $("#catalogul a").click(function () {
        var page = $(this).next("span").html();
        $.ajax({
            type: "Get",
            url: "/ajax/CheckRead.ashx",
            cache: false,
            data: "doi=" + doi + "&type=" + mType,
            success: function (data) {
                if (data == "-1") {
                    alert("请先登录");
                }
                else if (data == "0") {
                    alert("用户尚未购买该书，请购买后阅读");
                }
                else if (data == "1") {
                    var url = "/knreader/Default.aspx?doi=" + doi + "&type=" + mType + "&page=" + page;
                    window.location.href = url;
                }
            }
        });
    });
}


// U盘电子书列表加载价格
function loadBookListPrice(xml, priceService, funcname) {
    GetPriceArrayByAjax(xml, priceService, loadBookPreferential_Success);
}

// 加载价格
function loadBookPrice(xml, priceService, funcname) {
    GetPriceArrayByAjax(xml, priceService, funcname);
}

//绑定重点图书左侧
function loadBookPreferential_Success(priceArr) {

    for (var i = 0; i < priceArr.length; i++) {
        if (priceArr[i].podPrice != "0") {
            if (priceArr[i].podOldPrice != "0") {
                if (priceArr[i].podOldPrice == priceArr[i].podPrice) {
                    $("li[data-id='" + priceArr[i].guid.toLowerCase() + "']").children("p").children(".book_price1").text("￥" + priceArr[i].podPrice);
                }
                else {
                    $("li[data-id='" + priceArr[i].guid.toLowerCase() + "']").children("p").children(".book_price1").text("￥" + priceArr[i].podPrice);
                }
            }
            else {
                $("li[data-id='" + priceArr[i].guid.toLowerCase() + "']").children("p").children(".book_price1").text("￥" + priceArr[i].podOldPrice);
            }

        }
        if (priceArr[i].readPrice != "0") {
            if (priceArr[i].readOldPrice != "0") {
                if (priceArr[i].readOldPrice == priceArr[i].podPrice) {
                    $("li[data-id='" + priceArr[i].guid + "']").children("p").children(".book_price2").text("￥" + priceArr[i].readPrice);
                }
                else {
                    $("li[data-id='" + priceArr[i].guid + "']").children("p").children(".book_price2").text("￥" + priceArr[i].readPrice);
                }
            }
            else {
                $("li[data-id='" + priceArr[i].guid + "']").children("p").children(".book_price2").text("￥" + priceArr[i].readOldPrice);
            }
        }
        //if (priceArr[i].podOldPrice != "0") {
        //    if (priceArr[i].podOldPrice == priceArr[i].podPrice) {
        //        $("span[name='important_left_discount']").eq(i).css("display", "none");
        //    }
        //    else {
        //        $("li[data-id='" + priceArr[i].guid + "']").children("p").children(".book_price1").text("￥" + priceArr[i].podOldPrice);
        //    }

        //}
    }
}
function loadImportantList(priceArr) {
    for (var i = 0; i < priceArr.length; i++) {
        if (priceArr[i].podPrice != "0") {
            $("span[name='important_list_cost']").eq(i).text("￥" + priceArr[i].podPrice);

        }
        if (priceArr[i].podOldPrice != "0") {
            if (priceArr[i].podOldPrice == priceArr[i].podPrice) {
                $("span[name='important_list_discount']").eq(i).css("display", "none");
            }
            else {
                $("span[name='important_list_discount']").eq(i).text("￥" + priceArr[i].podOldPrice);
            }

        }
        else {
            $("span[name='important_list_discount']").eq(i).css("display", "none");
        }
    }
}

function Fund(priceArr) {
    for (var i = 0; i < priceArr.length; i++) {
        if (priceArr[i].podPrice != "0") {
            $("span[name='fund_cost']").eq(i).text("￥" + priceArr[i].podPrice);
            //$("span[name='fund_discount']").eq(i).text("￥" + priceArr[i].podOldPrice);

        }
        if (priceArr[i].podOldPrice != "0") {
            if (priceArr[i].podOldPrice == priceArr[i].podPrice) {
                $("span[name='fund_discount']").eq(i).css("display", "none");
            }
            else {
                $("span[name='fund_discount']").eq(i).text("￥" + priceArr[i].podOldPrice);
            }

        }
        else {
            $("span[name='fund_discount']").eq(i).css("display", "none");
        }
    }
}

function TeachingMaterial(priceArr) {
    for (var i = 0; i < priceArr.length; i++) {
        if (priceArr[i].podPrice != "0") {
            $("span[name='teachingMaterial_cost']").eq(i).text("￥" + priceArr[i].podPrice);
            //$("span[name='teachingMaterial_discount']").eq(i).text("￥" + priceArr[i].podOldPrice);

        }
        if (priceArr[i].podOldPrice != "0") {
            if (priceArr[i].podOldPrice == priceArr[i].podPrice) {
                $("span[name='teachingMaterial_discount']").eq(i).css("display", "none");
            }
            else {
                $("span[name='teachingMaterial_discount']").eq(i).text("￥" + priceArr[i].podOldPrice);
            }

        }
        else {
            $("span[name='teachingMaterial_discount']").eq(i).css("display", "none");
        }
    }
}

function WinBook(priceArr) {
    for (var i = 0; i < priceArr.length; i++) {
        if (priceArr[i].podPrice != "0") {
            $("span[name='winBook_cost']").eq(i).text("￥" + priceArr[i].podPrice);
            //$("span[name='winBook_discount']").eq(i).text("￥" + priceArr[i].podOldPrice);
        }
        if (priceArr[i].podOldPrice != "0") {
            if (priceArr[i].podOldPrice == priceArr[i].podPrice) {
                $("span[name='winBook_discount']").eq(i).css("display", "none");
            }
            else {
                $("span[name='winBook_discount']").eq(i).text("￥" + priceArr[i].podOldPrice);
            }

        }
        else {
            $("span[name='winBook_discount']").eq(i).css("display", "none");
        }
    }
}

//图书index页面
function loadBookListPrice_Success(priceArr) {
    //alert("sdf");
    //console.log(priceArr);
    for (var i = 0; i < priceArr.length; i++) {
        if (priceArr[i].podPrice != 0) {
            $("p[data-value='" + priceArr[i].guid + "']").children(".book_price1").html(priceArr[i].podPrice+"元");
            //if (priceArr[i].podPrice != priceArr[i].podOldPrice) {
            //    $("p[data-value='" + priceArr[i].guid + "']").children(".book_price1").html("");
            //    $("p[data-value='" + priceArr[i].guid + "']").children(".book_price1").html("<font>" + priceArr[i].podOldPrice + "</font>&nbsp;" + priceArr[i].podPrice);
            //}
        }
        if (priceArr[i].readPrice != 0) {
            $("p[data-value='" + priceArr[i].guid + "']").children(".book_price2").html(priceArr[i].readPrice + "元");
            //if (priceArr[i].readPrice != priceArr[i].readOldPrice) {
            //    $("p[data-value='" + priceArr[i].guid + "']").children(".book_price2").html("");
            //    $("p[data-value='" + priceArr[i].guid + "']").children(".book_price2").html("<font>" + priceArr[i].readOldPrice + "</font>&nbsp;" + priceArr[i].readPrice);
            //}
        }
    }
}
//图书Detail页面
function loadBookDetailPrice_Success(priceArr) {
    console.log(priceArr);
    for (var i = 0; i < priceArr.length; i++) {
        if (priceArr[i].podPrice != "0") {
            $(".book_price[data-doi='" + priceArr[i].guid + "']").children(".book_price1").html(priceArr[i].podPrice);
            if (priceArr[i].podPrice != priceArr[i].podOldPrice) {
                $(".book_price[data-doi='" + priceArr[i].guid + "']").children(".book_price1").html("");
                $(".book_price[data-doi='" + priceArr[i].guid + "']").children(".book_price1").html("<font>" + priceArr[i].podOldPrice + "</font>&nbsp;" + priceArr[i].podPrice);
            }
        }
        if (priceArr[i].readPrice != "0") {
            $(".book_price[data-doi='" + priceArr[i].guid + "']").children(".book_price2").html(priceArr[i].readPrice);
            if (priceArr[i].readPrice != priceArr[i].readOldPrice) {
                $(".book_price[data-doi='" + priceArr[i].guid + "']").children(".book_price2").html("");
                $(".book_price[data-doi='" + priceArr[i].guid + "']").children(".book_price2").html("<font>" + priceArr[i].readOldPrice + "</font>&nbsp;" + priceArr[i].readPrice);
            }
        }
    }
}

//期刊详情页
//通过ajax获取价格信息 并绑定到页面
//将期刊加入购物车 doi 单期doi yeardoi全年doi
//buyType 1纸书购买 2在线阅读购买 3下载  mType资源类型，对应枚举DataBaseType sType 0单期 1全年 2多年
function AddJournalToCart(doi, yeardoi, buyType, mType, sType) {
    $.ajax({
        type: "Get",
        url: "/ajax/AddJournalToCart.ashx",
        cache: false,
        data: "doi=" + doi + "&yeardoi=" + yeardoi + "&buyType=" + buyType + "&mType=" + mType + "&sType=" + sType,
        success: function (data) {
            if (data == "-1") {  //尚未登录                
                window.location.href = "/Login.aspx?url=web" + "&ReturnUrl=" + encodeURIComponent(document.URL);
            }
            else if (data == "0") {
                alert("操作失败,请重试!")
            }
            else if (data == "-4") {
                if (sType == "0") {
                    window.location.href = "/Adminknreader/Default.aspx?doi=" + doi + "&type=" + mtype;
                } else {
                    alert("您已购买!");
                }
            } else if (data == "-5") {
                alert("您是机构用户，包库记录中不存在该期刊，请先购买!");
            }
            else if (data == "1") {
                window.location.href = "/UserCenter/MyCart.aspx";
            }
        }
    });
}
function JournalPriceDetail() {
    var guid = "";
    var yearguid = "";
    var singlePrice = 0;
    var yearPrice = 0;
    var singleYearPrice = 0;
    var savePrice = 0;
}
function GetJournalPriceBuyAjax(baseid, year, priceService, yearcount, funcName) {
    var yearguid;
    var singlePrice;  //单本
    var yearPrice;  //全年
    var singleYearPrice;  //全年订购每期
    var savePrice;  //全年节省
    $.getJSON(priceService + "/PriceService.svc/GetJournalPrice?jsoncallback=?",
        { baseID: baseid, year: year },
        function (data) {
            var json = $.parseJSON(data);
            if (json.Success) { // 如果连接正确
                $("[id$=GuidDoi]").val(json.Guid);   //获取传过年guid，全年购买时需要
                var EBook = json.EBook;
                //alert("EBook----" + EBook);
                if (EBook != null) {
                    var YearEPrice = EBook.Price; //年价格
                    var EPrice = EBook.SinglePrice; //每期价格
                    var EDiscountRate = EBook.DiscountRate;
                    var EDiscount = EBook.Discount;
                    if (EDiscountRate != null) {
                        if (EDiscountRate.Value > 0) { // 降价
                            singlePrice = EPrice - EDiscountRate.Value;
                        } else { // 打折
                            if (EDiscount != null) {
                                singlePrice = multiplication(EPrice, EDiscount.Value);
                            }
                            else {
                                singlePrice = EPrice;
                            }

                        }
                    }
                    else {
                        if (EDiscount != null) {
                            singlePrice = multiplication(EPrice, EDiscount.Value);
                        }
                        else {
                            singlePrice = EPrice;
                        }
                    }

                }
            }
            //            var bookPrice = new BookPriceDetail();
            //            bookPrice.readPrice = readPrice;
            yearPrice = YearEPrice;
            singleYearPrice = Math.round((parseFloat(YearEPrice) / parseInt(yearcount)) * 100) / 100;
            savePrice = parseInt(yearcount) * EPrice - YearEPrice;

            var journalPrice = new JournalPriceDetail();
            journalPrice.yearguid = yearguid;
            journalPrice.singlePrice = singlePrice;
            journalPrice.yearPrice = yearPrice;
            journalPrice.singleYearPrice = singleYearPrice;
            journalPrice.savePrice = savePrice;

            if (funcName && typeof (funcName) == "function") {
                funcName(journalPrice);
            }
        }
    );
}

function GetJournalPriceArrayByAjax(xml, priceService, yearcount, funcName) {
    $.getJSON(priceService + "/PriceService.svc/GetJournalPriceArray?jsoncallback=?", { xmlDocument: xml },
    function (data) {
        var arr = new Array();
        var json = $.parseJSON(data);
        if (json.Success) {
            var priceList = json.PriceList;
            for (var j = 0; j < priceList.length; j++) {
                var yearguid = "";
                var singlePrice = 0;  //单本
                var yearPrice = 0;  //全年
                var singleYearPrice = 0;  //全年订购每期
                var savePrice = 0;  //全年节省
                if (priceList[j].Success) {
                    //guid = priceList[j].Guid;
                    yearguid = priceList[j].Guid;

                    // 电子书 (在线阅读)
                    var EBook = priceList[j].EBook;
                    if (EBook != null) {
                        var YearEPrice = EBook.Price; //年价格
                        var EPrice = EBook.SinglePrice; //每期价格
                        var EDiscountRate = EBook.DiscountRate;
                        var EDiscount = EBook.Discount;
                        if (EDiscountRate != null) {
                            if (EDiscountRate.Value > 0) { // 降价
                                singlePrice = EPrice - EDiscountRate.Value;
                            } else { // 打折
                                if (EDiscount != null) {
                                    singlePrice = multiplication(EPrice, EDiscount.Value);
                                }
                                else {
                                    singlePrice = EPrice;
                                }

                            }
                        }
                        else {
                            if (EDiscount != null) {
                                singlePrice = multiplication(EPrice, EDiscount.Value);
                            }
                            else {
                                singlePrice = EPrice;
                            }
                        }
                        yearPrice = YearEPrice;
                        singleYearPrice = Math.round((parseFloat(YearEPrice) / parseInt(yearcount)) * 100) / 100;
                        savePrice = parseInt(yearcount) * EPrice - YearEPrice;
                    }
                }

                var journalPrice = new JournalPriceDetail();
                journalPrice.yearguid = yearguid;
                journalPrice.singlePrice = singlePrice;
                journalPrice.yearPrice = yearPrice;
                journalPrice.singleYearPrice = singleYearPrice;
                journalPrice.savePrice = savePrice;
                arr.push(journalPrice);
            }
        }
        if (funcName && typeof (funcName) == "function") {
            funcName(arr);
        }
    }
);
}

function loadJournalPrice(baseid, year, priceService, yearcount) {
    GetJournalPriceBuyAjax(baseid, year, priceService, yearcount, loadJournalPrice_Success);
}
function loadJournalListPrice(xml, priceService, yearcount) {
    GetJournalPriceArrayByAjax(xml, priceService, yearcount, loadJournalListPrice_Success);
}
function loadJournalPrice_Success(priceObj) {
    if (priceObj.yearguid) {
        $("#yearguid").val(priceObj.yearguid);
    }
    if (priceObj.singlePrice) {
        $("#singlePrice").text("￥" + priceObj.singlePrice);
    }
    if (priceObj.yearPrice) {
        $("#yearPrice").text("共" + priceObj.yearPrice + "元");
    }
    if (priceObj.singleYearPrice) {
        $("#singleYearPrice").text(priceObj.singleYearPrice);
    }
    if (priceObj.savePrice) {
        $("#savePrice").text(priceObj.savePrice);
    }
}
function loadJournalListPrice_Success(priceArr) {
    var yeardoilist = new Array();
    var yearsave = 0;
    var yeartotal = 0;
    for (var i = 0; i < priceArr.length; i++) {
        yearsave += priceArr[i].savePrice;
        yeartotal += priceArr[i].yearPrice;
        yeardoilist.push(priceArr[i].yearguid);
    }
    $("#YearTotal").text(yeartotal);
    $("#YearSave").text(yearsave);
    $("#YearDoi").val(yeardoilist.join(';'));
}
//期刊详情页

function addressDialog(Url) {
    var url2 = Url + "";
    if (url2.indexOf("?") > 0) {
        url2 += "&eventts=";
    }
    else {
        url2 += "?eventts=";
    }
    var newDiv = $(document.createElement('div'));
    newDiv.dialog({
        autoOpen: true,
        width: 700,
        resizable: true,
        title: "管理收货地址",
        modal: true,
        open: function (event, ui) {
            $(this).load(url2 + event.timeStamp, null, function () {
                GenerateDistrict(0, "Province");
            });
        },
        close: function (event, ui) {
            $(this).remove();
        },
        buttons: {
            "提交": function () {
                checkAddress();
            },
            "取消": function () {
                $(this).dialog("close");
            }
        }
    });
}
function GenerateDistrict(parentID, ctrlID) {
    $.ajax({
        type: "GET",
        url: "/UserCenter/GetAddress",
        async: false,
        cache: false,
        data: { "parentID": parentID },
        dataType: "json",
        success: function (data) {
            if (data) {
                $("#" + ctrlID).empty();
                $("#" + ctrlID).append("<option value='0'>--请选择--</option>");
                for (var i = 0; i < data.length; i++) {
                    $("#" + ctrlID).append("<option value='" + data[i].ID + "'>" + data[i].Name + "</option>");
                }
            }
        }
    });
}
//修改收货地址时初始化地址信息
function InitAddressData(id) {
    $.ajax({
        type: "GET",
        url: "/UserCenter/GetAddressInfo",
        cache: false,
        data: { ID: id },
        dataType: "json",
        success: function (data) {
            if (data) {
                $("#Province").val(data.ProvinceID);
                GenerateDistrict(data.ProvinceID, "city");
                $("#city").val(data.CityID);
                GenerateDistrict(data.CityID, "District");
                $("#District").val(data.CountryID);
                $("#Street").val(data.Street);
                $("#zipcode").val(data.ZipCode);
                $("#Consignee").val(data.Addressee);
                $("#Phone").val(data.Phone);
            }
        }
    });
}
//管理收货地址时弹出新建或修改窗口
function dialogIframe(Url, id, even) {
    var url2 = Url + "";
    if (url2.indexOf("?") > 0) {
        url2 += "&eventts=";
    }
    else {
        url2 += "?eventts=";
    }
    var newDiv = $(document.createElement('div'));
    newDiv.attr("id", "AddressDialogDiv");
    newDiv.dialog({
        autoOpen: true,
        width: 700,
        height: 350,
        resizable: true,
        title: "管理收货地址",
        modal: true,
        open: function (event, ui) {
            $(this).load(url2 + event.timeStamp, null, function () {
                GenerateDistrict(0, "Province");
                if (id) {//修改收货地址，需要加载相应的信息，初始化页面元素
                    InitAddressData(id);
                }
            });
        },
        close: function (event, ui) {
            $(this).remove();
        },
        buttons: {
            "提交": function () {
                checkAddress(id);
                if (even) {
                    even();
                }
                else {
                    window.location.reload();
                }
                $(this).dialog("close");
            },
            "取消": function () {
                $(this).dialog("close");
            }
        }
    });
}

function BindSelect1() {
    var parentID = $("#Province").val();
    if (parentID == 0) {
        $("#city").empty();
    } else {
        GenerateDistrict(parentID, "city");
    }
    $("#District").empty();
}
function BindSelect2() {
    var parentID = $("#city").val();
    if (parentID == 0) {
        $("#District").empty();
    } else {
        GenerateDistrict(parentID, "District");
    }
}
///验证表单信息是否正确，若正确则提交表单
var numReg = /^\d+$/;
function checkAddress(type) {
    //判断省市的下拉框
    var prosl = $("#Province").val();
    var citysl = $("#city").val();
    var dissl = $("#District").val();
    if (prosl == "0" || prosl == "") {
        alert("请选择省份");
        $("#Province").focus();
        return;
    }
    if (citysl == "0" || prosl == "") {
        alert("请选择\"市\"");
        $("#city").focus();
        return;
    }
    if (dissl == "0" || dissl == "") {
        alert("请选择\"区\"");
        $("#District").focus();
        return
    }
    //判断其它信息
    var street = $("#Street").val();
    var zip = $("#zipcode").val();
    var consignee = $("#Consignee").val();
    var phone = $("#Phone").val();
    if (street == "" || zip == "" || consignee == "" || phone == "") {
        alert("必填项不能为空");
        return;
    }
    if (street.length < 5) {
        alert("街道不能少于5个字符")
        return;
    }

    if (!numReg.exec(zip)) {
        alert("邮编只能是数字");
        return;
    }
    if (!numReg.exec(phone)) {
        alert("电话格式不正确");
        return;
    }
    $("#address").dialog("close");

    if (type != "1") {
        if (confirm("确定要修改收货地址吗？修改后已提交的订单中收货地址也会改变，请谨慎操作")) {

        }
        else {
            return;
        }
    }
    $.ajax({
        async: false,
        type: "GET",
        url: "/UserCenter/Addaddress",
        data: { Province: prosl, city: citysl, District: dissl, Street: street, Consignee: consignee, zipcode: zip, Phone: phone, type: type },
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        success: function (data) {
            if (data != "false") {
                alert("操作成功！");
            }
            else {
                alert("操作成功！");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("请求出错，具体错误内容" + XMLHttpRequest.status + ":" + errorThrown);
        }
    })
}
//购物车页面验证输入
function ckSubmit() {
    var mail = $("#MailMsg").css("display"); //若存在这个元素说明需要送货则要检验是否选择了收货地址
    var rdoAddressee = "";
    var DeliveryTime = "";
    var isInvoice = "";
    if (mail != "none") {
        //验证是否选择了收货地址
        var isSuccess = false;
        $("input[type='radio'][name='rdo_Addressee']").each(function () {
            if ($(this).attr("checked")) {
                isSuccess = true;
                rdoAddressee = $(this).val();
            }
        });
        if (!isSuccess) {
            alert("请选择收货地址");
            return false;
        }
        //验证是否选择了送货方式
        isSuccess = false;
        $("input[type='radio'][name='DeliveryTime']").each(function () {
            if ($(this).attr("checked")) {
                isSuccess = true;
                DeliveryTime = $(this).val();
            }
        });
        if (!isSuccess) {
            alert("请选择送货方式");
            return false;
        }
    }
    if ($("#isInvoice").attr("checked")) {//验证发票信息是否完整
        isInvoice = "true";
        if ($("#txt_title").val() == "") {
            alert("发票抬头不能为空！");
            return false;
        }
    }
    var hidid = $("#hid_id").val();
    var txt_title = $("#txt_title").val();
    var slt_Kind = $("#slt_Kind").val();
    var slt_Type = $("#slt_Type").val();
    var txt_remark = $("#txt_remark").val();
    CreateOrder(rdoAddressee, DeliveryTime, hidid, isInvoice, txt_title, slt_Kind, slt_Type, txt_remark);
}
//提交订单 返回值0 成功 1 订单生成成功，但是发票生成错误，2，订单生成错误
function CreateOrder(rdoAddressee, DeliveryTime, hidid, isInvoice, txt_title, slt_Kind, slt_Type, txt_remark) {
    $.ajax({
        async: false,
        type: "get",
        data: { rdoAddressee: rdoAddressee, DeliveryTime: DeliveryTime, hidid: hidid, isInvoice: isInvoice, txt_title: txt_title, slt_Kind: slt_Kind, slt_Type: slt_Type, txt_remark: txt_remark },
        url: "/OrderList/submitOrder_Click",
        dataType: "text",
        success: function (data) {
            var order = data.toString().split(";");
            if (order[0] == "0") {
                window.location = "/OrderList/OrderDetail?order=" + order[1];
            }
            else if (order[0] == "1") {
                if (isInvoice == "") {
                    window.location = "/OrderList/OrderDetail?order=" + order[1];
                }
                else {
                    if (confirm("订单生成成功，但是发票生成错误")) {
                        window.location = "/OrderList/OrderDetail?order=" + order[1];
                    }
                }
            }
            else {
                alert("订单生成失败！");
                return;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("请求出错，具体错误内容" + XMLHttpRequest.status + ":" + errorThrown);
        }

    })
}
// 章节加载价格
function loadCptPrice(doi, priceService) {
    GetPriceBuyAjax(doi, priceService, loadCptPrice_Success);
}
function loadCptPrice_Success(priceObj) {
    if (priceObj.readPrice) {
        $("#readPrice").html("&yen " + priceObj.readPrice + "");
    }
    if (priceObj.downPrice) {
        $("#downPrice").html("&yen " + priceObj.downPrice + "")
    }
    //    if (!priceObj.readPrice && !priceObj.downPrice) {
    //        $("#readPrice").parent().html("");
    //    }
}

//用于机构用户包库
//sourceType：章节类型
function orgbuyChapter(doi, type, sourceType) {

    if (!doi) {
        alert("请选择要阅读的章节")
        return false;
    }
    var sType = "";
    if (sourceType) { sType = sourceType }
    if (type == "2") {
        window.parent.location.href = "../knreader/Default.aspx?doi=" + doi + "&type=" + sType;
    }
    else if (type == "3") {
        window.parent.location.href = "/pages/DownLoadDrmFile.aspx?doi=" + doi + "&type=" + sType;
    }
}


//购买章节  在线阅读2 下载3
//sourceType：章节类型
function buyChapter(doi, type, sourceType) {
    if (!doi) {
        alert("请选择要购买或下载的章节")
        return false;
    }
    //判断该章节是否定价 若为定价则弹出提示
    if (type == "2" && $("#readPrice").html() == "暂未定价") {
        alert("该章节尚未定价 无法购买");
        return false;
    }
    if (type == "3" && $("#downPrice").html() == "暂未定价") {
        alert("该章节尚未定价 无法购买");
        return false;
    }
    var sType = "";
    if (sourceType) { sType = sourceType }
    $.ajax({
        type: "GET",
        url: "/Ajax/BuyBook.ashx",
        cache: false,
        data: "doi=" + doi + "&type=" + type + "&mType=" + sType,
        success: function (data) {
            if (data == "-1") {
                alert("请先登录！");
            }
            else if (data == "0") {
                alert("操作失败！请重试");
            }
            else if (data == "-4") {
                //alert("您已经购买过该资源，不能重复购买！");
                if (type == "2") {
                    window.parent.location.href = "../knreader/Default.aspx?doi=" + doi + "&type=" + sType;
                }
                else if (type == "3") {
                    window.parent.location.href = "/pages/DownLoadDrmFile.aspx?doi=" + doi + "&type=" + sType;
                }
            }
            else if (data == "1") {
                window.parent.location = "/UserCenter/MyCart.aspx";
            }
            else if (data == "-5") {
                alert("您是机构用户，包库记录中不存在该书，请先购买");
            }
        }
    });
}


// 词条加载价格
function LoadReferencePrice(doi, priceService) {
    GetPriceBuyAjax(doi, priceService, LoadReferencePrice_Success);
}
function LoadReferencePrice_Success(priceObj) {
    var pricedoc = $(".specialMain .specialbook-price p:eq(0)");
    if (priceObj.readPrice) {
        pricedoc.html("<span>【价格】</span>  &yen " + priceObj.readPrice + " 元");
    }
}

function LoadOnLinePrice(priceService, guid) {
    var href = $("#" + guid + " h3 a").attr("href");
    if (href) {
        var doi = href.substring(href.indexOf("doi=") + 4, href.length);
        $("#" + guid + " p.n_price").each(function () {
            var control_P = $(this);
            GetPriceArrayByAjaxControl(doi, priceService, loadPrice_OnLine, control_P);
        })
        //数知网。
        // $("#" + guid).next(".extention_element").find(".Zbook").each(function () {
        //         $("#" + guid).find(".extention_element").find(".Zbook").each(function () {
        //            var control_P = $(this).parent();
        //            GetPriceArrayByAjaxControl(doi, priceService, loadPrice_ShowHide, control_P);
        //        })
    }
}

function LoadOnLinePriceXD(priceService, guid) {
    var href = $("#" + guid + " h4 a").attr("href");
    if (href) {
        var doi = href.substring(href.indexOf("doi=") + 4, href.length);
        $("#" + guid + " .XDnewBook_price span").each(function () {
            var control_P = $(this);
            GetPriceArrayByAjaxControl(doi, priceService, loadPrice_OnLineXD, control_P);
        })

    }
}
function loadPrice_OnLineXD(priceObj, control) {
    var oldText = control.text();
    //control.text(priceObj.readPrice);
    //control.text("定　价：--");

    if (priceObj.readPrice) {
        control.text(oldText + priceObj.readPrice);
        // control.text("定　价：￥"+priceObj.readPrice+"元");
    }
    else {
        control.text("暂未定价");
    }

}

function LoadOnLinePriceShuZhi(priceService, guid) {
    var href = $("#" + guid + " h5 a").attr("href");
    if (href) {
        var doi = href.substring(href.indexOf("doi=") + 4, href.length);

        //数知网。
        // $("#" + guid).next(".extention_element").find(".Zbook").each(function () {
        $("#" + guid).find(".extention_element").find(".Zbook").each(function () {
            var control_P = $(this).parent();
            GetPriceArrayByAjaxControl(doi, priceService, loadPrice_ShowHide, control_P);
        })
    }
}
//数知网。
function loadPrice_ShowHide(priceObj, control) {
    //var oldText = control.text();
    //control.text(priceObj.readPrice);
    //control.text("定　价：--");
    if (priceObj.podPrice) {
        control.find(".Zbook").show();
    }
    if (priceObj.downPrice) {
        control.find(".Ebook").show();
    }

}


function loadPrice_OnLine(priceObj, control) {
    var oldText = control.text(); alert('d');
    //control.text(priceObj.readPrice);
    //control.text("定　价：--");

    if (priceObj.readPrice) {
        control.text(oldText.replace("--", priceObj.readPrice));
        // control.text("定　价：￥"+priceObj.readPrice+"元");
    }

}

//通过Ajax加载价格列表信息
function GetPriceArrayByAjaxControl(doi, priceService, funcName, control) {

    var podPrice;
    var readPrice;
    var downPrice;
    var podOldPrice;
    var readOldPrice;
    var downOldPrice;
    $.getJSON(priceService + "/PriceService.svc/GetPrice?jsoncallback=?",
        { guid: doi },
        function (data) {
            var json = $.parseJSON(data);
            if (json.Success) { // 如果连接正确
                var PBook = json.Book;
                if (PBook != null) {
                    var PDiscountRate = PBook.DiscountRate;
                    var Discount = PBook.Discount;
                    var PPirce = PBook.Price;
                    podOldPrice = PPirce;
                    if (PDiscountRate != null) {
                        if (PDiscountRate.Value > 0) { // 如果减价,不考虑打折
                            podPrice = PPirce - PDiscountRate.Value;
                        } else { // 打折
                            if (Discount != null) {
                                podPrice = multiplication(PPirce, Discount.Value);
                            } else {
                                podPrice = PPirce;
                            }
                        }
                    }
                    else {
                        if (Discount != null) {
                            podPrice = multiplication(PPirce, Discount.Value);
                        }
                        else {
                            podPrice = PPirce;
                        }
                    }
                }
                // 电子书 (在线阅读)
                var EBook = json.EBook;
                //alert("EBook----" + EBook);
                if (EBook != null) {
                    var EPrice = EBook.Price;
                    var EDiscountRate = EBook.DiscountRate;
                    var EDiscount = EBook.Discount;
                    readOldPrice = EPrice;
                    if (EDiscountRate != null) {
                        if (EDiscountRate.Value > 0) { // 降价
                            readPrice = EPrice - EDiscountRate.Value;
                        } else { // 打折
                            if (EDiscount != null) {
                                readPrice = multiplication(EPrice, EDiscount.Value);
                            }
                            else {
                                readPrice = EPrice;
                            }

                        }
                    }
                    else {
                        if (EDiscount != null) {
                            readPrice = multiplication(EPrice, EDiscount.Value);
                        }
                        else {
                            readPrice = EPrice;
                        }
                    }
                }
                // 下载阅读

                var DLBook = json.Downloading;
                //alert("DLBook----"+DLBook);
                if (DLBook != null) {
                    var DLPrice = DLBook.Price;
                    var DLDiscountRate = DLBook.DiscountRate;
                    var DLDiscount = DLBook.Discount;
                    downOldPrice = DLPrice;
                    if (DLDiscountRate != null) {
                        if (DLDiscountRate.Value > 0) { // 降价
                            downPrice = DLPrice - DLDiscountRate.Value;
                        } else { // 打折
                            if (DLDiscount != null) {
                                downPrice = multiplication(DLPrice, DLDiscount.Value);
                            } else {
                                downPrice = DLPrice;
                            }
                        }
                    }
                    else {
                        if (DLDiscount != null) {
                            downPrice = multiplication(DLPrice, DLDiscount.Value);
                        } else {
                            downPrice = DLPrice;
                        }
                    }
                }
            }
            var bookPrice = new BookPriceDetail();
            bookPrice.podPrice = podPrice;
            bookPrice.readPrice = readPrice;
            bookPrice.downPrice = downPrice;
            bookPrice.podOldPrice = podOldPrice;
            bookPrice.readOldPrice = readOldPrice;
            bookPrice.downOldPrice = downOldPrice;
            if (funcName && typeof (funcName) == "function") {
                funcName(bookPrice, control);
            }
        }
    );
}