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

HOME_CHECK.DEFAULT_SORT_TYPE = "3";
HOME_CHECK.DEFAULT_SORT_ORDER = "2";
HOME_CHECK.DEFAULT_SEARCH_DIVISION = 0;

HOME_CHECK.home_realTotalRecord = 0;
// Thumbnail array
HOME_CHECK.thumbnailArr = [];
// Content type array.
HOME_CHECK.contentTypeArr = [];
HOME_CHECK.contentIdArray = [];
HOME_CHECK.totalPage;

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


HOME_CHECK.projectInfoArr = []; //ProjectInfo array.

//プッシュメッセージ一覧
HOME_CHECK.newMessageCnt = 0;
// ==========================================================
$(document).ready(function() {

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

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

    $('#dspCommunication').click(HOME_CHECK.showCommunicationDialog);
    $('#dspCommunication').show();
    $('#dspCommonContent').click(HOME_CHECK.viewCommonContent);
    $('#dspCommonContent').show();
    $('#dspSettingCheck').click(HOME_CHECK.viewSetting);
    $('#dspSettingCheck').show();
    $('#dspRefreshCheck').click(HOME_CHECK.refreshProject);
    $('#dspRefreshCheck').show();

    $('.dspBack').click(HOME_CHECK.backProjectList);

    // プロジェクト一覧　初期表示
    HOME_CHECK.initProjectView();
    HOME_CHECK.getPushMessageNew();

    // Go To Details Page
    //$('.button-report-details').live('click', HOME_CHECK.reportClickFunction);
    //$('.button-report-details').live('touchend', HOME_CHECK.reportClickFunction);

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

});

HOME_CHECK.viewCommonContent = function() {
    HOME_CHECK.initContentView(null, "2");
};

HOME_CHECK.viewSetting = function() {
    $('#listValues').hide();
    $('.sectionSetting').show();
    $('.sectionSetting').css("margin-top", "65px");

    $('#projectBar').hide();
    $('#settingBar').show();
};

// Initial Project Screen
HOME_CHECK.initProjectView = function() {

    var sid = ClientData.userInfo_sid();

    // Render Project
    HOME_CHECK.renderProject(sid);

};

// Initial Content Screen
HOME_CHECK.initContentView = function(relatedContentList, projectUse, projectName) {

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

    var contentIds = '';
    if (relatedContentList) {
        $.each(relatedContentList, function(i, post) {
            if (contentIds != ''){
                contentIds = contentIds + ',' +  post.contentId;
            } else {
                contentIds = post.contentId;
            }
        });
    }

    var offsetPage = 0;
    var limitPage = 999; //暫定

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

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

    // Language Handle
    //HOME.handleLanguage();
    // handle
    //HOME.handleSortDisp();

    $('#listValues').hide();
    $('#content-grid').show();

    $('#projectBar').hide();
    $('#contentBar').show();

    // Refresh GridView
    HOME_CHECK.refreshGrid();

    //HOME.resetShowNextRecordCount();

    // Render Gridview
    HOME_CHECK.renderContent(sid, searchText, searchDivision, sortType, sortOrder, offsetPage, limitPage, genreId, groupId, contentIds, projectUse, projectName);

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

};

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

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

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

        var countCnt = 0;
        var versionArr = ClientData.ResourceVersion();
        var metaArr = ClientData.MetaVersion();
        var readArr = ClientData.ReadingContentIds();
        
        // プロジェクト名表示
        if (projectName) {
        	$('#content-grid').append($("<div/>", { class: "projectName_div" }).append($("<span/>", { class: "textEllipsis" }).text(projectName)));
        }

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

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

            var gridHtml = "" 
            	+ '<section class="sectionhomelist">'
                + '	<div class="cnt_section_list">'
                + '		<a class="img">'
                + '			<canvas height="110" width="150" id="content-thumbnail' + post.contentId + '" contentid="' + post.contentId + '" style="display:none;"></canvas>'
                + '	        <img id="loadingIcon' + post.contentId + '" src="./img/data_loading.gif" height="25px" width="25px" style="padding: 46px; "/>'
                + '		</a>'
                + '		<div class="text">'
                + '         <a id="title' + post.contentId + '" class="dialog name lang" lang="lblTitle" contentid="' + post.contentId + '">'
                + '             <img class="listIcon" src="' + COMMON.getIconTypeContent(post.contentType) + '" width="20" height="20" style="float:left">'
                + ' 			<div class="content-list textEllipsis" style="">' + post.contentTitle + '</div>'
                + '         </a>'
                + '			<div class="info">'
                + '				<ul class="date">'
                + '					<li><span class="lang" lang="txtPubDt"> </span>：' + outputDate + '</li>'
                + '					<li><span class="lang" lang="txtViewDt"> </span>：<span id="lblVdate' + post.contentId + '"> </span></li>'
                + '				</ul>'
                + '			</div>'
                + '		</div>'
                + '		<div class="pic">'
                + '			<ul class="iconList"><li><a class="read lang button-details" contentid="' + post.contentId + '" lang="txtRead">読む</a></li></ul>'
                + '		</div>'
                + '	</div>'
                + '</section>';

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

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

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

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

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

            // Check if user has read this content or not.
//            HOME_CHECK.checkUserHasReadContent(post.contentId, post.resourceVersion, post.metaVersion, versionArr, metaArr, readArr); TODO Newマークを使うなら復元
            HOME_CHECK.getContentThumbnail(post.contentId);
            // 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
            });

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

        HOME_CHECK.home_realTotalRecord += data.contentList.length;

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

        I18N.i18nReplaceText();
    });
};

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

// Get content type base on contentid
HOME_CHECK.returnContentType = function(contentid) {
    // Array Length
    var iArrCnt = HOME_CHECK.contentTypeArr.length;
    // Get contentType in array by contentId
    for ( var i = 0; i < iArrCnt; i++) {
        if (HOME_CHECK.contentTypeArr[i].contentId == contentid) {
            return HOME_CHECK.contentTypeArr[i].contentType;
        }
    }
};

// サムネイル情報を取得
HOME_CHECK.getContentThumbnail = function(contId) {

    var imgThumb = new Image();

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

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

    imgThumb.onload = function() {
        var resizeImg = COMMON.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 = COMMON.getThumbnailForOtherType(contentType);
            if (src != '') {
                imgThumb.src = src;
            }
        }
    } else {
        imgThumb.src = contentThumbnail;
    }

};

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

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

        var src = COMMON.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 = COMMON.resizeResourceThumbnail(img, c.width, c.height);
        ctx.drawImage(img, (c.width / 2) - (resizeImg[0] / 2) + 4, c.height - resizeImg[1] + 4, resizeImg[0], resizeImg[1]);
        $("#loadingIcon" + id).fadeOut('slow', function() {
            $('#content-thumbnail' + id).fadeIn('slow');
        });
    };

    img.src = imgSrc;
};

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

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

};

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

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

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

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

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

    var checkflag = false;

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

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

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

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

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

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

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

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

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

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

$(function() {

});

HOME_CHECK.cssInit = function() {
    $('html').css({
        'overflow-y' : 'scroll'
    });
    $('html,body').css({
        'height' : '100%',
        'margin' : '0',
        'padding' : '0'
    });
    $('body').css({
        'background' : '#f4f4f4',
        'color' : '#333'
    });
};

HOME_CHECK.showContentView = function() {

    var y = 0;
    if (document.documentElement.scrollTop) {
        y = document.documentElement.scrollTop;
    }
    if (document.body.scrollTop) {
        if (y == undefined || y == 0) {
            y = document.body.scrollTop;
        }
    }
    if (y == undefined || y == null) {
        y = 0;
    }
    HOME_CHECK.scrollTop = y;
    window.scrollTo(0, 0);

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

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

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

};

// /Render Project
HOME_CHECK.renderProject = function(sid) {
    var params = {
        sid : sid
    };

    HOME_CHECK.checkApi('webProjectList', params, 'POST', function(data) {

        var countCnt = 0;

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

            HOME_CHECK.renderAddProject(post);

            // assign content type to array
            HOME_CHECK.projectInfoArr.push({
                projectId : post.projectId,
                projectType : post.projectType,
                projectName : post.projectName
            });
        });
    });
};

HOME_CHECK.renderAddProject = function(post) {

	var listLi = $("<li></li>", {
		id: "list_" + post.projectId,
		class: "read"
	});
	
	var taskInfo = $("<div/>", {class: "taskInfoDiv"});
	var codeAndExpiration = $("<ul/>", {class: "codeAndExpiration"});

	var startDate = "-/-/-";
	var endDate = "-/-/-";
	var dateStr = " ～ ";
	var periodStr = "期間：";
	var isInspect = post.projectReportType == "1";
	
	if (isInspect) {
		periodStr = "作業期間：";
		var projectStartDate = post.projectStartDate.replace(/-/g, '/');
		var projectEndDate = post.projectEndDate.replace(/-/g, '/');
		if (!HOME_CHECK.isInspectingProject(projectStartDate)) {
			// プロジェクトの開始日になってない場合
			dateStr = periodStr + "作業データがありません。" + "「" + projectStartDate + "」から情報更新ができるようになります。";
		} else if (post.reportStartDate && post.reportEndDate) {
			startDate = post.reportStartDate.replace(/-/g, '/');
			endDate = post.reportEndDate.replace(/-/g, '/');
			dateStr = periodStr + startDate + dateStr + endDate;
		} else if (HOME_CHECK.isCompletedProject(projectEndDate)) {
			// 終了したプロジェクトの場合非表示
			return;
		} else {
			// 対象作業がない場合
			dateStr = periodStr + "作業データがありません。";
		}
	} else {
		startDate = post.projectStartDate.replace(/-/g, '/');
		endDate = post.projectEndDate.replace(/-/g, '/');
		dateStr = periodStr + startDate + dateStr + endDate;
	}
	codeAndExpiration.append($("<li/>", {class: "period"}).text(dateStr));

	taskInfo.append(codeAndExpiration);

	taskInfo.append($("<p/>", {class: "projectName"}).text(post.projectName));
	taskInfo.append($("<p/>", {class: "workContent"}).html(post.projectDescriptions.replace(/\n/ig, "<br>")));

	listLi.append(taskInfo);

	var actionBtnDiv = $("#actionBtnDiv").clone().attr("id", post.projectId + "_actionBtnDiv");
	actionBtnDiv.css("display", "flex");
	
	if (isInspect && !HOME_CHECK.isInspectingProject(projectStartDate)) {
        $(actionBtnDiv.children()[0]).find('img').attr("src","img/check/icon_working_off.png");
	} else {
		$(actionBtnDiv.children()[0]).on("click", function() {
			//CHK.reportMode = "1";
			HOME_CHECK.createSession(post.projectId, post.projectType, post.projectReportType); 
		});
	}
	$(actionBtnDiv.children()[1]).hide();

    if (post.relatedContentList.length > 0) {
        $(actionBtnDiv.children()[2]).on("click", function() {
            HOME_CHECK.initContentView(post.relatedContentList, null, post.projectName);
        });
    } else {
        $(actionBtnDiv.children()[2]).find('img').attr("src","img/check/icon_document_reference_off.png");
        $(actionBtnDiv.children()[2]).prop("disabled", true);
    }
    
	listLi.append(actionBtnDiv);

	$(".addition_list").append(listLi);

};

// プロジェクトが始まったか判定
HOME_CHECK.isInspectingProject = function(projectStartDateStr) {
	var now = new Date();
	var projectStartDate = new Date(projectStartDateStr);
	return now.getTime() >= projectStartDate.getTime();
}

// プロジェクトが終了したか判定
HOME_CHECK.isCompletedProject = function(projectEndDateStr) {
	var now = new Date();
	var projectEndDate = new Date(projectEndDateStr);
	return now.getTime() > projectEndDate.getTime();
}

// Report Click function
HOME_CHECK.reportClickFunction = function(e) {
    if (e) {
        e.preventDefault();
    }

    var projectId = $(this).attr('id');

    HOME_CHECK.createSession(projectId);

};

HOME_CHECK.createSession = function(projectId, projectType, projectReportType) {
    
    var checkApiUrl = AVWEB.getCheckApiUrl(ClientData.userInfo_accountPath()) + "/webCreateSession/";

    //var type = HOME_CHECK.returnProjectType(projectId);
    var linkUrl = AVWEB.getShopApiUrl(ClientData.userInfo_accountPath()) + "/vtour/report/" + projectId + "/?view_mode=1&project_type=" + projectType + "&project_report_type=" + projectReportType + "&is_cms=0&is_web=1";

    console.log("linkUrl:" + linkUrl);

	var params = {
	        sid: ClientData.userInfo_sid()
        };

	var sysSettings = AVWEB.avwSysSetting();
	// ajax によるAPIの実行（dataType text）
	$.ajax( {
		async:		false,
		type:		'GET',
		url:		checkApiUrl,
		dataType:	'text',
		data:		params,
		crossDomain: true,
  		beforeSend: function(xhr) {
  			xhr.setRequestHeader('X-AGT-AppId', sysSettings.appName);
			xhr.setRequestHeader('X-AGT-AppVersion', sysSettings.appVersion);
   		},
		success: function(data) {
            //var linkUrlTmp2 = linkUrl + "&;jsessionid=" + data;
            window.open().location.href = linkUrl;
		},
		error: function(xmlHttpRequest, txtStatus, errorThrown) {
			/* call custom error process */
			AVWEB.avwLog("error" + errorThrown);
		}
	});
};

// Get project type base on projectId
HOME_CHECK.returnProjectType = function(projectId) {
    // Array Length
    var iArrCnt = HOME_CHECK.projectInfoArr.length;

    // Get contentType in array by contentId
    for ( var i = 0; i < iArrCnt; i++) {
        if (HOME_CHECK.projectInfoArr[i].projectId == projectId) {
            return HOME_CHECK.projectInfoArr[i].projectType;
        }
    }
    return -1;
};

// Call API
HOME_CHECK.checkApi = function(name, params, method, callback, errorCallback) {
    var checkApiUrl = AVWEB.getCheckApiUrl(ClientData.userInfo_accountPath())
	AVWEB.avwCmsApiWithUrl(checkApiUrl, ClientData.userInfo_accountPath(), name, method, params, callback, errorCallback);
};

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

HOME_CHECK.backProjectList = function() {
	$('#listValues').show();
	$('.sectionSetting').hide();
	$('#content-grid').hide();

	$('#projectBar').show();
	$('#settingBar').hide();
	$('#contentBar').hide();
	
	$('.toast-container').remove();
};


///Refresh Project
var isRefreshing = false;

HOME_CHECK.refreshProject = function() {
	if (!isRefreshing) {
		isRefreshing = true;
		
		var params = {
			sid : ClientData.userInfo_sid()
		};
		
			
		HOME_CHECK.lockLayout();
		animateRefreshIcon();
		
		HOME_CHECK.checkApi('webProjectList', params, 'POST', function(data) {
			var countCnt = 0;
			$(".addition_list").html("");
			HOME_CHECK.projectInfoArr.clear();
			$.each(data.projectList, function(i, post) {
				HOME_CHECK.renderAddProject(post);
				// assign content info to array
				HOME_CHECK.projectInfoArr.push({
					projectId : post.projectId,
					projectType : post.projectType,
					projectName : post.projectName
				});
			});
			
			HOME_CHECK.unlockLayout();
			isRefreshing = false;
		});
	}
};

function animateRefreshIcon() {
	$("#dspRefreshCheck").zIndex(0);
	$("#dspRefreshCheck").animate({zIndex:1}, {duration:1500, easing: "swing", 
    	step:function(now) { 
    		$("#dspRefreshCheck").css({transform:'rotate(' + now * 360 + 'deg)'});
    	}, 
    	complete:function() {
    		if (isRefreshing) {
    			animateRefreshIcon();
    		}
    	}
    });
}

/**
 * コミュニケーションダイアログを表示
 *
 * @param message 表示メッセージ
 */
HOME_CHECK.showCommunicationDialog = function() {
	$("#communication").css("top", ($(window).height()-$("#communication").height())/2);
	$("#communication").css("left", ($(window).width()-$("#communication").width())/2);
	HOME_CHECK.lockLayout();
	$("#communication").show();
}

HOME_CHECK.closeDialog = function() {
	HOME_CHECK.unlockLayout();
	$("#communication").hide();
	$("#recept_push_message").hide();
	$("#select_project_for_send").hide();
	$("#send_push_message").hide();
	$("#message_form").hide();
}


HOME_CHECK.showPushMessageList = function() {
	$("#communication").hide();
	$("#recept_push_message").css("top", ($(window).height()-$("#recept_push_message").height())/2);
	$("#recept_push_message").css("left", ($(window).width()-$("#recept_push_message").width())/2);
	$(".new_message_mark").remove();
	$("#recept_push_message").show();
	var params = {
		sid : ClientData.userInfo_sid()
	};
	$("#recept_push_message_list").empty();
	
	HOME_CHECK.checkApi('webPushMessageList', params, 'POST', function(data) {
		$.each(data.pushMessageList, function(i, json) {
			var li = $("<li/>", { style: "height:auto;border-bottom:1px solid black;width:560px;display:inline-block;position:relative;" });
			var leftDiv = $("<div/>", { style: "text-align:left;margin: 20px 5px 20px 20px;width:290px;" });
			leftDiv.append($("<div/>", { style: "font-size:20px;overflow:hidden;width:100%;margin:10px 0;" }).html(json.pushMessage.replace(/\n/ig, "<br>")));
			leftDiv.append($("<div/>", { style: "font-size:16px;overflow:hidden;width:100%;" }).text(json.pushSendDate));
			var rightDiv = $("<div/>", { style: "text-align:right;width:200px;position:absolute;bottom:0;right:20px;" });
			if (json.projectName) {
				rightDiv.append($("<div/>", { style: "font-size:16px;text-overflow:ellipsis;overflow:hidden;width:100%;white-space:nowrap;" }).text("プロジェクト名"));
				rightDiv.append($("<div/>", { style: "font-size:16px;text-overflow:ellipsis;overflow:hidden;width:100%;white-space:nowrap;font-weight:bold;" }).text(json.projectName));
			}
			if (json.pushSendLoginId) {
				rightDiv.append($("<div/>", { style: "font-size:16px;text-overflow:ellipsis;overflow:hidden;width:100%;white-space:nowrap;margin:10px 0;" }).text("送信者： " + json.pushSendLoginId));
			}
			li.append(leftDiv);
			li.append(rightDiv);
			if (i < HOME_CHECK.newMessageCnt) {
				li.append($("<p/>", { class:"new_message_mark", style: "background-color:red;width:10px;height:10px;border-radius:10px;position:absolute;top:0;left:5px;" }));
			}
			$("#recept_push_message_list").append(li);
		});
		
		HOME_CHECK.newMessageCnt = 0;
		HOME_CHECK.changeImageForReceptPushMessage();
	});
}

// プッシュメッセージの新着状況
HOME_CHECK.changeImageForReceptPushMessage = function(isNew) {
	var menuImgSrc = "img/check/communication_menu_icon@3x.png";
	var listImgSrc = "img/check/ic_communication_push_message_list.png";
	if (isNew) {
		menuImgSrc = "img/check/ic_communication_menu_with_badge.png";
		listImgSrc = "img/check/ic_communication_push_message_list_with_badge.png";
	}
	$("#communication_menu_img").attr("src", menuImgSrc);
	$("#message_list_img").attr("src", listImgSrc);
}

HOME_CHECK.showSelectProjectForPushMessage = function() {
	$("#communication").hide();
	$("#send_push_message").hide();
	$("#select_project_for_send").css("top", ($(window).height()-$("#select_project_for_send").height())/2);
	$("#select_project_for_send").css("left", ($(window).width()-$("#select_project_for_send").width())/2);
	$("#select_project_for_send").show();
	$("#selectable_project_list").empty();
	$.each(HOME_CHECK.projectInfoArr, function(i, json) {
		var li = $("<li/>", { style: "height:auto;border-bottom:1px solid black;width:400px;display:flex;position:relative;line-height:40px;cursor:pointer;"
			, onclick: "HOME_CHECK.showSendPushMessage(" + json.projectId + ", '" + json.projectName + "');" });
		li.append($("<div/>", { style: "font-size:20px;overflow:hidden;width:340px;margin:10px 10px;", title: json.projectName }).text(json.projectName));
		li.append($("<img>", { style: "float:right;margin:10px 0;height:40px;width:20px;position:absolute;right:20px;", src: "img/main_next.png" }));
		$("#selectable_project_list").append(li);
	});
}

HOME_CHECK.showSendPushMessage = function(projectId, projectName) {
	$("#select_project_for_send").hide();
	$("#send_push_message").css("top", ($(window).height()-$("#send_push_message").height())/2);
	$("#send_push_message").css("left", ($(window).width()-$("#send_push_message").width())/2);
	$("#send_push_message").show();
	
	$("#send_project_name").text(projectName);
	$("#all_group").removeClass("selected_send_type");
	$("#sender_group").addClass("selected_send_type");
	$("#messageFormName").text("自由入力");
	$("#send_message").val("");
	$("#selectedProjectIdForSendPushMessage").val(projectId);
}

HOME_CHECK.changeSendType = function(clickedElem) {
	if (!clickedElem.hasClass("selected_send_type")) {
		$("#sender_group").toggleClass("selected_send_type");
		$("#all_group").toggleClass("selected_send_type");
	}
}

HOME_CHECK.showMessageFormList = function() {
	$("#send_push_message").hide();
	$("#message_form").css("top", ($(window).height()-$("#message_form").height())/2);
	$("#message_form").css("left", ($(window).width()-$("#message_form").width())/2);
	$("#message_form").show();
	
	var params = {
			sid : ClientData.userInfo_sid()
	};
	
	HOME_CHECK.checkApi('getPushMessage', params, 'POST', function(data) {
		$("#message_form_list").empty();
		// 自由入力
		var freeLi = $("<li/>", { style: "height:auto;border-bottom:1px solid black;width:400px;display:inline-block;position:relative;cursor:pointer;"
			, onclick:"HOME_CHECK.backToSendPushMessage('" + "自由入力" + "', '" + "" + "');" });
		var freeDiv = $("<div/>", { style: "text-align:left;margin: 20px 5px 20px 20px;width:360px;" });
		freeDiv.append($("<div/>", { style: "font-size:20px;overflow:hidden;width:100%;margin:10px 0;font-weight:bold;width:100%;" }).text("自由入力"));
		freeLi.append(freeDiv);
		$("#message_form_list").append(freeLi);
		$.each(data.pushMessage, function(i, json) {
			var li = $("<li/>", { style: "height:auto;border-bottom:1px solid black;width:400px;display:inline-block;position:relative;cursor:pointer;"
				, onclick:"HOME_CHECK.backToSendPushMessage('" + json.name + "', '" + json.value + "');" });
			var div = $("<div/>", { style: "text-align:left;margin: 20px 5px 20px 20px;width:360px;" });
			div.append($("<div/>", { style: "font-size:20px;overflow:hidden;width:100%;margin:10px 0;font-weight:bold;width:100%;" }).text(json.name));
			div.append($("<div/>", { style: "font-size:16px;overflow:hidden;width:100%;text-indent:10px;width:100%;" }).text(json.value));
			li.append(div);
			$("#message_form_list").append(li);
		});
	});
}

HOME_CHECK.backToSendPushMessage = function(formName, formValue) {
	$("#message_form").hide();
	$("#send_push_message").show();
	if (formName) {
		$("#message_form_name").text(formName);
		$("#send_message").val(formValue);
	}
}

HOME_CHECK.sendPushMessage = function() {
	var messageSendType = $("#sender_group").hasClass("selected_send_type")? 0 : 1;
	
	var params = {
			sid : ClientData.userInfo_sid(),
			sendType : messageSendType,
			projectId : $("#selectedProjectIdForSendPushMessage").val(),
			message : $("#send_message").val()
	};
	
	HOME_CHECK.checkApi('sendPushMessage', params, 'POST', function(data) {
		HOME_CHECK.closeDialog();
		$('.notification-pushmessage').html("プッシュメッセージを送信しました。").slideDown();
		// auto off notification push message after timeWaitCloseNewInfoPushMessage
		setTimeout(function () {
			$('.notification-pushmessage').slideUp();
		}, 5000);
	}, function(xmlHttpRequest, txtStatus, errorThrown) {
		/* call custom error process */
		if(xmlHttpRequest.status == 400) {
			/* show messages */
			$().toastmessage({ position: 'middle-center' });
			$().toastmessage('showToast', {
				type: 'error',
				sticky: true,
				text: "プッシュメッセージの送信に失敗しました。"
			});
		} else {
			AVWEB.showSystemError();
		}
	});
}

//get message new
HOME_CHECK.getPushMessageNew = function()
{
	//ロック中かビューア画面ならチェックしない
	if ($("#viewer").length) {
		//表示状態か
		if( $('#viewer').is(':visible')){
			return;
		}
	}
	//$('.notification-pushmessage').hide();
	var params = {
			"sid": ClientData.userInfo_sid()
	};
	AVWEB.avwCmsApi(
			ClientData.userInfo_accountPath(),
			"webPushMessageNew",
			"post",
			params,
			HOME_CHECK.callbackGetPushMessageNewSuccess,
			function (xhr, b, c) { }
	);
};

//callback get number new message success
HOME_CHECK.callbackGetPushMessageNewSuccess = function(data) {
    if (data) {
        // show notification for new message
        if (data.count > 0) {
            $('.notification-pushmessage').html(I18N.i18nText("msgPushAlert")).slideDown();
            HOME_CHECK.changeImageForReceptPushMessage(1);
            HOME_CHECK.newMessageCnt += data.count;
            // auto off notification push message after timeWaitCloseNewInfoPushMessage
            setTimeout(function () {
                $('.notification-pushmessage').slideUp();
            }, 5000);
        }
    }

    // continue check new push message
    setTimeout(HOME_CHECK.getPushMessageNew, 10000);
};

//Hide the locking layout
HOME_CHECK.unlockLayout = function() {
    $('#avw-sys-modal').hide();
};

// Show the locking layout
HOME_CHECK.lockLayout = function() {
    if (document.getElementById('avw-sys-modal')) {
        $('#avw-sys-modal').show();
    } else {
        var tags = '<div id="avw-sys-modal"></div>';
        $('body').prepend(tags);
        $('#avw-sys-modal').css({
            'opacity' : 0.7,
            'position' : 'fixed',
            'top' : '0',
            'left' : '0',
            'width' : $(window).width(),
            'height' : $(window).height(),
            'background' : '#999',
            'z-index' : 10000
        });
        // resize error page
        $(window).resize(function() {
            $('#avw-sys-modal').css({
                'width' : $(window).width(),
                'height' : $(window).height()
            });
        });
    }
};
