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

/// <reference path="../common/js/avweb.js" />

/// <reference path="../common/js/screenLock.js" />

/// <reference path="../common/js/common.js" />

/// <reference path="../common/js/i18n.js" />

/// <reference path="../common/js/jquery-1.8.1.min.js" />

/// <reference path="../common/js/jquery-ui-1.8.23.custom.min.js" />

/// <reference path="../common/js/jquery.toastmessage.js" />

/// <reference path="../common/js/pageViewer.js" />

/// <reference path="init.js" />

//var TotalThread = 0;

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

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

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

    LockScreen();



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

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

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

        // Synchronize bookmarks with server
        SyncContent();

        // Collection all detail of pages
        bookmark_collectAllPages();

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

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

        ClearGrid();

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

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

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

        HideSorting();

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

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

// update status sort
//function changeStatusSort(obj, isAsc) {
//    $('#sortingDiv .sort li a').removeClass().addClass('lang');
//    $('#sortingDiv .sort li').removeClass('current');
//    $(obj).addClass(isAsc ? 'ascending_sort' : 'descending_sort').parent().addClass("current");
//};

function dspTitleNm_Click() {
    
    var isAsc = false;
    if (ClientData.sortOpt_searchDivision() == 1) { // Name
        if (ClientData.sortOpt_sortType() == 1) {   // ASC
            isAsc = false;
            ClientData.sortOpt_sortType(2);
        }
        else {
            isAsc = true;
            ClientData.sortOpt_sortType(1);
        }
    }
    else {
        ClientData.sortOpt_searchDivision(1);
        ClientData.sortOpt_sortType(1); // default is asc
        isAsc = true;
    }
    
    SortTitleName(isAsc);
//    $("#dspTitleNm").addClass("active_tops");        
//    $("#dspTitleNmKn").removeClass("active_tops");
//    $("#dspPubDt").removeClass("active_tops");

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

};
function dspTitleNmKn_Click() {
    var isAsc = false;
    if (ClientData.sortOpt_searchDivision() == 2) { // Kana
        if (ClientData.sortOpt_sortType() == 1) {   // ASC
            isAsc = false;
            ClientData.sortOpt_sortType(2);
        }
        else {
            isAsc = true;
            ClientData.sortOpt_sortType(1);
        }
    }
    else {
        ClientData.sortOpt_searchDivision(2); // Kana
        ClientData.sortOpt_sortType(1); // default is asc
        isAsc = true;
    }

    SortTitleNameKana(isAsc);

//    $("#dspTitleNm").removeClass("active_tops");        
//    $("#dspTitleNmKn").addClass("active_tops");    
    //    $("#dspPubDt").removeClass("active_tops");

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

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

    SortPubDate(isAsc);

//    $("#dspTitleNm").removeClass("active_tops");        
//    $("#dspTitleNmKn").removeClass("active_tops");    
    //    $("#dspPubDt").addClass("active_tops");

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

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

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

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


// Cancel dialog of deleting
function dspCancel_Click() {
    // Close dialog
    //$('#dlgConfirm').dialog('close');
    $("#delete_shiori").hide();
    unlockLayout();
};
// Process deleting
function dspConfirmOK_Click() {
    // --------------------------------
    // 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();
    unlockLayout();
};

function dspDelete1_Click() {
    dspDelete_Click();
};

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

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

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

            contentid = ClientData.BookMarkData()[nIndex].contentid;
            pageNo = ClientData.BookMarkData()[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 < collection_contents.length; nIndex2++) {
                if (collection_contents[nIndex2].contentid == contentid) {
                    contentTitle = collection_contents[nIndex2].contentTitle;
                    contentTitleKana = collection_contents[nIndex2].contentTitleKana;
                    contentType = collection_contents[nIndex2].contentType;
                    
                    // Search in pages
                    for (var nIndex3 = 0; nIndex3 < collection_contents[nIndex2].pages.length; nIndex3++) {
                        if (pageNo == collection_contents[nIndex2].pages[nIndex3].pageNo) {
                            pageDetail = collection_contents[nIndex2].pages[nIndex3];
                            break;
                        }
                    }
                }
            }            
            if (pageDetail) {
                // If bookmark does not exist
                if (pageDetail.existed == true) {
                    // Show normal
                    UpdateBookmark(contentid, pageDetail.pageNo, contentTitle, contentTitleKana);

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

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

        }
        $("a[name='dspRead']").unbind('click');
        $("a[name='dspRead']").click(dspRead_Click);
    }
};
// Hide all sorting symbol
function HideSorting() {
//    $("#txtTitleNmAsc").hide();
//    $("#txtTitleNmDesc").hide();
//    $("#txtTitleNmKnAsc").hide();
//    $("#txtTitleNmKnDesc").hide();
//    $("#txtPubDtAsc").hide();
    //    $("#txtPubDtDesc").hide();

    $('#menu_sort li a').removeClass('ascending_sort').removeClass('descending_sort');

};
// Sort by title name
function SortTitleName(isAsc) {
//    HideSorting();
//    
//    if (isAsc) {
//        $("#txtTitleNmAsc").show();        
//    }
//    else {
//        $("#txtTitleNmDesc").show();
//    }

    setStatusSort('#dspTitleNm', isAsc);

    var arrSource = ClientData.BookMarkData();
    var arrTarget = [];
    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]);
            // Remove min item from source array
            arrSource.splice(nTempIndex, 1);
        }
        else {
            isStop = true;
        }
    }
    ClearGrid();
    ClientData.BookMarkData(arrTarget);
    ShowBookmark();
};
// Clear all rows of grid
function ClearGrid() {

    var arrSelectedBookmarks = $("input[name='chkDelete']");
    $.each(arrSelectedBookmarks, function () {
        $(this).parent().parent().parent().remove();
    });
    
    //if (TotalThread == 0) {
        //$('#grid tr').remove();
    //}
    
    // var arrSelectedBookmarks = $("input[name='chkDelete']");

    
};
// Sort by title name kana
function SortTitleNameKana(isAsc) {
//    HideSorting();

//    if (isAsc) {
//        $("#txtTitleNmKnAsc").show();               
//    }
//    else {
//        $("#txtTitleNmKnDesc").show();        
    //    }

    setStatusSort('#dspTitleNmKn', isAsc);

    var arrSource = ClientData.BookMarkData();
    var arrTarget = [];
    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]);
            // Remove min item from source array
            arrSource.splice(nTempIndex, 1);
        }
        else {
            isStop = true;
        }
    }
    ClearGrid();
    ClientData.BookMarkData(arrTarget);
    ShowBookmark();
};
// Sort by publish date
function SortPubDate(isAsc) {
//    HideSorting();

//    if (isAsc) {
//        $("#txtPubDtAsc").show();
//    }
//    else {
//        $("#txtPubDtDesc").show();
//    }

    setStatusSort('#dspPubDt', isAsc);

    var arrSource = ClientData.BookMarkData();
    var arrTarget = [];
    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]);
            // Remove min item from source array
            arrSource.splice(nTempIndex, 1);
        }
        else {
            isStop = true;
        }
    }
    ClearGrid();
    ClientData.BookMarkData(arrTarget);
    ShowBookmark();
};
/*
Update information of specified bookmark
*/
function UpdateBookmark(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
*/
function insertRowError(contentid, pageTitle, pageNo) {

    var newRow = "";

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

    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">' + truncate(pageTitle, 20) + '</label>';
    newRow += '         <div class="info">';
    newRow += "                 <label class='lang name' lang='msgShioriDeleted'>" + i18nText('msgShioriDeleted') + "</label>";
    
    newRow += "         </div>";
    newRow += "     </div>";
    
    newRow += "</section>";
    $('#pnlTop').after(newRow);
};

// Insert row to grid       
function insertRow(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'>";
    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 += '<label id="Label1" class="name" style="color: #2D83DA;">' + truncate(pageTitle, 20) + '</label>';
    newRow += '<a class="name" href="#" id="Label1">' + truncate(pageTitle, 20) + '</a>'; //<img src="img/bookshelf/icon_01.jpg" width="20" height="20" class="listIcon">

    newRow += '<div class="info">';
    newRow += '<ul class="date">';
    newRow += '<li><label id="Label2" class="lang" lang="txtPage">' + i18nText('txtPage') + '</label><label id="Label3">' + pageNo + '</label></li>';
    var contentText = htmlEncode(getLines(pageText, 3));

    newRow += '<li><label id="Label1">' + truncate(contentText, 80) + '</label></li>';
    newRow += "</ul>";

	newRow += '<ul class="pic"  style="align:right">';
	newRow += "<li>";

    //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 += imgMemo;
	}
	else {
	    newRow += imgMemoHide;
	}
    newRow += "</li>";
    newRow += "<li>";
    
    if (hasMarking) {
        newRow += imgMarking;
    }
    else {
        newRow += imgMarkingHide;
    }
    newRow += "</li>";
    newRow += "<li><a class='read lang' name='dspRead' value='{\"contentid\":\"" + contentid + "\", \"pageNo\":\"" + pageNo + "\"}' lang='txtRead'>" + i18nText('txtRead') + "</a></li>";  	
    newRow += "</ul>";
    newRow += "</div>";
    newRow += "</div>";
    newRow += "</div>";
    newRow += "</section>";
    */
    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 += "<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="#"><img src="img/bookshelf/icon_01.jpg" width="20" height="20" class="listIcon">' + truncate(pageTitle, 20) + '</a>';
    newRow += '<a class="name" href="#">' + truncate(pageTitle, 20) + '</a>';

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

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

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

//    newRow +='<li>公開日:2012/09/14</li>';
//    newRow += '<li>閲覧日:2012/09/18</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="#">' + imgMemo + '</a></li>';
    }
    else {
        newRow += '<li><a href="#">' + imgMemoHide + '</a></li>';
    }
//    newRow += "</li>";
//    newRow += "<li>";

    if (hasMarking) {
        newRow += '<li><a href="#">' + imgMarking + '</a></li>';
    }
    else {
        newRow += '<li><a href="#">' + imgMarkingHide + '</a></li>';
    }


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


    //newRow +='<li><a href="#"><img class="sticker" src="img/list/icon_sticker.png"></a></li>';
    //newRow +='<li><a href="#"><img class="pen" src="img/list/icon_pen.png"></a></li>';

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

    newRow += "</section>";

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


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



/*
----------------------------------------------------------------------------
Setting dialog [start]
----------------------------------------------------------------------------
*/
$(function () {
    
    $("#dspTitleNm").click(dspTitleNm_Click);
    $("#dspTitleNmKn").click(dspTitleNmKn_Click);
    $("#dspPubDt").click(dspPubDt_Click);

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


// Contains non-exist content
var bookmark_errorContent = [];

// Contain contents
var collection_contents = [];

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

        var contentid = 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
        collection_contents[nIndex].pages = pages;

        // Join pages to request to server
        var strPageNos = buildPageNos(collection_contents[nIndex].pages);
        
            // Call api to get all details of pages 1 time
        avwCmsApiSync(ClientData.userInfo_accountPath(), "webContentPage", "GET",
                    { contentId: contentid, sid: ClientData.userInfo_sid(), pageNos: strPageNos, thumbnailFlg: 1 },
                    function (data) {

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

                            var comparePageNo = 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
                                    collection_contents[nIndex].pages[nIndex2].existed = true;
                                    // Store detail of page
                                    collection_contents[nIndex].pages[nIndex2].pageText = data.pages[nIndex2].pageText;
                                    collection_contents[nIndex].pages[nIndex2].pageThumbnail = data.pages[nIndex2].pageThumbnail;
                                }
                                else if (contentTypes[contentid] == "none" && data.pages.length > 0) {
                                    collection_contents[nIndex].pages[nIndex2].existed = true;
                                    // Store detail of page
                                    collection_contents[nIndex].pages[nIndex2].pageText = ''; //data.pages[0].pageText;
                                    collection_contents[nIndex].pages[nIndex2].pageThumbnail = pathImgContentNone; //data.pages[nIndex2].pageThumbnail;
                                }
                            }

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

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

                            }
                        }
                    }
        );
       
    }
};
/*
    Build pageNos
*/
function buildPageNos(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 
*/
function IsErrorContent(strContentId) {
    var isError = false;
    
    for (var nIndex = 0; nIndex < bookmark_errorContent.length; nIndex++) {
        if (strContentId == bookmark_errorContent[nIndex].contentid) {
            isError = true;
            break;
        }
    }
    return isError;
};

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

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

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

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

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

    // Reset error contents
    bookmark_errorContent = [];

    // Reset ok checked content
    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 (IsErrorContent(oneBookMark.contentid) == false) {
            // If content is ok + checked
            if (IsOKCheckedContent(oneBookMark.contentid) == false) {
                if (!IsExistContent(oneBookMark.contentid)["isExisted"]) {
                    if (avwHasError()) {
                        // System error excepting 404
                        showSystemError();
                        return;
                    }
                    else {
                        // Add to list of error content
                        bookmark_errorContent.push({ contentid: oneBookMark.contentid });
                        // Remove bookmark
                        arrBookmarks.splice(nIndex, 1);
                        ClientData.isChangedBookmark(true);
                    }
                }
                // ==================================
                // Check existence of content [ end ]
                // ==================================
                else {
                    // Add nromal content
                    AddContent(oneBookMark.contentid, 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
*/
function IsExistContent(strContentId) {
    var isExisted = false;
    var contentType = '';
    var result = [];
    var params = {
        sid: ClientData.userInfo_sid(),
        getType: '1',
        contentId: strContentId
    };
    avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", 'GET', params,
                function (data) {
                    isExisted = true;
                    contentType = data.contentData.contentType;

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

                    // save content type
                    contentTypes[strContentId] = contentType;
                    contentName[strContentId] = data.contentData.contentName;
                    // save alert message level
                    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
                        showSystemError();
                    }
                });
                
    return result;
};

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

function truncate(strInput, length){
    if (strInput.length <= length)
    {
        return strInput;
    }
    else
    {
        return strInput.substring(0, length) + "...";
    }
};
