document.write("<div class='contentsWrapper' id='calendar'></div>");

mm = new RegExp("time=(.*)");
dateobj = new Date();
if (ret = document.URL.match(/time=([0-9]+)$/)) {
	if (ret[1]) dateobj = new Date(ret[1] * 1000);
}
drawCalendar(dateobj);

function drawCalendar(dateobj) {
	today = new Date();
	work  = new Date();

	if (dateobj.getMonth() > 7)
		prevtext = '<a href="#" onClick="prevMonth(' + dateobj.getTime() + ');">&lt;前月</a>';
	else
		prevtext = '';

	if (dateobj.getMonth() < 8)
		nexttext = '<a href="#" onClick="nextMonth(' + dateobj.getTime() + ');">翌月&gt;</a>';
	else
		nexttext = '';

	text = '<div class="contentsBox"><table summary="カレンダー"><caption>'
	     + prevtext
	     + '<span id="calendarTitle">' + (dateobj.getMonth() + 1) + '月の番組表</span>'
	     + nexttext + '</caption>';
	text += '<tr><th>日</th><th>月</th><th>火</th><th>水</th><th>木</th><th>金</th><th>土</th></tr>';

	work.setFullYear(dateobj.getFullYear());
	work.setDate(1);
	work.setMonth(dateobj.getMonth());
	nowMonth = dateobj.getMonth();
//	work.setHours(4);
//	work.setMinutes(0);
//	work.setSeconds(0);
//	work.setMilliseconds(0);
	text += '<tr>';
	for (i=0; i < work.getDay(); i++)
		text += '<td></td>';
	for (i=1; i<=32; i++) {
		work.setDate(i);
		if (work.getMonth() != nowMonth){
			if(work.getDay() % 7 == 0){
				break;
			}else{
				for (j=1; j<=7-work.getDay(); j++) {
					text += '<td></td>';
				}
				break;
			}
		}
		if (work.getDay() % 7 == 0)
			text += '<tr>';

		if (work.getDate()==today.getDate() && work.getMonth()==today.getMonth())
			text += '<td class="today"><a href="/timet/?time='+ Math.floor(work.getTime() / 1000) + '">'+i+'</a></td>';
		else
			text += '<td><a href="/timet/?time='+ Math.floor(work.getTime() / 1000) + '">'+i+'</a></td>';

		if (work.getDay() % 7 == 6)
			text += '</tr>';
	}
	text += '</tr></table><p style="margin-top:5px;font-size:85%;">視聴したい日付をクリック！</p></div>';
	calbase = document.getElementById('calendar');
	calbase.innerHTML=text;
}

function prevMonth(dateval) {
	dateobj = new Date(dateval);
	dateobj.setDate(1);
	dateobj.setMonth(dateobj.getMonth()-1);
	drawCalendar(dateobj);
}

function nextMonth(dateval) {
	dateobj = new Date(dateval);
	dateobj.setDate(1);
	dateobj.setMonth(dateobj.getMonth()+1);
	drawCalendar(dateobj);
}
