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

// Start Declare Variables
// ----Constant-----------//
// HOME.DEFAULT_DISP_NUMBER_RECORD_FROM = 1;
// HOME.DEFAULT_DISP_NUMBER_RECORD_TO = 15;
HOME.DEFAULT_SORT_TYPE = "3";
HOME.DEFAULT_SORT_ORDER = "2";
HOME.DEFAULT_SEARCH_DIVISION = 0;

HOME.home_realTotalRecord = 0;

HOME.iNumberOfNextRecord = 15;
// Thumbnail array
HOME.thumbnailArr = [];
// Content type array.
HOME.contentTypeArr = [];

HOME.contentIdArray = [];
// HOME.resourceVersionArr = [];
// HOME.metaVersionArr = [];
HOME.errorPage = [];
HOME.errorContent = [];
HOME.dataGroup;
HOME.dataGenre;
HOME.totalPage;
HOME.existContent = [];
HOME.isSubMenuHoverOn = false;
HOME.home_isMove = false;
HOME.isShowBookShelf = true;
HOME.showNextRecordClickNumber = 1;

HOME.allowTimerCloseSubMenu = true;
HOME.timer_subMenu;

HOME.genre_totalcontent = -1;
HOME.group_totalcontent = -1;

// スクロール復帰
HOME.scrollTop = 0;
// 閲覧履歴に保持する最大件数
HOME.historyBuffer = 100;

// ==========================================================
$(document).ready(function() {

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

    // ソート条件デフォルト設定
    if (AVWEB.avwSysSetting().sortTypeHome != undefined) {
        HOME.DEFAULT_SORT_TYPE = AVWEB.avwSysSetting().sortTypeHome;
    }
    if (AVWEB.avwSysSetting().sortOrderHome != undefined) {
        HOME.DEFAULT_SORT_ORDER = AVWEB.avwSysSetting().sortOrderHome;
    }

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

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

    // Check if Force Change password
    if (ClientData.requirePasswordChange() != 1) {
        // Register log
        COMMON.RegisterLog();

        // Sync Data
        HOME.syncContentData();

        // remove hover css if is touch device
        HOME.removeHoverCss();

        // Get default view mode for rendergrid view
        HOME.setDefaultViewMode();

        // Toggle TreeView Disp
        HOME.handleTreeViewDisp();

        // Format text display more record
        HOME.formatDisplayMoreRecord();

        // Render Grid
        HOME.renderGridView();

        // Render Genre
        HOME.getDataJsonFileGenre();
        HOME.getDataJsonFileGroup();

        // Lock screen is here, because of in getDataJsonFileGroup() called
        // click to expand speified nodes of treeview
        if (ClientData.serviceOpt_encryption() != 'Y') {
            COMMON.LockScreen();
        }

        // Change display type to bookshelf type
        $('#control-bookshelf-type').click(HOME.changeDispBookShelfFunction);

        // Change display type to list type
        $('#control-list-type').click(HOME.changeDispListFunction);

        // Go To Details Page
        $('#main-ws canvas').live('click', HOME.canvasClickFunction);
        $('#main-ws canvas').live('touchend', HOME.canvasClickFunction);
        $('#main-ws canvas').live('touchmove', function() {
            HOME.home_isMove = true;
        });

        // Open dialog
        $('.dialog').live('click', HOME.openSubMenuDialogFunction);
        // $('.dialog').live('touchstart', HOME.openSubMenuDialogFunction);
        $('.dialog').live('touchend', HOME.openSubMenuDialogFunction);
        $('.dialog').live('touchmove', function() {
            HOME.home_isMove = true;
        });

        // Render Genre TreeView
        $('#lnkbtnGenre').click(HOME.genreSelectFunction);

        // Render Group TreeView
        $('#lnkbtnGroup').click(HOME.groupSelectFunction);

        // Button details on dialog click event
        $('#dialog-detail').click(HOME.detailsSubmenuFunction);

        // Button Read on dialog click event
        $('#dialog-read').click(HOME.readSubmenuFunction);

        // Show Next Record
        $('a#control-nextrecord').click(HOME.showNextRecordFunction);

        // Sort Title
        $('#control-sort-title').click(HOME.sortByTitleFunction);

        // Sort by title kana
        $('#control-sort-titlekana').click(HOME.sortByTitleKanaFunction);

        // sort by release date
        $('#control-sort-releasedate').click(HOME.sortByReleaseDateFunction);

        // Go To Details Page
        $('.button-details').live('click', HOME.readSubmenuFunction);
        // $('.button-details').live('touchstart', HOME.readSubmenuFunction);
        $('.button-details').live('touchend', HOME.readSubmenuFunction);
        $('.button-details').live('touchmove', function() {
            HOME.home_isMove = true;
        });

        // Show Share Dialog
        $('.button-share').live('click', HOME.showContentShareDlgFunction);
        $('.button-share').live('touchend', HOME.showContentShareDlgFunction);
        $('.button-share').live('touchmove', function() {
            HOME.home_isMove = true;
        });

        $('#dlgSubMenu').hover(HOME.subMenuHoverFunction, HOME.subMenuHoverOffFunction);

        if (COMMON.isTouchDevice() == true) {
            var avwUserEnvObj = new UserEnvironment();
            if (avwUserEnvObj.os == 'ipad') {
                $('#dlgSubMenu').click(function() {
                    HOME.allowTimerCloseSubMenu = false;
                });
            }
        }

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

        $('body').click(HOME.bodyHomeClickFunction);
        if (COMMON.isTouchDevice() == true) {
            var avwUserEnvObj = new UserEnvironment();
            if (avwUserEnvObj.os == 'ipad') {
                $('body').bind('touchstart', function() {
                    if ($('#dlgSubMenu').css('display') != "none") {
                        HOME.allowTimerCloseSubMenu = true;
                        HOME.timer_subMenu = setTimeout("HOME.startTimerCloseMenu();", 500);
                    }
                });
            } else {
                $('body').bind('touchstart', HOME.bodyHomeClickFunction);
            }
        }

        $(window).resize(function() {
            if ($("#contentDetail").css("display") != "none") {
                // Refresh panel of detail to center.
                $("#contentDetail").center();
                if ($("#contentDetail").height() > $(window).height()) {
                    $("#contentDetail").css('top', '0');
                }
            }
        });
    } else {
        HEADER.checkForceChangePassword();
    }

    // 日比谷用設定ボタン隠す
    $('#dspHibiya').hide();

    // カタログエディション対応判定
    if (ClientData.serviceOpt_catalog_edition() == 'Y') {
        $('.tabUnit').hide();
        // センタリングするようサイズ調整
        $('#bookshelf-main').width(660);
    } else {
        $('.tabUnit').show();
    }

    // hide tab group with user anonymous
    if (COMMON.isAnonymousLogin()) {

        // グループ選択隠す
        $('.switchingTab .colright').hide();
        // プッシュメッセージ隠す
        $('#dspPushMessage').hide();

        // 日比谷対応判定
        if (ClientData.serviceOpt_hibiyakadan_catalog() == 'Y') {
            $('#dspHibiya').show();
            jQuery('#dlgAddMemberGroup').dialog({
                autoOpen : false,
                modal : true,
                width : 350
            });
            $('#dspHibiya').click(HOME.dspHibiyaClickFunction);
            $('#btnAddMemberGroupSearch').click(HOME.btnAddMemberGroupSearchClickFunction);
        }
    } else {
        // $('.tabUnit').show();
        $('.switchingTab .colright').show();
        // プッシュメッセージ判定
        if (ClientData.serviceOpt_apns() == 'Y' || ClientData.serviceOpt_usable_push_message() == 'Y') {
            // プッシュメッセージ表示
            $('#dspPushMessage').show();
        } else {
            $('#dspPushMessage').hide();
        }
    }

    // set scroll for tree view with IE9 on win7
    var ua = window.navigator.userAgent.toLowerCase();
    if (/msie 9.0/.test(ua) && /windows nt 6.1/.test(ua) && !/tablet/.test(ua)) {
        $('.tab_bg_color').css({
            "overflow-x" : "scroll"
        });
    }

    // 詳細、共有表示パーツ読み込み
    $("#inc_detail").load("./inc_detail.html?__UPDATEID__", function(myData, myStatus, xhr) {
        // 読み込み完了時の処理
        I18N.i18nReplaceText();
        $('.datepicker').pickadate({
            format : 'yyyy-mm-dd'
        });
    });

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

});

// 日比谷カスタム ここから
HOME.dspHibiyaClickFunction = function() {
    $('#dlgAddMemberGroup').dialog('open');
};
HOME.btnAddMemberGroupSearchClickFunction = function() {

    var addGroupName = $('#txtAddMemberGroupName').val();
    if (addGroupName == "") {
        return;
    }

    var groupIds = HOME.getAddMemberGroupId(addGroupName);
    if (groupIds == "") {
        alert("コードが不正です");
        return;
    }

    $('#dlgAddMemberGroup').dialog('close');
    ClientData.searchCond_groupId(groupIds);

    // 画面再描画開始
    var recordFrom = 0;
    var recordTo = 0;

    if (HOME.isShowBookShelf) {
        recordFrom = HOME.DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = HOME.returnNumberDispRecordForBookShelf();
    } else if (!HOME.isShowBookShelf) {
        recordFrom = HOME.DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = HOME.returnNumberDispRecordForList();
    } else {
        recordFrom = HOME.DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = HOME.returnNumberDispRecordForBookShelf();
    }

    var id = ClientData.userInfo_sid();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    // ClientData.searchCond_groupId('');
    ClientData.searchCond_genreId('');
    var groupId = ClientData.searchCond_groupId();
    var genreId = ClientData.searchCond_genreId();

    // refresh gridview
    HOME.refreshGrid();

    HOME.resetShowNextRecordCount();

    HOME.handleSortDisp();

    HOME.renderContent(id, searchText, searchDivision, sortType, sortOrder, recordFrom, recordTo, genreId, groupId);

};

HOME.getAddMemberGroupId = function(strGroupName) {

    var groupIds = "";
    var params = {
        sid : ClientData.userInfo_sid(),
        groupName : strGroupName
    };
    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "addMemberGroup", 'POST', params,
    // Success
    function(data) {
        if (data.groupIds) {
            groupIds = data.groupIds;
        }
    }, function(xmlHttpRequest, txtStatus, errorThrown) {
        //
    });
    return groupIds;
};
// --日比谷カスタム ここまで

HOME.startTimerCloseMenu = function() {
    if (HOME.timer_subMenu) {
        clearTimeout(HOME.timer_subMenu);
        HOME.timer_subMenu = null;
    }
    if (HOME.allowTimerCloseSubMenu == true) {
        $('#dlgSubMenu').hide();
    }
};

HOME.subMenuHoverFunction = function() {
    HOME.isSubMenuHoverOn = true;
};

HOME.subMenuHoverOffFunction = function() {
    HOME.isSubMenuHoverOn = false;
};

HOME.bodyHomeClickFunction = function() {
    if (!HOME.isSubMenuHoverOn) {
        $('#dlgSubMenu').hide();
    }
};

// Toggle Genre/Group Tab
HOME.handleTreeViewDisp = function() {
    $('#lblGenre').css('display', 'block');
    $('#lnkGenre').css('display', 'none');
    $('#lnkGroup').css('display', 'block');
    $('#lblGroup').css('display', 'none');
};

// Change Display BookShelf Function
HOME.changeDispBookShelfFunction = function() {

    if (HOME.isShowBookShelf) {
        //既に本棚表示
        return;
    }

    HOME.isShowBookShelf = true;

    $('body').attr('id', 'bookshelf');
    $('#control-bookshelf-type').parent().removeClass("thumbnail");
    $('#control-bookshelf-type').parent().addClass("thumbnail_select");
    $('#control-list-type').parent().removeClass("list_select");
    $('#control-list-type').parent().addClass("list");

    // ページ遷移初期化
    HOME.resetShowNextRecordCount();

    var recordOffset = 0;
    var recordLimit = HOME.returnNumberDispRecordForBookShelf();
    // refresh sort order
    HOME.refreshSortTypeOrder();

    var id = ClientData.userInfo_sid();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    var groupId = ClientData.searchCond_groupId();
    var genreId = ClientData.searchCond_genreId();

    // handle sort display
    HOME.handleSortDisp();

    // refresh Grid view
    HOME.refreshGrid();

    HOME.renderContent(id, searchText, searchDivision, sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);

    // format text disp more record
    HOME.formatDisplayMoreRecord();

    // Get next record will be displayed
    HOME.getNextRecordNumForBookShelf();

};

// Change Display List Function
HOME.changeDispListFunction = function() {

    if (HOME.isShowBookShelf == false) {
        return;
    }

    HOME.isShowBookShelf = false;

    $('body').attr('id', 'list');
    $('#control-list-type').parent().removeClass("list");
    $('#control-list-type').parent().addClass("list_select");
    $('#control-bookshelf-type').parent().removeClass("thumbnail_select");
    $('#control-bookshelf-type').parent().addClass("thumbnail");

    // ページ遷移初期化
    HOME.resetShowNextRecordCount();

    // Check VIewmode
    var recordOffset = 0;
    var recordLimit = HOME.returnNumberDispRecordForList();
    // refresh sort order
    HOME.refreshSortTypeOrder();

    var id = ClientData.userInfo_sid();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    var groupId = ClientData.searchCond_groupId();
    var genreId = ClientData.searchCond_genreId();

    // Handle Sort disp
    HOME.handleSortDisp();

    // refresh Grid view
    HOME.refreshGrid();

    HOME.renderContent(id, searchText, searchDivision, sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);

    // format text disp more record
    HOME.formatDisplayMoreRecord();

    // Get next record will be displayed
    HOME.getNextRecordNumForList();

};

// Canvas Click function
HOME.canvasClickFunction = function(e) {
    if (e) {
        e.preventDefault();
    }

    if (HOME.home_isMove == true) {
        HOME.home_isMove = false;
        return;
    }

    var contentId = $(this).attr('id');
    var outputId = contentId.substring(17);

    if (HOME.isShowBookShelf) {
        LIMIT_ACCESS_CONTENT.checkLimitContent(outputId, function() {
            HOME.canvasClickFunction_callback(outputId);
        }, function() {
        });
    } else {
        HOME.canvasClickFunction_callback(outputId);
    }
};

HOME.canvasClickFunction_callback = function(outputId) {
    var date = new Date();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var outputDate = COMMON.formatNormalDate(day, month, date.getFullYear());
    var checkflag = false;
    var base64String = HOME.returnThumbnail(outputId);

    // Set content id for next screen
    ClientData.contentInfo_contentThumbnail(base64String);
    // Get image of selected image
    ClientData.contentInfo_contentId(outputId);

    var contentType = HOME.returnContentType(outputId);
    ClientData.contentInfo_contentType(contentType);

    // Check Display mode to handle action
    HOME.contentIdArray = ClientData.ReadingContentIds();
    if (!HOME.isShowBookShelf) {

        // Store Content id that user has read
        if (HOME.contentIdArray.length > 0) {
            checkflag = false;
            for ( var nIndex = 0; nIndex < HOME.contentIdArray.length; nIndex++) {
                if (HOME.contentIdArray[nIndex].contentid == outputId) {
                    checkflag = true;
                    break;
                }
            }

            if (!checkflag) {
                HOME.contentIdArray.push({
                    contentid : outputId,
                    viewdate : '',
                    originviewdate : ''
                });
            }
        } else {
            HOME.contentIdArray.push({
                contentid : outputId,
                viewdate : '',
                originviewdate : ''
            });
        }

        // Renew ReadingContentID
        var newArray = [];
        ClientData.ReadingContentIds(newArray);

        // Set data for readingcontentid
        ClientData.ReadingContentIds(HOME.contentIdArray);

        // Set ResouceVersion for content
        COMMON.setResourceVersionData(outputId);

        // Set MetaVersion for content
        COMMON.setMetaVersionData(outputId);

        // Close Submenu
        $('#dlgSubMenu').hide();

        // Delete 'new' icon
        HOME.drawEditImage(outputId);

        // Open content Detail
        DETAIL.openContentDetail();
    } else {

        // Store Content id that user has read
        if (HOME.contentIdArray.length > 0) {

            checkflag = false;
            for ( var nIndex = 0; nIndex < HOME.contentIdArray.length; nIndex++) {
                if (HOME.contentIdArray[nIndex].contentid == outputId) {
                    checkflag = true;
                    if (HOME.contentIdArray[nIndex].viewdate == null || HOME.contentIdArray[nIndex].viewdate == 'undefined' || HOME.contentIdArray[nIndex].viewdate == '') {
                        HOME.contentIdArray[nIndex].viewdate = outputDate;
                        HOME.contentIdArray[nIndex].originviewdate = date;
                    }
                    break;
                }
            }

            if (!checkflag) {
                HOME.contentIdArray.push({
                    contentid : outputId,
                    viewdate : outputDate,
                    originviewdate : date
                });
            }
        } else {
            HOME.contentIdArray.push({
                contentid : outputId,
                viewdate : outputDate,
                originviewdate : date
            });
        }

        // Renew ReadingContentID
        var newArray = [];
        ClientData.ReadingContentIds(newArray);

        // Set data for readingcontentid
        ClientData.ReadingContentIds(HOME.contentIdArray);

        // Set ResouceVersion for content
        COMMON.setResourceVersionData(outputId);

        // Set MetaVersion for content
        COMMON.setMetaVersionData(outputId);

        // $('body,html').animate({ scrollTop: 0 }, 0);
        ClientData.IsRefresh(false);

        if (contentType == COMMON.ContentTypeKeys.Type_Others) {
            // Download content
            HEADER.downloadResourceById(outputId);
            // redraw content remove new icon
            HOME.drawEditImage(outputId);
        } else if (contentType == COMMON.ContentTypeKeys.Type_Link) {
            // link content
            HEADER.viewLinkContentById(outputId);
            // redraw content remove new icon
            HOME.drawEditImage(outputId);
        } else {
            HOME.drawEditImage(outputId);
            // ビュアーに切り替え
            HOME.showContentView();
        }

    }

};

// function Open SubMenu Dialog
HOME.openSubMenuDialogFunction = function(e) {
    if (e) {
        e.preventDefault();
    }
    if (HOME.home_isMove == true) {
        HOME.home_isMove = false;
        return;
    }

    var array = [ e.clientX, e.clientY ];
    var contentid = $(this).attr('contentid');
    var checkflag = false;

    if (!HOME.isShowBookShelf) {
        // Get image of selected image
        var base64String = HOME.returnThumbnail(contentid);
        ClientData.contentInfo_contentThumbnail(base64String);
        ClientData.contentInfo_contentId(contentid);

        var contentType = HOME.returnContentType(contentid);
        ClientData.contentInfo_contentType(contentType);

        // Store Content id that user has read
        HOME.contentIdArray = ClientData.ReadingContentIds();
        if (HOME.contentIdArray.length > 0) {

            for ( var nIndex = 0; nIndex < HOME.contentIdArray.length; nIndex++) {
                if (HOME.contentIdArray[nIndex].contentid == contentid) {
                    checkflag = true;
                    break;
                }
            }

            if (!checkflag) {
                HOME.contentIdArray.push({
                    contentid : contentid,
                    viewdate : '',
                    originviewdate : ''
                });
            }
        } else {
            HOME.contentIdArray.push({
                contentid : contentid,
                viewdate : '',
                originviewdate : ''
            });
        }

        // Renew ReadingContentID
        var newArray = [];
        ClientData.ReadingContentIds(newArray);

        // Set data for readingcontentid
        ClientData.ReadingContentIds(HOME.contentIdArray);

        // Set ResouceVersion for content
        COMMON.setResourceVersionData(contentid);

        // Set MetaVersion for content
        COMMON.setMetaVersionData(contentid);

        // Close Submenu
        $('#dlgSubMenu').hide();

        // Delete 'new' icon
        HOME.drawEditImage(contentid);

        DETAIL.openContentDetail();

    } else {
        $('#dialog-read').attr('contentid', contentid);
        $('#dialog-detail').attr('contentid', contentid);
        $("#dlgSubMenu").show();
        HOME.allowTimerCloseSubMenu = false;
        $("#dlgSubMenu").position({
            my : "left bottom",
            at : "left-10 top",
            of : this,
            collision : "fit"
        });
    }
};

// Genre Click Function
HOME.genreSelectFunction = function() {
    $('.file').css('font-weight', 'normal');
    $('.file').css('text-decoration', 'none');

    $('.folder').css('font-weight', 'normal');
    $('.folder').css('text-decoration', 'none');

    $('#all').css('font-weight', 'bold');
    $('#all').css('text-decoration', 'underline');

    var recordOffset = 0;
    var recordLimit = 0;
    if (HOME.isShowBookShelf) {
        recordLimit = HOME.returnNumberDispRecordForBookShelf();
    } else {
        recordLimit = HOME.returnNumberDispRecordForList();
    }

    var id = ClientData.userInfo_sid();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    ClientData.searchCond_groupId('');
    ClientData.searchCond_genreId('');
    var groupId = ClientData.searchCond_groupId();
    var genreId = ClientData.searchCond_genreId();

    // refresh gridview
    HOME.refreshGrid();

    HOME.resetShowNextRecordCount();

    HOME.handleSortDisp();

    HOME.renderContent(id, searchText, searchDivision, sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);
};

// Group Click Function
HOME.groupSelectFunction = function() {
    $('.file').css('font-weight', 'normal');
    $('.file').css('text-decoration', 'none');

    $('.folder').css('font-weight', 'normal');
    $('.folder').css('text-decoration', 'none');

    var firstNode = $('#list_1').find('a')[0];
    $('#list_1').find(firstNode).css('text-decoration', 'underline');
    $('#list_1').find(firstNode).css('font-weight', 'bold');

    var recordOffset = 0;
    var recordLimit = 0;
    if (HOME.isShowBookShelf) {
        recordLimit = HOME.returnNumberDispRecordForBookShelf();
    } else {
        recordLimit = HOME.returnNumberDispRecordForList();
    }

    var id = ClientData.userInfo_sid();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    ClientData.searchCond_groupId('');
    ClientData.searchCond_genreId('');
    var groupId = ClientData.searchCond_groupId();
    var genreId = ClientData.searchCond_genreId();

    // refresh gridview
    HOME.refreshGrid();

    HOME.resetShowNextRecordCount();

    HOME.handleSortDisp();

    HOME.renderContent(id, searchText, searchDivision, sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);
};

// Get Data from Category Json
HOME.getDataJsonFileGenre = function() {
    var params = {
        sid : ClientData.userInfo_sid()
    };
    HOME.abapi('category', params, 'GET', function(data1) {
        HOME.dataGenre = data1.categoryList;
        var arrData = new Array();
        var totalCount = 0;

        $.each(HOME.dataGenre, function(i, value) {
            // Calculate total content
            totalCount += Number(HOME.dataGenre[i].contentCount);
            if (HOME.dataGenre[i].parentCategoryId == 0) {
                var node = new TreeNode();
                // node.IsCategory = true;
                node.Text = COMMON.htmlEncode(HOME.dataGenre[i].categoryName);
                node.id = HOME.dataGenre[i].categoryId;
                node.Value = HOME.dataGenre[i].categoryId;
                node.ContentCount = HOME.dataGenre[i].contentCount;
                HOME.AddChidrenNodeGenre(node);
                // node.IsClosed = false; //#13200 カテゴリツリーの階層プラス・マイナスのアイコンが逆
                node.ExpandAfterBuild = true; // #14287 第一階層を開くようにする

                node.IsCategory = node.ChildNodes.length > 0; // Has child node

                arrData.push(node);
            }
        });
        var tree1 = new TreeView();
        tree1.CategoryTagName = "a";
        // tree1.TotalCount = totalCount;
        if (HOME.genre_totalcontent != -1) {
            tree1.TotalCount = HOME.genre_totalcontent;
        }
        tree1.Show("branch1", arrData, "HOME.AddGenre_Callback");
        $("#branch1").treeview();

        $('#all').css('font-weight', 'bold');
        $('#all').css('text-decoration', 'underline');

        $('.treeview > li').addClass('tabCategory');

        // Expand nodes(#14287 第1階層を開くようにする)
        for ( var nIndex = 0; nIndex < tree1.ExpandNodes.length; nIndex++) {
            if ($("#" + tree1.ExpandNodes[nIndex]).parent()) {
                var objParent = $("#" + tree1.ExpandNodes[nIndex]).parent();
                var objChild = objParent.children()[0];
                if (objChild) {
                    try {
                        objChild.click();
                    } catch (err) {
                        // For safari
                        var evObj = document.createEvent('MouseEvents');
                        evObj.initMouseEvent('click', true, true, window);
                        objChild.dispatchEvent(evObj);
                    }
                }
            }
        }

    });
};

// Add Children Node Category
HOME.AddChidrenNodeGenre = function(node1) {
    var dataChild = [];
    $.each(HOME.dataGenre, function(index, value) {
        if (HOME.dataGenre[index].parentCategoryId == node1.id) {
            // Check if current node is added or not
            var isChildNodeExisted = false;
            for ( var nChildNodesIndex = 0; nChildNodesIndex < dataChild.length; nChildNodesIndex++) {
                if (dataChild[nChildNodesIndex].categoryId == HOME.dataGenre[index].categoryId) {
                    isChildNodeExisted = true;
                }
            }
            if (!isChildNodeExisted) {
                dataChild.push(HOME.dataGenre[index]);
            }
            // dataChild.push(HOME.dataGenre[index]);
        }
    });

    $.each(dataChild, function(i, value) {
        var item = new TreeNode();
        // item.IsCategory = true;
        item.Text = COMMON.htmlEncode(dataChild[i].categoryName);
        item.id = dataChild[i].categoryId;
        item.Value = dataChild[i].categoryId;
        item.ContentCount = dataChild[i].contentCount;
        HOME.AddChidrenNodeGenre(item);

        item.IsCategory = item.ChildNodes.length > 0; // Has child node

        node1.ChildNodes.push(item);
    });
};

// Get Value for sort
HOME.AddGenre_Callback = function(selectedNode) {

    $('.file').css('font-weight', 'normal');
    $('.file').css('text-decoration', 'none');

    $('.folder').css('font-weight', 'normal');
    $('.folder').css('text-decoration', 'none');

    if (selectedNode.Id == "all") {
        var arrAllNodes = $('.root');
        for ( var nIndex = 0; nIndex < arrAllNodes.length; nIndex++) {
            var objTarget = $(arrAllNodes[nIndex]);
            // Check treeview
            if (objTarget.parent().parent().css('display') != 'none') {
                objTarget.css('font-weight', 'bold');
                objTarget.css('text-decoration', 'underline');
            }
        }
    } else {
        if (selectedNode.IsCategory == true) {
            var targetObj = $('#' + selectedNode.Id).parent().children()[1];
            $(targetObj).css('font-weight', 'bold');
            $(targetObj).css('text-decoration', 'underline');
        } else {
            $('#' + selectedNode.Id).css('font-weight', 'bold');
            $('#' + selectedNode.Id).css('text-decoration', 'underline');
        }
    }

    var node = new TreeNode();
    node = selectedNode;

    lCateId = node.Value;
    $('#content-grid').html('');

    var recordOffset = 0;
    var recordLimit = 0;
    if (HOME.isShowBookShelf) {
        recordLimit = HOME.returnNumberDispRecordForBookShelf();
    } else {
        recordLimit = HOME.returnNumberDispRecordForList();
    }

    ClientData.searchCond_genreId(lCateId);

    var id = ClientData.userInfo_sid();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    var groupId = ClientData.searchCond_groupId();
    var genreId = ClientData.searchCond_genreId();

    // refresh gridview
    HOME.refreshGrid();

    HOME.resetShowNextRecordCount();

    HOME.renderContent(id, searchText, searchDivision, sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);

    HOME.handleSortDisp();
};

// Get Data from Group Json
HOME.getDataJsonFileGroup = function() {
    var params = {
        sid : ClientData.userInfo_sid()
    };
    HOME.abapi('group', params, 'GET', function(data1) {
        HOME.dataGroup = data1.groupList;
        var arrData = new Array();
        var totalCount = 0;
        $.each(HOME.dataGroup, function(i, value) {
            // Calculate total group
            totalCount += Number(HOME.dataGroup[i].contentCount);

            if (HOME.dataGroup[i].parentGroupId == 0 || HOME.dataGroup[i].groupLevel == "0") {
                var node = new TreeNode();
                node.IsCategory = true;
                node.Text = COMMON.htmlEncode(HOME.dataGroup[i].groupName);
                node.id = HOME.dataGroup[i].groupId;
                node.Value = HOME.dataGroup[i].groupId;
                node.ContentCount = HOME.dataGroup[i].contentCount;
                HOME.AddChidrenNodeGroup(node);
                // node.IsClosed = false;
                node.ExpandAfterBuild = true;

                node.IsCategory = node.ChildNodes.length > 0; // Has child node

                arrData.push(node);
            }
        });
        var tree2 = new TreeView();
        tree2.CategoryTagName = "a";
        // tree1.TotalCount = totalCount;
        if (HOME.group_totalcontent != -1) {
            tree2.TotalCount = HOME.group_totalcontent;
        }
        tree2.Show("branch2", arrData, "HOME.AddGroup_Callback");
        $("#branch2").treeview();

        var firstNode = $('#branch2').find('a')[0];
        $('#branch2').find(firstNode).css('text-decoration', 'underline');
        $('#branch2').find(firstNode).css('font-weight', 'bold');

        $('.treeview > li').addClass('tabCategory');
        // Expand nodes
        for ( var nIndex = 0; nIndex < tree2.ExpandNodes.length; nIndex++) {
            if ($("#" + tree2.ExpandNodes[nIndex]).parent()) {
                var objParent = $("#" + tree2.ExpandNodes[nIndex]).parent();
                var objChild = objParent.children()[0];
                if (objChild) {
                    try {
                        objChild.click();
                    } catch (err) {
                        // For safari
                        var evObj = document.createEvent('MouseEvents');
                        evObj.initMouseEvent('click', true, true, window);
                        objChild.dispatchEvent(evObj);
                    }

                }
            }
        }
    });
};

// Add Children Node Group
HOME.AddChidrenNodeGroup = function(node1) {
    var dataChild = [];
    $.each(HOME.dataGroup, function(index, value) {
        if (HOME.dataGroup[index].parentGroupId == node1.id) {
            // Check if current node is added or not
            var isChildNodeExisted = false;
            for ( var nChildNodesIndex = 0; nChildNodesIndex < dataChild.length; nChildNodesIndex++) {
                if (dataChild[nChildNodesIndex].groupId == HOME.dataGroup[index].groupId) {
                    isChildNodeExisted = true;
                }
            }
            if (!isChildNodeExisted) {
                dataChild.push(HOME.dataGroup[index]);
            }
        }
    });

    $.each(dataChild, function(i, value) {
        var item = new TreeNode();
        // item.IsCategory = true;
        item.Text = COMMON.htmlEncode(dataChild[i].groupName);
        item.id = dataChild[i].groupId;
        item.Value = dataChild[i].groupId;
        item.ContentCount = dataChild[i].contentCount;
        HOME.AddChidrenNodeGroup(item);

        item.IsCategory = item.ChildNodes.length > 0; // Has child node

        node1.ChildNodes.push(item);
    });
};

// Get Value for sort
HOME.AddGroup_Callback = function(selectedNode) {
    $('.file').css('font-weight', 'normal');
    $('.file').css('text-decoration', 'none');

    $('.folder').css('font-weight', 'normal');
    $('.folder').css('text-decoration', 'none');

    if (selectedNode.Id == "all") {
        var arrAllNodes = $('.root');
        for ( var nIndex = 0; nIndex < arrAllNodes.length; nIndex++) {
            var objTarget = $(arrAllNodes[nIndex]);
            // Check treeview
            if (objTarget.parent().parent().css('display') != 'none') {
                objTarget.css('font-weight', 'bold');
                objTarget.css('text-decoration', 'underline');
            }
        }
    } else {
        if (selectedNode.IsCategory == true) {
            var targetObj = $('#' + selectedNode.Id).parent().children()[1];
            $(targetObj).css('font-weight', 'bold');
            $(targetObj).css('text-decoration', 'underline');
        } else {
            $('#' + selectedNode.Id).css('font-weight', 'bold');
            $('#' + selectedNode.Id).css('text-decoration', 'underline');
        }
    }

    var node = new TreeNode();

    node = selectedNode;
    lGrpId = node.Value;
    $('#content-grid').html('');

    var recordOffset = 0;
    var recordLimit = 0;
    if (HOME.isShowBookShelf) {
        recordLimit = HOME.returnNumberDispRecordForBookShelf();
    } else {
        recordLimit = HOME.returnNumberDispRecordForList();
    }

    ClientData.searchCond_groupId(lGrpId);

    var id = ClientData.userInfo_sid();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    var groupId = ClientData.searchCond_groupId();
    var genreId = ClientData.searchCond_genreId();

    // refreshGrid
    HOME.refreshGrid();

    HOME.resetShowNextRecordCount();

    HOME.renderContent(id, searchText, searchDivision, sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);

    HOME.handleSortDisp();
};

// Re-render page from and total record
HOME.reRenderPageNumber = function(dispRecord, dispTotal) {

    if (dispTotal) {
        $('#dispPage').html(dispRecord);
        $('#totalPage').html(dispTotal);
        $('#dispPage').css('visibility', 'visible');
        $('#totalPage').css('visibility', 'visible');
        $('.pageNumControl').css('visibility', 'visible');
    } else {
        $('#dispPage').css('visibility', 'hidden');
        $('#totalPage').css('visibility', 'hidden');
        $('.pageNumControl').css('visibility', 'hidden');
    }

};

// Call API
HOME.abapi = function(name, param, method, callback) {
    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), name, method, param, callback, null);
};

// Dialog Details Button Click
HOME.detailsSubmenuFunction = function(e) {
    if (e) {
        e.preventDefault();
    }
    HOME.allowTimerCloseSubMenu = false;

    var contentId = $(this).attr('contentid');
    // Get image of selected image
    var base64String = HOME.returnThumbnail(contentId);
    var contentType = HOME.returnContentType(contentId);
    ClientData.contentInfo_contentType(contentType);
    ClientData.contentInfo_contentId(contentId);
    ClientData.contentInfo_contentThumbnail(base64String);

    var checkflag = false;
    // Store Content id that user has read
    HOME.contentIdArray = ClientData.ReadingContentIds();
    if (HOME.contentIdArray.length > 0) {

        for ( var nIndex = 0; nIndex < HOME.contentIdArray.length; nIndex++) {
            if (HOME.contentIdArray[nIndex].contentid == contentId) {
                checkflag = true;
                break;
            }
        }

        if (!checkflag) {
            HOME.contentIdArray.push({
                contentid : contentId,
                viewdate : '',
                originviewdate : ''
            });
        }
    } else {
        HOME.contentIdArray.push({
            contentid : contentId,
            viewdate : '',
            originviewdate : ''
        });
    }

    // Renew ReadingContentID
    var newArray = [];
    ClientData.ReadingContentIds(newArray);

    // Set data for readingcontentid
    ClientData.ReadingContentIds(HOME.contentIdArray);

    // Set ResouceVersion for content
    COMMON.setResourceVersionData(contentId);

    // Set MetaVersion for content
    COMMON.setMetaVersionData(contentId);

    // Close popup menu
    $('#dlgSubMenu').hide();

    // delete 'new' icon
    HOME.drawEditImage(contentId);

    // Show detail
    DETAIL.openContentDetail();
};

// Dialog Read Button CLick
HOME.readSubmenuFunction = function(e) {
    if (e) {
        e.preventDefault();
    }
    HOME.allowTimerCloseSubMenu = false;

    if (HOME.home_isMove == true) {
        HOME.home_isMove = false;
        return;
    }

    // hide dialog sub menu
    $('#dlgSubMenu').hide();

    var contentId = $(this).attr('contentid');
    // check limit of content
    LIMIT_ACCESS_CONTENT.checkLimitContent(contentId, function() {
        HOME.readSubmenuFunction_callback(contentId);
    }, function() {
    });

};

// Dialog Read Button CLick callback
HOME.readSubmenuFunction_callback = function(contentId) {
    var contentThumbnail = HOME.returnThumbnail(contentId);

    var date = new Date();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    var outputDate = COMMON.formatNormalDate(day, month, date.getFullYear());

    ClientData.contentInfo_contentId(contentId);
    ClientData.contentInfo_contentThumbnail(contentThumbnail);

    var contentType = HOME.returnContentType(contentId);
    ClientData.contentInfo_contentType(contentType);

    var checkflag = false;

    // Store Content id that user has read
    HOME.contentIdArray = ClientData.ReadingContentIds();
    if (HOME.contentIdArray.length > 0) {

        for ( var nIndex = 0; nIndex < HOME.contentIdArray.length; nIndex++) {
            if (HOME.contentIdArray[nIndex].contentid == contentId) {
                checkflag = true;
                if (HOME.contentIdArray[nIndex].viewdate == '' || HOME.contentIdArray[nIndex].viewdate == null || HOME.contentIdArray[nIndex].viewdate == 'undefined') {
                    HOME.contentIdArray[nIndex].viewdate = outputDate;
                    HOME.contentIdArray[nIndex].originviewdate = date;
                }
                break;
            }
        }

        if (!checkflag) {
            HOME.contentIdArray.push({
                contentid : contentId,
                viewdate : outputDate,
                originviewdate : date
            });
        }
    } else {
        HOME.contentIdArray.push({
            contentid : contentId,
            viewdate : outputDate,
            originviewdate : date
        });
    }

    // Renew ReadingContentID
    var newArray = [];
    ClientData.ReadingContentIds(newArray);

    // Set ResouceVersion for content
    COMMON.setResourceVersionData(contentId);

    // Set MetaVersion for content
    COMMON.setMetaVersionData(contentId);

    // Set data for readingcontentid
    ClientData.ReadingContentIds(HOME.contentIdArray);

    // Close Submenu
    $('#dlgSubMenu').hide();

    // $('body,html').animate({ scrollTop: 0 }, 0);
    ClientData.IsRefresh(false);

    // For testing without other Type.
    if (contentType == COMMON.ContentTypeKeys.Type_Others) {
        // Download content
        HEADER.downloadResourceById(contentId);
        // redraw content remove new icon
        HOME.drawEditImage(contentId);
    } else if (contentType == COMMON.ContentTypeKeys.Type_Link) {
        // link content
        HEADER.viewLinkContentById(contentId);
        // redraw content remove new icon
        HOME.drawEditImage(contentId);
    } else {
        // Go to Conten view page
        HOME.drawEditImage(contentId);
        HOME.showContentView();
    }
};

// Handle Back To Top Button
HOME.handleBackToTop = function() {

    if (ClientData.searchCond_recordTo() >= HOME.totalPage) {
        $('#control-nextrecord').css('display', 'none');
    } else {
        $('#control-nextrecord').css('display', 'block');
    }

    if (HOME.totalPage == 0) {
        $('#control-nextrecord').css('display', 'none');
    }

};

// Show Next Record Function
HOME.showNextRecordFunction = function() {

    $('#control-nextrecord').hide();

    // Count number of click
    HOME.showNextRecordClickNumber = HOME.showNextRecordClickNumber + 1;

    var fromPage = ClientData.searchCond_recordFrom();
    var toPage = ClientData.searchCond_recordTo();
    var sortType = ClientData.searchCond_sortType();
    var sortOrder = ClientData.searchCond_sortOrder();
    var searchText = ClientData.searchCond_searchText();
    var searchDivision = ClientData.searchCond_searchDivision();
    var genreId = ClientData.searchCond_genreId();
    var groupId = ClientData.searchCond_groupId();
    var sid = ClientData.userInfo_sid();
    var totalrecord = HOME.totalPage;

    var offsetPage = ClientData.searchCond_recordTo();
    if (offsetPage == null || offsetPage == 'undefined') {
        offsetPage = 0;
    }

    var limitPage = 0; //ClientData.searchCond_recordTo();
    if (HOME.isShowBookShelf) {
        limitPage = HOME.returnNumberDispRecordForBookShelf();
    } else {
        limitPage = HOME.returnNumberDispRecordForList();
    }

//	if (fromPage == null || fromPage == 'undefined') {
//		fromPage = HOME.DEFAULT_DISP_NUMBER_RECORD_FROM;
//	}
//
//	if (toPage == null || toPage == 'undefined') {
//		if (HOME.isShowBookShelf) {
//			toPage = HOME.returnNumberDispRecordForBookShelf();
//		} else if (!HOME.isShowBookShelf) {
//			toPage = HOME.returnNumberDispRecordForList();
//		} else {
//			toPage = HOME.returnNumberDispRecordForBookShelf();
//		}
//	}
//
//	fromPage = eval(toPage) + 1;
//	var iRecordNumber = eval(totalrecord) - eval(fromPage);
//
//	if (iRecordNumber < HOME.iNumberOfNextRecord) {
//		toPage = eval(fromPage) + eval(iRecordNumber);
//	} else {
//		toPage = eval(fromPage) + (eval(HOME.iNumberOfNextRecord) - 1);
//	}
//	ClientData.searchCond_recordFrom(fromPage);
//	ClientData.searchCond_recordTo(toPage);

    if (offsetPage <= totalrecord) {
        HOME.renderContent(sid, searchText, searchDivision, sortType, sortOrder, offsetPage, limitPage, genreId, groupId);
    }
};

// Sort By Title Function
HOME.sortByTitleFunction = function() {

    $('#control-nextrecord').hide();

    var sortOrder = ClientData.searchCond_sortOrder();
    var sortType = ClientData.searchCond_sortType();
    var sid = ClientData.userInfo_sid();
    var genreId = ClientData.searchCond_genreId();
    var groupId = ClientData.searchCond_groupId();

    var recordOffset = 0;
    var recordLimit = 0;
    if (HOME.isShowBookShelf) {
        recordLimit = HOME.returnNumberDispRecordForBookShelf();
    } else {
        recordLimit = HOME.returnNumberDispRecordForList();
    }

    if (sortOrder == COMMON.Consts.ConstOrderSetting_Asc) {
        if (sortType == 1) {
            sortOrder = COMMON.Consts.ConstOrderSetting_Desc;
        }
    } else {
        sortOrder = COMMON.Consts.ConstOrderSetting_Asc;
    }
    ClientData.searchCond_sortOrder(sortOrder);

    HEADER.setStatusSort('#control-sort-title', sortOrder == COMMON.Consts.ConstOrderSetting_Asc);

    sortType = 1;
    ClientData.searchCond_sortType(sortType);

    // refresh Gridview
    HOME.refreshGrid();

    HOME.renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);
};

// Sort By Title Kana function
HOME.sortByTitleKanaFunction = function() {

    $('#control-nextrecord').hide();

    var sortOrder = ClientData.searchCond_sortOrder();
    var sortType = ClientData.searchCond_sortType();
    var sid = ClientData.userInfo_sid();
    var genreId = ClientData.searchCond_genreId();
    var groupId = ClientData.searchCond_groupId();

    var recordOffset = 0;
    var recordLimit = 0;
    if (HOME.isShowBookShelf) {
        recordLimit = HOME.returnNumberDispRecordForBookShelf();
    } else {
        recordLimit = HOME.returnNumberDispRecordForList();
    }

    if (sortOrder == COMMON.Consts.ConstOrderSetting_Asc) {
        if (sortType == 2) {
            sortOrder = COMMON.Consts.ConstOrderSetting_Desc;
        }
    } else {
        sortOrder = COMMON.Consts.ConstOrderSetting_Asc;
    }
    ClientData.searchCond_sortOrder(sortOrder);

    HEADER.setStatusSort('#control-sort-titlekana', sortOrder == COMMON.Consts.ConstOrderSetting_Asc);

    sortType = 2;
    // refresh gridview
    HOME.refreshGrid();

    ClientData.searchCond_sortType(sortType);
    HOME.renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);

};

// Sort By Release Date
HOME.sortByReleaseDateFunction = function() {

    $('#control-nextrecord').hide();

    var sortOrder = ClientData.searchCond_sortOrder();
    var sortType = ClientData.searchCond_sortType();
    var sid = ClientData.userInfo_sid();
    var genreId = ClientData.searchCond_genreId();
    var groupId = ClientData.searchCond_groupId();

    var recordOffset = 0;
    var recordLimit = 0;
    if (HOME.isShowBookShelf) {
        recordLimit = HOME.returnNumberDispRecordForBookShelf();
    } else {
        recordLimit = HOME.returnNumberDispRecordForList();
    }

    if (sortOrder == COMMON.Consts.ConstOrderSetting_Asc) {
        if (sortType == 3) {
            sortOrder = COMMON.Consts.ConstOrderSetting_Desc;
        }
    } else {
        sortOrder = COMMON.Consts.ConstOrderSetting_Asc;
    }
    ClientData.searchCond_sortOrder(sortOrder);

    HEADER.setStatusSort('#control-sort-releasedate', sortOrder == COMMON.Consts.ConstOrderSetting_Asc);

    sortType = 3;
    // refresh gridview
    HOME.refreshGrid();

    ClientData.searchCond_sortType(sortType);
    HOME.renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordOffset, recordLimit, genreId, groupId);

};

// Handle language
HOME.handleLanguage = function() {

    if (I18N.getCurrentLanguage() == COMMON.Consts.ConstLanguage_En || I18N.getCurrentLanguage() == COMMON.Consts.ConstLanguage_Ko) {
        $('#control-sort-titlekana').css('display', 'none');
        $('#separate').css('display', 'none');
        $('#titlekana-sorttype').html('');
    } else {
        $('#control-sort-titlekana').css('display', 'inline');
        $('#separate').css('display', 'inline');
        if (ClientData.searchCond_sortOrder() != null && ClientData.searchCond_sortOrder() != 'undefined' || ClientData.searchCond_sortType() != '') {
            var typeSort = ClientData.searchCond_sortType();
            var orderSort = ClientData.searchCond_sortOrder();
            HEADER.setStatusSort('#' + $('#menu_sort li.current a').attr('id'), orderSort == COMMON.Consts.ConstOrderSetting_Asc);
        }
    }
};

// /Render Content
HOME.renderContent = function(id, text, division, type, order, offset, limit, cateid, grpid) {
    var params = {
        sid : id,
        searchText : text,
        searchDivision : division,
        sortType : type,
        sortOrder : order,
        recordFrom : offset,
        recordTo : limit,
        genreId : cateid,
        groupId : grpid
    };

    HOME.abapi('webContentList', params, 'POST', function(data) {

        var countCnt = 0;
        var versionArr = ClientData.ResourceVersion();
        var metaArr = ClientData.MetaVersion();
        var readArr = ClientData.ReadingContentIds();

        $.each(data.contentList, function(i, post) {

            var outputDate = COMMON.formatDeliveryDate(post.contentDeliveryDate);

            if (HOME.isShowBookShelf) {
                $('#content-grid').append(
                        '<section class="sectionhomebookshelf" id="bookshelf' + post.contentId + '">'
                        + '	<div class="cnt_section_bookshelf">'
                        + '		<div class="img">'
                        + '			<canvas height="150" width="150" id="content-thumbnail' + post.contentId + '" contentid="' + post.contentId + '" style="display:none;"></canvas>'
                        + '		</div>'
                        + '	    <img id="loadingIcon' + post.contentId + '" src="./img/data_loading.gif" height="25px" width="25px" style="padding: 86px; "/>'
                        + '	</div>'
                        + ' <a id="title' + post.contentId + '" class="name dialog lang" lang="lblTitle" contentid="' + post.contentId + '">'
                        + '		<img src="' + HEADER.getIconTypeContent(post.contentType) + '" width="20" height="20">'
                        + '		<div class="content-title" style="float:right;text-indent:0px">' + post.contentTitle + '</div>'
                        + ' </a>'
                        + '</section>'
                    );

                if ((HOME.home_realTotalRecord + i + 1) % 3 == 0) {
                    $('#bookshelf' + post.contentId).addClass('no_m_right');
                }
                HOME.getNextRecordNumForBookShelf();
            } else {
                var gridHtml = '<section class="sectionhomelist">'
                    + '	<div class="cnt_section_list">'
                    + '		<a class="img">'
                    + '			<canvas height="110" width="150" id="content-thumbnail' + post.contentId + '" contentid="' + post.contentId + '" style="display:none;"></canvas>'
                    + '	        <img id="loadingIcon' + post.contentId + '" src="./img/data_loading.gif" height="25px" width="25px" style="padding: 46px; "/>'
                    + '		</a>'
                    + '		<div class="text">'
                    + '         <a id="title' + post.contentId + '" class="dialog name lang" lang="lblTitle" contentid="' + post.contentId + '">'
                    + '             <img class="listIcon" src="' + HEADER.getIconTypeContent(post.contentType) + '" width="20" height="20" style="float:left">'
                    + ' 			<div class="content-list" style="">' + post.contentTitle + '</div>'
                    + '         </a>'
                    + '			<div class="info">'
                    + '				<ul class="date">'
                    + '					<li><span class="lang" lang="txtPubDt"> </span>:' + outputDate + '</li>'
                    + '					<li><span class="lang" lang="txtViewDt"> </span>:<span id="lblVdate' + post.contentId + '"> </span></li>'
                    + '				</ul>'
                    + '				<ul class="pic">'
                    + '					<li><img src="' + COMMON.DEFAULT_IMG_OPTION_MEMO + '" id="imgMemo' + post.contentId + '" class="sticker"  /></li>'
                    + '					<li><img src="' + COMMON.DEFAULT_IMG_OPTION_MARKING + '" id="imgBookMark' + post.contentId + '" class="pen"  /></li>'
                    + '					<li><ul class="iconList">{share}<li><a class="read lang button-details" contentid="' + post.contentId + '" lang="txtRead">読む</a></li></ul></li>'
                    + '				</ul>'
                    + '			</div>'
                    + '		</div>'
                    + '	</div>'
                    + '</section>';

                var shareHtml = "";
                if (post.readerShare == '1') {
                    shareHtml = '<li><a class="read lang button-share" contentid="' + post.contentId + '" lang="txtShare">共有</a></li>';
                }
                gridHtml = gridHtml.replace(/\{share\}/g, shareHtml);

                $('#content-grid').append(gridHtml);

                HOME.getNextRecordNumForList();
            }

            // assign thumbnail to array
            var formatThumbnail = post.contentThumbnail;
            if ((formatThumbnail != null) && (formatThumbnail != 'undefined') && (formatThumbnail != '')) {
                formatThumbnail = COMMON.formatStringBase64(formatThumbnail);
            }

            HOME.thumbnailArr.push({
                contentId : post.contentId,
                thumbnail : formatThumbnail
            });

            // assign content type to array
            HOME.contentTypeArr.push({
                contentId : post.contentId,
                contentType : post.contentType
            });

            // save alert message level
            LIMIT_ACCESS_CONTENT.messageLevel[post.contentId] = {
                alertMessageLevel : post.alertMessageLevel,
                alertMessage : post.alertMessage
            };

            // Check if user has read this content or not.
            HOME.checkUserHasReadContent(post.contentId, post.resourceVersion, post.metaVersion, versionArr, metaArr, readArr);
            // assign version to array
            COMMON.resourceVersionArr.push({
                contentid : post.contentId,
                resourceversion : post.resourceVersion
            });

            // assign meta version to array
            COMMON.metaVersionArr.push({
                contentid : post.contentId,
                metaversion : post.metaVersion
            });

            // Check if content has marking or memo
            HOME.checkContentMarkingMemoOption(post.contentId);

            // renderViewDate
            var viewdate = HOME.renderViewDate(post.contentId,readArr);
            if (viewdate != null || viewdate != 'undefined') {
                $('#lblVdate' + post.contentId).html(viewdate);
            }
        });

        HOME.home_realTotalRecord += data.contentList.length;
        // Save total record for tree:genere/group

        if (cateid == '' && grpid == '') {
            if (HOME.genre_totalcontent == -1) {
                HOME.genre_totalcontent = data.totalRecord;
            }
            if (HOME.group_totalcontent == -1) {
                HOME.group_totalcontent = data.totalRecord;
            }
        }

        ClientData.searchCond_recordFrom(data.recordFrom);
        ClientData.searchCond_recordTo(data.recordTo);
        HOME.totalPage = data.totalRecord;

        HOME.reRenderPageNumber(ClientData.searchCond_recordTo(), HOME.totalPage);

        // Toggle scroll to top Control
        HOME.handleBackToTop();

        // I18N.changeLanguage(ClientData.userInfo_language());
        I18N.i18nReplaceText();
    });
};

// Initial Screen
HOME.renderGridView = function() {

    var sortType = HOME.DEFAULT_SORT_TYPE;
    var sortOrder = HOME.DEFAULT_SORT_ORDER;
    var searchText = '';
    var searchDivision = HOME.DEFAULT_SEARCH_DIVISION;
    var genreId = '';
    var groupId = '';
    var sid = ClientData.userInfo_sid();

    var offsetPage = 0;
    var limitPage = 0;
    if (HOME.isShowBookShelf) {
        limitPage = HOME.returnNumberDispRecordForBookShelf();
    } else {
        limitPage = HOME.returnNumberDispRecordForList();
    }

    //初期化
    ClientData.searchCond_recordFrom(0);
    ClientData.searchCond_recordTo(0);

    ClientData.searchCond_sortType(sortType);
    ClientData.searchCond_sortOrder(sortOrder);
    ClientData.searchCond_searchText(searchText);
    ClientData.searchCond_searchDivision(searchDivision);
    ClientData.searchCond_genreId(genreId);
    ClientData.searchCond_groupId(groupId);

    // Language Handle
    HOME.handleLanguage();

    // handle
    HOME.handleSortDisp();

    // Refresh GridView
    HOME.refreshGrid();

    HOME.resetShowNextRecordCount();

    // Render Gridview
    HOME.renderContent(sid, searchText, searchDivision, sortType, sortOrder, offsetPage, limitPage, genreId, groupId);
};

// Get Thumnail base on contentid
HOME.returnThumbnail = function(contentid) {
    var iArrCnt = HOME.thumbnailArr.length;
    for ( var i = 0; i < iArrCnt; i++) {
        if (HOME.thumbnailArr[i].contentId == contentid) {
            return HOME.thumbnailArr[i].thumbnail;
        }
    }
};

// Get content type base on contentid
HOME.returnContentType = function(contentid) {
    // Array Length
    var iArrCnt = HOME.contentTypeArr.length;

    // Get contentType in array by contentId
    for ( var i = 0; i < iArrCnt; i++) {
        if (HOME.contentTypeArr[i].contentId == contentid) {
            return HOME.contentTypeArr[i].contentType;
        }
    }
};

// Check if Content Has marking or memo
HOME.checkContentMarkingMemoOption = function(contentId) {

    if (!HOME.isShowBookShelf) {
        // Check if contentid has marking
        if (ClientData.MarkingData().length == 0) {
            $('#imgBookMark' + contentId).css('visibility', 'hidden');
        } else {
            for ( var nIndex1 = 0; nIndex1 < ClientData.MarkingData().length; nIndex1++) {
                if (ClientData.MarkingData()[nIndex1].contentid == contentId) {
                    $('#imgBookMark' + contentId).css('visibility', 'visible');
                    break;
                } else {
                    $('#imgBookMark' + contentId).css('visibility', 'hidden');
                }
            }
        }

        if (ClientData.MemoData().length == 0) {
            $('#imgMemo' + contentId).css('visibility', 'hidden');
        } else {
            // Check if contentid has memo
            for ( var nIndex1 = 0; nIndex1 < ClientData.MemoData().length; nIndex1++) {
                if (ClientData.MemoData()[nIndex1].contentid == contentId) {
                    $('#imgMemo' + contentId).css('visibility', 'visible');
                    break;
                } else {
                    $('#imgMemo' + contentId).css('visibility', 'hidden');
                }
            }
        }

    }
};

// Check if User has read content
HOME.checkUserHasReadContent = function(contId, resourceVer, metaVer, versionArr, metaArr, readArr) {

    var imgThumb = new Image();
    var imgIconNew = new Image();
    var imgIconEdit = new Image();

    var c = document.getElementById('content-thumbnail' + contId);
    var ctx = c.getContext('2d');

    var readFlg = false;
    //var versionArr = ClientData.ResourceVersion();
    //var metaArr = ClientData.MetaVersion();
    //var readArr = ClientData.ReadingContentIds();

    var contentThumbnail = HOME.returnThumbnail(contId);
    var contentType = HOME.returnContentType(contId);

    if (readArr <= 0) {
        imgThumb.onload = function() {
            var resizeImg = HOME.resizeResourceThumbnail(imgThumb, c.width, c.height);
            ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
            imgIconNew.onload = function() {
                ctx.drawImage(imgIconNew, c.width / 2 - resizeImg[0] / 2, c.height - resizeImg[1]);
                $("#loadingIcon" + contId).fadeOut('slow', function() {
                    $('#content-thumbnail' + contId).fadeIn('slow');
                });
            };
            imgIconNew.src = COMMON.DEFAULT_IMG_CONTENT_NEW;
        };

        if (contentThumbnail == '' || contentThumbnail == null) {
            if (!COMMON.isPdfContent(contentType)) {
                var src = HEADER.getThumbnailForOtherType(contentType);
                if (src != '') {
                    imgThumb.src = src;
                }
            }
        } else {
            imgThumb.src = contentThumbnail;
        }

    } else {
        // Check if user has read this content or not
        for ( var nIndex1 = 0; nIndex1 < ClientData.ReadingContentIds().length; nIndex1++) {
            if (ClientData.ReadingContentIds()[nIndex1].contentid == contId) {
                imgThumb.onload = function() {
                    var resizeImg = HOME.resizeResourceThumbnail(imgThumb, c.width, c.height);
                    ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
                    $("#loadingIcon" + contId).fadeOut('slow', function() {
                        $('#content-thumbnail' + contId).fadeIn('slow');
                    });
                };

                if (contentThumbnail == '' || contentThumbnail == null) {
                    if (!COMMON.isPdfContent(contentType)) {
                        var src = HEADER.getThumbnailForOtherType(contentType);
                        if (src != '') {
                            imgThumb.src = src;
                        }
                    }
                } else {
                    imgThumb.src = contentThumbnail;
                }

                readFlg = true;
                break;
            } else {
//				imgThumb.onload = function() {
//					var resizeImg = HOME.resizeResourceThumbnail(imgThumb, c.width, c.height);
//					ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
//					imgIconNew.onload = function() {
//						ctx.drawImage(imgIconNew, c.width / 2 - resizeImg[0] / 2, c.height - resizeImg[1]);
//						$("#loadingIcon" + contId).fadeOut('slow', function() {
//							$('#content-thumbnail' + contId).fadeIn('slow');
//						});
//					};
//					imgIconNew.src = COMMON.DEFAULT_IMG_CONTENT_NEW;
//				};
//				// Start Function : No.12 -- Editor : Le Long -- Date :
//				// 07/31/2013 -- Summary : Check contentType to set thumbnail.
//
//				if (contentThumbnail == '' || contentThumbnail == null) {
//					if (!COMMON.isPdfContent(contentType)) {
//						var src = HEADER.getThumbnailForOtherType(contentType);
//						if (src != '') {
//							imgThumb.src = src;
//						}
//					}
//				} else {
//					imgThumb.src = contentThumbnail;
//				}
//
//				// End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013
//				// -- Summary : Check contentType to set thumbnail.
            }
        }
    }

    // Check if resource version has change
    if (readFlg) {
        if (versionArr == null || versionArr <= 0 || versionArr == 'undefined') {
        } else {
            for ( var nIndex2 = 0; nIndex2 < versionArr.length; nIndex2++) {
                if (versionArr[nIndex2].contentid == contId) {
                    if (versionArr[nIndex2].resourceversion != resourceVer) {
                        imgThumb.onload = function() {
                            var resizeImg = HOME.resizeResourceThumbnail(imgThumb, c.width, c.height);
                            ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
                            imgIconEdit.onload = function() {
                                ctx.drawImage(imgIconEdit, c.width / 2 - resizeImg[0] / 2, c.height - resizeImg[1]);

                                $("#loadingIcon" + contId).fadeOut('slow', function() {
                                    $('#content-thumbnail' + contId).fadeIn('slow');
                                });
                            };
                            imgIconEdit.src = COMMON.DEFAULT_IMG_CONTENT_EDIT;
                        };

                        if (contentThumbnail == '' || contentThumbnail == null) {
                            if (!COMMON.isPdfContent(contentType)) {
                                var src = HEADER.getThumbnailForOtherType(contentType);
                                if (src != '') {
                                    imgThumb.src = src;
                                }
                            }
                        } else {
                            imgThumb.src = contentThumbnail;
                        }

                        break;
                    }
                }
            }
        }

        if (metaArr == null || metaArr <= 0 || metaArr == 'undefined') {
        } else {
            for ( var nIndex2 = 0; nIndex2 < metaArr.length; nIndex2++) {
                if (metaArr[nIndex2].contentid == contId) {
                    if (metaArr[nIndex2].metaversion != metaVer) {
                        imgThumb.onload = function() {
                            var resizeImg = HOME.resizeResourceThumbnail(imgThumb, c.width, c.height);
                            ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
                            imgIconEdit.onload = function() {
                                ctx.drawImage(imgIconEdit, c.width / 2 - resizeImg[0] / 2, c.height - resizeImg[1]);
                                $("#loadingIcon" + contId).fadeOut('slow', function() {
                                    $('#content-thumbnail' + contId).fadeIn('slow');
                                });
                            };
                            imgIconEdit.src = COMMON.DEFAULT_IMG_CONTENT_EDIT;
                        };

                        if (contentThumbnail == '' || contentThumbnail == null) {
                            if (!COMMON.isPdfContent(contentType)) {
                                var src = HEADER.getThumbnailForOtherType(contentType);
                                if (src != '') {
                                    imgThumb.src = src;
                                }
                            }
                        } else {
                            imgThumb.src = contentThumbnail;
                        }

                        break;
                    }
                }
            }
        }
    } else {
        imgThumb.onload = function() {
            var resizeImg = HOME.resizeResourceThumbnail(imgThumb, c.width, c.height);
            ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
            imgIconNew.onload = function() {
                ctx.drawImage(imgIconNew, c.width / 2 - resizeImg[0] / 2, c.height - resizeImg[1]);
                $("#loadingIcon" + contId).fadeOut('slow', function() {
                    $('#content-thumbnail' + contId).fadeIn('slow');
                });
            };
            imgIconNew.src = COMMON.DEFAULT_IMG_CONTENT_NEW;
        };

        if (contentThumbnail == '' || contentThumbnail == null) {
            if (!COMMON.isPdfContent(contentType)) {
                var src = HEADER.getThumbnailForOtherType(contentType);
                if (src != '') {
                    imgThumb.src = src;
                }
            }
        } else {
            imgThumb.src = contentThumbnail;
        }

    }
};

// draw Edit Image
HOME.drawEditImage = function(id) {
    var img = new Image();
    var imgSrc = HOME.returnThumbnail(id);

    if (imgSrc != null) {
    } else {
        var contentType = HOME.returnContentType(id);

        var src = HEADER.getThumbnailForOtherType(contentType);
        if (src != '') {
            imgSrc = src;
        }
    }

    var c = document.getElementById('content-thumbnail' + id);

    // use getContext to use the canvas for drawing
    var ctx = c.getContext('2d');
    ctx.clearRect(0, 0, c.width, c.height);
    img.onload = function() {
        var resizeImg = HOME.resizeResourceThumbnail(img, c.width, c.height);
        ctx.drawImage(img, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
        $("#loadingIcon" + id).fadeOut('slow', function() {
            $('#content-thumbnail' + id).fadeIn('slow');
        });
    };

    img.src = imgSrc;
};

// Render User view date
HOME.renderViewDate = function(id, readArr) {
    for ( var i = 0; i < readArr.length; i++) {
        if (readArr[i].contentid == id) {
            return readArr[i].viewdate;
        }
    }
};

// handle display sort direction
HOME.handleSortDisp = function() {
    $('#control-sort-title').removeClass('active_tops');
    $('#control-sort-titlekana').removeClass('active_tops');
    $('#control-sort-releasedate').removeClass('active_tops');

    var typeSort;
    var orderSort;

    if (ClientData.searchCond_sortType() == null || ClientData.searchCond_sortType() == 'undefined' || ClientData.searchCond_sortType() == '') {
        $('#title-sorttype').html('');
        $('#title-sorttype').html('');
        $('#titlekana-sorttype').html('');
        $('#rDate-sorttype').html('');
    } else {
        if (ClientData.searchCond_sortOrder() != null && ClientData.searchCond_sortOrder() != 'undefined' || ClientData.searchCond_sortType() != '') {
            typeSort = ClientData.searchCond_sortType();
            orderSort = ClientData.searchCond_sortOrder();

            if (typeSort == 1) {
                HEADER.setStatusSort('#control-sort-title', orderSort == COMMON.Consts.ConstOrderSetting_Asc);
            } else if (typeSort == 2) {
                HEADER.setStatusSort('#control-sort-titlekana', orderSort == COMMON.Consts.ConstOrderSetting_Asc);
            } else if (typeSort == 3) {
                HEADER.setStatusSort('#control-sort-releasedate', orderSort == COMMON.Consts.ConstOrderSetting_Asc);
            }
        }
    }
};

// Get Number Disp Record For List
HOME.returnNumberDispRecordForBookShelf = function() {
    var toPage = 0;
    var sysSettings = AVWEB.avwSysSetting();
    toPage = sysSettings.bookShelfCount;
    return toPage;
};

// Get Number Disp Record For List
HOME.returnNumberDispRecordForList = function() {
    var toPage = 0;
    var sysSettings = AVWEB.avwSysSetting();
    toPage = sysSettings.bookListCount;
    return toPage;
};

// Get number record disp next for list
HOME.getNextRecordNumForList = function() {
    HOME.iNumberOfNextRecord = HOME.returnNumberDispRecordForList();
};

// Get number record disp next for bookshelf
HOME.getNextRecordNumForBookShelf = function() {
    HOME.iNumberOfNextRecord = HOME.returnNumberDispRecordForBookShelf();
};

// refresh sort order
HOME.refreshSortTypeOrder = function() {
    $('#title-sorttype').html('');
    $('#titlekana-sorttype').html('');
    $('#rDate-sorttype').html('');
    $('#rDate-sorttype').html('');
};

// refresh GridView
HOME.refreshGrid = function() {
    $('#control-nextrecord').hide();
    $('#content-grid').html('');
    $('.pageNumControl').css('visibility', 'hidden');
};

// format text display more record
HOME.formatDisplayMoreRecord = function() {

    // I18N.changeLanguage(ClientData.userInfo_language());
    I18N.i18nReplaceText();

    if (HOME.isShowBookShelf) {
        $('#control-nextrecord').html(AVWEB.format(I18N.i18nText('dspViewMore'), HOME.returnNumberDispRecordForBookShelf()).toString());
    } else {
        $('#control-nextrecord').html(AVWEB.format(I18N.i18nText('dspViewMore'), HOME.returnNumberDispRecordForList()));
    }

};

/*
 * Check content whether existed or not
 */
HOME.IsExistContent = function(strContentId) {
    var isExisted = true;
    var params = {
        sid : ClientData.userInfo_sid(),
        getType : '1',
        contentId : strContentId
    };
    AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", 'GET', params, function(data) {
        isExisted = true;
    }, 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 isExisted;
};

//HOME.syncReadingContent = function() {
//	var readArr = ClientData.ReadingContentIds();
//	var metaArr = ClientData.MetaVersion();
//	var resourceArr = ClientData.ResourceVersion();
//
//	for ( var i = readArr.length - 1; i >= 0; i--) {
//		var readContent = readArr[i];
//
//		if (!HOME.IsExistContent(readContent.contentid)) {
//
//			HOME.errorContent.push({
//				contentid : readContent.contentid
//			});
//			readArr.splice(i, 1);
//			metaArr.splice(i, 1);
//			resourceArr.splice(i, 1);
//		}
//		// Do not process next
//		if (AVWEB.avwHasError()) {
//			return;
//		}
//	}
//
//	ClientData.ReadingContentIds(readArr);
//	ClientData.MetaVersion(metaArr);
//	ClientData.ResourceVersion(resourceArr);
//};

HOME.syncReadingContent = function(readArr) {
    //var readArr = ClientData.ReadingContentIds();
    //100件以下なら行わない
    if(readArr.length <= HOME.historyBuffer){
        //console.log("readArr.length:" + readArr.length);
        return;
    }

    var metaArr = ClientData.MetaVersion();
    var resourceArr = ClientData.ResourceVersion();

    //閲覧日順に並び替える
    var temp;
    for ( var i = 0; i < readArr.length; i++) {
        for ( var j = readArr.length - 1; j > i; j--) {
            if (readArr[j].originviewdate > readArr[j - 1].originviewdate) {
                temp = readArr[j];
                readArr[j] = readArr[j - 1];
                readArr[j - 1] = temp;
            }
        }
    }

    //後ろから100件移行捨てる
    for ( var i = readArr.length - 1; i >= HOME.historyBuffer; i--) {
        temp = readArr[i];
        readArr.splice(i, 1);

        for ( var j = metaArr.length - 1; j >= 0; j--) {
            if (metaArr[j].contentid == temp.contentid) {
                //削除
                metaArr.splice(j, 1);
            }
        }
        for ( var j = resourceArr.length - 1; j >= 0; j--) {
            if (resourceArr[j].contentid == temp.contentid) {
                //削除
                resourceArr.splice(j, 1);
            }
        }

        // Do not process next
        if (AVWEB.avwHasError()) {
            return;
        }

    }

    //console.log("readArr.length:" + readArr.length);
    //console.log("metaArr.length:" + metaArr.length);
    //console.log("resourceArr.length:" + resourceArr.length);
    ClientData.ReadingContentIds(readArr);
    ClientData.MetaVersion(metaArr);
    ClientData.ResourceVersion(resourceArr);
};

HOME.syncBookmarkContent = function() {
    var arrBookmark = ClientData.BookMarkData();

    for ( var j = arrBookmark.length - 1; j >= 0; j--) {
        var bookmark = arrBookmark[j];

        if (HOME.isErrorContent(bookmark.contentid)) {
            arrBookmark.splice(j, 1);
        } else {
            if (!HOME.IsExistContent(bookmark.contentid)) {
                HOME.errorContent.push({
                    contentid : bookmark.contentid
                });
                arrBookmark.splice(j, 1);
                ClientData.isChangedBookmark(true);
            }
        }
    }

    ClientData.BookMarkData(arrBookmark);
};

HOME.syncMemoContent = function() {
    var arrMemo = ClientData.MemoData();

    for ( var j = arrMemo.length - 1; j >= 0; j--) {
        var memo = arrMemo[j];

        if (HOME.isErrorContent(memo.contentid)) {
            arrMemo.splice(j, 1);
        } else {
            if (!HOME.IsExistContent(memo.contentid)) {
                HOME.errorContent.push({
                    contentid : memo.contentid
                });
                arrMemo.splice(j, 1);
                ClientData.isChangedMemo(true);
            }
        }
    }

    ClientData.MemoData(arrMemo);
};

HOME.syncMarkingContent = function() {

    var arrMarking = ClientData.MarkingData();

    for ( var j = arrMarking.length - 1; j >= 0; j--) {
        var marking = arrMarking[j];

        if (HOME.isErrorContent(marking.contentid)) {
            arrMarking.splice(j, 1);
        } else {
            if (!HOME.IsExistContent(marking.contentid)) {
                HOME.errorContent.push({
                    contentid : marking.contentid
                });
                arrMarking.splice(j, 1);
                ClientData.isChangedMarkingData(true);
            }
        }
    }

    ClientData.MarkingData(arrMarking);
};

HOME.syncContentData = function() {

    var readingContentIds = ClientData.ReadingContentIds();
    if(readingContentIds.length == 0){
        ClientData.common_contentDataChkFlg(false);
        return;
    }

    if (ClientData.common_contentDataChkFlg() == 'true') {
        HOME.syncReadingContent(readingContentIds);
        HOME.syncBookmarkContent();
        HOME.syncMemoContent();
        HOME.syncMarkingContent();
        HOME.getExistContentPages();
        HOME.SyncMemoPages();
        HOME.SyncMarkingPages();

        ClientData.common_contentDataChkFlg(false);
    }
};

HOME.isErrorContent = function(contentid) {
    var isError = false;
    for ( var j = HOME.errorContent.length - 1; j >= 0; j--) {
        var contentErr = HOME.errorContent[j];
        if (contentid == contentErr.contentid) {
            isError = true;
            break;
        }
    }
    return isError;
};

HOME.getExistContentPages = function() {
    var memoArr = ClientData.MemoData();
    var markingArr = ClientData.MarkingData();

    for ( var i = 0; i < memoArr.length; i++) {
        var memo = memoArr[i];

        HOME.existContent.push({
            contentid : memo.contentid
        });
    }

    for ( var i = 0; i < markingArr.length; i++) {
        var marking = markingArr[i];

        HOME.existContent.push({
            contentid : marking.contentid
        });
    }
};

HOME.SyncMemoPages = function() {
    var arrMemo = ClientData.MemoData();
    for ( var nIndex = 0; nIndex < HOME.existContent.length; nIndex++) {

        // Get one content
        var oneContent = HOME.existContent[nIndex];

        var params = {
            sid : ClientData.userInfo_sid(),
            contentId : oneContent.contentid,
            thumbnailFlg : 0
        };
        var webContentPage;

        // Get all pages of content
        AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webContentPage", 'GET', params, function(data) {
            // Success
            if (data.pages) {
                webContentPage = data.pages;
            }
        }, null);

        if (webContentPage) {
            if (webContentPage.length > 0) {
                for ( var nIndex1 = arrMemo.length - 1; nIndex1 >= 0; nIndex1--) {
                    // Get one bookmar entity
                    var oneMemo = arrMemo[nIndex1];

                    // Found contentid
                    if (oneMemo.contentid == oneContent.contentid) {

                        var isFoundPage = false;
                        for ( var nIndex2 = 0; nIndex2 < webContentPage.length; nIndex2++) {
                            if (oneMemo.pageNo == webContentPage[nIndex2].pageNo) {
                                // Found pageNo
                                isFoundPage = true;
                                break;
                            }
                        }

                        if (!isFoundPage) {
                            arrMemo.splice(nIndex1, 1);
                            ClientData.isChangedMemo(true);
                        }
                    }
                }

            } else { // webContentPage.length = 0
                for ( var nIndex1 = 0; nIndex1 < arrMemo.length; nIndex1++) {
                    // Get one bookmar entity
                    var oneMemo = arrMemo[nIndex1];

                    if (oneMemo.contentid == oneContent.contentid) {
                        arrMemo.splice(nIndex1, 1);
                        ClientData.isChangedMemo(true);
                    }
                }
            }
        }
    }

    ClientData.MemoData(arrMemo);
};

HOME.SyncMarkingPages = function() {
    var arrMarking = ClientData.MarkingData();
    for ( var nIndex = 0; nIndex < HOME.existContent.length; nIndex++) {

        // Get one content
        var oneContent = HOME.existContent[nIndex];

        var params = {
            sid : ClientData.userInfo_sid(),
            contentId : oneContent.contentid,
            thumbnailFlg : 0
        };
        var webContentPage;

        // Get all pages of content
        AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webContentPage", 'GET', params, function(data) {
            // Success
            if (data.pages) {
                webContentPage = data.pages;
            }
        }, null);

        if (webContentPage) {
            if (webContentPage.length > 0) {
                for ( var nIndex1 = arrMarking.length - 1; nIndex1 >= 0; nIndex1--) {
                    // Get one bookmar entity
                    var oneMarking = arrMarking[nIndex1];

                    // Found contentid
                    if (oneMarking.contentid == oneContent.contentid) {

                        var isFoundPage = false;
                        for ( var nIndex2 = 0; nIndex2 < webContentPage.length; nIndex2++) {
                            if (oneMarking.pageNo == webContentPage[nIndex2].pageNo) {
                                // Found pageNo
                                isFoundPage = true;
                                break;
                            }
                        }

                        if (!isFoundPage) {
                            arrMarking.splice(nIndex1, 1);
                            ClientData.isChangedMarkingData(true);
                        }
                    }
                }

            } else { // webContentPage.length = 0
                for ( var nIndex1 = 0; nIndex1 < arrMarking.length; nIndex1++) {
                    // Get one bookmar entity
                    var oneMarking = arrMarking[nIndex1];

                    if (oneMarking.contentid == oneContent.contentid) {
                        arrMarking.splice(nIndex1, 1);
                        ClientData.isChangedMarkingData(true);
                    }
                }
            }
        }
    }

    ClientData.MarkingData(arrMarking);
};

function changeLanguageCallBackFunction() {
    HOME.handleLanguage();
    HOME.formatDisplayMoreRecord();
    document.title = I18N.i18nText('dspHome') + ' | ' + I18N.i18nText('sysAppTitle');
};

HOME.resizeResourceThumbnail = function(mg, width, height) {

    var newWidth;
    var newHeight;
    /*
     * if (mg.width > mg.height) { newWidth = width; newHeight = (mg.height *
     * width) / mg.width; } else { newHeight = height; newWidth = (mg.width *
     * height) / mg.height; }
     */
    var delta = Math.min(width / mg.width, height / mg.height);

    newHeight = parseInt(delta * mg.height);
    newWidth = parseInt(delta * mg.width);

    var result = [ newWidth, newHeight ];
    return result;

};

HOME.resetShowNextRecordCount = function() {
    HOME.showNextRecordClickNumber = 1;
};

HOME.setDefaultViewMode = function() {
    if (ClientData.sortOpt_viewMode() == COMMON.Consts.ConstDisplayMode_BookShelf) {
        HOME.isShowBookShelf = true;
        $('body').attr('id', 'bookshelf');
        $('#control-bookshelf-type').parent().removeClass("thumbnail");
        $('#control-bookshelf-type').parent().addClass("thumbnail_select");
        $('#control-list-type').parent().removeClass("list_select");
        $('#control-list-type').parent().addClass("list");
    } else if (ClientData.sortOpt_viewMode() == COMMON.Consts.ConstDisplayMode_List) {
        HOME.isShowBookShelf = false;
        $('body').attr('id', 'list');
        $('#control-list-type').parent().removeClass("list");
        $('#control-list-type').parent().addClass("list_select");
        $('#control-bookshelf-type').parent().removeClass("thumbnail_select");
        $('#control-bookshelf-type').parent().addClass("thumbnail");
    } else {
        HOME.isShowBookShelf = true;
        $('body').attr('id', 'bookshelf');
        $('#control-bookshelf-type').parent().removeClass("thumbnail");
        $('#control-bookshelf-type').parent().addClass("thumbnail_select");
        $('#control-list-type').parent().removeClass("list_select");
        $('#control-list-type').parent().addClass("list");
    }
};

HOME.removeHoverCss = function() {
    if (COMMON.isTouchDevice()) {
        $('#control-sort-title').removeClass('nottouchdevice');
        $('#control-sort-titlekana').removeClass('nottouchdevice');
        $('#control-sort-releasedate').removeClass('nottouchdevice');
    }
};

// Dialog Read Button CLick
HOME.showContentShareDlgFunction = function(e) {

    if (e) {
        e.preventDefault();
    }

    if (HOME.home_isMove == true) {
        HOME.home_isMove = false;
        return;
    }

	var contentId = $(this).attr('contentid');
	// check limit of content
//	LIMIT_ACCESS_CONTENT.checkLimitContent(contentId, function() {
		SHARE.contentId = contentId;
		SHARE.contentTitle = "";
		SHARE.openContentShare();
//	}, function() {
//		// console.log("checkLimitContent_bbb");
//	});

};

$(function() {
    HOME.cssInit();
});

HOME.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'
    });
};

HOME.showContentView = function() {

    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;
    }
    HOME.scrollTop = y;
    window.scrollTo(0, 0);

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

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

    // CONTENTVIEW_FILESYSTEM.initFS(CONTENTVIEW.ready);
    CONTENTVIEW.ready();

};

// Dialog Read Button CLick
HOME.downloadSubmenuFunction = function(e) {
    if (e) {
        e.preventDefault();
    }
    HOME.allowTimerCloseSubMenu = false;

    if (HOME.home_isMove == true) {
        HOME.home_isMove = false;
        return;
    }

    // hide dialog sub menu
    $('#dlgSubMenu').hide();

    var contentId = $(this).attr('contentid');

    // Download content
    HEADER.downloadResourceById(contentId);

};