2 * (c) 2005-2009 Richard Cowin (http://openrico.org)
3 * (c) 2005-2009 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;
61 this.re=/^\s*(\w+)(\W)(\w+)(\W)(\w+)/i;
62 this.setDateFmt(this.options.dateFmt);
66 setDateFmt: function(fmt) {
67 this.dateFmt=(fmt=='rico') ? Rico.dateFmt : fmt;
68 Rico.log(this.id+' date format set to '+this.dateFmt);
70 if (this.re.exec(this.dateFmt)) {
71 this.dateParts[RegExp.$1]=0;
72 this.dateParts[RegExp.$3]=1;
73 this.dateParts[RegExp.$5]=2;
78 * Call before displaying calendar to highlight special days
80 * @param m month (1-12)
81 * @param y year (0 implies a repeating holiday)
82 * @param desc description
83 * @param bgColor background color for cell displaying this day (CSS value, defaults to '#DDF')
84 * @param txtColor text color for cell displaying this day (CSS value), if not specified it is displayed with the same color as other days
86 addHoliday : function(d, m, y, desc, bgColor, txtColor) {
87 this.Holidays[this.holidayKey(y,m-1,d)]={desc:desc, txtColor:txtColor, bgColor:bgColor || '#DDF'};
91 holidayKey : function(y,m,d) {
92 return 'h'+Rico.zFill(y,4)+Rico.zFill(m,2)+Rico.zFill(d,2);
96 Rico.log('Calendar#atLoad: '+this.id);
97 var div=Rico.$(this.id);
101 this.createContainer();
102 this.container.id=this.id;
104 Rico.addClass(this.content, Rico.theme.calendar || 'ricoCalContainer');
105 this.direction=Rico.direction(this.container);
107 var r,c,i,j,img,dow,a,s,tab;
108 this.colStart=this.options.showWeekNumber ? 1 : 0;
109 var colcnt=7+this.colStart
110 this.maintab=document.createElement("table");
111 this.maintab.cellSpacing=2;
112 this.maintab.cellPadding=0;
113 this.maintab.border=0;
114 this.maintab.style.borderCollapse='separate';
115 this.maintab.className=Rico.theme.calendarTable || 'ricoCalTab';
116 this.tbody=Rico.getTBody(this.maintab);
117 this.tbody.className='ricoCalBody';
118 this.thead=this.maintab.createTHead();
119 r=this.thead.insertRow(-1);
120 this.heading=r.insertCell(-1);
121 this.heading.colSpan=colcnt;
123 this.content.style.display='block';
124 if (this.position == 'absolute') {
125 this.content.style.width='auto';
126 this.maintab.style.width='auto';
128 this.container.style.position='relative';
129 this.heading.style.position='static'; // fixes issue with ie7
130 this.content.style.padding='0px';
131 this.content.style.width='15em';
132 this.maintab.style.width='100%';
135 // Navigation controls
136 //this.heading=this.content.appendChild(document.createElement("div"));
137 this.heading.className='RicoCalHeading';
138 if (Rico.theme.calendarHeading) Rico.addClass(this.heading,Rico.theme.calendarHeading)
139 this.navtab=this.heading.appendChild(document.createElement("table"));
140 this.navrow=this.navtab.insertRow(-1);
141 this._createTitleSection('Month');
142 this.navrow.insertCell(-1).innerHTML=" ";
143 this._createTitleSection('Year');
144 new Rico.HoverSet(this.heading.getElementsByTagName('a'));
145 if (this.position == 'absolute') this.heading.appendChild(Rico.closeButton(Rico.eventHandle(this,'close')));
148 for (i=0; i<7; i++) {
149 r=this.tbody.insertRow(-1);
150 r.className=i==0 ? 'ricoCalDayNames' : 'row'+i;
151 if (this.options.showWeekNumber) {
153 c.className='ricoCalWeekNum';
154 if (i==0) c.innerHTML=Rico.getPhraseById("calWeekHdg");
156 for (j=0; j<7; j++) {
159 dow=(j+this.options.startAt) % 7;
160 c.innerHTML=Rico.dayAbbr(dow);
161 this.styles[j]='ricoCal'+dow;
163 c.className=this.styles[j];
164 if (Rico.theme.calendarDay) Rico.addClass(c,Rico.theme.calendarDay);
169 // table footer (today)
170 if (this.options.showToday) {
171 this.tfoot=this.maintab.createTFoot();
172 this.tfoot.className='ricoCalFoot';
173 r=this.tfoot.insertRow(-1);
174 this.todayCell=r.insertCell(-1);
175 this.todayCell.colSpan=colcnt;
176 this.todayCell.className=Rico.theme.calendarFooter || 'ricoCalFoot';
177 Rico.eventBind(this.todayCell,"click", Rico.eventHandle(this,'selectNow'), false);
179 this.content.appendChild(this.maintab);
180 new Rico.HoverSet(this.tbody.getElementsByTagName('td'),{ hoverNodes: function(e) { return e.innerHTML.match(/^\d+$/) ? [e] : []; } });
183 this.monthPopup=new Rico.Popup(document.createElement("div"),{shim:false,zIndex:10});
184 this.monthPopup.content.className='ricoCalMonthPrompt';
185 tab=document.createElement("table");
186 tab.className='ricoCalMenu';
187 if (Rico.theme.calendarPopdown) Rico.addClass(tab,Rico.theme.calendarPopdown);
191 tab.style.borderCollapse='separate';
192 tab.style.margin='0px';
193 for (i=0; i<4; i++) {
195 for (j=0; j<3; j++) {
197 a=document.createElement("a");
198 a.innerHTML=Rico.monthAbbr(i*3+j);
200 if (Rico.theme.calendarDay) Rico.addClass(a,Rico.theme.calendarDay);
202 Rico.eventBind(a,"click", Rico.eventHandle(this,'selectMonth'), false);
205 new Rico.HoverSet(tab.getElementsByTagName('a'));
206 this.monthPopup.content.appendChild(tab);
207 this.container.appendChild(this.monthPopup.container);
208 this.monthPopup.closePopup();
211 this.yearPopup=new Rico.Popup(document.createElement("div"),{shim:false,zIndex:10});
212 this.yearPopup.content.className='ricoCalYearPrompt';
213 if (Rico.theme.calendarPopdown) Rico.addClass(this.yearPopup.content,Rico.theme.calendarPopdown);
214 var p1=document.createElement("p");
215 p1.innerHTML=Rico.getPhraseById("calYearRange",this.options.minDate.getFullYear(),this.options.maxDate.getFullYear());
216 var p2=document.createElement("p");
217 this.yearInput=p2.appendChild(document.createElement("input"));
218 this.yearInput.maxlength=4;
219 this.yearInput.size=4;
220 Rico.eventBind(this.yearInput,"keyup", Rico.eventHandle(this,'yearKey'), false);
221 a=Rico.floatButton('Checkmark', Rico.eventHandle(this,'processPopUpYear'));
223 a=Rico.floatButton('Cancel', Rico.eventHandle(this,'popDownYear'));
225 this.yearPopup.content.appendChild(p1);
226 this.yearPopup.content.appendChild(p2);
227 this.container.appendChild(this.yearPopup.container);
228 this.yearPopup.closePopup();
230 // fix anchors so they work in IE6
231 a=this.content.getElementsByTagName('a');
232 for (i=0; i<a.length; i++) {
233 a[i].href='javascript:void(0)';
236 Rico.eventBind(this.tbody,"click", Rico.eventHandle(this,'saveAndClose'));
238 this.bPageLoaded=true;
241 _createTitleSection : function(section) {
242 var arrows=['left','right'];
243 if (this.direction=='rtl') arrows.reverse();
244 var c=this.navrow.insertCell(-1);
245 var a=c.appendChild(document.createElement("a"));
246 a.className='Rico_'+arrows[0]+'Arrow';
247 a.appendChild(this.createNavArrow('dec'+section,arrows[0]));
249 c=this.navrow.insertCell(-1);
250 a=c.appendChild(document.createElement("a"));
251 Rico.eventBind(a,"click", Rico.eventHandle(this,'popUp'+section), false);
252 this['title'+section]=a;
254 c=this.navrow.insertCell(-1);
255 a=c.appendChild(document.createElement("a"));
256 a.className='Rico_'+arrows[1]+'Arrow';
257 a.appendChild(this.createNavArrow('inc'+section,arrows[1]));
260 selectNow : function() {
261 var today = new Date();
262 this.dateNow = today.getDate();
263 this.monthNow = today.getMonth();
264 this.yearNow = today.getFullYear();
265 this.monthSelected=this.monthNow;
266 this.yearSelected=this.yearNow;
267 this.constructCalendar();
271 createNavArrow: function(funcname,direction) {
272 var span=document.createElement("span");
273 span.className=Rico.theme[direction+'Arrow'] || 'rico-icon Rico_'+direction+'Arrow';
274 span.style.display="inline-block";
275 Rico.eventBind(span,"click", Rico.eventHandle(this,funcname), false);
280 * @returns true if yr/mo is within minDate/MaxDate
282 isValidMonth : function(yr,mo) {
283 if (yr < this.options.minDate.getFullYear()) return false;
284 if (yr == this.options.minDate.getFullYear() && mo < this.options.minDate.getMonth()) return false;
285 if (yr > this.options.maxDate.getFullYear()) return false;
286 if (yr == this.options.maxDate.getFullYear() && mo > this.options.maxDate.getMonth()) return false;
290 incMonth : function() {
291 var newMonth=this.monthSelected+1;
292 var newYear=this.yearSelected;
297 if (!this.isValidMonth(newYear,newMonth)) return;
298 this.monthSelected=newMonth;
299 this.yearSelected=newYear;
300 this.constructCalendar();
303 decMonth : function() {
304 var newMonth=this.monthSelected-1;
305 var newYear=this.yearSelected;
310 if (!this.isValidMonth(newYear,newMonth)) return;
311 this.monthSelected=newMonth;
312 this.yearSelected=newYear;
313 this.constructCalendar();
317 selectMonth : function(e) {
318 var el=Rico.eventElement(e);
319 this.monthSelected=parseInt(el.name,10);
320 this.constructCalendar();
324 // position: 0=left, 1=right
325 openYrMo : function(popup,position) {
326 if (this.direction=='rtl') position=1-position;
328 var left=position ? this.content.offsetWidth - popup.container.offsetWidth - 5 : 3;
329 popup.move(left, this.heading.offsetHeight+2);
332 popUpMonth : function(e) {
334 if (this.monthPopup.visible()) {
339 this.openYrMo(this.monthPopup,0);
343 popDownMonth : function() {
344 this.monthPopup.closePopup();
347 popDownYear : function() {
348 this.yearPopup.closePopup();
349 this.yearInput.disabled=true; // make sure this does not get submitted
355 popUpYear : function(e) {
357 if (this.yearPopup.visible()) {
362 this.yearInput.disabled=false;
363 this.yearInput.value=''; // this.yearSelected
364 this.openYrMo(this.yearPopup,1);
366 setTimeout(function() { self.yearInput.focus(); }, 10); // ie8 has issues without this delay
370 yearKey : function(e) {
371 switch (Rico.eventKey(e)) {
372 case 27: this.popDownYear(); Rico.eventStop(e); return false;
373 case 13: this.processPopUpYear(); Rico.eventStop(e); return false;
378 processPopUpYear : function() {
379 var newYear=this.yearInput.value;
380 newYear=parseInt(newYear,10);
381 if (isNaN(newYear) || newYear<this.options.minDate.getFullYear() || newYear>this.options.maxDate.getFullYear()) {
382 alert(Rico.getPhraseById("calInvalidYear"));
384 this.yearSelected=newYear;
386 this.constructCalendar();
390 incYear : function() {
391 if (this.yearSelected>=this.options.maxDate.getFullYear()) return;
393 this.constructCalendar();
396 decYear : function() {
397 if (this.yearSelected<=this.options.minDate.getFullYear()) return;
399 this.constructCalendar();
402 // tried a number of different week number functions posted on the net
403 // this is the only one that produced consistent results when comparing week numbers for December and the following January
404 WeekNbr : function(year,month,day) {
405 var when = new Date(year,month,day);
406 var newYear = new Date(year,0,1);
407 var offset = 7 + 1 - newYear.getDay();
408 if (offset == 8) offset = 1;
409 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;
410 var weeknum = Math.floor((daynum-offset+7)/7);
413 var prevNewYear = new Date(year,0,1);
414 var prevOffset = 7 + 1 - prevNewYear.getDay();
415 weeknum = (prevOffset == 2 || prevOffset == 8) ? 53 : 52;
420 constructCalendar : function() {
421 var aNumDays = [31,0,31,30,31,30,31,31,30,31,30,31];
422 var startDate = new Date (this.yearSelected,this.monthSelected,1);
423 var endDate,numDaysInMonth,i,colnum;
425 if (typeof this.monthSelected!='number' || this.monthSelected>=12 || this.monthSelected<0) {
426 alert('ERROR in calendar: monthSelected='+this.monthSelected);
430 if (this.monthSelected==1) {
431 endDate = new Date (this.yearSelected,this.monthSelected+1,1);
432 endDate = new Date (endDate - (24*60*60*1000));
433 numDaysInMonth = endDate.getDate();
435 numDaysInMonth = aNumDays[this.monthSelected];
437 var dayPointer = startDate.getDay() - this.options.startAt;
438 if (dayPointer<0) dayPointer+=7;
442 //this.bgcolor=Rico.getStyle(this.tbody,'background-color');
443 //this.bgcolor=this.bgcolor.replace(/\"/g,'');
444 if (this.options.showWeekNumber) {
445 for (i=1; i<7; i++) {
446 this.tbody.rows[i].cells[0].innerHTML=' ';
449 for ( i=0; i<dayPointer; i++ ) {
450 this.resetCell(this.tbody.rows[1].cells[i+this.colStart]);
453 for ( var datePointer=1,r=1; datePointer<=numDaysInMonth; datePointer++,dayPointer++ ) {
454 colnum=dayPointer % 7;
455 if (this.options.showWeekNumber && colnum==0) {
456 this.tbody.rows[r].cells[0].innerHTML=this.WeekNbr(this.yearSelected,this.monthSelected,datePointer);
458 var c=this.tbody.rows[r].cells[colnum+this.colStart];
459 c.innerHTML=datePointer;
460 c.className=this.styles[colnum];
461 if ((datePointer==this.dateNow)&&(this.monthSelected==this.monthNow)&&(this.yearSelected==this.yearNow)) {
462 Rico.addClass(c,Rico.theme.calendarToday || 'ricoCalToday');
464 if (Rico.theme.calendarDay) Rico.addClass(c,Rico.theme.calendarDay);
465 if ((datePointer==this.odateSelected) && (this.monthSelected==this.omonthSelected) && (this.yearSelected==this.oyearSelected)) {
466 Rico.addClass(c,Rico.theme.calendarSelectedDay || 'ricoSelectedDay');
468 var h=this.Holidays[this.holidayKey(this.yearSelected,this.monthSelected,datePointer)];
470 h=this.Holidays[this.holidayKey(0,this.monthSelected,datePointer)];
472 c.style.color=h ? h.txtColor : '';
473 c.style.backgroundColor=h ? h.bgColor : '';
474 c.title=h ? h.desc : '';
475 c.style.visibility='visible';
478 while (dayPointer<42) {
479 colnum=dayPointer % 7;
480 this.resetCell(this.tbody.rows[r].cells[colnum+this.colStart]);
485 this.titleMonth.innerHTML = Rico.monthAbbr(this.monthSelected);
486 this.titleYear.innerHTML = this.yearSelected;
487 if (this.todayCell) {
488 this.todayCell.innerHTML = Rico.getPhraseById("calToday",this.dateNow,Rico.monthAbbr(this.monthNow),this.yearNow,this.monthNow+1);
493 resetCell: function(c) {
494 c.innerHTML=" ";
496 c.style.visibility='hidden';
500 saveAndClose : function(e) {
502 var el=Rico.eventElement(e);
503 var s=el.innerHTML.replace(/ /g,'');
504 if (s=='' || el.className=='ricoCalWeekNum') return;
505 var day=parseInt(s,10);
506 if (isNaN(day)) return;
507 var d=new Date(this.yearSelected,this.monthSelected,day);
508 var dateStr=Rico.formatDate(d,this.dateFmt=='ISO8601' ? 'yyyy-mm-dd' : this.dateFmt);
509 if (this.returnValue) {
510 this.returnValue(dateStr);
515 open : function(curval) {
516 if (!this.bPageLoaded) return;
517 var today = new Date();
518 this.dateNow = today.getDate();
519 this.monthNow = today.getMonth();
520 this.yearNow = today.getFullYear();
521 this.oyearSelected = -1;
522 if (typeof curval=='object') {
523 this.odateSelected = curval.getDate();
524 this.omonthSelected = curval.getMonth();
525 this.oyearSelected = curval.getFullYear();
526 } else if (this.dateFmt=='ISO8601') {
527 var d=Rico.setISO8601(curval);
529 this.odateSelected = d.getDate();
530 this.omonthSelected = d.getMonth();
531 this.oyearSelected = d.getFullYear();
533 } else if (this.re.exec(curval)) {
534 var aDate = [ RegExp.$1, RegExp.$3, RegExp.$5 ];
535 this.odateSelected = parseInt(aDate[this.dateParts.dd], 10);
536 this.omonthSelected = parseInt(aDate[this.dateParts.mm], 10) - 1;
537 this.oyearSelected = parseInt(aDate[this.dateParts.yyyy], 10);
538 if (this.oyearSelected < 100) {
539 // apply a century to 2-digit years
540 this.oyearSelected+=this.yearNow - (this.yearNow % 100);
541 var maxyr=this.options.maxDate.getFullYear();
542 while (this.oyearSelected > maxyr) this.oyearSelected-=100;
546 alert('ERROR: invalid date passed to calendar ('+curval+')');
549 if (this.oyearSelected > 0) {
550 this.dateSelected=this.odateSelected;
551 this.monthSelected=this.omonthSelected;
552 this.yearSelected=this.oyearSelected;
554 this.dateSelected=this.dateNow;
555 this.monthSelected=this.monthNow;
556 this.yearSelected=this.yearNow;
558 this.constructCalendar();