/// <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="header.js" />

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

var DEFAULT_IMG_OPTION_MEMO = 'img/list/icon_sticker.png';
var DEFAULT_IMG_OPTION_MARKING = 'img/list/icon_pen.png';
var DEFAULT_IMG_CONTENT_EDIT = 'img/common/band_updated.png';
var DEFAULT_IMG_CONTENT_NEW = 'img/common/band_new.png';
var home_realTotalRecord = 0;

var iNumberOfNextRecord = 15;
//Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Create new Array for function No.12.
//Thumbnail array
var thumbnailArr = [];
//Content type array.
var contentTypeArr = [];

var ThumbnailForOtherType = {
    Thumbnail_ImageType : 'img/image_type.png',
    Thumbnail_VideoType : 'img/iPad_video.png',
    Thumbnail_MusicType : 'img/thumb_default_sound.png',
    Thumbnail_OthersType : 'img/thumb_default_other.png',
    Thumbnail_NoFileType : 'img/thumb_default_none.png',
    Thumbnail_HtmlType :  'img/thumb_default_html.png'
};
//End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Create new Array for function No.12.

var contentIdArray = [];
var resourceVersionArr = [];
var metaVersionArr = [];
var errorPage = [];
var errorContent = [];
var dataGroup;
var dataGenre;
var totalPage;
var existContent = [];
var isSubMenuHoverOn = false;
var home_isMove = false;
var isShowBookShelf = null;
var showNextRecordClickNumber = 1;

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

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

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

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

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

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

        //Sync Data
        if (ClientData.ReadingContentIds() == null || ClientData.ReadingContentIds() == 'undefined' || ClientData.ReadingContentIds().length == 0) {
            ClientData.common_contentDataChkFlg(false);
        } else {
            syncContentData();
        }

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

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

        //Toggle TreeView Disp
        handleTreeViewDisp();

        //Format text display more record
        formatDisplayMoreRecord();

        //Render Grid
        renderGridView();

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

        // Lock screen is here, because of in getDataJsonFileGroup() called click to expand speified nodes of treeview
        LockScreen();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $('body').click(bodyHomeClickFunction);
        if (isTouchDevice() == true) {
            var avwUserEnvObj = new UserEnvironment();
            if (avwUserEnvObj.os == 'ipad') {
                $('body').bind('touchstart', function () {
                    if ($('#dlgSubMenu').css('display') != "none") {
                        allowTimerCloseSubMenu = true;
                        timer_subMenu = setTimeout("startTimerCloseMenu();", 500);
                    }
                });
            }
            else {
                $('body').bind('touchstart', 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 {
        checkForceChangePassword();
    }

    // hide tab group with user anonymous
    if (isAnonymousLogin()) {
    	//カタログエディション対応判定
    	if( ClientData.serviceOpt_catalog_edition() == 'Y'){
        	$('.tabUnit').hide();
        	//センタリングするようサイズ調整
        	$('#main').width(660);
        	
    	} else {
            $('.tabUnit').show();
            $('.switchingTab .colright').hide();
    	}
    	//日比谷対応判定
    	if( ClientData.serviceOpt_hibiyakadan_catalog() == 'Y'){
        	$('#dspHibiya').show();
        	
			jQuery( '#dlgAddMemberGroup' ).dialog( {
				autoOpen: false,
				modal: true,
				width: 350
			});
			$('#dspHibiya').click(dspHibiyaClickFunction);
			$('#btnAddMemberGroupSearch').click(btnAddMemberGroupSearchClickFunction);
			
    	} else {
        	$('#dspHibiya').hide();
    	}
    	
    	//プッシュメッセージ隠す
    	$('#dspPushMessage').hide();
    	
    } else {
        $('.tabUnit').show();
        $('.switchingTab .colright').show();
	}
	
	// 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" });
	}
	//if (isIE9()) {
	//	$('.tab_bg_color').css({ "overflow-x": "scroll" });
	//}

});

//日比谷カスタム ここから
function dspHibiyaClickFunction(){
	$( '#dlgAddMemberGroup' ).dialog( 'open' );
}
function btnAddMemberGroupSearchClickFunction(){
	
	var addGroupName = $('#txtAddMemberGroupName').val();
	if( addGroupName == "" ){
		return;
	}
	
	var groupIds = getAddMemberGroupId(addGroupName);
	if( groupIds == "" ){
		alert("コードが不正です");
		return;
	}
	
	$( '#dlgAddMemberGroup' ).dialog( 'close' );
	ClientData.searchCond_groupId(groupIds);
	
	//画面再描画開始
    var recordFrom = 0;
    var recordTo = 0;

    if (isShowBookShelf) {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = returnNumberDispRecordForBookShelf();
    }
    else if (!isShowBookShelf) {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = returnNumberDispRecordForList();
    }
    else {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = 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
    refreshGrid();

    resetShowNextRecordCount();

    handleSortDisp();

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

function getAddMemberGroupId(strGroupName) {

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


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

function subMenuHoverFunction() {
    isSubMenuHoverOn = true;
};

function subMenuHoverOffFunction() {
    isSubMenuHoverOn = false;
};

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

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

//Change Display BookShelf Function
function changeDispBookShelfFunction() {
    if (isShowBookShelf == false) {
        //ClientData.sortOpt_viewMode(Consts.ConstDisplayMode_BookShelf);

        isShowBookShelf = true;
        var recordFrom = 0;
        var recordTo = 0;

        //Start : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
        $('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");
        //End : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon

        // if(ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_BookShelf){	
        if (isShowBookShelf) {
            recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
            recordTo = returnNumberDispRecordForBookShelf() * showNextRecordClickNumber;
        }
        //refresh sort order
        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
        handleSortDisp();

        //refresh Grid view
        refreshGrid();

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

        //format text disp more record
        formatDisplayMoreRecord();

        //Get next record will be displayed
        getNextRecordNumForBookShelf();
    }
};

//Change Display List Function
function changeDispListFunction() {
    if (isShowBookShelf == true) {
        //ClientData.sortOpt_viewMode(Consts.ConstDisplayMode_List);

        isShowBookShelf = false;
        var recordFrom = 0;
        var recordTo = 0;

        //Start : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
        $('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");
        //End : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon

        //Check VIewmode
        // if(ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_List){
        if (!isShowBookShelf) {
            recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
            recordTo = returnNumberDispRecordForList() * showNextRecordClickNumber;
        }

        //refresh sort order
        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
        handleSortDisp();

        //refresh Grid view
        refreshGrid();

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

    //format text disp more record
    formatDisplayMoreRecord();

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

};

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

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

    var contentId = $(this).attr('id');
    var outputId = contentId.substring(17);
    checkLimitContent(outputId,
        function(){
            canvasClickFunction_callback(outputId);
        },
        function(){
        }
    );

};

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

    // Set content id for next screen
    ClientData.contentInfo_contentThumbnail(base64String);
    // Get image of selected image
    ClientData.contentInfo_contentId(outputId);
    
    //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
    var contentType = returnContentType(outputId);
    ClientData.contentInfo_contentType(contentType);
    //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
    
    //Check Display mode to handle action

    if (isShowBookShelf != null) {
        if (!isShowBookShelf) {

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

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

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

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

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

            //Set ResouceVersion for content
            setResourceVersionData(outputId);

            //Set MetaVersion for content
            setMetaVersionData(outputId);

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

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

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

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

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

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

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

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

            //Set ResouceVersion for content
            setResourceVersionData(outputId);

            //Set MetaVersion for content
            setMetaVersionData(outputId);

            //$('body,html').animate({ scrollTop: 0 }, 0);
            ClientData.IsRefresh(false);
            
            //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : check for download content type other.
            //contentType = ContentTypeKeys.Type_Others;
            if(contentType == ContentTypeKeys.Type_Others){                              
                //Download content
                downloadResourceById(outputId);
                // redraw content remove new icon
                drawEditImage(outputId);
            }
            else{                
                //Go to Conten view page
                avwScreenMove(ScreenIds.ContentView);
            }
            //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : check for download content type other.
                    
        }
    } else {
        if (!isShowBookShelf) {

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

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

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

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

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

            //Set ResouceVersion for content
            setResourceVersionData(outputId);

            //Set MetaVersion for content
            setMetaVersionData(outputId);

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

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

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

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

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

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

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

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

            //Set ResouceVersion for content
            setResourceVersionData(outputId);

            //Set MetaVersion for content
            setMetaVersionData(outputId);

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

            //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.           
            //For testing without other Type.
            //contentType = ContentTypeKeys.Type_Others;
            
            if(contentType == ContentTypeKeys.Type_Others){
                //Download content
                downloadResourceById(outputId);

                 // redraw content remove new icon
                drawEditImage(outputId);

            }
            else{
                //Go to Conten view page
                avwScreenMove(ScreenIds.ContentView);
            }
            //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
        }
    }

};



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


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

    if (isShowBookShelf != null) {
        if (!isShowBookShelf) {
            // Get image of selected image
            var base64String = returnThumbnail(contentid);
            ClientData.contentInfo_contentThumbnail(base64String);
            ClientData.contentInfo_contentId(contentid);
            
            //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
            var contentType = returnContentType(contentid);
            ClientData.contentInfo_contentType(contentType);
            //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
            
            //Store Content id that user has read
            if (ClientData.ReadingContentIds().length > 0) {
                contentIdArray = ClientData.ReadingContentIds();

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

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

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

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

            //Set ResouceVersion for content
            setResourceVersionData(contentid);

            //Set MetaVersion for content
            setMetaVersionData(contentid);

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

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

            openContentDetail();

        }
        else if (isShowBookShelf) {
            $('#dialog-read').attr('contentid', contentid);
            $('#dialog-detail').attr('contentid', contentid);
            //$("#dlgSubMenu").dialog({position: array, width: 130, height: 90});
            $("#dlgSubMenu").show();
            allowTimerCloseSubMenu = false;
            $("#dlgSubMenu").position({ my: "left bottom",
                at: "left-10 top",
                of: this,
                collision: "fit"
            });
        }
        else {
            $('#dialog-read').attr('contentid', contentid);
            $('#dialog-detail').attr('contentid', contentid);
            //$("#dlgSubMenu").dialog({position: array, width: 130, height: 90});
            $("#dlgSubMenu").show();
            allowTimerCloseSubMenu = false;
            $("#dlgSubMenu").position({ my: "left bottom",
                at: "left-10 top",
                of: this,
                collision: "fit"
            });
        }
    }   
    else {
        if (!isShowBookShelf) {
            // Get image of selected image
            var base64String = returnThumbnail(contentid);
            ClientData.contentInfo_contentThumbnail(base64String);
            ClientData.contentInfo_contentId(contentid);
            
            //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
            var contentType = returnContentType(contentid);
            ClientData.contentInfo_contentType(contentType);
            //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
            
            //Store Content id that user has read
            if (ClientData.ReadingContentIds().length > 0) {
                contentIdArray = ClientData.ReadingContentIds();

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

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

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

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

            //Set ResouceVersion for content
            setResourceVersionData(contentid);

            //Set MetaVersion for content
            setMetaVersionData(contentid);

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

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

            openContentDetail();

        }
        else if (isShowBookShelf) {
            $('#dialog-read').attr('contentid', contentid);
            $('#dialog-detail').attr('contentid', contentid);
            //$("#dlgSubMenu").dialog({position: array, width: 130, height: 90});
            $("#dlgSubMenu").show();
            allowTimerCloseSubMenu = false;
            $("#dlgSubMenu").position({ my: "left bottom",
                at: "left-10 top",
                of: this,
                collision: "fit"
            });
        }
        else {
            $('#dialog-read').attr('contentid', contentid);
            $('#dialog-detail').attr('contentid', contentid);
            //$("#dlgSubMenu").dialog({position: array, width: 130, height: 90});
            $("#dlgSubMenu").show();
            allowTimerCloseSubMenu = false;
            $("#dlgSubMenu").position({ my: "left bottom",
                at: "left-10 top",
                of: this,
                collision: "fit"
            });
        }
    }
};

//Genre Click Function
function genreSelectFunction() {
    $('.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 recordFrom = 0;
    var recordTo = 0;

    if (isShowBookShelf) {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = returnNumberDispRecordForBookShelf();
    }
    else if (!isShowBookShelf) {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = returnNumberDispRecordForList();
    }
    else {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        recordTo = 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
    refreshGrid();

    resetShowNextRecordCount();

    handleSortDisp();

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

//Group Click Function
function groupSelectFunction() {
    $('.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 recordFrom = 0;
    var recordTo = 0;

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

    //ClientData.searchCond_sortOrder(DEFAULT_SORT_ORDER);
    //ClientData.searchCond_sortType(DEFAULT_SORT_TYPE);

    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
    refreshGrid();

    resetShowNextRecordCount();

    handleSortDisp();

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

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

        $.each(dataGenre, function (i, value) {
            // Calculate total content
            totalCount += Number(dataGenre[i].contentCount);
            if (dataGenre[i].parentCategoryId == 0) {
                var node = new TreeNode();
                //node.IsCategory = true;
                node.Text = htmlEncode(dataGenre[i].categoryName);
                node.id = dataGenre[i].categoryId;
                node.Value = dataGenre[i].categoryId;
                node.ContentCount = dataGenre[i].contentCount;
                AddChidrenNodeGenre(node);
                node.IsClosed = false;
                node.IsCategory = node.ChildNodes.length > 0; // Has child node

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

        $('#all').css('font-weight', 'bold');
        $('#all').css('text-decoration', 'underline');
        
        $('.treeview > li').addClass('tabCategory');
    });
};

//Add Children Node Category
function AddChidrenNodeGenre(node1) {
    var dataChild = [];
    $.each(dataGenre, function (index, value) {
        if (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 == dataGenre[index].categoryId) {
                    isChildNodeExisted = true;
                }
            }
            if(!isChildNodeExisted) {
                dataChild.push(dataGenre[index]);
            }
            //dataChild.push(dataGenre[index]);
        }
    });

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

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

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

//Get Value for sort
function AddGenre_Callback(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();
    var recordFrom = 0;
    var recordTo = 0;
    node = selectedNode;

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

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

    ClientData.searchCond_genreId(lCateId);
    //ClientData.searchCond_sortOrder(DEFAULT_SORT_ORDER);
    //ClientData.searchCond_sortType(DEFAULT_SORT_TYPE);

    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
    refreshGrid();

    resetShowNextRecordCount();

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

    handleSortDisp();
};

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

            if (dataGroup[i].parentGroupId == 0 || dataGroup[i].groupLevel == "0") {
                var node = new TreeNode();
                node.IsCategory = true;
                node.Text = htmlEncode(dataGroup[i].groupName);
                node.id = dataGroup[i].groupId;
                node.Value = dataGroup[i].groupId;
                node.ContentCount = dataGroup[i].contentCount;
                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 (group_totalcontent != -1) {
            tree2.TotalCount = group_totalcontent;
        }
        tree2.Show("branch2", arrData, "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
function AddChidrenNodeGroup(node1) {
    var dataChild = [];
    $.each(dataGroup, function (index, value) {
        if (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 == dataGroup[index].groupId) {
                    isChildNodeExisted = true;
                }
            }
            if(!isChildNodeExisted) {
                dataChild.push(dataGroup[index]);
            }
            //dataChild.push(dataGroup[index]);
        }
    });

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

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

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

//Get Value for sort
function AddGroup_Callback(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();
    var recordFrom = 0;
    var recordTo = 0;

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

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

    ClientData.searchCond_groupId(lGrpId);
    //ClientData.searchCond_sortOrder(DEFAULT_SORT_ORDER);
    //ClientData.searchCond_sortType(DEFAULT_SORT_TYPE);

    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
    refreshGrid();

    resetShowNextRecordCount();

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

    handleSortDisp();
};

//Re-render page from and total record
function reRenderPageNumber(dispRecord, dispTotal) {
    $('#dispPage').html(dispRecord);
    $('#totalPage').html(dispTotal);
    $('.pageNumControl').css('visibility', 'visible');
};

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

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

    var contentId = $(this).attr('contentid');
    // Get image of selected image
    var base64String = returnThumbnail(contentId);
    //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Set contentType of content to local storage for display details.
    var contentType = returnContentType(contentId);
    ClientData.contentInfo_contentType(contentType);
    //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Set contentType of content to local storage for display details.
    ClientData.contentInfo_contentId(contentId);
    ClientData.contentInfo_contentThumbnail(base64String);
    
    
    
    //Store Content id that user has read
    if (ClientData.ReadingContentIds().length > 0) {
        contentIdArray = ClientData.ReadingContentIds();

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

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

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

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

    //Set ResouceVersion for content
    setResourceVersionData(contentId);

    //Set MetaVersion for content
    setMetaVersionData(contentId);

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

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

    // Show detail
    openContentDetail();
};

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

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

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

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

};

//Dialog Read Button CLick callback
function readSubmenuFunction_callback(contentId)
{
    var contentThumbnail = returnThumbnail(contentId);
           
    var date = new Date();
    var month = date.getMonth() + 1;
    var day = date.getDate();

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

    ClientData.contentInfo_contentId(contentId);
    ClientData.contentInfo_contentThumbnail(contentThumbnail);
    
    //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
    var contentType = returnContentType(contentId);
    ClientData.contentInfo_contentType(contentType);
    //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
    
    var checkflag = false;

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

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

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

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

    //Set ResouceVersion for content
    setResourceVersionData(contentId);

    //Set MetaVersion for content
    setMetaVersionData(contentId);

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

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

    //$('body,html').animate({ scrollTop: 0 }, 0);
    ClientData.IsRefresh(false);
    
    //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.           
    //For testing without other Type.
    //contentType = ContentTypeKeys.Type_Others;
    
    if(contentType == ContentTypeKeys.Type_Others){
        //Download content
        downloadResourceById(contentId);

         // redraw content remove new icon
        drawEditImage(contentId);

    }
    else{
        //Go to Conten view page
        avwScreenMove(ScreenIds.ContentView);
    }
    //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Add ContentType to Storage.
};

//Handle Back To Top Button
function handleBackToTop() {

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

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

};

//Show Next Record Function
function showNextRecordFunction() {

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

    //Count number of click
    showNextRecordClickNumber = 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 = totalPage;

    if (fromPage == null || fromPage == 'undefined') {
        fromPage = DEFAULT_DISP_NUMBER_RECORD_FROM;
    }

    if (toPage == null || toPage == 'undefined') {
        if (isShowBookShelf) {
            toPage = returnNumberDispRecordForBookShelf();
        }
        else if (!isShowBookShelf) {
            toPage = returnNumberDispRecordForList();
        }
        else {
            toPage = returnNumberDispRecordForBookShelf();
        }
    }

    fromPage = eval(toPage) + 1;
    var iRecordNumber = eval(totalrecord) - eval(fromPage);

    if (iRecordNumber < iNumberOfNextRecord) {
        toPage = eval(fromPage) + eval(iRecordNumber);
    }
    else {
        toPage = eval(fromPage) + (eval(iNumberOfNextRecord) - 1);
    }

    ClientData.searchCond_recordFrom(fromPage);
    ClientData.searchCond_recordTo(toPage);

    if (fromPage <= totalrecord) {
        renderContent(sid, searchText, searchDivision, sortType, sortOrder, fromPage, toPage, genreId, groupId);
    }
};

//Sort By Title Function
function sortByTitleFunction() {

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

    //$(this).addClass('active_tops');

//    $('#control-sort-title').addClass('active_tops');
//    $('#control-sort-titlekana').removeClass('active_tops');
//    $('#control-sort-releasedate').removeClass('active_tops');

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

    if (sortOrder == Consts.ConstOrderSetting_Asc) {
        if (sortType == 1) {
            sortOrder = Consts.ConstOrderSetting_Desc;
//            $('#title-sorttype').html('');
//            $('#title-sorttype').html('▼');
//            $('#title-sorttype').css('width', '12px');
//            $('#titlekana-sorttype').html('');
//            $('#rDate-sorttype').html('');
        }
        else {
            sortOrder = Consts.ConstOrderSetting_Asc;
//            $('#title-sorttype').html('');
//            $('#title-sorttype').html('▲');
//            $('#title-sorttype').css('width', '12px');
//            $('#titlekana-sorttype').html('');
//            $('#rDate-sorttype').html('');
        }
        ClientData.searchCond_sortOrder(sortOrder);
    }
    else {
        sortOrder = Consts.ConstOrderSetting_Asc;
//        $('#title-sorttype').html('');
//        $('#title-sorttype').html('▲');
//        $('#title-sorttype').css('width', '12px');
//        $('#titlekana-sorttype').html('');
//        $('#rDate-sorttype').html('');
        ClientData.searchCond_sortOrder(sortOrder);
    }

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

    if (recordFrom == null || recordFrom == 'undefined') {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        ClientData.searchCond_recordFrom(recordFrom);
    }

    if (recordTo == null || recordTo == 'undefined') {

        if (isShowBookShelf) {
            recordTo = returnNumberDispRecordForBookShelf();
        }
        else if (!isShowBookShelf) {
            recordTo = returnNumberDispRecordForList();
        }
        else {
            recordTo = returnNumberDispRecordForBookShelf();
        }
        ClientData.searchCond_recordFrom(recordTo);
    }

    sortType = 1;
    ClientData.searchCond_sortType(sortType);

    //refresh Gridview
    refreshGrid();

    renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordFrom, recordTo, genreId, groupId);
};

//Sort By Title Kana function
function sortByTitleKanaFunction() {

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

//    $('#control-sort-titlekana').addClass('active_tops');
//    $('#control-sort-title').removeClass('active_tops');
//    $('#control-sort-releasedate').removeClass('active_tops');

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

    if (sortOrder == Consts.ConstOrderSetting_Asc) {
        if (sortType == 2) {
            sortOrder = Consts.ConstOrderSetting_Desc;
//            $('#title-sorttype').html('');
//            $('#titlekana-sorttype').html('');
//            $('#titlekana-sorttype').html('▼');
//            $('#titlekana-sorttype').css('width', '12px');
//            $('#rDate-sorttype').html('');
        }
        else {
            sortOrder = Consts.ConstOrderSetting_Asc;
//            $('#title-sorttype').html('');
//            $('#titlekana-sorttype').html('');
//            $('#titlekana-sorttype').html('▲');
//            $('#titlekana-sorttype').css('width', '12px');
//            $('#rDate-sorttype').html('');
        }
        ClientData.searchCond_sortOrder(sortOrder);
    }
    else {
        sortOrder = Consts.ConstOrderSetting_Asc;
//        $('#title-sorttype').html('');
//        $('#titlekana-sorttype').html('');
//        $('#titlekana-sorttype').html('▲');
//        $('#titlekana-sorttype').css('width', '12px');
//        $('#rDate-sorttype').html('');
        ClientData.searchCond_sortOrder(sortOrder);
    }

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

    if (recordFrom == null || recordFrom == 'undefined') {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        ClientData.searchCond_recordFrom(recordFrom);
    }

    if (recordTo == null || recordTo == 'undefined') {

        if (isShowBookShelf) {
            recordTo = returnNumberDispRecordForBookShelf();
        }
        else if (!isShowBookShelf) {
            recordTo = returnNumberDispRecordForList();
        }
        else {
            recordTo = returnNumberDispRecordForBookShelf();
        }
        ClientData.searchCond_recordFrom(recordTo);
    }

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

    ClientData.searchCond_sortType(sortType);
    renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordFrom, recordTo, genreId, groupId);

};

//Sort By Release Date
function sortByReleaseDateFunction() {

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

    //$(this).addClass('active_tops');
  
//    $('#control-sort-releasedate').addClass('active_tops');
//    $('#control-sort-title').removeClass('active_tops');
//    $('#control-sort-titlekana').removeClass('active_tops');

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

    if (sortOrder == Consts.ConstOrderSetting_Asc) {
        if (sortType == 3) {
            sortOrder = Consts.ConstOrderSetting_Desc;
//            $('#title-sorttype').html('');
//            $('#titlekana-sorttype').html('');
//            $('#rDate-sorttype').html('');
//            $('#rDate-sorttype').html('▼');
//            $('#rDate-sorttype').css('width', '12px');
        }
        else {
            sortOrder = Consts.ConstOrderSetting_Asc;
//            $('#title-sorttype').html('');
//            $('#titlekana-sorttype').html('');
//            $('#rDate-sorttype').html('');
//            $('#rDate-sorttype').html('▲');
//            $('#rDate-sorttype').css('width', '12px');
        }
        ClientData.searchCond_sortOrder(sortOrder);        
    }
    else {
        sortOrder = Consts.ConstOrderSetting_Asc;
//        $('#title-sorttype').html('');
//        $('#titlekana-sorttype').html('');
//        $('#rDate-sorttype').html('');
//        $('#rDate-sorttype').html('▲');
//        $('#rDate-sorttype').css('width', '12px');
        ClientData.searchCond_sortOrder(sortOrder);
    }
    setStatusSort('#control-sort-releasedate',sortOrder == Consts.ConstOrderSetting_Asc);

    if (recordFrom == null || recordFrom == 'undefined') {
        recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
        ClientData.searchCond_recordFrom(recordFrom);
    }

    if (recordTo == null || recordTo == 'undefined') {

        if (isShowBookShelf) {
            recordTo = returnNumberDispRecordForBookShelf();
        }
        else if (!isShowBookShelf) {
            recordTo = returnNumberDispRecordForList();
        }
        else {
            recordTo = returnNumberDispRecordForBookShelf();
        }
        ClientData.searchCond_recordFrom(recordTo);
    }

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

    ClientData.searchCond_sortType(sortType);
    renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordFrom, recordTo, genreId, groupId);

};

//Handle language
function handleLanguage() {

    if (getCurrentLanguage() == Consts.ConstLanguage_En || getCurrentLanguage() == 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();

            setStatusSort('#'+$('#menu_sort li.current a').attr('id'),orderSort == Consts.ConstOrderSetting_Asc);

            if (typeSort == 2) {
                if (orderSort == Consts.ConstOrderSetting_Asc) {
//                    $('#titlekana-sorttype').html('');
//                    $('#titlekana-sorttype').html('▲');
//                    $('#titlekana-sorttype').css('width', '12px');
                }
                else {
//                    $('#titlekana-sorttype').html('');
//                    $('#titlekana-sorttype').html('▼');
//                    $('#titlekana-sorttype').css('width', '12px');
                }
            }
        }
    }
};

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


    abapi('webContentList', params, 'POST', function (data) {
        var countCnt = 0;
        
        $.each(data.contentList, function (i, post) {

            var outputDate = formatDeliveryDate(post.contentDeliveryDate);

            if (isShowBookShelf == null) {
                if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_BookShelf) {
                    $('#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="dialog name lang" lang="lblTitle" contentid="' + post.contentId + '">'
						+ '   <img src="'+getIconTypeContent(post.contentType)+'" width="20" height="20">'
						+     truncate(htmlEncode(post.contentTitle), 20)
					    + ' </a>'
						+ '</section>'
					);
                    if ((home_realTotalRecord + i + 1) % 3 == 0) {
                        $('#bookshelf' + post.contentId).addClass('no_m_right');
                    }

                    getNextRecordNumForBookShelf();
                }
                // else if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_List) {
                else if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_List) {
                    $('#content-grid').append(
						 '<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="name dialog" contentid="' + post.contentId + '">'
						+ '             <img class="listIcon" src="'+getIconTypeContent(post.contentType)+'" width="20" height="20">'
						+               truncate(htmlEncode(post.contentTitle), 20) 
						+ '         </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="' + DEFAULT_IMG_OPTION_MEMO + '" id="imgMemo' + post.contentId + '" class="sticker"  /></li>'
						+ '					<li><img src="' + DEFAULT_IMG_OPTION_MARKING + '" id="imgBookMark' + post.contentId + '" class="pen"  /></li>'
						+ '					<li><a class="read lang button-details" contentid="' + post.contentId + '" lang="txtRead">読む</a></li>'
						+ '				</ul>'
						+ '			</div>'
						+ '		</div>'
						+ '	</div>'
						+ '</section>'
					);
                    getNextRecordNumForList();
                }
                else {

                }
            } else {

                // if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_BookShelf) {
                if (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="dialog name lang" lang="lblTitle" contentid="' + post.contentId + '">'
                    + '   <img src="'+getIconTypeContent(post.contentType)+'" width="20" height="20">'
                    +     truncate(htmlEncode(post.contentTitle), 20)
                    + ' </a>'
					+ '</section>'
				);
                    
                    if ((home_realTotalRecord + i + 1) % 3 == 0) {
                        $('#bookshelf' + post.contentId).addClass('no_m_right');
                    }
                    getNextRecordNumForBookShelf();
                }
                // else if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_List) {
                else if (!isShowBookShelf) {
                    $('#content-grid').append(
					 '<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="'+getIconTypeContent(post.contentType)+'" width="20" height="20">'
                    +               truncate(htmlEncode(post.contentTitle), 20)
                    + '         </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="' + DEFAULT_IMG_OPTION_MEMO + '" id="imgMemo' + post.contentId + '" class="sticker"  /></li>'
					+ '					<li><img src="' + DEFAULT_IMG_OPTION_MARKING + '" id="imgBookMark' + post.contentId + '" class="pen"  /></li>'
					+ '					<li><a class="read lang button-details" contentid="' + post.contentId + '" lang="txtRead">読む</a></li>'
					+ '				</ul>'
					+ '			</div>'
					+ '		</div>'
					+ '	</div>'
					+ '</section>'
				);
                                      
                    getNextRecordNumForList();
                }
                else {

                }
            }

            //assign thumbnail to array
            var formatThumbnail = post.contentThumbnail;
            if((formatThumbnail != null) && (formatThumbnail != 'undefined') && (formatThumbnail != '')){
                formatThumbnail = formatStringBase64(formatThumbnail);
            }
            
            thumbnailArr.push({ contentId: post.contentId, thumbnail:  formatThumbnail});
            
            //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Assign content type to array to manage.
            //assign content type to array 
            contentTypeArr.push({ contentId: post.contentId, contentType: post.contentType });
            //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Assign content type to array to manage.
                        
            // save alert message level
            messageLevel[post.contentId] = { alertMessageLevel:post.alertMessageLevel, alertMessage:post.alertMessage};

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

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

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

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

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

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

        if (data.totalRecord < data.recordTo) {
            ClientData.searchCond_recordTo(data.totalRecord);
        } else {
            ClientData.searchCond_recordTo(data.recordTo);
        }

        ClientData.searchCond_recordFrom(data.recordFrom);
        totalPage = data.totalRecord;

        reRenderPageNumber(ClientData.searchCond_recordTo(), totalPage);

        //Toggle scroll to top Control
        handleBackToTop();

        //changeLanguage(ClientData.userInfo_language());
        i18nReplaceText();
    });
};
var genre_totalcontent = -1;
var group_totalcontent = -1;

//Initial Screen
function renderGridView() {

    var fromPage = DEFAULT_DISP_NUMBER_RECORD_FROM;
    var toPage = 0;
    var sortType = DEFAULT_SORT_TYPE;
    var sortOrder = DEFAULT_SORT_ORDER;
    var searchText = '';
    var searchDivision = DEFAULT_SEARCH_DIVISION;
    var genreId = '';
    var groupId = '';
    var sid = ClientData.userInfo_sid();

    ClientData.searchCond_recordFrom(fromPage);

    if (isShowBookShelf) {
        toPage = returnNumberDispRecordForBookShelf();
    }
    else if (!isShowBookShelf) {
        toPage = returnNumberDispRecordForList();
    }
    else {
        toPage = returnNumberDispRecordForBookShelf();
    }
    ClientData.searchCond_recordTo(toPage);

    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
    handleLanguage();

    //handle 
    handleSortDisp();

    //Refresh GridView
    refreshGrid();

    resetShowNextRecordCount();

    //Render Gridview
    renderContent(sid, searchText, searchDivision, sortType, sortOrder, fromPage, toPage, genreId, groupId);
};

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

//Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Create new function to return content type of content.
//Get content type base on contentid
function returnContentType(contentid){
    //Array Length
    var iArrCnt = contentTypeArr.length;
    
    //Get contentType in array by contentId
    for(var i = 0; i < iArrCnt; i++){
        if (contentTypeArr[i].contentId == contentid) {
            return contentTypeArr[i].contentType;
        }
    }
};

//Check content type is pdf content
function isPdfContent(contentType){
    if(!(contentType == ContentTypeKeys.Type_PDF)){
        return false; 
    }
    else{
        return true;
    }
};


////Get resource Id of content
//function downloadResourceById(contentId){
//    var params = {
//        sid: ClientData.userInfo_sid(),
//        contentId: contentId,
//        getType: '2',
//    };
//    
//    var resourceUrl;
//    
//    abapi('webGetContent', params, 'GET', function (data) {
//        var resourceId;
//        
//        $.each(data.contentData , function(i, n){
//            if(typeof n == "object"){
//                resourceId = n.resourceId;                
//            }                        
//        });
//      
//       //Get resource
//       resourceUrl = getResourceByIdFromAPI(resourceId);           

//       window.open(resourceUrl, "_blank");

//    });           
//};

////Download resource
//function getResourceByIdFromAPI(resourceId){
//    return getURL("webResourceDownload") + "/?sid=" + ClientData.userInfo_sid() + "&resourceId=" + resourceId + "&isDownload=true"; 
//};

/* get url */
function getURL(apiName) {
    var sysSettings = avwSysSetting();
    var url = sysSettings.apiResourceDlUrl;
    url = format(url, ClientData.userInfo_accountPath()) + '/' + apiName;
    return url;
};

function createIframeForDownload(url){
    
};
//End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Create new function to return content type of content.

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

    if (!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
function checkUserHasReadContent(contId, resourceVer, metaVer) {

    var imgThumb = new Image();
    //imgThumb.src = returnThumbnail(contId);

    var imgIconNew = new Image();
    //imgIconNew.src = DEFAULT_IMG_CONTENT_NEW;

    var imgIconEdit = new Image();
    //imgIconEdit.src = DEFAULT_IMG_CONTENT_EDIT;

    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();
    
    //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Declare variable handle contentType and Thumbnail of content.
    var contentThumbnail = returnThumbnail(contId);
    var contentType = returnContentType(contId);
    //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Declare variable handle contentType and Thumbnail of content.


    if (readArr == null || readArr <= 0 || readArr == 'undefined') {
        imgThumb.onload = function () {
            var resizeImg = 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 = 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(!isPdfContent(contentType)){
                if(contentType == ContentTypeKeys.Type_Image){
                    imgThumb.src = ThumbnailForOtherType.Thumbnail_ImageType;
                }
                else if(contentType == ContentTypeKeys.Type_Music){
                    imgThumb.src = ThumbnailForOtherType.Thumbnail_MusicType;
                }
                else if(contentType == ContentTypeKeys.Type_Video){
                    imgThumb.src = ThumbnailForOtherType.Thumbnail_VideoType;
                }
                else if(contentType == ContentTypeKeys.Type_NoFile){
                    imgThumb.src = ThumbnailForOtherType.Thumbnail_NoFileType;
                }
                else if(contentType == ContentTypeKeys.Type_Others){
                    imgThumb.src = ThumbnailForOtherType.Thumbnail_OthersType;
                }
                else if(contentType == ContentTypeKeys.Type_Html){
                    imgThumb.src = ThumbnailForOtherType.Thumbnail_HtmlType;
                }
            }
        }else{
            imgThumb.src = contentThumbnail;
        }
                
        //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Check contentType to set thumbnail.
    }
    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 = 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');
                    });
                };
                //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Check contentType to set thumbnail.
      
                if(contentThumbnail == '' || contentThumbnail == null){
                    if(!isPdfContent(contentType)){
                        if(contentType == ContentTypeKeys.Type_Image){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_ImageType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Music){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_MusicType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Video){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_VideoType;
                        }
                        else if(contentType == ContentTypeKeys.Type_NoFile){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_NoFileType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Others){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_OthersType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Html){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_HtmlType;
                        }
                    }
                }else{
                    imgThumb.src = contentThumbnail;
                }
                        
                //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Check contentType to set thumbnail.
                readFlg = true;
                break;
            }
            else {
                imgThumb.onload = function () {
                    var resizeImg = 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 = 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(!isPdfContent(contentType)){
                        if(contentType == ContentTypeKeys.Type_Image){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_ImageType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Music){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_MusicType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Video){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_VideoType;
                        }
                        else if(contentType == ContentTypeKeys.Type_NoFile){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_NoFileType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Others){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_OthersType;
                        }
                        else if(contentType == ContentTypeKeys.Type_Html){
                            imgThumb.src = ThumbnailForOtherType.Thumbnail_HtmlType;
                        }
                    }
                }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 = 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 = DEFAULT_IMG_CONTENT_EDIT;
                        };
                        //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Check contentType to set thumbnail.
                      
                        if(contentThumbnail == '' || contentThumbnail == null){
                            if(!isPdfContent(contentType)){
                                if(contentType == ContentTypeKeys.Type_Image){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_ImageType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Music){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_MusicType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Video){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_VideoType;
                                }
                                else if(contentType == ContentTypeKeys.Type_NoFile){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_NoFileType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Others){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_OthersType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Html){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_HtmlType;
                                }
                            }
                        }else{
                            imgThumb.src = contentThumbnail;
                        }
                                
                        //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Check contentType to set thumbnail.
                        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 = 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 = DEFAULT_IMG_CONTENT_EDIT;
                        };
                        //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Check contentType to set thumbnail.
      
                        if(contentThumbnail == '' || contentThumbnail == null){
                            if(!isPdfContent(contentType)){
                                if(contentType == ContentTypeKeys.Type_Image){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_ImageType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Music){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_MusicType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Video){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_VideoType;
                                }
                                else if(contentType == ContentTypeKeys.Type_NoFile){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_NoFileType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Others){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_OthersType;
                                }
                                else if(contentType == ContentTypeKeys.Type_Html){
                                    imgThumb.src = ThumbnailForOtherType.Thumbnail_HtmlType;
                                }
                            }
                        }else{
                            imgThumb.src = contentThumbnail;
                        }
                                
                        //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Check contentType to set thumbnail.
                        break;
                    }
                }
            }
        }
        readFlg = false;
    }
};

//draw Edit Image
function drawEditImage(id) {
    var img = new Image();
    var imgSrc = returnThumbnail(id);
    
    if(imgSrc != null){
        
    }
    else{
        var contentType = returnContentType(id);
        
        if(contentType == ContentTypeKeys.Type_Image){
            imgSrc = ThumbnailForOtherType.Thumbnail_ImageType;
        }
        else if(contentType == ContentTypeKeys.Type_Music){
            imgSrc = ThumbnailForOtherType.Thumbnail_MusicType;
        }
        else if(contentType == ContentTypeKeys.Type_Video){
            imgSrc = ThumbnailForOtherType.Thumbnail_VideoType;
        }
        else if(contentType == ContentTypeKeys.Type_NoFile){
            imgSrc = ThumbnailForOtherType.Thumbnail_NoFileType;
        }
        else if(contentType == ContentTypeKeys.Type_Others){
            imgSrc = ThumbnailForOtherType.Thumbnail_OthersType;
        }
        else if(contentType == ContentTypeKeys.Type_Html){
            imgSrc = ThumbnailForOtherType.Thumbnail_HtmlType;
        }       
    }
       
    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 = 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
function renderViewDate(id) {

    for (var i = 0; i < ClientData.ReadingContentIds().length; i++) {
        if (ClientData.ReadingContentIds()[i].contentid == id) {
            return ClientData.ReadingContentIds()[i].viewdate;
        }
    }
};

//set resource version data
function setResourceVersionData(conId) {
    var tempResourceArr;
    var tempResource;
    //check if insert new or edit
    var flag = false;

    if (ClientData.ResourceVersion().length <= 0 || ClientData.ResourceVersion() == null || ClientData.ResourceVersion() == 'undefined') {
        tempResourceArr = [];
    }
    else {
        tempResourceArr = ClientData.ResourceVersion();
    }

    for (var i = 0; i < resourceVersionArr.length; i++) {
        if (resourceVersionArr[i].contentid == conId) {
            tempResource = resourceVersionArr[i].resourceversion;
            break;
        }
    }

    if (tempResourceArr.length > 0) {
        for (var j = 0; j < tempResourceArr.length; j++) {
            if (tempResourceArr[j].contentid == conId) {
                tempResourceArr[j].resourceversion = tempResource;
                flag = true;
                break;
            }
            else {
                flag = false;
            }
        }

        if (!flag) {
            tempResourceArr.push({ contentid: conId, resourceversion: tempResource });
        }

    } else {
        tempResourceArr.push({ contentid: conId, resourceversion: tempResource });
    }

    ClientData.ResourceVersion(tempResourceArr);
};

//set meta Version Data
function setMetaVersionData(conId) {

    var tempMetaArr;
    var tempMeta;
    //check if insert new or edit
    var flag = false;

    if (ClientData.MetaVersion().length <= 0 || ClientData.MetaVersion() == null || ClientData.MetaVersion() == 'undefined') {
        tempMetaArr = [];
    }
    else {
        tempMetaArr = ClientData.MetaVersion();
    }

    for (var i = 0; i < metaVersionArr.length; i++) {
        if (metaVersionArr[i].contentid == conId) {
            tempMeta = metaVersionArr[i].metaversion;
            break;
        }
    }

    if (tempMetaArr.length > 0) {
        for (var j = 0; j < tempMetaArr.length; j++) {
            if (tempMetaArr[j].contentid == conId) {
                tempMetaArr[j].metaversion = tempMeta;
                flag = true;
                break;
            }
            else {
                flag = false;
            }
        }

        if (!flag) {
            tempMetaArr.push({ contentid: conId, metaversion: tempMeta });
        }

    } else {
        tempMetaArr.push({ contentid: conId, metaversion: tempMeta });
    }

    ClientData.MetaVersion(tempMetaArr);
};

//handle display sort direction
function handleSortDisp() {
    $('#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) {
//                if (orderSort == Consts.ConstOrderSetting_Asc) {
//                    $('#title-sorttype').html('');
//                    $('#title-sorttype').html('▲');
//                    $('#title-sorttype').css('width', '12px');
//                    $('#titlekana-sorttype').html('');
//                    $('#rDate-sorttype').html('');
//                }
//                else {
//                    $('#title-sorttype').html('');
//                    $('#title-sorttype').html('▼');
//                    $('#title-sorttype').css('width', '12px');
//                    $('#titlekana-sorttype').html('');
//                    $('#rDate-sorttype').html('');
//                }

//                $('#control-sort-title').addClass('active_tops');
                setStatusSort('#control-sort-title',orderSort == Consts.ConstOrderSetting_Asc);
            }
            else if (typeSort == 2) {

//                if (orderSort == Consts.ConstOrderSetting_Asc) {
//                    $('#title-sorttype').html('');
//                    $('#titlekana-sorttype').html('');
//                    $('#titlekana-sorttype').html('▲');
//                    $('#titlekana-sorttype').css('width', '12px');
//                    $('#rDate-sorttype').html('');
//                }
//                else {
//                    $('#title-sorttype').html('');
//                    $('#titlekana-sorttype').html('');
//                    $('#titlekana-sorttype').html('▼');
//                    $('#titlekana-sorttype').css('width', '12px');
//                    $('#rDate-sorttype').html('');
//                }

//                $('#control-sort-titlekana').addClass('active_tops');
                setStatusSort('#control-sort-titlekana',orderSort == Consts.ConstOrderSetting_Asc);
            }
            else if (typeSort == 3) {
//                if (orderSort == Consts.ConstOrderSetting_Asc) {
//                    $('#title-sorttype').html('');
//                    $('#titlekana-sorttype').html('');
//                    $('#rDate-sorttype').html('');
//                    $('#rDate-sorttype').html('▲');
//                    $('#rDate-sorttype').css('width', '12px');
//                }
//                else {
//                    $('#title-sorttype').html('');
//                    $('#titlekana-sorttype').html('');
//                    $('#rDate-sorttype').html('');
//                    $('#rDate-sorttype').html('▼');
//                    $('#rDate-sorttype').css('width', '12px');
//                }

//                $('#control-sort-releasedate').addClass('active_tops');
                setStatusSort('#control-sort-releasedate',orderSort == Consts.ConstOrderSetting_Asc);
            }
        }
    }
};

//convert delivery Date
function formatDeliveryDate(date) {

    var day = date.date;
    var month = eval(date.month) + 1;
    var year = eval(date.year) + 1900;

    var outputDate = year + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + (('' + day).length < 2 ? '0' : '') + day;

    return outputDate;
};

//convert view Date
function formatNormalDate(day, month, year) {
    var outputDate = year + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + (('' + day).length < 2 ? '0' : '') + day;

    return outputDate;
};

//format Image string
function formatStringBase64(imgStr) {

    var outputString = 'data:image/jpeg;base64,' + imgStr;

    return outputString;
};

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

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

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

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

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

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

//format text display more record
function formatDisplayMoreRecord() {
    //changeLanguage(ClientData.userInfo_language());
    i18nReplaceText();

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

/*
Check content whether existed or not
*/
function IsExistContent(strContentId) {
    var isExisted = true;
    var params = {
        sid: ClientData.userInfo_sid(),
        getType: '1',
        contentId: strContentId
    };
    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
                        showSystemError();
                    }
                });
    return isExisted;
};

function syncReadingContent() {
    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 (!IsExistContent(readContent.contentid)) {

            errorContent.push({ contentid: readContent.contentid });
            readArr.splice(i, 1);
            metaArr.splice(i, 1);
            resourceArr.splice(i, 1);
        }
        // Do not process next
        if (avwHasError()) {
            return;
        }
    }

    ClientData.ReadingContentIds(readArr);
    ClientData.MetaVersion(metaArr);
    ClientData.ResourceVersion(resourceArr);
};

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

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

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

    ClientData.BookMarkData(arrBookmark);
};

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

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

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

    ClientData.MemoData(arrMemo);
};

function syncMarkingContent() {

    var arrMarking = ClientData.MarkingData();

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

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

    ClientData.MarkingData(arrMarking);
};

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

        ClientData.common_contentDataChkFlg(false);
    }
};

function isErrorContent(contentid) {

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

        if (contentid == contentErr.contentid) {
            return true;
        }
        else {
            return false;
        }
    }
};

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

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

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

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

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

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

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

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

        // Get all pages of content
        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);
};

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

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

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

        // Get all pages of content
        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() {
    handleLanguage();
    formatDisplayMoreRecord();
    document.title = i18nText('dspHome') + ' | ' + i18nText('sysAppTitle');
};

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

function resizeResourceThumbnail(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;

};

function resetShowNextRecordCount() {
    showNextRecordClickNumber = 1;
};

function setDefaultViewMode() {
    if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_BookShelf) {
        isShowBookShelf = true;
        
        
        //Start : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
        $('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");
        //End : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
    }
    else if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_List) {
        isShowBookShelf = false;
        
        //Start : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
         $('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");
        //End : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
    }
    else {
        isShowBookShelf = true;
        
        //Start : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
        $('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");
        //End : Apply new css - Editor: Long - Date : 09/03/2013 - Summary : For handle view mode icon
    }
};

function removeHoverCss() {

    if (isTouchDevice()) {
        $('#control-sort-title').removeClass('nottouchdevice');
        $('#control-sort-titlekana').removeClass('nottouchdevice');
        $('#control-sort-releasedate').removeClass('nottouchdevice');
    }
};