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

// Start Declare Variables
// ----Constant-----------//
CONTENTSEARCH.DEFAULT_DISP_NUMBER_RECORD_FROM = 0;
// CONTENTSEARCH.DEFAULT_DISP_NUMBER_RECORD_TO = 15;
CONTENTSEARCH.DEFAULT_SORT_TYPE = '1';
CONTENTSEARCH.DEFAULT_SORT_ORDER = '1';

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

CONTENTSEARCH.totalPage;
CONTENTSEARCH.chkSearchTextEmpty = false;
CONTENTSEARCH.noRecordFlg = false;
CONTENTSEARCH.home_isMove = false;

// スクロール復帰
CONTENTSEARCH.scrollTop = 0;

$(document).ready(function() {

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

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

	if (ClientData.serviceOpt_encryption() != 'Y') {
		COMMON.LockScreen();
	}

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

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

	// Check if Force Change password
	if (ClientData.requirePasswordChange() != 1) {
		// Format text display more record
		CONTENTSEARCH.formatDisplayMoreRecord();

		// remove hover effect when is touch device
		CONTENTSEARCH.removeHoverCss();

		// InitScreen
		CONTENTSEARCH.initialScreen();

		// Render Grid
		CONTENTSEARCH.renderGridView();

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

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

		// Show Next Record
		$('a#control-nextrecord').click(CONTENTSEARCH.showNextRecordFunction);
		// Sort Title
		$('#control-sort-title').click(CONTENTSEARCH.sortByTitleFunction);
		// Sort by title kana
		$('#control-sort-titlekana').click(CONTENTSEARCH.sortByTitleKanaFunction);
		// sort by release date
		$('#control-sort-releasedate').click(CONTENTSEARCH.sortByReleaseDateFunction);
		// Go To Details Page
		$('.button-details').live('click', CONTENTSEARCH.readSubmenuFunction);
		// $('.button-details').live('touchstart',
		// CONTENTSEARCH.readSubmenuFunction);
		$('.button-details').live('touchend', CONTENTSEARCH.readSubmenuFunction);
		$('.button-details').live('touchmove', function() {
			CONTENTSEARCH.home_isMove = true;
		});

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

		$('#main-search').click(CONTENTSEARCH.searchEventButtonFunction);
		$('#txtSearchWs').keydown(CONTENTSEARCH.mainSearchKeyDownFunction);
		$('#main-search-content').click(CONTENTSEARCH.mainSearchContentClickFunction);
		$('#main-search-tag').click(CONTENTSEARCH.mainSearchTagClickFunction);
		$('#main-search-body').click(CONTENTSEARCH.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
		HEADER.checkForceChangePassword();
	}

	if (COMMON.isAnonymousLogin()) {
		// プッシュメッセージ隠す
		$('#dspPushMessage').hide();
	} else {
		if ((ClientData.serviceOpt_apns() == 'Y') || (ClientData.serviceOpt_usable_push_message() == 'Y')) {
			$('#dspPushMessage').show();
		} else {
			$('#dspPushMessage').hide();
		}
	}

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

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

});

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

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

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

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

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

// Initial screen
CONTENTSEARCH.initialScreen = function() {
	var searchText = ClientData.searchCond_searchText();
	var searchDivision = ClientData.searchCond_searchDivision();

	$('#txtSearchWs').val(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');
	}

	CONTENTSEARCH.handleLanguage();
};

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

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

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

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

			var outputDate = "";
			if (post.contentDeliveryDate != null && post.contentDeliveryDate != undefined && post.contentDeliveryDate != 'undefined') {
				outputDate = COMMON.formatDeliveryDate(post.contentDeliveryDate);
			}

			var htmlTemp = '<section class="sectionsearchlist">'
				+ '	<div class="cnt_section_list">'
				+ '		<a class="img">'
				+ '			<canvas height="110" width="150" id="content-thumbnail' + post.contentId + '" contentid="' + post.contentId + '" style="display:none;"></canvas>'
				+ '	        <img id="loadingIcon' + post.contentId + '" src="./img/data_loading.gif" height="25px" width="25px" style="padding: 46px; "/>'
				+ '		</a>'
				+ '		<div class="text">'
				+ '			<a id="title' + post.contentId + '" class="name dialog" contentid="' + post.contentId + '">'
				+ '             <img class="listIcon" src="' + HEADER.getIconTypeContent(post.contentType) + '" width="20" height="20">'
				+ '             <div class="contentsearch_title">' + post.contentTitle + '</div>'
				+ '         </a>'
				+ '			<div class="info">'
				+ '				<ul class="date">'
				+ '					<li><span class="lang" lang="txtPubDt"> </span> : ' + outputDate + '</li>'
				+ '					<li><span class="lang" lang="txtViewDt"> </span>:<span id="lblVdate' + post.contentId + '"> </span></li>'
				+ '				</ul>'
				+ '				<ul class="pic">'
				+ '					<li><img src="' + COMMON.DEFAULT_IMG_OPTION_MEMO + '" id="imgMemo' + post.contentId + '" class="sticker"  /></li>'
				+ '					<li><img src="' + COMMON.DEFAULT_IMG_OPTION_MARKING + '" id="imgBookMark' + post.contentId + '" class="pen"  /></li>'
				+ '					<li><ul class="iconList">{share}<li><a class="read lang button-details" contentid="' + post.contentId + '" lang="txtRead">読む</a></li></ul></li>'
				+ '				</ul>'
				+ '			</div>'
				+ '		</div>'
				+ '	</div>'
				+ '</section>';

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

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

			CONTENTSEARCH.getNextRecordNumForList();

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

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

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

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

			// Check if user has read this content or not.
			CONTENTSEARCH.checkUserHasReadContent(post.contentId, post.resourceVersion, post.metaVersion, versionArr, metaArr, readArr);

			// assign version to array
			COMMON.resourceVersionArr.push({
				contentid : post.contentId,
				resourceversion : post.resourceVersion
			});

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

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

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

		// Get Next record number for list
		CONTENTSEARCH.getNextRecordNumForList();

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

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

		// Render Page number
		if (CONTENTSEARCH.totalPage == 0) {
			CONTENTSEARCH.reRenderPageNumber(CONTENTSEARCH.totalPage, CONTENTSEARCH.totalPage);
		} else {
			CONTENTSEARCH.reRenderPageNumber(ClientData.searchCond_recordTo(), CONTENTSEARCH.totalPage);
		}

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

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

// Handle Back To Top Button
CONTENTSEARCH.handleBackToTop = function() {
	if (ClientData.searchCond_recordTo() >= CONTENTSEARCH.totalPage) {
		$('#control-nextrecord').css('visibility', 'hidden');
	} else {
		$('#control-nextrecord').css('visibility', 'visible');
	}

	if (CONTENTSEARCH.totalPage == 0) {
		$('#control-nextrecord').css('visibility', 'hidden');
		CONTENTSEARCH.displayResultNoRecord();
		CONTENTSEARCH.noRecordFlg = true;
	} else {
		$('#msgSearchNotExist').hide();
		$('#content-grid').removeClass('lang');
		$('#content-grid').removeAttr('lang');
		CONTENTSEARCH.enableSort();
		CONTENTSEARCH.noRecordFlg = false;
	}
};

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

	if (I18N.getCurrentLanguage() == COMMON.Consts.ConstLanguage_En || I18N.getCurrentLanguage() == COMMON.Consts.ConstLanguage_Ko) {
		$('#control-sort-titlekana').css('display', 'none');
		$('#separate').css('display', 'none');
		$("#titlekana-sorttype").html('');
	} else {
		if (ClientData.searchCond_sortOrder() != null && ClientData.searchCond_sortOrder() != 'undefined' || ClientData.searchCond_sortType() != '') {
			var typeSort = ClientData.searchCond_sortType();
			var orderSort = ClientData.searchCond_sortOrder();

			HEADER.setStatusSort('#' + $('#menu_sort li.current a').attr('id'), orderSort == COMMON.Consts.ConstOrderSetting_Asc);
		}
		if (CONTENTSEARCH.noRecordFlg) {
			$('#control-sort-titlekana').css('display', 'block');
			$('#separate').css('display', 'block');
		} else {
			$('#control-sort-titlekana').css('display', 'block');
			$('#separate').css('display', 'block');
		}
	}
};

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

	//var fromPage = CONTENTSEARCH.DEFAULT_DISP_NUMBER_RECORD_FROM;
	//var toPage = CONTENTSEARCH.returnNumberDispRecordForList();
	var sortType = CONTENTSEARCH.DEFAULT_SORT_TYPE;
	var sortOrder = CONTENTSEARCH.DEFAULT_SORT_ORDER;
	var searchText = ClientData.searchCond_searchText();
	var searchDivision = ClientData.searchCond_searchDivision();
	var sid = ClientData.userInfo_sid();

	var offsetPage = 0;
	var limitPage = CONTENTSEARCH.returnNumberDispRecordForList();

	ClientData.searchCond_recordFrom(0);
	ClientData.searchCond_recordTo(0);
	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
	CONTENTSEARCH.handleSortDisp();

	// Language Handle
	CONTENTSEARCH.handleLanguage();

	// Refresh GridView
	CONTENTSEARCH.refreshGrid();

	$('#msgSearchNotExist').hide();
	CONTENTSEARCH.chkSearchTextEmpty = false;
	// Render Gridview
	CONTENTSEARCH.renderContent(sid, searchText, searchDivision, sortType, sortOrder, offsetPage, limitPage, genreId, groupId);
	$('#control-nextrecord').css('visibility', 'visible');

};

// Canvas Click function
CONTENTSEARCH.canvasClickFunction = function(e) {

	if (e) {
		e.preventDefault();
	}
	if (CONTENTSEARCH.home_isMove == true) {
		CONTENTSEARCH.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 = CONTENTSEARCH.returnThumbnail(outputId);
	ClientData.contentInfo_contentThumbnail(base64String);

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

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

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

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

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

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

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

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

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

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

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

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

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

};

// Show Next Record Function
CONTENTSEARCH.showNextRecordFunction = function() {
	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 = CONTENTSEARCH.totalPage;

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

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

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

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

	var offset = 0;
	var limit = CONTENTSEARCH.returnNumberDispRecordForList();

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

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

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

	// refresh Gridview
	CONTENTSEARCH.refreshGrid();

	// refresh add more record
	$('#control-nextrecord').css('visibility', 'hidden');

	CONTENTSEARCH.renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, offset, limit, genreId, groupId);
};

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

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

	var offset = 0;
	var limit = CONTENTSEARCH.returnNumberDispRecordForList();

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

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

	sortType = '2';
	// refresh gridview
	CONTENTSEARCH.refreshGrid();

	// refresh add more record
	$('#control-nextrecord').css('visibility', 'hidden');

	ClientData.searchCond_sortType(sortType);
	CONTENTSEARCH.renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, offset, limit, genreId, groupId);
};

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

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

	var offset = 0;
	var limit = CONTENTSEARCH.returnNumberDispRecordForList();

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

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

	sortType = '3';
	// refresh gridview
	CONTENTSEARCH.refreshGrid();

	// refresh add more record
	$('#control-nextrecord').css('visibility', 'hidden');

	ClientData.searchCond_sortType(sortType);
	CONTENTSEARCH.renderContent(sid, ClientData.searchCond_searchText(), ClientData.searchCond_searchDivision(), sortType, sortOrder, offset, limit, genreId, groupId);
};

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

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

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

// Dialog Read Button CLick
CONTENTSEARCH.readSubmenuFunction = function(e) {
	if (e) {
		e.preventDefault();
	}
	if (CONTENTSEARCH.home_isMove == true) {
		CONTENTSEARCH.home_isMove = false;
		return;
	}
	var contentId = $(this).attr('contentid');
	// check limit of content
	LIMIT_ACCESS_CONTENT.checkLimitContent(contentId, function() {
		CONTENTSEARCH.readSubmenuFunction_callback(contentId);
	}, function() {
	});

};

// read content callback
CONTENTSEARCH.readSubmenuFunction_callback = function(contentId) {
	var contentThumbnail = CONTENTSEARCH.returnThumbnail(contentId);
	var date = new Date();
	var month = date.getMonth() + 1;
	var day = date.getDate();

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

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

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

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

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

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

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

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

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

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

	ClientData.IsRefresh(false);

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

	}
};

// Check if Content Has marking or memo
CONTENTSEARCH.checkContentMarkingMemoOption = function(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
CONTENTSEARCH.checkUserHasReadContent = function(contId, resourceVer, metaVer, versionArr, metaArr, readArr) {

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

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

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

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

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

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

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

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

				readFlg = true;
				break;
			}
		}
	}

	// 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 = CONTENTSEARCH.resizeResourceThumbnail(imgThumb, c.width, c.height);
							ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
							imgIconEdit.onload = function() {
								ctx.drawImage(imgIconEdit, c.width / 2 - resizeImg[0] / 2, c.height - resizeImg[1]);

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

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

						// 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 = CONTENTSEARCH.resizeResourceThumbnail(imgThumb, c.width, c.height);
							ctx.drawImage(imgThumb, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
							imgIconEdit.onload = function() {
								ctx.drawImage(imgIconEdit, c.width / 2 - resizeImg[0] / 2, c.height - resizeImg[1]);
								$("#loadingIcon" + contId).fadeOut('slow', function() {
									$('#content-thumbnail' + contId).fadeIn('slow');
								});
							};
							imgIconEdit.src = COMMON.DEFAULT_IMG_CONTENT_EDIT;
						};
						// thumbnail.
						if (contentThumbnail == '' || contentThumbnail == null) {
							if (!COMMON.isPdfContent(contentType)) {
								var src = HEADER.getThumbnailForOtherType(contentType);
								if (src != '') {
									imgThumb.src = src;
								}
							}
						} else {
							imgThumb.src = contentThumbnail;
						}

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

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

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

	if (imgSrc != null) {

	} else {
		var contentType = CONTENTSEARCH.returnContentType(id);

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

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

	// use getContext to use the canvas for drawing
	var ctx = c.getContext('2d');
	ctx.clearRect(0, 0, c.width, c.height);
	img.onload = function() {
		var resizeImg = CONTENTSEARCH.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;
};

// Search Function
CONTENTSEARCH.searchEventButtonFunction = function() {

	var sortType = CONTENTSEARCH.DEFAULT_SORT_TYPE;
	var sortOrder = CONTENTSEARCH.DEFAULT_SORT_ORDER;
	var searchText = $('#txtSearchWs').val();
	var searchDivision;
	var content = $('#main-content').attr('checked');
	var tag = $('#main-tag').attr('checked');
	var body = $('#main-body').attr('checked');

	var offset = 0;
	var limit = CONTENTSEARCH.returnNumberDispRecordForList();

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

	// Handle display sort
	CONTENTSEARCH.handleSortDisp();

	$('#msgSearchNotExist').hide();
	$('#control-nextrecord').css('visibility', 'hidden');
	// Render Gridview
	CONTENTSEARCH.chkSearchTextEmpty = false;
	CONTENTSEARCH.renderContent(sid, searchText, searchDivision, sortType, sortOrder, offset, limit, genreId, groupId);
};

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

// handle display sort direction
CONTENTSEARCH.handleSortDisp = function() {

	var typeSort;
	var orderSort;

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

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

// function Open SubMenu Dialog
CONTENTSEARCH.titleClickFunction = function(e) {
	if (e) {
		e.preventDefault();
	}
	if (CONTENTSEARCH.home_isMove == true) {
		CONTENTSEARCH.home_isMove = false;
		return;
	}
	var checkflag = false;
	var contentid = $(this).attr('contentid');
	// Get image of selected image
	var base64String = CONTENTSEARCH.returnThumbnail(contentid);
	ClientData.contentInfo_contentThumbnail(base64String);
	ClientData.contentInfo_contentId(contentid);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

};

CONTENTSEARCH.displayResultNoRecord = function() {
	I18N.i18nReplaceText();
	// $('#content-grid').html(I18N.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 (I18N.getCurrentLanguage() == COMMON.Consts.ConstLanguage_En || I18N.getCurrentLanguage() == COMMON.Consts.ConstLanguage_Ko) {
		/* $('#control-sort-titlekana').hide(); */
		$('#separate').hide();
		$('#control-sort-titlekana').hide();
	}
};

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

CONTENTSEARCH.resizeResourceThumbnail = function(mg, width, height) {
	var newWidth;
	var newHeight;
	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;

};

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

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

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

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

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

	}, function() {
		// console.log("checkLimitContent_bbb");
	});

};

CONTENTSEARCH.showContentView = function() {

	// TOPに戻す
	var y = 0;
	if (document.documentElement.scrollTop) {
		y = document.documentElement.scrollTop;
	}
	if (document.body.scrollTop) {
		if (y == undefined || y == 0) {
			y = document.body.scrollTop;
		}
	}
	if (y == undefined || y == null) {
		y = 0;
	}
	CONTENTSEARCH.scrollTop = y;
	window.scrollTo(0, 0);

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

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

	CONTENTVIEW.ready();

};

CONTENTSEARCH.cssInit = function() {
	$('html').css({
		'overflow-y' : 'scroll'
	});
	$('html,body').css({
		'height' : '100%',
		'margin' : '0',
		'padding' : '0'
	});
	$('html>body').css({
		'font-size' : '16px',
		'font-size' : '68.75%'
	});
	$('body').css({
		'font-family' : 'Verdana, helvetica, arial, sans-serif',
		'font-size' : '68.75%',
		'background' : '#fff',
		'color' : '#333'
	});
};

// ダウンロードButton CLick
CONTENTSEARCH.downloadSubmenuFunction = function(e) {
	if (e) {
		e.preventDefault();
	}

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

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

	// Download content
	HEADER.downloadResourceById(contentId);

};