/* softrCalendar 1.11 -------------------------------------|
	Fecha de creación: 20 de Abril de 2007
	Autor: Daniel Niquet
	Web: http://softr.net
	email: danielniquet@softr.net
	Última fecha de modificación: 10 de Julio de 2007
	Función del archivo: Crea un control calendario. Funciona con Mootools V1.11
	Inspirado en http://www.schizofreend.nl/test/
*/
var softrCalendar = new Class({
	initialize: function(targetInput, options, event){
		this.targetInput = targetInput;
		this.targetElement = $(targetInput);
		this.event=event;
		var isCal=false;
		$extend(this.options, options);
		if($('cal'+targetInput)) 
			if($('cal'+targetInput).getStyle('display')=='block') $('cal'+targetInput).setStyle('display','none'); else isCal=true;
		if(isCal || !$('cal'+targetInput)){			
			this.calendar = false; this.render(this.targetElement.value); $('cal'+targetInput).setStyle('display','block');
		}
	},
	options:{
		Months : ["Janvier ", "Fevrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Decembre"],
		WeekDays : ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"], 
		StartDay : 1, 
		WeekEnd : [0,6],
		/*DateRegexp : /^(\d{4})-(\d{1,2})-(\d{1,2})$/ */
		DateRegexp : /^(\d{1,2})-(\d{1,2})-(\d{4})$/
	},
	setDate: function(targetValue){
		this.targetElement.value = targetValue;	
		this.calendar.setStyle('display', "none");
	},
	render: function(startDate){
		var currentDate = (!startDate || !$chk(startDate)) ?  new Date() : (!isNaN(startDate))? new Date(startDate) : this.stringToDate(startDate);
		currentDate.setDate(this.stringToDate(this.targetElement.value).getDate());
		this.today=new Date();
		this.currentDate=currentDate;
		this.lastMonth = new Date(currentDate).setMonth(currentDate.getMonth()-1);
		this.nextMonth = new Date(currentDate).setMonth(currentDate.getMonth()+1);
		this.lastYear = new Date(currentDate).setFullYear(currentDate.getFullYear()-1);
		this.nextYear = new Date(currentDate).setFullYear(currentDate.getFullYear()+1);
		var cThis=this, firstDay = new Date(currentDate), d=new Date(currentDate.getFullYear()+'/'+(currentDate.getMonth()+1)+'/01'), lastDay = new Date(this.nextMonth).setDate(0);
		firstDay.setDate(1-(7+d.getDay()-this.options.StartDay)%7);

		this.table = new Element('table',{'class':'calendarTable'});
		this.tbody = new Element('tbody').injectInside(this.table);

		thMove=new Element('TH',{'class':'calMove'});
		this.tbody.adopt(
			new Element('TR').adopt(thMove).adopt(
				new Element('TD',{'class':'currentMonth','colSpan':5,'nowrap':'nowrap'}).adopt(
					new Element('SPAN').appendText(this.options.Months[currentDate.getMonth()]+" ")
				).adopt(
					new Element('SPAN',{'class':'changeYear','events':{'click':function(){cThis.changeYear(this);}}}).appendText(currentDate.getFullYear()))
				).adopt(
					new Element('TH',{'class':'calClose','events':{'click':function(){new softrCalendar(this.targetInput,this.event);}.bind(this)}}).appendText('X')
			)
		).adopt(
			new Element('TR').adopt(
				new Element('TD',{'class':'yearSwitch','events':{'click':function(){this.render(this.lastYear);}.bind(this)}}).setHTML('&laquo;')
			).adopt(
				new Element('TD',{'class':'monthSwitch','events':{'click':function(){this.render(this.lastMonth);}.bind(this)}}).setHTML('&lsaquo;')
			).adopt(
				new Element('TD',{'class':'currentDay','colSpan':3,'nowrap':'nowrap','events':{'click':function(){this.render(this.currentDate); this.setDate(this.dateToString(this.today))}.bind(this)}}).appendText('Aujourd\'hui')
			).adopt(
				new Element('TD',{'class':'monthSwitch','align':'right','events':{'click': function() { this.render(this.nextMonth); }.bind(this)}}).setHTML('&rsaquo;')
			).adopt(
				new Element('TD',{'class':'yearSwitch','align':'right','events':{'click':function() { this.render(this.nextYear); }.bind(this)}}).setHTML('&raquo;')
			)
		);

		//this.table.makeDraggable({handle: thMove});
		var currentDay = new Date(firstDay);
		Row = new Element('TR').injectInside(this.tbody);		
		(7).times(function(i){new Element('TH').appendText(this.options.WeekDays[(this.options.StartDay+i)%7]).injectInside(Row);}.bind(this));
		while (currentDay.getMonth() == currentDate.getMonth() || currentDay.getMonth() == firstDay.getMonth()) {
			var Row = new Element('TR').injectInside(this.tbody);
			(7).times(function(j)
			{
				var colorAnt="none", dis=this, dayEl = new Element('TD',{'lang' : currentDay,'styles':{'cursor':'pointer'},'events':{'click':function(el){dis.setDate(dis.dateToString(this.getProperty('lang')));}}}).appendText(currentDay.getDate()).injectInside(Row);
				/*I hate IE... so much*/
				if(window.ie){
					dayEl.addEvent('mouseout',function(){
						this.getParent().getChildren().each(function(el){
							if(el.hasClass('weekend')) el.setStyle('background-color','#DFDFFF'); 
							else if(el.hasClass('currentdate')) el.setStyle('background-color','#FFF'); 
							else el.setStyle('background-color','#EEF')
						});
						this.setStyle('background',colorAnt); 
					}).addEvent('mouseover',function(){
							this.getParent().getChildren().setStyle('background-color','#CFCDFF');
							if(this.hasClass('weekend')){ colorAnt="#DFDFFF";}
							else if(this.hasClass('currentdate')){ colorAnt="#FFF";} 
							else colorAnt="none"; 
							this.setStyle('background','#aaf'); 
					});
				}
				
				var a=(this.options.StartDay+j)%7;
				if(currentDay.getDate()+'-'+currentDay.getMonth()+'-'+currentDay.getFullYear()==this.today.getDate()+'-'+this.today.getMonth()+'-'+this.today.getFullYear()){dayEl.addClass('today');}
				if (currentDay.getDate() == currentDate.getDate() && currentDay.getMonth() == currentDate.getMonth()) {	dayEl.addClass('currentdate');	}else if (a == this.options.WeekEnd[0] || a == this.options.WeekEnd[1])	{ dayEl.addClass('weekend'); } else { dayEl.addClass('workday'); }
				if (currentDay.getMonth() != currentDate.getMonth()) dayEl.addClass('othermonth');
				currentDay.setDate(currentDay.getDate()+1);
			}.bind(this));
		}
		if (!this.calendar){
			
			this.calendar = new Element('DIV').setProperty('id','cal'+this.targetElement.id).setStyles({'position': 'absolute',top:"5px",left:"5px"}).injectAfter(this.targetElement);

		}
		this.calendar.empty();	
		this.table.injectInside(this.calendar);
		this.calendar.makeDraggable({handle: thMove});
		
		document.addEvent("keydown",(function(ev){if(ev.key=='esc') new softrCalendar(this.targetInput,ev);}.bind(this)).bindWithEvent(document));

		if(window.ie){/*$%&$%&$%&#~€¬ Internet explorer*/
			new Element('iframe',{'src':'javascript:false;','frameborder':0,'styles':{'position':'absolute',top:'0',left:'5px',width:this.calendar.getStyle('width').toInt()-10,height:this.calendar.getStyle('height').toInt()-10,zIndex:this.calendar.getStyle('z-index')-1, padding:'0px',border:'none'}}).injectBefore(this.table);
		}
	},
	changeYear:function(obj){
		var txt=obj.innerHTML.toInt()+3, dis=this;
		obj.addClass('changeYearOpen').removeEvents().empty();
		if(window.ie) obj.setStyle('margin-top','0');
		for(i=txt; i>(txt-7);i--) obj.adopt(new Element('a',{'events':{'click':function(){ dis.render(dis.currentDate.setYear(this.innerHTML))}}}).appendText(i));
	},
	stringToDate: function(inputString){
		if (!this.options.DateRegexp.exec(inputString)) alert("Date non valide: "+ inputString);
		return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1 ));
	},
	dateToString: function(currentDate){
		currentDate = new Date(currentDate);
		return (new String ((currentDate.getDate().toString().length==1?'0'+currentDate.getDate():currentDate.getDate())+"-"+((currentDate.getMonth()+1).toString().length==1?'0'+(currentDate.getMonth()+1):(currentDate.getMonth()+1))+"-"+currentDate.getFullYear())); 
	}
});
