/*********************/
/* UTILITY FUNCTIONS */
/*********************/
// day of week of month's first day
function getFirstDay(theYear, theMonth){
	var firstDate = new Date(theYear,theMonth,1);
	return firstDate.getDay();
}

// number of days in the month
function getMonthLen(theYear, theMonth) {
	var nextMonth = new Date(theYear, theMonth + 1, 1);
	nextMonth.setHours(nextMonth.getHours() - 3);
	return nextMonth.getDate();
}

/****************************************************************************************/
/* DRAW CALENDAR CONTENTS																*/
/*  3.8.5.1 (2006/04/28) today parameter add											*/
/*  5.6.3.4 (2013/04/26) "/" 付の日付欄の場合の処理を追加								*/
/*  5.9.5.1 (2016/02/12) HTML5Modal対応													*/
/* 			2017/12/13 3ヵ月分の表示とレイアウト変更のためcarendar2.jsをコピーして変更	*/
/****************************************************************************************/
// clear and re-populate table based on form's selections
function populateTable(today,cntMonth,basic,isFmt) {
	var theMonth , theYear , ymd , firstDay , howMany , header , tmpMonth , dayCounter , tBody , newR , newC , done , i ;
	var howMany = new Array(cntMonth);
	var dayCounter = new Array(cntMonth);
	var firstDay = new Array(cntMonth);
	var listYear = new Array(cntMonth);
	var listMonth = new Array(cntMonth);
	var endCnt;

	theMonth = today.getMonth();
	theYear = today.getFullYear();

	// 今日
	var now = new Date();
	// ﾍｯﾀﾞｰ１段目の年月表示
	var tHeadMonth = document.getElementById("tableHaderMonth");
	tHeadMonth.innerHTML = theYear + " / " + ("0"+(theMonth+1)).slice(-2);
	// ﾍｯﾀﾞ-２段目の年月送りリンク表示
	var tHeadLink = document.getElementById("tableHeaderLink");
	// 今日
	var hLink = "<a href='#' class='movelink' onClick='changeMonth( " + theYear + "," + ( theMonth + 1 ) + "," + today.getDate() + ",-12," + cntMonth + "," + basic.getFullYear() + "," + basic.getMonth() + "," + basic.getDate() + ");return false;'>&lt;&lt;</a>";
	// 月戻り
	hLink += "<a href='#' class='movelink' onClick='changeMonth( " + theYear + "," + ( theMonth + 1 ) + "," + today.getDate() + ",-1," + cntMonth + "," + basic.getFullYear() + "," + basic.getMonth() + "," + basic.getDate() + ");return false;'>&lt;</a>";
	// 年戻り
	hLink += "<a href='#' class='movelink' onClick='changeToday(" + cntMonth + "," + basic.getFullYear() + "," + basic.getMonth() + "," + basic.getDate() + ");'>今日</a>"
	// 月送り
	hLink += "<a href='#' class='movelink' onClick='changeMonth( " + theYear + "," + ( theMonth + 1 ) + "," + today.getDate() + ",1," + cntMonth + "," + basic.getFullYear() + "," + basic.getMonth() + "," + basic.getDate() + ");return false;'>&gt;</a>";
	// 年送り
	hLink += "<a href='#' class='movelink' onClick='changeMonth( " + theYear + "," + ( theMonth + 1 ) + "," + today.getDate() + ",12," + cntMonth + "," + basic.getFullYear() + "," + basic.getMonth() + "," + basic.getDate() + ");return false;'>&gt;&gt;</a>";
	tHeadLink.innerHTML = hLink;

	// 指定分の年月を戻す
	var rivMonth = Math.floor(cntMonth / 2);
	theMonth -= rivMonth;
	if(theMonth < 0){
		// 前の年
		theMonth += 12;
		theYear -= 1;
	}

	//   3.8.5.1 (2006/04/28) today parameter get value
	if( today == null ) {
		if( typeof window.dialogArguments != "undefined" ){
			ymd = window.dialogArguments;
		}
		else{
			ymd = getPopArgs(); // 5.9.5.1
		}

		if( isFmt ) { ymd = ymd.replace(/\//g,''); }	// 5.6.3.4 (2013/04/26) "/" 付の日付欄の場合の処理を追加
		today = new Date( ymd.substring(0,4),ymd.substring(4,6)-1,ymd.substring(6,8));
	}

	for(i = 0; i < cntMonth; i++){
		// 年月の保存
		if(i == 0){
			listYear[i] = theYear;
			listMonth[i] = theMonth;
		}else{
			if(listMonth[i-1] < 11){
				listYear[i] = listYear[i-1];
				listMonth[i] = listMonth[i-1] + 1;
			}else{
				listYear[i] = listYear[i-1] + 1; // 次の年
				listMonth[i] = 0;
			}
		}

		// pick up date form choices
		// initialize date-dependent variables
		// 月曜開始対応HYBS_CAL_START_MON
	//	if( true ){ 5.6.9.1
		if(HYBS_CAL_START_MON){
			firstDay[i] = (getFirstDay(listYear[i], listMonth[i])+6)%7;
		}
		else{
			firstDay[i] = getFirstDay(listYear[i], listMonth[i]);
		}
		howMany[i]  = getMonthLen(listYear[i], listMonth[i]);

		header = "";
		tmpMonth = "0" + ( listMonth[i] + 1 );
		header = tmpMonth.slice( tmpMonth.length - 2 ) + "月";

		if(i == 0){
			document.getElementById("tableHeader").innerHTML =  header;
		}else{
			document.getElementById("tableHeader" + i).innerHTML =  header;
		}

		// initialize vars for table creation
		dayCounter[i] = 1;
	}

	tBody = document.getElementById("tableBody");
	// clear any existing rows
	while (tBody.rows.length > 0) {
		tBody.deleteRow(0);
	}
	done=false;
	endCnt = 0;
	while (!done) {
		// create new row at end
		newR = tBody.insertRow(tBody.rows.length);
		if (newR) {
			for ( k = 0; k < cntMonth ;k++) {
				for ( i = 0; i < 7; i++) {
					// create new cell at end of row
					newC = newR.insertCell(newR.cells.length);

					// セルのクラス設定
					newC.className += " cell";
					// 月別右端セルのクラス設定
					if(i == 6 && k != cntMonth - 1){
						newC.className += " cell-right";
					}

					if (tBody.rows.length == 1 && i < firstDay[k]) {
						// empty boxes before first day
						newC.innerHTML = "&nbsp;";
						continue;
					}
					if (dayCounter[k] == howMany[k]) {
						// no more rows after this one
						endCnt += 1;
						if(endCnt == cntMonth){
							done = true;
						}
					}
					// plug in link/date (or empty for boxes after last day)
					if (dayCounter[k] <= howMany[k]) {
						// 土日のクラス設定
						var tmpDay = new Date(listYear[k], listMonth[k], dayCounter[k]);
						if(tmpDay.getDay() == 0 || tmpDay.getDay() == 6){
							newC.className += " holiday";
						}
						// 今日のクラス設定
						if(now.getFullYear() == listYear[k] &&
								now.getMonth() == listMonth[k] &&
								now.getDate() == dayCounter[k]) {
							newC.className += " now";
						}
						// 基準日のid設定
						if (today != null && basic.getFullYear() == listYear[k] &&
							basic.getMonth() == listMonth[k] &&
							basic.getDate() == dayCounter[k]) {
							newC.id = "basic";
						}
						// 日付の設定
						newC.innerHTML = "<a href='#'onclick='chooseDate(" +
							dayCounter[k] + "," + listMonth[k] + "," + listYear[k] + "," + isFmt +		// 5.6.3.4 (2013/04/26) "/" 付の日付欄の場合の処理を追加
							"); return false;'>" + dayCounter[k] + "</a>";
						 dayCounter[k]++;
					} else {
						newC.innerHTML = "&nbsp;";
					}
				}
			}
		} else {
			done = true;
		}
	}
	//3.8.1.3 (2006/01/30) Set Window Size
	setWinSize();
}


/************************************************************/
/*   PROCESS CHOICE											*/
/*  5.6.3.4 (2013/04/26) "/" 付の日付欄の場合の処理を追加	*/
/*  5.9.5.1 (2016/02/12) html5対応
/************************************************************/
// function chooseDate(date, month, year) {
function chooseDate(date, month, year,isFmt ) {
	var sYear , sMonth , sDate ;

	sYear = year.toString();
	sMonth = (month>=9) ? (month + 1).toString() : "0" + (month + 1).toString() ;
	sDate =  (date>=10) ? date.toString() : "0" + date.toString();

//	window.opener.document.getElementById( window.name ).value = sYear + sMonth + sDate;

	// 5.6.3.4 (2013/04/26) "/" 付の日付欄の場合の処理を追加
//	window.returnValue = sYear + sMonth + sDate;
	if( isFmt ) {
//			window.returnValue = sYear + "/" + sMonth + "/" + sDate;
			rtnPopup( sYear + "/" + sMonth + "/" + sDate ); // 5.9.5.1
		}
	else        {
//			window.returnValue = sYear + sMonth + sDate;
			rtnPopup( sYear + sMonth + sDate ); // 5.9.5.1
	}
	if( typeof window.dialogArguments != "undefined" ){
		window.close();
	}
}

/************************************************************/
/*   initCalendar											*/
/*  5.9.5.1 (2016/02/12) html5対応							*/
/*  5.9.32.0 (2018/05/02) 日付(/を除いた状態)に文字が含まれる場合のフリーズ対応		*/
/************************************************************/
function initCalendar(cntMonth) {
	var ymd , today , calObj ;

	// デフォルト設定
	var cntMonth = typeof cntMonth != 'undefined' ? cntMonth : 1;

	//   3.8.5.1 (2006/04/28) today parameter get value
	ymd = getPopArgs(); // 5.9.5.1

	// 5.6.3.4 (2013/04/26) "/" 付の日付欄の場合の処理を追加
	var isFmt = (ymd.indexOf( "/" ) >= 0);

	if( isFmt ) { ymd = ymd.replace(/\//g,''); }

	//  5.9.32.0 (2018/05/02) ADD isNanの条件を追加
	if( ymd == null || ymd.length != 8 || isNaN(ymd)) {
//	if( ymd == null || ymd.length != 8 ) {
		today = new Date();
	}
	else {
		today = new Date( ymd.substring(0,4),ymd.substring(4,6)-1,ymd.substring(6,8));
	}

	window.returnValue = ymd;
	populateTable(today,cntMonth,today,isFmt);	// 5.6.3.4 (2013/04/26) "/" 付の日付欄の場合の処理を追加
	calObj = document.getElementById("calendar") ;
	calObj.style.visibility = "visible";

	window.focus();
}

function setWinSize() {
	var calObj , ver , adjusted_height , adjusted_width ;

	calObj = document.getElementById("calendarTable") ;

	if( calObj ) {
		// スクロールが表示される場合があるので、初期値を3としておく
		adjusted_height = 0;
		adjusted_width = 0;
		if(document.all) { // IE
			ver = getInternetExplorerVersion();
			if ( ver < 7.0 ) {
				adjusted_width = 6 ;
				adjusted_height = 52 ;
			}

		//if( document.readyState=="complete" ) {
			window.dialogWidth = calObj.offsetWidth + adjusted_width + "px";
			window.dialogHeight = calObj.offsetHeight + adjusted_height + "px";
		//}
		}
		else { // Firefox
			// html5ModalDialogの場合の幅調整
			var i = 10; // 5.9.10.3 (2016/07/8) 無限ループ抑制 回数で抑え込む
			do {
				adjusted_width  = calObj.offsetWidth - (document.documentElement["clientWidth" ] || document.body["clientWidth" ]);
				adjusted_height = calObj.offsetHeight - (document.documentElement["clientHeight"] || document.body["clientHeight"]);

				window.resizeBy(adjusted_width, adjusted_height);
				i--;
			}
			//while(adjusted_width > 0 || adjusted_width > 0);
			 while( (adjusted_width > 0 || adjusted_width > 0) && i > 0 );
		}
	}
}

/****************************************/
/* 今日の日付に移動させる				*/
/* cntMont : 出力月数					*/
/***************************************/
function changeToday(cntMonth,yearb,monthb,dayb){
	var today = new Date();
	var basic = new Date(yearb,monthb,dayb);
	populateTable(today,cntMonth,basic);
}

/****************************************/
/* diffに指定分の月数を移動させる		*/
/* year : 年							*/
/* month: 月							*/
/* day  : 日							*/
/* diff : 先月（-1）、来月（1）			*/
/* cntMonth : 出力月数					*/
/****************************************/
function changeMonth( year,month,day,diff,cntMonth,yearb,monthb,dayb ) {
	var newMonth , newYear , newDate ;

	newMonth = Number( month ) + diff;
	newYear = year;
	if ( newMonth <= 0 ) {
		newMonth = 12 + newMonth;
		newYear = Number( year ) - 1;
	}
	else if ( newMonth >= 13 ) {
		newMonth = newMonth - 12;
		newYear = Number( year ) + 1;
	}

	newDate = new Date( newYear,newMonth-1, day );

	var basic = new Date(yearb,monthb,dayb);

	populateTable(newDate,cntMonth,basic);
}
