2 * (c) 2005-2011 Richard Cowin (http://openrico.org)
3 * (c) 2005-2011 Matt Brown (http://dowdybrown.com)
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6 * file except in compliance with the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software distributed under the
11 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
12 * either express or implied. See the License for the specific language governing permissions
13 * and limitations under the License.
16 // Inspired by code originally written by Tan Ling Wee on 2 Dec 2001
18 Rico.CalendarControl = function(id,options) {
19 this.initialize(id,options);
22 Rico.CalendarControl.prototype = {
24 * @class Implements a pop-up Gregorian calendar.
25 * Dates of adoption of the Gregorian calendar vary by country - accurate as a US & British calendar from 14 Sept 1752 to present.
26 * Mark special dates with calls to addHoliday()
29 * @param id unique identifier
30 * @param options object may contain any of the following:<dl>
31 * <dt>startAt </dt><dd> week starts with 0=sunday, 1=monday? default=0</dd>
32 * <dt>showWeekNumber</dt><dd> show week number in first column? default=0</dd>
33 * <dt>showToday </dt><dd> show "Today is..." in footer? default=1</dd>
34 * <dt>dateFmt </dt><dd> date format for return value (one of values accepted by {@link Date#formatDate}), default=ISO8601</dd>
35 * <dt>minDate </dt><dd> earliest selectable date? default=today-50 years</dd>
36 * <dt>maxDate </dt><dd> last selectable date? default=today+50 years</dd>
39 initialize: function(id,options) {
42 Rico.extend(this, new Rico.Popup());
43 Rico.extend(this.options, {
49 minDate : new Date(today.getFullYear()-50,0,1),
50 maxDate : new Date(today.getFullYear()+50,11,31)
52 Rico.extend(this.options, options || {});
54 * alias for closePopup
57 this.close=this.closePopup;
58 this.bPageLoaded=false;
60 this.re=/^\s*(\w+)(\W)(\w+)(\W)(\w+)/i;
61 this.setDateFmt(this.options.dateFmt);
63 Rico.onLoad(function() { self.atLoad(); })
67 setDateFmt: function(fmt) {
68 this.dateFmt=(fmt=='rico') ? Rico.dateFmt : fmt;
69 Rico.log(this.id+' date format set to '+this.dateFmt);
71 if (this.re.exec(this.dateFmt)) {
72 this.dateParts[RegExp.$1]=0;
73 this.dateParts[RegExp.$3]=1;
74 this.dateParts[RegExp.$5]=2;
79 * Call before displaying calendar to highlight special days
81 * @param m month (1-12)
82 * @param y year (0 implies a repeating holiday)
83 * @param desc description
84 * @param bgColor background color for cell displaying this day (CSS value, defaults to '#DDF')
85 * @param txtColor text color for cell displaying this day (CSS value), if not specified it is displayed with the same color as other days
87 addHoliday : function(d, m, y, desc, bgColor, txtColor) {
88 this.Holidays[this.holidayKey(y,m-1,d)]={desc:desc, txtColor:txtColor, bgColor:bgColor || '#DDF'};
92 holidayKey : function(y,m,d) {
93 return 'h'+Rico.zFill(y,4)+Rico.zFill(m,2)+Rico.zFill(d,2);
97 Rico.log('Calendar#atLoad: '+this.id);
98 var div=Rico.$(this.id);
102 this.createContainer();
103 this.container.id=this.id;
105 Rico.addClass(this.content, Rico.theme.calendar || 'ricoCalContainer');
106 this.direction=Rico.direction(this.container);
108 var r,c,i,j,dow,a,s,tab;
109 this.colStart=this.options.showWeekNumber ? 1 : 0;
110 var colcnt=7+this.colStart
111 this.maintab=document.createElement("table");
112 this.maintab.cellSpacing=2;
113 this.maintab.cellPadding=0;
114 this.maintab.border=0;
115 this.maintab.style.borderCollapse='separate';
116 this.maintab.className=Rico.theme.calendarTable || 'ricoCalTab';
118 // thead (Navigation controls)
119 this.thead=this.maintab.createTHead();
120 r=this.thead.insertRow(-1);
121 this.heading=r.insertCell(-1);
122 this.heading.colSpan=colcnt;
123 //this.heading=this.content.appendChild(document.createElement("div"));
124 this.heading.className='RicoCalHeading';
125 if (Rico.theme.calendarHeading) Rico.addClass(this.heading,Rico.theme.calendarHeading)
127 // table footer (today)
128 if (this.options.showToday) {
129 this.tfoot=this.maintab.createTFoot();
130 this.tfoot.className='ricoCalFoot';
131 r=this.tfoot.insertRow(-1);
132 this.todayCell=r.insertCell(-1);
133 this.todayCell.colSpan=colcnt;
134 this.todayCell.className=Rico.theme.calendarFooter || 'ricoCalFoot';
135 Rico.eventBind(this.todayCell,"click", Rico.eventHandle(this,'selectNow'), false);
138 this.tbody=Rico.getTBody(this.maintab);
139 this.tbody.className='ricoCalBody';
141 this.content.style.display='block';
142 if (this.position == 'absolute') {
143 this.content.style.width='auto';
144 this.maintab.style.width='auto';
146 this.container.style.position='relative';
147 this.heading.style.position='static'; // fixes issue with ie7
148 this.content.style.padding='0px';
149 this.content.style.width='15em';
150 this.maintab.style.width='100%';
154 for (i=0; i<7; i++) {
155 r=this.tbody.insertRow(-1);
156 r.className=i==0 ? 'ricoCalDayNames' : 'row'+i;
157 if (this.options.showWeekNumber) {
159 c.className='ricoCalWeekNum';
160 if (i==0) c.innerHTML=Rico.getPhraseById("calWeekHdg");
162 for (j=0; j<7; j++) {
165 dow=(j+this.options.startAt) % 7;
166 c.innerHTML=Rico.dayAbbr(dow);
167 this.styles[j]='ricoCal'+dow;
169 c.className=this.styles[j];
170 if (Rico.theme.calendarDay) Rico.addClass(c,Rico.theme.calendarDay);
175 this.content.appendChild(this.maintab);
176 new Rico.HoverSet(this.tbody.getElementsByTagName('td'),{ hoverNodes: function(e) { return e.innerHTML.match(/^\d+$/) ? [e] : []; } });
178 this.navtab=this.heading.appendChild(document.createElement("table"));
179 this.navrow=this.navtab.insertRow(-1);
180 this._createTitleSection('Month');
181 this.navrow.insertCell(-1).innerHTML=" ";
182 this._createTitleSection('Year');
183 new Rico.HoverSet(this.heading.getElementsByTagName('a'));
184 if (this.position == 'absolute') this.heading.appendChild(Rico.closeButton(Rico.eventHandle(this,'close')));
187 this.monthPopup=new Rico.Popup(document.createElement("div"),{shim:false,zIndex:10});
188 this.monthPopup.content.className='ricoCalMonthPrompt';
189 tab=document.createElement("table");
190 tab.className='ricoCalMenu';
191 if (Rico.theme.calendarPopdown) Rico.addClass(tab,Rico.theme.calendarPopdown);
195 tab.style.borderCollapse='separate';
196 tab.style.margin='0px';
197 for (i=0; i<4; i++) {
199 for (j=0; j<3; j++) {
201 a=document.createElement("a");
202 a.innerHTML=Rico.monthAbbr(i*3+j);
204 if (Rico.theme.calendarDay) Rico.addClass(a,Rico.theme.calendarDay);
206 Rico.eventBind(a,"click", Rico.eventHandle(this,'selectMonth'), false);
209 new Rico.HoverSet(tab.getElementsByTagName('a'));
210 this.monthPopup.content.appendChild(tab);
211 this.container.appendChild(this.monthPopup.container);
212 this.monthPopup.closePopup();
215 this.yearPopup=new Rico.Popup(document.createElement("div"),{shim:false,zIndex:10});
216 this.yearPopup.content.className='ricoCalYearPrompt';
217 if (Rico.theme.calendarPopdown) Rico.addClass(this.yearPopup.content,Rico.theme.calendarPopdown);
218 var p1=document.createElement("p");
219 p1.innerHTML=Rico.getPhraseById("calYearRange",this.options.minDate.getFullYear(),this.options.maxDate.getFullYear());
220 var p2=document.createElement("p");
221 this.yearInput=p2.appendChild(document.createElement("input"));
222 this.yearInput.maxlength=4;
223 this.yearInput.size=4;
224 Rico.eventBind(this.yearInput,"keyup", Rico.eventHandle(this,'yearKey'), false);
225 a=Rico.floatButton('Checkmark', Rico.eventHandle(this,'processPopUpYear'));
227 a=Rico.floatButton('Cancel', Rico.eventHandle(this,'popDownYear'));
229 this.yearPopup.content.appendChild(p1);
230 this.yearPopup.content.appendChild(p2);
231 this.container.appendChild(this.yearPopup.container);
232 this.yearPopup.closePopup();
234 // fix anchors so they work in IE6
235 a=this.content.getElementsByTagName('a');
236 for (i=0; i<a.length; i++) {
237 a[i].href='javascript:void(0)';
240 Rico.eventBind(this.tbody,"click", Rico.eventHandle(this,'saveAndClose'));
242 this.bPageLoaded=true;
245 _createTitleSection : function(section) {
246 var arrows=['left','right'];
247 if (this.direction=='rtl') arrows.reverse();
248 var c=this.navrow.insertCell(-1);
249 var a=c.appendChild(document.createElement("a"));
250 a.className='Rico_'+arrows[0]+'Arrow';
251 a.appendChild(this._createNavArrow(arrows[0]));
252 Rico.eventBind(a,"click", Rico.eventHandle(this,'dec'+section), false);
254 c=this.navrow.insertCell(-1);
255 a=c.appendChild(document.createElement("a"));
256 Rico.eventBind(a,"click", Rico.eventHandle(this,'popUp'+section), false);
257 this['title'+section]=a;
259 c=this.navrow.insertCell(-1);
260 a=c.appendChild(document.createElement("a"));
261 a.className='Rico_'+arrows[1]+'Arrow';
262 a.appendChild(this._createNavArrow(arrows[1]));
263 Rico.eventBind(a,"click", Rico.eventHandle(this,'inc'+section), false);
266 _createNavArrow: function(direction) {
267 var span=document.createElement("span");
268 span.className=Rico.theme[direction+'Arrow'] || 'rico-icon Rico_'+direction+'Arrow';
269 span.style.display="inline-block";
273 selectNow : function() {
274 var today = new Date();
275 this.dateNow = today.getDate();
276 this.monthNow = today.getMonth();
277 this.yearNow = today.getFullYear();
278 this.monthSelected=this.monthNow;
279 this.yearSelected=this.yearNow;
280 this.constructCalendar();
284 * @returns true if yr/mo is within minDate/MaxDate
286 isValidMonth : function(yr,mo) {
287 if (yr < this.options.minDate.getFullYear()) return false;
288 if (yr == this.options.minDate.getFullYear() && mo < this.options.minDate.getMonth()) return false;
289 if (yr > this.options.maxDate.getFullYear()) return false;
290 if (yr == this.options.maxDate.getFullYear() && mo > this.options.maxDate.getMonth()) return false;
294 incMonth : function() {
295 var newMonth=this.monthSelected+1;
296 var newYear=this.yearSelected;
301 if (!this.isValidMonth(newYear,newMonth)) return;
302 this.monthSelected=newMonth;
303 this.yearSelected=newYear;
304 this.constructCalendar();
307 decMonth : function() {
308 var newMonth=this.monthSelected-1;
309 var newYear=this.yearSelected;
314 if (!this.isValidMonth(newYear,newMonth)) return;
315 this.monthSelected=newMonth;
316 this.yearSelected=newYear;
317 this.constructCalendar();
321 selectMonth : function(e) {
322 var el=Rico.eventElement(e);
323 this.monthSelected=parseInt(el.name,10);
324 this.constructCalendar();
328 // position: 0=left, 1=right
329 openYrMo : function(popup,position) {
330 if (this.direction=='rtl') position=1-position;
332 var left=position ? this.content.offsetWidth - popup.container.offsetWidth - 5 : 3;
333 popup.move(left, this.heading.offsetHeight+2);
336 popUpMonth : function(e) {
338 if (this.monthPopup.visible()) {
343 this.openYrMo(this.monthPopup,0);
347 popDownMonth : function() {
348 this.monthPopup.closePopup();
351 popDownYear : function() {
352 this.yearPopup.closePopup();
353 this.yearInput.disabled=true; // make sure this does not get submitted
359 popUpYear : function(e) {
361 if (this.yearPopup.visible()) {
366 this.yearInput.disabled=false;
367 this.yearInput.value=''; // this.yearSelected
368 this.openYrMo(this.yearPopup,1);
370 setTimeout(function() { self.yearInput.focus(); }, 10); // ie8 has issues without this delay
374 yearKey : function(e) {
375 switch (Rico.eventKey(e)) {
376 case 27: this.popDownYear(); Rico.eventStop(e); return false;
377 case 13: this.processPopUpYear(); Rico.eventStop(e); return false;
382 processPopUpYear : function() {
383 var newYear=this.yearInput.value;
384 newYear=parseInt(newYear,10);
385 if (isNaN(newYear) || newYear<this.options.minDate.getFullYear() || newYear>this.options.maxDate.getFullYear()) {
386 alert(Rico.getPhraseById("calInvalidYear"));
388 this.yearSelected=newYear;
390 this.constructCalendar();
394 incYear : function() {
395 if (this.yearSelected>=this.options.maxDate.getFullYear()) return;
397 this.constructCalendar();
400 decYear : function() {
401 if (this.yearSelected<=this.options.minDate.getFullYear()) return;
403 this.constructCalendar();
406 // tried a number of different week number functions posted on the net
407 // this is the only one that produced consistent results when comparing week numbers for December and the following January
408 WeekNbr : function(year,month,day) {
409 var when = new Date(year,month,day);
410 var newYear = new Date(year,0,1);
411 var offset = 7 + 1 - newYear.getDay();
412 if (offset == 8) offset = 1;
413 var daynum = ((Date.UTC(year,when.getMonth(),when.getDate(),0,0,0) - Date.UTC(year,0,1,0,0,0)) /1000/60/60/24) + 1;
414 var weeknum = Math.floor((daynum-offset+7)/7);
417 var prevNewYear = new Date(year,0,1);
418 var prevOffset = 7 + 1 - prevNewYear.getDay();
419 weeknum = (prevOffset == 2 || prevOffset == 8) ? 53 : 52;
424 constructCalendar : function() {
425 var aNumDays = [31,0,31,30,31,30,31,31,30,31,30,31];
426 var startDate = new Date (this.yearSelected,this.monthSelected,1);
427 var endDate,numDaysInMonth,i,colnum;
429 if (typeof this.monthSelected!='number' || this.monthSelected>=12 || this.monthSelected<0) {
430 alert('ERROR in calendar: monthSelected='+this.monthSelected);
434 if (this.monthSelected==1) {
435 endDate = new Date (this.yearSelected,this.monthSelected+1,1);
436 endDate = new Date (endDate - (24*60*60*1000));
437 numDaysInMonth = endDate.getDate();
439 numDaysInMonth = aNumDays[this.monthSelected];
441 var dayPointer = startDate.getDay() - this.options.startAt;
442 if (dayPointer<0) dayPointer+=7;
446 //this.bgcolor=Rico.getStyle(this.tbody,'background-color');
447 //this.bgcolor=this.bgcolor.replace(/\"/g,'');
448 if (this.options.showWeekNumber) {
449 for (i=1; i<7; i++) {
450 this.tbody.rows[i].cells[0].innerHTML=' ';
453 for ( i=0; i<dayPointer; i++ ) {
454 this.resetCell(this.tbody.rows[1].cells[i+this.colStart]);
457 for ( var datePointer=1,r=1; datePointer<=numDaysInMonth; datePointer++,dayPointer++ ) {
458 colnum=dayPointer % 7;
459 if (this.options.showWeekNumber && colnum==0) {
460 this.tbody.rows[r].cells[0].innerHTML=this.WeekNbr(this.yearSelected,this.monthSelected,datePointer);
462 var c=this.tbody.rows[r].cells[colnum+this.colStart];
463 c.innerHTML=datePointer;
464 c.className=this.styles[colnum];
465 if ((datePointer==this.dateNow)&&(this.monthSelected==this.monthNow)&&(this.yearSelected==this.yearNow)) {
466 Rico.addClass(c,Rico.theme.calendarToday || 'ricoCalToday');
468 if (Rico.theme.calendarDay) Rico.addClass(c,Rico.theme.calendarDay);
469 if ((datePointer==this.odateSelected) && (this.monthSelected==this.omonthSelected) && (this.yearSelected==this.oyearSelected)) {
470 Rico.addClass(c,Rico.theme.calendarSelectedDay || 'ricoSelectedDay');
472 var h=this.Holidays[this.holidayKey(this.yearSelected,this.monthSelected,datePointer)];
474 h=this.Holidays[this.holidayKey(0,this.monthSelected,datePointer)];
476 c.style.color=h ? h.txtColor : '';
477 c.style.backgroundColor=h ? h.bgColor : '';
478 c.title=h ? h.desc : '';
479 c.style.visibility='visible';
482 while (dayPointer<42) {
483 colnum=dayPointer % 7;
484 this.resetCell(this.tbody.rows[r].cells[colnum+this.colStart]);
489 this.titleMonth.innerHTML = Rico.monthAbbr(this.monthSelected);
490 this.titleYear.innerHTML = this.yearSelected;
491 if (this.todayCell) {
492 this.todayCell.innerHTML = Rico.getPhraseById("calToday",this.dateNow,Rico.monthAbbr(this.monthNow),this.yearNow,this.monthNow+1);
497 resetCell: function(c) {
498 c.innerHTML=" ";
500 c.style.visibility='hidden';
504 saveAndClose : function(e) {
506 var el=Rico.eventElement(e);
507 var s=el.innerHTML.replace(/ /g,'');
508 if (s=='' || el.className=='ricoCalWeekNum') return;
509 var day=parseInt(s,10);
510 if (isNaN(day)) return;
511 var d=new Date(this.yearSelected,this.monthSelected,day);
512 var dateStr=Rico.formatDate(d,this.dateFmt=='ISO8601' ? 'yyyy-mm-dd' : this.dateFmt);
513 if (this.returnValue) {
514 this.returnValue(dateStr);
519 open : function(curval) {
520 if (!this.bPageLoaded) return;
521 var today = new Date();
522 this.dateNow = today.getDate();
523 this.monthNow = today.getMonth();
524 this.yearNow = today.getFullYear();
525 this.oyearSelected = -1;
526 if (typeof curval=='object') {
527 this.odateSelected = curval.getDate();
528 this.omonthSelected = curval.getMonth();
529 this.oyearSelected = curval.getFullYear();
530 } else if (this.dateFmt=='ISO8601') {
531 var d=Rico.setISO8601(curval);
533 this.odateSelected = d.getDate();
534 this.omonthSelected = d.getMonth();
535 this.oyearSelected = d.getFullYear();
537 } else if (this.re.exec(curval)) {
538 var aDate = [ RegExp.$1, RegExp.$3, RegExp.$5 ];
539 this.odateSelected = parseInt(aDate[this.dateParts.dd], 10);
540 this.omonthSelected = parseInt(aDate[this.dateParts.mm], 10) - 1;
541 this.oyearSelected = parseInt(aDate[this.dateParts.yyyy], 10);
542 if (this.oyearSelected < 100) {
543 // apply a century to 2-digit years
544 this.oyearSelected+=this.yearNow - (this.yearNow % 100);
545 var maxyr=this.options.maxDate.getFullYear();
546 while (this.oyearSelected > maxyr) this.oyearSelected-=100;
550 alert('ERROR: invalid date passed to calendar ('+curval+')');
553 if (this.oyearSelected > 0) {
554 this.dateSelected=this.odateSelected;
555 this.monthSelected=this.omonthSelected;
556 this.yearSelected=this.oyearSelected;
558 this.dateSelected=this.dateNow;
559 this.monthSelected=this.monthNow;
560 this.yearSelected=this.yearNow;
562 this.constructCalendar();