/**
 * Inlementation for he calendar object
 */

Calendar = {
	date : null, 

	MONTHES : new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"), 

   //elem : null,
	// setups calendar
	setup : function(year, month, day){
		this.date = new Date(year, month, day);

		this.refresh();
	},

	// returns offset of the first day
	getOffset : function(date){
		var _date = new Date(date);
		_date.setDate(1);

		return _date.getDay();
	},

	// Returns month days filled with events
	// refreshes calendar view
	refresh : function(){
		// Retrieve days filled with event
		var params = 'month=' + (this.date.getMonth() + 1) + '&year=' + this.date.getFullYear();

		var fDays = null;
		new Ajax.Request('./event_cal.php', {
			method: 'POST', 
			asynchronous: false, 
			parameters : params,
			onSuccess : function(res){
				eval('fDays = ' + res.responseText + ';');
			}
		});

		var offset = this.getOffset(this.date);
		var _date = new Date(this.date.getFullYear(), this.date.getMonth(), 1);
		_date.setDate(_date.getDate() - offset);
				
		// setup header
		document.getElementById('cal_monthyear').innerHTML = this.MONTHES[this.date.getMonth()] + ',' + this.date.getFullYear();

		for(var i = 0; i < 6; i++){
			for(var k = 0; k < 7; k++) {
				var idx = i * 7 + k;
				var elem = document.getElementById('cal_d_' + idx);
				elem.innerHTML = _date.getDate();
	
				var css = null;
				if(_date.getMonth() != this.date.getMonth()){
					css = 'cal-passive';
				}else if(_date.valueOf() == this.date.valueOf()){
					css = 'cal-selected';
				}else if(fDays && fDays.indexOf(_date.getDate()) != -1){
					css = 'calhaveevents';
				}else{
					css = 'cal-normal';
				}

				elem.className = css;
				elem.setAttribute('cal_y', _date.getFullYear());
				elem.setAttribute('cal_m', _date.getMonth() + 1);
				elem.setAttribute('cal_d', _date.getDate());
				
				_date.setDate(_date.getDate() + 1);
			}			
		}
	},

	// returns events for specified date
	getForDate : function(elem){
		document.getElementById('cal_y').value = elem.getAttribute('cal_y');
		document.getElementById('cal_m').value = elem.getAttribute('cal_m');
		document.getElementById('cal_d').value = elem.getAttribute('cal_d');

		document.getElementById('cal_form').submit();
	},

	// Go to the previous month
	prevMonth : function(){
		this.date.setMonth(this.date.getMonth() - 1);
		this.refresh();
	},

	// Go to the next month
	nextMonth : function(){
		this.date.setMonth(this.date.getMonth() + 1);
		this.refresh();
	}
}


/**
 * Returns only date value from the date objects
 * Sets time to 00:00:00 
 * @param	date
 */
Date.prototype.toDate = function(){
	var _date = new Date(this.getFullYear(), this.getMonth(), this.getDate());
	return _date;
}

