//	Mootools Events Calendar v0.2.1 (2009-02-09) - http://dansnetwork.com/mootools/events-calendar

/*

	License:
		MIT-style license.


//	Modified For ROCKWOOL By Brocelia.
*/

var Calendar = new Class({

	Implements: [Options, Events],
	options: {
		calContainer: 'calendrier', // id of the element that the calendar will be "injected" into
		newDate: 0, // used to set the initial selected date to one other than the current day
		view: 'month', // options are: month, week, day - sets the default view
		feedPlugin: '', // default (empty string) uses cEvents[] for manual event entry
		feedSpan: 3, // This is the number of months (past and future) of events to retrieve. Not needed for manual event entry using cEvents.
		scroller: true,
		cEvents: [] //event container
	},
	initialize: function(options){
		this.setOptions(options);
		this.months = ['JANVIER', 'FEVRIER', 'MARS', 'AVRIL', 'MAI', 'JUIN', 'JUILLET', 'AOUT', 'SEPTEMBRE', 'OCTOBRE', 'NOVEMBRE', 'DECEMBRE'];
		this.daysInMonth = 30; // can be set with setDaysInMonth(month,year)
		this.options.newDate != 0 ? this.calDate = new Date(this.options.newDate) : this.calDate = new Date();
		this.startingOffset = 0; // determine the offset of the first of the month and Sunday - used for the "month" view
		this.viewStartDate = new Date(); // starting date for current view
		this.viewEndDate = new Date(); // ending date for current view
		this.gotEvents = false; // initial request for the events feed
		this.eventRangeStart = new Date(); //current range of events that have been fetched
		this.eventRangeEnd = new Date();
		this.setCalParams();
		this.extendDate();
		switch(this.options.view){
			case 'month':
				this.showMonth();
				break;
			default:
				this.showMonth;
		}
	},
	setDaysInMonth: function(month, year){ // month: must be an integer (0 - 11) year: used to dertermine if leap year exists
		var daysInMonths = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		if(new Date(year,1,29).getDate() == 29) // determine if leap year
			daysInMonths[1] = 29;
		this.daysInMonth = daysInMonths[month];
	},
	setStartingOffset: function(month,year){ // month: must be an integer (0 - 11)
		this.startingOffset = new Date(year,month,0).getDay();
	},
	setDate: function(day){
		this.calDate.setDate(day);
	},
	setCalParams: function(){
		this.setDaysInMonth(this.calDate.getMonth(), this.calDate.getFullYear());
		this.setStartingOffset(this.calDate.getMonth(), this.calDate.getFullYear());
	},
	showNextMonth: function(){
		this.calDate.nextMonth();
		this.setCalParams();
		this.showMonth();
	},
	showPrevMonth: function(){
		this.calDate.prevMonth();
		this.setCalParams();
		this.showMonth();
	},
	showControlsRow: function(calM, calY){

		var cal = $('contenu');
		var calBoite = $('calendrier');

			var liHeaderCal = new Element('p', {
				'class':'mois',
				'html':calM
			}).inject(cal, 'before');

			var liHeaderCal = new Element('p', {
				'class':'jour',
				'html':calY
			}).inject(cal, 'before');

			var aPrevCal = new Element('a',{
				'href':'javascript:void(0)',
				'class':'aPrevCal precedent',
				'html':'<img src="/Files/Maison-respekt/images/calendrier/precedent.gif" alt="&lt;" />'
			}).inject(cal, 'after');

			var aNextCal = new Element('a',{
				'href':'javascript:void(0)',
				'class':'aNextCal suivant',
				'html':'<img src="/Files/Maison-respekt/images/calendrier/suivant.gif" alt="&gt;" />'
			}).inject(cal, 'after');


			aPrevCal.addEvent('click',function(){
				this.showPrevMonth()
			}.bind(this));
			aNextCal.addEvent('click',function(){
				this.showNextMonth()
			}.bind(this));


	},
	showMonth: function(){

		$(this.options.calContainer).set('html','');
		this.options.view = 'month';
		var table = new Element('div',{
			'class':'mooECal',
			'id':'monthCal'
		});


		var calDone = false;
		var datejour = new Date().getMonth();
		var datecal  = this.calDate.getMonth();
		var yearcal  = new String(this.calDate.getFullYear());
		var year 	 = new Date().getFullYear();

		var tr = new Element('div',{'class':'monthWeek contenu', 'id':'contenu'}).inject(table); // create weeks

		for (var i = 0; i < 6; i++){
			if(calDone){
				break;
			}

			for (var j = 0; j < 7; j++) {
				var day = ((j+1) + (i*7)) - this.startingOffset;

				var td = new Element('div',{'class':'monthDay jour0','id':'day'+day}).inject(tr); // create days
				if (day > 0 && day <= this.daysInMonth){
					/*td.set({
						events: {
							'mouseover': function(){this.addClass('hover')},
							'mouseout': function(){this.removeClass('hover')},
						}
					});*/
					new Element('span',{'text':day}).store('date',day).inject(td);
					td.store('date',day);
					/*td.addEvent('click', function(){
						$$('div.monthDay').each(function(td){td.removeClass('jour2')});
						this.addClass('jour2');
					});*/
					td.addEvent('click',function(e){
						this.setDate(e.target.retrieve('date'))
					}.bind(this));
					if(day == this.calDate.getDate() && datejour == datecal && yearcal == year) //set background color for current day
						td.addClass('jour2');

					if(((day > this.calDate.getDate() && datecal == datejour) || datecal > datejour) && yearcal == year ) //set background color for days after current day
						td.addClass('jour3');

					if(day == this.daysInMonth)
						calDone = true;
				}
			}
		}

		this.viewStartDate.setTime(this.calDate.valueOf());
		this.viewStartDate.setDate(1);
		this.viewEndDate.setTime(this.calDate.valueOf());
		this.viewEndDate.setDate(this.daysInMonth);
		this.viewStartDate.startOfDay();
		this.viewEndDate.endOfDay();

		table.inject($(this.options.calContainer));
		this.showControlsRow(this.months[this.calDate.getMonth()], yearcal.substr(2, 2));
		this.getCalEvents();

	}, // end of showMonth

	getCalEvents: function(){
		if ((!this.gotEvents || this.viewStartDate < this.eventRangeStart || this.viewEndDate > this.eventRangeEnd) && this.options.feedPlugin != '') {
			this.eventRangeStart.setTime(this.viewStartDate.getTime());
			this.eventRangeEnd.setTime(this.viewEndDate.getTime());
			this.eventRangeStart.setMonth(this.eventRangeStart.getMonth()-this.options.feedSpan);
			this.eventRangeEnd.setMonth(this.eventRangeEnd.getMonth()+this.options.feedSpan);
			$('loading').fade('in');
			this.options.feedPlugin.getEvents(this,this.eventRangeStart,this.eventRangeEnd)
		}
		else
			this.loadCalEvents();
	},
	loadCalEvents: function(){
		var time = '';
		$$('div.tip').each(function(divs){divs.getParent().destroy();}); // Tips cleanup - tip divs kept building up after switching calendar views

		var div = new Array();

		if(this.options.cEvents.length > 0)
		for(var i = 0; i < this.options.cEvents.length; i++){
			var eStart = new Date();

			eStart.setISO8601(this.options.cEvents[i].start);
			time = (this.options.cEvents[i].start.toString().match(new RegExp(/(\d\d\d\d-\d\d-\d\dT)/))) ? eStart.thTime() : '';
			if(eStart >= this.viewStartDate && eStart <= this.viewEndDate){

				var j = 'day'+eStart.getDate();
				var k = 'box'+eStart.getDate();
				eventDiv = $(j);
				eventDiv.addClass('jour1');

				var contenu = $('day'+eStart.getDate()).getChildren('span')[0];
				var txt = contenu.get('text');
				contenu.empty();

				var link = new Element('a',{
                     'href':'#',
                     'html':txt
                }).inject($('day'+eStart.getDate()).getChildren('span')[0], 'inside');

				if($(k)){

				}else{

					div[k] = new Element('div',{
						'id' : k,
						'class': 'events'
					}).inject($('pageactualites'), 'inside');
					div[k].setStyle('display', 'none');

					var ul = new Element('ul').inject(div[k] , 'inside');

					var close = new Element('a', {
						'html':'Fermer',
						'href':'#',
						'class':'close'
					}).inject(ul, 'before');

					close.addEvent('click', function(event){
				    	event.preventDefault();
					});

					(function(){
					var z = k;
						eventDiv.addEvents({
							'mouseover': function(e){
								Reinit();
								div[z].setStyle('left', e.page.x);
								div[z].setStyle('top', e.page.y);
						        div[z].setStyle('display', 'block').morph({opacity: 1});
						    }
						});
						close.addEvent('click', function(){
						    div[z].morph({opacity: 0});
						})
					})();
				}

				if($(k)){
					var li = new Element('li').inject(ul , 'inside');
				}else{
					var li = new Element('li').inject($(k).getElement('ul'), 'inside');
				}

				var link2 = new Element('a',{
                     'href':time+' '+this.options.cEvents[i].location,
                     'html':this.options.cEvents[i].title
                }).inject(li , 'inside');
			}
		}

	},
	extendDate: function(){ // this section could also be implemented with MooTools::Implement (no pun intended)
		function prevMonth(){
			Reinit();
			Remove();
			var thisMonth = this.getMonth();
			this.setMonth(thisMonth-1);
			if(this.getMonth() != thisMonth-1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1))){
				this.setDate(0);
			}
		};
		function nextMonth(){
			Reinit();
			Remove();
			var thisMonth = this.getMonth();
			this.setMonth(thisMonth+1);
			if(this.getMonth() != thisMonth+1 && this.getMonth() != 0)
				this.setDate(0);
		};
		function startOfDay(){
			this.setHours(0);
			this.setMinutes(0);
			this.setSeconds(0);
			this.setMilliseconds(0);
		};
		function endOfDay(){
			this.setHours(23);
			this.setMinutes(59);
			this.setSeconds(59);
			this.setMilliseconds(999);
		};
		function ymd(){
			var ymdString = this.getFullYear()+'-'+(parseInt(this.getMonth())+1).toString()+'-'+this.getDate();
			return ymdString;
		}
		function thTime(){ // twelve hour time
			var timestring;
			var minutes = this.getMinutes()<10 ? '0'+this.getMinutes().toString() : this.getMinutes().toString();
			timestring = this.getHours()>12 ?  (this.getHours()-12).toString()+':'+minutes+'pm' : this.getHours().toString()+':'+minutes+'am';
			return timestring;
		}
		function setISO8601(dString){
			var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
			var ymd = /(\d\d\d\d)-(\d\d)-(\d\d)/;
			if (dString.toString().match(new RegExp(regexp))) {
				var d = dString.match(new RegExp(regexp));
				var offset = 0;

				this.setUTCDate(1);

				this.setUTCFullYear(parseInt(d[1],10));
				this.setUTCMonth(parseInt(d[3],10) - 1);
				this.setUTCDate(parseInt(d[5],10));
				this.setUTCHours(parseInt(d[7],10));
				this.setUTCMinutes(parseInt(d[9],10));
				this.setUTCSeconds(parseInt(d[11],10));
				if (d[12])
					this.setUTCMilliseconds(parseFloat(d[12],10) * 1000);
				else
				this.setUTCMilliseconds(0);
				if (d[13] != 'Z') {
					offset = (d[15] * 60) + parseInt(d[17],10);
					offset *= ((d[14] == '-') ? -1 : 1);
					this.setTime(this.getTime() - offset * 60 * 1000);
				}
			}
			else if(dString.toString().match(new RegExp(ymd))){
				var d = dString.toString().match(new RegExp(ymd));
				{
					this.setDate(parseInt(1));
					this.setFullYear(parseInt(d[1],10));
					this.setMonth(parseInt(d[2],10)-1);
					this.setDate(parseInt(d[3],10));
				}
			}
			else{
				this.setTime(Date.parse(dString));
			}
			return this;
		};

		Date.prototype.nextMonth = nextMonth;
		Date.prototype.prevMonth = prevMonth;
		Date.prototype.startOfDay = startOfDay;
		Date.prototype.endOfDay = endOfDay;
		Date.prototype.ymd = ymd;
		Date.prototype.thTime = thTime;
		Date.prototype.setISO8601 = setISO8601;
	}

});

function Reinit(){
	/*REINITIALISATION*/
	$$('.events').each(function(e){
		e.morph({opacity: 0});
	})
}

function Remove(){
	/*REINITIALISATION*/
	$$('.events').each(function(e){
		e.destroy();
	})
}