﻿;
var $ = jQuery.noConflict();
document.domain = 'fanshu.com';
var divNum = parseInt($("#spPC").text()); //生成DIV个数
var ed = $("#hidED").val(); //Metaid
var bcover=$("#hidECover").val();
var bname=$("#hidEName").val();
var bauthor=$("#hidEAuthor").val();
var bprice=$("#hidEPrice").val();
var kw = $("#hidKW").val(); //关键词 漂黄
var root = $("#hidRoot").val(); //Img root网址
var df = parseInt($("#hidDefaultFormat").val());  //新旧图书1新0旧
var secUri = $("#hidSecUri").val();  //图书二级路径
var cip = parseInt($("#hidspPN").val()); //初始页码
var schH = 54; //头部header高度54
var blankH = 10; //div间隔
var hp = $("#hidHP").val(); //飘黄的页码
var st = 0; //当前状态是大图还是小图 0:小图   1:大图
var isFull = false; //是否全屏显示
var arrHP = new Array(divNum); //记录有飘黄的页码 0,1
var hasHP = new Array(divNum); //是否已经加载过飘黄 0,1,2
var hasImg = new Array(divNum); //是否已经加载过图片 0,1,2
var hasRead = new Array(divNum); //记录可以阅读的页码 0,1
var pageHeights = new Array(divNum); //记录每一页所在的高度,小图时
var pageHeightsB = new Array(divNum); //记录每一页所在的高度,小图时
var initPage =1; //记录初始化的页码 处理版权页问题
var imgUrl = new Array(divNum); //记录每一页图片的地址
var catagrayInfo = new Array(); //记录目录起始页信息
var catagrayName = new Array(); //记录目录对应得名字
var isHP = parseInt($("#hidNPH").val()); //是否需要飘黄
var readPagenums = parseInt($("#hidCRD").val()); //免费浏览的页数 从0页开始
var beginReadPage = parseInt($("#hidBRD").val()); //搜索命中后的可阅读起始页
var endReadPage = parseInt($("#hidERD").val()); //搜索命中后的可阅读最后页
var limitImgH = 224; //限制页高度
var isShow = 1; //是否显示飘黄信息  1显示  0不显示
var moving = false; //是否移动
var hasBuy = $("#hidIsSales").val();
var whichOne = 1; //默认提交最上面的text
var W = parseInt($("#hidW").val()); //原始宽
var H = parseInt($("#hidH").val()); //原始高度是加载第一张图后取出来的
var mod = 620 / W; //小图系数
var modB = 920 / W;  //大图系数
var imgH = parseInt(mod * H); //图片小图高度
var imgBH = parseInt(modB * H); //图片大图高度
var IntIsOk = false; //是否加载完第三章图片,也就是说网络是否正常
var chapter= $("#chapter").val();//用户对本书的有效章节（如果为“”&&cip<=readPagenums,表示拥有整本书的阅读权限）
var chapterArr=(chapter=="null"||chapter=="")?null:chapter.split(',');
var pageArr=new Array();//此数组为二维数组，每一组数据存放每个章节的初始页码和结束页码
var rType=parseInt($("#readType").val());
var limitType=parseInt($("#limitType").val());

function checkNum(){
    var n = $("#spPN").val();
    var popobj = new Apabi.dom.PopMenu();
    if ((n.search("^-?\\d+$") != 0) || (parseInt(n) == 0 || parseInt(n) > divNum)) {
        popobj.showTip("请输入正确的页码！",0);
    }
}


//初始化pageArr
function initPageArr(){
    if(chapterArr==null){return;}
    for(var i=0;i<chapterArr.length;i++){
        pageArr[i]=chapterArr[i].split('-');
    }
}

//判断当前页是否可以阅读
function isRead(pagenum)
{
    if(rType==1){
        if(pagenum<=readPagenums||(beginReadPage <= i && i <= endReadPage)){
            return true;
        }
    }else{
         if(chapterArr==null){
            if(pagenum<=readPagenums||(beginReadPage <= i && i <= endReadPage)||chapter==""){
                return true;
            }
         }else{
             for(var i=0;i<pageArr.length;i++){
                if((pagenum>=parseInt(pageArr[i][0])&&pagenum<=parseInt(pageArr[i][1]))||pagenum<=readPagenums){
                    return true;
                }
             }
         }
    }
    return false;
}

//初始化可阅读和限制页，并初始化每页所在的高度
function InitReadPage() {
    if(rType==-1){
       initPageArr();//初始化pageArr
       
       //加入css样式
        if(limitType==1){
            var script = document.createElement('link');
            script.setAttribute('href', "http://read.fanshu.com/css/source_reading.css");
            script.setAttribute('rel', "stylesheet");
            script.setAttribute('type', "text/css");
            document.getElementsByTagName('head')[0].appendChild(script); 
        }
    }
    if(rType==1){
         recordRecent(ed,bcover,bname,bauthor,bprice,rType);
    }
    var pageH = 0;
    var pageBH = 0;
    pageHeights[0] = 0;
    pageHeightsB[0] = 0; 
    //region 记录初始化的页码 处理版权页问题
    for (var i = 0; i < divNum; i++) {
        if (isRead(i+1)) {
            hasRead[i] = 1;
            if(i<initPage-1){
                pageHeights[i + 1] = pageH;
                pageHeightsB[i + 1] = pageBH;
            }else{
                pageHeights[i + 1] = pageH + imgH + blankH;
                pageH = pageHeights[i + 1];
                pageHeightsB[i + 1] = pageBH + imgBH + blankH;
                pageBH = pageHeightsB[i + 1];
            }
            
        } else {
            hasRead[i] = 0;
            pageHeights[i + 1] = pageH + limitImgH + blankH;
            pageH = pageHeights[i + 1];
            pageHeightsB[i + 1] = pageBH + limitImgH + blankH;
            pageBH = pageHeightsB[i + 1];
        }
    }
    //endregion
//    for (var i = 0; i < divNum; i++) {
//        if (isRead(i+1)) {
//            hasRead[i] = 1;
//            pageHeights[i + 1] = pageH + imgH + blankH;
//            pageH = pageHeights[i + 1];
//            pageHeightsB[i + 1] = pageBH + imgBH + blankH;
//            pageBH = pageHeightsB[i + 1];
//        } else {
//            hasRead[i] = 0;
//            pageHeights[i + 1] = pageH + limitImgH + blankH;
//            pageH = pageHeights[i + 1];
//            pageHeightsB[i + 1] = pageBH + limitImgH + blankH;
//            pageBH = pageHeightsB[i + 1];
//        }
//    }
}


//初始化飘黄数组
function InitHP() {
    if (hp.length == 0 && isHP == 1) {
        for (var i = 0; i < divNum; i++)
            arrHP[i] = 1;
    } else {
        for (var i = 0; i < divNum; i++)
            arrHP[i] = 0;
    }
    for (var i = 0; i < arrHP.length; i++) {
        hasHP[i] = 0;
        hasImg[i] = 0;
    }
    if (isHP == 1) {
        if (hp.length > 0) {
            var arr = hp.split(",");
            for (var i = 0; i < arr.length; i++) {
                var j = parseInt(arr[i]) - 1;
                arrHP[j] = 1;
            }
        }
    }
}

//根据st值判断是应该给小图还是大图,并拼接内容图片的地址
function makeurl(page) {
    if (df == 1) {
        if (st == 0) {
            return root + secUri + page + "s.jpg";
        } else {
            return root + secUri + page + "b.jpg";
        }
    } else if(df == 0) {
        if (st == 0) {
            return encodeURI(root + secUri + "/w640_" + page + ".cebimage");
        } else {
            return encodeURI(root + secUri + "/w1000_" + page + ".cebimage");
        }
    }else if(df==2){
        if (st == 0) {
                return encodeURI(root + secUri + page +  "s.jpg");
            } else {
                return encodeURI(root + secUri + page + "b.jpg");
            }
    }else if(df==3){
        if (st == 0) {
            return root + secUri + page + "s.jpg";
        } else {
            return root + secUri + page + "b.jpg";
        }
    }
}

//二分查找当前高度所在页码,并返回在数组中的索引位置
function getPageNumFromHeight(arr, start, end, num) {
    var middle;
    if (start > end) {
        return getPageNumFromHeight(arr, end, start, num);
    }
    if ((end - start) % 2 == 0) {
        middle = (end + start) / 2;
    } else {
        middle = parseInt((end + start) / 2) + 1;
    }
    
    if (arr[middle] == num) {
        return middle;
    }
    if(arr[middle] > num){
        if(middle>0){
            if (arr[middle-1]<=num) {
                return middle-1;
            }else{
               return getPageNumFromHeight(arr, start, middle-1, num);
            }
        }else{
             return middle;
        }
    }
    if(arr[middle] < num){
        if(middle<end){
            if (arr[middle+1]>num) {
                return middle;
            }else{
               return getPageNumFromHeight(arr, middle+1, end, num);
            }
        }else{
             return middle;
        }
    }
}

function getReadDiv(i) {
    var html = "";
    var imgurl = makeurl(i);
    if (st == 0) {
        html = html + "<div id='div_" + i + "' class='layer' style='height:" + imgH + "px;top:" + pageHeights[i - 1] + "px;background:url(\"" + imgurl + "\") no-repeat;'>";
    } else {
        html = html + "<div id='div_" + i + "' class='layer' style='width:920px;height:" + imgBH + "px;top:" + pageHeightsB[i - 1] + "px;margin-left:-460px;background:url(\"" + imgurl + "\") no-repeat'>";

    }
    if (hasImg[i - 1] == 0) {
        html = html + "<span id='sp_" + i + "_1' class='spTop'>正在加载...</span><span id='sp_" + i + "_2' class='spBot'>正在加载...</span>";
    }
    html = html + "</div>";
    return html;
}

function getLimitDiv(i) {
     var html = "";
     if (st == 0) {
            html = html + "<div id='div_" + i + "' class='limit' style='top:" + pageHeights[i - 1] + "px'>";
        } else {
            html = html + "<div id='div_" + i + "' class='limit' style='top:" + pageHeightsB[i - 1] + "px'>";
        }
    if(rType==1){
        var lbGou = $("#lbGou").html();
       // var lbZu = $("#lbZu").html();
        if (hasBuy == 1) {
            html = html + "<div class='txt'><em>第<span>" + i + "</span>页 此页为收费内容 请购买后阅读</em>";
            html = html + "<div class='txt1'>" + lbGou+ "</div></div>";
        } else {
            html = html + "<div class='txt'><em>第<span>" + i + "</span>页 此页为受限内容</em></div>";
        }
        
    }else{
        var lbGou = $("#serialLimit").html();
        html+=lbGou;
    }
    html += "</div>";
    return html;
}
//以google形式（只初始化需要展示的div）
function createDivs(page) {
    if (!IntIsOk) {
        return;
    }
    var curp;
    if (page == 'undefined' || page == undefined) {
        curp = cip;
    } else {
        curp = page;
    }
    var divContainer = $("#Container");
    if (st == 0) {
        divContainer.css('height', pageHeights[divNum] + "px");
    } else {
        divContainer.css('height', pageHeightsB[divNum] + "px");
    }
  
    var per = parseInt(getTotalHeight() / limitImgH);
    var num = 5;
    if(num>divNum){
        num=divNum;
    }
    var n = 3;
    var html = "";
    if (curp == 1) {
        for (var i = curp; i <= num; i++) {
            if (hasRead[i - 1] == 1) {
                html += getReadDiv(i);
            } else {
                html += getLimitDiv(i);
            }
        }
    } else if (curp == divNum) {
        for (var i = num; i >= 0; i--) {
            if (hasRead[curp - i - 1] == 1) {
                html += getReadDiv(curp - i);
            } else {
                html += getLimitDiv(curp - i);
            }
        }
    } else {
        //初始化当前页之前的n个div
        for (var i = n; i >= 1; i--) {
            if (curp - i > 0) {
                if (hasRead[curp - i - 1] == 1) {
                    html += getReadDiv(curp - i);
                } else {
                    html += getLimitDiv(curp - i);
                }
            }
        }
        //初始化当前div
        if (hasRead[curp - 1] == 1) {
            html += getReadDiv(curp);
        } else {
            html += getLimitDiv(curp);
        }
        //初始化之后n个div
        for (var j = 1; j <= n; j++) {
            var page = parseInt(curp) + j;
            if (page <= divNum) {
                if (hasRead[page - 1] == 1) {
                    html += getReadDiv(page);
                } else {
                    html += getLimitDiv(page);
                }
            }
        }
    }
    divContainer.html(html);
   
}
//加载图片
function LoadImg(url, i) {
    if (i > divNum || i <= 0)
        return;
    if (hasRead[i - 1] == 0)
        return;
    if (st == 0 && hasImg[i - 1] == 1)
        return;
    if (st == 1 && hasImg[i - 1] == 2)
        return;
    $("#sp_" + i + "_1").hide();
    $("#sp_" + i + "_2").hide();

    var image = new Image();
    image.onload = function() {
        $("#sp_" + i + "_2").hide();
    };

    image.src = url;
    $("#div_" + i).css("background", "url(" + image.src + ") no-repeat");
    if (arrHP[i - 1] == 1 && (hasHP[i - 1] == 0 || (hasHP[i - 1] == 1 && st == 1) || (hasHP[i - 1] == 2 && st == 0))) {
        Csscoord($("#div_" + i), i); //当需要飘黄，且还未加载过飘黄或小图未加载或大图未加载
    }
    if (st == 0) {
        hasImg[i - 1] = 1; //has load Img
    } else {
        hasImg[i - 1] = 2;
    }
}
//加载下一张图
function LoadNextImg(i) {
    var n = i + 1;
    LoadImg(makeurl(n), n);
}
//飘黄
function Csscoord(d, i) {
    var url = "bookpic.fcgi?qw=" + kw + "&bd=" + ed + "&pg=" + i + "&pf=0";
    $.getJSON(url, function(text) {
        var imgH = text.h;
        var imgW = text.w;
        if (st == 0)
            mod = 620 / imgW;
        else
            mod = 920 / imgW;
        for (var i = 0; i < text.font.length; i++) {
            var h = parseInt(text.font[i].h);
            var w = parseInt(text.font[i].w);
            var l = parseInt(text.font[i].l);
            var t = parseInt(text.font[i].t);
            if (h < 0 || w < 0 || l < 0 || t < 0) {
                continue;
            }
            var yh = h * mod + "px";
            var yw = w * mod + "px";
            var yl = l * mod + "px";
            var yt = t * mod + "px";
            if (isShow == 1)
                $("<div/>").css("width", yw).css("height", yh).css("left", yl).css("top", yt).addClass('is_show_yellow').addClass('msg_yellow').appendTo(d);
            else
                $("<div/>").css("width", yw).css("height", yh).css("left", yl).css("top", yt).addClass('is_show_yellow').appendTo(d);
        }
    });
    if (st == 0)
        hasHP[i - 1] = 1;
    else
        hasHP[i - 1] = 2;
}
//点击目录
function ScrollGotoML(f) {
    f = parseInt(f);
    if (f > 0 && f <= divNum) {
        GotoPage(f);
        var limtNum = parseInt($("div.limit").length);
        if (limtNum > 2) {
            setTimeout("waitGoto(" + f + ")", 50);
        }
    } else {
         var popobj = new Apabi.dom.PopMenu();
          popobj.showTip("超出可阅读范围！",0);
    }
    $(".catalogs").hide();
}
//显示目录 
   var scrollTo=0;
function ShowCatalog() {
    var nowNum = parseInt($("#spPN").val());
    
    var targets = $(".catalogs a");
    var target = $(".catalogs");
    target.html("");

    if (catagrayInfo.length > 0) {
//        if (targets.length == 0) {
            for (var i = 0; i < catagrayInfo.length; i++) {
                var addCss="";
                if(nowNum>=catagrayInfo[i]&&nowNum<catagrayInfo[i+1])
                {
                    addCss=" class='show'";
                    scrollTo=i;
                }
                var html = "<a href='javascript:void(0)'"+addCss+" onmouseover='return false;' onmousemove='return false;' onmouseout='return false;' onclick='ScrollGotoML(" + catagrayInfo[i] + ")'><em>第"+ catagrayInfo[i] + "页</em>"+ catagrayName[i]+"</a>";
                $(html).appendTo(target);
                
            }
            
//        }
    } else {
        target.html("<a href='javascript:void(0)'>该书没有目录数据！</a>");
        target.css("height", "30px");
    }
   
    setMuluDivPosition();
}
//设置目录弹出div的位置
function setMuluDivPosition() {
    var cataleft = document.getElementById("cataname").getBoundingClientRect().left;
    var catatop = document.getElementById("cataname").getBoundingClientRect().top;
    var cataheight = 17;
    var cat = $(".catalogs");
    cat.show();
    cat.css("left", cataleft);
    cat.css("top", catatop + cataheight);
    cat.scrollTop(20*(scrollTo-4));
     
}
//跳转
function ScrollGoto() {
    var f = $("#spPN").val();
    if (f == "" || (f.search("^-?\\d+$") != 0) || (parseInt(f) == 0)) {
       var popobj = new Apabi.dom.PopMenu();
       popobj.showTip("请输入正确的数字！",0);
       return;
    }
    f = parseInt(f);
    if (f > divNum || f < 0) {
        var popobj = new Apabi.dom.PopMenu();
        popobj.showTip("超出可阅读范围！",0);
        return;
    } else {
        GotoPage(f);
        var limtNum = parseInt($("div.limit").length);
        if (limtNum > 2) {
            setTimeout("waitGoto(" + f + ")", 50);
        }
    }
    changeButtonImage();
}
function waitGoto(page) {
    $("#spPN").val(page);
    changeButtonImage();
}
//跳转到指定页面
function GotoPage(page, flag,isByInterval) {
    //region 记录初始化的页码 处理版权页问题
    if(page<initPage){
        GotoPage(initPage);
        return;
    }
    //endregion
    if ($("#div_" + page).size() == 0 || flag == 1) {
        $("#Container>div").remove();
        createDivs(page);
    }
    if(isByInterval==0){
        if (st == 0) {
            ScrollByInterval(pageHeights[page - 1]);
        } else {
            ScrollByInterval(pageHeightsB[page - 1]);
          }
    }else{
        if (st == 0) {
                $("#divSrl").scrollTop(pageHeights[page - 1]);
        } else {
                $("#divSrl").scrollTop(pageHeightsB[page - 1]);
          }
        
     }
}
//向前翻页
function ScrollPre() {
    var f = parseInt($("#spPN").val());
    //找到当前div的最小页码
    var fobj = $("#Container>div:first");
    var fid = fobj.attr('id');
    var fp = parseInt(fid.substring(4));
    var limtNum = parseInt($("div.limit").length);
    if ((limtNum > 1 && limtNum < 4 && f >= divNum - limtNum + 3) || (limtNum > 2 && f > divNum - 2)) {
        $("#spPN").val(f - 1);
        changeButtonImage();
        return;
    }
    //fp > 1 处理版权
    if (fp > initPage) {
        $("#Container>div:last").remove();
        if (hasRead[fp - 2] == 1) {
            fobj.before(getReadDiv(fp - 1));
        } else {
            fobj.before(getLimitDiv(fp - 1));
        }
    }
     //fp > 1  处理版权
    if (f > initPage) {
        $("#spPN").val(f - 1);
        if (st == 0) {
//            $("#divSrl").scrollTop(pageHeights[f - 2]);
              ScrollByInterval(pageHeights[f - 2]);
        } else {
//            $("#divSrl").scrollTop(pageHeightsB[f - 2]);
              ScrollByInterval(pageHeightsB[f - 2]);

        }
    }
//    changeButtonImage();
}
//向后翻页
function ScrollNext() {
    var f = parseInt($("#spPN").val());
    //找到当前div的最大页码
    var fobj = $("#Container>div:last");
    var fid = fobj.attr('id');
    var fp = parseInt(fid.substring(4));
    var limtNum = parseInt($("div.limit").length);
    if (fp < divNum) {  // && limtNum < 5
        $("#Container>div:first").remove();
        if (hasRead[fp] == 1) {
            fobj.after(getReadDiv(fp + 1));
        } else {
            fobj.after(getLimitDiv(fp + 1));
        }
    }
    if (f < divNum) {
        $("#spPN").val(f + 1);
        if ((limtNum > 1 && limtNum < 4 && f > divNum - limtNum) || (limtNum > 2 && f >= divNum - 2)) {
            changeButtonImage();
            return;
        }
        if (st == 0) {
//            $("#divSrl").scrollTop(pageHeights[f]);
              ScrollByInterval(pageHeights[f]);
        } else {
//            $("#divSrl").scrollTop(pageHeightsB[f]);
              ScrollByInterval(pageHeightsB[f]);
        }
         
    }
//    changeButtonImage();
}
function GetSrlNum() {
    var cp = parseInt($("#spPN").val());
    var gonum =0;
    if(st==0){
        gonum=getPageNumFromHeight(pageHeights,0,divNum,document.getElementById("divSrl").scrollTop);
    }else{
        gonum=getPageNumFromHeight(pageHeightsB,0,divNum,document.getElementById("divSrl").scrollTop);
    }
    var limtNum = parseInt($("div.limit").length);
    if (gonum == cp) {
        var fobj = $("#Container>div:last");
        var fid = fobj.attr('id');
        var fp = parseInt(fid.substring(4));
        if (fp + 1 <= divNum) {
            $("#Container>div:first").remove();
            if (hasRead[fp] == 1) {
                fobj.after(getReadDiv(fp + 1));
            } else {
                fobj.after(getLimitDiv(fp + 1));
            }
        }
    } else if (cp - 2 == gonum) {   // && (limtNum < 6)
        var fobj = $("#Container>div:first");
        var fid = fobj.attr('id');
        var fp = parseInt(fid.substring(4));
        if (fp - 1 > 0) {
            $("#Container>div:last").remove();
            if (hasRead[fp - 2] == 1) {
                fobj.before(getReadDiv(fp - 1));
            } else {
                fobj.before(getLimitDiv(fp - 1));
            }
        }
    } else if (gonum > cp || gonum < cp - 2) {

        GotoPage(gonum + 1, 1);
          //下面两句是 GotoPage(gonum + 1, 1)中的一部分，如果想要平滑效果再用GotoPage(gonum + 1, 1)的话会出现跳转混乱的情况，因为
//          $("#Container>div").remove();
//          createDivs(gonum + 1);
    } else {
        setTimeout("ForShowImg(" + gonum + ")", 2000); //可-10
    }
    $("#spPN").val(gonum + 1);
    /**更改前后页图片*/
    changeButtonImage();
    checkCurrentChapter(gonum + 1);
}
//设置向前向后翻页按钮的图片显示
function changeButtonImage() {
    var cpage = parseInt($("#spPN").val());
    var lastpage = parseInt($("#spPC").text());
    if (cpage == initPage) {//cpage == 1 出理版权页
        $("#aPre").attr("class", "up_s");
        $("#aPre").attr("href", "javascript:void(0);");
        $("#aNext").attr("class", "down");
        $("#aNext").attr("href", "javascript:ScrollNext();");
    } else if (cpage == lastpage) {
        $("#aNext").attr("class", "down_s");
        $("#aNext").attr("href", "javascript:void(0);");
        $("#aPre").attr("class", "up");
        $("#aPre").attr("href", "javascript:ScrollPre();");
    } else {
        $("#aPre").attr("class", "up");
        $("#aPre").attr("href", "javascript:ScrollPre();");
        $("#aNext").attr("class", "down");
        $("#aNext").attr("href", "javascript:ScrollNext();");
    }
    if(st==1){
        $(".limit").css("width","920px");
        $(".limit").css("left","39.5%");
    }
}
//2秒钟后自动执行的前后页加载
function ForShowImg(nowNum) {
    LoadNextImg(nowNum);
    LoadNextImg(nowNum + 1);
}
//得到初始页数
function GetInitNum() {
    var numPage=0;
    if(st==0){
        numPage=parseInt(getPageNumFromHeight(pageHeights,0,divNum,document.getElementById("divSrl").scrollTop))+1;
    }else{
        numPage=parseInt(getPageNumFromHeight(pageHeightsB,0,divNum,document.getElementById("divSrl").scrollTop))+1;
    }
     $("#spPN").val(numPage);
    changeButtonImage();
}
function Closeit(div) {
    $("#" + div).hide();
}
//移动DIV
function move_div() {
    this.offsetY = 0;
    this.div_mousemove = function(evt, eBut) {
        var e = evt ? evt : (window.event ? window.event : null);
        if (eBut != 1 || (!moving)){
            return false;
        }
        document.getElementById("divSrl").scrollTop = this.offsetY - e.clientY;

    };
    this.div_mousedown = function(evt) {
        var e = evt ? evt : (window.event ? window.event : null);
        moving = true;
        this.offsetY = e.clientY + parseInt(document.getElementById("divSrl").scrollTop);
    };
}
//移动目录树
function moveMenuBar() {
    this.offsetY = 0;
    this.div_mousemove = function(evt, eBut) {
        var e = evt ? evt : (window.event ? window.event : null);
        if (eBut != 1 || (!moving))
            return false;
        document.getElementById("page_number").scrollTop = this.offsetY - e.clientY;
    };
    this.div_mousedown = function(evt) {
        var e = evt ? evt : (window.event ? window.event : null);
        moving = true;
        this.offsetY = e.clientY + parseInt(document.getElementById("page_number").scrollTop);
    };
}

//移动读书笔记文本框
function moveSummeryDiv() {
    this.divX=0;
    this.divY=0;
    this.mouseX=0;
    this.mouseY=0;
    this.div_mousemove = function(evt, eBut) {
        var e = evt ? evt : (window.event ? window.event : null);
        if (eBut != 1 || (!moving))
            return false;
         var moveX=e.clientX-this.mouseX;
         var moveY=e.clientY-this.mouseY;
         $("#divBkExt").css("top",(this.divY+moveY)+"px");
         $("#divBkExt").css("left",(this.divX+moveX)+"px");
    };
    this.div_mousedown = function(evt) {
        var e = evt ? evt : (window.event ? window.event : null);
        this.divX=parseInt($("#divBkExt").css("left"));
        this.divY=parseInt($("#divBkExt").css("top"));
         
        this.mouseX=e.clientX;
        this.mouseY =e.clientY;
        moving = true;
    };
}
//在页面加载完之前处理票黄信息
var beforReady = function() {
    var isShowTarget = getIsShowYellow();
    if (isShowTarget != null && isShowTarget != 'undefined' && isShowTarget != 'null' && isShowTarget != '') {
        isShow = parseInt(isShowTarget);
    }
    if (isHP) {
        if (isShow) {
            $(".msg_bg1").show();
            $(".msg_bg2").hide();
        } else {
            $(".msg_bg2").show();
            $(".msg_bg1").hide();
        }
    }
};
//页面加载入口
$("#divSrl").ready(function() {
    var cateTree = $("#page_number");
    var divSrl = $("#divSrl");
    initCatagrayInfo();
    getInitHeight(); //取得该书的实际小图高度，只调用一次
    
    cateTree.css('height', getTotalHeight() - 54 - 24 - 10 + "px").css('top', '105px'); //91px

    divSrl.scroll(GetSrlNum);
    checkCurrentChapter(cip);

    var infoRmove = new move_div();
    divSrl.mousedown(function(e) { infoRmove.div_mousedown(e); return false;});
    divSrl.mousemove(function(e) { infoRmove.div_mousemove(e, e.which); show_bottom_scroll_div(e);return false;});
    divSrl.mouseup(function(e) { moving = false;return false; });
    divSrl.mouseout(function(e) { moving = false; return false; });
    var menuMove = new moveMenuBar();
    cateTree.mousedown(function(e) { menuMove.div_mousedown(e); return false; });
    cateTree.mousemove(function(e) { menuMove.div_mousemove(e, e.which); return false; });
    cateTree.mouseup(function(e) { moving = false; return false; });
    cateTree.mouseout(function(e) { moving = false; return false; });
    
    
    //begin 实现添加读书笔记可拖拽功能
    var summeryDivMove=new moveSummeryDiv();
    var summertDiv1=$("#divBKExt_div1");
    summertDiv1.mousedown(function(e) { summeryDivMove.div_mousedown(e);return false; });
    summertDiv1.mousemove(function(e) { summeryDivMove.div_mousemove(e, e.which); return false; });
    summertDiv1.mouseup(function(e) { moving = false; return false; });
    summertDiv1.mouseout(function(e) { moving = false; return false; });
    //end 实现添加读书笔记可拖拽功能
     showAndautoClose($('.screen_text'));//显示”点击全屏可放大阅读“
//      passport.valIsLogin(function(){
//        showAndautoClose($('.screen_text'));//显示”点击全屏可放大阅读“
//      }, isLogin);
      set_bottom_scroll_div_top(false);//设置透明下翻页按钮的宽度和高度
      setTimeout(function(){IsShowLastMarkPage();},4000); //等到”点击全屏可放大阅读“消失 显示上次阅读的页数
});

//判断是否登录
//function isLogin(){
//   $("#divSrl").hide();
//    $("#shadebg").show();
//    passport.poplr(function(){
//        $("#divSrl").show();
//        $("#shadebg").hide();
//        showAndautoClose($('.screen_text'));//显示”点击全屏可放大阅读“
//    }, true);
//    $("#pass_popmenu").css("z-index",10000);
//}

//是否显示上次阅读的页数
function IsShowLastMarkPage(){
    var lastPage=parseInt($("#markPage").val());
    if(lastPage>0&&lastPage!=cip){
       $(".con_reading").html("<a href=\"javascript:void(0);\" onclick=\"$('.con_reading').hide();\" class=\"fr\" href=\"javascript:void(0);\">关闭</a>您上次阅读到第<b>"+lastPage+"</b>页，<a onclick=\"ScrollGotoML("+lastPage+");$('.con_reading').hide();\" href=\"javascript:void(0);\">点击继续阅读</a>");
        $(".con_reading").show();
    }
}

//全屏显示
function ShowFull() {
    //hidAllDiv();
    $("#header").hide();
    $(".menu_td").hide();
    $("#aFull").attr("class", "screen");
    $("#aFull").attr("href", "javascript:ShowSingle();");
     $("#aFull").attr("title", "退出全屏");

    isFull = true;
    st = 1;
    mod = 920 / W; //更改系数
    imgH = parseInt(mod * H); //1285
    imgBH = parseInt(modB * H);
    var divSrl = $("#divSrl");
    divSrl.css("width", "100%");
    var headHeight = $("#header").css('height');
    $(".lay1").css('height', getTotalHeight() + "px");
    divSrl.css("height", getTotalHeight() - 20 + "px");
    $("#Container").css("height", pageHeightsB[divNum]);

    $(".page_number").css('height', getTotalHeight() - 26 + "px").css('top', "30px");
    getMenuInfo();
    var currPage = parseInt($("#spPN").val());
    if ($(".layer").css('width') != '920px') {
        GotoPage(currPage, 1);
        ChangeImg(st);
    }
    //$(".is_show_yellow").remove();
    if (isHP == 1) {
        Csscoord($("#div_" + currPage), currPage);
        Csscoord($("#div_" + (currPage + 1)), currPage + 1);
    }
    $("#aBig").attr("href", "javascript:void(0);");
    $("#aBig").attr("class", "zoo_b");
    $("#aSmall").attr("href", "javascript:ShowSmall();");
    $("#aSmall").attr("class", "zoo_s");
    set_bottom_scroll_div_top(true);//设置透明下翻页按钮的宽度和高度
    $(".bottom_scroll").attr("onClick","ScrollNextScreen()");

    $(".limit").css("width","920px");
    $(".limit").css("left","39.5%");
}
//非全屏显示时
function ShowSingle() {
    //hidAllDiv();
    $("#header").show();
    $(".menu_td").show();
    $("#aFull").attr("class", "screen_s");
    $("#aFull").attr("href", "javascript:ShowFull();");
    $("#aFull").attr("title", "全屏显示");

    var headHeight = $("#header").css('height');
    $("#divSrl").css("height", getTotalHeight() - 90 + "px");

    isFull = false;
    st = 0;
    mod = 620 / W; //更改系数
    imgH = parseInt(mod * H);
    imgBH = parseInt(modB * H);
    $("#Container").css("height", pageHeights[divNum] + "px");

    $(".page_number").css('height', getTotalHeight() - 96 + "px").css('top', '105px'); //91px
    getMenuInfo();

    var currPage = parseInt($("#spPN").val());
    if ($(".layer").css('width') != '620px') {
        GotoPage(currPage, 1);
        ChangeImg(st);
    }
    //$(".is_show_yellow").remove();
    if (isHP == 1) {
        Csscoord($("#div_" + currPage), currPage);
        Csscoord($("#div_" + (currPage + 1)), currPage + 1);
    }
    $("#aBig").attr("href", "javascript:ShowBig();");
    $("#aBig").attr("class", "zoo_b");
    $("#aSmall").attr("href", "javascript:void(0);");
    $("#aSmall").attr("class", "zoo_s");
    set_bottom_scroll_div_top(false);//设置透明下翻页按钮的宽度和高度
     $(".bottom_scroll").attr("onClick","ScrollNextScreen()");
}
//放大
function ShowBig() {
    //hidAllDiv();
    st = 1;
    mod = 920 / W; //更改系数
    imgH = parseInt(mod * H); //1285
    imgBH = parseInt(modB * H);
    $("#divSrl").css("width", "100%");
    $(".menu_td").css("display", "none");
    $("#Container").css("height", pageHeightsB[divNum] + "px");
    var currPage = parseInt($("#spPN").val());
    GotoPage(currPage, 1);
    ChangeImg(st);
    //$(".is_show_yellow").remove();
    if (isHP == 1) {
        Csscoord($("#div_" + currPage), currPage);
        Csscoord($("#div_" + (currPage + 1)), currPage + 1);
    }
    $("#aBig").attr("href", "javascript:void(0);");
    $("#aBig").attr("class", "zoo_b");
    $("#aSmall").attr("href", "javascript:ShowSmall();");
    $("#aSmall").attr("class", "zoo_s");
    set_bottom_scroll_div_top(true);//设置透明下翻页按钮的宽度和高度
     $(".bottom_scroll").attr("onClick","ScrollNextScreen()");
    
    $(".limit").css("width","920px");
    $(".limit").css("left","39.5%");
}
//默认显示（缩小）
function ShowSmall() {
    //hidAllDiv();
    st = 0;
    mod = 620 / W; //更改系数
    imgH = parseInt(mod * H);
    imgBH = parseInt(modB * H);
    $("#Container").css("height", pageHeights[divNum] + "px");
    if (!isFull) {
        $(".menu_td").css("display", "");
    }

    var currPage = parseInt($("#spPN").val());
    GotoPage(currPage, 1);
    ChangeImg(st);
    //$(".is_show_yellow").remove();
    if (isHP == 1) {
        Csscoord($("#div_" + currPage), currPage);
        Csscoord($("#div_" + (currPage + 1)), currPage + 1);
    }
    $("#aBig").attr("href", "javascript:ShowBig();");
    $("#aBig").attr("class", "zoo_b");
    $("#aSmall").attr("href", "javascript:void(0);");
    $("#aSmall").attr("class", "zoo_s");   
    set_bottom_scroll_div_top(false);//设置透明下翻页按钮的宽度和高度 
      $(".bottom_scroll").attr("onClick","ScrollNextScreen()");
}
function hidAllDiv() {
    $("div.msg_yellow").each(function() {
        $(this).hide();
    });
}
//设置当前的状态 0 默认大小  1 放大
function ChangeImg(type) {
     //begin 设置书签的属性
    if(type==0){
        $(".con_reading").css("margin-left","-317px"); 
        $(".con_reading").css("width","618px");
    }else{
         $(".con_reading").css("margin-left","-468px"); 
         $(".con_reading").css("width","918px");
    }
     //end 设置书签的属性
    var f = parseInt($("#spPN").val()) - 1;
    ForShowImg(f);
//     alert($("#Container").css("width"));
}
//显示黄色提示快
var ShowYellow = function() {
    isShow = 1;
    //$(".is_show_yellow").addClass('msg_yellow');
    $(".msg_bg1").show();
    $(".msg_bg2").hide();
    $.cookie("is_show_yellow", "1", { expires: 30, path: '/', domain: 'fanshu.com' });
};
//取消黄色提示
var HiddenYellow = function() {
    isShow = 0;
    //$(".is_show_yellow").removeClass('msg_yellow');
    $(".msg_bg1").hide();
    $(".msg_bg2").show();
    $.cookie("is_show_yellow", "0", { expires: 30, path: '/', domain: 'fanshu.com' });
};
//从cookie获取是否需要显示黄色
var getIsShowYellow = function() {
    //return $.cookie("is_show_yellow");
};
//初始化目录信息
var initCatagrayInfo = function() {
    var catagrayType=$("#catagrayType").val();
    $.getJSON("../services/EBookService.ashx?jsoncallback=?", { action: "fill", id: encodeURIComponent(ed),ctype:catagrayType }, function(cataData) {
//        var cataData = eval(json);
        if(cataData==undefined||cataData==null){
            return;
        }
        var index = 0;
        for (var i = 0; i < cataData.length; i++) {
            if (i == 0) {
                catagrayInfo[index] = parseInt(cataData[i].s);
                catagrayName[index] = decodeURIComponent(cataData[i].n);
                index++;
            } else {
                if (cataData[i].s != cataData[i - 1].s) {
                    catagrayInfo[index] = parseInt(cataData[i].s);
                    catagrayName[index] = decodeURIComponent(cataData[i].n);
                    index++;
                }
            }
        }
    },"json");
};

//根据目录信息创建目录树
var getMenuInfo = function() {
    $(".page_number div").remove();
    var allHeight = parseInt($(".page_number").css("height"));
    var vh = 6;    //最小间隔
    var cataLength = catagrayInfo.length;
    if (cataLength == 0 || (!IntIsOk)) {
        setTimeout("getMenuInfo()", 1000);
        return;
    }
    //为了解决章节多，从而每个按钮都拥挤在一起的问题，
    //当前采取的措施是每个div向上padding6个像素，
    //这样就会导致漂浮按钮的层的高度比底下的那个竖线高了 menu个数*30个像素，
    //希望将这些等比例的去分配到章节中去从而产生了这样一个modeH
    var modeH = allHeight / (allHeight + vh * cataLength);
    var virtualH = allHeight + vh * cataLength;
    var containerH = pageHeights[divNum];
    var htmls = "";
    var prePage;
    var prePageHeight;
    var preH;
    var lastH;
    var topH;
    var startPage;
    var currentPageH;
    var heightDiv = 0;
    for (var i = 0; i < cataLength; i++) {
        startPage = catagrayInfo[i];
        currentPageH = pageHeights[startPage];
//        if (i == 0) {
//            topH = virtualH * (currentPageH / containerH) * modeH;
//        } else if (i != 0 && i != cataLength - 1) {
            if (i != cataLength - 1) {
            prePage = catagrayInfo[i - 1];
            prePageHeight = pageHeights[prePage];
            preH = virtualH * ((currentPageH - prePageHeight) / containerH) * modeH;
            heightDiv = preH + vh;
        } else {
            lastH = virtualH * ((containerH - currentPageH) / containerH) * modeH;
            heightDiv = vh + lastH;
        }
        htmls += "<div id=menuBar" + i + " style='height:" + heightDiv + "px'><a id='" + i + "' href='javascript:void(0);' onmouseover='showMenuInfo(this)' onmouseout='hiddenMubuBox()' onclick='ScrollGotoML(" + startPage + ")'></a></div>";
    }
    $(".page_number").html(htmls);
//    $("#menuBar0").css('margin-top', topH + vh + "px");
    $("#menuBar0").css('margin-top',vh + "px");
};
//获得浏览器的高度
function getTotalHeight() {
    if ($.browser.msie) {
        return document.compatMode == "CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight;
    } else {
        return self.innerHeight;
    }
   
}
function autoheight() {
    var allHeight = getTotalHeight();
    var headHeight = parseInt($("#header").css('height'));
    var menuHeight = parseInt($(".funcbar").css('height'));
    if (!isFull) {
        $("#divSrl").css("height", allHeight - headHeight - menuHeight - 6);
        $(".page_number").css('height', allHeight - headHeight - menuHeight - 20); //-6
    } else {
        $("#divSrl").css("height", allHeight - menuHeight - 6);
        $(".page_number").css('height', allHeight - menuHeight - 6);
    }
    getMenuInfo();
    checkCurrentChapter(cip);
}
//隐藏章节提示框
var hiddenMubuBox = function() {
    $(".msg_page").hide();
};
//显示章节提示框
var showMenuInfo = function(obj) {
    $(".msg_page a").remove();
    var text = parseInt(obj.id);
    var html = "<a href='javascript:void(0)'>" + catagrayName[text] +"<span>第"+ catagrayInfo[text] + "页</span></a>";
    $(html).appendTo($(".msg_page"));
    $(".msg_page").show();
    $(obj).bind('mouseover', function(e) {
        $(".msg_page").css('top', e.pageY - 25 + "px");
    });
};
//判断当前页所处的章节
var checkCurrentChapter = function(curPage) {
    $(".show").removeClass('show');
    if (curPage >= catagrayInfo[catagrayInfo.length - 1]) {
        $("#menuBar" + (catagrayInfo.length - 1) + " a").addClass("show");
    } else {
        var index = getCurrentIndex(catagrayInfo, 0, catagrayInfo.length, curPage);
        $("#menuBar" + index + " a").addClass("show");
    }
};
//二分查找当前所在目录,并返回在数组中的索引位置
function getCurrentIndex(arr, start, end, num) {
    var middle;
    if ((end - start) % 2 == 0) {
        middle = (end + start) / 2;
    } else {
        middle = parseInt((end + start) / 2) + 1;
    }
    if (start > end) {
        return end;
    }
    if (arr[middle] == num) {
        return middle;
    }
    else if (num < arr[middle]) {
        return getCurrentIndex(arr, start, middle - 1, num);
    }
    else if (num > arr[middle]) {
        return getCurrentIndex(arr, middle + 1, end, num);
    }
}
//显示书内关键词
var showKeywordInBook = function() {
    var bookid = $("#hidED").val();
    var json = $("#keywordsInBook").val();
    if (json == '') {
        json = "[]";
    }
    var html = "";
    var parent = $(".phrases");
    var ah = $(".phrases a");
    if (ah.length > 0) {
        return;
    }
    var data = eval(json);
    if (data.length == 0) {
        parent.remove();
    } else {
        var html = "";
        var keyword;
        var urls;
        for (var i = 0; i < data.length; i++) {
            keyword = data[i].k;
            urls = "s.fcgi?qw=" + keyword + "&wm=0&st=&tp=0&bd=" + bookid + "&pg=1&ifp=0&ath=&pub=&isbn=&pf=10&ifr=1&nowp=0&wf=1&t=2";
            if (i < 5) {
                html += "<a href='" + urls + "' target='_blank'><b>" + keyword + "</b></a> ";
            } else {
                html += "<a href='" + urls + "' target='_blank'>" + keyword + "</a> ";
            }
        }
        parent.html(html);
    }
};
function toHander() {
    $("#Container").css("cursor", "url(/images/closehand.cur),auto");
}
function toPointer() {
    $("#Container").css("cursor", "url(/images/openhand.cur),auto");
}
function clearOther(n) {
    whichOne = n;
}
//当改变浏览器大小时重新设置高度
$(window).bind('resize', function() {
    if(st==1){
        set_bottom_scroll_div_top(true);
    }else{
        set_bottom_scroll_div_top(false);
    }
    autoheight();
});
//屏蔽右键
$(document).ready(function() {
    $(document).bind("contextmenu", function(e) {
        return false;
    });
});
document.onkeypress = function(event) {
    if ($.browser.msie) {
        SubmitForm();
    } else {
        SubmitFormFirfox(event);
    }
}
function submitform() {
    //var query_word = document.form1.qw.value;
    //saveSearchRecord(query_word);
    //document.getElementById('form1').submit();
}
function submitforms() {
    //document.form2.bd.value = document.getElementById("hidED").value;
    //document.form2.qw.value = document.getElementById("searchqws").value;
    //document.form2.t.value = 2;
    //document.getElementById('form2').submit();
}
function SubmitForm() {
    if (window.event.keyCode == 13) {
        if (whichOne == 1) {
            submitform();
        } else if (whichOne == 2) {
            submitforms();
        } else if (whichOne == 3) {
            ScrollGoto();
        } else {
            return;
        }
    }
}
function SubmitFormFirfox(event) {
    if (event.keyCode == 13) {
        if (whichOne == 1) {
            submitform();
        } else if (whichOne == 2) {
            submitforms();
        } else if (whichOne == 3) {
            ScrollGoto();
        } else {
            return;
        }
    }
}
var ShowBK = function() {
//    passport.valIsLogin(function(){$("#BEcip").val($("#spPN").val());$("#divBkExt").show();},passport.poplr(function(){$("#BEcip").val($("#spPN").val());$("#divBkExt").show();}));
    $.post("../services/DoLoginService.ashx", { done: "islogin" },function(result){
       switch (parseInt(result)){
           case -2: passport.poplr(ShowBK);break;
           case 1:
               $("#BEcip").val($("#spPN").val());
               $("#divBkExt").show();
//             var popobj = new Apabi.dom.PopMenu("提交读书笔记");
//             popobj.showTip("<div class='msg_text msg_bg5'>"+bname+"<br><span>所在页码：第<input type='text' class='input_num1' id='BEcip'>页<br>读书笔记正文：<br><textarea class='input_num2' id='txtBody'></textarea></span></div>",0,"提交",SaveSummary); 
//             $("#BEcip").val($("#spPN").val());
             break;
       }
   });
};
function SaveSummary() {
    var p = $("#BEcip").val();
    var b = $("#txtBody").val();
    var popobj = new Apabi.dom.PopMenu("提交读书笔记");
    if ((p.search("^-?\\d+$") != 0) || (parseInt(p) == 0 || parseInt(p) > divNum)) {
        popobj.showTip("请输入正确的页码！",0);
        return;
    }
    if (isSpace(b)) {
        popobj.showTip("请输入读书笔记内容！",0);
        return;
    }
    $.post("../services/EBookService.ashx", { action: "savesu", id: ed, page: p, boby: encodeURIComponent(b),bookname:encodeURIComponent(bname)}, function(json) {
         switch(json.result){
            case 1:
                $("#BEcip").val("");
                $("#txtBody").val("");
                $("#divBkExt").hide();
                popobj.showTip("发表成功",1); 
                break;
            case 0: popobj.showTip("发表失败",-1); break;
            case -1:popobj.showTip("对不起，您已经被禁言",0); break;
            case -2:popobj.showTip("您输入的内容不规范",0); break;
            case -3: passport.poplr(ShowBK);break;
         } 
    });

//    var p = $("#BEcip").val();
//    var b = $("#txtBody").val();
//    if ((p.search("^-?\\d+$") != 0) || (parseInt(p) == 0 || parseInt(p) > divNum)) {
//        alert("请输入正确的页码！");
//        return;
//    }
//    if (isSpace(b)) {
//        alert("请输入读书笔记内容！");
//        return;
//    }
//    $.post("../services/EBookService.ashx", { action: "savesu", id: ed, page: p, boby: encodeURIComponent(b),bookname:encodeURIComponent(bname)}, function(json) {
//         var popobj = new Apabi.dom.PopMenu();
//         switch(json.result){
//            case 1:
//                $("#BEcip").val("");
//                $("#txtBody").val("");
//                $("#divBkExt").hide();
//                popobj.showTip("发表成功",1); 
//                break;
//            case 0: alert("发表失败"); break;
//            case -1:alert("对不起，您已经被禁言"); break;
//            case -2:alert("您输入的内容不规范"); break;
//            case -3: passport.poplr(ShowBK);break;
//         } 
//    });
}

var defaultkey = "请输入书名";
function search() {

 var keyPre = $("#txtKey").val();
	        if (keyPre == "" || keyPre == null || keyPre == defaultkey) {
	            alert("请输入关键词");
	            return false;
	        }
//	        var sHref="http://s.fanshu.com/fcgi-bin/s.fcgi?";
            var sHref="http://s.fanshu.com/fs.fcgi?";

            sHref += "qw="+encodeURIComponent(keyPre);//搜索关键字
//            sHref +="&wm="+$("#searchtype").val();//搜索类型
            sHref +="&wm=2";//搜索类型为书名 
            sHref +="&st=0";//排序类型（先只有相关性排序 0）
            sHref +="&tp=2";//搜索数据限制（0/可阅读电子书  1/全部图书  2/不可阅读电子书）
            sHref +="&bd=";//图书id
            sHref +="&pg=1";//关键词搜索结果的第pg页
            sHref +="&ifp=0";//是否只显示图片（在番薯网首页的搜索框用不到   1/是  0/否）
            sHref +="&ath=";//作者（精确搜索使用 暂时没用到）
            sHref +="&pub=";//出版社（精确搜索使用 暂时没用到）
            sHref +="&isbn=";//isbn号（精确搜索使用 暂时没用到）
            sHref +="&pf=10";//搜索结果每页显示的结果个数
            sHref +="&ifr=1";//是否阅读 （没用到）
            sHref +="&nowp=0";//书内阅读时使用，书的某一页
            sHref +="&wf=1";//书的分组（后台传输），书内搜索时使用
            sHref +="&t=1";//模版选择（1/搜索模版  2/书内搜索  3/阅读  4/详情）  
            window.location=sHref;
//    var keyPre = $("#txtKey").val();
//    if (keyPre == "" || keyPre == null || keyPre == defaultkey) {
//        alert("请输入关键词");
//        return false;
//    }
//    window.location = "http://shop.fanshu.com/EbookSearch.aspx?key=" + encodeURIComponent(keyPre) + "&type=" + $("#searchtype").val();
}

function getInitHeight() {
    var img0 = new Image();
     //region 处理版权页问题
    img0.onerror=function(){
        if(initPage<=divNum){
            if(initPage==divNum){
                return;
            }else{
                initPage++;
            }
            img0.src=makeurl(initPage);
            cip=initPage;
            $("#spPN").val(initPage);
        }
    };
    //endregion
   img0.onload = function() {
        if (img0.height > 0) {
            IntIsOk = true;
        }
        $("#hidH").val(img0.height);
        H = img0.height;
        imgH = parseInt(mod * H);
        imgBH = parseInt(modB * H);
        InitReadPage();
        createDivs();
        if (cip > 1) {
            GotoPage(cip);
        }
        getMenuInfo();
    };
    img0.src = makeurl(initPage);
}
/*addBookMark.js*/
getRootParentDom = function() {
    var env = window;
    try {
        while (env.parent != env) {
            env = env.parent;
        }
    }
    catch (e) { }
    return env;
}
SearchEvent = function() {
    if (document.all) {
        return window.event;
    }
    var func = SearchEvent.caller;
    while (func != null) {
        var arg0 = func.arguments[0];
        if (arg0) {
            if (arg0.constructor == Event || arg0.constructor == MouseEvent) {
                return arg0;
            }
        }
        func = func.caller;
    }
    return null;
}
moveToFocus = function(e, elem, top, left) {
    var elemEv = e;
    var top = top ? top : 2;
    var left = left ? left : 2;
    elem.style.top = elemEv.clientY + document.documentElement.scrollTop - top + "px";
}
movetocenter = function(env, obj, top, left) {
    var top = top ? top : 109;
    var left = left ? left : 200;
    obj.style.left = (env.document.documentElement.scrollLeft + env.document.documentElement.clientWidth / 2 - left) + "px";
    obj.style.top = (env.document.documentElement.scrollTop + env.document.documentElement.clientHeight / 2 - top) + "px";
}

//用户点击按钮触发添加书签事件
addbookmark = function() {
    //判断显示状态
    var mataid = $("#hidED").val();
    var page = parseInt($("#spPN").val());

    var popobj = new Apabi.dom.PopMenu();
    $.post("/services/BookMarkService.ashx", { done: "add", metaid: mataid, page: page, type: 0 },
   function(json) {
      switch (parseInt(json.result)) {
           case -1: passport.poplr(addbookmark);break;
           case 0:popobj.showTip("对不起，不能重复添加标签！", 0);break;
           case 1: popobj.showTip("添加成功", 1);break;
       }
   },"json");
}
//自动添加书签事件
addbookmarkOnClose = function() {
    //判断显示状态
    var mataid = $("#hidED").val();
    var page = parseInt($("#spPN").val());
    $.post("/services/BookMarkService.ashx", { done: "add", metaid: mataid, page: page ,type:1},
   function(result) {
   });
}


function show_bottom_scroll_div(evt)
{

    var x=0;
    var e = evt ? evt : (window.event ? window.event : null);
    if(st==1){
        x=e.clientX;
    }else{
        x=e.clientX-225;
    }
    var y=e.clientY-$(window).height()+67;
    if(x>0&&y>0){
         $("#bottom_scroll_div").show();
    }
    else{
         $("#bottom_scroll_div").hide();
    }
}
function set_bottom_scroll_div_top(isBig){
    //    alert("浏览器当前窗口可视区域的高度"+$(window).height());
    //    alert("浏览器当前窗口可视区域文档的高度"+$(document).height());
    //    alert("浏览器当前窗口可视区域文档body的高度"+$(document.body).height());
    //    alert("浏览器当前窗口可视区域文档body的总高度"+$(document.body).outerHeight(true));
    //    
    //    alert("浏览器当前窗口可视区域的宽度"+$(window).width());
    //    alert("浏览器当前窗口可视区域文档的宽度"+$(document).width());
    //    alert("浏览器当前窗口可视区域文档body的宽度"+$(document.body).width());
    //    alert("浏览器当前窗口可视区域文档body的总宽度"+$(document.body).outerWidth(true));alert("浏览器当前窗口可视区域文档body的总高度"+$(document.body).outerHeight(true));
    var t=0;
    var w=0;
    if($(window).height()-67>0){
        t=$(window).height()-67+"px";
     }
     
     if(isBig){
        if($(window).width()-25>0){
             $(".bottom_scroll").css("left","0px");
            w=$(window).width()-25+"px";
        }
     }
     else{
        if($(window).width()-25-225>0){
             $(".bottom_scroll").css("left","225px");
            w=$(window).width()-25-225+"px";
        }
     }
     $(".bottom_scroll").css("width",w);
     $(".bottom_scroll").css("top",t);
}
function ScrollNextScreen(){
    //翻屏时需要去掉头部(23+52)、目录部(26)的高度,由于有可能出现最下面的一行被覆盖一半的情况，所以需要去掉一行字的高度，大概为26(放大为40)
    if(st==1){
//        $("#divSrl").scrollTop($(window).height()-26-40+$("#divSrl").scrollTop());//放大
          ScrollByInterval($(window).height()-26-40+$("#divSrl").scrollTop());
    }else{
//        $("#divSrl").scrollTop($(window).height()-23-52-26-26+$("#divSrl").scrollTop());
          ScrollByInterval($(window).height()-23-52-26-26+$("#divSrl").scrollTop());

    }
    
    
}
//根据指定的时间段进行平滑翻页
var ScrollByInterval=function(divSrlscrollTop){
    $("#divSrl").animate({scrollTop:divSrlscrollTop},100);
}
//对于一些提示框 在出现之后3S后自动消失
var showAndautoClose=function(obj){
     $(obj).css("opacity",1);
     $(obj).show();
     setTimeout(function(){$(obj).animate({opacity:0},1000,function(){$(obj).hide();});},3000); 
    
}
isSpace = function(str){
    var parten = /^\s*$/;
    if(parten.test(str)){
        return true;
    }
    return false;
}
//记录最近浏览记录
recordRecent = function(metaid, cover, name,author, price,type) {
    var tmp;
    var json;
    var myDate = new Date();
    myDate.setFullYear(myDate.getFullYear() + 1);
    //当前阅读的一本书压入cookie

    //历史记录
    if (Apabi.dom.getCookie("recent_fanshu") != null && Apabi.dom.getCookie("recent_fanshu") != "undefined") {
        var value = decodeURIComponent(Apabi.dom.getCookie("recent_fanshu"));
       try{
            json = eval("(" + value + ")");
        }catch(err){
            json = null;
        }
        //判断当请图书是否是记录的图书
        if (json == null || json == undefined || (json.metaid.length == 1 && json.metaid[0].m == metaid)) {
            //Apabi.ById("skim").innerHTML = "暂无浏览记录";
            
        }
        //记录开始
       tmp = "{metaid:[";
        tmp += "{m:'" + encodeURIComponent(metaid) + "'";
        tmp += ",c:'" + encodeURIComponent(cover) + "'";
        tmp += ",n:'" + encodeURIComponent(name) + "'";
        tmp += ",a:'" + encodeURIComponent(author) + "'";
        tmp += ",p:'" + price + "'";
        tmp += ",t:'" + type + "'}";

        if (!(json == null || json == undefined)) {
           for (var i = 0; i < json.metaid.length; i++) {
            if (json.metaid[i].m == metaid) {
                continue;
            }
            if (i == 6) {
                break;
            }
            tmp += ",{m:'" + json.metaid[i].m + "'";
                tmp += ",c:'" + json.metaid[i].c + "'";
                tmp += ",n:'" + json.metaid[i].n + "'";
                tmp += ",a:'" + json.metaid[i].a + "'";
                tmp += ",p:'" + json.metaid[i].p + "'";
                tmp += ",t:'" + json.metaid[i].t + "'}";
          }
            
        }
        tmp += "]}";
    } else {
         tmp = "{metaid:[";
        tmp += "{m:'" + encodeURIComponent(metaid) + "'";
        tmp += ",c:'" + encodeURIComponent(cover) + "'";
        tmp += ",n:'" + encodeURIComponent(name) + "'";
        tmp += ",a:'" + encodeURIComponent(author) + "'";
        tmp += ",p:'" + price + "'";
        tmp += ",t:'" + type + "'}";
        tmp += "]}";
    }
    Apabi.dom.setCookie("recent_fanshu", tmp, myDate, "/", "fanshu.com");
}


//源创

//投票
function castVote(){
    var popobj = new Apabi.dom.PopMenu();
    $.post("/services/VoteService.ashx",{command:"castvote",mid:encodeURIComponent(ed)},function(date){
        if(date!="undefined"||date!=null){
            switch(date.result){
                case 1:
                    $("#voteCount").html(parseInt($("#voteCount").html())+1);
                    $("#popAdd").show();
                    $("#popAdd").animate({opacity:0,"margin-top":"-35px"},1000);
                    break;
                case 0:popobj.showTip("投票失败",1);break;
                case -1:popobj.showTip("您今天已经投过票，明天再来支持吧!",1);break;
                case -2:passport.poplr(castVote);break;
            }
        }
    
    });

}


function buy(obj){
    var metaid=encodeURIComponent(ed);
    var popobj = new Apabi.dom.PopMenu();
    var objArr=$(obj).parent().parent(".txt").children("input[checked=true]");
    if($(objArr).length==0){
        popobj.showTip("请选择章节",0);
        return;
     }
    $.post("/services/AuthorityService.ashx",{command:"getauthority",mid:metaid},function(date){
        if(date!="undefined"||date!=null){
            switch(date.result){
                case 1:  //有权限
                    var oldChapter=date.chapters;
                    var outChapter="";
                     if(oldChapter==""){
                        outChapter="您已经有了整本书的阅读权限";
                        popobj.showTip(outChapter,0);
                    }else{
                        var newChapter="";
                        $(objArr).each(function(i){
                            if(oldChapter.indexOf($(this).attr("name"))==-1){
                                newChapter+=$(this).attr("id")+"-";
                            }else{
                                outChapter+=$(this).nextUntil('lable').html()+"、";
                            }
                        });  
                        if(newChapter!=""){
                            newChapter=newChapter.substring(0,newChapter.length-1);
                        }
                        if(outChapter!=""){
                            outChapter="您已经有了第"+outChapter.substring(0,outChapter.length-1)+"部分的阅读权限";
                            popobj.showTip(outChapter,0);
                        }else{
                            location.href="http://shop.fanshu.com/SerialOrderConfirm.aspx?metaid="+metaid+"&sid="+newChapter;
                        }
                    }
                    break;
                case 0: //无权限
                    var newChapter="";
                     $(objArr).each(function(i){
                        newChapter+=$(this).attr("id")+"-";
                     });  
                    newChapter=newChapter.substring(0,newChapter.length-1);
                     location.href="http://shop.fanshu.com/SerialOrderConfirm.aspx?metaid="+metaid+"&sid="+newChapter;
                     break;
                case -1: //未登录
                    passport.poplr(function(){buy(obj);});break;
            }
        }
    
    });
}


//选择策略
function selectChapters(obj){
    if($(obj).attr("checked")==true){
           $("#serialAllLimit input[type='checkbox']").attr("checked",true);
    }else{
         $("#serialAllLimit input[type='checkbox']").attr("checked",false);
    }    
}

//预定图书
function serialBuyer(){
    var popobj = new Apabi.dom.PopMenu();
    $.getJSON("http://shop.fanshu.com/services/SerialBuyer.ashx?do=book&rType=1&jsoncallback=?",{mid:encodeURIComponent(ed)},function(date){
        switch (date.result){
            case 904: passport.poplr(serialBuyer);break;
            case 911: popobj.showTip("图书已经预订过！",0);break;
            case 909: popobj.showTip("图书不能预订！",-1);break;
            case 900: popobj.showTip("预订成功！<br>将在第一时间给您注册邮箱发送消息",1);break;
        }
    });
    
}

