/// <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 = '1';
var DEFAULT_SORT_ORDER = '1';
var DEFAULT_SEARCH_DIVISION = 0;

var DEFAULT_IMG_OPTION_MEMO = 'img/list/pic_1.png';
var DEFAULT_IMG_OPTION_MARKING = 'img/list/pic_2.png';
var DEFAULT_IMG_CONTENT_EDIT = 'img/list/updatebook.png';
var DEFAULT_IMG_CONTENT_NEW = 'img/list/newbook.png';

var iNumberOfNextRecord = 15;
var arrayTemp = [];
var contentIdArray = [];
var resourceVersionArr = [];
var metaVersionArr = [];
var totalPage;
var chkSearchTextEmpty = false;
var noRecordFlg = false;
var home_isMove = false;

$(document).ready(function(){
 	
 	if (!avwCheckLogin(ScreenIds.Login)){
 		return;
 	}
 	
 	LockScreen();
 	
 	document.title = i18nText('txtSearchResult') + ' | ' + i18nText('sysAppTitle');

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

	//Check if Force Change password
	if(ClientData.requirePasswordChange() != 1){
		//Format text display more record
	 	formatDisplayMoreRecord();
	 	
	 	//remove hover effect when is touch device
	 	removeHoverCss();
	 	
	 	//InitScreen
	 	initialScreen();
	 	
	 	//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; });	
		
		//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; });	
		
		$('#main-search').click(searchEventButtonFunction);
		
		$('#txtSearch').keydown(mainSearchKeyDownFunction);
		
		$('#main-search-content').click(mainSearchContentClickFunction);
		
		$('#main-search-tag').click(mainSearchTagClickFunction);
		
		$('#main-search-body').click(mainSearchBodyClickFunction);
	
		$('#control-nextrecord').css('visibility', 'hidden');
	
		$(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();
	}
});	


function mainSearchBodyClickFunction(){
	$('#main-body').attr('checked','checked');
	$('#main-tag').removeAttr('checked');
	$('#main-content').removeAttr('checked');
};

function mainSearchTagClickFunction(){
	$('#main-tag').attr('checked','checked');
	$('#main-body').removeAttr('checked');
	$('#main-content').removeAttr('checked');
};

function mainSearchContentClickFunction(){
	$('#main-content').attr('checked','checked');
	$('#main-tag').removeAttr('checked');
	$('#main-body').removeAttr('checked');
};


function mainSearchKeyDownFunction(e){
 	var code = (e.keyCode ? e.keyCode : e.which);
 	if(code == 13) { //Enter keycode
   		$('#main-search').click();
 	}
};

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

//Initial screen 
function initialScreen(){
	var searchText = ClientData.searchCond_searchText();
	var searchDivision = ClientData.searchCond_searchDivision();
	
	$('#txtSearch').val(searchText);
	//ClientData.searchCond_searchText('');
	
	if(searchDivision == 1){
		$('#main-tag').attr('checked',false);
		$('#main-body').attr('checked',false);
		$('#main-content').attr('checked','checked');
	}
	else if(searchDivision == 2){
		$('#main-content').attr('checked',false);
		$('#main-body').attr('checked',false);
		$('#main-tag').attr('checked','checked');
	}
	else
	{
		$('#main-content').attr('checked',false);
		$('#main-tag').attr('checked',false);
		$('#main-body').attr('checked','checked');	
	}
	
	handleLanguage();
};

///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) {
	    $.each(data.contentList, function (i, post) {

	        var outputDate = formatDeliveryDate(post.contentDeliveryDate);

	       $('#content-grid').append(
					 '<section>'
					+'	<div class="cnt_section">'
					+'		<a class="img">'
					+'			<canvas height="105px" width="150px" 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-top: 46px; padding-left: 66px"/>'
					+ '		</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"> </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>'
				);	

	        //assign thumbnail to array
	        arrayTemp.push({ contentId: post.contentId, thumbnail: formatStringBase64(post.contentThumbnail) });

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

	    //Get Next record number for list
	    getNextRecordNumForList();
	    
	    if(data.totalRecord < data.recordTo){
	    	ClientData.searchCond_recordTo(data.totalRecord);
	    }else{
	    	 ClientData.searchCond_recordTo(data.recordTo);
	    }

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

	    //Render Page number
	    if(totalPage == 0){
	    	reRenderPageNumber(totalPage, totalPage);
	    }
	    else{
	    	reRenderPageNumber(ClientData.searchCond_recordTo(), totalPage);
	    }
	    
	    //Toggle scroll to top Control
	    handleBackToTop();

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

//Handle Back To Top Button
function handleBackToTop(){
	if(ClientData.searchCond_recordTo() >= totalPage){
		$('#control-nextrecord').css('visibility','hidden');
	}
	else{
		$('#control-nextrecord').css('visibility','visible');
	}
	
	if(totalPage == 0){
		$('#control-nextrecord').css('visibility','hidden');
		displayResultNoRecord();
		noRecordFlg = true;
	}
    else {
        $('#msgSearchNotExist').hide();
		$('#content-grid').removeClass('lang');
		$('#content-grid').removeAttr('lang');
		enableSort();
		noRecordFlg = false;
	}
};

//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');
		$('#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();

	        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');
		}else{
			$('#control-sort-titlekana').css('display','block');
			$('#separate').css('display','block');
		}
	}	
};

//Initial Screen
function renderGridView(){
	
	var fromPage = DEFAULT_DISP_NUMBER_RECORD_FROM;
	var toPage = returnNumberDispRecordForList();
	var sortType = DEFAULT_SORT_TYPE;
	var sortOrder = DEFAULT_SORT_ORDER;
	var searchText = ClientData.searchCond_searchText();
	var searchDivision = ClientData.searchCond_searchDivision();
	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);
	
	ClientData.searchCond_genreId('');
	
	ClientData.searchCond_groupId('');
	
	var genreId = ClientData.searchCond_genreId();
	var groupId = ClientData.searchCond_groupId();
	
	//Handle display sort
	handleSortDisp();
	
	//Language Handle
	handleLanguage();
		
	//Refresh GridView
	refreshGrid();
	
	if(searchText == '' || searchText == null){
		displayResultNoRecord();
		chkSearchTextEmpty = true;
		noRecordFlg = true;
		reRenderPageNumber(0, 0);
	}
    else {
        $('#msgSearchNotExist').hide();
		chkSearchTextEmpty = false;
		//Render Gridview
		renderContent(sid, searchText, searchDivision, sortType, sortOrder, fromPage, toPage, genreId, groupId);
		
		$('#control-nextrecord').css('visibility','visible');
	}

};

//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);
	var checkflag = false;

    // Set content id for screen: content detail
	ClientData.contentInfo_contentId(outputId);
	
	// Get image of selected image
	var base64String = returnThumbnail(outputId);
	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 == 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();
};

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

//Show Next Record Function
function showNextRecordFunction(){
	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'){
		toPage = returnNumberDispRecordForList();
	}
	
	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(){
	
	$(this).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);	
	}			
	
	if(recordFrom == null || recordFrom == 'undefined'){
		recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
		ClientData.searchCond_recordFrom(recordFrom);
	}

	if(recordTo == null || recordTo == 'undefined'){
		
		recordTo = returnNumberDispRecordForList();
		ClientData.searchCond_recordFrom(recordTo);
	}
	
	sortType = '1';
	ClientData.searchCond_sortType(sortType);

	//refresh Gridview
	refreshGrid();
	
	//refresh add more record
	$('#control-nextrecord').css('visibility','hidden');	
				
	renderContent(sid, ClientData.searchCond_searchText(), 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');
		
		
	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);	
	}			
	
	if(recordFrom == null || recordFrom == 'undefined'){
		recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
		ClientData.searchCond_recordFrom(recordFrom);
	}
	
	if(recordTo == null || recordTo == 'undefined'){
		
		recordTo = returnNumberDispRecordForList();

		ClientData.searchCond_recordFrom(recordTo);
	}
	
	sortType = '2';
	//refresh gridview
	refreshGrid();
		
	
	//refresh add more record
	$('#control-nextrecord').css('visibility','hidden');
	
				
	ClientData.searchCond_sortType(sortType);
	renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordFrom, recordTo, genreId, groupId);
};

//Sort By Release Date
function sortByReleaseDateFunction(){
	
	$(this).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);	
	}			
	
	if(recordFrom == null || recordFrom == 'undefined'){
		recordFrom = DEFAULT_DISP_NUMBER_RECORD_FROM;
		ClientData.searchCond_recordFrom(recordFrom);
	}
	
	if(recordTo == null || recordTo == 'undefined'){
		
		recordTo = returnNumberDispRecordForList();

		ClientData.searchCond_recordFrom(recordTo);
	}
	
	sortType = '3';
	//refresh gridview
	refreshGrid();
		
	//refresh add more record
	$('#control-nextrecord').css('visibility','hidden');
		
	ClientData.searchCond_sortType(sortType);	
	renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, recordFrom, recordTo, genreId, groupId);
};

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

//Dialog Read Button CLick
function readSubmenuFunction(e){
    if (e) {
        e.preventDefault();
    }
    if (home_isMove == true) {
        home_isMove = false;
        return;
    }
    
	var contentId = $(this).attr('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);
	
	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);
	avwScreenMove(ScreenIds.ContentView);
};

//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();
    
    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);
			    $("#loadingIcon" + contId).fadeOut('slow', function () {
			        $('#content-thumbnail' + contId).fadeIn('slow');
			    });
			};
			imgIconNew.src = DEFAULT_IMG_CONTENT_NEW;
		};
		
		imgThumb.src = returnThumbnail(contId);
		
    }
    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]);
		 			$("#loadingIcon" + contId).fadeOut('slow', function () {
		 			    $('#content-thumbnail' + contId).fadeIn('slow');
		 			});
	    		};
		    	imgThumb.src = returnThumbnail(contId);
		    	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]);
		    		imgIconNew.onload = function(){
		    		    ctx.drawImage(imgIconNew, c.width / 2 - resizeImg[0] / 2, 0);
		    		    $("#loadingIcon" + contId).fadeOut('slow', function () {
		    		        $('#content-thumbnail' + contId).fadeIn('slow');
		    		    });
		    		};
		    		imgIconNew.src = DEFAULT_IMG_CONTENT_NEW;
		    	};
		    	imgThumb.src = returnThumbnail(contId);	
			}	
		}
    }
    	
	//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]);
			    			imgIconEdit.onload = function(){
			    			    ctx.drawImage(imgIconEdit, c.width / 2 - resizeImg[0] / 2, 0);
			    			    $("#loadingIcon" + contId).fadeOut('slow', function () {
			    			        $('#content-thumbnail' + contId).fadeIn('slow');
			    			    });
			    			};
							imgIconEdit.src = DEFAULT_IMG_CONTENT_EDIT;
			    		};
			    		imgThumb.src = returnThumbnail(contId);
			    		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]);
			    			imgIconEdit.onload = function(){
			    			    ctx.drawImage(imgIconEdit, c.width / 2 - resizeImg[0] / 2, 0);
			    			    $("#loadingIcon" + contId).fadeOut('slow', function () {
			    			        $('#content-thumbnail' + contId).fadeIn('slow');
			    			    });
			    			};
							imgIconEdit.src = DEFAULT_IMG_CONTENT_EDIT;
			    		};
			    		imgThumb.src = returnThumbnail(contId);
			    		break;
					}		    
				}				
			}
		}
		readFlg = false;
	}
};

//draw Edit Image
function drawEditImage(id){
	var img = new Image();
	img.src = returnThumbnail(id);
								
	var c = document.getElementById('content-thumbnail'+id);
			
	//use getContext to use the canvas for drawing
	var ctx = c.getContext('2d');
	img.onload = function(){	            
	 	var resizeImg = resizeResourceThumbnail(img, c.width, c.height);
	 	ctx.drawImage(img, c.width / 2 - resizeImg[0] / 2, 0, resizeImg[0], resizeImg[1]);
	 	$("#loadingIcon" + id).fadeOut('slow', function () {
	 	    $('#content-thumbnail' + id).fadeIn('slow');
	 	});
	};
};

//Search Function
function searchEventButtonFunction(){
	
	var fromPage = DEFAULT_DISP_NUMBER_RECORD_FROM;
	var toPage = returnNumberDispRecordForList();
	var sortType = DEFAULT_SORT_TYPE;
	var sortOrder = DEFAULT_SORT_ORDER;
	var searchText = $('#txtSearch').val();
	var searchDivision;
	var content = $('#main-content').attr('checked');
	var tag = $('#main-tag').attr('checked');
	var body = $('#main-body').attr('checked');
	
	
	if(content == 'checked')
	{
		searchDivision = $('#searchbox-content').val();
	}
	if(tag == 'checked')
	{
		searchDivision = $('#searchbox-tag').val();
	}
	if(body == 'checked')
	{
		searchDivision = $('#searchbox-body').val();
	}
	
	var genreId = ClientData.searchCond_genreId();
	var groupId = ClientData.searchCond_groupId();
	var sid = ClientData.userInfo_sid();
	ClientData.searchCond_sortOrder(sortOrder);
	ClientData.searchCond_sortType(sortType);
	ClientData.searchCond_searchText(searchText);
	ClientData.searchCond_searchDivision(searchDivision);
	//refresh grid
	refreshGrid();
	
	//Handle display sort
	handleSortDisp();
	
	
	if(searchText == '' || searchText == null){
		displayResultNoRecord();
		chkSearchTextEmpty = true;
		noRecordFlg = true;
		reRenderPageNumber(0, 0);
	}
    else {
        $('#msgSearchNotExist').hide();
        $('#control-nextrecord').css('visibility','hidden');
		//Render Gridview
		chkSearchTextEmpty = false;
		renderContent(sid, searchText, searchDivision, sortType, sortOrder, fromPage, toPage, genreId, groupId);
		//$('#control-nextrecord').css('visibility','visible');
	}
};

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

//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 checkflag = false;
	var contentid = $(this).attr('contentid');
	// Get image of selected image
	var base64String = returnThumbnail(contentid);
	ClientData.contentInfo_contentThumbnail(base64String);
	ClientData.contentInfo_contentId(contentid);

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

	//Open content Detail
	openContentDetail();
};

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

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

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

//format text display more record
function formatDisplayMoreRecord(){
    i18nReplaceText();
	//changeLanguage(ClientData.userInfo_language());
	$('#control-nextrecord').html(format(i18nText('dspViewMore'), returnNumberDispRecordForList()));
	
};

function changeLanguageCallBackFunction(){
	handleLanguage();
	formatDisplayMoreRecord();
	
	if(chkSearchTextEmpty){
		displayResultNoRecord();
    } else {
        
		$('#control-nextrecord').css('visibility','visible');
		enableSort();
	}
	
	document.title = i18nText('txtSearchResult') + ' | ' + i18nText('sysAppTitle');
};

function displayResultNoRecord(){
	i18nReplaceText();
	//$('#content-grid').html(i18nText('msgSearchNotExist'));
	//$('#content-grid').css({ 'text-align': 'left', 'margin-top': '20px', 'clear': 'both' });
	$('#content-grid').html('');
	$('#msgSearchNotExist').show();
	$('#msgSearchNotExist').css({ 'text-align': 'left', 'margin-top': '20px', 'clear': 'both' });

	$('#control-nextrecord').css('visibility','hidden');
	$('.control_sort_on').hide();
	$('.control_sort_off').show();
	if(getCurrentLanguage() == Consts.ConstLanguage_En || getCurrentLanguage() == Consts.ConstLanguage_Ko){
		$('#label-sort-titlekana').hide();
		$('#separate').hide();
	}
};

function enableSort(){
	$('.control_sort_on').show();
	$('.control_sort_off').hide();
	if(getCurrentLanguage() == Consts.ConstLanguage_En || getCurrentLanguage() == Consts.ConstLanguage_Ko){
		$('#control-sort-titlekana').hide();
		$('#separate').hide();
	}
};

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 result = [newWidth, newHeight];
    return result;

};

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