var DatePicker = Class.create();

DatePicker.prototype  = {

initialize : function (elt,elt2,value) {
		
		this.target = $(elt);
		if (!this.target) {
			return;
		}

		this.htarget = $(elt2);


		this.dayduration = 24 * 60 * 60 * 1000,
  		this.holidays =  {},
  	
  		/*
		this.monthsList = [ 'January' ,'February' , 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
		this.daysList = [ 'Monday' ,'Tuesday' , 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ],
		*/
		/*
		this.monthsList = [ 'Janvier' ,'Février' , 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aôut', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ],
		this.daysList = [ 'Lundi' ,'Mardi' , 'Mercredi', 'Jeudi', 'Vendrerdi', 'Samedi', 'Dimanche' ],
		*/
		
		this.monthsList = [ 'Enero' ,'Febrero' , 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
		this.daysList = [ 'Lunes' ,'Martes' , 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo' ],
		
		this.shortDaysList = [ 'L' ,'M' , 'M', 'J', 'V', 'S', 'D' ],

		this.target.addClassName('calendar');
		
		this.calDiv = document.createElement('div');
		this.calDiv.className='calendar-div';
	 	this.calDiv.style.display = 'none';
		
		this.target.parentNode.insertBefore(this.calDiv, this.target.nextSibling);
	
	    Event.observe(this.calDiv,'mouseover', this.handleEvent.bindAsEventListener(this), true);
	    Event.observe(this.calDiv,'mouseout', this.handleEvent.bindAsEventListener(this), true);
	    Event.observe(this.calDiv,'click', this.handleEvent.bindAsEventListener(this), true);
	  
	    Event.observe(this.target,'click', this.showCalendar.bindAsEventListener(this), true);


	  this.setValue(value||this.target.value);
	
},

setMysql : function() {
	/*
		var tmp = this.htarget.value.split('-');
	 	this.Year = tmp[0];
	 	this.Month = tmp[1]-1;
	 	this.Day = tmp[2];
	 	
	 	this.setValue(this.getValue()); 
	 */
},

getValue : function() {
	return this.paddZero(this.Day) + '/' + this.paddZero(this.Month+1) + '/' + this.Year;
},


getMysql : function() {
	return this.Year + '-' + this.paddZero(this.Month+1) + '-' + this.paddZero(this.Day);
},

getTimestamp : function() {
	
	var d = new Date(this.Year,this.Month-1,this.Day);
	return Number(d)/1000;
},

setValue : function(value) {
	
	this.oNow = new Date();		  
	var dateRegExp = new RegExp ('^\(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])\/([12][0-9]{3})$');
	
	if (value && typeof(value)=='object') {
		this.Year = value.getFullYear();
		this.Month = value.getMonth();
		this.Day = value.getDate();
	} else if (value && (this.matches = value.match( dateRegExp ))) {		
		this.Year = Number(this.matches[3]);
		this.Month = Number(this.matches[2])-1;
		this.Day = Number(this.matches[1]);
	}	else {
		this.Year = this.oNow.getFullYear();
		this.Month = this.oNow.getMonth();
		this.Day = this.oNow.getDate();
	}		
	
	//var result = this.Year + '/' + (this.Month+1) + '/' + this.Day;
	
	this.target.value=this.getValue();

		  
  	this.calDiv.innerHTML = this.refresh();	
  	if (this.htarget && this.target.value!='') {
  		this.htarget.value = this.getMysql();
  	}
				
	//return result;
	
},

getHolidays : function() {
	/* 
		 Holidays depends of country. Might be usefull to have Ajax trigger to get holidays days ? 
		 Moreover by this mean we can get more datas like non worked day, appointments, ... 	
	*/
	
	/* Festivos Regionales y Nacionales */
	this.holidays = { 0 : { 1: {name:"Año Nuevo",classname:"national"}, 6: {name: "Epifanía del Señor", classname: "national"} },
					  1: {}, 
					  2: {19:{name:"San José", classname: "national"} }, 
					  3: {},					  
					  4 : {1:{name:"Día del Trabajo", classname: "national"} }, 
					  5:{9:{name:"Día de la Región", classname: "regional"} }, 
					  6: {},
					  7 : {15:{name:"Asunción de la Virgen", classname: "national"} }, 
					  8:{}, 
					  9:{12:{name:"Fiesta Nacional", classname: "national"} }, 
					  10 : {1:{name:"Todos los Santos", classname: "national"} },
					  11 : {6: {name:"Día de la Constitución Española", classname: "national"}, 8: {name:"La Inmaculada Concepción", classname: "national"}, 25: {name:"Natividad del Señor", classname: "national"} } 					 
					  };
	
	
	var p = this.paques(this.Year);
 	p.setDate(p.getDate()-2);
	this.holidays[ p.getMonth() ][ p.getDate() ] = {name: 'Viernes Santo', classname: "national"}; 

},

paques : function(annee) {
   annee = parseInt(annee);
   var date_paques = null;
   var b = annee - 1900;
   var c = annee % 19;
   var d = Math.floor((7*c+1)/19);
   var e = (11*c+4-d) % 29;
   var f = Math.floor(b/4);
   var g = (b+f+31-e) % 7;
   var avril = 25-e-g;
   if (avril > 0) date_paques = new Date(annee, 3, avril);
   else date_paques = new Date(annee, 2, avril + 31);
   return date_paques;
},

/*function calcular(anne) {
    var ent = document.frm.year;
    var sal = document.frm.res;
    year = parseInt(ent.value);
    a = year % 19;
    b = year % 4;
    c = year % 7;
    if (year >= 1583 && year <= 1699) {
        m = 22;
        n = 2;
    } else {
        if (year >= 1700 && year <= 1799) {
            m = 23;
            n = 3;
        } else {
            if (year >= 1800 && year <= 1899) {
                m = 23;
                n = 4;
            } else {
                if (year >= 1900 && year <= 2099) {
                    m = 24;
                    n = 5;
                } else {
                    if (year >= 2100 && year <= 2199) {
                        m = 24;
                        n = 6;
                    } else {
                        if (year >= 2200 && year <= 2299) {
                            m = 25;
                            n = 0;
                        } else {
                            sal.value = "AxF1o debe ser entre 1583 y 2299";
                            return;
                        }
                    }
                }
            }
        }
    }
d = (19 * a + m) % 30;
e = (2 * b + 4 * c + 6 * d + n) % 7;
    if (d + e < 10) {
        sal.value = (d + e + 22) + " de Marzo";
    } else {
        if ((d + e - 9) == 26) {
            sal.value = "19 de Abril";
        } else {
            if ((d + e - 9) == 25 && d == 28 && e == 6 && a > 10) {
                sal.value = "18 de Abril";
            } else {
                sal.value = (d + e - 9) + " de Abril";
            }
        }
    }
}*/
close: function () {
	new Effect.Fade($(this.calDiv));
	/*this.calDiv.style.display = this.calDiv.style.display=='none'?'block':'none';*/
},

refresh : function () {
		this.getHolidays();
		this.currentDate = new Date(this.Year, this.Month, 1); 
		this.firstDay = this.currentDate.getDay();
		this.firstDay = this.firstDay ? this.firstDay - 1 : 6;
		
		this.days = this.numberOfDays( this.currentDate.getMonth() + 1, this.currentDate.getFullYear());	

		var str = '<table class="calendar-table"><thead>';
		str += '<tr><th class="calendar-minus"><span>-</span></th><th colspan="2" class="calendar-title">'+this.monthsList[ this.Month ] +'</th><th  class="calendar-plus"><span>+</span></th>';
		str += '<th class="calendar-minus-year"><span>-</span></th><th class="calendar-title">'+this.Year+'</th><th class="calendar-plus-year"><span>+</span></th></tr>';
				
		$A(this.shortDaysList).each ( function (d) { str+='<th class="calendar-dayname">'+ d +'</th>'; } );
		
		str += '</tr>';
		str += '</thead>';
		
		str += '<tbody><tr>';
	  
		for(var j=1;j <= 42 ;j++) { 
			d = j - this.firstDay;
				if (d>0 && d <= this.days) {
				
				var class_str ='';
				if (d == this.oNow.getDate() && this.Month == this.oNow.getMonth() && this.Year == this.oNow.getFullYear()) class_str += ' calendar-today';
				
				if (this.holidays[this.Month] && this.holidays[this.Month][d]) {
					var o = this.holidays[this.Month][d]; 
					class_str = ' calendar-holiday-'+o.classname; 
					str+= '<td class="'+class_str+'" title="'+o.name+'">'+d+'</td>';
				}	else {
					
					var dt = new Date(this.Year, this.Month, d); 
					
					if (dt.getDay()==0 ) {
						class_str = ' calendar-holiday-national'; 	
					}
									
					str+= '<td class="'+class_str+'">'+d+'</td>';
				}
					
			} else {
				str +='<td>&nbsp;</td>';
			}
			
			if (j % 7==0) str+='</tr>\n<tr>';
		}
		
		str += '</tr></tbody></table>';
		return str;
},

showCalendar: function  (evt) {

	var t =  Event.element(evt);
	
	var p3 = Position.positionedOffset(this.target);
  	Element.setStyle(this.calDiv, { position:'absolute', left: (p3[0]) +'px', zindex: 999});
	new Effect.Appear($(this.calDiv));
	this.calDiv.innerHTML = this.refresh();

},

handleEvent : function (evt) {

	var t =  Event.element(evt);
	
	switch (t.nodeName.toLowerCase()) {
			case 'input':
				//this.setValue(this.target.value); 
				break;
			case 'th':
				switch (evt.type) {
					case 'click':
						switch (t.className) {
							case 'calendar-minus-year':
							  	this.Year--;
								break;
								
							case 'calendar-minus':
							  if (this.Month>0) {
							  	this.Month--;
							  } else if (this.Year>1900) {
							  	this.Month=11;
							  	this.Year--;
							  }
							  
								break;
							case 'calendar-plus-year':
							  	this.Year++;
								break;

							case 'calendar-plus':
							  if (this.Month<11) {
							  	this.Month++;
								} else {
									this.Month=0;
									this.Year++;
								}
								break;
							case 'calendar-title':
							 	//alert('title');
							 	
							
						}
						
						this.calDiv.innerHTML = this.refresh();
						break;
				}
				break;
			case 'td':
			  if (t.innerHTML=='&nbsp;') break;
			  switch (evt.type) {
			  	case 'click':
			  	  this.close();
			  	  this.Day = t.innerHTML;
			  	  
			  	  this.target.value = this.getValue();
			  	  if (this.htarget) this.htarget.value = this.getMysql();
			  	  this.target.focus();
			  	  break;
			  	  
			  	case 'mouseover':
						t.className += ' calendar-day-over';
						break;
					case 'mouseout':
						t.className = t.className.replace(/\bcalendar-day-over\b/g, "");
						break;
				}									
				break;
			default: 
		}
},

paddZero : function (value) {
	
	value = value.toString(); 

  if ( value.length < 2) {
  	value = '0'+value;
  }

  return value;
}, 

numberOfDays : function (month,year) {
	switch (month) { 
	 	case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
			break;
		case 2:
			return year%4==0?29:28;
	}
}

};



/*
concentre.inputmasks.unixdatepicker = function() {
		this.init.apply(this, arguments);
};

concentre.inputmasks.unixdatepicker.inherits(DatePicker);

concentre.inputmasks.unixdatepicker.prototype.getValue = function(value) {
	var d = new Date(this.Year,this.Month-1,this.Day);
	return Number(d)/1000;
};

concentre.inputmasks.unixdatepicker.prototype.setValue = function(value) {
	 
  var d = new Date(value * 1000);

	this.Year = d.getFullYear();
	this.Month = d.getMonth();
	this.Day = d.getDate();

	this.oNow = new Date();		  
  this.calDiv.innerHTML = this.refresh();	
  	
	return this.Year + '/' + (this.Month+1) + '/' + this.Day;
	
};

*/