/* 初回出発日 (2009-07-01) */
var firstDepartureDate = 20090701;
/* トップ検索、空席検索で出発日を制御するための最大表示日。ブランクの場合は6か月となります */
var hyojiLimitDate = "";

// 静的画面用データセット
function setSearchData(formName, dateElmName){
	// 年月のセット
	ymSet(document.forms[formName],dateElmName);

}
// 与えられた引数から日付を取得する。
function getDate(yyyymmdd) {
	try {
		var ymd = yyyymmdd.toString();
		var y = ymd.substr(0,4);
		var m = ymd.substr(4,2);
		var d = ymd.substr(6,2);

		// 月は-1する
		return new Date(y, m -1 , d);
	} catch (e) {
		// エラーの場合はシステム日付
		return new Date();
	}
}

/* 初回出発日 と現在日付を比較した結果を返す*/
function getDepartureDate() {
	var date = new Date();
	/* 初回出発日より前か？ */
	if (date.getTime() < getDate(firstDepartureDate).getTime()) {
		date = getDate(firstDepartureDate);
	}
	return date;
}

//年月のセット
function ymSet(form,dateElmName) {
	var cnt = 0;
	var obj = form.elements[dateElmName + "YM"].options;
	var date = new Date();

	// 比較する日付
	var compareDate = getDate(firstDepartureDate);
	/* 初回出発日より前か？ */
	var isBeforeFirstDepartureDate = false;
	if (date.getTime() < compareDate.getTime()) {
		date = compareDate;
		isBeforeFirstDepartureDate = true;
	}
	date.setDate(1);
	var monthCount = getMonthCount(date);
	while (cnt < monthCount) {
		y1 = date.getFullYear();
		m1 = date.getMonth() + 1;
		if (m1 < 10) {
			m1 = "0" + m1
		}
		obj[cnt] = new Option(y1 + "年" + m1 + "月", y1 + "" + m1);
		date.setMonth(date.getMonth() + 1);
		cnt++;
	}
	if (!isBeforeFirstDepartureDate) {
		if (!useJquery) {
			form.checkinD.selectedIndex = new Date().getDate() - 1;
		} else {
			form.checkinD.selectedIndex = 0;
		}
	}
//	form[dateElmName+"D"].selectedIndex = date.getDate();
}

function leftPad(str, delim , range) {

	str = str + "";
	if (str == undefined || str == null || str == "") {
		return "";
	}

	if (str.length < range) {
		var count = range - str.length;
		for (i = 0; i < count; i++) {
			str = delim + str;
		}
	}

	return str;
}



// **************************** 追加分 *******************************************
// 月数を計算する
function getMonthCount(date){

	var now = date;
	// 最大表示日
	var strLimit = getLimitDate();
	if (strLimit == "") {
		// 数値でない場合は6か月。 ""(ブランク)含む
		return 6;
	}

	// 文字列にして足し算する
	var strNowYmd = now.getFullYear() + leftPad(now.getMonth() + 1, 0 ,2) +  leftPad(now.getDate(), 0 ,2);

	if (strNowYmd > strLimit) {
		// 現在日付が最大表示日を上回ってしまった場合
		return 6;
	}
	// 日付に変換する
	limit = getDate(strLimit);

	// 閏年用の対策
	calcDate = new Date( 1970, 0, 1 );
	calcDate.setTime(limit.getTime()-calcDate.getTime());

	//求めた年月日から基準日を引く
	calcYear  = calcDate.getUTCFullYear() - now.getFullYear();
	calcMonth = calcDate.getUTCMonth() - now.getMonth() + 1;

	// 月がマイナスなので年から繰り下げ
	if(calcMonth < 0) {
		calcYear --;
		calcMonth += 12;
	}

	// 差分の月数 + 12 * 年数
	return calcMonth + (12 * calcYear);
}

/* セレクトボックスで表示する出発日の最大値を設定します。yyyymmddの文字列で指定します。 */
function getLimitDate() {

	return String(hyojiLimitDate);
}

// 日セレクトボックスの再生成を行う
function reCreateDateOption(dateElmName) {

	// 最大表示日
	var limitDate = getLimitDate();

	y0 = limitDate.substr(0,4);
	m0 = limitDate.substr(4,2);
	d0 = limitDate.substr(6,2);
	var strLimitYm = y0 + m0;

	// 今
	var now = new Date();
	// 比較する日付
	var compareDate = getDate(firstDepartureDate);
	if (now.getTime() < compareDate.getTime()) {
		now = compareDate;
	}

	y1 = now.getFullYear();
	m1 = now.getMonth() + 1;
	d1 = now.getDate();
	// 文字列の足し算をするために文字列にする
	strY1 = "" + y1;
	strM1 = leftPad(m1, "0", 2);
	var strNowYm = strY1 + strM1;

	// 選択した年月
	var targetYm = $('select[name="' + dateElmName +  'YM"]').val();
	// 選択した日
	var targetD = $('select[name="' + dateElmName +  'D"]').val();

	// checkinYMの値が存在しない場合（画面起動ready時にも呼ばれるのでcheckinYMの値が存在しないこともある）
	if (targetYm == null || targetYm == '') {
		// 「今」を設定する
		targetYm = strNowYm;
	}

	// 選んだ月の最終日を取得
	var lastTargetDateOfMonth = getLastDayOfMonth(targetYm);

	// 選択した年月によって日付のオプションを作りかえる
	var option = '';

	// 選択した年月と現在年月が同じ場合
	if (strNowYm == targetYm) {

		option = reCreateOption(d1, lastTargetDateOfMonth);

	// 選択した年月と設定されている最大表示日が同じ場合
	} else if (strLimitYm == targetYm) {

		option = reCreateOption(1, d0);

	} else {

		option = reCreateOption(1, lastTargetDateOfMonth);
	}

	// 出発日（日）のオブジェクト
	var objcheckinD = $('select[name="' + dateElmName +  'D"]');
	// 日のセレクトオプションを設定する
	objcheckinD.html(option);
	if ( jQuery.browser.msie ) {
		// IEは入れないとエラーが起きる
		objcheckinD.width();	//for IE
	}
	// 選択した日付を設定しなおす。
	objcheckinD.val(targetD);
}

// 日のオプションを作りなおす
function reCreateOption(begin, end) {

	// 選択した年月によって日付のオプションを作りかえる
	var option = '';
	for (date = begin; date <= end; date++) {
		var strDate = leftPad(date, "0", 2);
		option = option + '<option value="' + strDate + '">' + date + '日</option>';
	}

	return option;
}
// 引数の月の最終日を取得する
function getLastDayOfMonth(ym) {

	strY = ym.substr(0,4);
	strM = ym.substr(4,2);

	var date = new Date(strY, strM, 00);

	iLastDayOfMonth = date.getDate();

	return iLastDayOfMonth;
}

// JQuery使用できる場合はtrue
var useJquery = false;

try {
	// js起動時に実行して落ちるかどうかでJqueryが使用できるか判定。
	$('select[name="checkinYM"]').val();
	useJquery = true;
} catch(e) {}

try {
	$(function() {
		$('select[name="checkinYM"]').ready(function () {reCreateDateOption("checkin")});
		$('select[name="checkinYM"]').change(function () {reCreateDateOption("checkin")});
		$('select[name="shupatuYM"]').ready(function () {reCreateDateOption("shupatu")});
		$('select[name="shupatuYM"]').change(function () {reCreateDateOption("shupatu")});
		$('select[name="tochakuYM"]').ready(function () {reCreateDateOption("tochaku")});
		$('select[name="tochakuYM"]').change(function () {reCreateDateOption("tochaku")});
	});
} catch(e) {
	// Jqueryがなくても動くように例外は握りつぶす。
	// JQueryがない場合エラーとなるがここでcatchして何もなかったことにする。
	// reCreateDateOptionで記述されている内容は、selectのonchangeイベントが拾えなくなるので使われなくなり問題ない。
	// <select onchange="reCreateDateOption()">とされるとアウトなのでこれはしないようにしてもらう。
}
