/// <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 = '4';
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 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 totalPage;
var contentViewData = [];
var noRecordFlg = false;
var home_isMove = false;
var history_contentTitleKana = [];

$(document).ready(function(){
 	
 	if (!avwCheckLogin(ScreenIds.Login)){
 		return;
 	} 
 	
 	LockScreen();

	document.title = i18nText('dspViewHistory') + ' | ' + i18nText('sysAppTitle');
	
	ClientData.BookmarkScreen(ScreenIds.History);
 	
 	if(ClientData.requirePasswordChange() != 1){
 		if(ClientData.ReadingContentIds() == null || ClientData.ReadingContentIds() == 'undefined' || ClientData.ReadingContentIds().length == 0){	
		}else{
			syncReadingContent();
		}
	 	
	 	//remove hover effect when is touch device
	 	removeHoverCss();
	 	
	 	//Render Grid
	 	renderGridView();
			
		//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', titleClickFunction);	
		//$('.dialog').live('touchstart', titleClickFunction);	
	    $('.dialog').live('touchend', titleClickFunction);
	    $('.dialog').live('touchmove', function () { home_isMove = true; });
			
		//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);	
		
		$('#control-sort-viewdate').click(sortByViewDateFunction);
			
		//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; });
	
	    $(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{
 		//Check if Force Change password
		checkForceChangePassword();
 	}
 	
    if (isAnonymousLogin()) {
        //プッシュメッセージ隠す
        $('#dspPushMessage').hide();
    }
 	
});	

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

///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,
        categoryId: cateid,
        groupId: grpid
    };

    avwCmsApiSync(ClientData.userInfo_accountPath(), 'webContentList', 'POST', params,
            function (data) {
                
                $('#content-grid').html('');
                //var htmlTemp = "";
                for (var i = 0; i < data.contentList.length; i++) {
                    post = data.contentList[i];

                    var outputDate = formatDeliveryDate(post.contentDeliveryDate);
                    //renderViewDate  
                    var viewdate = renderViewDate(post.contentId);

                    if (viewdate != null && viewdate != 'undefined' && viewdate != '') {
                        
                        /*htmlTemp += '<section class="sectionhistory">'
                        //$('#content-grid').append(
                        // '<section>'
				        + '	<div class="cnt_section">'
				        + '		<a class="img">'
				        + '			<canvas style="display:none" height="105px" width="150px" class="home_canvas" id="content-thumbnail' + post.contentId + '" contentid="' + post.contentId + '">'
				        + '			</canvas>'
				        + '			<img id="imgloading'+ post.contentId +'" class="home_canvas" src="./img/data_loading.gif" height="25px" width="25px" style=""/>'
				        + '		</a>'
				        + '		<div class="text">'
				        + '			<a id="title' + post.contentId + '" class="dialog name" contentid="' + post.contentId + '">' + truncate(htmlEncode(post.contentTitle), 25) + '</a>'
				        + '			<div class="info">'
				        + '				<ul class="date">'
				        + '					<li><span class="lang" lang="txtPubDt">' + i18nText("txtPubDt") + '</span> : ' + outputDate + '</li>'
				        + '					<li><span class="lang" lang="txtViewDt">' + i18nText("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">' + i18nText("txtRead") + '</a></li>'
				        + '				</ul>'
				        + '			</div>'
				        + '		</div>'
				        + '	</div>'
				        + '</section>'*/


                       var htmlTemp = '<section class="sectionhistory">'
						+ '	<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="imgloading' + 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">'+i18nText("txtRead")+'</a></li>'
						+ '				</ul>'
						+ '			</div>'
						+ '		</div>'
						+ '	</div>'
						+ '</section>';

                        $('#content-grid').append(htmlTemp);
                    }
                }
                
                

                for (var i = 0; i < data.contentList.length; i++) {
                    post = data.contentList[i];
                    var viewdate = renderViewDate(post.contentId);

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

                    if (viewdate != null && viewdate != 'undefined' && viewdate != '') {
                        
                        //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.

                        //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);

                        $('#lblVdate' + post.contentId).html(viewdate);

                        addReadContentToArray(post.contentId, post.resourceVersion, post.metaVersion, post.contentThumbnail, post.contentTitle, returnContentTitleKana(post.contentId), post.contentDeliveryDate,post.contentType);

                        //showContentThumbnail();
                    }
                }

                if (data.recordFrom) {
                    ClientData.searchCond_recordFrom(data.recordFrom);
                }
                if (data.recordTo) {
                    ClientData.searchCond_recordTo(data.recordTo);
                }
                totalPage = data.totalRecord;
                //Render Page number
                reRenderPageNumber(totalPage, totalPage);

            }, null);
};

//Handle language
function handleLanguage(){

	//if(ClientData.userInfo_language() == Consts.ConstLanguage_En || ClientData.userInfo_language() == Consts.ConstLanguage_Ko)
    if (getCurrentLanguage() == Consts.ConstLanguage_En || getCurrentLanguage() == Consts.ConstLanguage_Ko)
	{
		$('#control-sort-titlekana').css('display','none');
		$('#control-sort-titlekana-off').css('display','none');
		$('#label-sort-titlekana').css('display','none');
		$('#separate').css('display','none');
		$("#titlekana-sorttype").html('');
	}
	else {		
	    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');
//	            }
//	        }
	    }
        	
		if(noRecordFlg){
			$('#label-sort-titlekana').css('display','block');
			$('#separate').css('display','block');
			
			$('#control-sort-titlekana-off').css('display','block');
			
			$('#content-grid').html("<div id='msgHistoryNotExist'>" + i18nText('msgHistoryNotExist') + "</div>");
		}else{
			$('#control-sort-titlekana').css('display','block');
			$('#separate').css('display','block');
		}
	}	
	
};

//Initial Screen
function renderGridView(){
	
	var fromPage = '';
	var toPage = '';
	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);
			
	ClientData.searchCond_recordTo(toPage);
	
	ClientData.searchCond_sortType(sortType);

	ClientData.searchCond_sortOrder(sortOrder);

	ClientData.searchCond_searchDivision(searchDivision);

	//Handle display sort
	handleSortDisp();
	
	//Display user name
	$('#login-username').html(ClientData.userInfo_loginId_session());
	
	//Refresh GridView
	refreshGrid();
	
	if(ClientData.ReadingContentIds() == null || ClientData.ReadingContentIds() == 'undefined' || ClientData.ReadingContentIds().length == 0){
		displayResultNoRecord();
		noRecordFlg = true;
		reRenderPageNumber(0,0);
	}
	else{
		//Render Gridview
		renderContent(sid, searchText, searchDivision, 3, sortOrder, fromPage, toPage, genreId, groupId);
		sortByViewDateDesc();
	}
	
	//Language Handle
	handleLanguage();
};

//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);

    // Set content id for screen: content detail
	ClientData.contentInfo_contentId(outputId);
	
	// Get image of selected image
	var base64String = returnThumbnail(outputId);
	ClientData.contentInfo_contentThumbnail(base64String);

    //Start Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Declare variable handle contentType of content.
    var contentType = returnContentType(outputId);
    ClientData.contentInfo_contentType(contentType);
    //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Declare variable handle contentType of content.
    
	//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);
	
	//Delete 'new' icon
	drawEditImage(outputId);

	//Open content Detail
	openContentDetail();
};

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

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

};

//Sort By Title Function
function sortByTitleFunction(){
	
//	$(this).addClass('active_tops');
//	$('#control-sort-titlekana').removeClass('active_tops');
//	$('#control-sort-releasedate').removeClass('active_tops');
//	$('#control-sort-viewdate').removeClass('active_tops');
			
	var sortOrder = ClientData.searchCond_sortOrder();
	var sortType = ClientData.searchCond_sortType();
	var sid = ClientData.userInfo_sid();
	var recordFrom = null;
	var recordTo = null;
	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('');	
//			$('#vDate-sorttype').html('');
			sortByTitleDesc();	
		}
		else{
			sortOrder = Consts.ConstOrderSetting_Asc;
//			$('#title-sorttype').html('');
//			$('#title-sorttype').html('▲');
//			$('#title-sorttype').css('width', '12px');
//			$('#titlekana-sorttype').html('');
//			$('#rDate-sorttype').html('');	
//			$('#vDate-sorttype').html('');	
			sortByTitleAsc();	
		}	
		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('');		
//		$('#vDate-sorttype').html('');		
		ClientData.searchCond_sortOrder(sortOrder);	
		sortByTitleAsc();	
	}			

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

	sortType = '1';
	ClientData.searchCond_sortType(sortType);

	//refresh Gridview
	//refreshGrid();
				
	//renderContent(sid, '', ClientData.searchCond_searchDivision(), sortType, sortOrder, recordFrom, recordTo, genreId, groupId);
};

//Sort By Title Kana function
function sortByTitleKanaFunction(){
		
//	$(this).addClass('active_tops');
//	$('#control-sort-title').removeClass('active_tops');
//	$('#control-sort-releasedate').removeClass('active_tops');
//	$('#control-sort-viewdate').removeClass('active_tops');
		
	var sortOrder = ClientData.searchCond_sortOrder();
	var sortType = ClientData.searchCond_sortType();
	var sid = ClientData.userInfo_sid();
	var recordFrom = null;
	var recordTo = null;
	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('');	
//			$('#vDate-sorttype').html('');
			sortByTitleKanaDesc();
		}
		else{
			sortOrder = Consts.ConstOrderSetting_Asc;
//			$('#title-sorttype').html('');
//			$('#titlekana-sorttype').html('');
//			$('#titlekana-sorttype').html('▲');
//			$('#titlekana-sorttype').css('width', '12px');
//			$('#rDate-sorttype').html('');
//			$('#vDate-sorttype').html('');	
			sortByTitleKanaAsc();
		}	
		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('');
//		$('#vDate-sorttype').html('');
		ClientData.searchCond_sortOrder(sortOrder);	
		sortByTitleKanaAsc();
	}			
	
    setStatusSort('#control-sort-titlekana',sortOrder == Consts.ConstOrderSetting_Asc);
	
	sortType = '2';
	//refresh gridview
	//refreshGrid();
				
	ClientData.searchCond_sortType(sortType);
	//renderContent(sid, '', ClientData.searchCond_searchDivision(), sortType, sortOrder, null, null, genreId, groupId);
	
};

//Sort By Release Date
function sortByReleaseDateFunction(){
	
//	$(this).addClass('active_tops');
//	$('#control-sort-titlekana').removeClass('active_tops');
//	$('#control-sort-title').removeClass('active_tops');
//	$('#control-sort-viewdate').removeClass('active_tops');
	
	var sortOrder = ClientData.searchCond_sortOrder();
	var sortType = ClientData.searchCond_sortType();
	var sid = ClientData.userInfo_sid();
	var recordFrom = null;
	var recordTo = null;
	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');
//			$('#vDate-sorttype').html('');
			sortByPublishDateDesc();
		}
		else{
			sortOrder = Consts.ConstOrderSetting_Asc;	
//			$('#title-sorttype').html('');
//			$('#titlekana-sorttype').html('');
//			$('#rDate-sorttype').html('');
//			$('#rDate-sorttype').html('▲');
//			$('#rDate-sorttype').css('width', '12px');
//			$('#vDate-sorttype').html('');
			sortByPublishDateAsc();
		}
		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');
//		$('#vDate-sorttype').html('');
		ClientData.searchCond_sortOrder(sortOrder);	
		sortByPublishDateAsc();
	}			

    setStatusSort('#control-sort-releasedate',sortOrder == Consts.ConstOrderSetting_Asc);
    
	sortType = '3';		
	ClientData.searchCond_sortType(sortType);	
	//renderContent(sid, '', ClientData.searchCond_searchDivision(), sortType, sortOrder, recordFrom, recordTo, genreId, groupId);
};

//Sort By View Date
function sortByViewDateFunction(){
	
//	$(this).addClass('active_tops');
//	$('#control-sort-titlekana').removeClass('active_tops');
//	$('#control-sort-title').removeClass('active_tops');
//	$('#control-sort-releasedate').removeClass('active_tops');
	
	var sortOrder = ClientData.searchCond_sortOrder();
	var sortType = ClientData.searchCond_sortType();

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

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

	sortType = '4';
	
	ClientData.searchCond_sortType(sortType);	
	
};

//Get Thumnail base on contentid
function returnThumbnail(contentid){
	
	for(var i = 0; i < thumbnailArr.length; 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");        

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

//    });           
//};

////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;
};
//End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Create new function to return content type of content.


//Dialog Read Button CLick
function readSubmenuFunction(e){
    if (e) {
        e.preventDefault();
    }
    if (home_isMove == true) {
        home_isMove = false;
        return;
    }
	
	var contentId = $(this).attr('contentid');

    // check limit of content
    checkLimitContent(contentId,
        function()
        { 
            readSubmenuFunction_callback(contentId);
        },
        function(){
        }
    );

};

// read content 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 : 08/01/2013 -- Summary : Store contentType to storage.  
	var contentType = returnContentType(contentId);
	ClientData.contentInfo_contentType(contentType);
	//End Function : No.12 -- Editor : Le Long -- Date : 08/01/2013 -- Summary : Store 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 == 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: 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);

	ClientData.IsRefresh(false);
	
    //Start Function : No.12 -- Editor : Le Long -- Date : 08/02/2013 -- Summary : Check content type other for download.          
    //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);
    }
    //End Function : No.12 -- Editor : Le Long -- Date : 08/02/2013 -- Summary : Check content type other for download. 
}



//Check if Content Has marking or memo
function checkContentMarkingMemoOption(contentId){
	//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, 0, resizeImg[0],  resizeImg[1]);
			imgIconNew.onload = function(){
				ctx.drawImage(imgIconNew, c.width/2 - resizeImg[0]/2, 0);
				showContentThumbnail(contId);
			};
			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, 0, resizeImg[0],  resizeImg[1]);
					showContentThumbnail(contId);
	    		};
		    	//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, 0, resizeImg[0],  resizeImg[1]);
					showContentThumbnail(contId);
		    		imgIconNew.onload = function(){
		    			ctx.drawImage(imgIconNew, c.width/2 - resizeImg[0]/2, 0);
		    		};
		    		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, 0, resizeImg[0],  resizeImg[1]);
							showContentThumbnail(contId);
			    			imgIconEdit.onload = function(){
			    				ctx.drawImage(imgIconEdit, c.width/2 - resizeImg[0]/2, 0);
			    			};
							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, 0, resizeImg[0],  resizeImg[1]);
							showContentThumbnail(contId);
			    			imgIconEdit.onload = function(){
			    				ctx.drawImage(imgIconEdit, c.width/2 - resizeImg[0]/2, 0);
			    			};
							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;
		}
	}
};

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

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

//function Open SubMenu Dialog
function titleClickFunction(e){
    if (e) {
        e.preventDefault();
    }
    if (home_isMove == true) {
        home_isMove = false;
        return;
    }
	
	var contentid = $(this).attr('contentid');
	// 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 : Declare variable handle contentType of content.
    var contentType = returnContentType(contentid);
    ClientData.contentInfo_contentType(contentType);
    //End Function : No.12 -- Editor : Le Long -- Date : 07/31/2013 -- Summary : Declare variable handle contentType of content.

	//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);
	
	//Delete 'new' icon
	drawEditImage(contentid);

	//Open content Detail
	openContentDetail();
};

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

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

function sortByViewDateAsc(){
 	var sortArr = contentViewData;
  	var t;
  	for(var i = 0; i < sortArr.length; i++){
  		for(var j = 1; j < sortArr.length - i; j++){
  			if(sortArr[j-1].originviewdate > sortArr[j].originviewdate){
  				t = sortArr[j-1];
  				sortArr[j-1] = sortArr[j];
  				sortArr[j] = t;
  			}
  		}
  	}
  	
  	var resultArr = sortArr;
  	renderContentAfterSort(resultArr);  	 
};

function formatDate(originDate){
	var sourceDate = new Date(originDate);
	var year = sourceDate.getFullYear() + 1;
	var month = sourceDate.getMonth();
	var day = sourceDate.getDate();
	var hour = sourceDate.getHours();
	var minute = sourceDate.getMinutes();
	var second = sourceDate.getSeconds();
	var milisecond = sourceDate.getMilliseconds();
	
	var newDate = new Date(year, month, day, hour, minute, second, milisecond);
	return newDate;
};

function sortByViewDateDesc(){
	var sortArr = contentViewData;
	
	var temp;
	for(var i = 0; i < sortArr.length; i++){
		for(var j = sortArr.length - 1; j > i; j--){
			if(sortArr[j].originviewdate > sortArr[j - 1].originviewdate){
				temp = sortArr[j];
				sortArr[j] = sortArr[j - 1];
			 	sortArr[j - 1] = temp;
			}
		}
	}
	
	var resultArr = sortArr;
	renderContentAfterSort(resultArr);
};

function addReadContentToArray(strContentId, strResourceVersion, strMetaVersion, strThumbnail, strTitle, strTitleKana, strDelivDate,contentType){
    if (contentViewData.length > 0) {
        var flag;
		for(var j = 0; j < contentViewData.length; j++){
			if(contentViewData[j].contentid == strContentId){		
				flag = true;
				break;
			}
			else{
				flag = false;
			}
		}
		
		if(!flag){
			contentViewData.push({contentid: strContentId, originviewdate: formatDate(returnOriginalViewDate(strContentId)), contenttitle: strTitle, contenttitlekana: strTitleKana, deliverydate: strDelivDate, resourceversion: strResourceVersion, metaversion: strMetaVersion, thumbnail: formatStringBase64(strThumbnail),contenttype:contentType  });
		}
		
	}else{
		contentViewData.push({contentid: strContentId, originviewdate: formatDate(returnOriginalViewDate(strContentId)), contenttitle: strTitle, contenttitlekana: strTitleKana, deliverydate: strDelivDate, resourceversion: strResourceVersion, metaversion: strMetaVersion, thumbnail: formatStringBase64(strThumbnail),contenttype:contentType });
	}	
};

function showContentThumbnail(conid) {

	$('img#imgloading'+conid).fadeOut('slow',function(){
		$('canvas#content-thumbnail'+conid).fadeIn('slow');
	});
};

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)) {
	        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);
};

/*
    Get content title kana if it existed
*/
function getContentNameKana(strContentId) {
    var strContentNameKana = null;
    for (var nIndex = 0; nIndex < history_contentTitleKana.length; nIndex++) {
        if (history_contentTitleKana[nIndex].contentId == strContentId) {
            strContentNameKana = history_contentTitleKana[nIndex].contentNameKana;
            break;
        }
    }
    return strContentNameKana;
};

/*
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;
                    history_contentTitleKana.push({ contentId: strContentId, contentNameKana: data.contentData.contentNameKana });
                },
                function (xmlHttpRequest, txtStatus, errorThrown) {
                    if (xmlHttpRequest.status == 404) {
                        isExisted = false;
                    }
                    else if(xmlHttpRequest.status == 403) {
                        isExisted = true;  // Mark this flag to prevent bookmarks from deleting
                        //認証エラー
                        showSystemError('sysErrorCallApi02');
                    }
                    else {
                        // Show system error
                        isExisted = true;  // Mark this flag to prevent bookmarks from deleting
                        showSystemError();
                    }
                });
    return isExisted;
};

function changeLanguageCallBackFunction(){
	handleLanguage();
	document.title = i18nText('dspViewHistory') + ' | ' + i18nText('sysAppTitle');
};

function displayResultNoRecord(){
	i18nReplaceText();
	$('#content-grid').html("<div id='msgHistoryNotExist'>" + i18nText('msgHistoryNotExist') + "</div>");	
	$('#control-nextrecord').css('visibility','hidden');
    $('.control_sort_on').hide();
    $('.control_sort_off').show();
    $('#off-default').addClass('descending_sort');
};

function enableSort(){
	$('.control_sort_on').show();
	$('.control_sort_off').hide();
};

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

function sortByTitleAsc(){

	var sortArr = contentViewData;	
  	var t;
  	for(var i = 0; i < sortArr.length; i++){
  		for(var j = 1; j < sortArr.length - i; j++){
  			if(sortArr[j-1].contenttitle.toUpperCase() > sortArr[j].contenttitle.toUpperCase()){
  				t = sortArr[j-1];
  				sortArr[j-1] = sortArr[j];
  				sortArr[j] = t;
  			}
  		}
  	}
	
	var resultArr = sortArr;
	renderContentAfterSort(resultArr);
};

function sortByTitleDesc(){
	var sortArr = contentViewData;
	var temp;
	for(var i = 0; i < sortArr.length; i++){
		for(var j = sortArr.length - 1; j > i; j--){
			if(sortArr[j].contenttitle.toUpperCase() > sortArr[j - 1].contenttitle.toUpperCase()){
				temp = sortArr[j];
				sortArr[j] = sortArr[j - 1];
			 	sortArr[j - 1] = temp;
			}
		}
	}
		
	var resultArr = contentViewData;
	renderContentAfterSort(resultArr);
};

function sortByPublishDateAsc(){
	var sortArr = contentViewData;	
	
  	var t;
  	for(var i = 0; i < sortArr.length; i++){
  		for(var j = 1; j < sortArr.length - i; j++){
  			if(formatOriginalPublishDate(sortArr[j-1].deliverydate) > formatOriginalPublishDate(sortArr[j].deliverydate)){
  				t = sortArr[j-1];
  				sortArr[j-1] = sortArr[j];
  				sortArr[j] = t;
  			}
  		}
  	}

	var resultArr = sortArr;
	renderContentAfterSort(resultArr);
};

function sortByPublishDateDesc(){
	var sortArr = contentViewData;
	var temp;
	for(var i = 0; i < sortArr.length; i++){
		for(var j = sortArr.length - 1; j > i; j--){
			if(formatOriginalPublishDate(sortArr[j].deliverydate) > formatOriginalPublishDate(sortArr[j - 1].deliverydate)){
				temp = sortArr[j];
				sortArr[j] = sortArr[j - 1];
			 	sortArr[j - 1] = temp;
			}
		}
	}
		
	var resultArr = sortArr;
	renderContentAfterSort(resultArr);
};

function sortByTitleKanaAsc(){
	var sortArr = contentViewData;	
  	var t;
  	for(var i = 0; i < sortArr.length; i++){
  		for(var j = 1; j < sortArr.length - i; j++){
  			if(sortArr[j-1].contenttitlekana > sortArr[j].contenttitlekana){
  				t = sortArr[j-1];
  				sortArr[j-1] = sortArr[j];
  				sortArr[j] = t;
  			}
  		}
  	}

	var resultArr = sortArr;
	renderContentAfterSort(resultArr);
};

function sortByTitleKanaDesc(){
	var sortArr = contentViewData;
	var temp;
	for(var i = 0; i < sortArr.length; i++){
		for(var j = sortArr.length - 1; j > i; j--){
			if(sortArr[j].contenttitlekana > sortArr[j - 1].contenttitlekana){
				temp = sortArr[j];
				sortArr[j] = sortArr[j - 1];
			 	sortArr[j - 1] = temp;
			}
		}
	}
		
	var resultArr = sortArr;
	renderContentAfterSort(resultArr);
};


function renderContentAfterSort(contentSortArr){
    refreshGrid();
    //var htmlTemp = "";    
	for(var i = 0; i < contentSortArr.length; i++) {
        post = contentSortArr[i];

		var outputDeliveryDate = formatDeliveryDate(post.deliverydate);
		/*htmlTemp += '<section class="sectionhistory">'
					+ '	<div class="cnt_section">'
					+ '		<a class="img">'
					+ '			<canvas style="display:none" height="105px" width="150px" class="home_canvas" id="content-thumbnail' + post.contentid + '" contentid="' + post.contentid + '">'
					+ '			</canvas>'
					+ '			<img id="imgloading'+ post.contentid +'" src="./img/data_loading.gif" height="25px" class="home_canvas" width="25px"/>'
					+ '		</a>'
					+ '		<div class="text">'
					+ '			<a id="title' + post.contentid + '" class="dialog name" contentid="' + post.contentid + '">' + truncate(htmlEncode(post.contenttitle), 25) + '</a>'
					+ '			<div class="info">'
					+ '				<ul class="date">'
					+ '					<li><span class="lang" lang="txtPubDt">' + i18nText("txtPubDt") + '</span> : ' + outputDeliveryDate + '</li>'
					+ '					<li><span class="lang" lang="txtViewDt">' + i18nText("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">' + i18nText("txtRead") + '</a></li>'
					+ '				</ul>'
					+ '			</div>'
					+ '		</div>'
					+ '	</div>'
					+ '</section>';*/

                var htmlTemp = '<section class="sectionhistory">'
						+ '	<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="imgloading' + 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">'+i18nText("txtPubDt")+'</span> : ' + outputDeliveryDate + '</li>'
						+ '					<li><span class="lang" lang="txtViewDt">'+i18nText("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">'+i18nText("txtRead")+'</a></li>'
						+ '				</ul>'
						+ '			</div>'
						+ '		</div>'
						+ '	</div>'
						+ '</section>';

                        $('#content-grid').append(htmlTemp);
	        }

	for (var i = 0; i < contentSortArr.length; i++) {
	    post = contentSortArr[i];

	    var viewdate = renderViewDate(post.contentid);

	    reRenderPageNumber(totalPage, totalPage);
	    //Check if user has read this content or not.
	    checkUserHasReadContent(post.contentid, post.resourceversion, post.metaversion);

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

	    $('#lblVdate' + post.contentid).html(viewdate);

	    showContentThumbnail();

	}
};

function formatOriginalPublishDate(date){

	var day = date.date;
	var month = date.month + 1;
	var year = date.year + 1900;
	var hour = date.hours;
	var minute = date.minutes;
	var second = date.seconds;
	
	var resultDate = new Date(year, month, day, hour, minute, second);
	return resultDate;
};

function returnContentTitleKana(id) {
    var titleKana;

    // Get title kana from existed contents
    titleKana = getContentNameKana(id);

    if (titleKana != null) {
        // Skip this case
    }
    else {
        var params = {
            contentId: id,
            sid: ClientData.userInfo_sid(),
            getType: 1
        };
        

        // Get all pages of content
        avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", 'GET', params,
	    function (data) {
	        // Success	      
	        titleKana = data.contentData.contentNameKana;
	    }, null);

	}
	return titleKana;
};

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 removeHoverCss(){
	
	if(isTouchDevice()){
		$('#control-sort-title').removeClass('nottouchdevice');
		$('#control-sort-titlekana').removeClass('nottouchdevice');
		$('#control-sort-releasedate').removeClass('nottouchdevice');
		$('#control-sort-viewdate').removeClass('nottouchdevice');		
	}
};
