めも帖

「めも帖」代わりにダラダラと書いていったり、めもしたりしているだけです。

JavaScriptのカレンダー(2)

prototype.jsを使ってclass化を始めました。気づいたのだけれど、1月の最終日の取得がおかしい気がする。調べてみようと思います。
あとは、カレンダーを管理するクラスと、日付をクリックされたときのイベントについてどうするか?(カレンダーだけじゃないのです)期間指定について、何かを渡すと、一気に期間として指定できるのが欲しいところ。

//
Date.prototype.last_day_of_month = function() {
	var d = new Date( this.getYear(), this.getMonth(), this.getDate());
	d.setMonth(d.getMonth() + 1);
	d.setDate(1);
	d.setTime(d.getTime() - 1);
	return d.getDate();
};

// 
var Calendar = Class.create();
var Day      = Class.create();

Day.prototype = {
	initialize:function(){
	}
}

Calendar.prototype = {
	today        : new Date(),
	date         : new Date(),
	year         : '',
	month        : '',
	weekDay      : new Array('日','月','火','水','木','金','土'),
	wDay         : '',
	firstWeekDay : '',
	line         : '',
	calArray     : new Array(),
	calHTML      : '',

	initialize:function(year,month){
		if(year){
			this.year = year;
		}else{
			this.year = this.date.getYear() + 1900;
		}

		if(month){
			this.month = month;
		}else{
			this.month = this.date.getMonth() + 1;
		}

		this.date.setYear(this.year);
		this.date.setMonth(this.month-1);
		this.date.setDate(1);

		this.firstWeekDay = this.date.getDay();
		this.line         = Math.ceil((this.firstWeekDay + this.date.last_day_of_month())/7);

		this._setUpArray();
	},

	_setUpArray:function(){
		for( var i=0; i<this.line*7; i++ ){
			var day = new Day();
			if(i>=this.firstWeekDay && (i-this.firstWeekDay) < this.date.last_day_of_month()){
				day['year']  = this.year;
				day['month'] = this.month;
				day['day']  = (i+1) - this.firstWeekDay;    // 日付
				this.date.setDate(day['day']);
				day['week'] = Math.floor(i/7);    // 第何週
				day['wDay'] = this.weekDay[this.date.getDay()];    // 曜日
				if(this.date.getTime() == this.today.getTime()){
					day['isToday'] = true;
				}
				if(this.date.getTime() > this.today.getTime()){
					day['isWill'] = true;
				}
				this.calArray[i] = day;
			}else{
				this.calArray[i] = day;
			}
		}
	},

	display:function(){
		this.calHTML += '<table border="1">';
		this.calHTML += '<tr><td colspan="7">';
		this.calHTML += this.year + '/' + this.month;
		this.calHTML += '</td></tr>';
		for(var i=0; i<this.line; i++){
			this.calHTML += '<tr>';
			for(var j=0; j<7; j++){
				this.calHTML += '<td>';
				if(this.calArray[j+(i*7)]['isWill']){
					this.calHTML += '<span style="color:#cccccc;">';
				}
				if(this.calArray[j+(i*7)]['isToday']){
					this.calHTML += '<strong>';
				}
				if(this.calArray[j+(i*7)]['day']){
					this.calHTML += this.calArray[j+(i*7)]['day'];
				}
				if(this.calArray[j+(i*7)]['isToday']){
					this.calHTML += '</strong>';
				}
				if(this.calArray[j+(i*7)]['isWill']){
					this.calHTML += '</span>';
				}
				this.calHTML += '</td>';
			}
			this.calHTML += '</tr>';
		}
		this.calHTML += '</table>';
		return this.calHTML;
	}
}