Roo/form/ComboBoxArray.js
[roojs1] / Roo / DatePicker.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.DatePicker
14  * @extends Roo.Component
15  * Simple date picker class.
16  * @constructor
17  * Create a new DatePicker
18  * @param {Object} config The config object
19  */
20 Roo.DatePicker = function(config){
21     Roo.DatePicker.superclass.constructor.call(this, config);
22
23     this.value = config && config.value ?
24                  config.value.clearTime() : new Date().clearTime();
25
26     this.addEvents({
27         /**
28              * @event select
29              * Fires when a date is selected
30              * @param {DatePicker} this
31              * @param {Date} date The selected date
32              */
33         'select': true,
34         /**
35              * @event monthchange
36              * Fires when the displayed month changes 
37              * @param {DatePicker} this
38              * @param {Date} date The selected month
39              */
40         'monthchange': true
41     });
42
43     if(this.handler){
44         this.on("select", this.handler,  this.scope || this);
45     }
46     // build the disabledDatesRE
47     if(!this.disabledDatesRE && this.disabledDates){
48         var dd = this.disabledDates;
49         var re = "(?:";
50         for(var i = 0; i < dd.length; i++){
51             re += dd[i];
52             if(i != dd.length-1) re += "|";
53         }
54         this.disabledDatesRE = new RegExp(re + ")");
55     }
56 };
57
58 Roo.extend(Roo.DatePicker, Roo.Component, {
59     /**
60      * @cfg {String} todayText
61      * The text to display on the button that selects the current date (defaults to "Today")
62      */
63     todayText : "Today",
64     /**
65      * @cfg {String} okText
66      * The text to display on the ok button
67      */
68     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
69     /**
70      * @cfg {String} cancelText
71      * The text to display on the cancel button
72      */
73     cancelText : "Cancel",
74     /**
75      * @cfg {String} todayTip
76      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
77      */
78     todayTip : "{0} (Spacebar)",
79     /**
80      * @cfg {Date} minDate
81      * Minimum allowable date (JavaScript date object, defaults to null)
82      */
83     minDate : null,
84     /**
85      * @cfg {Date} maxDate
86      * Maximum allowable date (JavaScript date object, defaults to null)
87      */
88     maxDate : null,
89     /**
90      * @cfg {String} minText
91      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
92      */
93     minText : "This date is before the minimum date",
94     /**
95      * @cfg {String} maxText
96      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
97      */
98     maxText : "This date is after the maximum date",
99     /**
100      * @cfg {String} format
101      * The default date format string which can be overriden for localization support.  The format must be
102      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
103      */
104     format : "m/d/y",
105     /**
106      * @cfg {Array} disabledDays
107      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
108      */
109     disabledDays : null,
110     /**
111      * @cfg {String} disabledDaysText
112      * The tooltip to display when the date falls on a disabled day (defaults to "")
113      */
114     disabledDaysText : "",
115     /**
116      * @cfg {RegExp} disabledDatesRE
117      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
118      */
119     disabledDatesRE : null,
120     /**
121      * @cfg {String} disabledDatesText
122      * The tooltip text to display when the date falls on a disabled date (defaults to "")
123      */
124     disabledDatesText : "",
125     /**
126      * @cfg {Boolean} constrainToViewport
127      * True to constrain the date picker to the viewport (defaults to true)
128      */
129     constrainToViewport : true,
130     /**
131      * @cfg {Array} monthNames
132      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
133      */
134     monthNames : Date.monthNames,
135     /**
136      * @cfg {Array} dayNames
137      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
138      */
139     dayNames : Date.dayNames,
140     /**
141      * @cfg {String} nextText
142      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
143      */
144     nextText: 'Next Month (Control+Right)',
145     /**
146      * @cfg {String} prevText
147      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
148      */
149     prevText: 'Previous Month (Control+Left)',
150     /**
151      * @cfg {String} monthYearText
152      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
153      */
154     monthYearText: 'Choose a month (Control+Up/Down to move years)',
155     /**
156      * @cfg {Number} startDay
157      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
158      */
159     startDay : 0,
160     /**
161      * @cfg {Bool} showClear
162      * Show a clear button (usefull for date form elements that can be blank.)
163      */
164     
165     showClear: false,
166     
167     /**
168      * Sets the value of the date field
169      * @param {Date} value The date to set
170      */
171     setValue : function(value){
172         var old = this.value;
173         
174         if (typeof(value) == 'string') {
175          
176             value = Date.parseDate(value, this.format);
177         }
178         if (!value) {
179             value = new Date();
180         }
181         
182         this.value = value.clearTime(true);
183         if(this.el){
184             this.update(this.value);
185         }
186     },
187
188     /**
189      * Gets the current selected value of the date field
190      * @return {Date} The selected date
191      */
192     getValue : function(){
193         return this.value;
194     },
195
196     // private
197     focus : function(){
198         if(this.el){
199             this.update(this.activeDate);
200         }
201     },
202
203     // privateval
204     onRender : function(container, position){
205         
206         var m = [
207              '<table cellspacing="0">',
208                 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>',
209                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
210         var dn = this.dayNames;
211         for(var i = 0; i < 7; i++){
212             var d = this.startDay+i;
213             if(d > 6){
214                 d = d-7;
215             }
216             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
217         }
218         m[m.length] = "</tr></thead><tbody><tr>";
219         for(var i = 0; i < 42; i++) {
220             if(i % 7 == 0 && i != 0){
221                 m[m.length] = "</tr><tr>";
222             }
223             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
224         }
225         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
226             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
227
228         var el = document.createElement("div");
229         el.className = "x-date-picker";
230         el.innerHTML = m.join("");
231
232         container.dom.insertBefore(el, position);
233
234         this.el = Roo.get(el);
235         this.eventEl = Roo.get(el.firstChild);
236
237         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
238             handler: this.showPrevMonth,
239             scope: this,
240             preventDefault:true,
241             stopDefault:true
242         });
243
244         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
245             handler: this.showNextMonth,
246             scope: this,
247             preventDefault:true,
248             stopDefault:true
249         });
250
251         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
252
253         this.monthPicker = this.el.down('div.x-date-mp');
254         this.monthPicker.enableDisplayMode('block');
255         
256         var kn = new Roo.KeyNav(this.eventEl, {
257             "left" : function(e){
258                 e.ctrlKey ?
259                     this.showPrevMonth() :
260                     this.update(this.activeDate.add("d", -1));
261             },
262
263             "right" : function(e){
264                 e.ctrlKey ?
265                     this.showNextMonth() :
266                     this.update(this.activeDate.add("d", 1));
267             },
268
269             "up" : function(e){
270                 e.ctrlKey ?
271                     this.showNextYear() :
272                     this.update(this.activeDate.add("d", -7));
273             },
274
275             "down" : function(e){
276                 e.ctrlKey ?
277                     this.showPrevYear() :
278                     this.update(this.activeDate.add("d", 7));
279             },
280
281             "pageUp" : function(e){
282                 this.showNextMonth();
283             },
284
285             "pageDown" : function(e){
286                 this.showPrevMonth();
287             },
288
289             "enter" : function(e){
290                 e.stopPropagation();
291                 return true;
292             },
293
294             scope : this
295         });
296
297         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
298
299         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
300
301         this.el.unselectable();
302         
303         this.cells = this.el.select("table.x-date-inner tbody td");
304         this.textNodes = this.el.query("table.x-date-inner tbody span");
305
306         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
307             text: "&#160;",
308             tooltip: this.monthYearText
309         });
310
311         this.mbtn.on('click', this.showMonthPicker, this);
312         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
313
314
315         var today = (new Date()).dateFormat(this.format);
316         
317         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
318         if (this.showClear) {
319             baseTb.add( new Roo.Toolbar.Fill());
320         }
321         baseTb.add({
322             text: String.format(this.todayText, today),
323             tooltip: String.format(this.todayTip, today),
324             handler: this.selectToday,
325             scope: this
326         });
327         
328         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
329             
330         //});
331         if (this.showClear) {
332             
333             baseTb.add( new Roo.Toolbar.Fill());
334             baseTb.add({
335                 text: '&#160;',
336                 cls: 'x-btn-icon x-btn-clear',
337                 handler: function() {
338                     //this.value = '';
339                     this.fireEvent("select", this, '');
340                 },
341                 scope: this
342             });
343         }
344         
345         
346         if(Roo.isIE){
347             this.el.repaint();
348         }
349         this.update(this.value);
350     },
351
352     createMonthPicker : function(){
353         if(!this.monthPicker.dom.firstChild){
354             var buf = ['<table border="0" cellspacing="0">'];
355             for(var i = 0; i < 6; i++){
356                 buf.push(
357                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
358                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
359                     i == 0 ?
360                     '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
361                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
362                 );
363             }
364             buf.push(
365                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
366                     this.okText,
367                     '</button><button type="button" class="x-date-mp-cancel">',
368                     this.cancelText,
369                     '</button></td></tr>',
370                 '</table>'
371             );
372             this.monthPicker.update(buf.join(''));
373             this.monthPicker.on('click', this.onMonthClick, this);
374             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
375
376             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
377             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
378
379             this.mpMonths.each(function(m, a, i){
380                 i += 1;
381                 if((i%2) == 0){
382                     m.dom.xmonth = 5 + Math.round(i * .5);
383                 }else{
384                     m.dom.xmonth = Math.round((i-1) * .5);
385                 }
386             });
387         }
388     },
389
390     showMonthPicker : function(){
391         this.createMonthPicker();
392         var size = this.el.getSize();
393         this.monthPicker.setSize(size);
394         this.monthPicker.child('table').setSize(size);
395
396         this.mpSelMonth = (this.activeDate || this.value).getMonth();
397         this.updateMPMonth(this.mpSelMonth);
398         this.mpSelYear = (this.activeDate || this.value).getFullYear();
399         this.updateMPYear(this.mpSelYear);
400
401         this.monthPicker.slideIn('t', {duration:.2});
402     },
403
404     updateMPYear : function(y){
405         this.mpyear = y;
406         var ys = this.mpYears.elements;
407         for(var i = 1; i <= 10; i++){
408             var td = ys[i-1], y2;
409             if((i%2) == 0){
410                 y2 = y + Math.round(i * .5);
411                 td.firstChild.innerHTML = y2;
412                 td.xyear = y2;
413             }else{
414                 y2 = y - (5-Math.round(i * .5));
415                 td.firstChild.innerHTML = y2;
416                 td.xyear = y2;
417             }
418             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
419         }
420     },
421
422     updateMPMonth : function(sm){
423         this.mpMonths.each(function(m, a, i){
424             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
425         });
426     },
427
428     selectMPMonth: function(m){
429         
430     },
431
432     onMonthClick : function(e, t){
433         e.stopEvent();
434         var el = new Roo.Element(t), pn;
435         if(el.is('button.x-date-mp-cancel')){
436             this.hideMonthPicker();
437         }
438         else if(el.is('button.x-date-mp-ok')){
439             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
440             this.hideMonthPicker();
441         }
442         else if(pn = el.up('td.x-date-mp-month', 2)){
443             this.mpMonths.removeClass('x-date-mp-sel');
444             pn.addClass('x-date-mp-sel');
445             this.mpSelMonth = pn.dom.xmonth;
446         }
447         else if(pn = el.up('td.x-date-mp-year', 2)){
448             this.mpYears.removeClass('x-date-mp-sel');
449             pn.addClass('x-date-mp-sel');
450             this.mpSelYear = pn.dom.xyear;
451         }
452         else if(el.is('a.x-date-mp-prev')){
453             this.updateMPYear(this.mpyear-10);
454         }
455         else if(el.is('a.x-date-mp-next')){
456             this.updateMPYear(this.mpyear+10);
457         }
458     },
459
460     onMonthDblClick : function(e, t){
461         e.stopEvent();
462         var el = new Roo.Element(t), pn;
463         if(pn = el.up('td.x-date-mp-month', 2)){
464             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
465             this.hideMonthPicker();
466         }
467         else if(pn = el.up('td.x-date-mp-year', 2)){
468             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
469             this.hideMonthPicker();
470         }
471     },
472
473     hideMonthPicker : function(disableAnim){
474         if(this.monthPicker){
475             if(disableAnim === true){
476                 this.monthPicker.hide();
477             }else{
478                 this.monthPicker.slideOut('t', {duration:.2});
479             }
480         }
481     },
482
483     // private
484     showPrevMonth : function(e){
485         this.update(this.activeDate.add("mo", -1));
486     },
487
488     // private
489     showNextMonth : function(e){
490         this.update(this.activeDate.add("mo", 1));
491     },
492
493     // private
494     showPrevYear : function(){
495         this.update(this.activeDate.add("y", -1));
496     },
497
498     // private
499     showNextYear : function(){
500         this.update(this.activeDate.add("y", 1));
501     },
502
503     // private
504     handleMouseWheel : function(e){
505         var delta = e.getWheelDelta();
506         if(delta > 0){
507             this.showPrevMonth();
508             e.stopEvent();
509         } else if(delta < 0){
510             this.showNextMonth();
511             e.stopEvent();
512         }
513     },
514
515     // private
516     handleDateClick : function(e, t){
517         e.stopEvent();
518         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
519             this.setValue(new Date(t.dateValue));
520             this.fireEvent("select", this, this.value);
521         }
522     },
523
524     // private
525     selectToday : function(){
526         this.setValue(new Date().clearTime());
527         this.fireEvent("select", this, this.value);
528     },
529
530     // private
531     update : function(date)
532     {
533         var vd = this.activeDate;
534         this.activeDate = date;
535         if(vd && this.el){
536             var t = date.getTime();
537             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
538                 this.cells.removeClass("x-date-selected");
539                 this.cells.each(function(c){
540                    if(c.dom.firstChild.dateValue == t){
541                        c.addClass("x-date-selected");
542                        setTimeout(function(){
543                             try{c.dom.firstChild.focus();}catch(e){}
544                        }, 50);
545                        return false;
546                    }
547                 });
548                 return;
549             }
550         }
551         
552         var days = date.getDaysInMonth();
553         var firstOfMonth = date.getFirstDateOfMonth();
554         var startingPos = firstOfMonth.getDay()-this.startDay;
555
556         if(startingPos <= this.startDay){
557             startingPos += 7;
558         }
559
560         var pm = date.add("mo", -1);
561         var prevStart = pm.getDaysInMonth()-startingPos;
562
563         var cells = this.cells.elements;
564         var textEls = this.textNodes;
565         days += startingPos;
566
567         // convert everything to numbers so it's fast
568         var day = 86400000;
569         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
570         var today = new Date().clearTime().getTime();
571         var sel = date.clearTime().getTime();
572         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
573         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
574         var ddMatch = this.disabledDatesRE;
575         var ddText = this.disabledDatesText;
576         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
577         var ddaysText = this.disabledDaysText;
578         var format = this.format;
579
580         var setCellClass = function(cal, cell){
581             cell.title = "";
582             var t = d.getTime();
583             cell.firstChild.dateValue = t;
584             if(t == today){
585                 cell.className += " x-date-today";
586                 cell.title = cal.todayText;
587             }
588             if(t == sel){
589                 cell.className += " x-date-selected";
590                 setTimeout(function(){
591                     try{cell.firstChild.focus();}catch(e){}
592                 }, 50);
593             }
594             // disabling
595             if(t < min) {
596                 cell.className = " x-date-disabled";
597                 cell.title = cal.minText;
598                 return;
599             }
600             if(t > max) {
601                 cell.className = " x-date-disabled";
602                 cell.title = cal.maxText;
603                 return;
604             }
605             if(ddays){
606                 if(ddays.indexOf(d.getDay()) != -1){
607                     cell.title = ddaysText;
608                     cell.className = " x-date-disabled";
609                 }
610             }
611             if(ddMatch && format){
612                 var fvalue = d.dateFormat(format);
613                 if(ddMatch.test(fvalue)){
614                     cell.title = ddText.replace("%0", fvalue);
615                     cell.className = " x-date-disabled";
616                 }
617             }
618         };
619
620         var i = 0;
621         for(; i < startingPos; i++) {
622             textEls[i].innerHTML = (++prevStart);
623             d.setDate(d.getDate()+1);
624             cells[i].className = "x-date-prevday";
625             setCellClass(this, cells[i]);
626         }
627         for(; i < days; i++){
628             intDay = i - startingPos + 1;
629             textEls[i].innerHTML = (intDay);
630             d.setDate(d.getDate()+1);
631             cells[i].className = "x-date-active";
632             setCellClass(this, cells[i]);
633         }
634         var extraDays = 0;
635         for(; i < 42; i++) {
636              textEls[i].innerHTML = (++extraDays);
637              d.setDate(d.getDate()+1);
638              cells[i].className = "x-date-nextday";
639              setCellClass(this, cells[i]);
640         }
641
642         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
643         this.fireEvent('monthchange', this, date);
644         
645         if(!this.internalRender){
646             var main = this.el.dom.firstChild;
647             var w = main.offsetWidth;
648             this.el.setWidth(w + this.el.getBorderWidth("lr"));
649             Roo.fly(main).setWidth(w);
650             this.internalRender = true;
651             // opera does not respect the auto grow header center column
652             // then, after it gets a width opera refuses to recalculate
653             // without a second pass
654             if(Roo.isOpera && !this.secondPass){
655                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
656                 this.secondPass = true;
657                 this.update.defer(10, this, [date]);
658             }
659         }
660         
661         
662     }
663 });