/// しおりリスト画面 - SCRSLS0100

//名前空間用のオブジェクトを用意する
var BOOKMARK = {};

BOOKMARK.contentTypes = {};
BOOKMARK.contentName = {};
BOOKMARK.pathImgContentNone = './img/page-none.png';

//Contains non-exist content
BOOKMARK.bookmark_errorContent = [];
// Contain contents
BOOKMARK.collection_contents = [];

//ソート条件復帰
BOOKMARK.searchDivision = 1;
BOOKMARK.sortType = 2;
//スクロール復帰
BOOKMARK.scrollTop = 0;

// Init function of page
$(document).ready(function () {

    if (!AVWEB.avwCheckLogin(COMMON.ScreenIds.Login)) return;

    if(ClientData.serviceOpt_encryption() != 'Y') {
   	 COMMON.LockScreen();
    }

    document.title = I18N.i18nText('dspShiori') + ' | ' + I18N.i18nText('sysAppTitle');

    // Set bookmark screen
    ClientData.BookmarkScreen(COMMON.ScreenIds.BookmarkList);

    //Check if Force Change password
    if (ClientData.requirePasswordChange() != 1) {

        // Synchronize bookmarks with server
    	BOOKMARK.SyncContent();

        // Collection all detail of pages
        BOOKMARK.bookmark_collectAllPages();

        $("#dspDelete").click(BOOKMARK.dspDelete_Click);

        $("#dspDelete1").click(BOOKMARK.dspDelete1_Click);
        $("#dspCancel").click(BOOKMARK.dspCancel_Click);
        $("#dspConfirmOK").click(BOOKMARK.dspConfirmOK_Click);

        BOOKMARK.ClearGrid();

        //if (ClientData.BookMarkData().length == 0) {
        if(BOOKMARK.collection_contents.length == 0){
            // Show error
            $("#msgShioriNotExists").show();
            $("#dspDelete").hide();
            $("#dspDelete1").hide();
        }
        else {
            $("#msgShioriNotExists").hide();
            $("#dspDelete").show();
            $("#dspDelete1").show();
        }

        // Show book in local storage
        //BOOKMARK.ShowBookmark();

        $("a[name='dspRead']").unbind('click');
        $("a[name='dspRead']").click(BOOKMARK.dspRead_Click);

        BOOKMARK.HideSorting();

        // Default sort is タイトル名, default is asc
        ClientData.sortOpt_searchDivision(BOOKMARK.searchDivision);
        ClientData.sortOpt_sortType(BOOKMARK.sortType);
        BOOKMARK.dspTitleNm_Click();
    }
    else {
        HEADER.checkForceChangePassword();
    }

    if (COMMON.isAnonymousLogin()) {
        //プッシュメッセージ隠す
        $('#dspPushMessage').hide();
    }

    if((ClientData.serviceOpt_apns() == 'Y') || (ClientData.serviceOpt_usable_push_message() == 'Y')) {
    	$('#dspPushMessage').show();
    }

    //ダイアログ関連
    $("#dspTitleNm").click(BOOKMARK.dspTitleNm_Click);
    $("#dspTitleNmKn").click(BOOKMARK.dspTitleNmKn_Click);
    $("#dspPubDt").click(BOOKMARK.dspPubDt_Click);

    // Check JP language and show title kana
    if (I18N.getCurrentLanguage() != COMMON.Consts.ConstLanguage_Ja) {
        $("#dspTitleNmKn").hide();
        $("#dspTitleNmKn_Seperate").hide();
    }
    else {
        $("#dspTitleNmKn").show();
        $("#dspTitleNmKn_Seperate").show();
    }

    //ビューア、共有表示パーツ読み込み
    $("#viewer").load("./inc_contentview.html?__UPDATEID__", function (myData, myStatus, xhr){
    	//読み込み完了時の処理
    	I18N.i18nReplaceText();
    });

});

BOOKMARK.refreshView = function() {

    // Synchronize bookmarks with server
	BOOKMARK.SyncContent();

    // Collection all detail of pages
    BOOKMARK.bookmark_collectAllPages();

    BOOKMARK.ClearGrid();

    //if (ClientData.BookMarkData().length == 0) {
    if(BOOKMARK.collection_contents.length == 0){
        // Show error
        $("#msgShioriNotExists").show();
        $("#dspDelete").hide();
        $("#dspDelete1").hide();
    }
    else {
        $("#msgShioriNotExists").hide();
        $("#dspDelete").show();
        $("#dspDelete1").show();
    }

    // Default sort is タイトル名, default is asc
    ClientData.sortOpt_searchDivision(BOOKMARK.searchDivision);
    //前と同じ状態にするので逆転させる
    if( BOOKMARK.sortType == 1 ){
    	BOOKMARK.sortType = 2;
    } else {
    	BOOKMARK.sortType = 1;
    }
    ClientData.sortOpt_sortType(BOOKMARK.sortType);

    if( BOOKMARK.searchDivision == 1 ){
        BOOKMARK.dspTitleNm_Click();
    } else if( BOOKMARK.searchDivision == 2 ){
    	BOOKMARK.dspTitleNmKn_Click();
    } else {
    	BOOKMARK.dspPubDt_Click();
    }

};


/*
----------------------------------------------------------------------------
Event groups [start]
----------------------------------------------------------------------------
*/

BOOKMARK.dspTitleNm_Click = function() {

    var isAsc = false;
    if (ClientData.sortOpt_searchDivision() == 1) { // Name
        if (ClientData.sortOpt_sortType() == 1) {   // ASC
            isAsc = false;
        	BOOKMARK.sortType = 2;
        }
        else {
            isAsc = true;
            BOOKMARK.sortType = 1;
        }
    }
    else {
    	BOOKMARK.searchDivision = 1;
    	BOOKMARK.sortType = 1;
        ClientData.sortOpt_searchDivision(1);
        isAsc = true;
    }
    ClientData.sortOpt_sortType(BOOKMARK.sortType);

    BOOKMARK.SortTitleName(isAsc);

    //changeStatusSort(this, isAsc);
    HEADER.setStatusSort('#dspTitleNm', isAsc);

};
BOOKMARK.dspTitleNmKn_Click = function() {
    var isAsc = false;
    if (ClientData.sortOpt_searchDivision() == 2) { // Kana
        if (ClientData.sortOpt_sortType() == 1) {   // ASC
            isAsc = false;
        	BOOKMARK.sortType = 2;
        }
        else {
            isAsc = true;
        	BOOKMARK.sortType = 1;
        }
    }
    else {
    	BOOKMARK.searchDivision = 2;
    	BOOKMARK.sortType = 1;
        ClientData.sortOpt_searchDivision(2); // Kana
        isAsc = true;
    }
    ClientData.sortOpt_sortType(BOOKMARK.sortType);

    BOOKMARK.SortTitleNameKana(isAsc);

    //changeStatusSort(this, isAsc);
    HEADER.setStatusSort('#dspTitleNmKn', isAsc);

};
BOOKMARK.dspPubDt_Click = function() {
    var isAsc = false;
    if (ClientData.sortOpt_searchDivision() == 3) { // Publish date
        if (ClientData.sortOpt_sortType() == 1) {   // ASC
            isAsc = false;
        	BOOKMARK.sortType = 2;
        }
        else {
            isAsc = true;
        	BOOKMARK.sortType = 1;
        }
    }
    else {
    	BOOKMARK.sortType = 1;
        ClientData.sortOpt_searchDivision(3); // Kana
        isAsc = true;
    }
    ClientData.sortOpt_sortType(BOOKMARK.sortType);

    BOOKMARK.SortPubDate(isAsc);

    //changeStatusSort(this, isAsc);
    HEADER.setStatusSort('#dspPubDt', isAsc);
};

// Event of each button [読む]
BOOKMARK.dspRead_Click = function() {
    var jsondata = $(this).attr("value");
    var data = JSON.parse(jsondata);

    LIMIT_ACCESS_CONTENT.checkLimitContent(
        data.contentid,
        function (){
        	BOOKMARK.dspRead_Click_callback(data);
        },
        function(){
        }
    );
};
//
BOOKMARK.dspRead_Click_callback = function(data) {

    ClientData.contentInfo_contentId(data.contentid);
    ClientData.bookmark_pageNo(data.pageNo);
    ClientData.contentInfo_contentType(data.contentType);
    ClientData.IsRefresh(false);
    //AVWEB.avwScreenMove(COMMON.ScreenIds.ContentView);

    //表示
    BOOKMARK.showContentView();

};

// Cancel dialog of deleting
BOOKMARK.dspCancel_Click = function() {
    // Close dialog
    //$('#dlgConfirm').dialog('close');
    $("#delete_shiori").hide();
    COMMON.unlockLayout();
};
// Process deleting
BOOKMARK.dspConfirmOK_Click = function() {
    // --------------------------------
    // Process deleting [start]
    // --------------------------------

    // Get selected bookmarks
    var arrSelectedBookmarks = $("input[name='chkDelete']:checked");
    $.each(arrSelectedBookmarks, function () {
        // Delete selected items on layout

        var contentid = JSON.parse(this.value).contentid;
        var pageNo = JSON.parse(this.value).pageNo;

        $(this).parent().parent().parent().remove();

        // Remove from ClientData
        var bm = ClientData.BookMarkData();

        for (var nIndex = bm.length - 1; nIndex >= 0; nIndex--) {
            if (bm[nIndex].contentid == contentid && bm[nIndex].pageNo == pageNo) {
                bm.splice(nIndex, 1);
                ClientData.isChangedBookmark(true);
            }
        }
        ClientData.BookMarkData(bm);

        if (ClientData.BookMarkData().length == 0) {
            // Show error
            $("#msgShioriNotExists").show();
            $("#dspDelete").hide();
            $("#dspDelete1").hide();
        }
    });

    // --------------------------------
    // Process deleting [ end ]
    // --------------------------------

    $("#delete_shiori").hide();
    COMMON.unlockLayout();
};

BOOKMARK.dspDelete1_Click = function() {
	BOOKMARK.dspDelete_Click();
};

BOOKMARK.dspDelete_Click = function() {
    if ($("input[name='chkDelete']:checked").length > 0) {
    	COMMON.lockLayout();
    	$("#delete_shiori").show();
    	$("#delete_shiori").center();
    }
};

// Show detail content
BOOKMARK.ShowBookmark = function(showList) {
    if (AVWEB.avwHasError()) {
        return;
    }
    else {
        var hasMemo = false;
        var hasMarking = false;
        var contentid = "";
        var pageNo = 0;

        if (showList.length > 0) {
            $("#dspDelete").show();
            $("#dspDelete1").show();
        }
        //TotalThread = ClientData.BookMarkData().length;
        for (var nIndex = showList.length - 1; nIndex >= 0; nIndex--) {
            hasMarking = false;
            hasMemo = false;

            contentid = showList[nIndex].contentid;
            pageNo = showList[nIndex].pageNo;

            // Check if contentid has marking
            for (var nIndex1 = 0; nIndex1 < ClientData.MarkingData().length; nIndex1++) {

                if (ClientData.MarkingData()[nIndex1].contentid == contentid
               && ClientData.MarkingData()[nIndex1].pageNo == pageNo) {
                    hasMarking = true;
                }
            }

            // Check if contentid has memo
            for (var nIndex1 = 0; nIndex1 < ClientData.MemoData().length; nIndex1++) {

                if (ClientData.MemoData()[nIndex1].contentid == contentid
               && ClientData.MemoData()[nIndex1].pageNo == pageNo) {
                    hasMemo = true;
                }
            }

            var pageDetail;
            var contentTitle = "";
            var contentTitleKana = "";
            var contentType = "";
            // Search current page if collection that get details before
            for (var nIndex2 = 0; nIndex2 < BOOKMARK.collection_contents.length; nIndex2++) {
                if (BOOKMARK.collection_contents[nIndex2].contentid == contentid) {
                    contentTitle = BOOKMARK.collection_contents[nIndex2].contentTitle;
                    contentTitleKana = BOOKMARK.collection_contents[nIndex2].contentTitleKana;
                    contentType = BOOKMARK.collection_contents[nIndex2].contentType;

                    // Search in pages
                    for (var nIndex3 = 0; nIndex3 < BOOKMARK.collection_contents[nIndex2].pages.length; nIndex3++) {
                        if (pageNo == BOOKMARK.collection_contents[nIndex2].pages[nIndex3].pageNo) {
                            pageDetail = BOOKMARK.collection_contents[nIndex2].pages[nIndex3];
                            if(contentType != COMMON.ContentTypeKeys.Type_PDF){
                                pageDetail.pageText = "";
                            }
                            break;
                        }
                    }

                }
            }
            if (pageDetail) {
                // If bookmark does not exist
                if (pageDetail.existed == true) {
                    // Show normal
                	BOOKMARK.UpdateBookmark(contentid, pageDetail.pageNo, contentTitle, contentTitleKana);

                    var pageThumbnail = (pageDetail.pageThumbnail != BOOKMARK.pathImgContentNone) ? ("data:image/jpeg;base64," + pageDetail.pageThumbnail) : BOOKMARK.pathImgContentNone;

                    BOOKMARK.insertRow(contentid, pageThumbnail, COMMON.htmlEncode(contentTitle),
                        pageDetail.pageText, pageDetail.pageNo, hasMemo, hasMarking, nIndex, contentType);
                }
                else {
                    // Not existed -> Show error
                	BOOKMARK.insertRowError(contentid, COMMON.htmlEncode(contentTitle), pageDetail.pageNo);
                }
            }

        }
        $("a[name='dspRead']").unbind('click');
        $("a[name='dspRead']").click(BOOKMARK.dspRead_Click);
    }
};
// Hide all sorting symbol
BOOKMARK.HideSorting = function() {
    $('#menu_sort li a').removeClass('ascending_sort').removeClass('descending_sort');
};
// Sort by title name
BOOKMARK.SortTitleName = function(isAsc) {

    HEADER.setStatusSort('#dspTitleNm', isAsc);

    var arrSource = ClientData.BookMarkData();
    var arrTarget = [];
    var arrShowList = [];
    var strTemp = "";
    var nTempIndex = 0;
    var isStop = false;
    while (!isStop) {
        if (arrSource.length > 0) {
            strTemp = "";
            // Lookup min item
            for (var nIndex = 0; nIndex < arrSource.length; nIndex++) {
                if (strTemp == "") {
                    strTemp = arrSource[nIndex].contentTitle;
                    nTempIndex = nIndex;
                }
                else {
                    // ASC
                    if (isAsc) {
                        if (arrSource[nIndex].contentTitle < strTemp) {
                            strTemp = arrSource[nIndex].contentTitle;
                            nTempIndex = nIndex;
                        }
                    }
                    else {
                        if (arrSource[nIndex].contentTitle > strTemp) {
                            strTemp = arrSource[nIndex].contentTitle;
                            nTempIndex = nIndex;
                        }
                    }
                }
            }
            // Add to target array
            arrTarget.push(arrSource[nTempIndex]);

            //表示対象なら表示用リストにプッシュ
            for (var nIndex2 = 0; nIndex2 < BOOKMARK.collection_contents.length; nIndex2++) {
                if (BOOKMARK.collection_contents[nIndex2].contentid == arrSource[nTempIndex].contentid) {
                    arrShowList.push(arrSource[nTempIndex]);
                    break;
                }
            }

            // Remove min item from source array
            arrSource.splice(nTempIndex, 1);
        }
        else {
            isStop = true;
        }
    }
    BOOKMARK.ClearGrid();
    ClientData.BookMarkData(arrTarget);
    BOOKMARK.ShowBookmark(arrShowList);
};
// Clear all rows of grid
BOOKMARK.ClearGrid = function() {

    var arrSelectedBookmarks = $("input[name='chkDelete']");
    $.each(arrSelectedBookmarks, function () {
        $(this).parent().parent().parent().remove();
    });

};
// Sort by title name kana
BOOKMARK.SortTitleNameKana = function(isAsc) {

    HEADER.setStatusSort('#dspTitleNmKn', isAsc);

    var arrSource = ClientData.BookMarkData();
    var arrTarget = [];
    var arrShowList = [];
    var strTemp = "";
    var nTempIndex = 0;
    var isStop = false;
    while (!isStop) {
        if (arrSource.length > 0) {
            strTemp = "";
            // Lookup min item
            for (var nIndex = 0; nIndex < arrSource.length; nIndex++) {
                if (strTemp == "") {
                    strTemp = arrSource[nIndex].contentTitleKana;
                    nTempIndex = nIndex;
                }
                else {
                    // ASC
                    if (isAsc) {
                        if (arrSource[nIndex].contentTitleKana < strTemp) {
                            strTemp = arrSource[nIndex].contentTitleKana;
                            nTempIndex = nIndex;
                        }
                    }
                    else {
                        if (arrSource[nIndex].contentTitleKana > strTemp) {
                            strTemp = arrSource[nIndex].contentTitleKana;
                            nTempIndex = nIndex;
                        }
                    }
                }
            }
            // Add to target array
            arrTarget.push(arrSource[nTempIndex]);

            //表示対象なら表示用リストにプッシュ
            for (var nIndex2 = 0; nIndex2 < BOOKMARK.collection_contents.length; nIndex2++) {
                if (BOOKMARK.collection_contents[nIndex2].contentid == arrSource[nTempIndex].contentid) {
                    arrShowList.push(arrSource[nTempIndex]);
                    break;
                }
            }

            // Remove min item from source array
            arrSource.splice(nTempIndex, 1);
        }
        else {
            isStop = true;
        }
    }
    BOOKMARK.ClearGrid();
    ClientData.BookMarkData(arrTarget);
    BOOKMARK.ShowBookmark(arrShowList);
};
// Sort by publish date
BOOKMARK.SortPubDate = function(isAsc) {

    HEADER.setStatusSort('#dspPubDt', isAsc);

    var arrSource = ClientData.BookMarkData();
    var arrTarget = [];
    var arrShowList = [];
    var dateTemp = undefined;
    var nTempIndex = 0;
    var isStop = false;
    while (!isStop) {
        if (arrSource.length > 0) {
            dateTemp = undefined;
            // Lookup min item
            for (var nIndex = 0; nIndex < arrSource.length; nIndex++) {
                if (dateTemp == undefined) {
                    dateTemp = arrSource[nIndex].registerDate;
                    nTempIndex = nIndex;
                }
                else {
                    // ASC
                    if (isAsc) {
                        if (arrSource[nIndex].registerDate < dateTemp) {
                            dateTemp = arrSource[nIndex].registerDate;
                            nTempIndex = nIndex;
                        }
                    }
                    else {
                        if (arrSource[nIndex].registerDate > dateTemp) {
                            dateTemp = arrSource[nIndex].registerDate;
                            nTempIndex = nIndex;
                        }
                    }
                }
            }
            // Add to target array
            arrTarget.push(arrSource[nTempIndex]);

            //表示対象なら表示用リストにプッシュ
            for (var nIndex2 = 0; nIndex2 < BOOKMARK.collection_contents.length; nIndex2++) {
                if (BOOKMARK.collection_contents[nIndex2].contentid == arrSource[nTempIndex].contentid) {
                    arrShowList.push(arrSource[nTempIndex]);
                    break;
                }
            }

            // Remove min item from source array
            arrSource.splice(nTempIndex, 1);
        }
        else {
            isStop = true;
        }
    }
    BOOKMARK.ClearGrid();
    ClientData.BookMarkData(arrTarget);
    BOOKMARK.ShowBookmark(arrShowList);
};
/*
Update information of specified bookmark
*/
BOOKMARK.UpdateBookmark = function(contentid, pageNo, contentTitle, contentTitleKana) {
    var arrBookmarks = ClientData.BookMarkData();

    for (var nIndex = 0; nIndex < arrBookmarks.length; nIndex++) {
        if (contentid == arrBookmarks[nIndex].contentid && pageNo == arrBookmarks[nIndex].pageNo) {
            if (contentTitle != null && contentTitle != undefined) {
                arrBookmarks[nIndex].contentTitle = contentTitle;
            }
            if (contentTitleKana != null && contentTitleKana != undefined) {
                arrBookmarks[nIndex].contentTitleKana = contentTitleKana;
            }
            break;
        }
    }
    // Set bookmark back to client data
    ClientData.BookMarkData(arrBookmarks);
};


/*
 Insert error row
*/
BOOKMARK.insertRowError = function(contentid, pageTitle, pageNo) {

    var newRow = "";

    newRow += "<section class='sectionBookmark'>";
    newRow += "     <div class='cnt_section'>";

    newRow += '<span class="check">';
    newRow += "<input type='checkbox' name='chkDelete' value='{\"contentid\":" + contentid + ", \"pageNo\":" + pageNo +"}' />";
    newRow += '</span>';

    newRow += "     <div class='text'>";
    newRow += '         <label class="name">' + COMMON.truncate(pageTitle, 20) + '</label>';
    newRow += '         <div class="info">';
    newRow += "                 <label class='lang name' lang='msgShioriDeleted'>" + I18N.i18nText('msgShioriDeleted') + "</label>";

    newRow += "         </div>";
    newRow += "     </div>";

    newRow += "</section>";
    $('#pnlTop').after(newRow);
};

// Insert row to grid
BOOKMARK.insertRow = function(contentid, pageThumbnail, pageTitle, pageText, pageNo, hasMemo, hasMarking, index, contentType) {
    var imgMarkingHide = '<img style="visibility:hidden" class="pen" alt="" src="./img/list/icon_pen.png" />';
    var imgMemoHide = '<img style="visibility:hidden" class="sticker" alt="" src="./img/list/icon_sticker.png" />';
    var imgMarking = '<img class="pen" alt="" src="./img/list/icon_pen.png" />';
    var imgMemo = '<img class="sticker" alt="" src="./img/list/icon_sticker.png" />';
    var newRow = "";

    newRow += "<section class='sectionBookmark'>";

    newRow +='<div class="cnt_section">';
    newRow +='<span class="check">';
    newRow += "<input type='checkbox' name='chkDelete' value='{\"contentid\":" + contentid + ", \"pageNo\":" + pageNo + ", \"index\": " + index + "}'/>";
    newRow +='</span>';
    newRow +='<a class="img" href="#">';
    newRow +='<img id="pageImg' + contentid + '" src="' + pageThumbnail + '" width="160" height="120" style="display:none;">';
    newRow +='<img id="loadingIcon' + contentid + "_" + pageNo + '" src="./img/data_loading.gif" height="25px" width="25px" style="padding: 46px; "/>';
    newRow +='</a>';

    newRow +='<div class="text">';
    newRow += '<a class="name" href="#">' +'<div class ="pageTitle" >'+ pageTitle +'</div>'+ '</a>';

    newRow +='<div class="info">';
    newRow += '<ul class="date">';

    var contentText = COMMON.htmlEncode(COMMON.getLines(pageText, 3));

    newRow += '<li><label id="Label1">' + COMMON.truncate(contentText, 60) + '</label></li>';

    newRow +='</ul>';
    newRow += '<ul class="pic">';


    //Resize Image
    var imgTemp = new Image();

    imgTemp.onload = function () {

        if (imgTemp.width > imgTemp.height) {

            $("img#pageImg" + contentid).attr('height', '');
            $("img#pageImg" + contentid).removeAttr('height');
            $("img#pageImg" + contentid).attr('width', '120');
            var realHeight = (120 * imgTemp.height) / imgTemp.width;
            $("img#pageImg" + contentid).css('padding-top', (120 - realHeight) / 2 + 'px');
        }
        else {
            $("img#pageImg" + contentid).attr('width', '');
            $("img#pageImg" + contentid).removeAttr('width');
            $("img#pageImg" + contentid).attr('height', '120');
            $("img#pageImg" + contentid).css('padding-top', '0px');
        }

        $("#loadingIcon" + contentid + "_" + pageNo).fadeOut('slow', function () {
            $("img#pageImg" + contentid).fadeIn('slow');
        });
    };

    imgTemp.src = pageThumbnail;

    if (hasMemo) {
        newRow += '<li><a href="javascript:void(0);" style="cursor: default;">' + imgMemo + '</a></li>';
    }
    else {
        newRow += '<li><a href="javascript:void(0);" style="cursor: default;">' + imgMemoHide + '</a></li>';
    }

    if (hasMarking) {
        newRow += '<li><a href="javascript:void(0);" style="cursor: default;">' + imgMarking + '</a></li>';
    }
    else {
        newRow += '<li><a href="javascript:void(0);" style="cursor: default;">' + imgMarkingHide + '</a></li>';
    }


    newRow += '<li class="pageno"><label id="Label2" class="lang" lang="txtPage">' + I18N.i18nText('txtPage') + '</label><label id="Label3">' + pageNo + '</label></li>';

    newRow +='<li>';
    newRow += "<a class='read read_open lang' name='dspRead' value='{\"contentid\":\"" + contentid + "\", \"pageNo\":\"" + pageNo + "\", \"contentType\":\"" + contentType + "\" }' lang='txtRead'>" + I18N.i18nText('txtRead') + "</a>";
    newRow +='</li>';

    newRow +='</ul>';
    newRow +='</div>';
    newRow +='</div>';
    newRow +='</div>';

    newRow += "</section>";

    $('#pnlTop').after(newRow);
};


/*
----------------------------------------------------------------------------
Event groups [ end ]
----------------------------------------------------------------------------
*/

/*
    Get all detail pages of content in bookmark
*/
BOOKMARK.bookmark_collectAllPages = function() {
    var arrBookMarks = ClientData.BookMarkData();
    for (var nIndex = 0; nIndex < BOOKMARK.collection_contents.length; nIndex++) {

        var contentid = BOOKMARK.collection_contents[nIndex].contentid;
        var pages = [];

        // Collect all pages of current content
        for (var nIndex1 = 0; nIndex1 < arrBookMarks.length; nIndex1++) {
            // Found content
            if (arrBookMarks[nIndex1].contentid == contentid) {
                pages.push({ pageNo: arrBookMarks[nIndex1].pageNo, pageText: "", pageThumbnail: "", existed: false });
            }
        }
        // Add collected pages to content
        BOOKMARK.collection_contents[nIndex].pages = pages;

        // Join pages to request to server
        var strPageNos = BOOKMARK.buildPageNos(BOOKMARK.collection_contents[nIndex].pages);

            // Call api to get all details of pages 1 time
        AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webContentPage", "GET",
                    { contentId: contentid, sid: ClientData.userInfo_sid(), pageNos: strPageNos, thumbnailFlg: 1 },
                    function (data) {

                    	BOOKMARK.collection_contents[nIndex].contentTitle = data.contentTitle;
                    	BOOKMARK.collection_contents[nIndex].contentTitleKana = data.contentTitleKana;
                        for (var nIndex2 = 0; nIndex2 < BOOKMARK.collection_contents[nIndex].pages.length; nIndex2++) {

                            var comparePageNo = BOOKMARK.collection_contents[nIndex].pages[nIndex2].pageNo;

                            for (var nIndex3 = 0; nIndex3 < data.pages.length; nIndex3++) {
                                if (data.pages[nIndex2] && comparePageNo == data.pages[nIndex2].pageNo) {
                                    // Set flag to determine page existed
                                	BOOKMARK.collection_contents[nIndex].pages[nIndex2].existed = true;
                                    // Store detail of page
                                	BOOKMARK.collection_contents[nIndex].pages[nIndex2].pageText = data.pages[nIndex2].pageText;
                                	BOOKMARK.collection_contents[nIndex].pages[nIndex2].pageThumbnail = data.pages[nIndex2].pageThumbnail;
                                }
                                else if (BOOKMARK.contentTypes[contentid] == "none" && data.pages.length > 0) {
                                	BOOKMARK.collection_contents[nIndex].pages[nIndex2].existed = true;
                                    // Store detail of page
                                	BOOKMARK.collection_contents[nIndex].pages[nIndex2].pageText = ''; //data.pages[0].pageText;
                                	BOOKMARK.collection_contents[nIndex].pages[nIndex2].pageThumbnail = BOOKMARK.pathImgContentNone; //data.pages[nIndex2].pageThumbnail;
                                }
                            }

                        }
                    },
                    function () { // when server response error

                        if (BOOKMARK.contentTypes[contentid] == "none") {
                        	BOOKMARK.collection_contents[nIndex].contentTitle = BOOKMARK.contentName[contentid];
                            for (var nIndex2 = 0; nIndex2 < BOOKMARK.collection_contents[nIndex].pages.length; nIndex2++) {
                            	BOOKMARK.collection_contents[nIndex].pages[nIndex2].existed = true;
                            	BOOKMARK.collection_contents[nIndex].pages[nIndex2].pageThumbnail = BOOKMARK.pathImgContentNone;
                            	BOOKMARK.collection_contents[nIndex].pages[nIndex2].pageText = '';

                            }
                        }
                    }
        );

    }
};
/*
    Build pageNos
*/
BOOKMARK.buildPageNos = function(pages) {
    var strResult = "";
    for (var nIndex = 0; nIndex < pages.length; nIndex++) {
        if (strResult == "") {
            strResult = "" + pages[nIndex].pageNo;
        }
        else {
            strResult += "," + pages[nIndex].pageNo;
        }
    }
    return strResult;
};

/*
Check a content is error or not
*/
BOOKMARK.IsErrorContent = function(strContentId) {
    var isError = false;

    for (var nIndex = 0; nIndex < BOOKMARK.bookmark_errorContent.length; nIndex++) {
        if (strContentId == BOOKMARK.bookmark_errorContent[nIndex].contentid) {
            isError = true;
            break;
        }
    }
    return isError;
};

/*
Check a content is checked + ok
*/
BOOKMARK.IsOKCheckedContent = function(strContentId) {
    var isOK = false;

    for (var nIndex = 0; nIndex < BOOKMARK.collection_contents.length; nIndex++) {
        if (strContentId == BOOKMARK.collection_contents[nIndex].contentid) {
            isOK = true;
            break;
        }
    }
    return isOK;
};

// Add OK checked content
BOOKMARK.AddContent = function(strContentId, contentType) {
    var isFound = false;
    for (var nIndex = 0; nIndex < BOOKMARK.collection_contents.length; nIndex++) {
        if (BOOKMARK.collection_contents[nIndex].contentid == strContentId) {
            isFound = true;
            break;
        }
    }
    // Add to bufer if it does not exist
    if(!isFound) {
    	BOOKMARK.collection_contents.push({ 'contentid': strContentId, 'contentType': contentType,  'contentTitle': "", 'contentTitleKana': "", 'pages': [] });
    }
};

/*
  event of changing language
*/
function changeLanguageCallBackFunction() {
    if (I18N.getCurrentLanguage() != COMMON.Consts.ConstLanguage_Ja) {
        $("#dspTitleNmKn").hide();
        $("#dspTitleNmKn_Seperate").hide();
        $("#txtTitleNmKnAsc").hide();
        $("#txtTitleNmKnDesc").hide();
    }
    else {
        $("#dspTitleNmKn").show();
        $("#dspTitleNmKn_Seperate").show();
        if (ClientData.sortOpt_searchDivision() == 2) { // Kana
            HEADER.setStatusSort('#dspTitleNmKn', orderSort == COMMON.Consts.ConstOrderSetting_Asc);
        }
    }
    document.title = I18N.i18nText('dspShiori') + ' | ' + I18N.i18nText('sysAppTitle');
};
/*
Synchronize bookmark with server
. Check existence of content
-> Delete absence content in local

. Check existence of pages
-> Delete absence pages in local
*/
BOOKMARK.SyncContent = function() {

    // Reset error contents
	BOOKMARK.bookmark_errorContent = [];

    // Reset ok checked content
	BOOKMARK.collection_contents = [];

    // Get bookmarks from local storage
    var arrBookmarks = ClientData.BookMarkData();

    for (var nIndex = arrBookmarks.length - 1; nIndex >= 0; nIndex--) {

        var oneBookMark = arrBookmarks[nIndex];
        // ==================================
        // Check existence of content [start]
        // ==================================
        if (BOOKMARK.IsErrorContent(oneBookMark.contentid) == false) {
            // If content is ok + checked
            if (BOOKMARK.IsOKCheckedContent(oneBookMark.contentid) == false) {
                if (!BOOKMARK.IsExistContent(oneBookMark.contentid)["isExisted"]) {
                    if (AVWEB.avwHasError()) {
                        // System error excepting 404
                    	AVWEB.showSystemError();
                        return;
                    }
                    else {
                        // Add to list of error content
                    	BOOKMARK.bookmark_errorContent.push({ contentid: oneBookMark.contentid });
                        // Remove bookmark
                        arrBookmarks.splice(nIndex, 1);
                        ClientData.isChangedBookmark(true);
                    }
                }
                // ==================================
                // Check existence of content [ end ]
                // ==================================
                else {
                    // Add nromal content
                	BOOKMARK.AddContent(oneBookMark.contentid, BOOKMARK.IsExistContent(oneBookMark.contentid)["contentType"]);
                }
            }
        }
        else {
            arrBookmarks.splice(nIndex, 1);
            ClientData.isChangedBookmark(true);
        }
    }

    // Set back to storage
    ClientData.BookMarkData(arrBookmarks);

};

/*
Check content whether existed or not
*/
BOOKMARK.IsExistContent = function(strContentId) {
    var isExisted = false;
    var contentType = '';
    var result = [];
    var params = {
        sid: ClientData.userInfo_sid(),
        getType: '1',
        contentId: strContentId
    };

    result["isExisted"] = isExisted;
    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", 'GET', params,
                function (data) {
                    isExisted = true;
                    contentType = data.contentData.contentType;

                    result["isExisted"] = isExisted;
                    result["contentType"] = contentType;

                    // save content type
                    BOOKMARK.contentTypes[strContentId] = contentType;
                    BOOKMARK.contentName[strContentId] = data.contentData.contentName;
                    // save alert message level
                    LIMIT_ACCESS_CONTENT.messageLevel[strContentId] = { alertMessageLevel: data.contentData.alertMessageLevel, alertMessage: data.contentData.alertMessage };

                },
                function (xmlHttpRequest, txtStatus, errorThrown) {
                    if (xmlHttpRequest.status == 404) {
                        isExisted = false;
                    }
                    else {
                        // Show system error
                        isExisted = true;  // Mark this flag to prevent bookmarks from deleting
                        AVWEB.showSystemError();
                    }
                });

    return result;
};


/*
----------------------------------------------------------------------------
Setting dialog [ end ]
----------------------------------------------------------------------------
*/

BOOKMARK.showContentView = function(){

	//TOPに戻す
	var y = 0;
	if( document.documentElement.scrollTop ){
		y = document.documentElement.scrollTop;
	}
	if( document.body.scrollTop ){
		if( y == undefined || y == 0){
			y = document.body.scrollTop;
		}
	}
	if( y == undefined || y == null){
		y = 0;
	}
	BOOKMARK.scrollTop = y;
	window.scrollTo(0,0);

	//試験
    $("#header-ws").hide();
    $("#ws-body").hide();
    $("#topcontrol").hide();

    CONTENTVIEW_INITOBJECT.clearViewerComponent();
    CONTENTVIEW.cssInit();
    $("#viewer").show();

	CONTENTVIEW.ready();

};

BOOKMARK.cssInit = function(){
	$('html').css({
		'overflow-y':'scroll'
		});
	$('html,body').css({
		'height':'100%',
		'margin': '0',
		'padding': '0'
		});
	$('html>body').css({
		'font-size':'16px',
		'font-size':'68.75%'
		});
	$('body').css({
		'font-family':'Verdana, helvetica, arial, sans-serif',
		'font-size':'68.75%',
		'background':'#fff',
		'color':'#333'
		});
};

BOOKMARK.downloadFunction = function(e) {
    if (e) {
        e.preventDefault();
    }

    var contentId = $(this).attr('contentid');
    //Download content
    HEADER.downloadResourceById(contentId);

};


