
var Calendar = new Class({
	options: {
		duration: 300
	},
	initialize: function(container, options) {
		this.setOptions(options);
		this.ms = 24 * 60 * 60 * 1000;
		this.window = new Element('div', {'class': 'calendar'}).injectInside(container);
		
		var jsonReq = new Json.Remote("ajax/selectDate.php", {
			onComplete: (function(result){
				this.dateF = result;
				this.make();
			}).bind(this)
		}).send();
	},
	make: function() {
		var today = new Date(), y = today.getFullYear();
		this.today = today;
		this.date = {
			'year': y + 50,
			'month': today.getMonth() + 1,
			'day': 1
		};		
		this.year = new Scale(
			new Element('div', {
				'class': 'year'
			}).injectInside(this.window),
			{max: y + 5, min: y}
		);
		
		this.month = new Scale(
			new Element('div', {'class': 'month'}).injectInside(this.window), {
			setHTML: function(value) {				
				var month = [
					'Jan.', 	'Febr.', 	'March', 	'April',
					'May', 		'June',		'July', 	'Aug.',  
					'Sept.', 	'Oct.', 	'Nov.', 	'Dec.'
				];
				this.element.setHTML(month[this.options.value - 1]);
			},
			max: 12,
			min: 1
		});	

		['Mon', 'Tue', 'Wed.', 'Thu.', 'Fri', 'Sat', 'Sun'].each((function(title) {
			var span = new Element('span').setText(title);
			span.injectInside(this.window);
		}).bind(this));

		this.days = [];
		for (var i = 0; i < 42; i++) {
			this.days[i] = new Element('a', {
				href: 'javascript:void(0);'}
			).injectInside(this.window); 			
			
			// Add click on day event
			this.days[i].addEvent('click', this.select.bind(this));
		}

		this.year.addEvent('onComplete', this.change.bind(this));
		this.month.addEvent('onComplete', this.change.bind(this));
	},
	select: function(event) {
		event = new Event(event);
		
		var a = event.target;
		if (!a.hasClass('enabled'))
			return;
		
		this.fireEvent('click', a);
	},	
	setDate: function(date) {

		var date = date.split('/');
		if (date.length != 3)
			return;

		this.date = {
			'year': date[2],
			'month': date[1],
			'day': date[0]
		};
		
		this.year.setValue(this.date.year);
		this.month.setValue(this.date.month);
	},
	change: function() {
		var year = this.year.getValue(), month = this.month.getValue(), 
			cd = new Date(), nd = new Date(), days, d = 1;
		
		cd.setFullYear(year, month - 1, 0);
		nd.setFullYear(year, month, 0);

		days = ((nd - cd) / this.ms).round();
		this.days.each((function(a, index) {
			if (index >= cd.getDay() && index < days + cd.getDay()) {
				if( month < 10 ) mois = '0'+month;
				else mois = month;
				if( d < 10 ) jour = '0'+d;
				else jour = d;
				
				a.addClass('enabled');
				if( this.dateF.contains(year+'-'+mois+'-'+jour) ){
					a.setStyle('color', '#000');
				}else  a.setStyle('color', '#5880b4');		
					
				a.setText(d);
				d++;
				return;
			}
			
			a.set({'class': ''});
			a.setText('');
		}).bind(this));
	}
});

Calendar.implement(new Events, new Options);

